tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.f16792fed
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.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/prove.cjs +47 -47
- package/dist/prove.js +46 -46
- package/dist/run.cjs +30 -30
- package/dist/run.js +28 -28
- package/dist/transfer.cjs +27 -27
- package/dist/transfer.js +27 -27
- package/package.json +1 -1
- package/src/cli/options.ts +1 -1
- package/src/coverage.ts +3 -8
- package/src/java-hash.ts +7 -0
- package/src/sany/nodes.ts +4 -10
- package/src/state-graph.ts +2 -7
- package/src/tlc/order.ts +2 -9
- package/src/tlc/trace-spec.ts +4 -5
- package/src/values.ts +1 -6
package/dist/run.cjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
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
|
-
const e=require("./worker.cjs"),t=require("./transfer.cjs"),n=require("./prove.cjs"),r=require("./tlapm.cjs");let i=require("node:path"),a=require("node:fs"),o=require("node:url"),s=require("node:os"),c=require("node:v8");const l=`META-INF/MANIFEST.MF`,u=async e=>{if(e===void 0||!(0,a.existsSync)(e))return`master`;let t=await import(`fflate`),n=t.unzipSync((0,a.readFileSync)(e),{filter:e=>e.name===l})[l];return(n&&/^X-Git-Tag: *(\S*)/m.exec(t.strFromU8(n))?.[1])===`v1.7.4`?`1.7.4`:`master`},d=/[*?[{]/,f=e=>e.flatMap(e=>d.test(e)?(0,a.globSync)(e).sort().map(e=>({path:e,isGlobbed:!0})):[{path:e,isGlobbed:!1}]),p=(e,t)=>e.map(e=>(0,i.join)(e,`${t}.tla`)).find(a.existsSync),m=e=>t=>{let n=p(e,t);return n===void 0?void 0:(0,a.readFileSync)(n,`utf8`)},h=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),g=e=>`jar:file:${(0,o.pathToFileURL)((0,i.resolve)(e)).pathname}!/tla2sany/StandardModules/`,_=t=>t instanceof e.V?e.rt(t.code):e.Q(t),v=(n,r)=>{if(n instanceof e._||n instanceof e.b){let i=t.Kt(n.message),a=n instanceof e.V?n.code:i&&!i.isEvalException?i.code:t.zt.general;return r.print(a,t.Bt.error,t.Ht(a,n.message,r.isTool))}console.error(`${n.name}: ${n.message}`)},y=async(n,r=t.Vt(!1))=>{try{return await n()}catch(t){if(!(t instanceof e.y))throw t;return v(t,r),_(t)}},b=(e,t,n)=>console.error(`File does not exist: ${(0,i.isAbsolute)(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,...n===void 0?[]:[g(n)]].join(`, `)}`),x=e=>e.endsWith(`/`)?e:`${e}/`,S=(e,n)=>r=>{let i=e(r);return i===void 0&&!t.at.has(r)&&n(`${r}.tla`),i},C=e=>e.classPath?.split(i.delimiter).find(e=>e.endsWith(`.jar`));var w=`0.0.10-dev.
|
|
9
|
+
const e=require("./worker.cjs"),t=require("./transfer.cjs"),n=require("./prove.cjs"),r=require("./tlapm.cjs");let i=require("node:path"),a=require("node:fs"),o=require("node:url"),s=require("node:os"),c=require("node:v8");const l=`META-INF/MANIFEST.MF`,u=async e=>{if(e===void 0||!(0,a.existsSync)(e))return`master`;let t=await import(`fflate`),n=t.unzipSync((0,a.readFileSync)(e),{filter:e=>e.name===l})[l];return(n&&/^X-Git-Tag: *(\S*)/m.exec(t.strFromU8(n))?.[1])===`v1.7.4`?`1.7.4`:`master`},d=/[*?[{]/,f=e=>e.flatMap(e=>d.test(e)?(0,a.globSync)(e).sort().map(e=>({path:e,isGlobbed:!0})):[{path:e,isGlobbed:!1}]),p=(e,t)=>e.map(e=>(0,i.join)(e,`${t}.tla`)).find(a.existsSync),m=e=>t=>{let n=p(e,t);return n===void 0?void 0:(0,a.readFileSync)(n,`utf8`)},h=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),g=e=>`jar:file:${(0,o.pathToFileURL)((0,i.resolve)(e)).pathname}!/tla2sany/StandardModules/`,_=t=>t instanceof e.V?e.rt(t.code):e.Q(t),v=(n,r)=>{if(n instanceof e._||n instanceof e.b){let i=t.Kt(n.message),a=n instanceof e.V?n.code:i&&!i.isEvalException?i.code:t.zt.general;return r.print(a,t.Bt.error,t.Ht(a,n.message,r.isTool))}console.error(`${n.name}: ${n.message}`)},y=async(n,r=t.Vt(!1))=>{try{return await n()}catch(t){if(!(t instanceof e.y))throw t;return v(t,r),_(t)}},b=(e,t,n)=>console.error(`File does not exist: ${(0,i.isAbsolute)(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,...n===void 0?[]:[g(n)]].join(`, `)}`),x=e=>e.endsWith(`/`)?e:`${e}/`,S=(e,n)=>r=>{let i=e(r);return i===void 0&&!t.at.has(r)&&n(`${r}.tla`),i},C=e=>e.classPath?.split(i.delimiter).find(e=>e.endsWith(`.jar`));var w=`0.0.10-dev.f16792fed`;const T=2224400062,E={int8:0,int16:1,int32:2,shared8:4,shared16:5,shared32:6,block32:8,string8:9,string32:10,doubleLittle:12},D={smallInt:64,smallString:32,smallBlock:128},O=(e,...t)=>({tag:e,fields:t}),k=e=>typeof e==`object`&&`tag`in e,A=(t,n)=>{let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<n+20||r.getUint32(n)!==T)throw new e.A(`corrupted fingerprint file`);let i=n+20+r.getUint32(n+4),a=[],o=n+20,s=t=>{let n=o;if(o+=t,o>i)throw new e.A(`corrupted fingerprint file`);return n},c=new TextDecoder,l=e=>{let n=s(e),r=c.decode(t.subarray(n,n+e));return a.push(r),r},u=(e,t)=>{let n=O(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 n=t[s(1)];if(n>=D.smallBlock)return u(n&15,n>>4&7);if(n>=D.smallInt)return n&63;if(n>=D.smallString)return l(n&31);switch(n){case E.int8:return r.getInt8(s(1));case E.int16:return r.getInt16(s(2));case E.int32:return r.getInt32(s(4));case E.shared8:return d(r.getUint8(s(1)));case E.shared16:return d(r.getUint16(s(2)));case E.shared32:return d(r.getUint32(s(4)));case E.block32:{let e=r.getUint32(s(4));return u(e&255,e>>>10)}case E.string8:return l(r.getUint8(s(1)));case E.string32:return l(r.getUint32(s(4)));case E.doubleLittle:{let e={float:r.getFloat64(s(8),!0)};return a.push(e),e}}throw new e.A(`corrupted fingerprint file`)};return{value:f(),next:i}},j=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(D.smallInt+e):e>=-128&&e<128?t.push(E.int8,e&255):e>=-32768&&e<32768?(t.push(E.int16),a(e,2)):(t.push(E.int32),a(e,4));if(n++,typeof e==`string`){let n=o.encode(e);n.length<32?t.push(D.smallString+n.length):n.length<256?t.push(E.string8,n.length):(t.push(E.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(!k(e)){let n=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));n.setFloat64(0,e.float,!0),t.push(E.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(D.smallBlock+e.tag+(c<<4)):(t.push(E.block32),a(c*1024+e.tag,4)),e.fields.forEach(s)};s(e);let c=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(20));return[T,t.length,n,r,i].forEach((e,t)=>c.setUint32(t*4,e)),new Uint8Array([...new Uint8Array(c.buffer),...t])},M=20210223,N={zenon:{field:1,tag:1},isabelle:{field:2,tag:0},smt:{field:10,tag:8},z3:{field:11,tag:9},ls4:{field:17,tag:16}},ee=[`false`,`timeout`],P=`tla-ts ${w}`,F=/* @__PURE__ */ new Map([[N.zenon.field,3],[N.isabelle.field,4]]),I=(e,t)=>e!==void 0&&k(e)?e.fields[t]:void 0,L=e=>e!==void 0&&typeof e==`object`&&`float`in e?e.float:1/0,te=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},ne=e=>e!==void 0&&k(e)?[[e.fields[0],e.fields[1]],...ne(e.fields[2])]:[],re=(t,n,r)=>{let i=(0,a.readFileSync)(n),o=A(i,0),s=A(i,o.next).value;if(o.value!==M||!k(s)||s.tag!==0)throw new e.A(`corrupted fingerprint file`);let c=I(I(s,0),1),l=(e,t)=>{let n=F.get(t);return!r||n===void 0||I(I(e,0),n)===P};t.clear(),(c!==void 0&&k(c)?c.fields:[]).flatMap(e=>ne(e).toReversed()).forEach(([n,r])=>{if(typeof n!=`string`||!k(r))throw new e.A(`corrupted fingerprint file`);t.set(n,r.fields.map((e,t)=>l(e,t)?e:0))})},ie=(e,t)=>{let n=I(t,0),r=I(n,0),i=I(I(n,1),0);if(r===void 0||r===1)return;let a=L(I(e===`isabelle`?I(i,0):i,0)),o=e===`isabelle`?I(i,1):void 0,s=I(I(r,0),0);return{method:{prover:e,timeLimitMs:a*1e3,...typeof o==`string`&&{tactic:o}},isProved:r===0,isReused:!1,...s!==void 0&&{reason:typeof s==`number`?ee[s]:String(I(s,0))}}},ae=e=>{let t=/* @__PURE__ */ new Date,n=e.method,r={float:n.rlimit??n.timeLimitMs/1e3},i=n.prover===`zenon`?O(0,r,5):n.prover===`isabelle`?O(0,O(0,r),n.tactic??`auto`):O(0,r),a=ee.indexOf(e.reason??``),o=e.reason===void 0?0:O(0,a===-1?O(0,e.reason):a);return O(0,O(0,O(0,e.isProved?0:O(0,o),O(N[n.prover].tag,i)),O(0,t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds()),P,P,P))},R=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=te(r)&t-1;n[i]=O(0,r,O(0,...e),n[i])}),O(0,O(0,e.size,O(0,...n),0,512))},z=e=>String(e).padStart(2,`0`),oe=(e,t)=>{let n=/* @__PURE__ */ new Date,r=`${e}.history`,o=(0,i.join)(r,`${n.getFullYear()}-${z(n.getMonth()+1)}-${z(n.getDate())}_${z(n.getHours())}_${z(n.getMinutes())}_${z(n.getSeconds())}`);(0,a.mkdirSync)(o,{recursive:!0}),[e,...t].filter(e=>(0,a.existsSync)(e)).forEach(e=>(0,a.cpSync)(e,(0,i.join)(o,(0,i.basename)(e)),{preserveTimestamps:!0})),(0,a.readdirSync)(r).map(e=>(0,i.join)(r,e)).sort((e,t)=>(0,a.statSync)(t).mtimeMs-(0,a.statSync)(e).mtimeMs).slice(10).forEach(e=>(0,a.rmSync)(e,{recursive:!0,force:!0}))},se=e=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=new Map([...e].map(([e,r])=>{let i=new Map(Object.entries(N).flatMap(([e,n])=>{let i=ie(e,I(r[n.field],0));return i?(t.set(i,r[n.field]),[[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)];r.forEach((e,n)=>{a[N[n].field]=t.get(e)??ae(e)}),e.set(i,a)}),(0,a.writeFileSync)(`${i}.tmp`,Buffer.concat([j(M),j(R(e))])),(0,a.renameSync)(`${i}.tmp`,i)}}},ce=(e,t)=>{let n=new Map(t.map(e=>{let[t,...n]=e.flag.split(` `);return[t,e.getArity??(()=>n.length)]}));return{usage:e.replace(`{options}`,t.map(e=>`[${e.flag}]${e.isRepeatable?`...`:``}`).join(` `)),parse:e=>{let t=[],r=[],i=[],a=[];for(let o=0;o<e.length;o++){let s=n.get(e[o]);if(s===void 0){(e[o].startsWith(`-`)?i:r).push(e[o]);continue}let c=s(e.slice(o+1)),l={name:e[o],values:e.slice(o+1,o+1+c)};t.push(l),l.values.length<c&&a.push(l),o+=c}return{options:t,positionals:r,unknown:i,incomplete:a[0],has:e=>t.some(t=>t.name===e),get:e=>t.findLast(t=>t.name===e)?.values}}}},le=ce(`tla-ts <Spec.tla|Spec.cfg|spec.ts|glob>... {options}`,[{flag:`-config <Spec.cfg>`},{flag:`-continue`},{flag:`-deadlock`},{flag:`-dump [<format>] <file>`,getArity:e=>e.length>1&&e[0].startsWith(`dot`)?2:1},{flag:`-fp <num>`},{flag:`-lncheck <final|default|off>`},{flag:`-maxSetSize <num>`},{flag:`-metadir <directory>`},{flag:`-nowarning`},{flag:`-seed <num>`},{flag:`-terse`},{flag:`-tool`},{flag:`-view`},{flag:`-workers <count|auto>`}]),ue=ce(`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`}]),de=[`Usage: ${le.usage}`,` ${ue.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
10
|
`),fe=/* @__PURE__ */ new Set([`--toolbox`,`--line`,`--threads`,`--nofpl`]),pe=e=>[`.`,...r.t().map(e=>(0,i.join)((0,i.dirname)((0,i.dirname)((0,a.realpathSync)(e))),`lib/tlapm/stdlib`)).filter(e=>(0,a.existsSync)(e)).slice(0,1),...e.options.flatMap(e=>e.name===`-I`?e.values:[]).toReversed()],me=e=>console.error(`@!!BEGIN\n${e.map(e=>`@!!${e}\n`).join(``)}@!!END\n`),he=(e,t,n)=>me([`type:obligation`,`id:${e.id}`,`loc:${e.location}`,`status:${t}`,...n]),ge=`9ed0376`,_e=e=>/^[+,\-./0-9:=@A-Z_a-z]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`,ve={failed:10,incomplete:11,emptyTarget:12},ye=(e,t,r)=>{let i=e.summary;r||(i.absent.forEach(e=>console.error(`Missing proof at ${n.p(e)}`)),i.omitted.forEach(e=>console.error(`Omitted proof at ${n.p(e)}`)));let a=i.absent.length+i.omitted.length>0;a&&console.error(`${n.f(e.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(e.name)}: ${i.absent.length} missing, ${i.omitted.length} omitted proof step(s).`);let o=t&&e.obligations.length===0;return o&&console.error(`${n.f(e.location)}[ERROR]: No proof obligation found for the selected target.`),[...a?[ve.incomplete]:[],...o?[ve.emptyTarget]:[]]},be=t=>{try{return t()}catch(t){if(!(t instanceof e.A))throw t;console.error(` tlapm ending abnormally with ${t.exception}\n`);return}},xe=(e,t)=>{let r=t.method.timeLimitMs,i=t.timeUsedMs===void 0?``:`; 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=(t.method.prover===`smt`||t.method.prover===`z3`)&&t.reason===`false`&&t.verdict?`(* SMT failed with status = ${t.verdict}\n *)\n`:``;he(e,t.isProved?`proved`:`failed`,[`prover:${t.method.prover}`,...o===``?[]:[`meth:${o}`],...t.reason===void 0?[]:[`reason:${t.reason}`],`already:${t.isReused}`,...t.isProved?[]:[`obl:${t.isReused?``:`\n${s}`}${n.n(e,t.isReused)}`]])},Se=(e,t)=>he(e,`failed`,[`prover:fail`,`meth:time-limit: inf`,`reason:${t}`,`already:false`,`obl:${e.text}`]),Ce=async(e,t,r,i)=>{let o=se(i.fingerprints),s=await n.i(e.obligations,{workers:i.workers,results:o.results,isFingerprinted:i.isFingerprinted,isProving:i.isProving,onReport:(e,t)=>{if(i.isToolbox){if(e.obligation.status===`trivial`)return he(t,`trivial`,[`prover:tlapm`,`already:false`]);if(t.kind.kind===`Error`)return Se(t,`user error`);e.attempts.forEach(e=>xe(t,e))}}});if((0,a.writeFileSync)(t,n.t(e.name,s,e.obligations)),console.log(`(* created new ${JSON.stringify(t)} *)`),o.save(r),console.log(`(* fingerprints written in ${JSON.stringify(r)} *)`),!i.isProving)return!1;let c=s.flatMap((t,n)=>`reason`in t.obligation?[{report:t,obligation:e.obligations[n]}]:[]);i.isToolbox&&c.filter(e=>e.report.attempts.length===0&&e.obligation.kind.kind!==`Error`).forEach(e=>Se(e.obligation,`unexpected error`)),c.toReversed().forEach(e=>console.error(`${n.f(e.obligation.locus)}${n.d(n.u(`[ERROR]: @[<v2>Could not prove or check:@,%a@]`,n.l(e.obligation.sequent)),35)}`));let l=`${e.obligations.length} obligation${e.obligations.length>1?`s`:``}`;return console.error(c.length===0?`${n.f(e.location)}[INFO]: All ${l} proved.`:`${n.f(e.location)}[ERROR]: ${c.length}/${l} failed.\nThere were backend errors processing module \`${JSON.stringify(e.name)}\`.`),c.length>0},we=async r=>{let o=ue.parse(r),c=!o.has(`-N`)&&!o.has(`--summary`),l=o.unknown[0]??(c&&o.has(`--printallobs`)?`--printallobs`:void 0);if(l!==void 0)return console.error(`Error: tla-ts tlapm does not support the tlapm option ${l}.`),1;if(o.incomplete)return console.error(`Error: option '${o.incomplete.name}' needs an argument.`),1;let u=o.options.find(e=>fe.has(e.name)&&e.values.some(e=>!/^-?\d+$/.test(e)));if(u)return console.error(`Error: option '${u.name}' expects an integer.`),1;if(o.has(`--version`))return console.log(ge),e.tt.success;let d=f(o.positionals).map(e=>e.path),p=d.map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(p.length===0)return console.error(de),1;let m=o.has(`--toolbox`)||o.has(`--line`);m&&console.log(`\n\\* TLAPM version ${ge}\n\\* launched at ${t.Wt(/* @__PURE__ */ new Date)} with command line:\n\\* ${[`tla-ts`,`tlapm`,...r].map(_e).join(` `)}\n`);let h=o.options.reduce((e,t)=>{let[r,i]=t.values.map(Number);return t.name===`--toolbox`?{start:r,end:i===0?1/0:i}:t.name===`--line`?r===0?n.o:{start:r,end:r}:e},n.o),g=p.reduce((e,t)=>e.includes((0,i.dirname)(t))?e:[(0,i.dirname)(t),...e],pe(o)),_=/* @__PURE__ */ new Set,v=be(()=>{let t=p.findIndex(e=>!(0,a.existsSync)(e));if(t!==-1){let n=d[t];throw console.error(`File "<unknown>":\nError: File ${JSON.stringify(n)} not found`),new e.A(`File ${n} not found`,{failure:`Module.Parser.parse_file`})}return n.c(p.map(e=>({file:`./${e}`,source:(0,a.readFileSync)(e,`utf8`)})),e=>{_.add(e);let t=g.map(t=>`${t}/${e}.tla`).find(e=>(0,a.existsSync)(e));return t===void 0?e===`TLAPS`?{file:`TLAPS.tla`,source:n.a}:void 0:{file:t,source:(0,a.readFileSync)(t,`utf8`)}},{lines:h,onWarning:e=>{if(e.channel===`stdout`)return console.log(e.text);let t=e.channel===`toolbox`||e.channel===`toolboxOnly`;if(m&&t)return me([`type:warning`,`msg:${e.text}`]);e.channel!==`toolboxOnly`&&console.error(e.text)}})});if(!v)return 3;let y=o.get(`--cache-dir`)?.[0]??process.env.TLAPM_CACHE_DIR??`.tlacache`,b=o.get(`--nofpl`)?.map(Number)??[0,0],x={isToolbox:m,isProving:!o.has(`--noproving`),workers:Math.max(1,Number(o.get(`--threads`)?.[0]??(0,s.availableParallelism)())),isFingerprinted:e=>!o.has(`--nofp`)&&!(e.locus&&e.locus.startLine>=b[0]&&e.locus.endLine<=b[1]),fingerprints:/* @__PURE__ */ new Map},S=[];for(let[e,t]of v.entries()){let r=`${y}/${t.name}.tlaps`,i=`${r}/fingerprints`,s=o.get(`--usefp`)?.[0]??i;if((0,a.mkdirSync)(r,{recursive:!0}),o.has(`--cleanfp`)&&(0,a.existsSync)(i)&&((0,a.rmSync)(i),console.log(`(* fingerprints file ${JSON.stringify(i)} removed *)`)),!o.has(`--cleanfp`)&&(0,a.existsSync)(s)&&t.summary.total!==0&&(console.log(o.has(`--nofp`)?`(* will not use fingerprints (because of option \`--nofp\`), but will now load fingerprints from the file \`${s}\`, in order to overwrite with the new fingerprints, and then save the results at the end. *)`:`(* loading fingerprints in ${JSON.stringify(s)} *)`),re(x.fingerprints,s,o.has(`--safefp`))),o.has(`--summary`)&&console.log(n.s(t)),m&&(t.obligations.forEach(e=>he(e,`to be proved`,o.has(`--printallobs`)?[`obl:${e.text}`]:[])),me([`type:obligationsnumber`,`count:${t.obligations.length}`])),o.has(`--strict`)&&S.push(...ye(t,h.start>0||h.end<1/0,o.has(`--summary`))),!c)continue;oe(i,[..._,...v.slice(0,e+1).map(e=>e.name)].map(e=>`${e}.tla`));let l=await Ce(t,`${r}/${t.name}.thy`,i,x);if(l&&o.has(`--strict`)&&S.push(ve.failed),l&&!o.has(`--strict`)&&!m)return console.error(` tlapm ending abnormally with Failure("backend errors: there are unproved obligations")
|
|
11
11
|
Raised at Stdlib.failwith in file "stdlib.ml", line 29, characters 17-33
|
|
12
12
|
Called from Tlapm_lib.process_module in file "src/tlapm_lib.ml", lines 492-493, characters 12-37
|
|
@@ -26,17 +26,17 @@ Called from Tlapm_lib.init in file "src/tlapm_lib.ml", line 659, characters 8-59
|
|
|
26
26
|
`&&ct(n),Ke(a)},xt=(e,t,n)=>bt(e,t,!0,n),St=(e,t)=>(bt(e,t,!1,!1),e.delimiter),Ct=(e,t)=>({params:e,tokenizer:yt(),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}),wt=()=>Ke([[He(`defaultInitValue`,0,0)]]),Tt=(e,t)=>[...e,...t.filter((n,r)=>!e.includes(n)&&t.indexOf(n)===r)],Et=(e,t)=>!t.some(t=>e.includes(t)),Dt=(e,t)=>{t.splice(0,t.length,...e)},Ot=(t,n,r)=>{let i=t.params,a=t.lookahead,o=t.lastToken,s=0,c=[],l=[],u=1,d=/* @__PURE__ */ new Set,f=!1,p=!1,m,h=[],g=!1,_=[],v=[],y=[],b=!1,x=!1,S=i.inputVersionNumber>=1500,C=t=>{throw new e.s(`${t}\n line ${o.line}, column ${o.column}`)},w=()=>{if(s===0)return lt(n),o.column=n.vcolumn+1,o.line=n.line+1,o.text=St(t.tokenizer,n),o.text;o.column=a.columns[0]+1,o.line=a.lines[0]+1;let e=a.tokens[0];for(let e=1;e<s;e++)a.tokens[e-1]=a.tokens[e],a.columns[e-1]=a.columns[e],a.lines[e-1]=a.lines[e];return--s,o.text=e,e},T=r=>{for(;s<r;){let r=s;if(lt(n)===` `)throw new e.s(`Premature end of file, perhaps because of unclosed comment, near\n line ${a.lines[r]+1}, column ${a.columns[r]+1}`);a.columns[r]=n.vcolumn,a.lines[r]=n.line,a.tokens[r]=St(t.tokenizer,n),s+=1}return a.tokens[r-1]},E=r=>{if(r<s)throw new e.o(`ParseAlgorithm.PeekPastAlgToken called to peek after a token
|
|
27
27
|
it has already peeked at`);for(;r>s;)a.tokens[s]=St(t.tokenizer,n),s+=1;return lt(n)},D=(r=!1)=>{if(s!==0)throw new e.o(`ParseAlgorithm: GetExpr called after lookahead`);let i=xt(t.tokenizer,n,r);return a.tokens[0]=t.tokenizer.delimiter,a.columns[0]=t.tokenizer.delimiterCol,a.lines[0]=t.tokenizer.delimiterLine,s=1,i},O=(e,t)=>{let n=w();n!==e&&n!==t&&C(`Expected "${e}" but found "${n}"`)},k=(t,n)=>{if(t===`;`){let t=T(1);if(`end begin else elsif or do macro procedure process fair define } {`.split(` `).includes(t))return;if(`if either while with call return goto print assert skip`.split(` `).includes(t))throw new e.s(`Missing \`;' before line ${a.lines[0]+1}, column ${a.columns[0]+1}`)}O(t,n)},A=()=>{let e=w();return e===`=`?!0:e===`\\in`||e===`∈`?!1:C(`Expected "=" or "\\in" but found "${e}"`)},j=()=>k(T(1)===`,`?`,`:`;`),M=()=>k(g?`{`:`begin`),N=e=>{g?k(`}`):(k(`end`),k(e))},ee=()=>{T(1)===`variables`?O(`variables`):k(`variable`)},P=()=>{let t={...V(),kind:`VarDecl`,var:w(),col:o.column,line:o.line,isEq:!0,val:wt()};if(![`=`,`\\in`,`∈`].includes(T(1)))return p=!0,t;if(t.isEq=A(),t.val=D(),t.val.tokens.length===0)throw new e.c(`NullPointerException`);return t},F=()=>{ee();let e=[],t=[`begin`,`{`,`procedure`,`process`,`fair`,`define`,`macro`];for(;!t.includes(T(1));)e.push(P()),j();return e},I=()=>{let t={...V(),kind:`PVarDecl`,var:w(),col:o.column,line:o.line,val:wt()};if(T(1)!==`=`)return p=!0,t;if(k(`=`),t.val=D(),t.val.tokens.length===0)throw new e.c(`NullPointerException`);return t},L=()=>{ee();let e=[];for(;T(1)!==`begin`&&T(1)!==`{`;)e.push(I()),j();return e},te=()=>{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=lt(n);return e.length>0&&e[0]===`:`&&!(e.length>1&&e[1]===`=`)},ne=()=>{if(!te())return``;let e=w();t.isInMacro&&C(`A label may not appear in a macro.`),e===`Done`&&C("Cannot use `Done' as a label."),e===`Error`&&C("Cannot use `Error' as a label."),k(`:`),f=!0,d.add(e);let n=T(1);return n!==`+`&&n!==`-`||(k(n),(n===`+`?_:v).push(e),S=!1),e},re=()=>{let e=[],t=e=>!g&&[`end`,`else`,`elsif`,`or`].includes(e)||g&&e===`}`;for(;!t(T(1));)e.push(...ae());return g&&e.length===0&&C(`Empty statement list`),e},ie=t=>{O(`{`);let n=re();if(k(`}`),k(`;`),t!==``){if(n[0].lbl!==``)throw new e.s(`Duplicate labeling of statement`,n[0]);n[0].lbl=t}return n},ae=()=>{let e=ne();if(g&&T(1)===`{`)return ie(e);let t=R();return t.lbl=e,[t]},R=()=>{let t=T(1);if(t===`if`)return oe(0);if(t===`either`)return se();if(t===`with`)return ce(0);if(t===`when`||t===`await`){O(t);let n=o.column,r=o.line,i=D();if(i.tokens.length===0)throw new e.c(`NullPointerException`);return k(`;`),{...V(),kind:`When`,col:n,line:r,exp:i}}if(t===`print`||t===`assert`){O(t);let e=o.column,n=o.line,r=D();return r.tokens.length===0&&C(`Empty expression in ${t} statement at `),k(`;`),{...V(),kind:t===`print`?`PrintS`:`Assert`,col:e,line:n,exp:r}}if(t===`skip`){O(`skip`);let e={...V(),kind:`Skip`,col:o.column,line:o.line};return k(`;`),e}if(t===`call`)return pe();if(t===`return`){O(`return`);let e={...V(),kind:`Return`,col:o.column,line:o.line,from:m};return k(`;`),e}if(t===`goto`){O(`goto`);let e=o.column,t=o.line,n=w();return b=!0,(n===`Done`||n===`"Done"`)&&(x=!0),k(`;`),{...V(),kind:`Goto`,col:e,line:t,to:n}}return t===`while`?z():E(1)[0]===`(`?me():ue()},z=()=>{O(`while`);let e=o.column,t=o.line;g&&k(`(`);let n=D();g&&k(`)`),n.tokens.length===0&&C(`Empty while test at `),g||k(`do`);let r=g?ae():re();return g||(k(`end`),k(`while`),k(`;`)),r.length===0&&C(`Missing body of while statement at`),{...V(),kind:`While`,col:e,line:t,test:n,unlabDo:r,labDo:[]}},oe=e=>{O(e===0?`if`:`elsif`);let t={...V(),kind:`LabelIf`,col:o.column,line:o.line,test:We(),unlabThen:[],labThen:[],unlabElse:[],labElse:[]};g&&k(`(`),t.test=D(),g&&k(`)`),t.test.tokens.length===0&&C(`Empty if test at `),g||k(`then`),t.unlabThen=g?ae():re();let n=T(1);return n===`else`&&(O(`else`),t.unlabElse=g?ae():re()),!g&&n===`elsif`&&(t.unlabElse=[oe(e+1)]),!g&&![`else`,`elsif`,`end`].includes(n)&&C(`Expecting "else", "elsif", or "end"`),!g&&e===0&&(k(`end`),k(`if`),k(`;`)),t.unlabElse.length===0&&Ve(t.unlabThen,t.unlabThen.length-1),t},se=()=>{O(`either`);let t={...V(),kind:`LabelEither`,col:o.column,line:o.line,clauses:[]};for(;;){let n={...V(),kind:`Clause`,unlabOr:g?ae():re(),labOr:[]};if(n.unlabOr.length===0)throw new e.s("`either' statement with empty `or' clause",t);if(t.clauses.push(n),T(1)!==`or`)break;O(`or`)}if(g||(O(`end`),k(`either`),k(`;`)),t.clauses.length===1)throw new e.s("`either' statement has no `or'",t);return t},ce=t=>{t===0&&(k(`with`),g&&k(`(`));let n={...V(),kind:`With`,col:o.column,line:o.line,var:w(),isEq:!0,exp:We(),Do:[]};n.isEq=A(),n.exp=D(),g&&T(1)===`)`||j(),n.exp.tokens.length===0&&C(`Empty with expression at `);let r=!g&&T(1)===`do`,i=g&&T(1)===`)`;if(r&&k(`do`),i&&O(`)`),n.Do=r?re():i?ae():[ce(t+1)],r&&(k(`end`),k(`with`),k(`;`)),n.Do.length===0)throw new e.s(`Missing body of with statement`,n);return n},le=()=>{let e=a.columns[0]+1,t=a.lines[0]+1,n={...V(),kind:`Lhs`,col:e,line:t,var:w(),sub:D()};k(`:=`,`≔`);let r=D();return r.tokens.length===0&&C(`Empty right-hand side of assignment at `),{...V(),kind:`SingleAssign`,col:e,line:t,lhs:n,rhs:r}},ue=()=>{let t={...V(),kind:`Assign`,col:a.columns[0]+1,line:a.lines[0]+1,ass:[le()]};for(;T(1)===`||`||T(1)===`‖`;){w();try{t.ass.push(le())}catch(t){if(!(t instanceof e.s))throw t;C(`Bad assignment statement at `)}}return k(`;`),t},de=()=>{let e=[];if(E(0)[0]!==`)`)for(;;){let t=D();if(e.push(t),t.tokens.length===0&&C(`Empty argument in call statement at `),T(1)===`)`)break;k(`,`)}return k(`)`),k(`;`),e},fe=()=>{O(`call`);let e={...V(),kind:`Call`,col:o.column,line:o.line,returnTo:``,to:w(),args:[]};return k(`(`),e.args=de(),y.includes(e.to)||y.push(e.to),e},pe=()=>{let e=fe();if(T(1)===`return`)return O(`return`),k(`;`),{...V(),kind:`CallReturn`,col:e.col,line:e.line,to:e.to,from:m,args:e.args};if(T(1)!==`goto`)return e;O(`goto`);let t={...V(),kind:`CallGoto`,col:e.col,line:e.line,to:e.to,after:w(),args:e.args};return b=!0,(t.to===`Done`||t.to===`"Done"`)&&(x=!0),k(`;`),t},me=()=>{let e={...V(),kind:`MacroCall`,name:w(),col:o.column,line:o.line,args:[]};return O(`(`),e.args=de(),e},he=e=>{t.isInMacro=!0,O(`macro`);let n={...V(),kind:`Macro`,col:o.column,line:o.line,name:w(),params:[],body:[]};for(k(`(`);T(1)!==`)`;)n.params.length>0&&k(`,`),n.params.push(w());return O(`)`),M(),n.body=re(),N(`macro`),T(1)===`;`&&w(),B(n.body,e),t.isInMacro=!1,n},ge=()=>{k(`procedure`);let e={...V(),kind:`Procedure`,col:o.column,line:o.line,name:w(),minusLabels:[],plusLabels:[],proceduresCalled:[],params:[],decls:[],body:[]};for(m=e.name,_=[],v=[],y=[],k(`(`);T(1)!==`)`;)e.params.length>0&&k(`,`),e.params.push(I());return O(`)`),T(1)!==`begin`&&T(1)!==`{`&&(e.decls=L()),M(),e.body=re(),N(`procedure`),T(1)===`;`&&w(),m=void 0,e.plusLabels=_,e.minusLabels=v,e.proceduresCalled=y,e},_e=()=>{k(`process`);let e=o.column,t=o.line;g&&k(`(`);let n=w(),r=A(),i=D();_=[],v=[],y=[],g&&k(`)`),i.tokens.length===0&&C(`Empty process id at `);let a=T(1)===`begin`||T(1)===`{`?[]:F();M();let s=re();return N(`process`),T(1)===`;`&&w(),{...V(),kind:`Process`,col:e,line:t,name:n,fairness:0,minusLabels:v,plusLabels:_,proceduresCalled:y,isEq:r,id:i,decls:a,body:s}},ve=()=>{let e=`${i.labelRoot}${u}`;return u+=1,d.has(e)?ve():e},ye=e=>{e.lbl===``&&(e.lbl=ve(),c.push(e.lbl),l.push(ze(e)))},be=(t,n,r,i,a)=>{Dt(i,a);let o=n,s=!1,c=e=>{ye(e),s=!0,a.length=0};return t.forEach(t=>{if(t.lbl!==``&&(s=!0,a.length=0,r))throw new e.s("Label in `with' statement",t);if(o){if(r)throw new e.s("Statement follows `call' or `return' inside a `with' statement.",t);c(t),o=!1}switch(t.kind){case`LabelIf`:{let e=[],n=[],i=be(t.unlabThen,!1,r,a,e);o=be(t.unlabElse,!1,r,a,n)||i,Dt(Tt(e,n),a);return}case`LabelEither`:{let e=[];t.clauses.forEach(t=>{let n=[];o=be(t.unlabOr,!1,r,a,n)||o,Dt(Tt(n,e),e)}),Dt(e,a);return}case`While`:if(r)throw new e.s("`while' inside a `with' statement",t);c(t),be(t.unlabDo,!1,!1,a,[]),o=!1;return;case`With`:{let e=[];o=be(t.Do,!1,!0,r?[...i]:[],e),Dt(e,a),!r&&!Et(i,a)&&c(t);return}}let n=t.kind===`Call`||t.kind===`CallGoto`,l=t.kind===`Return`||t.kind===`CallReturn`,u=t.kind===`Assign`?Tt([],t.ass.map(e=>e.lhs.var)):n||l?[`stack`,...l||t.to===m?h.flatMap(e=>[...e.params,...e.decls].map(e=>e.var)):[]]:[];if(o=n||l||t.kind===`Goto`,Et(a,u))Dt(Tt(a,u),a);else{if(r)throw new e.s(t.kind===`Assign`?"Second assignment to same variable inside a `with' statement":"Call or return makes second assignment to a variable inside a `with' statement",t);c(t),Dt(u,a)}}),s||o},xe=e=>{let t=e=>{let t=e.findIndex(e=>e.lbl!==``),n=t===-1?e:e.slice(0,t);return xe(n),{unlabeled:n,labeled:Se(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}}})},Se=t=>{let n=[];return t.forEach(t=>{if(t.lbl===``&&n.length>0)n[n.length-1].stmts.push(t);else{if(t.lbl===``)throw new e.o(`Failure of assertion: Missing Label in MakeLabeledStmtSeq`);n.push({...V(),kind:`LabeledStmt`,col:t.col,line:t.line,macroCol:t.macroCol,macroLine:t.macroLine,label:t.lbl,stmts:[t]})}}),n.forEach(e=>xe(e.stmts)),n},Ce=(t,n)=>{let r=t[n];switch(r.kind){case`LabelIf`:{let e=we(r.unlabThen);r.labThen.forEach(e=>we(e.stmts));let i=we(r.unlabElse);return r.labElse.forEach(e=>we(e.stmts)),r.labThen.length>0||r.labElse.length>0||e===2||i===2?2:(t[n]={...V(),kind:`If`,test:r.test,Then:r.unlabThen,Else:r.unlabElse},+(e+i>0))}case`LabelEither`:{let e=r.clauses.reduce((e,t)=>{let n=Math.max(e,we(t.unlabOr));return t.labOr.forEach(e=>we(e.stmts)),t.labOr.length>0?2:n},0);return e===2?2:(t[n]={...V(),kind:`Either`,ors:r.clauses.map(e=>e.unlabOr)},e)}case`With`:{let t=we(r.Do);if(t===2)throw new e.s(`with statement at ${ze(r)} contains a labeled statement`);return t}case`While`:if(n!==0)throw new e.o("ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.");return we(r.unlabDo),r.labDo.forEach(e=>we(e.stmts)),0;case`Call`:return t[n+1]?.kind===`Return`?0:1;case`Return`:case`CallReturn`:if(m===void 0)throw new e.s(`return statement not in a procedure at ${ze(r)}`);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.o(`ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${r.kind}`)}},we=t=>{for(let n=0;n<t.length;n++){let r=Ce(t,n);if(r!==0){if(n===t.length-1)return r;throw new e.o(`Translator discovered later than it should have that\n Statement at ${ze(t[n+1])} must have a label`)}}return 0},Te=e=>{be(e,!0,!1,[],[]);let t=Se(e);return t.forEach(e=>we(e.stmts)),t},Ee=(t,n,r,i,a)=>{let o=e=>nt(e,n,r),s=e=>e.map(e=>Ee(e,n,r,i,a)),c=e=>e.map(e=>({...V(),kind:`LabeledStmt`,label:e.label,stmts:e.stmts.map(e=>Ee(e,n,r,-1,0))})),l={...V(),col:t.col,line:t.line,macroCol:i>0?a:t.macroCol,macroLine:i>0?i:t.macroLine};switch(t.kind){case`Assign`:return{...l,kind:`Assign`,ass:t.ass.map(e=>De(e,n,r,i,a))};case`If`:return{...l,kind:`If`,test:o(t.test),Then:s(t.Then),Else:s(t.Else)};case`Either`:return{...l,kind:`Either`,ors:t.ors.map(s)};case`With`:return{...l,kind:`With`,var:t.var,isEq:t.isEq,exp:o(t.exp),Do:s(t.Do)};case`When`:case`Assert`:case`PrintS`:return{...l,kind:t.kind,exp:o(t.exp)};case`Skip`:return{...l,kind:`Skip`,macroCol:i>0?a:0,macroLine:i>0?i:-1};case`While`:return{...l,kind:`While`,test:o(t.test),unlabDo:s(t.unlabDo),labDo:c(t.labDo)};case`LabelIf`:return{...l,kind:`LabelIf`,test:o(t.test),unlabThen:s(t.unlabThen),labThen:c(t.labThen),unlabElse:s(t.unlabElse),labElse:c(t.labElse)};case`LabelEither`:return{...l,kind:`LabelEither`,clauses:t.clauses.map(e=>({...V(),kind:`Clause`,labOr:c(e.labOr),unlabOr:s(e.unlabOr)}))};case`Call`:return{...l,kind:`Call`,to:t.to,returnTo:t.returnTo,args:rt(t.args,n,r)};case`Return`:return{...l,kind:`Return`,from:t.from};case`CallReturn`:return{...l,kind:`CallReturn`,to:t.to,from:t.from,args:rt(t.args,n,r)};case`CallGoto`:return{...l,kind:`CallGoto`,to:t.to,after:t.after,args:rt(t.args,n,r)};case`Goto`:return{...l,kind:`Goto`,to:t.to};default:throw new e.o(`Found unexpected statement type in macro at${ze(t)}`)}},De=(t,n,r,i,a)=>{let o=nt(t.rhs,n,r),s={...V(),kind:`Lhs`,var:t.lhs.var,sub:t.lhs.sub.tokens.length===0?t.lhs.sub:nt(t.lhs.sub,n,r)},c={...V(),kind:`SingleAssign`,col:t.col,line:t.line,macroCol:i>0?a:t.macroCol,macroLine:i>0?i:t.macroLine,lhs:s,rhs:o},l=r.indexOf(s.var);if(l===-1)return c;let u=n[l],d=Ze(u,{line:0,item:0});if(d.type!==Fe.ident)throw new e.s(`Macro expansion substitutes \`${d.string}' for assignment variable\n at ${ze(c)}`);if(s.var=d.string,Qe(u,{line:0,item:0},1)===void 0)return c;let f=Je(u);return f.tokens[0].splice(0,1),Ge(f),s.sub.tokens.length===0?s.sub=f:Ye(s.sub,f,0),c},B=(e,t)=>{let n=e.flatMap(e=>{switch(e.kind){case`LabelIf`:return B(e.unlabThen,t),B(e.unlabElse,t),[e];case`LabelEither`:return e.clauses.forEach(e=>B(e.unlabOr,t)),[e];case`With`:return B(e.Do,t),[e];case`While`:return B(e.unlabDo,t),[e];case`MacroCall`:return Oe(e,t);default:return[e]}});e.splice(0,e.length,...n)},Oe=(t,n)=>{let r=n.findLast(e=>e.name===t.name);if(r===void 0)throw new e.s(`Macro ${t.name} undefined,\n at ${ze(t)}`);if(r.params.length!==t.args.length)throw new e.s(`Macro ${t.name} called with wrong number of arguments at \n ${ze(t)}`);let i=r.body.map(e=>Ee(e,t.args,r.params,t.line,t.col));return i.length>0&&(i[0].lbl=t.lbl),i},ke=t=>{t.forEach((n,r)=>{if(t.slice(r+1).some(e=>e.name===n.name))throw new e.s(`Multiple definitions of macro name \`${n.name}'`)})},Ae=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`||!Xe(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)},je=()=>{let t=c.length>1?`Missing labels at the following locations:`:`Missing label at the following location:`;throw new e.s([t,...l].join(`
|
|
28
28
|
`))},Me=e=>h.forEach(t=>{m=t.name,B(t.body,e),t.body=Te(t.body)}),Ne=()=>{r&&w()!==`algorithm`&&C("`--fair' not followed by `algorithm'");let e=w();g=T(1)===`{`,g&&O(`{`);let n=T(1)===`variable`||T(1)===`variables`?F():[],a=We();T(1)===`define`&&(O(`define`),g&&k(`{`),a=D(!0),N(`define`),k(`;`));let o=[];for(;T(1)===`macro`;)o.push(he(o));for(;T(1)===`procedure`;)h.push(ge()),S=!1;if(T(1)===`fair`&&(T(2)===`process`||T(2)===`+`&&T(3)===`process`)||T(1)===`process`){let r=[];for(;T(1)===`fair`||T(1)===`process`;){let e=T(1)===`fair`;e&&O(`fair`);let t=e&&T(1)===`+`;t&&O(`+`);let n=t||!e&&i.fairnessOption===`sf`?2:e||i.fairnessOption===`wf`?1:0;r.push({..._e(),fairness:n})}return N(`algorithm`),ke(o),r.forEach(e=>{B(e.body,o),e.body=Te(e.body),Ae(e.body)}),Me(o),c.length>0&&(i.labelFlag||je(),t.log(`Labels added.`)),(x||b)&&(S=!1),{...V(),kind:`Multiprocess`,name:e,decls:n,defs:a,macros:o,prcds:h,procs:r}}i.inputVersionNumber===1500&&T(1)===`fair`&&(k(`fair`),T(1)===`+`&&k(`+`),i.fairnessOption=`wf`),r&&([``,`wf`,`wfNext`].includes(i.fairnessOption)||t.log(`Warning: Option \`${i.fairnessOption}' specified for --fair algorithm.`),i.fairnessOption=`wf`),M();let s=re();ke(o),B(s,o),Me(o),g&&k(`}`),N(`algorithm`);let l=Te(s);return c.length>0&&(f&&!i.labelFlag&&je(),t.log(`Labels added.`)),(b||x)&&(S=!1),Ae(l),{...V(),kind:`Uniprocess`,name:e,decls:n,defs:a,macros:o,prcds:h,body:l}};try{return{ast:Ne(),shouldOmitPC:S,hasDefaultInitialization:p}}catch(t){if(!(t instanceof e.c))throw t;return C(`Unknown error at or before`)}},U={global:0,label:1,procedure:2,process:3,processVar:4,procedureVar:5,parameter:6},kt=[`Global variable`,`Label`,`Procedure`,`Process`,`Process variable`,`Procedure variable`,`Parameter`],At=/* @__PURE__ */ new Set([U.global,U.processVar,U.procedureVar,U.parameter]),jt=(e,t,n,r)=>e.symbols.find(e=>e.id===n&&e.context===r&&e.type===t),Mt=(e,t,n)=>e.symbols.find(e=>e.id===t&&e.context===n),Nt=(e,t)=>{let n=e.procedures.findIndex(e=>e.name===t);return n===-1?e.procedures.length:n},Pt=(e,t,n,r)=>!(t===U.procedureVar||t===U.processVar||t===U.parameter?jt(e,U.global,n,``)!==void 0||Mt(e,n,r)!==void 0:jt(e,t,n,r)!==void 0)&&(e.symbols.push({type:t,id:n,context:r,useThis:n}),!0),Ft=(e,t,n,r)=>jt(e,t,n,r)?.useThis??n,It=(e,t,n)=>{let r=Mt(e,t,n);return r===void 0?t:At.has(r.type)?r.useThis:t},Lt=t=>{let n={symbols:[],procedures:[],processNames:[],errorReport:``},r=(e,t)=>{Pt(n,U.label,e.label,t)||(n.errorReport+=`\nLabel ${e.label} redefined at line ${e.line}, column ${e.col}`),e.stmts.forEach(e=>i(e,t))},i=(t,n)=>{let a=e=>e.forEach(e=>i(e,n)),o=e=>e.forEach(e=>r(e,n));switch(t.kind){case`While`:a(t.unlabDo),o(t.labDo);return;case`If`:a(t.Then),a(t.Else);return;case`With`:a(t.Do);return;case`LabelIf`:a(t.unlabThen),o(t.labThen),a(t.unlabElse),o(t.labElse);return;case`Either`:t.ors.forEach(a);return;case`LabelEither`:t.clauses.forEach(e=>{a(e.unlabOr),o(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.o(`Unexpected AST type ${t.kind}`)}},a=(e,t,r=t===``?U.global:U.processVar)=>{Pt(n,r,e.var,t)||(n.errorReport+=`\n${kt[r]} ${e.var} redefined at line ${e.line}, column ${e.col}`)};if(Pt(n,U.global,`pc`,``),t.prcds.length>0&&Pt(n,U.global,`stack`,``),t.decls.forEach(e=>a(e,``)),t.prcds.forEach(e=>{let t=Nt(n,e.name)<n.procedures.length;t&&(n.errorReport+=`\nProcedure ${e.name} redefined at line ${e.line}, column ${e.col}`),t||n.procedures.push({name:e.name,params:e.params,decls:e.decls,initialPC:e.body.length===0?void 0:Be(e.body[0]).label}),Pt(n,U.procedure,e.name,``),e.decls.forEach(t=>a(t,e.name,U.procedureVar)),e.params.forEach(t=>a(t,e.name,U.parameter)),e.body.forEach(t=>r(Be(t),e.name))}),t.kind===`Multiprocess`&&t.procs.forEach(e=>{let t=n.processNames.includes(e.name);t&&(n.errorReport+=`\nProcess ${e.name} redefined at line ${e.line}, column ${e.col}`),t||n.processNames.push(e.name),Pt(n,U.process,e.name,``),e.decls.forEach(t=>a(t,e.name)),e.body.forEach(t=>r(Be(t),e.name))}),t.kind===`Uniprocess`&&t.body.forEach(e=>r(Be(e),``)),n.errorReport.length>0)throw new e.s(n.errorReport);return n},Rt=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},zt=t=>{let n=t.symbols.filter(e=>e.id===`defaultInitValue`).map(e=>`${kt[e.type]} name`);if(n.length>0)throw new e.s(`Cannot use \`defaultInitValue' as ${n.join(` or `)}`)},Bt=(t,n,r)=>{let i=(e,t)=>{let r=[],i=[];e.tokens.forEach(e=>e.forEach(e=>{if(e.type!==Fe.ident)return;let a=It(n,e.string,t);r.includes(e.string)||a===e.string||(r.push(e.string),i.push(Ke([[Wt(a)]])))})),i.length>0&&tt(e,i,r,!1)},a=(e,t)=>{e.var=It(n,e.var,t),i(e.val,t)},o=(e,t)=>e.forEach((r,i)=>{e[i]=Ft(n,U.label,r,t)}),s=(e,t)=>e===void 0?void 0:Ft(n,U.procedure,e,t),c=(e,t)=>{e.label=Ft(n,U.label,e.label,t),e.stmts.forEach(e=>l(e,t))},l=(t,r)=>{let a=e=>e.forEach(e=>l(e,r)),o=e=>e.forEach(e=>c(e,r)),u=e=>e.forEach(e=>i(e,r));switch(t.kind){case`LabeledStmt`:c(t,r);return;case`While`:a(t.unlabDo),o(t.labDo),i(t.test,r);return;case`Assign`:t.ass.forEach(e=>{e.lhs.var=It(n,e.lhs.var,r),i(e.lhs.sub,r),i(e.rhs,r)});return;case`If`:a(t.Then),a(t.Else),i(t.test,r);return;case`With`:i(t.exp,r),a(t.Do);return;case`When`:case`PrintS`:case`Assert`:i(t.exp,r);return;case`Skip`:return;case`LabelIf`:i(t.test,r),a(t.unlabThen),o(t.labThen),a(t.unlabElse),o(t.labElse);return;case`Call`:t.returnTo=Ft(n,U.procedure,t.returnTo,r),t.to=Ft(n,U.procedure,t.to,r),u(t.args);return;case`Return`:t.from=s(t.from,r);return;case`CallReturn`:t.from=s(t.from,r),t.to=Ft(n,U.procedure,t.to,r),u(t.args);return;case`CallGoto`:t.after=Ft(n,U.procedure,t.after,r),t.to=Ft(n,U.procedure,t.to,r),u(t.args);return;case`Goto`:if(jt(n,U.label,t.to,r)===void 0&&t.to!==`Done`)throw new e.s(`goto to non-existent label \`${t.to}' at line ${t.line}, column ${t.col}`);t.to=Ft(n,U.label,t.to,r);return;case`Either`:t.ors.forEach(a);return;case`LabelEither`:t.clauses.forEach(e=>{a(e.unlabOr),o(e.labOr)});return;default:throw new e.o(`Unexpected AST type${t.kind}`)}},u=e=>{e.decls.forEach(t=>a(t,e.name)),e.params.forEach(t=>a(t,e.name)),e.body.forEach(t=>c(Be(t),e.name));let t=Ve(n.procedures,Nt(n,e.name));o(e.plusLabels,e.name),o(e.minusLabels,e.name),t.initialPC!==void 0&&(t.initialPC=Ft(n,U.label,t.initialPC,e.name)),e.name=Ft(n,U.procedure,e.name,``),t.name=e.name},d=e=>{e.decls.forEach(t=>a(t,e.name)),e.body.forEach(t=>c(Be(t),e.name)),o(e.plusLabels,e.name),o(e.minusLabels,e.name),e.name=Ft(n,U.process,e.name,``)};t.decls.forEach(e=>a(e,``)),t.kind===`Multiprocess`&&((e,t)=>{e.forEach(u);let n=e.map(e=>e.name),i=e.map(e=>n.map(t=>e.proceduresCalled.includes(t)));n.forEach((e,t)=>i.forEach(e=>e.forEach((n,r)=>{e[r]=n||e[t]&&i[t][r]}))),e.forEach((e,t)=>{e.proceduresCalled=n.filter((e,n)=>i[t][n])});for(let e of t){d(e);let t=e.proceduresCalled;for(let e=0;e<t.length;e+=1){let a=n.indexOf(t[e]);if(a===-1){r(`\nUnrecoverable error:\n -- Could not find procedure name \`${t[e]}'.\n`);return}n.forEach((e,n)=>{i[a][n]&&!t.includes(e)&&t.push(e)})}}})(t.prcds,t.procs),t.kind===`Uniprocess`&&(t.prcds.forEach(u),t.body.forEach(e=>c(Be(e),``)))},Vt=e=>He(e,0,Fe.string),Ht=e=>He(e,0,Fe.added),Ut=e=>He(e,0,Fe.builtin),Wt=e=>He(e,0,Fe.ident),Gt=(e,t)=>{let n=[];return e.forEach(e=>{let r=n.at(-1),i=r===void 0?0:r.column+Ue(r)+t;n.push(He(e.string,i,e.type))}),Ke([n])},Kt=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+=Ue(e),e.type===Fe.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}})}),qt=(e,t,n,r=0,i=0)=>({...V(),kind:`SingleAssign`,line:r,col:i,lhs:{...V(),kind:`Lhs`,var:e,sub:t},rhs:n}),Jt=(e,t=0,n=0)=>({...V(),kind:`Assign`,line:t,col:n,ass:e}),Yt=(e,t,n=0,r=0)=>Jt([qt(e,Ke([]),t,n,r)],n,r),Xt=e=>{if(e.tokens.length>1)return!1;let t=Ve(e.tokens,0);return t.length===1?t[0].string===`TRUE`:t.length===3&&t[0].string===`(`&&t[1].string===`TRUE`&&t[2].string===`)`},Zt=e=>({...V(),kind:`When`,exp:Gt([Ht(`pc`),Ut(`=`),Vt(e)],1)}),Qt=e=>Yt(`pc`,Ke([[Vt(e??`null`)]])),$t=e=>[Wt(`Head`),Ut(`(`),Ht(`stack`),Ut(`)`),Ut(`.`),Wt(e)],en=()=>[Wt(`Tail`),Ut(`(`),Ht(`stack`),Ut(`)`)],tn=e=>Ke([$t(e)]),nn=(e,t,n,r)=>{let i=[[Ut(`<<`),Ut(`[`),Wt(`procedure`),Ut(`|->`),Vt(e),Ut(`,`)],[Wt(`pc`),Ut(`|->`),...t]];n.forEach(e=>{i[i.length-1].push(Ut(`,`)),i.push([Wt(e.var),Ut(`|->`),Wt(e.var)])}),i[i.length-1].push(Ut(`]`),Ut(`>>`)),i.push(r);let a=We(i);return Kt(a),Ge(a),a},rn=(t,n,r)=>{if(n.params.length!==r.args.length)throw new e.s(`Procedure ${r.to} called with wrong number of arguments`,r);return n.params.forEach((e,n)=>t.ass.push(qt(e.var,Ke([]),r.args[n],r.line,r.col))),[t,...n.decls.map(e=>Yt(e.var,e.val,r.line,r.col)),Qt(n.initialPC)]},an=(t,n,r)=>{let i,a=(t,r)=>{let i=Nt(n,t.to);if(i===n.procedures.length)throw new e.s(`Call of non-existent procedure ${t.to}`,t);let a=n.procedures[i],o=nn(t.to,[Vt(r)],[...a.decls,...a.params],[Ut(`\\o`),Ht(`stack`)]);return rn(Yt(`stack`,o,t.line,t.col),a,t)},o=t=>{t.from??=i;let r=t.from;if(r===void 0)throw new e.s("`return' statement not in procedure",t);let a=Nt(n,r);if(a>=n.procedures.length)throw new e.s(`Error in procedure (perhaps name used elsewhere)`,t);let o=n.procedures[a],s=(e,n)=>Jt([qt(e,We(),n,t.line,t.col)],t.line,t.col);return[s(`pc`,tn(`pc`)),...o.decls.map(e=>s(e.var,tn(e.var))),...o.params.map(e=>s(e.var,tn(e.var))),s(`stack`,Ke([en()]))]},s=t=>{let r=t.from;if(r===void 0)throw new e.s(`\`return' statement following \`call' at ${ze(t)} not in a procedure`);let i=Ve(n.procedures,Nt(n,r)),a=Nt(n,t.to);if(a===n.procedures.length)throw new e.s(`Call of non-existent procedure ${t.to}`,t);let o=n.procedures[a],s=Jt([],t.line,t.col);if(r!==t.to){i.decls.forEach(e=>s.ass.push(qt(e.var,We(),tn(e.var),t.line,t.col)));let e=nn(t.to,$t(`pc`),[...o.decls,...o.params],[Ut(`\\o`),...en()]);s.ass.push(qt(`stack`,Ke([]),e,t.line,t.col))}return rn(s,o,t)},c=(e,t)=>{if(e.length===0)return{stmts:[],labeledStmts:[],needsGoto:!r};let n={stmts:e,labeledStmts:[],needsGoto:!1},i=e[e.length-1];switch(i.kind){case`LabelIf`:case`LabelEither`:{let r=i.kind===`LabelIf`?p(i,t):m(i,t);e.pop(),e.push(r.stmt),n.labeledStmts=r.labeledStmts;break}case`Goto`:e.pop(),e.push(Qt(i.to));break;case`Call`:e.pop(),e.push(...a(i,t));break;case`Return`:e.pop(),e.push(...o(i));break;case`CallReturn`:e.pop(),e.push(...s(i));break;case`CallGoto`:e.pop(),e.push(...a({...V(),kind:`Call`,returnTo:``,to:i.to,args:i.args,line:i.line,col:i.col},i.after));break;case`If`:{let e=c(i.Then,t),a=c(i.Else,t);n.labeledStmts.push(...e.labeledStmts,...a.labeledStmts),i.Then=e.stmts,i.Else=a.stmts,r||(n.needsGoto=e.needsGoto&&a.needsGoto,n.needsGoto||(e.needsGoto&&i.Then.push(Qt(t)),a.needsGoto&&i.Else.push(Qt(t))));break}case`Either`:{let e=i.ors.map((e,r)=>{let a=c(e,t);return i.ors[r]=a.stmts,n.labeledStmts.push(...a.labeledStmts),a});n.needsGoto=e.every(e=>e.needsGoto),!r&&!n.needsGoto&&e.forEach((e,n)=>{e.needsGoto&&i.ors[n].push(Qt(t))});break}case`With`:{let e=c(i.Do,t);i.Do=e.stmts,n.labeledStmts.push(...e.labeledStmts),n.needsGoto=e.needsGoto;break}default:n.needsGoto=!0}return r&&(n.needsGoto=!1),n},l=(e,t)=>{let n=c(e,t);return n.needsGoto&&n.stmts.push(Qt(t)),n},u=(e,t)=>{let n=e.stmts.at(0);if(n?.kind===`While`)return f(e,n,t);let i=l([...e.stmts],t),a=[];return r||(i.stmts.unshift(Zt(e.label)),a.push({...V(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:i.stmts})),a.push(...i.labeledStmts),a},d=(e,t)=>e.flatMap((n,r)=>u(n,r<e.length-1?e[r+1].label:t)),f=(e,t,n)=>{let i=t.labDo.length===0?e.label:t.labDo[0].label,a=l([...t.unlabDo],i),o=l(e.stmts.slice(1),n),s=Xt(t.test),c=s?a.stmts:[{...V(),kind:`If`,test:t.test,Then:a.stmts,Else:o.stmts}];return[{...V(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:[...r?[]:[Zt(e.label)],...c]},...d(t.labDo,e.label),...a.labeledStmts,...s?[]:o.labeledStmts]},p=(e,t)=>{let n=l(e.unlabThen,e.labThen.length===0?t:e.labThen[0].label),r=l(e.unlabElse,e.labElse.length===0?t:e.labElse[0].label),i=d(e.labThen,t);return i.push(...d(e.labElse,t)),i.push(...n.labeledStmts,...r.labeledStmts),{stmt:{...V(),kind:`If`,col:e.col,line:e.line,test:e.test,Then:n.stmts,Else:r.stmts},labeledStmts:i}},m=(e,t)=>{let n=[],r=[];return e.clauses.forEach(e=>{let i=l(e.unlabOr,e.labOr.length>0?e.labOr[0].label:t);n.push(i.stmts),r.push(...i.labeledStmts),r.push(...d(e.labOr,t))}),{stmt:{...V(),kind:`Either`,col:e.col,line:e.line,ors:n},labeledStmts:r}},h=(e,t)=>d(e.map(Be),t),g=e=>{i=e.name;let t=h(e.body,Ft(n,U.label,`Error`,``));return i=void 0,{...V(),kind:`Procedure`,col:e.col,line:e.line,name:e.name,minusLabels:[],plusLabels:[],proceduresCalled:[],params:e.params,decls:e.decls,body:t}},_=e=>({...V(),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:h(e.body,`Done`)}),v=t.prcds.map(g);return t.kind===`Uniprocess`?{...V(),kind:`Uniprocess`,col:t.col,line:t.line,name:t.name,decls:t.decls,defs:t.defs,macros:[],prcds:v,body:h(t.body,`Done`)}:{...V(),kind:`Multiprocess`,col:t.col,line:t.line,name:t.name,decls:t.decls,defs:t.defs,macros:[],prcds:v,procs:t.procs.map(_)}},on=(t,n)=>{let r=n?[]:[`pc`];if(r.push(...t.decls.map(e=>e.var)),t.prcds.length>0&&r.push(`stack`),t.prcds.forEach(e=>{r.push(...e.params.map(e=>e.var)),r.push(...e.decls.map(e=>e.var))}),t.kind===`Multiprocess`&&t.procs.forEach(e=>r.push(...e.decls.map(e=>e.var))),r.length===0)throw new e.s(`The algorithm has no variables.`);let i=(e,t)=>{let n=r.indexOf(t);return n===-1?0:(e[n]+=1,e[n])},a=(e,t)=>t.forEach((t,n)=>{e[n]=Math.max(e[n],t)}),o=e=>[...e].sort((e,t)=>e.lhs.var<t.lhs.var?-1:+(e.lhs.var>t.lhs.var)),s=(t,n)=>{let s=[...n];t.ass=o(t.ass),new Set(t.ass.map(e=>e.lhs.var)).forEach(n=>{let a=t.ass.filter(e=>e.lhs.var===n);if(!r.includes(n))throw new e.s(`Assignment to undeclared variable ${n}`,a[0]);let o=a.some(e=>e.lhs.sub.tokens.length===0);if(i(s,n)>1||a.length>1&&o)throw new e.s(`Multiple assignment to ${n}`,t)}),a(n,s)},c=(t,n)=>{switch(t.kind){case`Assign`:s(t,n);return;case`If`:{let e=[...n],r=[...n];t.Then.forEach(t=>c(t,e)),t.Else.forEach(e=>c(e,r)),a(n,e),a(n,r);return}case`Either`:{let e=[...n];t.ors.forEach(t=>{let r=[...n];t.forEach(e=>c(e,r)),a(e,r)}),a(n,e);return}case`With`:t.Do.forEach(e=>c(e,n));return;case`When`:case`PrintS`:case`Assert`:case`Skip`:return;default:throw new e.o(`Unexpected AST type ${t.kind}`)}},l=e=>e.forEach(e=>{let t=r.map(()=>0);Be(e).stmts.forEach(e=>c(e,t))});t.prcds.forEach(e=>l(e.body)),(t.kind===`Uniprocess`?[t.body]:t.procs.map(e=>e.body)).forEach(l)},sn=(e,t,n,r)=>{let i=Lt(e);Rt(i)&&r(`Warning: symbols were renamed.`),Bt(e,i,r),on(an(e,i,t),t),n&&zt(i)},cn=`[ \\t\\n\\x0B\\f\\r]`,ln=RegExp(`\\\\\\* BEGIN TRANSLATION${cn}+\\(${cn}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${cn}*(=${cn}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${cn}*STRING)${cn}*\\/\\\\${cn}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${cn}*(=${cn}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${cn}*STRING)${cn}*\\)`),un=e=>process.getBuiltinModule(`node:zlib`).crc32(Buffer.from(e,`utf8`)).toString(16),dn=(e,t)=>e.log(`\nUnrecoverable error:\n -- ${t}.\n`),fn=(e,t)=>dn(e,t.node===void 0||t.node.line===0?t.message:`${t.message}\n at ${ze(t.node)}`),pn=e=>e.map(e=>`${Array.from(e).reduce((e,t)=>t===` `?e+` `.repeat(8-e.length%8):e+t,``)} `),mn=(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},hn=(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``},gn=(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},_n=e=>/^[\p{L}\p{Nd}_]$/u.test(e),vn=(e,t,n)=>{for(;t.line<e.length;){let r=hn(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=gn(r,e,` `),!0}t.column=gn(r,t.column,` `)}return!1},yn=(e,t)=>dn(e,`Command-line error: ${t}`),bn=(e,t)=>{let n=e.params,r=!0,i=!1,a=t=>(r&&=(n.fairnessOption=``,!1),n.fairnessOption===``?(n.fairnessOption=t,!0):(yn(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){yn(e,`
|
|
29
|
-
Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){yn(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){yn(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){yn(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){yn(e,"Version number must follow `-version' option");return}let t=Le(s);if(t<0||t>1903){dn(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),yn(e,`Bad version number`);return}n.inputVersionNumber=t,r+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){yn(e,"Integer value at least 60 must follow `-lineWidth' option");return}r+=1;continue;default:yn(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!i&&(n.fairnessOption=`wf`)},xn=(e,t,n)=>{if(hn(t,n),n.column+=7,!hn(t,n).slice(n.column).startsWith(`(`)){dn(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=hn(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=gn(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?dn(e,`No closing ')' found in options statement`):bn(e,r)},Sn=(t,n,r)=>{let i=0,a=!1,o=!1;for(let s=n;!a&&s<t.length;s++){let c=t[s],l=s===n?r:0,u=[c.slice(0,l)];o=!1;for(let e=l;!a&&e<c.length;e++){let t=c[e],n=c.slice(e,e+2);if(n===`(*`&&!o)i+=1,u.push(` `),e+=1;else if(n===`*)`&&!o&&i===0)u.push(n),a=!0;else if(n===`*)`&&!o)--i,u.push(` `),e+=1;else if(i>0)u.push(` `);else if(o&&t===`\\`&&n.length===2)u.push(n),e+=1;else{if(!o&&n===`\\*`){u.push(` `);break}t===`"`&&(o=!o),u.push(t)}}if(o)return new e.s(`Unterminated string in line ${s+1}`);t[s]=u.join(``)}},Cn=(t,n)=>{let r=10*2**Math.max(0,Math.ceil(Math.log2(n/10)));throw new e.c(`java.lang.ArrayIndexOutOfBoundsException: Index ${t} out of bounds for length ${r}`)},wn=(t,n,r)=>{if(!n.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let i=pn(n),a={line:0,column:0};for(;vn(i,a,`PlusCal`);){let e=hn(i,a).slice(a.column),n=Array.from(e).findIndex(e=>!_n(e));if(e.startsWith(`options`)&&(n===-1?e.length:n)===7){xn(t,i,a);break}}let o=0,s=-1,c=!1;for(;o<i.length;o++){let e=i[o];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){s=t+11;break}if(n!==-1){s=n+6,c=!0;break}}let l=/* @__PURE__ */ new Set,u=mn(i,0,`BEGIN`,`TRANSLATION`);u===-1&&l.add(`NO_TRANSLATION_EXISTS`);let d=mn(i,u+1,`END`,`TRANSLATION`);if(d===-1&&l.add(`NO_TRANSLATION_EXISTS`),u===-1&&d===-1)return l;if(s===-1)return l.add(`NO_PLUSCAL_EXISTS`),l;let f=Sn(i,o,s);if(f!==void 0)return fn(t,f),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let p;try{let e=Ot(t,ot(i,o,s),c);p=e.ast,sn(e.ast,e.shouldOmitPC,e.hasDefaultInitialization,t.log)}catch(n){if(!(n instanceof e.s))throw n;fn(t,n)}u===-1&&Cn(-1,i.length);let m=ln.exec(i[u]);if(m===null)return l.add(`NO_PCAL_CHECKSUMS_EXIST`),l;let h=m.groups?.pcal,g=c&&r!==`1.7.4`?`fair`:p===void 0?void 0:at(p,t.params.inputVersionNumber,r);h!==void 0&&(g===void 0||h!==un(g))&&l.add(`PCAL_DIVERGENCE_EXISTS`);let _=m.groups?.tla;if(_!==void 0){if(d===-1)throw new e.c(`java.lang.IllegalArgumentException: fromIndex(${u+1}) > toIndex(-1)`);let t=n.slice(u+1,d).join(``);_!==un(t)&&l.add(`TLA_DIVERGENCE_EXISTS`)}return l.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):l},Tn=[[`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]]],En={file:`--TLA+ BUILTINS--`,beginLine:0,beginColumn:0,endLine:0,endColumn:0},W=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}),Dn=e=>Tn.map(([t,n,r,i,a])=>{let o=e(),s=n<0?void 0:Array.from({length:n},(t,n)=>({...W(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{...W(o),levelChecked:c?99:0,level:r,kind:`OpDef`,defKind:`BuiltIn`,name:t,arity:n,params:s,body:void 0,isLocal:!1,location:En,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}}),On=(e,t)=>{let n=JSON.stringify(t);e.some(e=>JSON.stringify(e)===n)||e.push(t)},kn=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}`,An=e=>e?.kind===`OpAppl`&&e.isAbsent===!0,jn=e=>{let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;return t},Mn=()=>({buckets:Array.from({length:11},()=>[]),count:0,threshold:8}),Nn=(e,t)=>(e&2147483647)%t,Pn=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[Nn(e.hash,t)].unshift(e));e.buckets=n,e.threshold=Math.floor(t*.75)},Fn=(e,t,n=t)=>e.buckets[Nn(jn(n),e.buckets.length)].find(e=>e.key===t)?.value,In=(e,t,n,r=t)=>{let i=jn(r),a=e.buckets[Nn(i,e.buckets.length)].find(e=>e.key===t);a?a.value=n:(e.count>=e.threshold&&Pn(e),e.buckets[Nn(i,e.buckets.length)].unshift({hash:i,key:t,value:n}),e.count++)},Ln=e=>e.buckets.toReversed().flatMap(e=>e.map(e=>e.value)),Rn=`\0module `,zn=()=>({table:Mn(),symbols:[]}),Bn=e=>e.kind===`Module`?Rn+e.name:e.name,Vn=(e,t)=>{In(e.table,Bn(t),t,t.name),e.symbols.push(t)},Hn=e=>e.kind===`ThmOrAssumpDef`?e.params.length:e.kind===`Module`?0:e.arity,Un=(e,t)=>Fn(e.table,t),Wn=(e,t)=>Fn(e.table,Rn+t,t),Gn=e=>e.context.symbols.filter(e=>e.kind===`OpDef`&&e.defKind===`UserDefined`),Kn=(e,t)=>Ln(e.context.table).filter(e=>e.kind===`OpDecl`&&e.declKind===t).toReversed(),qn=e=>e.context.symbols.filter(e=>e.kind===`ThmOrAssumpDef`),Jn=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),Yn=e=>{if(e.length>3&&e.endsWith(`!!!`))return[...Yn(e.slice(0,-3)),`!!`];let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},Xn=e=>{switch(e.kind){case`Identifier`:return Yn(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=Yn(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}}})}},Zn=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},Qn=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,$n=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,er=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),tr=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,nr=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],rr=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},ir=e=>(t,n,r,i,a)=>{let o=[],s=[],c=[],l=e=>t[e].location??a,u={name:void 0,nameLocation:void 0,node:void 0,index:0,mode:`FindingOpName`,previousMode:void 0,letInContext:void 0,definitionArityFound:0,definitionArgs:[],isInSuffices:!1},d=e=>e.args??[];for(;u.index<t.length;){let f=t[u.index];if((f.op!==`Name`&&f.op!==`Null`||n!==0)&&f.args!==void 0)return e.addError(l(u.index),`Selector \`${f.name}' should not have argument(s).`);switch(u.mode){case`FindingOpName`:{let f,p,m=[];for(;f===void 0&&u.index<t.length;){let n=t[u.index];if(p=n.op===`Name`?u.name===void 0?e.resolveSynonym(n.name):`${u.name}!${e.resolveSynonym(n.name)}`:void 0,u.name===void 0&&n.op!==`Name`)return e.addError(l(u.index),`Need name or step number here, not \`${n.name}'.`);p!==void 0&&(f=u.letInContext===void 0?e.resolveSymbol(p):Un(u.letInContext,p)),f===void 0&&(p!==void 0&&(u.name=p,u.nameLocation=rr(u.nameLocation,l(u.index))),m.push(...d(n)),u.index++)}if(f===void 0&&e.version===`1.7.4`){let n=t.length-1;return e.addError(l(n),`Unknown operator: \`${Qn(t[n])}'.`)}if(f===void 0)return e.addError(u.nameLocation??a,`Unknown operator: \`${u.name}'.`);if(f.kind===`Module`)return e.addError(l(u.index),`Module name (${t[u.index].name}) not allowed here.`);if(u.node=f,u.nameLocation=rr(u.nameLocation,l(u.index)),u.name=p,er(f)&&t.length!==1)return e.addError(l(u.index),`Cannot take subexpression of \`${u.name}'.`);let h=Hn(f);if(n===0){if(m.push(...d(t[u.index])),u.definitionArityFound+m.length!==h)return e.addError(t[u.index].argsLocation??a,`The operator ${u.name} requires ${h-u.definitionArityFound} arguments.`);m.forEach((t,n)=>u.definitionArgs.push(e.generateArgument(f,n+u.definitionArityFound,t,l(u.index))))}if(u.definitionArityFound=h,f.kind===`OpDef`&&f.defKind===`ModuleInstance`){if(u.index===t.length-1&&!(i||r))return e.addError(l(u.index),`Operator name ${u.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(l(u.index),`Subexpression of \`${u.name}' used inside the operator's definition.`);if(u.index!==t.length-1&&n!==void 0){s.push(...n.params??[]),u.name=void 0,u.nameLocation=void 0,u.mode=t[u.index+1].op===`Name`?`FollowingLabels`:`FindingSubExpr`,c.push(...u.definitionArgs),u.definitionArityFound=0,u.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;u.mode===`FindingSubExpr`&&(u.node=e)}}u.previousMode=`FindingOpName`;break}case`FollowingLabels`:{let r=u.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(l(u.index),`Cannot find label \`${f.name}'.`);if(u.node=i,e.isOutOfLabelScope(i))return e.addError(l(u.index),`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(l(u.index),`Label \`${f.name}' used with wrong number of arguments.`);c.push(...d(f).map(e.generateExpression))}s.push(...i.params),u.index<t.length-1&&t[u.index+1].op!==`Name`&&(u.mode=`FindingSubExpr`),u.mode===`FindingSubExpr`&&(u.node=i.body),u.previousMode=`FollowingLabels`;break}case`FindingSubExpr`:{let n=u.node,r=()=>e.addError(l(u.index),`Nonexistent operand specified by \`${Qn(f)}'.`);if(f.op===`:`){if(!(u.previousMode!==`FindingSubExpr`&&(u.index===t.length-1&&u.previousMode===`FindingOpName`||u.index<t.length-1&&t[u.index+1].op===`Name`)))return e.addError(l(u.index),`\`!:' can be used only after a name and either at the end after an
|
|
30
|
-
operator name or before an operator name.`)}else if(n===void 0)return e.addError(l(u.index),`Subexpression selection failed, probably due to an error in the selected expression.`);else if(n.kind===`LetIn`){if(
|
|
31
|
-
from outside that declaration's scope.`);if(i<=n.assumptions.length){if(u.node=n.assumptions[i-1],u.node.kind===`NewSymb`&&u.index!==t.length-1)return e.addError(l(u.index),`Selected a subexpression of a NEW clause of an ASSUME.`)}else u.node=n.goal}}else if(n.kind===`OpArg`){let t=n.op;if(t.kind!==`OpDef`||t.name!==`LAMBDA`)return e.addError(l(u.index),`Trying to select subexpression of an operator argument.`);if(f.op!==`Null`&&f.op!==`@`)return e.addError(l(u.index),`Cannot use !${f.name} to select subexpression of a LAMBDA.`);if(f.op===`Null`){if(t.arity!==d(f).length)return e.addError(l(u.index),`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??[]),u.node=t.body}else if(n.kind===`Label`)u.node=n.body,u.index--;else return e.addError(l(u.index),`Selecting subexpression of expression that has none.`);if(u.node===void 0)return e.addError(l(u.index),`An unexpected null node specified by '${f.name}'.\nThis is probably due to a previous error.`);if(u.index!==t.length-1){let n=t[u.index+1];if(n.op===`Name`){for(;u.node?.kind===`Label`;)u.node=u.node.body;if(u.node?.kind!==`LetIn`)return e.addError(l(u.index),`A name selector here must be from a LET clause.`);u.letInContext=u.node.context,u.mode=`FindingOpName`}else if(n.op===`:`)return e.addError(l(u.index),`!: should not follow an operand selector.`)}u.previousMode=`FindingSubExpr`;break}}u.index++}let f=u.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 u.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`?
|
|
32
|
-
`&&i.push(e+1);return{name:e,source:n,tokens:r,lineOffsets:i,tokenIndexes:new Map(r.map((e,t)=>[
|
|
33
|
-
`,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},br=(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},xr=(e,t,n,r)=>{for(let i=t;i<=n;i++)if(G(e,i,r))return i;return-1},Sr=new Map(t.ct.flatMap(([e,...t])=>t.map(t=>[t,e]))),Cr=e=>e.split(`!`).map(e=>Sr.get(e)??(e===`~`?`\\lnot`:e)).join(`!`),wr={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}},Tr=e=>/^[A-Za-z0-9_]+$/.test(e),Er=e=>e!==`!!`&&e.includes(`!`),Dr=e=>e.contexts[e.contexts.length-1],Or=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=Un(e.contexts[n],t);if(r)return r}},kr=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,Ar=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,jr=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||Mr(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&Mr(n.module)}return!1},Mr=e=>Kn(e,2).length===0&&Kn(e,3).length===0,Nr=e=>[...e.kind===`Let`?e.instances??[]:[],...t.Qt(e).flatMap(Nr)],Pr=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:Pr(e)):Nr(e),Fr=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]:[]):[],...Fr(e.proof)]):[],Ir=(e,n)=>{let r=/* @__PURE__ */ new Set;for(let t of e.units)if(t.kind===`Module`&&r.add(t.module.name),t.kind===`Instance`&&t.instance.module===n.module)return r.has(n.module);return e.modules.some(e=>e.name===n.module&&t.pt(e.location,n.location))},Lr=e=>BigInt(e.startsWith(`\\`)?`0${e.slice(1).replace(/^h/i,`x`)}`:e).toString(),Rr=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`?Nr(e.definition.body):e.kind===`Theorem`&&s?[...Pr(e.theorem.statement),...Fr(e.theorem.proof)]:e.kind===`Assumption`&&s?Nr(e.assumption.expression):[]).filter(e=>l(e.module)&&!Ir(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}},zr=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),Br=e=>{let t=e.kind===`Apply`?Xn(e):void 0;return zr.has(e.kind)||t!==void 0&&Zn(t)},Vr=/* @__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`]]),Hr=/* @__PURE__ */ new Set([`N_GeneralId`,`N_OpApplication`,`N_PrefixExpr`,`N_InfixExpr`,`N_PostfixExpr`,`N_FcnAppl`,`N_RecordComponent`]),Ur=/* @__PURE__ */ new Set([`'`,`^+`,`^*`,`^#`]),Wr=(e,t)=>Ur.has(t)?`N_GenPostfixOp`:e.kind===`Lambda`||t===`~`||t===`-.`?`N_GenNonExpPrefixOp`:`N_GenInfixOp`,Gr=(n,r,i={})=>{let a=[],o=(e,t)=>On(a,{location:e,text:t,isWarning:!1}),s=(e,t)=>On(a,{location:e,text:t,isWarning:!0}),c=i.version===`1.7.4`?-1:0,l=()=>++c,u=0,d=(e,t)=>{let n=Or(e,t.name);if(n===t)return;if(n===void 0){Vn(Dr(e),t);return}let r=t.kind===`FormalParam`||kr(n)!==kr(t)||Hn(n)!==Hn(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(r&&i.version===`1.7.4`)?o(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):r?o(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${kn(n.location)}.`):jr(t,n)||s(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${kn(n.location)}.`)};i.version!==`1.7.4`&&Dn(l);let f=Dn(l);l();let p=new Map(f.map(e=>[e.name,e])),m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=(n,r)=>{let a=n===i.rootFileName&&i.rootFilePath||`${n}.tla`,o=t=>new e.M(`Could not parse module ${n} from file ${a}`,n,t),s=i.version===`1.7.4`?t.en(r):void 0;if(s!==void 0)throw o(s);try{return t.H(vr(r))}catch(n){throw n instanceof e.F?o(t.W(r)??`***Parse Error***\n${n.message}`):n}},_=(t,n,r)=>{let a=h.get(t);if(a)return a;if(n===void 0)throw new e.D(t,r,i.version!==`1.7.4`);i.onParse?.(t);let o=g(t,n);if(o.name!==t)throw new e.M(`File name '${t}' does not match the name '${o.name}' of the top level module it contains.`,void 0);let s={file:sr(o.name,n),module:o};return h.set(t,s),s},v=[],y=/* @__PURE__ */ new Set,b=[],x=(t,n,i)=>{let a=b.indexOf(t);if(a!==-1)throw new e.M(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...b.slice(a),t].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(y.has(t))return;y.add(t),b.push(t);let o=D(t,_(t,n,i).module);[...o.extendees,...o.instancees].forEach(e=>x(e,r(e),t)),b.pop(),v.push(t)},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=D(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=e=>{_(e,n);let t=()=>w(e,`extendees`,/* @__PURE__ */ new Set)??w(e,`instancees`,/* @__PURE__ */ new Set);for(let e=t();e!==void 0;e=t())h.has(e.name)||_(e.name,r(e.name),e.namingModule),S.add(`${e.importer} ${e.name}`)},E=i.rootFileName??g(``,n).name,D=(e,t)=>{let n=Rr(t);return e!==E||i.rootExtendees===void 0||(n.extendees.splice(t.extends.length,0,...i.rootExtendees),i.rootExtendees.forEach(t=>{n.importers.has(t)||n.importers.set(t,e)})),n};T(E),x(E,n);let O=(t,n,r,a)=>{let c={curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSectionCount:0},f=[],h=[],g=[],_=[],v=/* @__PURE__ */ new WeakSet,y=()=>_.push({labels:/* @__PURE__ */ new Map,params:[]}),b=()=>_.pop()?.labels??/* @__PURE__ */ new Map,x={depth:0,isDeclared:[],goal:void 0,goalClause:0},S=/* @__PURE__ */ new WeakMap,C=/* @__PURE__ */ new WeakMap,w=e=>{let t=e.kind===`AssumeProve`?S.get(e):void 0;t&&(t.isInProof=!1)},T=e=>q(n,K(n,e)),E=e=>e.range?fr(n,e.range):{start:lr(n,e),end:lr(n,e)},D={kind:`Module`,id:l(),name:t.name,location:q(n,E(t.location)),extendees:[],context:Dr(a),topLevel:[],definitions:[],opDefsInRecursiveSection:[],isLevelChecked:!1,levelCorrect:!0,argLevelParams:/* @__PURE__ */ new Map,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map,records:[]};r&&r.definitions.push(D);let k=e=>{for(let t=a.contexts.length-1;t>=0;t--){let n=Wn(a.contexts[t],e);if(n?.kind===`Module`)return n}return m.get(e)},A=t=>{let n=k(t);if(n===void 0)throw new e.F(`Could not find module ${t}`);return n},j=(e,t)=>{a.contexts.push(e);let n=t();return a.contexts.pop(),n},M=(e,t,n,r)=>{let i={...W(l()),kind:`FormalParam`,name:e,arity:t,location:n};return r&&d(a,i),i},N=e=>({...W(l()),kind:`OpDef`,defKind:`UserDefined`,arity:e.params?.length??0,params:[],body:void 0,isLocal:!1,module:D,source:void 0,preComments:[],isDefined:!0,inRecursive:!1,inRecursiveSection:!1,recursiveSection:-1,letInLevel:0,weights:(e.params??[]).map(()=>0),isLeibnizArg:(e.params??[]).map(()=>!0),isLeibniz:!0,opLevelCond:void 0,maxLevels:(e.params??[]).map(()=>3),minMaxLevel:void 0,labels:/* @__PURE__ */ new Map,step:void 0,...e}),ee=e=>{e.letInLevel=c.curLevel,c.unresolvedSum>0&&(e.recursiveSection=c.recursiveSectionCount,e.inRecursiveSection=c.unresolvedCount[c.curLevel]>0,D.opDefsInRecursiveSection.push(e))},P=(e,t,n,r={},i=l())=>({...W(i),kind:`OpAppl`,operator:e,operands:t,unbounded:r.unbounded,bounded:r.bounded,tupleOrs:r.tupleOrs,ranges:r.ranges??[],location:n}),F=()=>({...P(I(`$Nop`),[],En,{},u),isNull:!0}),I=t=>{let n=p.get(t);if(!n)throw new e.B(`SANY has no builtin operator ${t}`);return n},L=(e,t,n,r={})=>P(I(e),t,n,r),te=(e,t)=>({...W(l()),kind:`String`,value:e,location:t}),ne=(e,t)=>({...W(l()),kind:`OpArg`,op:e,location:t}),re=(t,n)=>{let r=Or(a,Cr(t));if(r===void 0||r.kind===`Module`)throw new e.F(`Unknown operator: \`${t}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},ie=(e,t,n)=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`)return;let r=e.params??[];r.length===t.length?r.forEach((r,i)=>{let a=t[i];r.arity===0&&a.kind===`OpArg`&&o(n,`Operator used in argument number ${i+1} has incorrect number of arguments.`);let s=a.kind===`OpArg`&&Hn(a.op)===r.arity&&!(a.op.kind===`OpDef`&&(a.op.params??[]).some(e=>e.arity>0));r.arity>0&&!s&&o(n,`Argument number ${i+1} to operator '${e.name}' \nshould be a ${r.arity}-parameter operator.`)}):o(n,`Wrong number of arguments (${t.length}) given to operator '${e.name}', \nwhich requires ${r.length} arguments.`)},ae=ir({version:i.version,resolveSymbol:e=>Or(a,e),resolveSynonym:Cr,generateExpression:e=>B(e),generateArgument:(e,t,n,r)=>he(e,t,n,r),createOpAppl:(e,t,n)=>{let r=P(e,t,n);return ie(e,t,n),r},createOpArg:ne,createFormalParam:(e,t,n)=>M(e,t,n,!1),createLambda:(e,t,r)=>N({name:`LAMBDA`,params:e,body:t,location:r,preComments:yr(n,lr(n,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>V(`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:I,addError:(e,t)=>(o(e,t),F()),isOutOfLabelScope:e=>{let t=C.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=S.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}}),R=(e,t)=>{let r=t.start;return e.map(e=>{let i=e.op===`Name`?e.name:e.op===`Null`?`(`:String(e.op),a=xr(n,r,t.end,i);if(a===-1)return e;if(e.op===`Null`){let t=dr(n,a);return r=t+1,{...e,location:q(n,{start:a,end:t})}}r=a+1;let o=J(n,a);if(e.args===void 0||!G(n,a+1,`(`))return{...e,location:o};let s=dr(n,a+1);return r=s+1,{...e,location:o,argsLocation:q(n,{start:a+1,end:s})}})},z=(t,r,i,a)=>{let o=Xn(t);if(o===void 0)throw new e.F(`Expected a name, found ${t.kind}`);return ae(R(o,K(n,t)),r,i,a,T(t))},oe=t=>{let n=z(t,0,!1,!1);if(n.kind!==`OpAppl`)throw new e.F(`Expected an expression`);return n},se=e=>{if(e.kind!==`OpAppl`)return;let t=f.find(t=>t.name===e.operator.name);t&&(t.node.operator=I(`$RecursiveFcnSpec`))},ce=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},[]),le=(e,t)=>Oe(e,t,ce(e).map(e=>B(e[0].set))),ue=(e,t)=>{let n=_.at(-1);n?.params.push(e);let r=B(t);return n?.params.pop(),r},de=(e,t,n,r,i)=>j(zn(),()=>{let a=le(t,n),o=ue(a.bounded.flat(),r);return L(e,[o],i,a)}),fe=e=>{let t=K(n,e),r=br(n,t.start,t.end,e.params);return j(zn(),()=>{let i=e.params.map((e,t)=>M(e,0,J(n,r[t]),!0)),a=ue(i,e.body);return N({name:`LAMBDA`,params:i,body:a,location:q(n,t),preComments:yr(n,t.start)})})},pe=e=>e.kind===`OperatorReference`?e.operator:e.kind===`Lambda`&&e.body.kind===`Apply`?e.body.operator:n.tokens[lr(n,e.location)].text,me=(t,n)=>{let r=T(t);if(t.kind===`Lambda`)return t.location.range!==void 0&&t.operator===void 0?ne(fe(t),r):ne(re(pe(t),r),r);if(!Br(t))return o(r,`Arity ${n.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${n.name}'.`),F();if(t.kind===`OperatorReference`)return ne(re(t.operator,r),r);let i=z(t,n.arity,!1,!1);if(i.kind===`OpArg`||i.kind===`OpAppl`&&i.isNull===!0)return i;throw new e.F(`Expected an operator argument at line ${r.beginLine}, column ${r.beginColumn}`)},he=(t,r,i,s)=>{let c=t.kind===`OpDef`&&(t.defKind===`UserDefined`||t.defKind===`ModuleInstance`)?t.params?.[r]?.arity??0:0;if(c===0)return B(i);let l=K(n,i),u=q(n,l),d=`${r+1} (counting from 1)`,f=mr(n,l);if(f!==l||!Br(i))return o(q(n,f),`An expression appears as argument number ${d} to operator '${t.name}', in a position an operator is required.`),F();if(i.kind===`Identifier`||i.kind===`Subexpression`||i.kind===`Apply`){let t=z(i,c,!1,!1);if(t.kind===`OpArg`||t.kind===`OpAppl`)return t;throw new e.F(`Expected an operator argument at ${kn(u)}`)}if(i.kind===`Lambda`&&i.location.range!==void 0&&i.operator===void 0){let e=fe(i),n=Hn(e);return n===c?ne(e,u):(o(s,`Lambda expression with arity ${n} used as argument ${r+1} of operator \`${t.name}', \nbut an operator of arity ${c} is required.`),F())}let p=pe(i),m=Or(a,Cr(p));if(m===void 0)return o(u,`Could not find declaration or definition of symbol '${p}'.`),F();let h=Hn(m);return h===c?ne(m,u):(o(s,`Operator with incorrect arity passed as argument. \nOperator '${m.name}' of arity ${h} is argument number ${d} to operator \`${kn(t.location)}', \nbut an operator of arity ${c} was expected.`),F())},ge=e=>{let t=T(e);if(e.isBulleted)return L(e.kind===`And`?`$ConjList`:`$DisjList`,e.operands.map(B),t);let r=K(n,e),i=e.kind===`And`?`\\land`:`\\lor`,[a,...o]=e.operands;return o.reduce((e,t,a)=>{let s=pr(n,K(n,t)),c=a===o.length-1?r.end:s.end;return L(i,[e,B(t)],q(n,{start:r.start,end:c}))},B(a))},_e=e=>{let t=K(n,e),r=e.arms.map((r,i)=>{let a=pr(n,K(n,r.condition)),o=i===e.arms.length-1&&e.other===void 0,s=pr(n,K(n,r.body)),c=[B(r.condition),B(r.body)];return L(`$Pair`,c,q(n,{start:a.start,end:o?t.end:s.end}))}),i=e.other;if(i){let e=pr(n,K(n,i)),a=ve(e.start,`OTHER`);r.push(L(`$Pair`,[void 0,B(i)],q(n,{start:a,end:t.end})))}return L(`$Case`,r,q(n,t))},ve=(e,t)=>{for(let r=e;r>=0;r--)if(G(n,r,t))return r;return e},ye=e=>{let t=K(n,e),r=q(n,t),i=[B(e.function)],a=L(`$Except`,i,r),o=K(n,e.function),s=xr(n,o.end+1,t.end,`EXCEPT`)+1;return e.updates.forEach(e=>{let r=xr(n,s,t.end,`!`),o=pr(n,K(n,e.value)),c=q(n,{start:r,end:o.end}),l=r+1,u=e.path.map(e=>{if(e.kind===`Field`){let t=be(l,e.name);return l=t+1,te(e.name,J(n,t))}let r=xr(n,l,t.end,`[`),i=dr(n,r);return l=i+1,e.args.length===1?B(e.args[0]):L(`$Tuple`,e.args.map(B),q(n,{start:r,end:i}))}),d=L(`$Seq`,u,c),f=L(`$Pair`,[d],c);g.push(f),h.push(a),f.operands.push(B(e.value)),g.pop(),h.pop(),i.push(f),s=o.end+1}),a},be=(e,t)=>{for(let r=e;r<n.tokens.length;r++)if(n.tokens[r].text===t&&n.tokens[r].kind!==`String`)return r;return e},xe=(e,t)=>{let r=K(n,t),i=r.start+1,a=t.fields.map((e,r)=>{let a=be(i,e.name),s=pr(n,K(n,e.value));return i=s.end+1,t.fields.slice(0,r).some(t=>t.name===e.name)&&o(J(n,a),`Non-unique fields in constructor.`),L(`$Pair`,[te(e.name,J(n,a)),B(e.value)],q(n,{start:a,end:s.end}))}),s=L(e,a,q(n,r));return D.records.push(s),s},Se=e=>({line:n.tokens[e].line,column:n.tokens[e].column}),Ce=e=>{let t=[],r=e;for(;n.tokens[r]?.kind===`Identifier`;){let e=G(n,r+1,`(`)?dr(n,r+1):r,i=n.tokens.slice(r+1,e).filter(e=>e.text===`_`).length;if(t.push({name:n.tokens[r].text,arity:i,location:{...Se(r),range:{module:n.name,start:Se(r),end:Se(e)}}}),!G(n,e+1,`,`))break;r=e+2}return t},we=e=>{let t=[...e.definitions.map(e=>({unit:{kind:`Definition`,definition:e},span:je(e)})),...(e.instances??[]).map(e=>({unit:{kind:`Instance`,instance:e},span:je(e)}))],r=K(n,e).start,i=pr(n,K(n,e.body)).start,a=[];for(let e=r+1;e<i;e++){let r=t.some(t=>t.span.start<=e&&e<=t.span.end);G(n,e,`RECURSIVE`)&&!r&&a.push({unit:{kind:`Recursive`,declarations:Ce(e+1)},span:{start:e,end:e}})}return[...t,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},Te=e=>{let t=zn();return j(t,()=>{c.curLevel++,c.unresolvedCount[c.curLevel]=0;let n=[],r=[];we(e).forEach(e=>{e.kind===`Recursive`?Ie(e.declarations):e.kind===`Instance`?ze(e.instance,n,r):e.definition.kind===`Function`?Pe(e.definition,n):Me(e.definition,n)}),Le(),c.curLevel=Math.max(c.curLevel-1,0);let i=B(e.body);return{...W(l()),kind:`LetIn`,opDefs:n,instances:r,body:i,context:t,location:T(e)}})},Ee=e=>{let t=K(n,e),r=q(n,t);return j(zn(),()=>{let i=e.pattern,a=i.kind===`Name`?[i.name]:i.names;if(e.set===void 0){let o=br(n,t.start,t.end,a),s=a.map((e,r)=>M(e,0,J(n,i.kind===`Name`?t.start:o[r]),!0)),c=ue(s,e.body);return L(`$UnboundedChoose`,[c],r,{unbounded:s})}let o=B(e.set),s=K(n,e.set),c=br(n,t.start,s.start,a),l=a.map((e,t)=>M(e,0,J(n,c[t]),!0)),u=ue(l,e.body);return L(`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},De=e=>{if(Tr(e.operator)||Er(e.operator)||e.args.length>2||Or(a,Cr(e.operator))!==void 0)return;let t=K(n,e);if(n.tokens[t.start].text===e.operator&&G(n,t.start+1,`(`))return;let r=pr(n,K(n,e.args[0])),i=e.args.length===1&&r.start!==t.start,o=i?t.start:r.end+1,s=gr(n,o);return{index:o,name:i&&s===`-`?`-.`:s,fixity:i?`prefix`:e.args.length===2?`infix`:`postfix`}},B=e=>{let t=T(e);switch(e.kind){case`Number`:return{...W(l()),kind:`Numeral`,value:Lr(e.text??String(e.value)),location:t};case`Decimal`:{let[n,r]=e.text.split(`.`),i=BigInt(n+r),a=i<=9223372036854775807n;return{...W(l()),kind:`Decimal`,mantissa:i.toString(),exponent:String(a?-r.length:r.length),integralPart:n,fractionalPart:r,location:t}}case`String`:return te(e.value,t);case`Identifier`:{let t=oe(e);return se(t),t}case`Apply`:{let r=De(e);if(r!==void 0)return o(J(n,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),o(t,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...F(),isAbsent:!0};let i=oe(e);return(Er(e.operator)||Tr(e.operator))&&se(i),i}case`Bracket`:return o(J(n,K(n,e).start),"Unsupported expression type `['."),{...F(),isAbsent:!0};case`OperatorReference`:case`Lambda`:{let r=n.tokens[K(n,e).start].text;return o(t,r===`LAMBDA`?`LAMBDA expression used where an expression is required.`:`Unsupported expression type \`${Wr(e,r)}'.`),{...F(),isAbsent:!0}}case`And`:case`Or`:return ge(e);case`Prime`:return L(`'`,[B(e.expression)],t);case`Unchanged`:return L(`UNCHANGED`,[B(e.expression)],t);case`Enabled`:return L(`ENABLED`,[B(e.expression)],t);case`Always`:return L(`[]`,[B(e.expression)],t);case`Eventually`:return L(`<>`,[B(e.expression)],t);case`If`:return L(`$IfThenElse`,[B(e.condition),B(e.consequent),B(e.alternative)],t);case`Case`:return _e(e);case`Let`:return Te(e);case`Forall`:case`Exists`:return de(e.kind===`Forall`?`$BoundedForall`:`$BoundedExists`,e.bounds,K(n,e).start,e.body,t);case`UnboundedQuantifier`:{let r=K(n,e),i=K(n,e.body),a=br(n,r.start,i.start,e.names),o=e.isTemporal?e.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:e.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return j(zn(),()=>{let r=e.names.map((e,t)=>M(e,0,J(n,a[t]),!0)),i=ue(r,e.body);return L(o,[i],t,{unbounded:r})})}case`Choose`:return Ee(e);case`SetEnumeration`:return L(`$SetEnumerate`,e.elements.map(B),t);case`Tuple`:return L(`$Tuple`,e.elements.map(B),t);case`SetFilter`:{let r=B(e.bound.set),i=K(n,e);return j(zn(),()=>{let n=Oe([e.bound],i.start,[r]),a=ue(n.bounded.flat(),e.predicate);return L(`$SubsetOf`,[a],t,n)})}case`SetMap`:return de(`$SetOfAll`,e.bounds,K(n,e.expression).end+1,e.expression,t);case`FunctionConstruction`:return de(`$FcnConstructor`,e.bounds,K(n,e).start,e.body,t);case`FunctionSet`:return L(`$SetOfFcns`,[B(e.domain),B(e.range)],t);case`Record`:return xe(`$RcdConstructor`,e);case`RecordSet`:return xe(`$SetOfRcds`,e);case`Except`:return ye(e);case`ExceptAt`:{let e=h[h.length-1],n=g[g.length-1];return e===void 0||n===void 0?(o(t,`@ used where its meaning is not defined.`),F()):{...W(l()),kind:`At`,except:e,component:n,location:n.location}}case`FunctionApplication`:{let n=B(e.function);if(An(n))return n;se(n);let r=n.kind===`OpAppl`?n.operator:void 0,i=r?.kind===`OpDef`&&r.defKind===`UserDefined`?r.body:void 0;if(i?.kind===`OpAppl`&&(i.operator.name===`$NonRecursiveFcnSpec`||i.operator.name===`$RecursiveFcnSpec`)){let n=(i.bounded??[]).reduce((e,t,n)=>e+(i.tupleOrs?.[n]?1:t.length),0);if(e.args.length>=2&&n!==e.args.length)return o(t,`Function '${r?.name}' is defined with ${n} parameters, but is applied to ${e.args.length} arguments.`),F()}let a=e.args.length===1?B(e.args[0]):L(`$Tuple`,e.args.map(B),t);return L(`$FcnApply`,[n,a],t)}case`FieldAccess`:{let r=B(e.record),i=K(n,e);return L(`$RcdSelect`,[r,te(e.field,J(n,i.end))],t)}case`Product`:return L(`$CartesianProd`,e.factors.map(B),t);case`BoxAction`:case`AngleAction`:return L(e.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[B(e.action),B(e.subscript)],t);case`WeakFairness`:case`StrongFairness`:return L(e.kind===`WeakFairness`?`$WF`:`$SF`,[B(e.subscript),B(e.action)],t);case`Label`:return ke(e);case`Subexpression`:return oe(e)}},Oe=(e,t,r)=>{let i=ce(e),a=t;return{bounded:i.map(e=>{let t=K(n,e[0].set),r=e.flatMap(e=>e.pattern.kind===`Name`?[e.pattern.name]:e.pattern.names),i=br(n,a,t.start,r);return a=t.end+1,r.map((e,t)=>M(e,0,J(n,i[t]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},ke=e=>{let t=T(e),r=_.at(-1);if(r===void 0)return o(t,`Label not in definition or proof step.`),F();if(x.isDeclared.slice(2,x.depth+1).some(Boolean))return o(t,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),F();if(h.length>0&&g.length>0)return o(t,`Labels inside EXCEPT clauses are not yet implemented.`),F();y();let i=B(e.body),s=b(),c=br(n,K(n,e).start,K(n,e.body).start,e.params),u=e.params.map((t,r)=>{let i=Or(a,t);if(i?.kind===`FormalParam`)return i;let s=J(n,c[r]);return o(s,`Illegal parameter ${t} of label \`${e.name}'.`),M(t,0,s,!1)}),d={...W(l()),kind:`Label`,name:e.name,params:u,body:i,labels:s,isAssumeProve:!1,location:t},f=/* @__PURE__ */ new Set;if(u.forEach(e=>{f.has(e)&&o(t,`Repeated formal parameter ${e.name} \nin label \`${d.name}'.`),f.add(e)}),r.params.flat().forEach(e=>{f.delete(e)||o(t,`Label ${d.name} must contain formal parameter \`${e.name}'.`)}),f.size>0){let e=[...f].map(e=>`${e.name} `).join(``);o(t,`Label ${d.name} declares extra parameter(s) ${e}`)}r.labels.has(d.name)?o(t,`Duplicate label \`${d.name}'.`):r.labels.set(d.name,d);let p=x.goal;return p&&C.set(d,{scope:p,clause:x.goalClause}),d},Ae=(e,t,r)=>{let i=t.start;return e.params.map(e=>{let t=e.location?lr(n,e.location):be(i,e.name),a=ct(t,e.arity);i=a.end+1;let o=e.arity===1&&G(n,t+1,`_`);return M(o?n.tokens[t].spelling??e.name:Cr(e.name),e.arity,q(n,a),r)})},je=e=>{let t=E(e.location);return e.isLocal&&!G(n,t.start,`LOCAL`)&&G(n,t.start-1,`LOCAL`)?{start:t.start-1,end:t.end}:t},Me=(e,t)=>{let r=je(e),i=q(n,r),s=Cr(e.name),l={start:e.isLocal?r.start+1:r.start,end:r.end},u=j(zn(),()=>{let t=Ae(e,l,!0),n=Or(a,s);if(n?.kind===`OpDef`&&n.inRecursive&&!n.isDefined){let e=n.params?.length===t.length&&t.every(e=>e.arity===0);n.letInLevel===c.curLevel?(e||o(i,`Definition of ${n.name} has different arity than its RECURSIVE declaration.`),n.params=t):o(i,`Recursive operator ${s} defined at wrong LET/IN level.`)}else n!==void 0&&o(i,`Operator ${s} already defined or declared.`);return y(),{params:t,body:B(e.body),existing:n}}),f=b(),p=u.existing,m=u.params,h=yr(n,r.start);if(p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined&&p.letInLevel===c.curLevel){p.weights=m.map(()=>0),p.maxLevels=m.map(()=>3),p.isLeibnizArg=m.map(()=>!0),p.labels=f,Ne(p,u.body,i,h),D.definitions.push(p),t?.push(p);return}let g=N({name:s,params:m,body:u.body,isLocal:e.isLocal,location:i,preComments:h,labels:f});d(a,g),ee(g),D.definitions.push(g),t?.push(g)},Ne=(e,t,n,r)=>{e.isDefined=!0,e.body=t,e.location=n,e.preComments=r,e.inRecursive&&(c.unresolvedCount[c.curLevel]--,c.unresolvedSum--)},Pe=(e,t)=>{let r=je(e),i=q(n,r),s=zn(),l=e.isLocal?r.start+1:r.start,u=j(s,()=>le(e.bounds,l+1)),p=j(s,()=>Or(a,e.name)),m=j(s,()=>M(e.name,0,i,p===void 0)),h=L(`$NonRecursiveFcnSpec`,[],i,{unbounded:[m],...u}),g=p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined,_=g&&p.letInLevel===c.curLevel;_?p.arity!==0&&o(i,`Function ${p.name} has operator arguments in its RECURSIVE declaration.`):g?o(i,`Recursive function ${e.name} defined at wrong LET/IN level.`):p!==void 0&&o(i,`Function name \`${e.name}' already defined or declared.`);let v=yr(n,r.start),x=p===void 0?N({name:e.name,params:[],body:h,isLocal:e.isLocal,location:i,preComments:v}):p.kind===`OpDef`&&(_||!g)?p:void 0;_?p.arity===0&&Ne(p,h,i,v):p===void 0&&x!==void 0&&(d(a,x),ee(x)),x!==void 0&&(D.definitions.push(x),t?.push(x)),f.unshift({name:e.name,node:h}),y();let S=()=>ue(u.bounded.flat(),e.body),C=x===void 0?S():j(s,S),w=b();x!==void 0&&(x.labels=w),f.shift(),h.operands=[C],h.operator.name===`$NonRecursiveFcnSpec`&&(h.unbounded=void 0)},Fe=[],Ie=e=>{c.unresolvedSum===0&&c.recursiveSectionCount++,c.unresolvedCount[c.curLevel]+=e.length,c.unresolvedSum+=e.length,e.forEach(e=>{let t=lt(e);l();let r=Array.from({length:e.arity},()=>M(``,0,void 0,!1)),i=N({name:Cr(e.name),params:r,location:q(n,t),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:c.recursiveSectionCount,letInLevel:c.curLevel});d(a,i),Fe.push(i),D.opDefsInRecursiveSection.push(i)})},Le=()=>{c.unresolvedCount[c.curLevel]!==0&&(Fe.filter(e=>e.letInLevel===c.curLevel&&!e.isDefined).forEach(e=>o(e.location,`Symbol ${e.name} declared in RECURSIVE statement but not defined.`)),c.unresolvedSum-=c.unresolvedCount[c.curLevel])},Re=(e,t,r)=>{l();let s=Ln(t.table).filter(e=>e.kind===`OpDecl`),c=s.flatMap(e=>{let t=Or(a,e.name);if(t===void 0)return[];let n=e.declKind===3||e.declKind===2&&e.arity===0;return n&&ie(t,[],r),[{op:e,expr:n?P(t,[],r):ne(t,r),isImplicit:!0}]}),u=(e,t)=>{(t.kind===`OpArg`?Hn(t.op):0)!==e.arity&&o(t.location,`An operator must be substituted for symbol '${e.name}', and it must have arity ${e.arity}.`)},d=je(e),f=xr(n,d.start,d.end,`WITH`)+1;return e.substitutions.forEach(e=>{let i=xr(n,f,d.end,e.name);i!==-1&&(f=K(n,e.expression).end+1);let a=Un(t,Cr(e.name));if(a?.kind!==`OpDecl`){o(i===-1?r:J(n,i),`Identifier '${i===-1?e.name:gr(n,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 s=a.arity===0?B(e.expression):me(e.expression,a);u(a,s);let l=c.find(e=>e.op.name===a.name);l&&!l.isImplicit?o(T(e.expression),`Multiple substitutions for symbol '${a.name}' in substitution.`):l?(l.expr=s,l.isImplicit=!1):c.push({op:a,expr:s,isImplicit:!1})}),c.filter(e=>e.isImplicit&&i.version!==`1.7.4`).forEach(e=>u(e.op,e.expr)),s.filter(e=>!c.some(t=>t.op.name===e.name)).forEach(e=>o(r,`Substitution missing for symbol ${e.name} declared at ${kn(e.location)} \nand instantiated in module ${D.name}.`)),c},V=(e,t,n,r,i,a=D)=>(An(n)&&o(i,e===`SubstIn`?`Substitution error, probably due to error
|
|
34
|
-
in module being instantiated.`:`Substitution error, probably due to error in module being instantiated.`),{...W(l()),kind:e,substs:t,body:n,instantiatingModule:a,instantiatedModule:r,location:i}),ze=(e,t,r)=>{let o=je(e),s=q(n,o),c=
|
|
35
|
-
the name of a theorem, assumption, or step.`)),{...W(l()),kind:`UseOrHide`,facts:r,defs:i,isOnly:e.isOnly,isHide:e.kind===`Hide`,location:t}},$e=e=>{let t=E(e.location),r=e.set&&B(e.set),i=be(t.start,e.name),o=wr[e.level],s={...W(l()),levelChecked:1,level:o.level,kind:`OpDecl`,name:Cr(e.name),arity:e.arity,declKind:o.declKind,location:q(n,ct(i,e.arity)),module:D};return d(a,s),{...W(l()),kind:`NewSymb`,declaration:s,set:r,location:q(n,t)}},et=(e,t,r)=>{let i=E(e.location),s=_r(n,i.start-1),c=K(n,e.conclusion).start,u=n.tokens.findLastIndex((e,t)=>t<c&&e.kind===`Keyword`&&e.text===`PROVE`),d=q(n,{start:s?i.start-1:i.start,end:i.start});s!==_r(n,u-1)&&o(d,s?`[]ASSUME matched by PROVE instead of []PROVE`:`ASSUME matched by []PROVE instead of PROVE`);let f=l();t>1&&a.contexts.push(zn()),s&&a.contexts.some(e=>v.has(e))&&o(d,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),s||v.add(Dr(a));let p={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};x.depth=t,x.isDeclared[t]=!1,t===1&&(x.goal=r&&p,x.goalClause=0);let m=e.assumptions.map((e,n)=>{let r=e.kind===`NewSymbol`,i=e.kind===`AssumeProve`?et(e,t+1):r?$e(e):B(e);return x.depth=t,r&&(x.isDeclared[t]=!0),p.isDeclaredBefore.push(p.isDeclaredBefore[n]||r),t===1&&x.goalClause++,i}),h=B(e.conclusion);t>1&&a.contexts.pop(),x.depth=t-1,t===1&&(x.goal=void 0);let g={...W(f),kind:`AssumeProve`,assumptions:m,goal:h,isSuffices:p.isSuffices,isBoxed:s,location:q(n,{start:s?i.start-1:i.start,end:i.end})};return S.set(g,p),g},tt=(e,t,n,r,i,a=!0)=>({...W(e),kind:`ThmOrAssumpDef`,name:t,isTheorem:a,body:n,params:[],isLocal:!1,location:r,module:D,source:void 0,labels:i,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]}),nt=e=>{let t=q(n,E(e.location));e.kind===`By`&&Ze(e,t);let r=e.kind===`By`?He(e.facts):[],i=e.kind===`By`?Xe(e.defs):[];return e.kind===`By`&&l(),e.kind===`By`&&r.length+i.length===0&&o(t,`Empty BY`),{...W(l()),kind:`LeafProof`,facts:r,defs:i,isOmitted:e.kind===`Omitted`,isOnly:e.kind===`By`&&e.isOnly,location:t}},rt=(e,t)=>{let r=e.body,i=q(n,t);switch(r.kind){case`Have`:return{node:L(`$Have`,[B(r.expression)],i),isPick:!1};case`Case`:return{node:L(`$Pfcase`,[B(r.expression)],i),isPick:!1};case`Witness`:return{node:L(`$Witness`,r.expressions.map(B),i),isPick:!1};case`Qed`:return{node:L(`$Qed`,[],i),isPick:!1};case`Take`:case`Pick`:{let e=r.kind===`Pick`,o=e?`$Pick`:`$Take`;e&&a.contexts.push(zn());let s=e=>r.kind===`Pick`?[ue(e,r.body)]:[];if(r.bounds.length>0){let n=le(r.bounds,t.start),a=s(n.bounded.flat());return{node:L(o,a,i,n),isPick:e}}let c=br(n,t.start,t.end+1,r.names),l=r.names.map((e,t)=>M(e,0,J(n,c[t]),!0)),u=s(l);return{node:L(o,u,i,{unbounded:l}),isPick:e}}}},it=e=>{if((e.kind===`And`||e.kind===`Or`)&&!e.isBulleted)return!0;if(e.kind!==`Apply`||e.args.length!==2)return!1;let t=pr(n,K(n,e.args[0])),r=K(n,e).start;return t.start===r&&!G(n,t.end+1,`(`)},at=t=>{if(t.kind!==`Steps`)return nt(t);let r=zn();a.contexts.push(r);let i=[],s=[],c,u=(t,r,a)=>{if(t.kind===`Define`){let r=t.definitions.map(t=>{let n=[];t.kind===`Instance`?ze(t,n,i):t.kind===`Function`?Pe(t,n):Me(t,n);let r=n[t.kind===`Instance`?n.length-1:0];if(r?.kind!==`OpDef`)throw new e.F(`A DEFINE step defines no operator`);return r});return{...W(l()),kind:`DefStep`,defs:r,location:q(n,a)}}if(t.kind===`Use`||t.kind===`Hide`)return{...Qe(t),location:q(n,r)};if(t.kind===`Instance`)return Be(t,!1,q(n,a))},f=t.steps.map(t=>{let r=E(t.location),i=fr(n,t.head),f={start:i.start+1,end:i.end},p=t.body;t.name!==void 0&&/^<[*+]>/.test(t.token)&&o(J(n,r.start),`<*> and <+> cannot be used for a named step.`),t.name!==void 0&&y();let m=t.name===void 0?void 0:l();p.kind!==`Assert`&&(c=void 0);let h=u(p,r,f);if(h!==void 0)return t.name!==void 0&&d(a,N({defKind:`NumberedProofStep`,name:t.name,location:q(n,r),labels:b(),step:h})),h;let g=p.kind===`Assert`&&p.statement.kind===`AssumeProve`;g&&(c=void 0);let _=p.kind===`Assert`&&p.isSuffices,v=zn(),x=p.kind===`Assert`?{node:(e=>{if(e.kind===`AssumeProve`){let n=j(v,()=>et(e,1,t.name===void 0?void 0:{isSuffices:_}));return n.isSuffices=_,n}if(_){let t=B(e);return L(`$Suffices`,[t],q(n,f))}let r=c!==void 0&&e.kind===`Apply`&&it(e)&&e.args[0].kind===`ExceptAt`,i=r?B(e.args[1]):void 0,a=r?P(re(e.operator,T(e)),[L(`$Nop`,[c],T(e.args[0])),i],T(e)):B(e),o=a.kind===`OpAppl`?a.operands[1]:void 0;return c=it(e)?o:void 0,a})(p.statement),isPick:!1}:rt(t,f);if(x===void 0)throw new e.F(`Unexpected proof step ${p.kind}`);let S=x.isPick?a.contexts.pop():void 0,C=t.name===void 0||m===void 0?void 0:tt(m,t.name,x.node,J(n,lr(n,t.location)),b());C&&d(a,C);let D=g&&!_;D&&a.contexts.push(v);let O=t.proof&&at(t.proof);return D&&a.contexts.pop(),w(x.node),g&&_&&(s.push(v),a.contexts.push(v)),S?.symbols.forEach(e=>d(a,e)),{...W(l()),kind:`Theorem`,definition:C,body:x.node,proof:O,isSuffices:_,location:q(n,r)}});return s.forEach(()=>{a.contexts.pop()?.symbols.forEach(e=>Vn(r,e))}),a.contexts.pop(),{...W(l()),kind:`NonLeafProof`,steps:f,instances:i,proofLevel:t.level,location:q(n,E(t.location))}},ot=e=>{let t=q(n,E(e.location)),r=e.statement,i=zn();e.name!==void 0&&y();let o=e.name===void 0?void 0:l();r.kind===`AssumeProve`&&a.contexts.push(i);let s=r.kind===`AssumeProve`?et(r,1,e.name===void 0?void 0:{isSuffices:!1}):B(r),c=e.name===void 0||o===void 0?void 0:tt(o,e.name,s,t,b());c&&(r.kind===`AssumeProve`&&a.contexts.pop(),d(a,c),D.definitions.push(c),r.kind===`AssumeProve`&&a.contexts.push(i));let u=e.proof&&at(e.proof);r.kind===`AssumeProve`&&a.contexts.pop(),w(s);let f={...W(l()),kind:`Theorem`,definition:c,body:s,proof:u,isSuffices:!1,location:t};D.topLevel.push(f)},st=e=>{let t=E(e.location),r=q(n,t);e.name!==void 0&&y();let i=B(e.expression),o=e.name===void 0?void 0:tt(l(),e.name,i,r,b(),!1);o&&(d(a,o),D.definitions.push(o));let s={...W(l()),kind:`Assume`,definition:o,body:i,location:r};D.topLevel.push(s)},ct=(e,t)=>t===0?{start:e,end:e}:G(n,e,`_`)?{start:e,end:G(n,e+2,`_`)?e+2:e+1}:G(n,e+1,`(`)?{start:e,end:dr(n,e+1)}:{start:e,end:G(n,e+1,`_`)?e+1:e},lt=e=>ct(E(e.location).start,e.arity),ut=(e,t)=>{let r=lt(e);e.name===`@`&&t===3&&o(q(n,r),`Attempted to declare '@' as a variable.`);let i={...W(l()),levelChecked:1,level:+(t===3),kind:`OpDecl`,name:Cr(e.name),arity:e.arity,declKind:t,location:q(n,r),module:D};return t===2&&(i.levelParams.add(i),i.allParams.add(i)),d(a,i),i};t.extends.forEach(e=>{let t=A(e);D.extendees.push(t);let n=Dr(a);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?Wn(n,e.name):Un(n,e.name);t===void 0?Vn(n,e):t!==e&&t.kind!==e.kind?o(e.location,`The ${Ar(e)} of '${e.name}' conflicts with \nits ${Ar(t)} at ${kn(t.location)}.`):t!==e&&!jr(t,e)&&s(e.location,`Warning: the ${Ar(t)} of '${e.name}' conflicts with \nits ${Ar(t)} at ${kn(t.location)}.`)}),D.topLevel.push(...t.topLevel)});let dt=(e,t)=>{c.unresolvedSum!==0&&o(q(n,E(e)),`${t} may not appear within a recursive definition section.`)};return t.units.forEach(e=>{switch(e.kind){case`Variables`:dt(e.location,`A VARIABLE declaration`),e.declarations.forEach(e=>ut(e,3));break;case`Constants`:dt(e.location,`A declaration`),e.declarations.forEach(e=>ut(e,2));break;case`Recursive`:Ie(e.declarations);break;case`Definition`:e.definition.kind===`Function`?Pe(e.definition,void 0):Me(e.definition,void 0);break;case`Instance`:e.instance.name===void 0?Be(e.instance):ze(e.instance,void 0,void 0);break;case`Assumption`:dt(e.assumption.location,`An ASSUME`),st(e.assumption);break;case`Theorem`:dt(e.theorem.location,`A THEOREM`),ot(e.theorem);break;case`Use`:dt(e.use.location,`A USE or HIDE`),D.topLevel.push(Qe(e.use));break;case`Module`:{dt(e.module.location,`A MODULE `);let t={contexts:[...a.contexts,zn()]},r=O(e.module,n,D,t),i=k(r.name);i===void 0?Vn(Dr(a),r):i!==r&&o(r.location,`Multiply-defined module '${r.name}': this definition or declaration conflicts \nwith the one at ${kn(i.location)}.`);break}}}),Le(),D},k=v.map(e=>{i.onAnalyze?.(e),u=Array.from({length:4},l)[1];let t=_(e,void 0),n=zn();f.toReversed().forEach(e=>Vn(n,e));let r=O(t.module,t.file,void 0,{contexts:[n]});return m.set(e,r),i.onModule?.(r,a),r});return{root:k[k.length-1],modules:k,messages:a}},Kr=(e,t,n,r)=>On(e.messages,{location:t,text:n,isWarning:!1,...r!==void 0&&!e.isTlc174&&{code:r}}),Y=(e,t)=>{for(let n of t)e.add(n)},qr=(e,t,n)=>`${e.id}:${t}:${n.id}`,Jr=(e,t,n,r)=>{e.set(qr(t,n,r),{op:t,index:n,param:r})},Yr=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},Xr=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},Zr=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&Xr(e,r,t)})},Qr=(e,t)=>`${e.id}:${t}`,$r=(e,t,n,r)=>{let i=Qr(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},ei=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&$r(e,t.param,t.position,t.level)})},ti=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},ni=(e,t)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Zr(e.levelConstraints,t.levelConstraints),ei(e.argLevelConstraints,t.argLevelConstraints),Yr(e.argLevelParams,t.argLevelParams)},ri=(e,t)=>t.includes(e.op)||t.includes(e.param),ii=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,ai=e=>e.kind!==`Module`,oi=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,si=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,ci=(e,t)=>e.kind===`OpDef`?e.weights[si(e,t)]??0:0,li=(e,t)=>e.maxLevels[si(e,t)]??3,ui=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,di=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[si(e,t)]??!0:e.isLeibnizArg[t]??!0,fi=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,pi=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],mi=(e,t)=>t.find(t=>t.op===e)?.expr,hi=(e,t,n)=>{let r=mi(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},gi=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=mi(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!ii(i.op))return;let a=i.op;hi(e.param,t,!1).forEach(t=>Jr(n,a,e.index,t))}),n},_i=(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;hi(r,t,!1).forEach(e=>Xr(a,e,i))}),e.argLevelParams.forEach(e=>{let n=mi(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;X(n.op,r,i);let o=li(n.op,e.index);hi(e.param,t,!1).forEach(e=>Xr(a,e,o))}),a},vi=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=mi(e.param,t);n===void 0?$r(i,e.param,e.position,e.level):n.kind===`OpArg`&&ii(n.op)&&$r(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=mi(e.param,t);if(a===void 0)return;let o=mi(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&ii(s)&&(X(a,n,r),$r(i,s,e.index,a.level))}),i},yi=(e,t)=>Kn(e,3).length>0||(Oi(e,t),Gn(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),bi=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(Qr(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(qr(e,i,t))))),Y(e.levelParams,n.levelParams),Y(e.allParams,n.allParams),Y(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(Qr(t,n))}),Yr(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},xi=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>li(t,o)&&(n&&X(a,r,i)&&Kr(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`||!oi(a.op)))return;let s=a.op;X(s,r,i);let c=Hn(s);for(let l=0;l<c;l++){let c=ui(t,o,l);li(s,l)>=c||(n&&X(a,r,i)&&Kr(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||!fi(t,o,l,u)||n.level<=li(s,u)||(X(a,r,i)&&X(n,r,i)&&Kr(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=X(n,r,i);n.level<=2||(o&&Kr(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${kn(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},Si=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);Zr(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&Zr(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>Zr(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=li(t,r);n?.levelParams.forEach(t=>Xr(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!oi(n.op))return;let o=n.op;X(o,r,i);let s=Hn(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!fi(t,a,r,i))continue;let s=li(o,i);n?.levelParams.forEach(t=>Xr(e.levelConstraints,t,s)),!o.isLeibniz&&!di(o,i)&&n&&Y(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&oi(n.op)&&(X(n.op,r,i),Xr(e.levelConstraints,t.param,li(n.op,t.index)))}),ei(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&ei(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>ei(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!ii(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)$r(e.argLevelConstraints,i,n,ui(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&fi(t,r,a,o)&&$r(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(X(n,r,i),$r(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&Yr(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>Yr(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):(X(a,r,i),a.levelParams.forEach(n=>Jr(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&ii(a.op)&&Jr(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!ii(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&fi(t,r,a,o)&&n.levelParams.forEach(t=>Jr(e.argLevelParams,i,o,t))})})},Ci=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),wi=(e,t)=>{let n=(n,r)=>{Kr(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=Ci.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.`)})},Ti=(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=>{X(r,t,n)||(e.levelCorrect=!1)}),e.ranges.forEach(r=>{X(r,t,n)||(e.levelCorrect=!1)});let i=e.operator;if(oi(i)){let r=X(i,t,n);xi(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&ci(i,n)===1?Math.max(e,t.level):e,i.level),e.ranges.forEach(t=>{e.level=Math.max(e.level,t.level)}),Y(e.levelParams,i.levelParams),Y(e.allParams,i.allParams),Y(e.nonLeibnizParams,i.nonLeibnizParams),e.operands.forEach((t,n)=>{t!==void 0&&(ci(i,n)===1&&Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),di(i,n)||Y(e.nonLeibnizParams,t.allParams))}),e.ranges.forEach(t=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams)});let a=new Set(pi(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),Si(e,i,a,t,n)}else X(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)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),Zr(e.levelConstraints,t.levelConstraints),$r(e.argLevelConstraints,i,n,t.level),ei(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>Jr(e.argLevelParams,i,n,t)),Yr(e.argLevelParams,t.argLevelParams)});return wi(e,n),e.levelCorrect},Ei=(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||X(e.step,t,n),e.levelCorrect;e.levelCorrect=X(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))}),bi(e,i,r),e.levelCorrect},Di=(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=X(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)}),bi(e,e.params,e.body)),e.levelCorrect),Oi=(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),Ei(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||Kr(t,e.location,`Argument ${r+1} of recursive operator ${e.name} is primed`)}),c=Math.max(c,e.level),Y(o,e.levelParams),Y(s,e.allParams))}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=2),e.level=Math.max(e.level,c),Y(e.levelParams,o),Y(e.allParams,s)}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=1),Ei(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(Oi(e,t)));let a=Gn(e);return a.forEach(e=>i(Ei(e,1,t))),qn(e).forEach(e=>i(Di(e,1,t))),e.topLevel.forEach(e=>i(X(e,1,t))),yi(e,t)||Kn(e,2).forEach(t=>Xr(e.levelConstraints,t,0)),a.forEach(t=>{Zr(e.levelConstraints,t.levelConstraints),ei(e.argLevelConstraints,t.argLevelConstraints),Yr(e.argLevelParams,t.argLevelParams,e=>!ri(e,t.params??[]))}),e.topLevel.forEach(t=>{Zr(e.levelConstraints,t.levelConstraints),ei(e.argLevelConstraints,t.argLevelConstraints),Yr(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},ki=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{ai(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=X(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),ni(e,t),Y(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),Ai=(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&&Kr(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&Kr(t,e.body.location,`Non-constant CASE for temporal goal.`),Ai(e.proof,t)):n===`$Qed`&&Ai(e.proof,t)})},ji=(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;Oi(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(r.expr,t,n)||(e.levelCorrect=!1)});let i=yi(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(X(a.expr,t,n)&&Kr(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||Kr(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&&(X(i.expr,t,n)&&Kr(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=X(o,t,n);for(let t=0;t<i.op.arity;t++){let a=r.argLevelConstraints.get(Qr(i.op,t))?.level;a===void 0||li(o,t)>=a||(s&&Kr(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=X(s,t,n);if(s.kind!==`OpDef`)return;let l=li(s,i.index);o.expr.level<=l||(c&&X(o.expr,t,n)&&Kr(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 Zr(e.levelConstraints,_i(r,e.substs,i,t,n),a),e.substs.forEach(t=>Zr(e.levelConstraints,t.expr.levelConstraints,a)),ei(e.argLevelConstraints,vi(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>ei(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),Yr(e.argLevelParams,gi(r.argLevelParams,e.substs),t=>!ri(t,e.params)),e.substs.forEach(t=>Yr(e.argLevelParams,t.expr.argLevelParams,t=>!ri(t,e.params))),e.levelCorrect},X=(e,t,n)=>{if(!ai(e))return Oi(e,n);switch(e.kind){case`OpAppl`:return Ti(e,t,n);case`OpDef`:return Ei(e,t,n);case`ThmOrAssumpDef`:return Di(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=X(r,t,n),r.kind===`Module`||(e.level=r.level,ti(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=>{X(r,t,n)||(e.levelCorrect=!1)}),X(e.body,t,n)||(e.levelCorrect=!1),e.instances.forEach(r=>{X(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),Zr(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>Zr(e.levelConstraints,t.levelConstraints)),ei(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>ei(e.argLevelConstraints,t.argLevelConstraints)),Yr(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];Yr(e.argLevelParams,t.argLevelParams,e=>!ri(e,n))}),e.instances.forEach(t=>Yr(e.argLevelParams,t.argLevelParams)),e.levelCorrect}case`Label`:{if(e.levelChecked>=t)return!0;e.levelChecked=t,e.params.forEach(e=>X(e,t,n));let r=X(e.body,t,n);return e.level=e.body.level,ti(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;X(i,t,n),e.level=i.level;let a=[i];for(let i of r.slice(1))if(i!==void 0){if(X(i,t,n),i===e.component)break;e.level=Math.max(e.level,i.level),a.push(i)}return a.forEach(t=>ni(e,t)),!0}case`SubstIn`:case`APSubstIn`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.body;X(r,t,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(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=>Y(e.levelParams,hi(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>Y(e.allParams,hi(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),Y(e.allParams,t.expr.allParams),Y(e.nonLeibnizParams,t.expr.nonLeibnizParams),e.nonLeibnizParams.has(t.op)&&(e.nonLeibnizParams.delete(t.op),Y(e.nonLeibnizParams,t.expr.allParams)))}));let i=yi(e.instantiatedModule,n);return e.levelConstraints=_i(r,e.substs,i,t,n),e.argLevelConstraints=vi(r,e.substs,t,n),e.argLevelParams=gi(r.argLevelParams,e.substs),e.levelCorrect}case`Instance`:return ji(e,t,n);case`Assume`:{if(e.levelChecked>=t)return!0;e.levelChecked=t;let r=X(e.body,t,n),i=!e.definition||X(e.definition,t,n);return e.level=e.body.level,ti(e,e.body),e.level!==0&&Kr(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=ki(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&&Kr(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&Ai(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return ki(e,e.facts,t,n);case`NonLeafProof`:return ki(e,[...e.steps,...e.instances],t,n);case`DefStep`:return ki(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=X(e.set,t,n),e.level=Math.max(e.level,e.set.level),e.level===3&&(e.levelCorrect=!1,Kr(n,e.location,`Level error:
|
|
36
|
-
Temporal formula used as set.`)),
|
|
29
|
+
Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){yn(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){yn(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){yn(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){yn(e,"Version number must follow `-version' option");return}let t=Le(s);if(t<0||t>1903){dn(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),yn(e,`Bad version number`);return}n.inputVersionNumber=t,r+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){yn(e,"Integer value at least 60 must follow `-lineWidth' option");return}r+=1;continue;default:yn(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!i&&(n.fairnessOption=`wf`)},xn=(e,t,n)=>{if(hn(t,n),n.column+=7,!hn(t,n).slice(n.column).startsWith(`(`)){dn(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=hn(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=gn(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?dn(e,`No closing ')' found in options statement`):bn(e,r)},Sn=(t,n,r)=>{let i=0,a=!1,o=!1;for(let s=n;!a&&s<t.length;s++){let c=t[s],l=s===n?r:0,u=[c.slice(0,l)];o=!1;for(let e=l;!a&&e<c.length;e++){let t=c[e],n=c.slice(e,e+2);if(n===`(*`&&!o)i+=1,u.push(` `),e+=1;else if(n===`*)`&&!o&&i===0)u.push(n),a=!0;else if(n===`*)`&&!o)--i,u.push(` `),e+=1;else if(i>0)u.push(` `);else if(o&&t===`\\`&&n.length===2)u.push(n),e+=1;else{if(!o&&n===`\\*`){u.push(` `);break}t===`"`&&(o=!o),u.push(t)}}if(o)return new e.s(`Unterminated string in line ${s+1}`);t[s]=u.join(``)}},Cn=(t,n)=>{let r=10*2**Math.max(0,Math.ceil(Math.log2(n/10)));throw new e.c(`java.lang.ArrayIndexOutOfBoundsException: Index ${t} out of bounds for length ${r}`)},wn=(t,n,r)=>{if(!n.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let i=pn(n),a={line:0,column:0};for(;vn(i,a,`PlusCal`);){let e=hn(i,a).slice(a.column),n=Array.from(e).findIndex(e=>!_n(e));if(e.startsWith(`options`)&&(n===-1?e.length:n)===7){xn(t,i,a);break}}let o=0,s=-1,c=!1;for(;o<i.length;o++){let e=i[o];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){s=t+11;break}if(n!==-1){s=n+6,c=!0;break}}let l=/* @__PURE__ */ new Set,u=mn(i,0,`BEGIN`,`TRANSLATION`);u===-1&&l.add(`NO_TRANSLATION_EXISTS`);let d=mn(i,u+1,`END`,`TRANSLATION`);if(d===-1&&l.add(`NO_TRANSLATION_EXISTS`),u===-1&&d===-1)return l;if(s===-1)return l.add(`NO_PLUSCAL_EXISTS`),l;let f=Sn(i,o,s);if(f!==void 0)return fn(t,f),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let p;try{let e=Ot(t,ot(i,o,s),c);p=e.ast,sn(e.ast,e.shouldOmitPC,e.hasDefaultInitialization,t.log)}catch(n){if(!(n instanceof e.s))throw n;fn(t,n)}u===-1&&Cn(-1,i.length);let m=ln.exec(i[u]);if(m===null)return l.add(`NO_PCAL_CHECKSUMS_EXIST`),l;let h=m.groups?.pcal,g=c&&r!==`1.7.4`?`fair`:p===void 0?void 0:at(p,t.params.inputVersionNumber,r);h!==void 0&&(g===void 0||h!==un(g))&&l.add(`PCAL_DIVERGENCE_EXISTS`);let _=m.groups?.tla;if(_!==void 0){if(d===-1)throw new e.c(`java.lang.IllegalArgumentException: fromIndex(${u+1}) > toIndex(-1)`);let t=n.slice(u+1,d).join(``);_!==un(t)&&l.add(`TLA_DIVERGENCE_EXISTS`)}return l.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):l},Tn=[[`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]]],En={file:`--TLA+ BUILTINS--`,beginLine:0,beginColumn:0,endLine:0,endColumn:0},W=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}),Dn=e=>Tn.map(([t,n,r,i,a])=>{let o=e(),s=n<0?void 0:Array.from({length:n},(t,n)=>({...W(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{...W(o),levelChecked:c?99:0,level:r,kind:`OpDef`,defKind:`BuiltIn`,name:t,arity:n,params:s,body:void 0,isLocal:!1,location:En,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}}),On=(e,t)=>{let n=JSON.stringify(t);e.some(e=>JSON.stringify(e)===n)||e.push(t)},kn=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}`,An=e=>e?.kind===`OpAppl`&&e.isAbsent===!0,jn=()=>({buckets:Array.from({length:11},()=>[]),count:0,threshold:8}),Mn=(e,t)=>(e&2147483647)%t,Nn=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[Mn(e.hash,t)].unshift(e));e.buckets=n,e.threshold=Math.floor(t*.75)},Pn=(e,n,r=n)=>e.buckets[Mn(t.Qt(r),e.buckets.length)].find(e=>e.key===n)?.value,Fn=(e,n,r,i=n)=>{let a=t.Qt(i),o=e.buckets[Mn(a,e.buckets.length)].find(e=>e.key===n);o?o.value=r:(e.count>=e.threshold&&Nn(e),e.buckets[Mn(a,e.buckets.length)].unshift({hash:a,key:n,value:r}),e.count++)},In=e=>e.buckets.toReversed().flatMap(e=>e.map(e=>e.value)),Ln=`\0module `,Rn=()=>({table:jn(),symbols:[]}),zn=e=>e.kind===`Module`?Ln+e.name:e.name,Bn=(e,t)=>{Fn(e.table,zn(t),t,t.name),e.symbols.push(t)},Vn=e=>e.kind===`ThmOrAssumpDef`?e.params.length:e.kind===`Module`?0:e.arity,Hn=(e,t)=>Pn(e.table,t),Un=(e,t)=>Pn(e.table,Ln+t,t),Wn=e=>e.context.symbols.filter(e=>e.kind===`OpDef`&&e.defKind===`UserDefined`),Gn=(e,t)=>In(e.context.table).filter(e=>e.kind===`OpDecl`&&e.declKind===t).toReversed(),Kn=e=>e.context.symbols.filter(e=>e.kind===`ThmOrAssumpDef`),qn=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),Jn=e=>{if(e.length>3&&e.endsWith(`!!!`))return[...Jn(e.slice(0,-3)),`!!`];let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},Yn=e=>{switch(e.kind){case`Identifier`:return Jn(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=Jn(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}}})}},Xn=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},Zn=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,Qn=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,$n=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),er=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,tr=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],nr=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},rr=e=>(t,n,r,i,a)=>{let o=[],s=[],c=[],l=e=>t[e].location??a,u={name:void 0,nameLocation:void 0,node:void 0,index:0,mode:`FindingOpName`,previousMode:void 0,letInContext:void 0,definitionArityFound:0,definitionArgs:[],isInSuffices:!1},d=e=>e.args??[];for(;u.index<t.length;){let f=t[u.index];if((f.op!==`Name`&&f.op!==`Null`||n!==0)&&f.args!==void 0)return e.addError(l(u.index),`Selector \`${f.name}' should not have argument(s).`);switch(u.mode){case`FindingOpName`:{let f,p,m=[];for(;f===void 0&&u.index<t.length;){let n=t[u.index];if(p=n.op===`Name`?u.name===void 0?e.resolveSynonym(n.name):`${u.name}!${e.resolveSynonym(n.name)}`:void 0,u.name===void 0&&n.op!==`Name`)return e.addError(l(u.index),`Need name or step number here, not \`${n.name}'.`);p!==void 0&&(f=u.letInContext===void 0?e.resolveSymbol(p):Hn(u.letInContext,p)),f===void 0&&(p!==void 0&&(u.name=p,u.nameLocation=nr(u.nameLocation,l(u.index))),m.push(...d(n)),u.index++)}if(f===void 0&&e.version===`1.7.4`){let n=t.length-1;return e.addError(l(n),`Unknown operator: \`${Zn(t[n])}'.`)}if(f===void 0)return e.addError(u.nameLocation??a,`Unknown operator: \`${u.name}'.`);if(f.kind===`Module`)return e.addError(l(u.index),`Module name (${t[u.index].name}) not allowed here.`);if(u.node=f,u.nameLocation=nr(u.nameLocation,l(u.index)),u.name=p,$n(f)&&t.length!==1)return e.addError(l(u.index),`Cannot take subexpression of \`${u.name}'.`);let h=Vn(f);if(n===0){if(m.push(...d(t[u.index])),u.definitionArityFound+m.length!==h)return e.addError(t[u.index].argsLocation??a,`The operator ${u.name} requires ${h-u.definitionArityFound} arguments.`);m.forEach((t,n)=>u.definitionArgs.push(e.generateArgument(f,n+u.definitionArityFound,t,l(u.index))))}if(u.definitionArityFound=h,f.kind===`OpDef`&&f.defKind===`ModuleInstance`){if(u.index===t.length-1&&!(i||r))return e.addError(l(u.index),`Operator name ${u.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(l(u.index),`Subexpression of \`${u.name}' used inside the operator's definition.`);if(u.index!==t.length-1&&n!==void 0){s.push(...n.params??[]),u.name=void 0,u.nameLocation=void 0,u.mode=t[u.index+1].op===`Name`?`FollowingLabels`:`FindingSubExpr`,c.push(...u.definitionArgs),u.definitionArityFound=0,u.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;u.mode===`FindingSubExpr`&&(u.node=e)}}u.previousMode=`FindingOpName`;break}case`FollowingLabels`:{let r=u.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(l(u.index),`Cannot find label \`${f.name}'.`);if(u.node=i,e.isOutOfLabelScope(i))return e.addError(l(u.index),`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(l(u.index),`Label \`${f.name}' used with wrong number of arguments.`);c.push(...d(f).map(e.generateExpression))}s.push(...i.params),u.index<t.length-1&&t[u.index+1].op!==`Name`&&(u.mode=`FindingSubExpr`),u.mode===`FindingSubExpr`&&(u.node=i.body),u.previousMode=`FollowingLabels`;break}case`FindingSubExpr`:{let n=u.node,r=()=>e.addError(l(u.index),`Nonexistent operand specified by \`${Zn(f)}'.`);if(f.op===`:`){if(!(u.previousMode!==`FindingSubExpr`&&(u.index===t.length-1&&u.previousMode===`FindingOpName`||u.index<t.length-1&&t[u.index+1].op===`Name`)))return e.addError(l(u.index),`\`!:' can be used only after a name and either at the end after an
|
|
30
|
+
operator name or before an operator name.`)}else if(n===void 0)return e.addError(l(u.index),`Subexpression selection failed, probably due to an error in the selected expression.`);else if(n.kind===`LetIn`){if(Qn(f.op,1)!==1)return e.addError(l(u.index),`A LET/IN expression has only one operand.`);u.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(l(u.index),`Internal error: Expecting $Pair and didn't find it.`),m=e=>e?.kind===`OpAppl`&&e.operator.name===`$Pair`,h=Qn(f.op,a.length);if(o){let e=Qn(f.op,i.arity);if(e===-1)return r();u.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();u.node=e.operands[1]}else if(i.name===`$Case`){if(u.index===t.length-1)return e.addError(l(u.index),`Subexpression of CASE must have form !i!j.`);if(h===-1)return r();let n=a[h-1];if(!m(n))return p();u.index++;let i=Qn(t[u.index].op,2);if(i===-1)return e.addError(l(u.index),`Second selector for CASE subexpression must specify one of two operands.`);if(u.node=n.operands[i-1],u.node===void 0)return e.addError(l(u.index),`Selecting OTHER in a CASE statement.`)}else if(i.name===`$Except`){if(h>1)return e.addError(l(u.index),`Selecting subexpression of an EXCEPT not yet implemented.`);if(h===-1)return r();u.node=a[h-1]}else if((n.bounded?.length??0)===0&&(n.unbounded?.length??0)===0){if(h===-1)return r();u.node=a[h-1]}else if(f.op===`Null`||f.op===`@`){let t=tr(n);if(s.push(...t),f.op===`Null`){if(d(f).length!==t.length)return e.addError(l(u.index),`Selector with ${d(f).length} argument(s) used for quantifier with ${t.length} bound identifier(s).`);c.push(...d(f).map(e.generateExpression))}u.node=a[0]}else{let e=Qn(f.op,n.ranges.length);if(e===-1)return r();u.node=n.ranges[e-1]}}else return e.addError(l(u.index),`Choosing operand \`${f.name}' of subexpression with no operands.`)}else if(n.kind===`AssumeProve`){if(n.isSuffices&&!u.isInSuffices){if(Qn(f.op,1)!==1)return e.addError(l(u.index),`Accessing non-existent subexpression of a SUFFICES`);u.isInSuffices=!0}else{u.isInSuffices=!1;let i=Qn(f.op,1+n.assumptions.length);if(i===-1)return r();if(e.isOutOfClauseScope(n,i))return e.addError(l(u.index),`Accessing ASSUME/PROVE clause within the scope of a declaration
|
|
31
|
+
from outside that declaration's scope.`);if(i<=n.assumptions.length){if(u.node=n.assumptions[i-1],u.node.kind===`NewSymb`&&u.index!==t.length-1)return e.addError(l(u.index),`Selected a subexpression of a NEW clause of an ASSUME.`)}else u.node=n.goal}}else if(n.kind===`OpArg`){let t=n.op;if(t.kind!==`OpDef`||t.name!==`LAMBDA`)return e.addError(l(u.index),`Trying to select subexpression of an operator argument.`);if(f.op!==`Null`&&f.op!==`@`)return e.addError(l(u.index),`Cannot use !${f.name} to select subexpression of a LAMBDA.`);if(f.op===`Null`){if(t.arity!==d(f).length)return e.addError(l(u.index),`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??[]),u.node=t.body}else if(n.kind===`Label`)u.node=n.body,u.index--;else return e.addError(l(u.index),`Selecting subexpression of expression that has none.`);if(u.node===void 0)return e.addError(l(u.index),`An unexpected null node specified by '${f.name}'.\nThis is probably due to a previous error.`);if(u.index!==t.length-1){let n=t[u.index+1];if(n.op===`Name`){for(;u.node?.kind===`Label`;)u.node=u.node.body;if(u.node?.kind!==`LetIn`)return e.addError(l(u.index),`A name selector here must be from a LET clause.`);u.letInContext=u.node.context,u.mode=`FindingOpName`}else if(n.op===`:`)return e.addError(l(u.index),`!: should not follow an operand selector.`)}u.previousMode=`FindingSubExpr`;break}}u.index++}let f=u.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 u.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`?Vn(f.op):u.previousMode===`FindingOpName`&&er(f)?Vn(f):0);if(n!==t)return e.addError(a,`Expected arity ${n} but found operator of arity ${t}.`)}let p=f;if(u.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(...u.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:Vn(t)},(t,n)=>e.createFormalParam(`NewParam${n}`,0,void 0))),p=e.createOpAppl(t,u.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=qn.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,u.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}.`)},ir=/* @__PURE__ */ new Map([[`(`,`)`],[`[`,`]`],[`{`,`}`],[`<<`,`>>`]]),ar=(e,t)=>`${e}:${t}`,or=(e,n)=>{let r=t.in(n).filter(e=>e.kind!==`End`).map(t.rn),i=[0,0];for(let e=0;e<n.length;e++)n[e]===`
|
|
32
|
+
`&&i.push(e+1);return{name:e,source:n,tokens:r,lineOffsets:i,tokenIndexes:new Map(r.map((e,t)=>[ar(e.line,e.column),t]))}},G=(e,t,n)=>e.tokens[t]!==void 0&&e.tokens[t].text===n&&e.tokens[t].kind!==`String`,sr=(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},cr=(e,t)=>e.tokenIndexes.get(ar(t.line,t.column))??Math.min(sr(e,t,!1),e.tokens.length-1),lr=(e,t)=>Math.max(sr(e,t,!0)-1,0),ur=(e,t)=>{let n=e.tokens[t].text,r=ir.get(n);if(r===void 0)return t;let i=0;for(let a=t;a<e.tokens.length;a++)if(G(e,a,n))i++;else if(G(e,a,r)&&(i--,i===0))return a;return t},dr=(e,t)=>({start:cr(e,t.start),end:lr(e,t.end)}),K=(e,t)=>{let n=t.location.range;if(n)return dr(e,n);let r=cr(e,t.location);return{start:r,end:ur(e,r)}},fr=(e,t)=>{let n=t.start-1,r=t.end+1;return G(e,n,`(`)&&G(e,r,`)`)&&ur(e,n)===r?fr(e,{start:n,end:r}):t},pr=(e,t)=>{let n=t.start-1,r=t.end+1;return G(e,n,`(`)&&ur(e,n)===r&&(G(e,n-1,`(`)||G(e,n-1,`,`))?pr(e,{start:n,end:r}):t},q=(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}),J=(e,t)=>q(e,{start:t,end:t}),mr=(e,n,r)=>{let i=0,a=e.lineOffsets[n];for(;a<e.source.length;){if(i=e.source[a]===` `?t.nn(i):i+1,i>=r)return a;a++}return a},hr=(e,t)=>{let n=e.tokens[t],r=mr(e,n.line,n.column);return e.source.slice(r,mr(e,n.line,n.endColumn)+1)},gr=(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},_r=n=>{let r=or(``,n),i=r.tokens.reduce((e,t,n)=>{if(!gr(r,n))return e;let i=mr(r,t.line,t.column);return`${e.slice(0,i)} ${e.slice(i+2)}`},n);if(i!==n&&t.W(n)!==void 0)throw new e.F(`SANY rejects a []ASSUME or []PROVE outside an ASSUME/PROVE`);return i},vr=(e,t)=>{let n=e.tokens[t-1],r=e.tokens[t],i=n===void 0?0:mr(e,n.line,n.endColumn)+1,a=e.source.slice(i,mr(e,r.line,r.column)),o=[],s=0;for(;s<a.length;)if(a.startsWith(`\\*`,s)){let e=a.indexOf(`
|
|
33
|
+
`,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},yr=(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},br=(e,t,n,r)=>{for(let i=t;i<=n;i++)if(G(e,i,r))return i;return-1},xr=new Map(t.ct.flatMap(([e,...t])=>t.map(t=>[t,e]))),Sr=e=>e.split(`!`).map(e=>xr.get(e)??(e===`~`?`\\lnot`:e)).join(`!`),Cr={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}},wr=e=>/^[A-Za-z0-9_]+$/.test(e),Tr=e=>e!==`!!`&&e.includes(`!`),Er=e=>e.contexts[e.contexts.length-1],Dr=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=Hn(e.contexts[n],t);if(r)return r}},Or=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,kr=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,Ar=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||jr(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&jr(n.module)}return!1},jr=e=>Gn(e,2).length===0&&Gn(e,3).length===0,Mr=e=>[...e.kind===`Let`?e.instances??[]:[],...t.$t(e).flatMap(Mr)],Nr=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:Nr(e)):Mr(e),Pr=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]:[]):[],...Pr(e.proof)]):[],Fr=(e,n)=>{let r=/* @__PURE__ */ new Set;for(let t of e.units)if(t.kind===`Module`&&r.add(t.module.name),t.kind===`Instance`&&t.instance.module===n.module)return r.has(n.module);return e.modules.some(e=>e.name===n.module&&t.pt(e.location,n.location))},Ir=e=>BigInt(e.startsWith(`\\`)?`0${e.slice(1).replace(/^h/i,`x`)}`:e).toString(),Lr=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`?Mr(e.definition.body):e.kind===`Theorem`&&s?[...Nr(e.theorem.statement),...Pr(e.theorem.proof)]:e.kind===`Assumption`&&s?Mr(e.assumption.expression):[]).filter(e=>l(e.module)&&!Fr(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}},Rr=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),zr=e=>{let t=e.kind===`Apply`?Yn(e):void 0;return Rr.has(e.kind)||t!==void 0&&Xn(t)},Br=/* @__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`]]),Vr=/* @__PURE__ */ new Set([`N_GeneralId`,`N_OpApplication`,`N_PrefixExpr`,`N_InfixExpr`,`N_PostfixExpr`,`N_FcnAppl`,`N_RecordComponent`]),Hr=/* @__PURE__ */ new Set([`'`,`^+`,`^*`,`^#`]),Ur=(e,t)=>Hr.has(t)?`N_GenPostfixOp`:e.kind===`Lambda`||t===`~`||t===`-.`?`N_GenNonExpPrefixOp`:`N_GenInfixOp`,Wr=(n,r,i={})=>{let a=[],o=(e,t)=>On(a,{location:e,text:t,isWarning:!1}),s=(e,t)=>On(a,{location:e,text:t,isWarning:!0}),c=i.version===`1.7.4`?-1:0,l=()=>++c,u=0,d=(e,t)=>{let n=Dr(e,t.name);if(n===t)return;if(n===void 0){Bn(Er(e),t);return}let r=t.kind===`FormalParam`||Or(n)!==Or(t)||Vn(n)!==Vn(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(r&&i.version===`1.7.4`)?o(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):r?o(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${kn(n.location)}.`):Ar(t,n)||s(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${kn(n.location)}.`)};i.version!==`1.7.4`&&Dn(l);let f=Dn(l);l();let p=new Map(f.map(e=>[e.name,e])),m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=(n,r)=>{let a=n===i.rootFileName&&i.rootFilePath||`${n}.tla`,o=t=>new e.M(`Could not parse module ${n} from file ${a}`,n,t),s=i.version===`1.7.4`?t.tn(r):void 0;if(s!==void 0)throw o(s);try{return t.H(_r(r))}catch(n){throw n instanceof e.F?o(t.W(r)??`***Parse Error***\n${n.message}`):n}},_=(t,n,r)=>{let a=h.get(t);if(a)return a;if(n===void 0)throw new e.D(t,r,i.version!==`1.7.4`);i.onParse?.(t);let o=g(t,n);if(o.name!==t)throw new e.M(`File name '${t}' does not match the name '${o.name}' of the top level module it contains.`,void 0);let s={file:or(o.name,n),module:o};return h.set(t,s),s},v=[],y=/* @__PURE__ */ new Set,b=[],x=(t,n,i)=>{let a=b.indexOf(t);if(a!==-1)throw new e.M(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...b.slice(a),t].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(y.has(t))return;y.add(t),b.push(t);let o=D(t,_(t,n,i).module);[...o.extendees,...o.instancees].forEach(e=>x(e,r(e),t)),b.pop(),v.push(t)},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=D(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=e=>{_(e,n);let t=()=>w(e,`extendees`,/* @__PURE__ */ new Set)??w(e,`instancees`,/* @__PURE__ */ new Set);for(let e=t();e!==void 0;e=t())h.has(e.name)||_(e.name,r(e.name),e.namingModule),S.add(`${e.importer} ${e.name}`)},E=i.rootFileName??g(``,n).name,D=(e,t)=>{let n=Lr(t);return e!==E||i.rootExtendees===void 0||(n.extendees.splice(t.extends.length,0,...i.rootExtendees),i.rootExtendees.forEach(t=>{n.importers.has(t)||n.importers.set(t,e)})),n};T(E),x(E,n);let O=(t,n,r,a)=>{let c={curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSectionCount:0},f=[],h=[],g=[],_=[],v=/* @__PURE__ */ new WeakSet,y=()=>_.push({labels:/* @__PURE__ */ new Map,params:[]}),b=()=>_.pop()?.labels??/* @__PURE__ */ new Map,x={depth:0,isDeclared:[],goal:void 0,goalClause:0},S=/* @__PURE__ */ new WeakMap,C=/* @__PURE__ */ new WeakMap,w=e=>{let t=e.kind===`AssumeProve`?S.get(e):void 0;t&&(t.isInProof=!1)},T=e=>q(n,K(n,e)),E=e=>e.range?dr(n,e.range):{start:cr(n,e),end:cr(n,e)},D={kind:`Module`,id:l(),name:t.name,location:q(n,E(t.location)),extendees:[],context:Er(a),topLevel:[],definitions:[],opDefsInRecursiveSection:[],isLevelChecked:!1,levelCorrect:!0,argLevelParams:/* @__PURE__ */ new Map,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map,records:[]};r&&r.definitions.push(D);let k=e=>{for(let t=a.contexts.length-1;t>=0;t--){let n=Un(a.contexts[t],e);if(n?.kind===`Module`)return n}return m.get(e)},A=t=>{let n=k(t);if(n===void 0)throw new e.F(`Could not find module ${t}`);return n},j=(e,t)=>{a.contexts.push(e);let n=t();return a.contexts.pop(),n},M=(e,t,n,r)=>{let i={...W(l()),kind:`FormalParam`,name:e,arity:t,location:n};return r&&d(a,i),i},N=e=>({...W(l()),kind:`OpDef`,defKind:`UserDefined`,arity:e.params?.length??0,params:[],body:void 0,isLocal:!1,module:D,source:void 0,preComments:[],isDefined:!0,inRecursive:!1,inRecursiveSection:!1,recursiveSection:-1,letInLevel:0,weights:(e.params??[]).map(()=>0),isLeibnizArg:(e.params??[]).map(()=>!0),isLeibniz:!0,opLevelCond:void 0,maxLevels:(e.params??[]).map(()=>3),minMaxLevel:void 0,labels:/* @__PURE__ */ new Map,step:void 0,...e}),ee=e=>{e.letInLevel=c.curLevel,c.unresolvedSum>0&&(e.recursiveSection=c.recursiveSectionCount,e.inRecursiveSection=c.unresolvedCount[c.curLevel]>0,D.opDefsInRecursiveSection.push(e))},P=(e,t,n,r={},i=l())=>({...W(i),kind:`OpAppl`,operator:e,operands:t,unbounded:r.unbounded,bounded:r.bounded,tupleOrs:r.tupleOrs,ranges:r.ranges??[],location:n}),F=()=>({...P(I(`$Nop`),[],En,{},u),isNull:!0}),I=t=>{let n=p.get(t);if(!n)throw new e.B(`SANY has no builtin operator ${t}`);return n},L=(e,t,n,r={})=>P(I(e),t,n,r),te=(e,t)=>({...W(l()),kind:`String`,value:e,location:t}),ne=(e,t)=>({...W(l()),kind:`OpArg`,op:e,location:t}),re=(t,n)=>{let r=Dr(a,Sr(t));if(r===void 0||r.kind===`Module`)throw new e.F(`Unknown operator: \`${t}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},ie=(e,t,n)=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`)return;let r=e.params??[];r.length===t.length?r.forEach((r,i)=>{let a=t[i];r.arity===0&&a.kind===`OpArg`&&o(n,`Operator used in argument number ${i+1} has incorrect number of arguments.`);let s=a.kind===`OpArg`&&Vn(a.op)===r.arity&&!(a.op.kind===`OpDef`&&(a.op.params??[]).some(e=>e.arity>0));r.arity>0&&!s&&o(n,`Argument number ${i+1} to operator '${e.name}' \nshould be a ${r.arity}-parameter operator.`)}):o(n,`Wrong number of arguments (${t.length}) given to operator '${e.name}', \nwhich requires ${r.length} arguments.`)},ae=rr({version:i.version,resolveSymbol:e=>Dr(a,e),resolveSynonym:Sr,generateExpression:e=>B(e),generateArgument:(e,t,n,r)=>he(e,t,n,r),createOpAppl:(e,t,n)=>{let r=P(e,t,n);return ie(e,t,n),r},createOpArg:ne,createFormalParam:(e,t,n)=>M(e,t,n,!1),createLambda:(e,t,r)=>N({name:`LAMBDA`,params:e,body:t,location:r,preComments:vr(n,cr(n,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>V(`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:I,addError:(e,t)=>(o(e,t),F()),isOutOfLabelScope:e=>{let t=C.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=S.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}}),R=(e,t)=>{let r=t.start;return e.map(e=>{let i=e.op===`Name`?e.name:e.op===`Null`?`(`:String(e.op),a=br(n,r,t.end,i);if(a===-1)return e;if(e.op===`Null`){let t=ur(n,a);return r=t+1,{...e,location:q(n,{start:a,end:t})}}r=a+1;let o=J(n,a);if(e.args===void 0||!G(n,a+1,`(`))return{...e,location:o};let s=ur(n,a+1);return r=s+1,{...e,location:o,argsLocation:q(n,{start:a+1,end:s})}})},z=(t,r,i,a)=>{let o=Yn(t);if(o===void 0)throw new e.F(`Expected a name, found ${t.kind}`);return ae(R(o,K(n,t)),r,i,a,T(t))},oe=t=>{let n=z(t,0,!1,!1);if(n.kind!==`OpAppl`)throw new e.F(`Expected an expression`);return n},se=e=>{if(e.kind!==`OpAppl`)return;let t=f.find(t=>t.name===e.operator.name);t&&(t.node.operator=I(`$RecursiveFcnSpec`))},ce=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},[]),le=(e,t)=>Oe(e,t,ce(e).map(e=>B(e[0].set))),ue=(e,t)=>{let n=_.at(-1);n?.params.push(e);let r=B(t);return n?.params.pop(),r},de=(e,t,n,r,i)=>j(Rn(),()=>{let a=le(t,n),o=ue(a.bounded.flat(),r);return L(e,[o],i,a)}),fe=e=>{let t=K(n,e),r=yr(n,t.start,t.end,e.params);return j(Rn(),()=>{let i=e.params.map((e,t)=>M(e,0,J(n,r[t]),!0)),a=ue(i,e.body);return N({name:`LAMBDA`,params:i,body:a,location:q(n,t),preComments:vr(n,t.start)})})},pe=e=>e.kind===`OperatorReference`?e.operator:e.kind===`Lambda`&&e.body.kind===`Apply`?e.body.operator:n.tokens[cr(n,e.location)].text,me=(t,n)=>{let r=T(t);if(t.kind===`Lambda`)return t.location.range!==void 0&&t.operator===void 0?ne(fe(t),r):ne(re(pe(t),r),r);if(!zr(t))return o(r,`Arity ${n.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${n.name}'.`),F();if(t.kind===`OperatorReference`)return ne(re(t.operator,r),r);let i=z(t,n.arity,!1,!1);if(i.kind===`OpArg`||i.kind===`OpAppl`&&i.isNull===!0)return i;throw new e.F(`Expected an operator argument at line ${r.beginLine}, column ${r.beginColumn}`)},he=(t,r,i,s)=>{let c=t.kind===`OpDef`&&(t.defKind===`UserDefined`||t.defKind===`ModuleInstance`)?t.params?.[r]?.arity??0:0;if(c===0)return B(i);let l=K(n,i),u=q(n,l),d=`${r+1} (counting from 1)`,f=pr(n,l);if(f!==l||!zr(i))return o(q(n,f),`An expression appears as argument number ${d} to operator '${t.name}', in a position an operator is required.`),F();if(i.kind===`Identifier`||i.kind===`Subexpression`||i.kind===`Apply`){let t=z(i,c,!1,!1);if(t.kind===`OpArg`||t.kind===`OpAppl`)return t;throw new e.F(`Expected an operator argument at ${kn(u)}`)}if(i.kind===`Lambda`&&i.location.range!==void 0&&i.operator===void 0){let e=fe(i),n=Vn(e);return n===c?ne(e,u):(o(s,`Lambda expression with arity ${n} used as argument ${r+1} of operator \`${t.name}', \nbut an operator of arity ${c} is required.`),F())}let p=pe(i),m=Dr(a,Sr(p));if(m===void 0)return o(u,`Could not find declaration or definition of symbol '${p}'.`),F();let h=Vn(m);return h===c?ne(m,u):(o(s,`Operator with incorrect arity passed as argument. \nOperator '${m.name}' of arity ${h} is argument number ${d} to operator \`${kn(t.location)}', \nbut an operator of arity ${c} was expected.`),F())},ge=e=>{let t=T(e);if(e.isBulleted)return L(e.kind===`And`?`$ConjList`:`$DisjList`,e.operands.map(B),t);let r=K(n,e),i=e.kind===`And`?`\\land`:`\\lor`,[a,...o]=e.operands;return o.reduce((e,t,a)=>{let s=fr(n,K(n,t)),c=a===o.length-1?r.end:s.end;return L(i,[e,B(t)],q(n,{start:r.start,end:c}))},B(a))},_e=e=>{let t=K(n,e),r=e.arms.map((r,i)=>{let a=fr(n,K(n,r.condition)),o=i===e.arms.length-1&&e.other===void 0,s=fr(n,K(n,r.body)),c=[B(r.condition),B(r.body)];return L(`$Pair`,c,q(n,{start:a.start,end:o?t.end:s.end}))}),i=e.other;if(i){let e=fr(n,K(n,i)),a=ve(e.start,`OTHER`);r.push(L(`$Pair`,[void 0,B(i)],q(n,{start:a,end:t.end})))}return L(`$Case`,r,q(n,t))},ve=(e,t)=>{for(let r=e;r>=0;r--)if(G(n,r,t))return r;return e},ye=e=>{let t=K(n,e),r=q(n,t),i=[B(e.function)],a=L(`$Except`,i,r),o=K(n,e.function),s=br(n,o.end+1,t.end,`EXCEPT`)+1;return e.updates.forEach(e=>{let r=br(n,s,t.end,`!`),o=fr(n,K(n,e.value)),c=q(n,{start:r,end:o.end}),l=r+1,u=e.path.map(e=>{if(e.kind===`Field`){let t=be(l,e.name);return l=t+1,te(e.name,J(n,t))}let r=br(n,l,t.end,`[`),i=ur(n,r);return l=i+1,e.args.length===1?B(e.args[0]):L(`$Tuple`,e.args.map(B),q(n,{start:r,end:i}))}),d=L(`$Seq`,u,c),f=L(`$Pair`,[d],c);g.push(f),h.push(a),f.operands.push(B(e.value)),g.pop(),h.pop(),i.push(f),s=o.end+1}),a},be=(e,t)=>{for(let r=e;r<n.tokens.length;r++)if(n.tokens[r].text===t&&n.tokens[r].kind!==`String`)return r;return e},xe=(e,t)=>{let r=K(n,t),i=r.start+1,a=t.fields.map((e,r)=>{let a=be(i,e.name),s=fr(n,K(n,e.value));return i=s.end+1,t.fields.slice(0,r).some(t=>t.name===e.name)&&o(J(n,a),`Non-unique fields in constructor.`),L(`$Pair`,[te(e.name,J(n,a)),B(e.value)],q(n,{start:a,end:s.end}))}),s=L(e,a,q(n,r));return D.records.push(s),s},Se=e=>({line:n.tokens[e].line,column:n.tokens[e].column}),Ce=e=>{let t=[],r=e;for(;n.tokens[r]?.kind===`Identifier`;){let e=G(n,r+1,`(`)?ur(n,r+1):r,i=n.tokens.slice(r+1,e).filter(e=>e.text===`_`).length;if(t.push({name:n.tokens[r].text,arity:i,location:{...Se(r),range:{module:n.name,start:Se(r),end:Se(e)}}}),!G(n,e+1,`,`))break;r=e+2}return t},we=e=>{let t=[...e.definitions.map(e=>({unit:{kind:`Definition`,definition:e},span:je(e)})),...(e.instances??[]).map(e=>({unit:{kind:`Instance`,instance:e},span:je(e)}))],r=K(n,e).start,i=fr(n,K(n,e.body)).start,a=[];for(let e=r+1;e<i;e++){let r=t.some(t=>t.span.start<=e&&e<=t.span.end);G(n,e,`RECURSIVE`)&&!r&&a.push({unit:{kind:`Recursive`,declarations:Ce(e+1)},span:{start:e,end:e}})}return[...t,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},Te=e=>{let t=Rn();return j(t,()=>{c.curLevel++,c.unresolvedCount[c.curLevel]=0;let n=[],r=[];we(e).forEach(e=>{e.kind===`Recursive`?Ie(e.declarations):e.kind===`Instance`?ze(e.instance,n,r):e.definition.kind===`Function`?Pe(e.definition,n):Me(e.definition,n)}),Le(),c.curLevel=Math.max(c.curLevel-1,0);let i=B(e.body);return{...W(l()),kind:`LetIn`,opDefs:n,instances:r,body:i,context:t,location:T(e)}})},Ee=e=>{let t=K(n,e),r=q(n,t);return j(Rn(),()=>{let i=e.pattern,a=i.kind===`Name`?[i.name]:i.names;if(e.set===void 0){let o=yr(n,t.start,t.end,a),s=a.map((e,r)=>M(e,0,J(n,i.kind===`Name`?t.start:o[r]),!0)),c=ue(s,e.body);return L(`$UnboundedChoose`,[c],r,{unbounded:s})}let o=B(e.set),s=K(n,e.set),c=yr(n,t.start,s.start,a),l=a.map((e,t)=>M(e,0,J(n,c[t]),!0)),u=ue(l,e.body);return L(`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},De=e=>{if(wr(e.operator)||Tr(e.operator)||e.args.length>2||Dr(a,Sr(e.operator))!==void 0)return;let t=K(n,e);if(n.tokens[t.start].text===e.operator&&G(n,t.start+1,`(`))return;let r=fr(n,K(n,e.args[0])),i=e.args.length===1&&r.start!==t.start,o=i?t.start:r.end+1,s=hr(n,o);return{index:o,name:i&&s===`-`?`-.`:s,fixity:i?`prefix`:e.args.length===2?`infix`:`postfix`}},B=e=>{let t=T(e);switch(e.kind){case`Number`:return{...W(l()),kind:`Numeral`,value:Ir(e.text??String(e.value)),location:t};case`Decimal`:{let[n,r]=e.text.split(`.`),i=BigInt(n+r),a=i<=9223372036854775807n;return{...W(l()),kind:`Decimal`,mantissa:i.toString(),exponent:String(a?-r.length:r.length),integralPart:n,fractionalPart:r,location:t}}case`String`:return te(e.value,t);case`Identifier`:{let t=oe(e);return se(t),t}case`Apply`:{let r=De(e);if(r!==void 0)return o(J(n,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),o(t,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...F(),isAbsent:!0};let i=oe(e);return(Tr(e.operator)||wr(e.operator))&&se(i),i}case`Bracket`:return o(J(n,K(n,e).start),"Unsupported expression type `['."),{...F(),isAbsent:!0};case`OperatorReference`:case`Lambda`:{let r=n.tokens[K(n,e).start].text;return o(t,r===`LAMBDA`?`LAMBDA expression used where an expression is required.`:`Unsupported expression type \`${Ur(e,r)}'.`),{...F(),isAbsent:!0}}case`And`:case`Or`:return ge(e);case`Prime`:return L(`'`,[B(e.expression)],t);case`Unchanged`:return L(`UNCHANGED`,[B(e.expression)],t);case`Enabled`:return L(`ENABLED`,[B(e.expression)],t);case`Always`:return L(`[]`,[B(e.expression)],t);case`Eventually`:return L(`<>`,[B(e.expression)],t);case`If`:return L(`$IfThenElse`,[B(e.condition),B(e.consequent),B(e.alternative)],t);case`Case`:return _e(e);case`Let`:return Te(e);case`Forall`:case`Exists`:return de(e.kind===`Forall`?`$BoundedForall`:`$BoundedExists`,e.bounds,K(n,e).start,e.body,t);case`UnboundedQuantifier`:{let r=K(n,e),i=K(n,e.body),a=yr(n,r.start,i.start,e.names),o=e.isTemporal?e.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:e.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return j(Rn(),()=>{let r=e.names.map((e,t)=>M(e,0,J(n,a[t]),!0)),i=ue(r,e.body);return L(o,[i],t,{unbounded:r})})}case`Choose`:return Ee(e);case`SetEnumeration`:return L(`$SetEnumerate`,e.elements.map(B),t);case`Tuple`:return L(`$Tuple`,e.elements.map(B),t);case`SetFilter`:{let r=B(e.bound.set),i=K(n,e);return j(Rn(),()=>{let n=Oe([e.bound],i.start,[r]),a=ue(n.bounded.flat(),e.predicate);return L(`$SubsetOf`,[a],t,n)})}case`SetMap`:return de(`$SetOfAll`,e.bounds,K(n,e.expression).end+1,e.expression,t);case`FunctionConstruction`:return de(`$FcnConstructor`,e.bounds,K(n,e).start,e.body,t);case`FunctionSet`:return L(`$SetOfFcns`,[B(e.domain),B(e.range)],t);case`Record`:return xe(`$RcdConstructor`,e);case`RecordSet`:return xe(`$SetOfRcds`,e);case`Except`:return ye(e);case`ExceptAt`:{let e=h[h.length-1],n=g[g.length-1];return e===void 0||n===void 0?(o(t,`@ used where its meaning is not defined.`),F()):{...W(l()),kind:`At`,except:e,component:n,location:n.location}}case`FunctionApplication`:{let n=B(e.function);if(An(n))return n;se(n);let r=n.kind===`OpAppl`?n.operator:void 0,i=r?.kind===`OpDef`&&r.defKind===`UserDefined`?r.body:void 0;if(i?.kind===`OpAppl`&&(i.operator.name===`$NonRecursiveFcnSpec`||i.operator.name===`$RecursiveFcnSpec`)){let n=(i.bounded??[]).reduce((e,t,n)=>e+(i.tupleOrs?.[n]?1:t.length),0);if(e.args.length>=2&&n!==e.args.length)return o(t,`Function '${r?.name}' is defined with ${n} parameters, but is applied to ${e.args.length} arguments.`),F()}let a=e.args.length===1?B(e.args[0]):L(`$Tuple`,e.args.map(B),t);return L(`$FcnApply`,[n,a],t)}case`FieldAccess`:{let r=B(e.record),i=K(n,e);return L(`$RcdSelect`,[r,te(e.field,J(n,i.end))],t)}case`Product`:return L(`$CartesianProd`,e.factors.map(B),t);case`BoxAction`:case`AngleAction`:return L(e.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[B(e.action),B(e.subscript)],t);case`WeakFairness`:case`StrongFairness`:return L(e.kind===`WeakFairness`?`$WF`:`$SF`,[B(e.subscript),B(e.action)],t);case`Label`:return ke(e);case`Subexpression`:return oe(e)}},Oe=(e,t,r)=>{let i=ce(e),a=t;return{bounded:i.map(e=>{let t=K(n,e[0].set),r=e.flatMap(e=>e.pattern.kind===`Name`?[e.pattern.name]:e.pattern.names),i=yr(n,a,t.start,r);return a=t.end+1,r.map((e,t)=>M(e,0,J(n,i[t]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},ke=e=>{let t=T(e),r=_.at(-1);if(r===void 0)return o(t,`Label not in definition or proof step.`),F();if(x.isDeclared.slice(2,x.depth+1).some(Boolean))return o(t,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),F();if(h.length>0&&g.length>0)return o(t,`Labels inside EXCEPT clauses are not yet implemented.`),F();y();let i=B(e.body),s=b(),c=yr(n,K(n,e).start,K(n,e.body).start,e.params),u=e.params.map((t,r)=>{let i=Dr(a,t);if(i?.kind===`FormalParam`)return i;let s=J(n,c[r]);return o(s,`Illegal parameter ${t} of label \`${e.name}'.`),M(t,0,s,!1)}),d={...W(l()),kind:`Label`,name:e.name,params:u,body:i,labels:s,isAssumeProve:!1,location:t},f=/* @__PURE__ */ new Set;if(u.forEach(e=>{f.has(e)&&o(t,`Repeated formal parameter ${e.name} \nin label \`${d.name}'.`),f.add(e)}),r.params.flat().forEach(e=>{f.delete(e)||o(t,`Label ${d.name} must contain formal parameter \`${e.name}'.`)}),f.size>0){let e=[...f].map(e=>`${e.name} `).join(``);o(t,`Label ${d.name} declares extra parameter(s) ${e}`)}r.labels.has(d.name)?o(t,`Duplicate label \`${d.name}'.`):r.labels.set(d.name,d);let p=x.goal;return p&&C.set(d,{scope:p,clause:x.goalClause}),d},Ae=(e,t,r)=>{let i=t.start;return e.params.map(e=>{let t=e.location?cr(n,e.location):be(i,e.name),a=ct(t,e.arity);i=a.end+1;let o=e.arity===1&&G(n,t+1,`_`);return M(o?n.tokens[t].spelling??e.name:Sr(e.name),e.arity,q(n,a),r)})},je=e=>{let t=E(e.location);return e.isLocal&&!G(n,t.start,`LOCAL`)&&G(n,t.start-1,`LOCAL`)?{start:t.start-1,end:t.end}:t},Me=(e,t)=>{let r=je(e),i=q(n,r),s=Sr(e.name),l={start:e.isLocal?r.start+1:r.start,end:r.end},u=j(Rn(),()=>{let t=Ae(e,l,!0),n=Dr(a,s);if(n?.kind===`OpDef`&&n.inRecursive&&!n.isDefined){let e=n.params?.length===t.length&&t.every(e=>e.arity===0);n.letInLevel===c.curLevel?(e||o(i,`Definition of ${n.name} has different arity than its RECURSIVE declaration.`),n.params=t):o(i,`Recursive operator ${s} defined at wrong LET/IN level.`)}else n!==void 0&&o(i,`Operator ${s} already defined or declared.`);return y(),{params:t,body:B(e.body),existing:n}}),f=b(),p=u.existing,m=u.params,h=vr(n,r.start);if(p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined&&p.letInLevel===c.curLevel){p.weights=m.map(()=>0),p.maxLevels=m.map(()=>3),p.isLeibnizArg=m.map(()=>!0),p.labels=f,Ne(p,u.body,i,h),D.definitions.push(p),t?.push(p);return}let g=N({name:s,params:m,body:u.body,isLocal:e.isLocal,location:i,preComments:h,labels:f});d(a,g),ee(g),D.definitions.push(g),t?.push(g)},Ne=(e,t,n,r)=>{e.isDefined=!0,e.body=t,e.location=n,e.preComments=r,e.inRecursive&&(c.unresolvedCount[c.curLevel]--,c.unresolvedSum--)},Pe=(e,t)=>{let r=je(e),i=q(n,r),s=Rn(),l=e.isLocal?r.start+1:r.start,u=j(s,()=>le(e.bounds,l+1)),p=j(s,()=>Dr(a,e.name)),m=j(s,()=>M(e.name,0,i,p===void 0)),h=L(`$NonRecursiveFcnSpec`,[],i,{unbounded:[m],...u}),g=p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined,_=g&&p.letInLevel===c.curLevel;_?p.arity!==0&&o(i,`Function ${p.name} has operator arguments in its RECURSIVE declaration.`):g?o(i,`Recursive function ${e.name} defined at wrong LET/IN level.`):p!==void 0&&o(i,`Function name \`${e.name}' already defined or declared.`);let v=vr(n,r.start),x=p===void 0?N({name:e.name,params:[],body:h,isLocal:e.isLocal,location:i,preComments:v}):p.kind===`OpDef`&&(_||!g)?p:void 0;_?p.arity===0&&Ne(p,h,i,v):p===void 0&&x!==void 0&&(d(a,x),ee(x)),x!==void 0&&(D.definitions.push(x),t?.push(x)),f.unshift({name:e.name,node:h}),y();let S=()=>ue(u.bounded.flat(),e.body),C=x===void 0?S():j(s,S),w=b();x!==void 0&&(x.labels=w),f.shift(),h.operands=[C],h.operator.name===`$NonRecursiveFcnSpec`&&(h.unbounded=void 0)},Fe=[],Ie=e=>{c.unresolvedSum===0&&c.recursiveSectionCount++,c.unresolvedCount[c.curLevel]+=e.length,c.unresolvedSum+=e.length,e.forEach(e=>{let t=lt(e);l();let r=Array.from({length:e.arity},()=>M(``,0,void 0,!1)),i=N({name:Sr(e.name),params:r,location:q(n,t),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:c.recursiveSectionCount,letInLevel:c.curLevel});d(a,i),Fe.push(i),D.opDefsInRecursiveSection.push(i)})},Le=()=>{c.unresolvedCount[c.curLevel]!==0&&(Fe.filter(e=>e.letInLevel===c.curLevel&&!e.isDefined).forEach(e=>o(e.location,`Symbol ${e.name} declared in RECURSIVE statement but not defined.`)),c.unresolvedSum-=c.unresolvedCount[c.curLevel])},Re=(e,t,r)=>{l();let s=In(t.table).filter(e=>e.kind===`OpDecl`),c=s.flatMap(e=>{let t=Dr(a,e.name);if(t===void 0)return[];let n=e.declKind===3||e.declKind===2&&e.arity===0;return n&&ie(t,[],r),[{op:e,expr:n?P(t,[],r):ne(t,r),isImplicit:!0}]}),u=(e,t)=>{(t.kind===`OpArg`?Vn(t.op):0)!==e.arity&&o(t.location,`An operator must be substituted for symbol '${e.name}', and it must have arity ${e.arity}.`)},d=je(e),f=br(n,d.start,d.end,`WITH`)+1;return e.substitutions.forEach(e=>{let i=br(n,f,d.end,e.name);i!==-1&&(f=K(n,e.expression).end+1);let a=Hn(t,Sr(e.name));if(a?.kind!==`OpDecl`){o(i===-1?r:J(n,i),`Identifier '${i===-1?e.name:hr(n,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 s=a.arity===0?B(e.expression):me(e.expression,a);u(a,s);let l=c.find(e=>e.op.name===a.name);l&&!l.isImplicit?o(T(e.expression),`Multiple substitutions for symbol '${a.name}' in substitution.`):l?(l.expr=s,l.isImplicit=!1):c.push({op:a,expr:s,isImplicit:!1})}),c.filter(e=>e.isImplicit&&i.version!==`1.7.4`).forEach(e=>u(e.op,e.expr)),s.filter(e=>!c.some(t=>t.op.name===e.name)).forEach(e=>o(r,`Substitution missing for symbol ${e.name} declared at ${kn(e.location)} \nand instantiated in module ${D.name}.`)),c},V=(e,t,n,r,i,a=D)=>(An(n)&&o(i,e===`SubstIn`?`Substitution error, probably due to error
|
|
34
|
+
in module being instantiated.`:`Substitution error, probably due to error in module being instantiated.`),{...W(l()),kind:e,substs:t,body:n,instantiatingModule:a,instantiatedModule:r,location:i}),ze=(e,t,r)=>{let o=je(e),s=q(n,o),c=vr(n,o.start),u=e.name??``,f=Rn(),p=e.isLocal?o.start+1:o.start;e.params.length>0&&a.contexts.push(f);let m=Ae(e,{start:p,end:o.end},e.params.length>0),h=A(e.module),g=h.context,_=Re(e,g,s);e.params.length>0&&a.contexts.pop(),In(g.table).forEach(n=>{if(n.kind!==`OpDef`||n.isLocal||n.defKind!==`UserDefined`&&n.defKind!==`ModuleInstance`)return;let r=[...m,...n.params??[]],i=`${u}!${n.name}`,o=n.defKind===`UserDefined`?N({name:i,params:r,body:_.length>0&&n.body?V(`SubstIn`,_,n.body,h,s):n.body,isLocal:e.isLocal,location:s,source:n.source??n,preComments:c,labels:n.labels}):N({defKind:`ModuleInstance`,name:i,params:r,isLocal:e.isLocal,location:s,module:n.module,source:n.source??n,preComments:c});d(a,o),n.defKind===`UserDefined`&&ee(o),(t??D.definitions).push(o)}),In(g.table).forEach(n=>{if(n.kind!==`ThmOrAssumpDef`||n.isLocal)return;let r=_.length>0?V(`APSubstIn`,_,n.body,h,s):n.body,i={...W(l()),kind:`ThmOrAssumpDef`,name:`${u}!${n.name}`,isTheorem:n.isTheorem,body:r,params:[...m,...n.params],isLocal:e.isLocal,location:s,module:D,source:n.source??n,labels:n.labels,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]};d(a,i),(t??D.definitions).push(i)});let v={...W(l()),kind:`Instance`,name:u,isLocal:e.isLocal,params:m,module:h,substs:_,location:s};(r??D.topLevel).push(v);let y=N({defKind:`ModuleInstance`,name:u,params:m,isLocal:e.isLocal,location:s,preComments:c});d(a,y),i.version!==`1.7.4`&&t?.push(y)},Be=(e,t=!0,r)=>{let i=je(e),o=r??q(n,i),s=vr(n,i.start),c=A(e.module),u=c.context,f=Re(e,u,o),p=e.isLocal,m=jr(c);In(u.table).forEach(e=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`||e.isLocal)return;let t=(t,n)=>{let r=N({name:e.name,params:e.params,body:n,isLocal:p,location:o,module:t,source:e.source??e,preComments:s,labels:e.labels});return d(a,r),r},n=()=>(d(a,e),e),r=e.module===void 0||jr(e.module),i=m||r?p?t(e.module,e.body):n():t(D,e.body&&V(`SubstIn`,f,e.body,c,o));D.definitions.push(i),ee(i)}),In(u.table).forEach(e=>{if(e.kind!==`ThmOrAssumpDef`||e.isLocal)return;let n=(t,n)=>{let r={...e,...W(l()),body:n,isLocal:p,location:o,module:t,source:e.source??e};return d(a,r),r},r=m?p?n(e.module,e.body):(d(a,e),e):jr(e.module)?p?n(D,e.body):e:n(D,V(`APSubstIn`,f,e.body,c,o));t&&D.definitions.push(r)});let h={...W(l()),kind:`Instance`,name:void 0,isLocal:p,params:[],module:c,substs:f,location:o};return t&&D.topLevel.push(h),h},Ve=e=>{let t=k(e.name)??(e.name===D.name?D:void 0);return t===void 0?(o(J(n,cr(n,e.location)+1),`Module \`${e.name}' used without being extended or instantiated.`),[]):[t]},He=t=>t.flatMap(t=>{if(t.kind===`ModuleFact`)return Ve(t);let n=Yn(t);if(n===void 0||!Xn(n))return[B(t)];let r=z(t,0,!0,!1);if(r.kind===`ThmOrAssumpDef`)throw new e.F(`Expected a fact`);return[r]}),Ue=e=>G(n,e.start,`(`)&&ur(n,e.start)===e.end,We=e=>fr(n,K(n,e)),Ge=(e,t)=>We(e.args[0]).start===t.start?e.args.length===2?`N_InfixExpr`:`N_PostfixExpr`:n.tokens[t.start].kind===`Identifier`?`N_OpApplication`:`N_PrefixExpr`,Ke=(e,t)=>Ue(t)?`N_ParenExpr`:e.kind===`String`?hr(n,t.start):e.kind===`Apply`?Ge(e,t):Br.get(e.kind),qe=(e,t)=>{if(e.kind===`String`&&!Ue(t))return!1;if(e.kind===`Identifier`&&!e.name.includes(`!`))return!0;let n=Ke(e,t);return n===void 0||Vr.has(n)?void 0:!0},Je=(e,t)=>{let r=(e,t=We(e))=>({last:t,lastKind:Ke(e,t)});if(Ue(t))return{hasChildlessFirstChild:!1,...r(e,{start:t.start+1,end:t.end-1})};switch(e.kind){case`If`:case`BoxAction`:case`AngleAction`:return{hasChildlessFirstChild:!1,...r(e.kind===`If`?e.condition:e.action)};case`Tuple`:case`SetEnumeration`:{let i=e.elements[0];return i===void 0?{hasChildlessFirstChild:!1,last:{start:t.end,end:t.end},lastKind:n.tokens[t.end].text}:{hasChildlessFirstChild:!1,...r(i)}}case`Always`:case`Eventually`:case`Enabled`:case`Unchanged`:return{hasChildlessFirstChild:!0,...r(e.expression,{start:t.start+1,end:t.end})};case`Prime`:return{hasChildlessFirstChild:qe(e.expression,We(e.expression)),last:{start:t.end,end:t.end},lastKind:`N_GenPostfixOp`};case`FunctionApplication`:case`FieldAccess`:{let t=e.kind===`FunctionApplication`?e.function:e.record,r=We(t),i=r.end+1;return{hasChildlessFirstChild:qe(t,r),last:{start:i,end:i},lastKind:n.tokens[i].text}}case`Apply`:{let n=Ge(e,t);if(n===`N_OpApplication`)return e.operator.includes(`!`)?void 0:{hasChildlessFirstChild:!0,last:{start:t.start+1,end:t.end},lastKind:`N_OpArgs`};if(n===`N_PrefixExpr`)return{hasChildlessFirstChild:!0,...r(e.args[0],{start:t.start+1,end:t.end})};let i=We(e.args[0]),a=i.end+1;return{hasChildlessFirstChild:qe(e.args[0],i),last:{start:a,end:a},lastKind:n===`N_InfixExpr`?`N_GenInfixOp`:`N_GenPostfixOp`}}}},Ye=e=>{let t=fr(n,K(n,e));if((e.kind===`Identifier`||e.kind===`Subexpression`||e.kind===`OperatorReference`)&&!Ue(t))return!1;let r=Je(e,t);if(r?.hasChildlessFirstChild===void 0||r.lastKind===void 0)return!1;let i=q(n,r.last);return r.hasChildlessFirstChild&&o(q(n,t),`Was expecting a GeneralId.`),r.lastKind===`N_OpArgs`?o(i,"Selector `!(...)' should not have argument(s)."):(o(i,`Unexpected token found.`),o(i,`Need name or step number here, not \`${r.lastKind}'.`)),o(q(n,t),`DEF clause entry should describe a defined operator.`),!0},Xe=e=>e.flatMap(e=>{if(e.kind===`ModuleFact`)return Ve(e);if(Ye(e))return[];let t=z(e.kind===`OperatorReference`?{kind:`Identifier`,name:e.operator,location:e.location}:e,-1,!1,!0);return t.kind===`OpDef`||t.kind===`ThmOrAssumpDef`&&!t.name.startsWith(`<`)?[t]:(o(T(e),`DEF clause entry should describe a defined operator.`),[])}),Ze=(e,t)=>{e.isOnly||e.facts.length+e.defs.length>0||o(t,`Empty BY, USE, or HIDE`)},Qe=e=>{let t=q(n,E(e.location));Ze(e,t);let r=He(e.facts),i=Xe(e.defs);return r.length+i.length===0&&o(t,`Empty USE or HIDE statement.`),e.kind===`Hide`&&r.filter(e=>e.kind===`OpAppl`&&e.operator.kind!==`ThmOrAssumpDef`).forEach(e=>o(e.location,`The only expression allowed as a fact in a HIDE is
|
|
35
|
+
the name of a theorem, assumption, or step.`)),{...W(l()),kind:`UseOrHide`,facts:r,defs:i,isOnly:e.isOnly,isHide:e.kind===`Hide`,location:t}},$e=e=>{let t=E(e.location),r=e.set&&B(e.set),i=be(t.start,e.name),o=Cr[e.level],s={...W(l()),levelChecked:1,level:o.level,kind:`OpDecl`,name:Sr(e.name),arity:e.arity,declKind:o.declKind,location:q(n,ct(i,e.arity)),module:D};return d(a,s),{...W(l()),kind:`NewSymb`,declaration:s,set:r,location:q(n,t)}},et=(e,t,r)=>{let i=E(e.location),s=gr(n,i.start-1),c=K(n,e.conclusion).start,u=n.tokens.findLastIndex((e,t)=>t<c&&e.kind===`Keyword`&&e.text===`PROVE`),d=q(n,{start:s?i.start-1:i.start,end:i.start});s!==gr(n,u-1)&&o(d,s?`[]ASSUME matched by PROVE instead of []PROVE`:`ASSUME matched by []PROVE instead of PROVE`);let f=l();t>1&&a.contexts.push(Rn()),s&&a.contexts.some(e=>v.has(e))&&o(d,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),s||v.add(Er(a));let p={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};x.depth=t,x.isDeclared[t]=!1,t===1&&(x.goal=r&&p,x.goalClause=0);let m=e.assumptions.map((e,n)=>{let r=e.kind===`NewSymbol`,i=e.kind===`AssumeProve`?et(e,t+1):r?$e(e):B(e);return x.depth=t,r&&(x.isDeclared[t]=!0),p.isDeclaredBefore.push(p.isDeclaredBefore[n]||r),t===1&&x.goalClause++,i}),h=B(e.conclusion);t>1&&a.contexts.pop(),x.depth=t-1,t===1&&(x.goal=void 0);let g={...W(f),kind:`AssumeProve`,assumptions:m,goal:h,isSuffices:p.isSuffices,isBoxed:s,location:q(n,{start:s?i.start-1:i.start,end:i.end})};return S.set(g,p),g},tt=(e,t,n,r,i,a=!0)=>({...W(e),kind:`ThmOrAssumpDef`,name:t,isTheorem:a,body:n,params:[],isLocal:!1,location:r,module:D,source:void 0,labels:i,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]}),nt=e=>{let t=q(n,E(e.location));e.kind===`By`&&Ze(e,t);let r=e.kind===`By`?He(e.facts):[],i=e.kind===`By`?Xe(e.defs):[];return e.kind===`By`&&l(),e.kind===`By`&&r.length+i.length===0&&o(t,`Empty BY`),{...W(l()),kind:`LeafProof`,facts:r,defs:i,isOmitted:e.kind===`Omitted`,isOnly:e.kind===`By`&&e.isOnly,location:t}},rt=(e,t)=>{let r=e.body,i=q(n,t);switch(r.kind){case`Have`:return{node:L(`$Have`,[B(r.expression)],i),isPick:!1};case`Case`:return{node:L(`$Pfcase`,[B(r.expression)],i),isPick:!1};case`Witness`:return{node:L(`$Witness`,r.expressions.map(B),i),isPick:!1};case`Qed`:return{node:L(`$Qed`,[],i),isPick:!1};case`Take`:case`Pick`:{let e=r.kind===`Pick`,o=e?`$Pick`:`$Take`;e&&a.contexts.push(Rn());let s=e=>r.kind===`Pick`?[ue(e,r.body)]:[];if(r.bounds.length>0){let n=le(r.bounds,t.start),a=s(n.bounded.flat());return{node:L(o,a,i,n),isPick:e}}let c=yr(n,t.start,t.end+1,r.names),l=r.names.map((e,t)=>M(e,0,J(n,c[t]),!0)),u=s(l);return{node:L(o,u,i,{unbounded:l}),isPick:e}}}},it=e=>{if((e.kind===`And`||e.kind===`Or`)&&!e.isBulleted)return!0;if(e.kind!==`Apply`||e.args.length!==2)return!1;let t=fr(n,K(n,e.args[0])),r=K(n,e).start;return t.start===r&&!G(n,t.end+1,`(`)},at=t=>{if(t.kind!==`Steps`)return nt(t);let r=Rn();a.contexts.push(r);let i=[],s=[],c,u=(t,r,a)=>{if(t.kind===`Define`){let r=t.definitions.map(t=>{let n=[];t.kind===`Instance`?ze(t,n,i):t.kind===`Function`?Pe(t,n):Me(t,n);let r=n[t.kind===`Instance`?n.length-1:0];if(r?.kind!==`OpDef`)throw new e.F(`A DEFINE step defines no operator`);return r});return{...W(l()),kind:`DefStep`,defs:r,location:q(n,a)}}if(t.kind===`Use`||t.kind===`Hide`)return{...Qe(t),location:q(n,r)};if(t.kind===`Instance`)return Be(t,!1,q(n,a))},f=t.steps.map(t=>{let r=E(t.location),i=dr(n,t.head),f={start:i.start+1,end:i.end},p=t.body;t.name!==void 0&&/^<[*+]>/.test(t.token)&&o(J(n,r.start),`<*> and <+> cannot be used for a named step.`),t.name!==void 0&&y();let m=t.name===void 0?void 0:l();p.kind!==`Assert`&&(c=void 0);let h=u(p,r,f);if(h!==void 0)return t.name!==void 0&&d(a,N({defKind:`NumberedProofStep`,name:t.name,location:q(n,r),labels:b(),step:h})),h;let g=p.kind===`Assert`&&p.statement.kind===`AssumeProve`;g&&(c=void 0);let _=p.kind===`Assert`&&p.isSuffices,v=Rn(),x=p.kind===`Assert`?{node:(e=>{if(e.kind===`AssumeProve`){let n=j(v,()=>et(e,1,t.name===void 0?void 0:{isSuffices:_}));return n.isSuffices=_,n}if(_){let t=B(e);return L(`$Suffices`,[t],q(n,f))}let r=c!==void 0&&e.kind===`Apply`&&it(e)&&e.args[0].kind===`ExceptAt`,i=r?B(e.args[1]):void 0,a=r?P(re(e.operator,T(e)),[L(`$Nop`,[c],T(e.args[0])),i],T(e)):B(e),o=a.kind===`OpAppl`?a.operands[1]:void 0;return c=it(e)?o:void 0,a})(p.statement),isPick:!1}:rt(t,f);if(x===void 0)throw new e.F(`Unexpected proof step ${p.kind}`);let S=x.isPick?a.contexts.pop():void 0,C=t.name===void 0||m===void 0?void 0:tt(m,t.name,x.node,J(n,cr(n,t.location)),b());C&&d(a,C);let D=g&&!_;D&&a.contexts.push(v);let O=t.proof&&at(t.proof);return D&&a.contexts.pop(),w(x.node),g&&_&&(s.push(v),a.contexts.push(v)),S?.symbols.forEach(e=>d(a,e)),{...W(l()),kind:`Theorem`,definition:C,body:x.node,proof:O,isSuffices:_,location:q(n,r)}});return s.forEach(()=>{a.contexts.pop()?.symbols.forEach(e=>Bn(r,e))}),a.contexts.pop(),{...W(l()),kind:`NonLeafProof`,steps:f,instances:i,proofLevel:t.level,location:q(n,E(t.location))}},ot=e=>{let t=q(n,E(e.location)),r=e.statement,i=Rn();e.name!==void 0&&y();let o=e.name===void 0?void 0:l();r.kind===`AssumeProve`&&a.contexts.push(i);let s=r.kind===`AssumeProve`?et(r,1,e.name===void 0?void 0:{isSuffices:!1}):B(r),c=e.name===void 0||o===void 0?void 0:tt(o,e.name,s,t,b());c&&(r.kind===`AssumeProve`&&a.contexts.pop(),d(a,c),D.definitions.push(c),r.kind===`AssumeProve`&&a.contexts.push(i));let u=e.proof&&at(e.proof);r.kind===`AssumeProve`&&a.contexts.pop(),w(s);let f={...W(l()),kind:`Theorem`,definition:c,body:s,proof:u,isSuffices:!1,location:t};D.topLevel.push(f)},st=e=>{let t=E(e.location),r=q(n,t);e.name!==void 0&&y();let i=B(e.expression),o=e.name===void 0?void 0:tt(l(),e.name,i,r,b(),!1);o&&(d(a,o),D.definitions.push(o));let s={...W(l()),kind:`Assume`,definition:o,body:i,location:r};D.topLevel.push(s)},ct=(e,t)=>t===0?{start:e,end:e}:G(n,e,`_`)?{start:e,end:G(n,e+2,`_`)?e+2:e+1}:G(n,e+1,`(`)?{start:e,end:ur(n,e+1)}:{start:e,end:G(n,e+1,`_`)?e+1:e},lt=e=>ct(E(e.location).start,e.arity),ut=(e,t)=>{let r=lt(e);e.name===`@`&&t===3&&o(q(n,r),`Attempted to declare '@' as a variable.`);let i={...W(l()),levelChecked:1,level:+(t===3),kind:`OpDecl`,name:Sr(e.name),arity:e.arity,declKind:t,location:q(n,r),module:D};return t===2&&(i.levelParams.add(i),i.allParams.add(i)),d(a,i),i};t.extends.forEach(e=>{let t=A(e);D.extendees.push(t);let n=Er(a);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?Un(n,e.name):Hn(n,e.name);t===void 0?Bn(n,e):t!==e&&t.kind!==e.kind?o(e.location,`The ${kr(e)} of '${e.name}' conflicts with \nits ${kr(t)} at ${kn(t.location)}.`):t!==e&&!Ar(t,e)&&s(e.location,`Warning: the ${kr(t)} of '${e.name}' conflicts with \nits ${kr(t)} at ${kn(t.location)}.`)}),D.topLevel.push(...t.topLevel)});let dt=(e,t)=>{c.unresolvedSum!==0&&o(q(n,E(e)),`${t} may not appear within a recursive definition section.`)};return t.units.forEach(e=>{switch(e.kind){case`Variables`:dt(e.location,`A VARIABLE declaration`),e.declarations.forEach(e=>ut(e,3));break;case`Constants`:dt(e.location,`A declaration`),e.declarations.forEach(e=>ut(e,2));break;case`Recursive`:Ie(e.declarations);break;case`Definition`:e.definition.kind===`Function`?Pe(e.definition,void 0):Me(e.definition,void 0);break;case`Instance`:e.instance.name===void 0?Be(e.instance):ze(e.instance,void 0,void 0);break;case`Assumption`:dt(e.assumption.location,`An ASSUME`),st(e.assumption);break;case`Theorem`:dt(e.theorem.location,`A THEOREM`),ot(e.theorem);break;case`Use`:dt(e.use.location,`A USE or HIDE`),D.topLevel.push(Qe(e.use));break;case`Module`:{dt(e.module.location,`A MODULE `);let t={contexts:[...a.contexts,Rn()]},r=O(e.module,n,D,t),i=k(r.name);i===void 0?Bn(Er(a),r):i!==r&&o(r.location,`Multiply-defined module '${r.name}': this definition or declaration conflicts \nwith the one at ${kn(i.location)}.`);break}}}),Le(),D},k=v.map(e=>{i.onAnalyze?.(e),u=Array.from({length:4},l)[1];let t=_(e,void 0),n=Rn();f.toReversed().forEach(e=>Bn(n,e));let r=O(t.module,t.file,void 0,{contexts:[n]});return m.set(e,r),i.onModule?.(r,a),r});return{root:k[k.length-1],modules:k,messages:a}},Gr=(e,t,n,r)=>On(e.messages,{location:t,text:n,isWarning:!1,...r!==void 0&&!e.isTlc174&&{code:r}}),Y=(e,t)=>{for(let n of t)e.add(n)},Kr=(e,t,n)=>`${e.id}:${t}:${n.id}`,qr=(e,t,n,r)=>{e.set(Kr(t,n,r),{op:t,index:n,param:r})},Jr=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},Yr=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},Xr=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&Yr(e,r,t)})},Zr=(e,t)=>`${e.id}:${t}`,Qr=(e,t,n,r)=>{let i=Zr(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},$r=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&Qr(e,t.param,t.position,t.level)})},ei=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},ti=(e,t)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Xr(e.levelConstraints,t.levelConstraints),$r(e.argLevelConstraints,t.argLevelConstraints),Jr(e.argLevelParams,t.argLevelParams)},ni=(e,t)=>t.includes(e.op)||t.includes(e.param),ri=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,ii=e=>e.kind!==`Module`,ai=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,oi=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,si=(e,t)=>e.kind===`OpDef`?e.weights[oi(e,t)]??0:0,ci=(e,t)=>e.maxLevels[oi(e,t)]??3,li=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,ui=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[oi(e,t)]??!0:e.isLeibnizArg[t]??!0,di=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,fi=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],pi=(e,t)=>t.find(t=>t.op===e)?.expr,mi=(e,t,n)=>{let r=pi(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},hi=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=pi(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!ri(i.op))return;let a=i.op;mi(e.param,t,!1).forEach(t=>qr(n,a,e.index,t))}),n},gi=(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;mi(r,t,!1).forEach(e=>Yr(a,e,i))}),e.argLevelParams.forEach(e=>{let n=pi(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;X(n.op,r,i);let o=ci(n.op,e.index);mi(e.param,t,!1).forEach(e=>Yr(a,e,o))}),a},_i=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=pi(e.param,t);n===void 0?Qr(i,e.param,e.position,e.level):n.kind===`OpArg`&&ri(n.op)&&Qr(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=pi(e.param,t);if(a===void 0)return;let o=pi(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&ri(s)&&(X(a,n,r),Qr(i,s,e.index,a.level))}),i},vi=(e,t)=>Gn(e,3).length>0||(Di(e,t),Wn(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),yi=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(Zr(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(Kr(e,i,t))))),Y(e.levelParams,n.levelParams),Y(e.allParams,n.allParams),Y(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(Zr(t,n))}),Jr(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},bi=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>ci(t,o)&&(n&&X(a,r,i)&&Gr(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`||!ai(a.op)))return;let s=a.op;X(s,r,i);let c=Vn(s);for(let l=0;l<c;l++){let c=li(t,o,l);ci(s,l)>=c||(n&&X(a,r,i)&&Gr(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||!di(t,o,l,u)||n.level<=ci(s,u)||(X(a,r,i)&&X(n,r,i)&&Gr(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=X(n,r,i);n.level<=2||(o&&Gr(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${kn(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},xi=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);Xr(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&Xr(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>Xr(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=ci(t,r);n?.levelParams.forEach(t=>Yr(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!ai(n.op))return;let o=n.op;X(o,r,i);let s=Vn(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!di(t,a,r,i))continue;let s=ci(o,i);n?.levelParams.forEach(t=>Yr(e.levelConstraints,t,s)),!o.isLeibniz&&!ui(o,i)&&n&&Y(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&ai(n.op)&&(X(n.op,r,i),Yr(e.levelConstraints,t.param,ci(n.op,t.index)))}),$r(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&$r(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>$r(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!ri(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)Qr(e.argLevelConstraints,i,n,li(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&di(t,r,a,o)&&Qr(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(X(n,r,i),Qr(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&Jr(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>Jr(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):(X(a,r,i),a.levelParams.forEach(n=>qr(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&ri(a.op)&&qr(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!ri(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&di(t,r,a,o)&&n.levelParams.forEach(t=>qr(e.argLevelParams,i,o,t))})})},Si=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),Ci=(e,t)=>{let n=(n,r)=>{Gr(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=Si.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.`)})},wi=(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=>{X(r,t,n)||(e.levelCorrect=!1)}),e.ranges.forEach(r=>{X(r,t,n)||(e.levelCorrect=!1)});let i=e.operator;if(ai(i)){let r=X(i,t,n);bi(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&si(i,n)===1?Math.max(e,t.level):e,i.level),e.ranges.forEach(t=>{e.level=Math.max(e.level,t.level)}),Y(e.levelParams,i.levelParams),Y(e.allParams,i.allParams),Y(e.nonLeibnizParams,i.nonLeibnizParams),e.operands.forEach((t,n)=>{t!==void 0&&(si(i,n)===1&&Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),ui(i,n)||Y(e.nonLeibnizParams,t.allParams))}),e.ranges.forEach(t=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams)});let a=new Set(fi(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),xi(e,i,a,t,n)}else X(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)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),Xr(e.levelConstraints,t.levelConstraints),Qr(e.argLevelConstraints,i,n,t.level),$r(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>qr(e.argLevelParams,i,n,t)),Jr(e.argLevelParams,t.argLevelParams)});return Ci(e,n),e.levelCorrect},Ti=(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||X(e.step,t,n),e.levelCorrect;e.levelCorrect=X(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))}),yi(e,i,r),e.levelCorrect},Ei=(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=X(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)}),yi(e,e.params,e.body)),e.levelCorrect),Di=(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),Ti(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||Gr(t,e.location,`Argument ${r+1} of recursive operator ${e.name} is primed`)}),c=Math.max(c,e.level),Y(o,e.levelParams),Y(s,e.allParams))}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=2),e.level=Math.max(e.level,c),Y(e.levelParams,o),Y(e.allParams,s)}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=1),Ti(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(Di(e,t)));let a=Wn(e);return a.forEach(e=>i(Ti(e,1,t))),Kn(e).forEach(e=>i(Ei(e,1,t))),e.topLevel.forEach(e=>i(X(e,1,t))),vi(e,t)||Gn(e,2).forEach(t=>Yr(e.levelConstraints,t,0)),a.forEach(t=>{Xr(e.levelConstraints,t.levelConstraints),$r(e.argLevelConstraints,t.argLevelConstraints),Jr(e.argLevelParams,t.argLevelParams,e=>!ni(e,t.params??[]))}),e.topLevel.forEach(t=>{Xr(e.levelConstraints,t.levelConstraints),$r(e.argLevelConstraints,t.argLevelConstraints),Jr(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},Oi=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{ii(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=X(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),ti(e,t),Y(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),ki=(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&&Gr(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&Gr(t,e.body.location,`Non-constant CASE for temporal goal.`),ki(e.proof,t)):n===`$Qed`&&ki(e.proof,t)})},Ai=(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;Di(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(r.expr,t,n)||(e.levelCorrect=!1)});let i=vi(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(X(a.expr,t,n)&&Gr(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||Gr(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&&(X(i.expr,t,n)&&Gr(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=X(o,t,n);for(let t=0;t<i.op.arity;t++){let a=r.argLevelConstraints.get(Zr(i.op,t))?.level;a===void 0||ci(o,t)>=a||(s&&Gr(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=X(s,t,n);if(s.kind!==`OpDef`)return;let l=ci(s,i.index);o.expr.level<=l||(c&&X(o.expr,t,n)&&Gr(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 Xr(e.levelConstraints,gi(r,e.substs,i,t,n),a),e.substs.forEach(t=>Xr(e.levelConstraints,t.expr.levelConstraints,a)),$r(e.argLevelConstraints,_i(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>$r(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),Jr(e.argLevelParams,hi(r.argLevelParams,e.substs),t=>!ni(t,e.params)),e.substs.forEach(t=>Jr(e.argLevelParams,t.expr.argLevelParams,t=>!ni(t,e.params))),e.levelCorrect},X=(e,t,n)=>{if(!ii(e))return Di(e,n);switch(e.kind){case`OpAppl`:return wi(e,t,n);case`OpDef`:return Ti(e,t,n);case`ThmOrAssumpDef`:return Ei(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=X(r,t,n),r.kind===`Module`||(e.level=r.level,ei(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=>{X(r,t,n)||(e.levelCorrect=!1)}),X(e.body,t,n)||(e.levelCorrect=!1),e.instances.forEach(r=>{X(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),Xr(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>Xr(e.levelConstraints,t.levelConstraints)),$r(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>$r(e.argLevelConstraints,t.argLevelConstraints)),Jr(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];Jr(e.argLevelParams,t.argLevelParams,e=>!ni(e,n))}),e.instances.forEach(t=>Jr(e.argLevelParams,t.argLevelParams)),e.levelCorrect}case`Label`:{if(e.levelChecked>=t)return!0;e.levelChecked=t,e.params.forEach(e=>X(e,t,n));let r=X(e.body,t,n);return e.level=e.body.level,ei(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;X(i,t,n),e.level=i.level;let a=[i];for(let i of r.slice(1))if(i!==void 0){if(X(i,t,n),i===e.component)break;e.level=Math.max(e.level,i.level),a.push(i)}return a.forEach(t=>ti(e,t)),!0}case`SubstIn`:case`APSubstIn`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.body;X(r,t,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(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=>Y(e.levelParams,mi(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>Y(e.allParams,mi(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),Y(e.allParams,t.expr.allParams),Y(e.nonLeibnizParams,t.expr.nonLeibnizParams),e.nonLeibnizParams.has(t.op)&&(e.nonLeibnizParams.delete(t.op),Y(e.nonLeibnizParams,t.expr.allParams)))}));let i=vi(e.instantiatedModule,n);return e.levelConstraints=gi(r,e.substs,i,t,n),e.argLevelConstraints=_i(r,e.substs,t,n),e.argLevelParams=hi(r.argLevelParams,e.substs),e.levelCorrect}case`Instance`:return Ai(e,t,n);case`Assume`:{if(e.levelChecked>=t)return!0;e.levelChecked=t;let r=X(e.body,t,n),i=!e.definition||X(e.definition,t,n);return e.level=e.body.level,ei(e,e.body),e.level!==0&&Gr(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=Oi(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&&Gr(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&ki(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return Oi(e,e.facts,t,n);case`NonLeafProof`:return Oi(e,[...e.steps,...e.instances],t,n);case`DefStep`:return Oi(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=X(e.set,t,n),e.level=Math.max(e.level,e.set.level),e.level===3&&(e.levelCorrect=!1,Gr(n,e.location,`Level error:
|
|
36
|
+
Temporal formula used as set.`)),ei(e,e.set)),e.levelCorrect;case`AssumeProve`:return e.levelChecked>=t||(e.levelChecked=t,e.levelCorrect=!0,e.assumptions.forEach(r=>{X(r,t,n)||(e.levelCorrect=!1)}),X(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=>ti(e,t)),e.levelCorrect&&e.levelParams.forEach(t=>{t.kind===`OpDecl`&&t.declKind===2&&Yr(e.levelConstraints,t,2)})),e.levelCorrect}},ji=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[]}},Mi=/* @__PURE__ */ new Map([[`Integers`,`Int`],[`Naturals`,`Nat`],[`Reals`,`Reals`]]),Ni=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&&Mi.get(e)===t.name||n(t))return!0}}return ji(e).some(n)};return n(e)},Pi=e=>e.operands.filter(e=>e?.kind===`OpAppl`),Fi=e=>{let t=e.operands[0];return t?.kind===`String`?t:void 0},Ii=e=>JSON.stringify([e.operands.length,...Pi(e).map(e=>Fi(e)?.value).sort()]),Li=(e,t=/* @__PURE__ */ new Set)=>(e.extendees.forEach(e=>{t.has(e)||(t.add(e),Li(e,t))}),t),Ri=e=>{let t=e.records.map(t=>({domain:Ii(t),warnings:Pi(t).flatMap(t=>{let n=Fi(t),r=n&&Hn(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 ${kn(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[...[...Li(e)].flatMap(e=>e.records),...e.records].forEach(e=>{let t=Ii(e);n.has(t)&&!r.has(t)&&Pi(e).some(Ni)&&r.add(t)}),t.flatMap(e=>r.has(e.domain)?[]:e.warnings)},zi=e=>`${kn(e.location)}\n\n${e.text}`,Bi=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=>`${zi(e)}\n\n\n`),n.length>0?`*** Warnings: ${n.length}\n\n`:``,...n.map(e=>`${zi(e)}\n\n\n`)].join(``)},Vi=4802,Hi=/* @__PURE__ */ new Set([`FiniteSets`,`Sequences`,`Bags`,`Naturals`,`Integers`,`Reals`,`RealTime`,`Randomization`,`TLC`]),Ui=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))},Wi=n=>{try{return t.H(_r(n))}catch(t){if(t instanceof e.F)return;throw t}},Gi=(e,n)=>n===`1.7.4`&&t.tn(e)!==void 0?void 0:Wi(e)?.name,Ki=(n,r,o={})=>{let s=(0,i.basename)(n,`.tla`),c=t.st(o.version),l=o.fileName??s,u=(0,a.existsSync)(n)?(0,a.readFileSync)(n,`utf8`):c.get(s),d=[],f=e=>{d.push(e),o.onPrint?.(e)},p=e=>f(`${e}\n`),m=o.version===`1.7.4`,h=m&&o.isXmlExport,g=e=>{o.isXmlExport||p(e)},_=o.describeFile,v=/* @__PURE__ */ new Map([[s,(0,a.existsSync)(n)?`file`:`standard`]]),y=!1,b=[],x=!1,S=!1,C=Ct(Ie(),p),w=/* @__PURE__ */ new Map,T=[],E=()=>T.splice(0).forEach(e=>e.isError?o.onPrintError?.(`${e.text}\n`):p(e.text)),D=e=>{let t=w.get(e),n=t?.module.location.range;if(t===void 0||n===void 0)return;let r=t.text.split(/\r\n|\r|\n/),i=wn(C,r.slice(n.start.line-1,n.end.line),o.version),a=i.has(`TLA_DIVERGENCE_EXISTS`),s=i.has(`PCAL_DIVERGENCE_EXISTS`),c=a===s?void 0:`The ${a?`TLA+ translation`:`PlusCal algorithm`} in module ${e} has changed since its last translation.`;if(m){let t=a&&s?`The PlusCal algorithm and its TLA+ translation in module ${e} filename since the last translation.`:c;t===void 0?i.has(`ERROR_ENCOUNTERED`)&&T.push({text:`A unexpected problem was encountered attempting to validate the specification for ${e}`,isError:!0}):T.push({text:`!! WARNING: ${t}`,isError:!1});return}let l=a&&s?`Both the PlusCal algorithm and its TLA+ translation in module ${e} have changed since the last translation.`:c??(i.has(`ERROR_ENCOUNTERED`)?`An unexpected problem was encountered attempting to validate the specification for ${e}`:void 0);if(l===void 0)return;let u=!i.has(`ERROR_ENCOUNTERED`)||a||s;b.some(e=>e.text===l)||b.push({location:e,text:l,isWarning:u})},O=(e,t)=>{if(o.isXmlExport||w.has(e))return;let n=Wi(t);if(n===void 0||n.name!==e)return;let r=[...w.values()].filter(t=>Ui(t.module).includes(e));w.set(e,{text:t,module:n}),r.forEach(()=>D(e)),Ui(n).filter(t=>t!==e&&w.has(t)).forEach(D)},k=()=>{if(E(),x)return;x=!0;let e=b.filter(e=>e.isWarning);e.length>0&&(g(`Warnings (${e.length}) during syntax parsing of ${l}:\n\n`),e.forEach(e=>g(`${zi(e)}\n\n\n`))),e.length!==b.length&&(p(Bi(b)),y=!0,S=!0)},A=e=>{let n=c.get(e),i=r(e),a=i===void 0&&n===void 0&&u!==void 0&&!m?t.B(u,e):void 0,o=i??a;return v.set(e,i===void 0?a===void 0?`standard`:`root file`:`file`),o!==void 0&&O(e,o),o??n},j=(()=>{try{if(u===void 0)throw new e.M(`Cannot find source file for module ${l}`,void 0);return O(s,u),Wr(u,A,{rootFileName:s,rootFilePath:o.isXmlExport?`${l.replace(/\.tla$/,``)}.tla`:void 0,version:o.version,rootExtendees:o.rootExtendees,onParse:e=>{_&&p(`Parsing file ${_(e,v.get(e)??`file`)}`),e===s&&D(s),E()},onAnalyze:e=>{k(),(_||h)&&!S&&p(`Semantic processing of module ${e}`)},onModule:(e,t)=>{if(S||(t.every(e=>e.isWarning)&&Di(e,{messages:t,isTlc174:m}),t.length===0))return;if(t.some(e=>!e.isWarning)&&(y=!0),m)return p(`Semantic errors:\n\n${Bi(t)}`);let n=t.filter(e=>e.isWarning);n.length>0&&(g(`*** Warnings: ${n.length}\n`),n.forEach(e=>g(`${zi(e)}\n\n\n`)));let r=t.filter(e=>!e.isWarning);r.length!==0&&(p(`Semantic errors:\n\n*** Errors: ${r.length}\n`),r.forEach(e=>p(`${zi(e)}\n\n`)))}})}catch(t){if(y=!0,t instanceof e.c){p(`\nFatal errors while parsing TLA+ spec in file ${l}\n`),p(t.message),p(Bi(b));return}if(!(t instanceof e.M))throw t;let n={location:t.location,text:t.message,isWarning:!1},r=m&&t.parseError?.includes(` and token "" `);if(t.parseError!==void 0&&!r&&!h&&p(t.parseError),p(`\nFatal errors while parsing TLA+ spec in file ${l}\n`),r){p(`java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null`);return}if(m){p(`tla2sany.semantic.AbortException`),f(`*** Abort messages: 1\n\n${zi(n)}\n\n\n`);return}p(zi(n)),p(Bi(x?[n]:[...b,n]))}})();if(j!==void 0&&k(),j!==void 0&&!y&&!o.isXmlExport&&!m){let e=j.modules.filter(e=>!Hi.has(e.name));_&&e.forEach(e=>p(`Linting of module ${e.name}`));let t=o.suppressedCodes?.includes(Vi)?[]:e.flatMap(Ri),n=o.errorCodes?.includes(Vi)?`Warning treated as error: `:``;t.forEach(e=>p(`${n}${zi(e)}\n\n\n`)),n&&t.length>0&&(y=!0)}return{text:d.join(``),isFailed:y,specification:S?void 0:j}},qi=e=>e.kind===`OpDef`&&e.defKind!==`BuiltIn`&&e.defKind!==`ModuleInstance`,Ji=(e,t)=>e.context.symbols.find(e=>qi(e)&&e.name===t),Yi=t=>e.it(new e.b(`Parsing or semantic analysis failed.Parsing or semantic analysis failed.${t}`),e.tt.specParseError),Xi=(n,r,i,a,o)=>{let s=r.replace(`__DebuggerExpr__`,`__DebuggerModule__`),c=`---- MODULE ${s} ----\nEXTENDS ${n}\n\n${r} == ${i}\n====`,l=e=>Yi(`Unknown location\n\n${e} while parsing breakpoint expression "${i}"`);try{t.V(c)}catch(t){throw t instanceof e.F?Yi(`Syntax error while parsing breakpoint expression "${i}"`):t}let u=!1,d=!1,f=(()=>{try{return Wr(c,a,{version:o,onModule:(e,t)=>{let n=()=>t.every(e=>e.isWarning);if(!n())return;let r=Di(e,{messages:t,isTlc174:o===`1.7.4`});e.name===s&&(u=!0,d=r&&n())}})}catch(t){throw t instanceof e.F?l(`Semantic error`):t}})();if(!u)throw l(`Semantic error`);if(!d)throw l(`Level-checking error`);let p=Ji(f.root,r)?.level??0;if(p===3)throw Yi(`Unknown location\n\nDebug expressions must be action-level or below; actual level: ${p} (Temporal)`);return p},Zi=(e,n,r,i,a)=>{let o=Date.now(),s=r.map((e,t)=>({expression:e.expression,name:Ji(n,e.expression)?e.expression:`__DebuggerExpr__${o+t}`})),c=s.map(e=>e.name),l=s.filter(e=>e.name!==e.expression);if(l.length===0)return{names:c,source:e};let u=t=>t===n.name?e:i(t),d=n.context.symbols.find(e=>e.kind===`OpDecl`&&e.declKind===3),f=l.map(e=>{let t=`${e.name} == `;return Xi(n.name,e.name,e.expression,u,a)===0&&d?`${e.name} ==\nLET ${e.name}State == ${d.name} IN\n${` `.repeat(t.length)}${e.expression}`:`${t}${e.expression}`}),p=e.split(`
|
|
37
37
|
`),m=(t.V(e).location.range?.end.line??p.length)-1,h=p[m].search(/={4,}/);return{names:c,source:[...p.slice(0,m),p[m].slice(0,h),...f,p[m].slice(h),...p.slice(m+1)].join(`
|
|
38
|
-
`)}},$i=[[-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]],ea=[[4003,4005],[4200,4206],[4220,4224],[4240,4247],[4260,4262],[4270,4275],[4290,4294],[4310,4315],[4330,4337],[4350,4357]],ta=/* @__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`]]),na=(e,t,n)=>({module:e,constant:n,operators:[{kind:`postcondition`,operator:t}]}),ra={json:na(`_JsonTrace`,`_JsonTrace`,`_JsonTraceFile`),tla:na(`_TLAPlusCounterExample`,`_TLAPlusCounterExample`,`_TLAPlusCounterExampleFile`),tlc:na(`_TLCTrace`,`_TLCTrace`,`_TLCTraceFile`),tlcplain:na(`_TLCTracePlain`,`_TLCTrace`,`_TLCTraceFile`),tlctespec:na(`_TLCTESpec`,`_TLCTrace`,`_TLCTraceFile`),tlcaction:na(`_TLCActionTrace`,`_TLCTrace`,`_TLCTraceFile`),dot:na(`_DotTrace`,`_DotTrace`,`_DotTraceFile`)},ia=(e,t)=>({module:e,constant:`${t}InputFile`,operators:[{kind:`constraint`,operator:`${t}Constraint`},{kind:`view`,operator:`${t}View`}]}),aa={tlc:ia(`_TLCTrace`,`_TLCTrace`),json:ia(`_JsonTrace`,`_JsonTrace`)},oa=(e,t)=>e.some(e=>t>=e[0]&&t<=e[1]),sa=(e,t)=>{if(e===``)return[e];let n=e.split(t);for(;n.at(-1)===``;)n.pop();return n},ca=(e,t)=>[...new Set(e.filter(e=>t.includes(e)))].sort((e,t)=>e-t),la=(e,t)=>{if(!/^[+-]?\d+$/.test(e))return;let n=BigInt(e);return BigInt.asIntN(t,n)===n?n:void 0},ua=e=>/^[+-]?(NaN|Infinity|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?[fFdD]?)$/.test(e.trim())?Number.parseFloat(e.trim().replace(/[fFdD]$/,``)):void 0,da=()=>({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,isUsage:!1,invariants:[],moduleOperators:[]}),fa={"-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}},pa=e=>{let t=da(),n=0,r=e=>({error:e,isTool:t.isTool}),i=()=>({error:`java.lang.ArrayIndexOutOfBoundsException: Index ${e.length} out of bounds for length ${e.length}`,isTool:t.isTool,isUncaught:!0}),o={tlc:[],sany:[]},c={tlc:[],sany:[]},l=()=>e[n],u=()=>e[n++],d=(e,t,i)=>{let a=l();if(a===void 0)return r(t);let o=la(a,e);return o===void 0?r(`${i} But encountered ${a}`):(n++,o)};for(;n<e.length;){let f=u();if(Object.hasOwn(fa,f))fa[f](t);else if(f===`-simulate`||f===`-generate`){t.mode=f===`-generate`?`generate`:`simulate`;let e=l();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=la(e,64),t.traceCount===void 0)return{error:`java.lang.NumberFormatException: For input string: "${e}"`,isTool:t.isTool,isUncaught:!0}}if(t.traceCount===void 0&&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(f===`-suppressMessages`||f===`-messagesAsErrors`){let e=u();if(e===void 0)return r(`Error: ${f} requires a comma-separated list of message codes.`);let t=f===`-suppressMessages`?o:c;for(let n of sa(e,`,`)){let e=n.replace(/^[^!-\uffff]+|[^!-\uffff]+$/g,``),i=la(e,32);if(i===void 0)return r(`Error: For input string: "${e}"`);let a=Number(i);if(oa($i,a))t.tlc.push(a);else{if(!ta.has(a)&&!oa(ea,a))return r(`Error: unknown message code: ${a}`);if(t===o&&!ta.has(a))return r(`Error: code ${a} is an error and cannot be suppressed.`);t.sany.push(a)}}}else if(f===`-inv`){let e=u();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(f===`-teSpecOutDir`){let e=u();if(e===void 0)return r(`Error: expected a path for -teSpecOutDir option.`);t.traceSpecPath=e}else if(f===`-userFile`){let e=u();if(e===void 0)return r(`Error: need to specify the full qualified file.`);try{(0,a.closeSync)((0,a.openSync)(e,`w`))}catch{return r(`Error: Failed to create user output log file.`)}t.userFile=e}else if(f===`-invlevel`){let e=u();if(e===void 0)return i();if(la(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(f===`-debugger`){let e=l();e!==void 0&&[`port=`,`nosuspend`,`nohalt`,`suspend`,`halt`].some(t=>e.includes(t))&&n++}else if(f===`-generateSpecTE`)t.isTraceSpecForced=!0,l()===`nomonolith`&&n++;else if(f===`-noGenerateSpecTE`||f.toLowerCase()===`-note`)t.isTraceSpecDisabled=!0;else if(f===`-noGenerateSpecTEBin`||f.toLowerCase()===`-notebin`)t.isTraceBinaryDisabled=!0;else{if(f===`-help`||f===`-h`)return{...t,isUsage:!0};if(f===`-lncheck`){let e=u();if(e===void 0)return r(`Error: expect a strategy such as final for -lncheck option.`);t.livenessCheck=e.toLowerCase()}else if(f===`-config`){let e=u();if(e===void 0)return r(`Error: expect a file name for -config option.`);let n=e.replace(/\.cfg$/,``);t.configPath=n.endsWith(`.tla`)?n:`${n}.cfg`}else if(f===`-dump`){let i=l();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(f.toLowerCase()===`-loadtrace`||f.toLowerCase()===`-dumptrace`){let i=f.toLowerCase()===`-loadtrace`?`-loadTrace`:`-dumpTrace`;if(n+1>=e.length)return r(i===`-loadTrace`?`Error: A format and a file name for loading traces required.`:`Error: A format and a file name for dumping traces required.`);let a=u(),o=u(),s=i===`-loadTrace`?aa:ra;if(!Object.hasOwn(s,a.toLowerCase()))return r(`Error: Unknown format ${a} given to ${i}.`);let c=s[a.toLowerCase()];t.moduleOperators.push(...c.operators.map(e=>({...e,module:c.module,constants:{[c.constant]:o}})))}else if(f.toLowerCase()===`-postcondition`){let e=u();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=sa(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(f===`-coverage`||f===`-checkpoint`){let e=f.slice(1),n=d(32,e===`coverage`?`Error: coverage report interval required.`:`Error: checkpoint interval required.`,e===`coverage`?`Error: An integer for coverage report interval required.`:`Error: An integer for checkpoint interval is required.`);if(typeof n!=`bigint`)return n;let i=BigInt.asIntN(32,n*60000n);if(i<0n)return r(`Error: expect a nonnegative integer for -${e} option.`);e===`coverage`&&(t.coverage=Number(i)/6e4)}else if(f===`-depth`){let e=d(32,`Error: trace length required.`,`Error: An integer for trace length required.`);if(typeof e!=`bigint`)return e;t.traceDepth=Number(e)}else if(f===`-seed`){let e=d(64,`Error: seed required.`,`Error: An integer for seed required.`);if(typeof e!=`bigint`)return e;t.seed=e}else if(f===`-aril`){let e=d(64,`Error: aril required.`,`Error: An integer for aril required.`);if(typeof e!=`bigint`)return e;t.aril=e}else if(f===`-maxSetSize`){let e=l(),n=d(32,`Error: maxSetSize required.`,`Error: An integer for maxSetSize required.`);if(typeof n!=`bigint`)return n;if(n<1n)return r(`Error: Value in interval [0, 2147483647] for maxSetSize required. But encountered ${e}`);t.maxSetSize=Number(n)}else if(f===`-recover`||f===`-metadir`){let e=u();if(e===void 0)return r(f===`-recover`?`Error: need to specify the metadata directory for recovery.`:`Error: need to specify the metadata directory.`);f===`-metadir`&&(t.metadir=e),f===`-recover`&&(t.recoverDirectory=e)}else if(f===`-workers`){let e=u();if(e===void 0)return r(`Error: expect an integer or 'auto' for -workers option.`);let n=e.trim().toLowerCase()===`auto`?BigInt((0,s.availableParallelism)()):la(e,32);if(n===void 0)return r(`Error: worker number or 'auto' required. But encountered ${e}`);if(n<1n)return r(`Error: at least one worker required.`);t.workers=Number(n)}else if(f===`-dfid`){let e=u(),n=e===void 0?void 0:la(e,32);if(e!==void 0&&n===void 0)return r(`Error: expect a nonnegative integer for -dfid option. But encountered ${e}`);if(n===void 0||n<0n)return r(`Error: expect a nonnegative integer for -dfid option.`);t.dfidDepth=Number(n)}else if(f===`-fp`){let e=d(32,`Error: expect an integer for -fp option.`,`Error: A number for -fp is required.`);if(typeof e!=`bigint`)return e;if(e<0n||e>=131)return r(`Error: The number for -fp must be between 0 and 130 (inclusive).`);t.fingerprintIndex=Number(e)}else if(f===`-fpmem`){let e=u();if(e===void 0)return r(`Error: fpset memory size required.`);let t=ua(e);if(t===void 0||t<0)return r(`Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered ${e}`);t>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.
|
|
39
|
-
`)}else if(f===`-fpbits`){let e=l(),t=d(32,`Error: fpbits required.`,`Error: An integer for fpbits required.`);if(typeof t!=`bigint`)return t;if(t<0n||t>30n)return r(`Error: Value in interval [0, 30] for fpbits required. But encountered ${e}`)}else{if(f.startsWith(`-`))return r(`Error: unrecognized option: ${f}`);t.specs.push(f)}}}if(!t.isWarningEnabled&&o.tlc.length+o.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 f=
|
|
38
|
+
`)}},Qi=[[-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]],$i=[[4003,4005],[4200,4206],[4220,4224],[4240,4247],[4260,4262],[4270,4275],[4290,4294],[4310,4315],[4330,4337],[4350,4357]],ea=/* @__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`]]),ta=(e,t,n)=>({module:e,constant:n,operators:[{kind:`postcondition`,operator:t}]}),na={json:ta(`_JsonTrace`,`_JsonTrace`,`_JsonTraceFile`),tla:ta(`_TLAPlusCounterExample`,`_TLAPlusCounterExample`,`_TLAPlusCounterExampleFile`),tlc:ta(`_TLCTrace`,`_TLCTrace`,`_TLCTraceFile`),tlcplain:ta(`_TLCTracePlain`,`_TLCTrace`,`_TLCTraceFile`),tlctespec:ta(`_TLCTESpec`,`_TLCTrace`,`_TLCTraceFile`),tlcaction:ta(`_TLCActionTrace`,`_TLCTrace`,`_TLCTraceFile`),dot:ta(`_DotTrace`,`_DotTrace`,`_DotTraceFile`)},ra=(e,t)=>({module:e,constant:`${t}InputFile`,operators:[{kind:`constraint`,operator:`${t}Constraint`},{kind:`view`,operator:`${t}View`}]}),ia={tlc:ra(`_TLCTrace`,`_TLCTrace`),json:ra(`_JsonTrace`,`_JsonTrace`)},aa=(e,t)=>e.some(e=>t>=e[0]&&t<=e[1]),oa=(e,t)=>{if(e===``)return[e];let n=e.split(t);for(;n.at(-1)===``;)n.pop();return n},sa=(e,t)=>[...new Set(e.filter(e=>t.includes(e)))].sort((e,t)=>e-t),ca=(e,t)=>{if(!/^[+-]?\d+$/.test(e))return;let n=BigInt(e);return BigInt.asIntN(t,n)===n?n:void 0},la=e=>/^[+-]?(NaN|Infinity|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?[fFdD]?)$/.test(e.trim())?Number.parseFloat(e.trim().replace(/[fFdD]$/,``)):void 0,ua=()=>({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,isUsage:!1,invariants:[],moduleOperators:[]}),da={"-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}},fa=e=>{let t=ua(),n=0,r=e=>({error:e,isTool:t.isTool}),i=()=>({error:`java.lang.ArrayIndexOutOfBoundsException: Index ${e.length} out of bounds for length ${e.length}`,isTool:t.isTool,isUncaught:!0}),o={tlc:[],sany:[]},c={tlc:[],sany:[]},l=()=>e[n],u=()=>e[n++],d=(e,t,i)=>{let a=l();if(a===void 0)return r(t);let o=ca(a,e);return o===void 0?r(`${i} But encountered ${a}`):(n++,o)};for(;n<e.length;){let f=u();if(Object.hasOwn(da,f))da[f](t);else if(f===`-simulate`||f===`-generate`){t.mode=f===`-generate`?`generate`:`simulate`;let e=l();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=ca(e,64),t.traceCount===void 0)return{error:`java.lang.NumberFormatException: For input string: "${e}"`,isTool:t.isTool,isUncaught:!0}}if(t.traceCount===void 0&&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(f===`-suppressMessages`||f===`-messagesAsErrors`){let e=u();if(e===void 0)return r(`Error: ${f} requires a comma-separated list of message codes.`);let t=f===`-suppressMessages`?o:c;for(let n of oa(e,`,`)){let e=n.replace(/^[^!-\uffff]+|[^!-\uffff]+$/g,``),i=ca(e,32);if(i===void 0)return r(`Error: For input string: "${e}"`);let a=Number(i);if(aa(Qi,a))t.tlc.push(a);else{if(!ea.has(a)&&!aa($i,a))return r(`Error: unknown message code: ${a}`);if(t===o&&!ea.has(a))return r(`Error: code ${a} is an error and cannot be suppressed.`);t.sany.push(a)}}}else if(f===`-inv`){let e=u();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(f===`-teSpecOutDir`){let e=u();if(e===void 0)return r(`Error: expected a path for -teSpecOutDir option.`);t.traceSpecPath=e}else if(f===`-userFile`){let e=u();if(e===void 0)return r(`Error: need to specify the full qualified file.`);try{(0,a.closeSync)((0,a.openSync)(e,`w`))}catch{return r(`Error: Failed to create user output log file.`)}t.userFile=e}else if(f===`-invlevel`){let e=u();if(e===void 0)return i();if(ca(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(f===`-debugger`){let e=l();e!==void 0&&[`port=`,`nosuspend`,`nohalt`,`suspend`,`halt`].some(t=>e.includes(t))&&n++}else if(f===`-generateSpecTE`)t.isTraceSpecForced=!0,l()===`nomonolith`&&n++;else if(f===`-noGenerateSpecTE`||f.toLowerCase()===`-note`)t.isTraceSpecDisabled=!0;else if(f===`-noGenerateSpecTEBin`||f.toLowerCase()===`-notebin`)t.isTraceBinaryDisabled=!0;else{if(f===`-help`||f===`-h`)return{...t,isUsage:!0};if(f===`-lncheck`){let e=u();if(e===void 0)return r(`Error: expect a strategy such as final for -lncheck option.`);t.livenessCheck=e.toLowerCase()}else if(f===`-config`){let e=u();if(e===void 0)return r(`Error: expect a file name for -config option.`);let n=e.replace(/\.cfg$/,``);t.configPath=n.endsWith(`.tla`)?n:`${n}.cfg`}else if(f===`-dump`){let i=l();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(f.toLowerCase()===`-loadtrace`||f.toLowerCase()===`-dumptrace`){let i=f.toLowerCase()===`-loadtrace`?`-loadTrace`:`-dumpTrace`;if(n+1>=e.length)return r(i===`-loadTrace`?`Error: A format and a file name for loading traces required.`:`Error: A format and a file name for dumping traces required.`);let a=u(),o=u(),s=i===`-loadTrace`?ia:na;if(!Object.hasOwn(s,a.toLowerCase()))return r(`Error: Unknown format ${a} given to ${i}.`);let c=s[a.toLowerCase()];t.moduleOperators.push(...c.operators.map(e=>({...e,module:c.module,constants:{[c.constant]:o}})))}else if(f.toLowerCase()===`-postcondition`){let e=u();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=oa(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(f===`-coverage`||f===`-checkpoint`){let e=f.slice(1),n=d(32,e===`coverage`?`Error: coverage report interval required.`:`Error: checkpoint interval required.`,e===`coverage`?`Error: An integer for coverage report interval required.`:`Error: An integer for checkpoint interval is required.`);if(typeof n!=`bigint`)return n;let i=BigInt.asIntN(32,n*60000n);if(i<0n)return r(`Error: expect a nonnegative integer for -${e} option.`);e===`coverage`&&(t.coverage=Number(i)/6e4)}else if(f===`-depth`){let e=d(32,`Error: trace length required.`,`Error: An integer for trace length required.`);if(typeof e!=`bigint`)return e;t.traceDepth=Number(e)}else if(f===`-seed`){let e=d(64,`Error: seed required.`,`Error: An integer for seed required.`);if(typeof e!=`bigint`)return e;t.seed=e}else if(f===`-aril`){let e=d(64,`Error: aril required.`,`Error: An integer for aril required.`);if(typeof e!=`bigint`)return e;t.aril=e}else if(f===`-maxSetSize`){let e=l(),n=d(32,`Error: maxSetSize required.`,`Error: An integer for maxSetSize required.`);if(typeof n!=`bigint`)return n;if(n<1n)return r(`Error: Value in interval [0, 2147483647] for maxSetSize required. But encountered ${e}`);t.maxSetSize=Number(n)}else if(f===`-recover`||f===`-metadir`){let e=u();if(e===void 0)return r(f===`-recover`?`Error: need to specify the metadata directory for recovery.`:`Error: need to specify the metadata directory.`);f===`-metadir`&&(t.metadir=e),f===`-recover`&&(t.recoverDirectory=e)}else if(f===`-workers`){let e=u();if(e===void 0)return r(`Error: expect an integer or 'auto' for -workers option.`);let n=e.trim().toLowerCase()===`auto`?BigInt((0,s.availableParallelism)()):ca(e,32);if(n===void 0)return r(`Error: worker number or 'auto' required. But encountered ${e}`);if(n<1n)return r(`Error: at least one worker required.`);t.workers=Number(n)}else if(f===`-dfid`){let e=u(),n=e===void 0?void 0:ca(e,32);if(e!==void 0&&n===void 0)return r(`Error: expect a nonnegative integer for -dfid option. But encountered ${e}`);if(n===void 0||n<0n)return r(`Error: expect a nonnegative integer for -dfid option.`);t.dfidDepth=Number(n)}else if(f===`-fp`){let e=d(32,`Error: expect an integer for -fp option.`,`Error: A number for -fp is required.`);if(typeof e!=`bigint`)return e;if(e<0n||e>=131)return r(`Error: The number for -fp must be between 0 and 130 (inclusive).`);t.fingerprintIndex=Number(e)}else if(f===`-fpmem`){let e=u();if(e===void 0)return r(`Error: fpset memory size required.`);let t=la(e);if(t===void 0||t<0)return r(`Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered ${e}`);t>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.
|
|
39
|
+
`)}else if(f===`-fpbits`){let e=l(),t=d(32,`Error: fpbits required.`,`Error: An integer for fpbits required.`);if(typeof t!=`bigint`)return t;if(t<0n||t>30n)return r(`Error: Value in interval [0, 30] for fpbits required. But encountered ${e}`)}else{if(f.startsWith(`-`))return r(`Error: unrecognized option: ${f}`);t.specs.push(f)}}}if(!t.isWarningEnabled&&o.tlc.length+o.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 f=sa(o.tlc,c.tlc),p=f.length>0?f.map(String):sa(o.sany,c.sany).map(e=>ea.get(e)??String(e));return p.length>0?r(`Error: The following codes were set to both -suppressMessages and -messagesAsErrors: [${p.join(`, `)}]`):(t.suppressedCodes=[...o.tlc,...o.sany],t.errorCodes=[...c.tlc,...c.sany],t)},pa=[{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
|
|
40
40
|
behavior is to halt on first violation`,isOptional:!0},{name:`-coverage`,sampleValue:`minutes`,description:`interval between the collection of coverage information;
|
|
41
41
|
if not specified, no coverage will be collected`,isOptional:!0},{name:`-deadlock`,description:`if specified DO NOT CHECK FOR DEADLOCK. Setting the flag is
|
|
42
42
|
the same as setting CHECK_DEADLOCK to FALSE in config
|
|
@@ -117,20 +117,20 @@ terminates. The optional parameter 'port=1274' makes the
|
|
|
117
117
|
debugger listen on port 1274 instead of on the standard
|
|
118
118
|
port 4712, and 'port=0' lets the debugger choose a port.
|
|
119
119
|
Multiple optional parameters must be comma-separated.
|
|
120
|
-
Specifying '-debugger' implies '-workers 1'.`,isOptional:!1,subOptions:`nosuspend`},{name:`SPEC`,isOptional:!1}],
|
|
121
|
-
starting with an initial depth of 'num'`,isOptional:!0},{name:`-view`,description:`apply VIEW (if provided) when printing out states`,isOptional:!0}],[...
|
|
120
|
+
Specifying '-debugger' implies '-workers 1'.`,isOptional:!1,subOptions:`nosuspend`},{name:`SPEC`,isOptional:!1}],ma=[[...pa,{name:`-dfid`,sampleValue:`num`,description:`run the model check in depth-first iterative deepening
|
|
121
|
+
starting with an initial depth of 'num'`,isOptional:!0},{name:`-view`,description:`apply VIEW (if provided) when printing out states`,isOptional:!0}],[...pa,{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
|
|
122
122
|
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
|
|
123
123
|
comma delimited: 'num=X' where X is the maximum number of
|
|
124
124
|
total traces to generate and/or 'file=Y' where Y is the
|
|
125
125
|
absolute-pathed prefix for trace file modules to be written
|
|
126
126
|
by the simulation workers; for example Y='/a/b/c/tr' would
|
|
127
|
-
produce, e.g, '/a/b/c/tr_1_15'`,isOptional:!1,subOptions:`file=X,num=Y`}]],
|
|
127
|
+
produce, e.g, '/a/b/c/tr_1_15'`,isOptional:!1,subOptions:`file=X,num=Y`}]],ha=[`When using the '-generateSpecTE' you can version the generated specification by doing:
|
|
128
128
|
./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
|
|
129
129
|
CONSTANT declaration and you've previous used 'integers' as model values, rename your
|
|
130
130
|
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
|
|
131
131
|
duplicate operator definitions, this is likely due to the 'monolith' specification
|
|
132
132
|
creation. Try re-running TLC adding the 'nomonolith' option to the '-generateSpecTE'
|
|
133
|
-
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.`],
|
|
133
|
+
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.`],ga=e=>`\u001b[1m${e}\u001b[0m`,_a=e=>`\u001b[3m${e}\u001b[0m`,va=e=>e.name.startsWith(`-`)&&!e.name.startsWith(`--`),ya=(e,t)=>e.name<t.name?-1:+(e.name>t.name),ba=e=>e.subOptions===void 0?``:` [${e.subOptions}]`,xa=e=>{let t=[...e].sort(ya),n=t.filter(e=>e.sampleValue===void 0&&e.isOptional&&va(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)=>va(e)===va(t)?ya(e,t):va(e)?-1:1);return[ga(`TLC`),...r===``?[]:[`[${ga(`-${r}`)}]`],...n.filter(e=>e.name.length!==2).map(e=>`[${ga(e.name)}${ba(e)}]`),...t.filter(e=>e.sampleValue===void 0&&e.isOptional&&e.name.startsWith(`--`)).map(e=>`[${ga(e.name)}${ba(e)}]`),...t.filter(e=>e.sampleValue!==void 0&&e.isOptional).map(e=>`[${ga(e.name)} ${e.subOptions===void 0?``:`[${e.subOptions}] `}${_a(e.sampleValue??``)}]`),...t.filter(e=>e.sampleValue!==void 0&&!e.isOptional).map(e=>`${ga(e.name)} ${_a(e.sampleValue??``)}`),...i.map(e=>`${e.name}${ba(e)}`)].join(` `)},Sa=()=>(/* @__PURE__ */ new Date()).toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).*$/,`Version $1.$2.$3.$4$5$6`),Ca=()=>{let e=[...new Map(ma.flat().map(e=>[e.name,e])).values()].sort(ya).filter(e=>e.sampleValue!==void 0||e.isOptional||va(e)),t=(e,t)=>e.replace(/\r\n|\r|\n/g,`\n${t}`);return[``,`${ga(`NAME`)}\n`,`\tTLC - provides model checking and simulation of TLA+ specifications - ${Sa()}\n\n`,`${ga(`SYNOPSIS`)}\n`,...ma.map(e=>`\t${xa(e)}`),``,`${ga(`DESCRIPTION`)}\n`,`\t${t(`The model checker (TLC) provides the functionalities of model checking
|
|
134
134
|
or simulation of TLA+ specifications. It may be invoked from the command
|
|
135
135
|
line, or via the model checking functionality of the Toolbox.
|
|
136
136
|
|
|
@@ -139,19 +139,19 @@ approach for the state space exploration.
|
|
|
139
139
|
|
|
140
140
|
A pretty-printed and in-depth description of TLC can be found at:
|
|
141
141
|
|
|
142
|
-
https://lamport.azurewebsites.net/tla/current-tools.pdf`.replace(/TLC(\)|\s|$)/g,`${
|
|
143
|
-
`)},
|
|
144
|
-
`},
|
|
145
|
-
`: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`,
|
|
146
|
-
`;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`},
|
|
147
|
-
are best checked with coverage and cost statistics disabled).`):i(t.zt.coverageEnd,`End of statistics.`)},
|
|
148
|
-
`)),
|
|
142
|
+
https://lamport.azurewebsites.net/tla/current-tools.pdf`.replace(/TLC(\)|\s|$)/g,`${ga(`TLC`)}$1`),` `)}`,``,`${ga(`OPTIONS`)}\n`,...e.map(e=>`\t${ga(e.name)}${e.sampleValue===void 0?``:` ${_a(e.sampleValue)}`}\n\t\t${t(e.description??``,` `)}`),``,`${ga(`TIPS`)}\n`,...ha.map(e=>`\t${t(e,` `)}\n`)].join(`
|
|
143
|
+
`)},wa=async t=>{let n=(await Promise.resolve().then(()=>require("./compile.cjs"))).compile((0,a.readFileSync)(t,`utf8`),t),r=`\\* Generated by tla-ts from ${(0,i.basename)(t)}. Edit ${(0,i.basename)(t)} instead.`,o=(0,i.join)((0,i.dirname)(t),`${n.name}.tla`),s=(0,i.join)((0,i.dirname)(t),`${n.name}.cfg`);for(let n of[o,s])if((0,a.existsSync)(n)&&!(0,a.readFileSync)(n,`utf8`).startsWith(r))throw new e.L(`${n} already exists, and tla-ts didn't generate it from ${t}`);return(0,a.writeFileSync)(o,`${r}\n${n.source}\n`),(0,a.writeFileSync)(s,`${r}\n${n.config}\n`),o},Ta={success:e.tt.success,"assumption-violation":e.tt.assumptionViolation,deadlock:e.tt.deadlock,"invariant-violation":e.tt.safetyViolation,"property-violation":e.tt.safetyViolation,"liveness-violation":e.tt.livenessViolation,"postcondition-violation":e.tt.assumptionViolation,error:e.tt.error},Ea=t=>{if((0,a.statSync)(t,{throwIfNoEntry:!1})?.isDirectory())throw new e.b(`${t} (Is a directory)`)},Da=(e,t)=>e.endsWith(t)?e:`${e}${t}`,Oa=e=>{if(e.length===1)return{path:Da(e[0],`.dump`)};let t=e[0].toLowerCase();return{path:Da(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`)}},ka=(e,n)=>e.print(t.zt.computingInitProgress,t.Bt.none,`Computed ${n} initial states...`),Aa=(e,n)=>e===`invariant-violation`?{code:t.zt.invariantViolatedInitial,text:`Invariant ${n} is violated by the initial state:`}:{code:t.zt.propertyViolatedInitial,text:`Property ${n} is violated by the initial state:`},ja=(e,n)=>n?.forEach(n=>{if(typeof n==`string`)return console.log(n);if(n.kind===`initial-states-progress`)return ka(e,n.count);let r=Aa(n.status,n.name);e.print(r.code,t.Bt.error,`${r.text}\n${t.Et(n.state)}`)}),Ma={code:t.zt.behaviorUpToThisPoint,text:`The behavior up to this point is:`},Na=(n,r,i=Ma,a=!1,o=i!==Ma)=>{r.length>0&&n.print(i.code,t.Bt.error,i.text);try{r.forEach((e,i)=>{(i>0||a)&&ja(n,e.output);let s=n.isDiffTrace&&i>0&&(o||i<r.length-1);n.print(t.zt.statePrint2,t.Bt.state,`${i+1}: <${e.label??e.action??`Initial predicate`}>\n${t.Et(e.state,s?r[i-1].state:void 0)}`)})}catch(r){if(!(r instanceof e.g))throw r;n.print(t.zt.general,t.Bt.error,r.message)}},Pa={code:t.zt.counterExample,text:`The following behavior constitutes a counter-example:
|
|
144
|
+
`},Fa=(e,t)=>t===`1.7.4`||e.length===0?`Temporal properties were violated.
|
|
145
|
+
`: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`,Ia=e=>e.filter((t,n)=>t!==e[n-1]).map((e,n)=>`${n}) ${t.K(e)}\n`).toReversed().join(``),La=e=>{if(e.length===0)return` The error call stack is empty.
|
|
146
|
+
`;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`},Ra=(e,n)=>{let r=n.generated,i=n.distinct,a=t.Wt(/* @__PURE__ */ new Date);r===i?e.print(t.zt.initGenerated1,t.Bt.none,`Finished computing initial states: ${i} distinct state${i===1?``:`s`} generated at ${a}.`):e.print(t.zt.initGenerated2,t.Bt.none,`Finished computing initial states: ${r} state${r===1?``:`s`} generated, with ${i} of them distinct at ${a}.`)},za=(e,n,r)=>{let i=Math.max(Date.now()-(r??0),1)/6e4,a=e=>e.toLocaleString(`en-US`),o=(e,t)=>r===void 0?``:` (${a(Math.floor(e/i))} ${t}/min)`;e.print(t.zt.progress,t.Bt.none,`Progress(${Math.max(n.depth,1)}) at ${t.Wt(/* @__PURE__ */ new Date)}: ${a(n.generatedStates)} states generated${o(n.generatedStates,`s`)}, ${a(n.distinctStates)} distinct states found${o(n.distinctStates,`ds`)}, ${a(n.queuedStates)} states left on queue.`)},Ba={init:t.zt.coverageInit,next:t.zt.coverageNext,invariant:t.zt.coverageProperty,implied:t.zt.coverageProperty,constraint:t.zt.coverageConstraint},Va=(e,n,r)=>{let i=(n,r)=>e.print(n,t.Bt.none,r);i(t.zt.coverageStart,`The coverage statistics at ${t.Wt(/* @__PURE__ */ new Date)} (see https://explain.tlapl.us/module-coverage-statistics for how to interpret the following statistics).`),n.variables.forEach(e=>i(t.zt.coverageVariable,`<${e.label}>: ${e.distinct}`)),n.relations.forEach(e=>{let n=Ba[e.kind];i(n,n===t.zt.coverageProperty?`<${e.label}>`:`<${e.label}>: ${e.distinct}:${e.generated}`),e.expressions.forEach(e=>{let n=` ${`|`.repeat(e.depth)}${e.location}`;e.cost>0?i(t.zt.coverageValueCost,`${n}: ${e.count}:${e.cost}`):i(t.zt.coverageValue,`${n}: ${e.count}`)})}),Date.now()-r>3e5?i(t.zt.coverageEndOverhead,`End of statistics (please note that for performance reasons large models
|
|
147
|
+
are best checked with coverage and cost statistics disabled).`):i(t.zt.coverageEnd,`End of statistics.`)},Ha=(e,t)=>(0,i.join)(e,`${t}.class`),Ua=(e,n,r,a)=>{let s=e.print;switch(n.kind){case`parsed`:r.isParsed=!0,e.isTool&&s(t.zt.sanyFinished,t.Bt.none,`SANY finished.`),s(t.zt.starting,t.Bt.none,`Starting... (${t.Wt(/* @__PURE__ */ new Date)})`);return;case`constant-level-invariant`:if(e.version===`1.7.4`)return;s(t.zt.constantLevelInvariant,t.Bt.warning,`The invariant ${n.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;s(t.zt.stateLevelProperty,t.Bt.warning,`The formula ${n.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 ${n.name} holds in all states of every behavior, use INVARIANT ${n.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${n.name} changes it into a temporal formula, asserting that ${n.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`);return;case`liveness-initializing`:n.isSymmetric&&s(t.zt.livenessSymmetry,t.Bt.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.`),n.isConstrained&&e.version===`1.7.4`&&s(t.zt.livenessConstraints,t.Bt.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`:s(t.zt.temporalBranches,t.Bt.none,`Implied-temporal checking--satisfiability problem has ${n.branches} branches.`);return;case`java-override`:{let e=(0,o.pathToFileURL)((0,i.resolve)(Ha(a,n.module))).href;s(n.isMatched?t.zt.javaOverrideLoaded:t.zt.javaOverrideMismatch,n.isMatched?t.Bt.none:t.Bt.warning,`${n.isMatched?`Loading`:`Failed to match`} ${n.operator} operator override from ${e.replace(`file:///`,`file:/`)} with signature: <Java Method: ${n.signature}>.`);return}case`initial-states-started`:s(t.zt.computingInit,t.Bt.none,`Computing initial states...`);return;case`initial-states-progress`:ka(e,n.count);return;case`initial-states-computed`:Ra(e,n.initialStates);return;case`progress`:za(e,n.statistics,r.startTime),n.statistics.coverage&&Va(e,n.statistics.coverage,r.startTime);return;case`liveness-started`:{r.livenessStartTime=Date.now(),n.isComplete&&za(e,n.statistics);let i=n.branches>1?`${n.branches} branches of `:``,a=n.branches*n.states;s(t.zt.checkingTemporal,t.Bt.none,`Checking ${i}temporal properties for the ${n.isComplete?`complete`:`current`} state space with ${a} total distinct states at (${t.Wt(/* @__PURE__ */ new Date)})`);return}case`liveness-finished`:Wa(e,r);return;case`sequential-fallback`:process.stderr.write(`Warning: the search ordered the string ${JSON.stringify(n.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`:s(n.code,t.Bt.warning,n.text);return;case`violation`:Ka(n.status,n.violation,e)}},Wa=(e,n)=>{n.livenessStartTime!==void 0&&(e.print(t.zt.checkingTemporalEnd,t.Bt.none,`Finished checking temporal properties in ${t.Gt(Date.now()-n.livenessStartTime)} at ${t.Wt(/* @__PURE__ */ new Date)}`),n.livenessStartTime=void 0)},Ga=(e,n)=>{n&&(n.counts&&console.log(n.counts),e.print(n.code,t.Bt.error,t.Ht(n.code,n.message,e.isTool)))},Ka=(e,n,r)=>{let i=r.print,a=n.name,o=n.loopStart,s=o===void 0&&n.trace.length===1&&(e===`invariant-violation`||e===`liveness-violation`),c={code:t.zt.temporalPropertyViolated,text:Fa(n.properties??[a],r.version)},l={success:void 0,error:void 0,"assumption-violation":n.message?{code:t.zt.assumptionEvaluationError,text:t.Ht(t.zt.assumptionEvaluationError,`Evaluating assumption ${a} failed.\n${n.message}`,r.isTool)}:{code:t.zt.assumptionFalse,text:`Assumption ${a} is false.`},deadlock:{code:t.zt.deadlockReached,text:`Deadlock reached.`},"invariant-violation":s?Aa(`invariant-violation`,a):{code:t.zt.invariantViolatedBehavior,text:`Invariant ${a} is violated.`},"property-violation":c,"liveness-violation":o===void 0?s?Aa(`liveness-violation`,a):{code:t.zt.actionPropertyViolatedBehavior,text:`Action property ${a} is violated.`}:c,"postcondition-violation":{code:n.postcondition?.code??t.zt.general,text:t.Ht(n.postcondition?.code??t.zt.general,n.message??`Postcondition ${a} is false.`,r.isTool)}}[e],u=e===`property-violation`,d=o!==void 0&&!u,f=u||d,p=f&&r.version!==`1.7.4`;if(p&&ja(r,n.trace[0]?.output),n.counts&&console.log(n.counts),l){let e=s?`${l.text}\n${t.Et(n.trace[0].state)}`:l.text;i(l.code,t.Bt.error,e)}if(s||(f||ja(r,n.trace[0]?.output),Na(r,n.trace,f?Pa:void 0,f&&!p)),ja(r,n.traceOutput),d){let e=n.loopLabel;o===n.trace.length-1?i(t.zt.statePrint3,t.Bt.state,`${o+2}: Stuttering`):r.isTool?i(t.zt.backToState,t.Bt.state,`${o+1}: Back to state${e?`: <${e}>\n`:``}`):console.log(`Back to state ${o+1}${e?`: <${e}>\n`:``}`)}n.warning&&r.version!==`1.7.4`&&i(n.warning.code,t.Bt.warning,n.warning.text);let m=n.unwitnessed??(e===`postcondition-violation`?void 0:n.postcondition);return ja(r,n.postconditionOutput),Ga(r,m),!s&&e!==`assumption-violation`},qa=(e,n)=>e.print(t.zt.nestedExpression,t.Bt.error,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${La(n)}`),Ja=(e,n,r)=>e.print(t.zt.success,t.Bt.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 = ${t.l(n)}`,...r===void 0?[]:[` based on the actual fingerprints: val = ${t.l(r)}`]].join(`
|
|
148
|
+
`)),Ya=(e,n)=>{switch(n.kind){case`message`:e.print(n.code,n.isError?t.Bt.error:t.Bt.none,e.isTool?n.toolMessage:n.message);return;case`behavior`:n.states.forEach((r,i)=>n.isInvariant?e.print(t.zt.statePrint2,t.Bt.state,`${i+1}: \n${t.Et(r,e.isDiffTrace?n.states[i-1]:void 0)}`):e.print(t.zt.statePrint1,t.Bt.state,`${i+1}:\n${t.Et(r)}`));return;case`nested-expressions`:qa(e,n.callStack);return;case`success`:Ja(e,n.optimistic,n.actual)}},Xa=(n,r,i)=>{let a=r.print;if(n.failure){let i=n.failure,o=r.isTool?i.toolMessage:i.message,s=()=>{let e=i.fingerprint;if(e){let n=i.callStack?.length&&r.version!==`1.7.4`?La(i.callStack):Ia(e.sources);a(t.zt.fingerprintFailed,t.Bt.error,`TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${n}\nReason:\n${t.Ut(e.reason,r.isTool)}`)}else i.callStack&&qa(r,i.callStack)};i.isCallStackFirst&&s();let c=i.initialState&&(()=>{try{return`While working on the initial state:\n${t.Et(i.initialState)}`}catch(t){throw t instanceof e.b?e.it(new e.b(`${e.G}${t.message}`),e.tt.error):t}})();a(c?t.zt.initialState:i.code,t.Bt.error,c?`${o}\n${c}`:o),ja(r,i.trace[0]?.output),Na(r,i.trace);let l=i.traceFailure;l&&a(l.code,t.Bt.error,r.isTool?l.toolMessage:l.message),ja(r,i.traceOutput),Ga(r,i.postcondition),i.isCallStackFirst||s()}else if(n.violation){if(!Ka(n.status,n.violation,r))return;let e=n.additionalViolation;e&&Ka(`property-violation`,e,r),n.liveCallStack&&qa(r,n.liveCallStack)}else n.status===`success`&&(Wa(r,i),Ja(r,t.f(n.distinctStates,n.generatedStates),n.fingerprintDistance===void 0?void 0:t.u(n.fingerprintDistance)));if(n.failure?.isWithoutStatistics)return;n.status!==`success`&&Wa(r,i),n.coverage&&Va(r,n.coverage,i.startTime),r.isTool&&za(r,n,i.startTime),a(t.zt.stats,t.Bt.none,`${n.generatedStates} states generated, ${n.distinctStates} distinct states found, ${n.queuedStates} states left on queue.`);let o=r.version===`1.7.4`,s=o?n.outDegrees??n.violationOutDegrees:n.outDegrees;(!o||s)&&a(t.zt.searchDepth,t.Bt.none,`The depth of the complete state graph search is ${o?Math.max(n.depth,1):n.depth}.`);let c=s&&t.p(s);c&&a(t.zt.stateGraphOutdegree,t.Bt.none,c)},Za=e=>t.bt([e]).toString(),Qa=(e,t,n,r,o)=>{let c=n.temporaryDirectory??(0,s.tmpdir)(),l=(0,a.existsSync)(c)?(0,a.realpathSync)(c):(0,i.resolve)(c),u=(0,i.join)(l,`tlc-${Za((0,i.resolve)(e))}`),d=C(n);return(n,s)=>{let c=`${n}.tla`;if(s===`file`)return(0,a.realpathSync)(p(t,n)??e);if(o===`1.7.4`)return(0,i.join)(l,c);if(s===`root file`){let t=r===void 0?l:(0,i.resolve)(r),o=(0,a.realpathSync)(e);return`${(0,i.join)(t,Za(`${o} ${n}`),c)} (${o})`}let f=(0,i.join)(u,c);return d===void 0?f:`${f} (${g(d)}${c})`}},$a=e=>e.print(t.zt.version,t.Bt.none,`TLC2 Version ${w} (rev: tla-ts)`),eo=(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`
|
|
149
149
|
`;let i=n.findIndex((e,t)=>t>r&&e.startsWith(`====`));return`${n.slice(r+1,i===-1?void 0:i).join(`
|
|
150
|
-
`).trim()}\n`},
|
|
151
|
-
`),r(t.zt.statePrint1,t.Bt.state,`:\n${t.Et(i.state)}`);return}case`progress`:{let i=n.statistics;if(e.isTool){ao(e,i);return}let a=i.levelM2/(i.traces+1);r(t.zt.simulationProgress,t.Bt.none,`Progress: ${i.generatedStates} states checked, ${i.traces} traces generated (trace length: mean=${i.levelMean}, var(x)=${Math.round(a)}, sd=${Math.round(Math.sqrt(a))})`);return}case`summary`:e.isTool&&ao(e,n.statistics),r(t.zt.simulationStats,t.Bt.none,`The number of states generated: ${n.statistics.generatedStates}\nSimulation using seed ${n.statistics.seed} and aril ${n.statistics.aril}`)}},ao=(e,n)=>e.print(t.zt.simulationProgress,t.Bt.none,`Progress(${n.traces}) at ${t.Wt(/* @__PURE__ */ new Date)}: ${n.generatedStates} states generated, -1 distinct states found, -1 states left on queue.`),oo=e=>e.replace(/\/+/g,`/`).replace(/(.)\/$/,`$1`),so=e=>{let t=oo(e),n=t.lastIndexOf(`/`);return n===-1?`.`:t.slice(0,Math.max(n,1))},co=(e,t)=>e.endsWith(`/`)?`${e}${t}`:`${e}/${t}`,lo=(e,t,n,r)=>{if(t===`1.7.4`||!e.isTraceSpecForced&&(e.isTraceSpecDisabled||e.isTool||e.isContinued||(0,i.basename)(n).includes(`_TTrace`)))return;let a=e.traceSpecPath,o=`${(0,i.basename)(n)}_TTrace_${Math.floor(r/1e3)}`,s=a===void 0?{directory:so(n),module:o}:a.toLowerCase().endsWith(`.tla`)?{directory:so(a),module:(0,i.basename)(a).replace(/\.tla$/,``)}:{directory:oo(a),module:o};return{...s,traceFile:e.isTraceBinaryDisabled?void 0:co(s.directory,`${s.module}.bin`)}},uo={ENOENT:`No such file or directory`,ENOTDIR:`Not a directory`,EISDIR:`Is a directory`,EACCES:`Permission denied`},fo=(t,n)=>{try{(0,a.writeFileSync)(t,n)}catch(n){let r=n instanceof Error&&`code`in n?uo[String(n.code)]:void 0;throw r===void 0?n:new e.b(`${t} (${r})`)}},po=e=>{try{(0,a.mkdirSync)(e,{recursive:!0})}catch{}},mo=e=>{let t=/* @__PURE__ */ new Date,n=(e,t=2)=>String(e).padStart(t,`0`),r=`${n(t.getFullYear()%100)}-${n(t.getMonth()+1)}-${n(t.getDate())}-${n(t.getHours())}-${n(t.getMinutes())}-${n(t.getSeconds())}.${n(t.getMilliseconds(),3)}`,o=(0,i.join)(e.metadir??`states`,r);return(0,a.mkdirSync)(o,{recursive:!0}),o},ho=async(r,o,s,c,l)=>{let u=o.livenessCheck,d=l.version;eo(l);let f=o.recoverDirectory;if(f!==void 0)throw(0,a.existsSync)((0,i.join)(f,`vars.chkpt`))?new e.x(`tla-ts can't recover a model check from the checkpoint in ${f}.`):new e.E(f);ro(l,o);let p=o.configPath??r.replace(/\.tla$/,`.cfg`);if(!(0,a.existsSync)(p))return l.print(t.zt.configFileError,t.Bt.error,`TLC encountered the following error when trying to read the configuration file ${p}:\nFile not found.`),e.tt.configParseError;let g=(0,i.basename)(r,`.tla`),y={startTime:Date.now(),livenessStartTime:void 0,isParsed:!1},b=()=>{let e=Date.now()-y.startTime;l.print(t.zt.finished,t.Bt.none,`Finished in ${l.isTool?`${e}ms`:t.Gt(e)} at (${t.Wt(/* @__PURE__ */ new Date)})`)},x=()=>l.print(t.zt.parsingFailed,t.Bt.error,`Parsing or semantic analysis failed.`),w=t=>(t instanceof e.F?x():v(t,l),b(),_(t)),T=(()=>{try{let e=(0,a.readFileSync)(p,`utf8`);return t.$t(p.endsWith(`.tla`)?to(e,p.replaceAll(`.tla`,``)):e,d)}catch(t){if(!(t instanceof e._))throw t;return t}})();if(T instanceof e._&&d===`1.7.4`)return l.print(t.zt.general,t.Bt.error,`${e.$(`tlc2.tool.ConfigFileException`)}${t.Ut(T.message,l.isTool)}`),b(),e.tt.error;if(T instanceof e._)return w(T);o.isDeadlockChecked||(T.checkDeadlock=!1);let E=(0,i.dirname)(r),D=[E,...c.libraries],O=m(D),k=lo(o,d,r.replace(/\.tla$/,``),y.startTime),A=e=>o.moduleOperators.filter(t=>t.kind===e).map(e=>e.module);l.isTool&&l.print(t.zt.startingSany,t.Bt.none,`Starting SANY...`);let j=(0,i.isAbsolute)(r),M=j?g:r.replace(/\.tla$/,``),N=C(c),ee=d===`1.7.4`?vo(r,c,N):void 0;ee?!(0,a.existsSync)(r)&&!t.at.has(g)&&ee(`${g}.tla`):!(0,a.existsSync)(r)&&!t.ot.has(g)&&h(j?E:process.cwd(),j?`${g}.tla`:`./${M}.tla`,[...j||E===`.`?[]:[E],...c.libraries]);let P=qi(r,ee?S(O,ee):O,{fileName:M,describeFile:$a(r,D,c,o.metadir,d),version:d,rootExtendees:[...A(`postcondition`),...k?.traceFile===void 0?[]:[`_TLCTrace`],...o.invariants.flatMap(e=>e.modules),...A(`constraint`),...A(`view`).slice(0,1)],suppressedCodes:o.suppressedCodes,errorCodes:o.errorCodes,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}),F=P.specification;if(P.isFailed||F===void 0)return Wa(l,{kind:`parsed`},y,E),x(),b(),e.tt.specParseError;try{let i=(0,a.readFileSync)(r,`utf8`),c=t.V(i).name;if(c!==g)throw new e.M(`File name '${g}' does not match the name '${c}' of the top level module it contains.`,void 0);let f=o.userFile,p=t.st(d),m=Qi(i,F.root,o.invariants,e=>O(e)??p.get(e)??t.B(i,e),d);T.invariants.push(...m.names);let h={workers:o.workers,livenessCheck:u===`off`?`off`:[`final`,`seqfinal`].includes(u)?`final`:`default`,seed:o.seed,fingerprintPolynomial:o.fingerprintIndex,maxSetSize:o.maxSetSize,isLazyValueExpanded:o.isLazyValueExpanded,isViewPrinted:o.isViewPrinted,dump:s,isTool:l.isTool,isContinued:o.isContinued,moduleOperators:o.moduleOperators,traceSpec:k,coverage:o.coverage,isSanyReported:!0,isWarningEnabled:o.isWarningEnabled,version:d,onProgress:e=>Wa(l,e,y,E),onPrint:f===void 0?void 0:e=>(0,a.appendFileSync)(f,`${e}\n`),source:m.source,config:T,onPause:()=>(0,a.readSync)(0,Buffer.alloc(1)),loadModule:O,loadClass:e=>{let t=Ua(E,e);return(0,a.existsSync)(t)?(0,a.readFileSync)(t):void 0},readFile:e=>(Da(e),(0,a.existsSync)(e)?(0,a.readFileSync)(e,`utf8`):void 0),writeFile:fo,makeDirectory:po};if(o.mode!==`model-check`){let e=Me({...h,traceDepth:o.traceDepth,traceCount:o.traceCount,aril:o.aril,isGenerating:o.mode===`generate`,scheduler:o.scheduler,onSimulation:e=>io(l,e)});return b(),e}if(o.dfidDepth!==void 0){let e=Oe({...h,maxDepth:o.dfidDepth,onOutput:e=>Xa(l,e)});return b(),e}let _=await n.m(h);if(Za(_,l,y),b(),k&&_.traceSpec!==void 0){let n=co(k.directory,`${k.module}.tla`);po(k.directory);let r=(()=>{try{fo(n,_.traceSpec);return}catch(t){if(!(t instanceof e.b))throw t;return t}})();l.print(r?t.zt.traceSpecFailed:t.zt.traceSpecWritten,t.Bt.none,r?`Failed to generate trace exploration spec; error message: ${r.message}`:`Trace exploration spec path: ${n}`)}return _.failure?.exitCode??Ea[_.status]}catch(t){if(!(t instanceof e.y))throw t;return t instanceof e.F&&console.log(go(t,g)),y.isParsed||Wa(l,{kind:`parsed`},y,E),w(t)}},go=(t,n)=>{let r=t instanceof e.M;if(!r&&!t.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${t.message}\n\n`;let i=r?t.location===void 0?`Unknown location\n\n${t.message}`:`In module ${t.location}\n\n${t.message}`:`In module ${n}\n\nCould not parse module ${n} from file ${n}.tla`;return`${t.failure?`***Parse Error***\n${t.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${n}\n\n${i}\n*** Errors: 1\n\n${i}\n\n\n`},_o=async(n,r)=>{let o=r.tlcVersion??`master`,s=pa(n);if(`error`in s)return s.isUncaught?(console.error(`Exception in thread "main" ${s.error}`),1):no(s.isTool,o,s.error);if(s.isUsage)return console.log(wa()),1;let c=s.dump&&ka(s.dump.map(e=>e.includes("${metadir}")?e.replace("${metadir}",mo(s)):e)),l=c?.path;if(l!==void 0)try{(0,a.closeSync)((0,a.openSync)(l,`w`))}catch{return console.log(`Error: Unable to write to file ${l}`),no(s.isTool,o,`Error: Given file name ${l} for dumping states invalid.`)}let u=s.configPath!==void 0;if(u&&s.specs.length>1)return no(s.isTool,o,`Error: more than one input files: ${s.specs[0].replace(/\.tla$/,``)} and ${s.specs[1]}`);let d=f(s.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||u||(0,a.existsSync)(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(d.length===0)return no(s.isTool,o,`Error: Missing input TLA+ module.`);if(u&&d.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let p=[...new Set(d.map(e=>(0,a.existsSync)(e)||(0,i.isAbsolute)(e)?e:r.libraries.map(t=>(0,i.join)(t,e)).find(a.existsSync)??e))],m=[];for(let[e,n]of p.entries()){e>0&&console.log(``);let a={...t.Vt(s.isTool,s.isWarningEnabled,o,s.suppressedCodes,s.errorCodes),isDiffTrace:s.isDiffTrace};m.push(await y(async()=>{let e=n.endsWith(`.ts`)?await Ta(n):n;return p.length>1&&console.log(`Checking ${(0,i.basename)(e)} with ${(0,i.basename)(e,`.tla`)}.cfg`),ho(e,s,c,r,a)},a))}return m.find(t=>t!==e.tt.success)??e.tt.success},vo=(e,t,n)=>{let r=e.slice(0,e.lastIndexOf(`/`)+1),a=(!(0,i.isAbsolute)(e)&&r!==``?[r]:t.libraries).map(x),o=a.length>0?a[a.length-1]:(0,i.isAbsolute)(e)?r:``;return e=>b(`${o}${e}`,a,n)},yo={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},bo=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:[]}),xo={"&":`&`,"<":`<`,">":`>`,"\r":` `},So=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:xo[e]),Co=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,wo=e=>{let t=(e.cdata??e.text)?.match(Co)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=wo(t);if(e)return e}},To=(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}>${So(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)To(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},Eo=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)]),Do=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)`}},Oo={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)`}}},ko={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},Ao=kn(`--TLA+ BUILTINS--`),jo=(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}]},Mo=(e,t=16)=>e>t*.75?Mo(e,t*2):t,No=(e,t)=>(e^e>>>16)&t-1,Po=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},Fo=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),Io=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,Lo=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=Po(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(Io,``)}).join(`
|
|
152
|
-
`)},
|
|
153
|
-
`)},
|
|
154
|
-
`),a=r.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${i}\n`).join(``);return e.it(new e.T(i,a),
|
|
155
|
-
`),n=r.isUncommented?
|
|
156
|
-
`)}\n`},
|
|
157
|
-
`)})(),
|
|
150
|
+
`).trim()}\n`},to=(e,n,r)=>{let i=t.Vt(e,!0,n);return $a(i),i.print(t.zt.commandLineError,t.Bt.error,`${r}\nUsage: java tlc2.TLC [-help] [-option] inputfile`),1},no=(e,n)=>{let r=`${n.workers} worker${n.workers===1?``:`s`} on ${(0,s.availableParallelism)()} cores with ${Math.floor((0,c.getHeapStatistics)().heap_size_limit/1024/1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${(0,s.type)()} ${(0,s.release)()} ${(0,s.arch)()}, Node.js ${process.versions.node} ${process.arch.endsWith(`64`)?64:32}bit`;n.mode===`model-check`&&n.dfidDepth!==void 0?e.print(t.zt.depthFirstModelChecking,t.Bt.none,`Running depth-first search Model-Checking with fp ${n.fingerprintIndex} and seed ${n.seed} with ${r}).`):n.mode===`model-check`?e.print(t.zt.modelChecking,t.Bt.none,`Running breadth-first search Model-Checking with fp ${n.fingerprintIndex} and seed ${n.seed} with ${r}, MemFPSet, MemStateQueue).`):e.print(t.zt.simulating,t.Bt.none,`Running ${n.scheduler===`rl`?`RL`:`Random`} Simulation with seed ${n.seed} with ${r}).`)},ro=(e,n)=>{let r=e.print;switch(n.kind){case`message`:r(n.code,n.isError?t.Bt.error:t.Bt.none,e.isTool?n.toolMessage:n.message);return;case`behavior`:{let i=n.trace[n.trace.length-1];if(!n.isLastStateOnly){Na(e,n.trace,Ma,!1,!0);return}r(t.zt.errorState,t.Bt.none,`The error state is:
|
|
151
|
+
`),r(t.zt.statePrint1,t.Bt.state,`:\n${t.Et(i.state)}`);return}case`progress`:{let i=n.statistics;if(e.isTool){io(e,i);return}let a=i.levelM2/(i.traces+1);r(t.zt.simulationProgress,t.Bt.none,`Progress: ${i.generatedStates} states checked, ${i.traces} traces generated (trace length: mean=${i.levelMean}, var(x)=${Math.round(a)}, sd=${Math.round(Math.sqrt(a))})`);return}case`summary`:e.isTool&&io(e,n.statistics),r(t.zt.simulationStats,t.Bt.none,`The number of states generated: ${n.statistics.generatedStates}\nSimulation using seed ${n.statistics.seed} and aril ${n.statistics.aril}`)}},io=(e,n)=>e.print(t.zt.simulationProgress,t.Bt.none,`Progress(${n.traces}) at ${t.Wt(/* @__PURE__ */ new Date)}: ${n.generatedStates} states generated, -1 distinct states found, -1 states left on queue.`),ao=e=>e.replace(/\/+/g,`/`).replace(/(.)\/$/,`$1`),oo=e=>{let t=ao(e),n=t.lastIndexOf(`/`);return n===-1?`.`:t.slice(0,Math.max(n,1))},so=(e,t)=>e.endsWith(`/`)?`${e}${t}`:`${e}/${t}`,co=(e,t,n,r)=>{if(t===`1.7.4`||!e.isTraceSpecForced&&(e.isTraceSpecDisabled||e.isTool||e.isContinued||(0,i.basename)(n).includes(`_TTrace`)))return;let a=e.traceSpecPath,o=`${(0,i.basename)(n)}_TTrace_${Math.floor(r/1e3)}`,s=a===void 0?{directory:oo(n),module:o}:a.toLowerCase().endsWith(`.tla`)?{directory:oo(a),module:(0,i.basename)(a).replace(/\.tla$/,``)}:{directory:ao(a),module:o};return{...s,traceFile:e.isTraceBinaryDisabled?void 0:so(s.directory,`${s.module}.bin`)}},lo={ENOENT:`No such file or directory`,ENOTDIR:`Not a directory`,EISDIR:`Is a directory`,EACCES:`Permission denied`},uo=(t,n)=>{try{(0,a.writeFileSync)(t,n)}catch(n){let r=n instanceof Error&&`code`in n?lo[String(n.code)]:void 0;throw r===void 0?n:new e.b(`${t} (${r})`)}},fo=e=>{try{(0,a.mkdirSync)(e,{recursive:!0})}catch{}},po=e=>{let t=/* @__PURE__ */ new Date,n=(e,t=2)=>String(e).padStart(t,`0`),r=`${n(t.getFullYear()%100)}-${n(t.getMonth()+1)}-${n(t.getDate())}-${n(t.getHours())}-${n(t.getMinutes())}-${n(t.getSeconds())}.${n(t.getMilliseconds(),3)}`,o=(0,i.join)(e.metadir??`states`,r);return(0,a.mkdirSync)(o,{recursive:!0}),o},mo=async(r,o,s,c,l)=>{let u=o.livenessCheck,d=l.version;$a(l);let f=o.recoverDirectory;if(f!==void 0)throw(0,a.existsSync)((0,i.join)(f,`vars.chkpt`))?new e.x(`tla-ts can't recover a model check from the checkpoint in ${f}.`):new e.E(f);no(l,o);let p=o.configPath??r.replace(/\.tla$/,`.cfg`);if(!(0,a.existsSync)(p))return l.print(t.zt.configFileError,t.Bt.error,`TLC encountered the following error when trying to read the configuration file ${p}:\nFile not found.`),e.tt.configParseError;let g=(0,i.basename)(r,`.tla`),y={startTime:Date.now(),livenessStartTime:void 0,isParsed:!1},b=()=>{let e=Date.now()-y.startTime;l.print(t.zt.finished,t.Bt.none,`Finished in ${l.isTool?`${e}ms`:t.Gt(e)} at (${t.Wt(/* @__PURE__ */ new Date)})`)},x=()=>l.print(t.zt.parsingFailed,t.Bt.error,`Parsing or semantic analysis failed.`),w=t=>(t instanceof e.F?x():v(t,l),b(),_(t)),T=(()=>{try{let e=(0,a.readFileSync)(p,`utf8`);return t.en(p.endsWith(`.tla`)?eo(e,p.replaceAll(`.tla`,``)):e,d)}catch(t){if(!(t instanceof e._))throw t;return t}})();if(T instanceof e._&&d===`1.7.4`)return l.print(t.zt.general,t.Bt.error,`${e.$(`tlc2.tool.ConfigFileException`)}${t.Ut(T.message,l.isTool)}`),b(),e.tt.error;if(T instanceof e._)return w(T);o.isDeadlockChecked||(T.checkDeadlock=!1);let E=(0,i.dirname)(r),D=[E,...c.libraries],O=m(D),k=co(o,d,r.replace(/\.tla$/,``),y.startTime),A=e=>o.moduleOperators.filter(t=>t.kind===e).map(e=>e.module);l.isTool&&l.print(t.zt.startingSany,t.Bt.none,`Starting SANY...`);let j=(0,i.isAbsolute)(r),M=j?g:r.replace(/\.tla$/,``),N=C(c),ee=d===`1.7.4`?_o(r,c,N):void 0;ee?!(0,a.existsSync)(r)&&!t.at.has(g)&&ee(`${g}.tla`):!(0,a.existsSync)(r)&&!t.ot.has(g)&&h(j?E:process.cwd(),j?`${g}.tla`:`./${M}.tla`,[...j||E===`.`?[]:[E],...c.libraries]);let P=Ki(r,ee?S(O,ee):O,{fileName:M,describeFile:Qa(r,D,c,o.metadir,d),version:d,rootExtendees:[...A(`postcondition`),...k?.traceFile===void 0?[]:[`_TLCTrace`],...o.invariants.flatMap(e=>e.modules),...A(`constraint`),...A(`view`).slice(0,1)],suppressedCodes:o.suppressedCodes,errorCodes:o.errorCodes,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}),F=P.specification;if(P.isFailed||F===void 0)return Ua(l,{kind:`parsed`},y,E),x(),b(),e.tt.specParseError;try{let i=(0,a.readFileSync)(r,`utf8`),c=t.V(i).name;if(c!==g)throw new e.M(`File name '${g}' does not match the name '${c}' of the top level module it contains.`,void 0);let f=o.userFile,p=t.st(d),m=Zi(i,F.root,o.invariants,e=>O(e)??p.get(e)??t.B(i,e),d);T.invariants.push(...m.names);let h={workers:o.workers,livenessCheck:u===`off`?`off`:[`final`,`seqfinal`].includes(u)?`final`:`default`,seed:o.seed,fingerprintPolynomial:o.fingerprintIndex,maxSetSize:o.maxSetSize,isLazyValueExpanded:o.isLazyValueExpanded,isViewPrinted:o.isViewPrinted,dump:s,isTool:l.isTool,isContinued:o.isContinued,moduleOperators:o.moduleOperators,traceSpec:k,coverage:o.coverage,isSanyReported:!0,isWarningEnabled:o.isWarningEnabled,version:d,onProgress:e=>Ua(l,e,y,E),onPrint:f===void 0?void 0:e=>(0,a.appendFileSync)(f,`${e}\n`),source:m.source,config:T,onPause:()=>(0,a.readSync)(0,Buffer.alloc(1)),loadModule:O,loadClass:e=>{let t=Ha(E,e);return(0,a.existsSync)(t)?(0,a.readFileSync)(t):void 0},readFile:e=>(Ea(e),(0,a.existsSync)(e)?(0,a.readFileSync)(e,`utf8`):void 0),writeFile:uo,makeDirectory:fo};if(o.mode!==`model-check`){let e=Me({...h,traceDepth:o.traceDepth,traceCount:o.traceCount,aril:o.aril,isGenerating:o.mode===`generate`,scheduler:o.scheduler,onSimulation:e=>ro(l,e)});return b(),e}if(o.dfidDepth!==void 0){let e=Oe({...h,maxDepth:o.dfidDepth,onOutput:e=>Ya(l,e)});return b(),e}let _=await n.m(h);if(Xa(_,l,y),b(),k&&_.traceSpec!==void 0){let n=so(k.directory,`${k.module}.tla`);fo(k.directory);let r=(()=>{try{uo(n,_.traceSpec);return}catch(t){if(!(t instanceof e.b))throw t;return t}})();l.print(r?t.zt.traceSpecFailed:t.zt.traceSpecWritten,t.Bt.none,r?`Failed to generate trace exploration spec; error message: ${r.message}`:`Trace exploration spec path: ${n}`)}return _.failure?.exitCode??Ta[_.status]}catch(t){if(!(t instanceof e.y))throw t;return t instanceof e.F&&console.log(ho(t,g)),y.isParsed||Ua(l,{kind:`parsed`},y,E),w(t)}},ho=(t,n)=>{let r=t instanceof e.M;if(!r&&!t.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${t.message}\n\n`;let i=r?t.location===void 0?`Unknown location\n\n${t.message}`:`In module ${t.location}\n\n${t.message}`:`In module ${n}\n\nCould not parse module ${n} from file ${n}.tla`;return`${t.failure?`***Parse Error***\n${t.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${n}\n\n${i}\n*** Errors: 1\n\n${i}\n\n\n`},go=async(n,r)=>{let o=r.tlcVersion??`master`,s=fa(n);if(`error`in s)return s.isUncaught?(console.error(`Exception in thread "main" ${s.error}`),1):to(s.isTool,o,s.error);if(s.isUsage)return console.log(Ca()),1;let c=s.dump&&Oa(s.dump.map(e=>e.includes("${metadir}")?e.replace("${metadir}",po(s)):e)),l=c?.path;if(l!==void 0)try{(0,a.closeSync)((0,a.openSync)(l,`w`))}catch{return console.log(`Error: Unable to write to file ${l}`),to(s.isTool,o,`Error: Given file name ${l} for dumping states invalid.`)}let u=s.configPath!==void 0;if(u&&s.specs.length>1)return to(s.isTool,o,`Error: more than one input files: ${s.specs[0].replace(/\.tla$/,``)} and ${s.specs[1]}`);let d=f(s.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||u||(0,a.existsSync)(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(d.length===0)return to(s.isTool,o,`Error: Missing input TLA+ module.`);if(u&&d.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let p=[...new Set(d.map(e=>(0,a.existsSync)(e)||(0,i.isAbsolute)(e)?e:r.libraries.map(t=>(0,i.join)(t,e)).find(a.existsSync)??e))],m=[];for(let[e,n]of p.entries()){e>0&&console.log(``);let a={...t.Vt(s.isTool,s.isWarningEnabled,o,s.suppressedCodes,s.errorCodes),isDiffTrace:s.isDiffTrace};m.push(await y(async()=>{let e=n.endsWith(`.ts`)?await wa(n):n;return p.length>1&&console.log(`Checking ${(0,i.basename)(e)} with ${(0,i.basename)(e,`.tla`)}.cfg`),mo(e,s,c,r,a)},a))}return m.find(t=>t!==e.tt.success)??e.tt.success},_o=(e,t,n)=>{let r=e.slice(0,e.lastIndexOf(`/`)+1),a=(!(0,i.isAbsolute)(e)&&r!==``?[r]:t.libraries).map(x),o=a.length>0?a[a.length-1]:(0,i.isAbsolute)(e)?r:``;return e=>b(`${o}${e}`,a,n)},vo={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},yo=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:[]}),bo={"&":`&`,"<":`<`,">":`>`,"\r":` `},xo=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:bo[e]),So=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,Co=e=>{let t=(e.cdata??e.text)?.match(So)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=Co(t);if(e)return e}},wo=(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}>${xo(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)wo(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},To=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)]),Eo=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)`}},Do={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)`}}},Oo={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},ko=kn(`--TLA+ BUILTINS--`),Ao=(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}]},jo=(e,t=16)=>e>t*.75?jo(e,t*2):t,Mo=(e,t)=>(e^e>>>16)&t-1,No=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},Po=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),Fo=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,Io=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=No(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(Fo,``)}).join(`
|
|
152
|
+
`)},Lo=e=>{let t=No(e),n=e=>Po(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(`
|
|
153
|
+
`)},Ro=(t,n,r)=>{let i=r.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=(t,n)=>{let r=[...c,...n].reverse(),i=[t,...r.map(e=>`\tat tla2sany.${e.at}`)].join(`
|
|
154
|
+
`),a=r.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${i}\n`).join(``);return e.it(new e.T(i,a),vo.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]:[],...Ao(e.kind,kn(e.location))],()=>g(e)))),Z(Eo(e),[Q(`UID`,e.id)])),p=(e,t,n)=>{let r=t.levelChecked===0?[]:[Q(`level`,t.level)],i=n?[To(n),...r]:r;return{...e,children:[...i,...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(`
|
|
155
|
+
`),n=r.isUncommented?Lo(Io(t)):t;return e.length>0?[{tag:`pre-comments`,cdata:n,children:[]}]:[]},g=t=>{switch(t.kind){case`FormalParam`:return p(Z(`FormalParamNode`,[Q(`uniquename`,t.name),Q(`arity`,t.arity)]),t,t.location);case`OpDecl`:return p(Z(`OpDeclNode`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Q(`kind`,t.declKind)]),t,t.location);case`OpDef`:{if(t.defKind===`NumberedProofStep`)throw i?u(yo(37),[Oo]):e.it(new e.B(yo(37)),vo.uncaughtException);if(t.defKind===`ModuleInstance`)return p(Z(`ModuleInstanceKind`,[Q(`uniquename`,t.name),...t.isLocal&&!i?[Z(`local`)]:[]]),t,t.location);let n=t.params??[];if(t.defKind===`BuiltIn`)return p(Z(`BuiltInKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),...t.params?[m(n,t.isLeibnizArg,$.builtInParam)]:[]]),t,t.location);let r=t.body,a=t.module;if(r===void 0&&i)throw d($.body);if(r===void 0||a===void 0)throw Error(`The definition of ${t.name} has no body`);return p(i?Z(`UserDefinedOpKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Z(`body`,[x(r,$.body)]),...t.params?[m(n,t.isLeibnizArg,$.param)]:[],...t.inRecursive?[Z(`recursive`)]:[]]):Z(`UserDefinedOpKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Z(`originalOperator`,[f(t.source??t)]),Z(`originallyDefinedInModule`,[f(a)]),Z(`body`,[x(r,$.body)]),m(n,t.isLeibnizArg,$.param),...h(t.preComments),...t.inRecursive?[Z(`recursive`)]:[],...t.recursiveSection>=0?[Q(`recursiveSection`,t.recursiveSection)]:[],...t.isLocal?[Z(`local`)]:[]]),t,t.location)}case`ThmOrAssumpDef`:return p(Z(t.isTheorem?`TheoremDefNode`:`AssumeDef`,[Q(`uniquename`,t.name),x(t.body,$.theoremDefinitionBody)]),t,t.location);case`Module`:return Z(`ModuleNode`,[To(t.location),..._(t)]);case`Theorem`:return p(Z(`TheoremNode`,[...t.definition?[Z(`definition`,[f(t.definition,$.theoremDefinition)])]:[],Z(`body`,[x(t.body,$.theorem)]),...t.proof?[x(t.proof,$.proof)]:[],...t.isSuffices?[Z(`suffices`)]:[]]),t,t.location);case`Assume`:return Z(`AssumeNode`,[To(t.location),...t.body.levelChecked===0?[]:[Q(`level`,t.body.level)],...t.definition?[Z(`definition`,[f(t.definition,$.assumeDefinition)])]:[],Z(`body`,[x(t.body,$.assume)])])}},_=e=>{let t=t=>!r.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)))],...Gn(e,2).filter(t).map(e=>f(e,$.constant)),...Gn(e,3).filter(t).map(e=>f(e,$.variable)),...Wn(e).filter(t).map(e=>f(e,$.definition)),...e.topLevel.map(e=>e.kind===`Instance`||e.kind===`UseOrHide`?x(e,$.topLevel):f(e,$.topLevel)),...e.definitions.filter(e=>!i&&e.kind===`Module`).map(e=>f(e))]},v=(e,t)=>l([t],()=>Z(`Subst`,[f(e.op,$.substOperator),x(e.expr,$.substExpression)])),y=e=>{if(e.isNull&&i)throw u(yo(0),[$.operator,...Ao(`OpDef`,ko),Oo]);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&&An(e)?i?Q(`StringNode`,`$Other`):Z(`StringNode`,[Q(`StringValue`,`$Other`)]):x(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`)]:[],x(e.ranges[n],$.range)]))])];return Z(`OpApplNode`,[Z(`operator`,[n]),Z(`operands`,r),...o])},b=(e,t)=>e.kind===`Module`||e.kind===`OpDef`?f(e,t):x(e,t),x=(e,t)=>{if(!i)return S(e);if(e.kind===`OpAppl`&&e.isAbsent&&`nullType`in t)throw d(t);return l([t,{at:`semantic.SemanticNode.export(SemanticNode.java:379)`,failedFor:kn(e.location)},{at:`semantic.LevelNode.getSemanticElement(LevelNode.java:333)`}],()=>S(e))},S=e=>{switch(e.kind){case`OpAppl`:return p(y(e),e,e.location);case`Numeral`:return p(Z(`NumeralNode`,[Q(`IntValue`,e.value)]),e,e.location);case`String`:return p(Z(`StringNode`,[Q(`StringValue`,e.value)]),e,e.location);case`Decimal`:return p(Z(`DecimalNode`,[Q(`mantissa`,e.mantissa),Q(`exponent`,e.exponent),...i?[]:[Q(`integralPart`,e.integralPart),Q(`fractionalPart`,e.fractionalPart)]]),e,e.location);case`LetIn`:{let t=x(e.body,$.letBody);return p(Z(`LetInNode`,[Z(`body`,[t]),Z(`opDefs`,e.opDefs.map(e=>f(e,$.letDefinition)))]),e,e.location)}case`Label`:return p(Z(`LabelNode`,[Q(`uniquename`,e.name),Q(`arity`,e.params.length),Z(`body`,[x(e.body,$.labelBody)]),Z(`params`,e.params.map(e=>f(e,$.labelParam)))]),e,e.location);case`OpArg`:return p(Z(`OpArgNode`,[Z(`argument`,[f(e.op,$.argument)])]),e,e.location);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`,[x(t,$.exceptObject),x(n,$.exceptComponents)]),e,e.location)}case`SubstIn`:case`APSubstIn`:{let t=Do[e.kind],n=e.substs.map(e=>v(e,t.subst)),r=x(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,e.location)}case`Instance`:{let t=e.substs.map(e=>v(e,$.instanceSubst)),n=e.params.map(e=>f(e,$.instanceParam));return Z(`InstanceNode`,[To(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=>b(e,$.useFact))),Z(`defs`,e.defs.map(e=>f(e,$.useDefinition))),...e.isOnly?[Z(`only`)]:[],...e.isHide?[Z(`hide`)]:[]]),e,e.location);case`NewSymb`:return p(Z(`NewSymbNode`,[f(e.declaration,$.newDeclaration),...e.set&&!(i&&An(e.set))?[x(e.set,$.newSet)]:[]]),e,e.location);case`AssumeProve`:return p(Z(`AssumeProveNode`,[Z(`assumes`,e.assumptions.map(e=>x(e,$.assumption))),Z(`prove`,[x(e.goal,$.goal)]),...e.isSuffices?[Z(`suffices`)]:[],...e.isBoxed?[Z(`boxed`)]:[]]),e,e.location);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=>b(e,$.byFact))),Z(`defs`,e.defs.map(e=>f(e,$.byDefinition))),...e.isOnly?[Z(`only`)]:[]]);return p(n,e,e.location)}case`NonLeafProof`:return p(Z(`steps`,[...i?[]:[Q(`proofLevel`,e.proofLevel)],...e.steps.map(e=>e.kind===`Theorem`?f(e,$.step):x(e,$.step))]),e,e.location);case`DefStep`:return p(Z(`DefStepNode`,e.defs.map(e=>f(e,$.defStep))),e,e.location)}},C=(r.isRestricted?[n]:t).map(e=>f(e,$.main)),w=jo(o.size),T=Z(`context`,[...o.entries()].toSorted(([e],[t])=>Mo(e,w)-Mo(t,w)).map(([e,t])=>Z(`entry`,[Q(`UID`,e),t])));return Z(`modules`,[Q(`RootModule`,n.name),T,...C])},zo=(t,n={version:`master`,isRestricted:!1,isUncommented:!1,isTerse:!1})=>{let r=Ro(t.modules,t.root,n),i=Co(r);if(i){let t=i.character.codePointAt(0)??0;throw e.it(new e.B(`The spec contains the character U+${t.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.`),vo.unrepresentableCharacter)}let a=[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>`];return wo(r,0,n.isTerse?0:2,a),n.isTerse?a.join(``):`${a.join(`
|
|
156
|
+
`)}\n`},Bo=(()=>{let e=e=>`\x1b[1m${e}\x1b[0m`,t=[[`-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.`]],n=[`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[``,e(`NAME`),``,` tla2sany.xml.XMLExporter - Emit SANY's parse tree as XML - Version 2.2 created 08 July 2020`,``,``,e(`SYNOPSIS`),``,`\t${e(`tla2sany.xml.XMLExporter`)} [${e(`-Iortu`)}] [${e(`-help`)}] FILE`,``,e(`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.`,``,e(`OPTIONS`),``,...t.map(([t,n])=>`\t${e(t)}\n\t\t${n}`),``,e(`TIPS`),``,...n.flatMap(e=>[`\t${e}`,``]),``].join(`
|
|
157
|
+
`)})(),Vo=e=>(process.stderr.write(`ERROR: ${e}\n${Bo}`),vo.argsParsingFailure),Ho=(t,n)=>{try{return process.stdout.write(zo(t,n)),e.tt.success}catch(t){if(!(t instanceof e.B))throw t;let n=e.Q(t),r=t instanceof e.T?t.unwound:``;return console.error(n===vo.uncaughtException?`${r}Exception in thread "main" ${t.message}`:`ERROR: ${t.message}`),n}},Uo=(e,t)=>{let n={flags:/* @__PURE__ */ new Set,includes:[],error:void 0},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`}},Wo=n=>{if(n.length===0)return Vo(`at least one .tla file must be given`);let r=Uo(n,/* @__PURE__ */ new Set([`-o`,`-t`,`-r`,`-u`]));if(r.error===`missing-include`)return Vo(`the -I flag must be followed by a directory and at least one .tla file`);if(r.error===`several-files`)return Vo(`Only one TLA file to check allowed!`);let o=n[n.length-1];if(o===`-help`)return process.stdout.write(Bo),e.tt.success;let s=o.endsWith(`.tla`)?o:`${o}.tla`,c=[`.`,...r.includes],l=c.map(e=>(0,i.resolve)(e,s)).find(a.existsSync);l===void 0&&!t.ot.has(s.slice(0,-4))&&h(process.cwd(),`./${s}`,r.includes);let u=Ki(l??s,m(c),{fileName:o,isXmlExport:!0});return process.stderr.write(u.text),u.isFailed||u.specification===void 0?(console.error(`ERROR: Failed to parse module.`),vo.specParsingFailure):Ho(u.specification,{version:`master`,isRestricted:r.flags.has(`-r`),isUncommented:r.flags.has(`-u`),isTerse:r.flags.has(`-t`)})},Go=(e,t)=>(console.error(`Exception in thread "main" ${e}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${t})`),vo.uncaughtException),Ko=(n,r)=>{if(n.length===0)return Go(`java.lang.IllegalArgumentException: at least one .tla file must be given`,59);let o=Uo(n,/* @__PURE__ */ new Set([`-o`]));if(o.error===`missing-include`)return Go(`java.lang.IllegalArgumentException: the -I flag must be followed by a directory and at least one .tla file`,71);if(o.error===`several-files`)return Go(`java.lang.IllegalArgumentException: Only one TLA file to check allowed!`,83);let s=n[n.length-1],c=`${s.replace(/\.tla$/i,``)}.tla`,l=(o.includes.length===0?[`/`]:o.includes).map(x),u=[`.`,...l],d=e=>b(`${l[l.length-1]}${e}`,l,r),f=u.map(e=>(0,i.resolve)(e,c)).find(a.existsSync);if(f===void 0&&!t.at.has((0,i.basename)(c,`.tla`)))return d(c),e.tt.success;let p=Ki(f??c,S(m(u),d),{fileName:s,isXmlExport:!0,version:`1.7.4`});return process.stderr.write(p.text),p.specification===void 0?Go(`tla2sany.xml.XMLExportingException: spec ${(f&&Gi((0,a.readFileSync)(f,`utf8`),`1.7.4`))??`null`} is malformed - does not have a root module`,110):Ho(p.specification,{version:`1.7.4`,isRestricted:!1,isUncommented:!1,isTerse:!0})},qo=[`tlc2.TLC`,`tla2sany.xml.XMLExporter`],Jo=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(i.delimiter));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||qo.includes(r)?{mainClass:r,args:e.slice(n+1),java:t}:void 0}},Yo=async e=>{if(e[0]===`tlapm`)return y(()=>we(e.slice(1)));let t=Jo(e);return t===void 0?go(e,{libraries:[]}):(t.java.tlcVersion??=await u(C(t.java)),t.mainClass===`tlc2.TLC`?go(t.args,t.java):t.mainClass===`tla2sany.xml.XMLExporter`?y(()=>t.java.tlcVersion===`1.7.4`?Ko(t.args,C(t.java)):Wo(t.args)):(console.error(`Error: tla-ts runs the Java classes ${qo.join(` and `)}, not ${t.mainClass}.`),1))},Xo=async()=>{process.exitCode=await Yo(process.argv.slice(2))};exports.runCli=Xo;
|