tla-ts 0.0.4-dev.702eb98 → 0.0.4-dev.7b5087a
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/README.md +1 -0
- package/dist/deciders.cjs +1 -1
- package/dist/deciders.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/prove-worker.cjs +1 -1
- package/dist/prove-worker.js +1 -1
- package/dist/prove.cjs +498 -17
- package/dist/prove.js +506 -25
- package/dist/run-cli.cjs +515 -28
- package/dist/run-cli.js +515 -28
- package/package.json +1 -1
- package/src/obligations/format.ts +6 -5
- package/src/obligations/index.ts +2 -0
- package/src/obligations/printer.ts +4 -4
- package/src/ocaml-marshal.ts +172 -0
- package/src/prove/decide-pool.ts +9 -9
- package/src/prove/deciders.ts +7 -1
- package/src/prove/isabelle/encode.ts +57 -22
- package/src/prove/prep/defs.ts +19 -13
- package/src/prove/prove-worker.ts +2 -4
- package/src/prove/prove.ts +212 -101
- package/src/prove/verdict.ts +6 -0
- package/src/run-cli.ts +277 -34
- package/src/tlapm-cache.ts +250 -0
package/dist/run-cli.js
CHANGED
|
@@ -6,33 +6,520 @@
|
|
|
6
6
|
* This source code is licensed under the MIT license found in the
|
|
7
7
|
* LICENSE file in the root directory of this source tree.
|
|
8
8
|
*/
|
|
9
|
-
import{C as e,D as t,M as n,R as r,T as i,U as a,V as o,a as s,b as c,g as l,h as u,k as d,m as f,o as p,s as m,x as h,z as g}from"./worker.js";import{$ as _,B as v,C as y,D as b,E as x,G as S,H as C,L as w,M as ee,N as T,O as E,Q as D,R as O,T as k,U as te,V as A,W as j,_ as ne,et as re,h as ie,j as M,k as ae,m as N,nt as oe,q as se,tt as ce,v as le,w as ue,z as de}from"./transfer.js";import{a as fe,c as pe,i as me,l as he,n as ge,o as P,r as _e,s as ve,t as ye}from"./prove.js";import{getTlapmPaths as be}from"./tlapm.js";import{basename as xe,delimiter as Se,dirname as Ce,isAbsolute as we,join as Te,resolve as Ee}from"node:path";import{existsSync as F,globSync as De,mkdirSync as Oe,readFileSync as ke,readSync as Ae,realpathSync as je,writeFileSync as I}from"node:fs";import{arch as Me,availableParallelism as Ne,release as Pe,tmpdir as Fe,type as Ie}from"node:os";import{pathToFileURL as Le}from"node:url";import{getHeapStatistics as Re}from"node:v8";var ze=`0.0.4-dev.702eb98`;const Be=e=>{let t=e.isRequired?e.flag:`[${e.flag}]`;return e.isRepeatable?`${t}...`:t},Ve=(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(Be).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}}}},L={builtin:1,number:2,string:3,ident:4,added:5},He=()=>({labelFlag:!1,reportLabelsFlag:!1,labelRoot:`Lbl_`,fairnessOption:``,fairAlgorithm:!1,checkTermination:!1,noOld:!1,nocfg:!1,noDoneDisjunct:!1,specOption:!1,myspecOption:!1,specFile:``,optionsInFile:!1,inputVersionNumber:1903}),Ue=e=>{let t={result:0,digitsAfterDecimal:0,isAfterDecimal:!1};for(let n of e)if(n===`.`)t.isAfterDecimal=!0;else if(n<`0`||n>`9`||(t.result=10*t.result+Number(n),t.isAfterDecimal&&(t.digitsAfterDecimal+=1),t.digitsAfterDecimal>3))return-1;return t.result*10**Math.max(0,3-t.digitsAfterDecimal)},We=[`unfair`,`wf`,`sf`],R=()=>({col:0,line:0,macroCol:0,macroLine:-1,lbl:``}),Ge=e=>e.macroLine<0?`line ${e.line}, column ${e.col}`:`line ${e.line}, column ${e.col} of macro called at line ${e.macroLine}, column ${e.macroCol}`,Ke=e=>{if(e.kind!==`LabeledStmt`)throw new m(`ClassCastException: ${e.kind}`);return e},qe=(e,t)=>{if(t<0||t>=e.length)throw new m(`ArrayIndexOutOfBoundsException: ${t}`);return e[t]},Je=(e,t,n)=>({string:e,column:t,type:n}),Ye=e=>e.type===L.string?e.string.length+2:e.string.length,Xe=(e=[])=>({tokens:e,anchorTokens:void 0,anchorTokCol:void 0}),Ze=e=>{for(;e.tokens.length>0&&e.tokens[0].length===0;)e.tokens.shift();for(;e.tokens.length>0&&e.tokens[e.tokens.length-1].length===0;)e.tokens.pop();let t=Math.min(999999,...e.tokens.filter(e=>e.length>0).map(e=>e[0].column));e.tokens.forEach(e=>e.forEach(e=>{e.column-=t}));let n=[],r=[];e.tokens.forEach((t,i)=>{if(r.push(0),n.push(void 0),t.length===0)return;let a=t[0].column,o=e.tokens.slice(0,i).findLast(e=>e.length>0&&e[0].column<=a);if(o===void 0)return;let s=o.findIndex((e,t)=>t>0&&e.column>a),c=o[(s===-1?o.length:s)-1];n[i]=c,r[i]=c.column}),e.anchorTokens=n,e.anchorTokCol=r},Qe=e=>{let t=Xe(e);return Ze(t),t},$e=e=>{let t=e.anchorTokens,n=e.anchorTokCol;if(t===void 0||n===void 0)throw new m(`NullPointerException: TLAExpr.renormalize`);e.tokens.forEach((e,r)=>{let i=t[r];if(i===void 0)return;let a=i.column-n[r];if(n[r]=i.column,a<0)throw new p(`TLAExpr.renormalize() found anchor has moved to left.`);e.forEach(e=>{e.column+=a})})},et=e=>Qe(e.tokens.map(e=>e.map(e=>({...e})))),tt=(e,t,n)=>{let r=t.tokens.length;e.tokens.splice(0,0,...t.tokens.slice(0,r-1));let i=t.tokens[r-1],a=e.tokens[r-1],o=i[i.length-1],s=o.column+Ye(o)+n;a.forEach(e=>{e.column+=s}),a.splice(0,0,...i);let c=[...t.anchorTokens??[]],l=[...t.anchorTokCol??[]];for(let t=r;t<e.tokens.length;t++)c.push(e.anchorTokens?.[t-r+1]),l.push(e.anchorTokCol?.[t-r+1]??0);e.anchorTokens=c,e.anchorTokCol=l,$e(e)},nt=e=>e.tokens.length===1&&e.tokens[0].length===1,rt=(e,t)=>qe(qe(e.tokens,t.line),t.item),it=(e,t,n)=>{if(e.tokens.length<=t.line)throw new s(`TLAExpr.StepCoord called with line too big`);if(e.tokens[t.line].length<=t.item)throw new s(`TLAExpr.StepCoord called with col too big`);let r={line:t.line,item:t.item};for(let t=0;t<n;t++)if(r.item+=1,e.tokens[r.line].length===r.item){for(r.item=0,r.line+=1;r.line<e.tokens.length&&e.tokens[r.line].length===0;)r.line+=1;if(r.line===e.tokens.length)return}return r},at=(e,t,n)=>{for(let r=e.tokens.length===0?void 0:{...n};r!==void 0;){let n=rt(e,r),i=n.type===L.string;if(!i&&n.string===t)return r;let a=!i&&(n.string===`[`||n.string===`,`)?it(e,r,2):void 0,o=a===void 0?void 0:rt(e,a),s=o!==void 0&&o.type!==L.string&&[`:`,`|->`,`↦`].includes(o.string),c=i?1:n.string===`.`?2:s?3:1;r=it(e,r,c)}},ot=(e,t,n,r)=>{let i=rt(e,n);if(nt(e)){let n=et(t);e.tokens=n.tokens,e.anchorTokens=n.anchorTokens,e.anchorTokCol=n.anchorTokCol;return}let a=e.tokens[n.line],o=n.item+1<a.length?a[n.item+1].column-(i.column+Ye(i)):0,s=a.splice(n.item+1),c={lineIndex:n.line,indent:+!!r+i.column,isInserting:!r},l=()=>e.tokens[c.lineIndex];if(nt(t)){let e=t.tokens[0][0];i.string=e.string,i.type=e.type}else{r&&(i.string=`(`,i.type=L.builtin);let n=et(t);if(n.tokens.forEach((t,r)=>{if(t.forEach(e=>{e.column+=c.indent,c.isInserting?(i.string=e.string,i.type=e.type,c.isInserting=!1):l().push(e)}),r+1>=n.tokens.length)return;c.indent=0,c.lineIndex+=1;let a=c.lineIndex;e.tokens.splice(a,0,[]);let o=e.anchorTokens??[],s=e.anchorTokCol??[];e.anchorTokens=e.tokens.map((e,t)=>t<a?o[t]:t===a?n.anchorTokens?.[r+1]:o[t-1]),e.anchorTokCol=e.tokens.map((e,t)=>t<a?s[t]:t===a?n.anchorTokCol?.[r+1]??0:s[t-1])}),r){let e=l()[l().length-1];l().push(Je(`)`,e.column+Ye(e),L.builtin))}}let u=l(),d={line:c.lineIndex,item:u.length-1};if(s.length>0){let e=u[u.length-1],t=e.column+Ye(e)+o-s[0].column;s.forEach(e=>{e.column+=t,u.push(e)})}return $e(e),it(e,d,1)},st=(e,t,n,r=!0)=>{let i=n.map(t=>at(e,t,{line:0,item:0}));for(;;){let a=i.reduce((e,t,n)=>t!==void 0&&(e===void 0||t.line<e.position.line||t.line===e.position.line&&t.item<e.position.item)?{index:n,position:t}:e,void 0);if(a===void 0)return;let o=it(e,a.position,1),s=ot(e,t[a.index],a.position,r);i[a.index]=s===void 0?void 0:at(e,n[a.index],s),i.forEach((e,t)=>{if(t!==a.index&&e!==void 0&&s!==void 0){if(o===void 0)throw new m(`NullPointerException: TLAExpr.substituteForAll`);e.line===a.position.line&&(e.item+=s.item-o.item),e.line+=s.line-o.line}})}},ct=(e,t,n)=>{let r=et(e);return st(r,t,n),r},lt=(e,t,n)=>e.map(e=>ct(e,t,n)),ut=(e,t)=>{let n=e=>t===`1.7.4`?``:`(col${e.column}) `,r=e.tokens.map(e=>e.map(e=>e.type===L.string?`"\\"", "${e.string}", "\\""`:e.string===`\\/`?`"${n(e)}\\\\/"`:e.string.startsWith(`\\`)?`"\\${e.string}"`:e.string===`/\\`?`"${n(e)}/\\\\"`:`"${e.string}"`)),i=r.findIndex(e=>e.length>0);return`<< ${r.map((e,t)=>{let n=i!==-1&&t>i;return e.map((e,t)=>n||t>0?`, ${e}`:e).join(``)}).join(`
|
|
10
|
-
`)} >>`},
|
|
11
|
-
`;let t=e.currentLine[e.column];return e.column+=1,e.vcolumn+=1,t===` `?(e.vcolumn%8!=0&&(e.isTabToSpaces=!0),` `):t},
|
|
12
|
-
`)break}return
|
|
13
|
-
`)},f=e=>{if(!n){d(),i.token=``;return}e>
|
|
14
|
-
`)return a(),l(),c();if(
|
|
9
|
+
import{C as e,D as t,M as n,R as r,T as i,U as a,V as o,a as s,b as c,g as l,h as u,k as d,m as f,o as p,s as m,x as h,z as g}from"./worker.js";import{$ as _,B as v,C as y,D as b,E as x,G as S,H as C,L as w,M as ee,N as T,O as E,Q as D,R as O,T as k,U as te,V as A,W as j,_ as ne,et as re,h as ie,j as M,k as ae,m as N,nt as oe,q as se,tt as ce,v as le,w as ue,z as de}from"./transfer.js";import{a as fe,c as pe,d as me,f as he,g as ge,h as P,i as _e,l as ve,m as ye,n as be,o as xe,p as Se,r as Ce,t as we,u as Te}from"./prove.js";import{getTlapmPaths as Ee}from"./tlapm.js";import{basename as De,delimiter as Oe,dirname as ke,isAbsolute as Ae,join as je,resolve as Me}from"node:path";import{cpSync as F,existsSync as I,globSync as Ne,mkdirSync as Pe,readFileSync as L,readSync as Fe,readdirSync as Ie,realpathSync as Le,renameSync as Re,rmSync as ze,statSync as Be,writeFileSync as Ve}from"node:fs";import{arch as He,availableParallelism as Ue,release as We,tmpdir as Ge,type as Ke}from"node:os";import{pathToFileURL as qe}from"node:url";import{getHeapStatistics as Je}from"node:v8";var Ye=`0.0.4-dev.7b5087a`;const Xe=e=>{let t=e.isRequired?e.flag:`[${e.flag}]`;return e.isRepeatable?`${t}...`:t},Ze=(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(Xe).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}}}},Qe=2224400062,R={int8:0,int16:1,int32:2,int64:3,shared8:4,shared16:5,shared32:6,block32:8,string8:9,string32:10,doubleBig:11,doubleLittle:12},$e={smallInt:64,smallString:32,smallBlock:128},z=(e,...t)=>({tag:e,fields:t}),et=e=>typeof e==`object`&&`tag`in e,tt=(t,n)=>{let r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.length<n+20||r.getUint32(n)!==Qe)throw new e(`corrupted fingerprint file`);let i=n+20+r.getUint32(n+4),a=[],o={position:n+20},s=t=>{let n=o.position;if(o.position+=t,o.position>i)throw new e(`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=z(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>=$e.smallBlock)return u(n&15,n>>4&7);if(n>=$e.smallInt)return n&63;if(n>=$e.smallString)return l(n&31);switch(n){case R.int8:return r.getInt8(s(1));case R.int16:return r.getInt16(s(2));case R.int32:return r.getInt32(s(4));case R.int64:return Number(r.getBigInt64(s(8)));case R.shared8:return d(r.getUint8(s(1)));case R.shared16:return d(r.getUint16(s(2)));case R.shared32:return d(r.getUint32(s(4)));case R.block32:{let e=r.getUint32(s(4));return u(e&255,e>>>10)}case R.string8:return l(r.getUint8(s(1)));case R.string32:return l(r.getUint32(s(4)));case R.doubleBig:case R.doubleLittle:{let e={float:r.getFloat64(s(8),n===R.doubleLittle)};return a.push(e),e}}throw new e(`corrupted fingerprint file`)};return{value:f(),next:i}},nt=e=>{let t=[],n={objects:0,words32:0,words64:0},r=(e,n)=>{for(let r=(n-1)*8;r>=0;r-=8)t.push(e>>>r&255)},i=new TextEncoder,a=e=>{if(typeof e==`number`)return e>=0&&e<64?t.push($e.smallInt+e):e>=-128&&e<128?t.push(R.int8,e&255):e>=-32768&&e<32768?(t.push(R.int16),r(e,2)):(t.push(R.int32),r(e,4));if(n.objects++,typeof e==`string`){let a=i.encode(e);a.length<32?t.push($e.smallString+a.length):a.length<256?t.push(R.string8,a.length):(t.push(R.string32),r(a.length,4)),t.push(...a),n.words32+=1+Math.floor((a.length+4)/4),n.words64+=1+Math.floor((a.length+8)/8);return}if(!et(e)){let r=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));r.setFloat64(0,e.float,!0),t.push(R.doubleLittle,...new Uint8Array(r.buffer)),n.words32+=3,n.words64+=2;return}let o=e.fields.length;o===0?n.objects--:(n.words32+=1+o,n.words64+=1+o),e.tag<16&&o<8?t.push($e.smallBlock+e.tag+(o<<4)):(t.push(R.block32),r(o*1024+e.tag,4)),e.fields.forEach(a)};a(e);let o=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(20));return[Qe,t.length,n.objects,n.words32,n.words64].forEach((e,t)=>o.setUint32(t*4,e)),new Uint8Array([...new Uint8Array(o.buffer),...t])},rt=20210223,it={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}},at=[`false`,`timeout`],ot=`tla-ts ${Ye}`,st=/* @__PURE__ */ new Map([[it.zenon.field,3],[it.isabelle.field,4]]),ct=(e,t)=>e!==void 0&&et(e)?e.fields[t]:void 0,lt=e=>e!==void 0&&typeof e==`object`&&`float`in e?e.float:1/0,ut=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},dt=/* @__PURE__ */ new WeakMap,ft=/* @__PURE__ */ new WeakMap,pt=e=>e!==void 0&&et(e)?[[e.fields[0],e.fields[1]],...pt(e.fields[2])]:[],mt=(t,n,r)=>{let i=L(n),a=tt(i,0),o=tt(i,a.next).value;if(a.value!==rt||!et(o)||o.tag!==0)throw new e(`corrupted fingerprint file`);let s=ct(ct(o,0),1),c=(e,t)=>{let n=st.get(t);return!r||n===void 0||ct(ct(e,0),n)===ot};t.clear(),(s!==void 0&&et(s)?s.fields:[]).flatMap(e=>pt(e).toReversed()).forEach(([n,r])=>{if(typeof n!=`string`||!et(r))throw new e(`corrupted fingerprint file`);t.set(n,r.fields.map((e,t)=>c(e,t)?e:0))})},ht=(e,t)=>{let n=ct(t,0),r=ct(n,0),i=ct(ct(n,1),0);if(r===void 0||r===1)return;let a=lt(ct(e===`isabelle`?ct(i,0):i,0)),o=e===`isabelle`?ct(i,1):void 0,s=ct(ct(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`?at[s]:String(ct(s,0))}}},gt=e=>new Map([...e].map(([e,t])=>{let n=new Map(Object.entries(it).flatMap(([e,n])=>{let r=ht(e,ct(t[n.field],0));return r?(dt.set(r,t[n.field]),[[e,r]]):[]}));return ft.set(n,t),[e,n]})),_t=e=>{let t=/* @__PURE__ */ new Date,n=e.method,r={float:n.rlimit??n.timeLimitMs/1e3},i=n.prover===`zenon`?z(0,r,5):n.prover===`isabelle`?z(0,z(0,r),n.tactic??`auto`):z(0,r),a=at.indexOf(e.reason??``),o=e.reason===void 0?0:z(0,a===-1?z(0,e.reason):a);return z(0,z(0,z(0,e.isProved?0:z(0,o),z(it[n.prover].tag,i)),z(0,t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds()),ot,ot,ot))},vt=(e,t)=>{e.clear(),t.forEach((t,n)=>{let r=[...ft.get(t)??Array(23).fill(0)];t.forEach((e,t)=>{r[it[t].field]=dt.get(e)??_t(e)}),e.set(n,r)})},yt=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=ut(r)&t-1;n[i]=z(0,r,z(0,...e),n[i])}),z(0,z(0,e.size,z(0,...n),0,512))},bt=e=>String(e).padStart(2,`0`),xt=(e,t)=>{let n=/* @__PURE__ */ new Date,r=`${e}.history`,i=je(r,`${n.getFullYear()}-${bt(n.getMonth()+1)}-${bt(n.getDate())}_${bt(n.getHours())}_${bt(n.getMinutes())}_${bt(n.getSeconds())}`);Pe(i,{recursive:!0}),[e,...t].filter(e=>I(e)).forEach(e=>F(e,je(i,De(e)),{preserveTimestamps:!0})),Ie(r).map(e=>je(r,e)).sort((e,t)=>Be(t).mtimeMs-Be(e).mtimeMs).slice(10).forEach(e=>ze(e,{recursive:!0,force:!0}))},St=(e,t)=>{Ve(`${t}.tmp`,Buffer.concat([nt(rt),nt(yt(e))])),Re(`${t}.tmp`,t)},Ct={builtin:1,number:2,string:3,ident:4,added:5},wt=()=>({labelFlag:!1,reportLabelsFlag:!1,labelRoot:`Lbl_`,fairnessOption:``,fairAlgorithm:!1,checkTermination:!1,noOld:!1,nocfg:!1,noDoneDisjunct:!1,specOption:!1,myspecOption:!1,specFile:``,optionsInFile:!1,inputVersionNumber:1903}),Tt=e=>{let t={result:0,digitsAfterDecimal:0,isAfterDecimal:!1};for(let n of e)if(n===`.`)t.isAfterDecimal=!0;else if(n<`0`||n>`9`||(t.result=10*t.result+Number(n),t.isAfterDecimal&&(t.digitsAfterDecimal+=1),t.digitsAfterDecimal>3))return-1;return t.result*10**Math.max(0,3-t.digitsAfterDecimal)},Et=[`unfair`,`wf`,`sf`],B=()=>({col:0,line:0,macroCol:0,macroLine:-1,lbl:``}),Dt=e=>e.macroLine<0?`line ${e.line}, column ${e.col}`:`line ${e.line}, column ${e.col} of macro called at line ${e.macroLine}, column ${e.macroCol}`,Ot=e=>{if(e.kind!==`LabeledStmt`)throw new m(`ClassCastException: ${e.kind}`);return e},kt=(e,t)=>{if(t<0||t>=e.length)throw new m(`ArrayIndexOutOfBoundsException: ${t}`);return e[t]},At=(e,t,n)=>({string:e,column:t,type:n}),jt=e=>e.type===Ct.string?e.string.length+2:e.string.length,Mt=(e=[])=>({tokens:e,anchorTokens:void 0,anchorTokCol:void 0}),Nt=e=>{for(;e.tokens.length>0&&e.tokens[0].length===0;)e.tokens.shift();for(;e.tokens.length>0&&e.tokens[e.tokens.length-1].length===0;)e.tokens.pop();let t=Math.min(999999,...e.tokens.filter(e=>e.length>0).map(e=>e[0].column));e.tokens.forEach(e=>e.forEach(e=>{e.column-=t}));let n=[],r=[];e.tokens.forEach((t,i)=>{if(r.push(0),n.push(void 0),t.length===0)return;let a=t[0].column,o=e.tokens.slice(0,i).findLast(e=>e.length>0&&e[0].column<=a);if(o===void 0)return;let s=o.findIndex((e,t)=>t>0&&e.column>a),c=o[(s===-1?o.length:s)-1];n[i]=c,r[i]=c.column}),e.anchorTokens=n,e.anchorTokCol=r},Pt=e=>{let t=Mt(e);return Nt(t),t},Ft=e=>{let t=e.anchorTokens,n=e.anchorTokCol;if(t===void 0||n===void 0)throw new m(`NullPointerException: TLAExpr.renormalize`);e.tokens.forEach((e,r)=>{let i=t[r];if(i===void 0)return;let a=i.column-n[r];if(n[r]=i.column,a<0)throw new p(`TLAExpr.renormalize() found anchor has moved to left.`);e.forEach(e=>{e.column+=a})})},It=e=>Pt(e.tokens.map(e=>e.map(e=>({...e})))),Lt=(e,t,n)=>{let r=t.tokens.length;e.tokens.splice(0,0,...t.tokens.slice(0,r-1));let i=t.tokens[r-1],a=e.tokens[r-1],o=i[i.length-1],s=o.column+jt(o)+n;a.forEach(e=>{e.column+=s}),a.splice(0,0,...i);let c=[...t.anchorTokens??[]],l=[...t.anchorTokCol??[]];for(let t=r;t<e.tokens.length;t++)c.push(e.anchorTokens?.[t-r+1]),l.push(e.anchorTokCol?.[t-r+1]??0);e.anchorTokens=c,e.anchorTokCol=l,Ft(e)},Rt=e=>e.tokens.length===1&&e.tokens[0].length===1,zt=(e,t)=>kt(kt(e.tokens,t.line),t.item),Bt=(e,t,n)=>{if(e.tokens.length<=t.line)throw new s(`TLAExpr.StepCoord called with line too big`);if(e.tokens[t.line].length<=t.item)throw new s(`TLAExpr.StepCoord called with col too big`);let r={line:t.line,item:t.item};for(let t=0;t<n;t++)if(r.item+=1,e.tokens[r.line].length===r.item){for(r.item=0,r.line+=1;r.line<e.tokens.length&&e.tokens[r.line].length===0;)r.line+=1;if(r.line===e.tokens.length)return}return r},Vt=(e,t,n)=>{for(let r=e.tokens.length===0?void 0:{...n};r!==void 0;){let n=zt(e,r),i=n.type===Ct.string;if(!i&&n.string===t)return r;let a=!i&&(n.string===`[`||n.string===`,`)?Bt(e,r,2):void 0,o=a===void 0?void 0:zt(e,a),s=o!==void 0&&o.type!==Ct.string&&[`:`,`|->`,`↦`].includes(o.string),c=i?1:n.string===`.`?2:s?3:1;r=Bt(e,r,c)}},Ht=(e,t,n,r)=>{let i=zt(e,n);if(Rt(e)){let n=It(t);e.tokens=n.tokens,e.anchorTokens=n.anchorTokens,e.anchorTokCol=n.anchorTokCol;return}let a=e.tokens[n.line],o=n.item+1<a.length?a[n.item+1].column-(i.column+jt(i)):0,s=a.splice(n.item+1),c={lineIndex:n.line,indent:+!!r+i.column,isInserting:!r},l=()=>e.tokens[c.lineIndex];if(Rt(t)){let e=t.tokens[0][0];i.string=e.string,i.type=e.type}else{r&&(i.string=`(`,i.type=Ct.builtin);let n=It(t);if(n.tokens.forEach((t,r)=>{if(t.forEach(e=>{e.column+=c.indent,c.isInserting?(i.string=e.string,i.type=e.type,c.isInserting=!1):l().push(e)}),r+1>=n.tokens.length)return;c.indent=0,c.lineIndex+=1;let a=c.lineIndex;e.tokens.splice(a,0,[]);let o=e.anchorTokens??[],s=e.anchorTokCol??[];e.anchorTokens=e.tokens.map((e,t)=>t<a?o[t]:t===a?n.anchorTokens?.[r+1]:o[t-1]),e.anchorTokCol=e.tokens.map((e,t)=>t<a?s[t]:t===a?n.anchorTokCol?.[r+1]??0:s[t-1])}),r){let e=l()[l().length-1];l().push(At(`)`,e.column+jt(e),Ct.builtin))}}let u=l(),d={line:c.lineIndex,item:u.length-1};if(s.length>0){let e=u[u.length-1],t=e.column+jt(e)+o-s[0].column;s.forEach(e=>{e.column+=t,u.push(e)})}return Ft(e),Bt(e,d,1)},Ut=(e,t,n,r=!0)=>{let i=n.map(t=>Vt(e,t,{line:0,item:0}));for(;;){let a=i.reduce((e,t,n)=>t!==void 0&&(e===void 0||t.line<e.position.line||t.line===e.position.line&&t.item<e.position.item)?{index:n,position:t}:e,void 0);if(a===void 0)return;let o=Bt(e,a.position,1),s=Ht(e,t[a.index],a.position,r);i[a.index]=s===void 0?void 0:Vt(e,n[a.index],s),i.forEach((e,t)=>{if(t!==a.index&&e!==void 0&&s!==void 0){if(o===void 0)throw new m(`NullPointerException: TLAExpr.substituteForAll`);e.line===a.position.line&&(e.item+=s.item-o.item),e.line+=s.line-o.line}})}},Wt=(e,t,n)=>{let r=It(e);return Ut(r,t,n),r},Gt=(e,t,n)=>e.map(e=>Wt(e,t,n)),Kt=(e,t)=>{let n=e=>t===`1.7.4`?``:`(col${e.column}) `,r=e.tokens.map(e=>e.map(e=>e.type===Ct.string?`"\\"", "${e.string}", "\\""`:e.string===`\\/`?`"${n(e)}\\\\/"`:e.string.startsWith(`\\`)?`"\\${e.string}"`:e.string===`/\\`?`"${n(e)}/\\\\"`:`"${e.string}"`)),i=r.findIndex(e=>e.length>0);return`<< ${r.map((e,t)=>{let n=i!==-1&&t>i;return e.map((e,t)=>n||t>0?`, ${e}`:e).join(``)}).join(`
|
|
10
|
+
`)} >>`},qt=(e,t,n)=>{let r=e=>Kt(e,n),i=[0],a={value:0},o=e=>(i[a.value+1]=i[a.value]+e.length,a.value+=1,e),s=()=>(--a.value,``),c=()=>`\n${` `.repeat(i[a.value])}`,l=t<1500,u=e=>`${o(`<<`)}${e.map((e,t)=>`${t>0?`, ${c()}`:``}${`kind`in e?m(e):r(e)}`).join(``)}>>${s()}`,d=e=>`${o(`<<`)}${e.map(e=>`"${e}"`).join(`, `)}>>${s()}`,f=e=>`${o(`<< `)}${e.map((e,t)=>`${t>0?`, ${c()}`:``}${u(e)}`).join(``)} >>${s()}`,p=e=>e?`"="`:`"\\\\in"`,m=e=>{switch(e.kind){case`Uniprocess`:return`${o(``)}[type |-> "uniprocess", ${c()} name |-> "${e.name}", ${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` defs |-> `)}${r(e.defs)},${s()}${c()}${o(` prcds |-> `)}${u(e.prcds)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`Multiprocess`:return`${o(``)}[type |-> "multiprocess", ${c()} name |-> "${e.name}", ${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` defs |-> `)}${r(e.defs)},${s()}${c()}${o(` prcds |-> `)}${u(e.prcds)},${s()}${c()}${o(` procs |-> `)}${u(e.procs)}]${s()}${s()}`;case`Procedure`:return l?`${o(``)}[name |-> "${e.name}", ${c()}${o(` params |-> `)}${u(e.params)},${s()}${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`:`${o(``)}[name |-> "${e.name}", ${c()}minusLabels |-> ${d(e.minusLabels)}, plusLabels |->${d(e.plusLabels)}, proceduresCalled |->${d(e.proceduresCalled)},${c()}${o(` params |-> `)}${u(e.params)},${s()}${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`Process`:return l?`${o(``)}[name |-> "${e.name}", ${c()} eqOrIn |-> ${p(e.isEq)},${c()} id |-> ${r(e.id)},${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`:`${o(``)}[name |-> "${e.name}",${c()} fairness |-> "${Et[e.fairness]}", minusLabels |-> ${d(e.minusLabels)}, plusLabels |->${d(e.plusLabels)}, proceduresCalled |->${d(e.proceduresCalled)},${c()} eqOrIn |-> ${p(e.isEq)},${c()} id |-> ${r(e.id)},${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`VarDecl`:return`${o(``)}[var |-> "${e.var}", eqOrIn |-> ${p(e.isEq)}, val |-> ${r(e.val)}]${s()}`;case`PVarDecl`:return`${o(``)}[var |-> "${e.var}", eqOrIn |-> "=", val |-> ${r(e.val)}]${s()}`;case`LabeledStmt`:return`${o(``)}[label |-> "${e.label}",${c()}${o(` stmts |-> `)}${u(e.stmts)}]${s()}${s()}`;case`While`:return`${o(``)}[type |-> "while", ${c()} test |-> ${r(e.test)},${c()}${o(` labDo |-> `)}${u(e.labDo)},${s()}${c()}${o(` unlabDo |-> `)}${u(e.unlabDo)}]${s()}${s()}`;case`Assign`:return`${o(``)}[type |-> "assignment",${c()}${o(` ass |-> `)}${u(e.ass)}]${s()}${s()}`;case`SingleAssign`:return`${o(``)}[lhs |-> ${m(e.lhs)},${c()} rhs |-> ${r(e.rhs)}]${s()}`;case`Lhs`:return`[var |-> "${e.var}", sub |-> ${r(e.sub)}]`;case`If`:return`${o(``)}[type |-> "if", ${c()} test |-> ${r(e.test)},${c()}${o(` then |-> `)}${u(e.Then)},${s()}${c()}${o(` else |-> `)}${u(e.Else)}]${s()}${s()}`;case`Either`:return`${o(``)}[type |-> "either", ${c()}${o(` ors |-> `)}${f(e.ors)}]${s()}${s()}`;case`With`:return`${o(``)}[type |-> "with", ${c()} var |-> "${e.var}",${c()} eqOrIn |-> ${p(e.isEq)},${c()} exp |-> ${r(e.exp)},${c()}${o(` do |-> `)}${u(e.Do)}]${s()}${s()}`;case`When`:return`${o(``)}[type |-> "when", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`PrintS`:return`${o(``)}[type |-> "print", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`Assert`:return`${o(``)}[type |-> "assert", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`Skip`:return`[type |-> "skip"]`;case`LabelIf`:return`${o(``)}[type |-> "labelIf",${c()} test |-> ${r(e.test)},${c()}${o(` unlabThen |-> `)}${u(e.unlabThen)},${s()}${c()}${o(` labThen |-> `)}${u(e.labThen)},${s()}${c()}${o(` unlabElse |-> `)}${u(e.unlabElse)},${s()}${c()}${o(` labElse |-> `)}${u(e.labElse)}]${s()}${c()}${s()}`;case`LabelEither`:return`${o(``)}[type |-> "labelEither",${c()}${o(` clauses |-> `)}${u(e.clauses)}]${s()}${c()}${s()}`;case`Clause`:return`${o(``)}${o(`[unlabOr |-> `)}${u(e.unlabOr)},${s()}${c()}${o(` labOr |-> `)}${u(e.labOr)}]${s()}${c()}${s()}`;case`Call`:return`${o(``)}[type |-> "call",${c()} returnTo |-> "${e.returnTo}",${c()} to |-> "${e.to}",${c()}${o(` args |-> `)}${u(e.args)}]${s()}${s()}`;case`Return`:return`[type |-> "return", from |-> "${e.from??`null`}"]`;case`CallReturn`:return`${o(``)}[type |-> "callReturn",${c()} from |-> "${e.from??`null`}",${c()} to |-> "${e.to}",${c()}${o(`args |-> `)}${u(e.args)}]${c()}${s()}${s()}`;case`CallGoto`:return`${o(``)}[type |-> "callGoto",${c()} after |-> "${e.after}",${c()} to |-> "${e.to}",${c()}${o(`args |-> `)}${u(e.args)}]${c()}${s()}${s()}`;case`Goto`:return`[type |-> "goto", to |-> "${e.to}"]`;case`Macro`:return`${o(``)}[name |-> "${e.name}", ${c()}${o(` params |-> `)}${o(`<<`)}${e.params.join(`, ${c()}`)}>>${s()},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`MacroCall`:return`${o(``)}[type |-> "macrocall",${c()} name |-> "${e.name}",${c()}${o(` args |-> `)}${u(e.args)}]${s()}${s()}`}};return m(e)},Jt=(e,t,n,r,i)=>({lines:e,currentLine:t<e.length?Array.from(e[t]):void 0,line:t,column:n,vcolumn:t<e.length?Array.from(e[t].slice(0,n)).reduce((e,t)=>t===` `?(Math.floor(e/8)+1)*8:e+1,0):0,lastLine:r,lastColumn:i,isTabToSpaces:!1}),Yt=e=>{if(e.currentLine===void 0)return` `;if(e.isTabToSpaces)return e.vcolumn+=1,e.vcolumn%8==0&&(e.isTabToSpaces=!1),` `;if(e.line>e.lastLine||e.line===e.lastLine&&e.column>=e.lastColumn)return` `;if(e.currentLine.length===e.column)return e.line+=1,e.column=0,e.vcolumn=0,e.currentLine=e.line>=e.lines.length?void 0:Array.from(e.lines[e.line]),`
|
|
11
|
+
`;let t=e.currentLine[e.column];return e.column+=1,e.vcolumn+=1,t===` `?(e.vcolumn%8!=0&&(e.isTabToSpaces=!0),` `):t},Xt=e=>{if(e.column>0){--e.column,--e.vcolumn;return}if(e.line===0)throw new s(`PcalCharReader.backspace trying to move past beginning of reader`);--e.line;let t=Array.from(e.lines[e.line]);for(e.currentLine=t,e.column=0,e.vcolumn=0;e.column<t.length-1;)Yt(e)},Zt=e=>{for(;;){let t=Yt(e);if(t===` `)return` `;if(t!==` `&&t!==`
|
|
12
|
+
`)break}return Xt(e),`${(e.currentLine??[]).slice(e.column).join(``)}\n`},Qt=/* @__PURE__ */ new Set([`(`,`[`,`{`,`<<`,`⟨`]),$t=/* @__PURE__ */ new Set([`>>_`,`⟩_`,`]_`,`)`,`}`,`]`,`>>`,`⟩`]),en=/* @__PURE__ */ new Set([...Qt,...$t,...`_ ASSUME ASSUMPTION AXIOM BOOLEAN CASE CONSTANT CONSTANTS EXCEPT EXTENDS FALSE IF INSTANCE LOCAL MODULE OTHER STRING THEOREM TRUE VARIABLE VARIABLES WITH WF_ SF_`.split(` `),...`\\A ∀ \\forall \\E ∃ \\exists \\AA \\EE ~ ¬ \\lnot \\neg <> ◇ CHOOSE ENABLED UNCHANGED SUBSET UNION DOMAIN ' ^+ ⁺ ^* ^#`.split(` `),...`=> ⇒ \\cdot ⋅ <=> ⇔ \\equiv ≡ ~> ↝ -+-> ⇸ \\subseteq ⊆ \\subset ⊂ \\supset ⊃ \\supseteq ⊇ \\ll ≪ \\gg ≫ \\ \\cap \\intersect ∩ \\cup \\union ∪ /\\ ∧ \\/ ∨ \\land \\lor \\X × - + * / ^ | || ‖ & && ++ -- ** // ^^ |- ⊢ |= ⊨ -| ⊣ =| ⫤ <: :> := ≔ ::= ⩴`.split(` `),...`(+) ⊕ (-) ⊖ \\oplus \\ominus (.) ⊙ \\odot (/) ⊘ \\oslash (\\X) ⊗ \\otimes \\uplus ⊎ \\sqcap ⊓ \\sqcup ⊔ \\div ÷ \\star ⋆ \\o ∘ \\circ \\bigcirc ◯ \\bullet ●`.split(` `),...`\\in ∈ \\notin ∉ = # /= ≠ < > =< <= ≤ >= ≥ \\prec ≺ \\succ ≻ \\preceq ⪯ \\succeq ⪰ \\sim ∼ \\simeq ≃ \\approx ≈ \\doteq ≐ \\asymp ≍ \\sqsubset ⊏ \\sqsupset ⊐ \\sqsubseteq ⊑ \\sqsupseteq ⊒ \\propto ∝`.split(` `),...`: -> → |-> ↦ <- ← == ≜ ELSE THEN LET IN [] □ .. ‥ ... … $ $$ ? ?? ⁇ % %% ## @@ !! ‼ \\times \\leq \\geq \\mod \\wr ≀ ≅ ! ; , . -. @`.split(` `)]),tn=e=>/^[A-Za-z_]$/.test(e),nn=e=>/^[0-9]$/.test(e),rn=e=>e===` `||e===`\f`||e===`\r`,an=new Set([...en].filter(e=>!tn(e[0])&&!(e[0]===`\\`&&tn(e[1]??``))).flatMap(e=>Array.from(e,(t,n)=>e.slice(0,e.length-n)))),on=/* @__PURE__ */ new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ~!@#$%^&*()_-+={}[]|:;<,>.?/`'0123456789"),sn=new Set(`; do then := ≔ begin variable variables || ‖ end else elsif if either or while with call return goto print assert skip procedure define process fair`.split(` `)),V={...Ct,dashes:6,endModule:7},cn=()=>({delimiter:``,delimiterLine:0,delimiterCol:0,commentDepth:0}),ln=(e,t,n,r)=>{let i={lines:[],line:[],token:``,state:`start`,column:t.vcolumn,nextColumn:t.vcolumn,nextChar:Yt(t),parenDepth:0,isInQuantifier:!1,isExprEnd:!1,previousToken:` `},a=()=>{i.nextColumn=t.vcolumn,i.nextChar=Yt(t)},o=()=>{i.token+=i.nextChar,a()},c=()=>{i.state=`start`,i.column=i.nextColumn},l=()=>{i.lines.push(i.line),i.line=[],i.column=0},u=e=>{throw new p(`${e} \`${i.token}' found at\n line ${t.line+1}, column ${i.column+1}`)},d=()=>{i.isExprEnd=!0,e.delimiter=i.token,e.delimiterCol=i.column,e.delimiterLine=t.line-+(i.nextChar===`
|
|
13
|
+
`)},f=e=>{if(!n){d(),i.token=``;return}e>V.ident&&u(`Illegal token in an expression`);let t=i.token;e!==V.string&&(sn.has(t)&&!(e===V.ident&&[`.`,`[`,`,`].includes(i.previousToken))||(t===`,`&&!i.isInQuantifier&&!r||t===`)`||t===`}`)&&i.parenDepth===0)?(i.parenDepth!==0&&u(`Expression with an unmatched (, [, {, or << followed by`),i.isInQuantifier&&u("Expression with \\A or \\E but no following `:` followed by"),d(),i.line.length>0&&l()):(e===V.builtin&&Qt.has(t)&&(i.parenDepth+=1),e===V.builtin&&$t.has(t)&&(--i.parenDepth,i.parenDepth<0&&u(`Extra (unmatching)`)),i.previousToken=e===V.string?` `:t,[`\\A`,`∀`,`\\E`,`∃`].includes(t)&&i.parenDepth===0&&(i.isInQuantifier=!0),i.isInQuantifier&&t===`:`&&i.parenDepth===0&&(i.isInQuantifier=!1),(t!==``||e===V.string)&&i.line.push(At(t,i.column,e)),i.token=``)},m=e=>{f(e),c()},h=e=>{o(),i.state=e},g=e=>{a(),i.state=e},_=n=>{switch(i.state){case`start`:if(rn(n))return a(),c();if(tn(n))return h(`id`);if(n===`ℕ`||n===`ℤ`||n===`ℝ`)return o(),m(V.ident);if(nn(n))return h(`numOrId`);if(n===`\\`)return h(`bs`);if(n===`-`)return h(`dash1`);if(n===`=`)return h(`eq1`);if(n===`(`)return g(`leftParen`);if(n===`"`)return g(`string`);if(n===`
|
|
14
|
+
`)return a(),l(),c();if(an.has(n))return h(`builtIn`);if(n===` `){i.state=`done`;return}return o(),u(`Illegal lexeme`);case`id`:return i.token===`WF_`||i.token===`SF_`?m(V.builtin):tn(n)||nn(n)?o():m(en.has(i.token)?V.builtin:V.ident);case`numOrId`:return nn(n)?o():tn(n)?h(`id`):m(V.number);case`bs`:if([`b`,`B`,`o`,`O`,`h`,`H`].includes(n))return h(`numOrBi`);if(tn(n)){i.state=`bsBuiltIn`;return}if(n===`*`){a(),i.token=``,i.state=`lineComment`;return}i.state=`builtIn`;return;case`numOrBi`:i.state=nn(n)?`num`:`bsBuiltIn`;return;case`num`:if(nn(n))return o();if(!tn(n))return m(V.number);o(),i.token.startsWith(`\\`)&&u(`Illegal lexeme`),i.state=`id`;return;case`bsBuiltIn`:return tn(n)&&n!==`_`?o():en.has(i.token)?m(V.builtin):u(`Illegal lexeme `);case`builtIn`:if(an.has(i.token+n))return o();if(!en.has(i.token)){for(Xt(t);!en.has(i.token);)Xt(t),i.token.length===0&&u(`Illegal lexeme`),i.token=Array.from(i.token).slice(0,-1).join(``);a()}return m(V.builtin);case`dash1`:case`dash2`:if(n===`-`)return h(i.state===`dash1`?`dash2`:`dash3`);i.state=`builtIn`;return;case`dash3`:return n!==`-`&&u(`Illegal lexeme`),h(`dashes`);case`dashes`:return n===`-`?o():m(V.dashes);case`eq1`:case`eq2`:if(n===`=`)return h(i.state===`eq1`?`eq2`:`eq3`);i.state=`builtIn`;return;case`eq3`:return n!==`=`&&u(`Illegal lexeme`),h(`eqs`);case`eqs`:return n===`=`?o():m(V.endModule);case`leftParen`:if(n===`*`)return e.commentDepth=1,g(`comment`);i.token=`(`,i.state=`builtIn`;return;case`string`:if(n===`\\`)return h(`escString`);if(n===`"`)return a(),m(V.string);o(),on.has(n)||u(`Illegal character in string`);return;case`escString`:o(),[`"`,`\\`,`t`,`n`,`f`,`r`].includes(n)||u(`Illegal character following \\ in string`),i.state=`string`;return;case`lineComment`:return n===`(`?g(`lineComParen`):n===`*`&&e.commentDepth>0?g(`lineComStar`):n===`
|
|
15
15
|
`||n===` `?(i.token=``,e.commentDepth=0,c()):e.commentDepth===0?o():a();case`lineComParen`:if(n===`*`)return e.commentDepth+=1,g(`lineComment`);e.commentDepth===0&&(i.token+=`(`),i.state=`lineComment`;return;case`lineComStar`:if(n===`)`){if(--e.commentDepth,e.commentDepth<0)throw new s(`Failure of assertion: case LINE_COM_STAR`);return g(`lineComment`)}e.commentDepth===0&&(i.token+=`*`),i.state=`lineComment`;return;case`comment`:case`orComment`:{let t=i.state===`comment`;if(n===`*`)return g(t?`commentStar`:`orCommentStar`);if(n===`(`)return g(t?`commentParen`:`orCommentParen`);if(n===`
|
|
16
16
|
`){i.token=``,a(),l(),i.state=`orComment`;return}if(n===` `)throw new p(t?`Input ended in the middle of a comment`:`Input ended in the middle of a multi-line comment`);return e.commentDepth===1?o():a()}case`commentStar`:case`orCommentStar`:{let t=i.state===`commentStar`?`comment`:`orComment`;if(n!==`)`){e.commentDepth===1&&(i.token+=`*`),i.state=t;return}if(a(),--e.commentDepth,t===`orComment`&&e.commentDepth<0)throw new s(`Assertion failure`);if(e.commentDepth!==0){i.state=t;return}return i.token=``,c()}case`commentParen`:case`orCommentParen`:{let t=i.state===`commentParen`?`comment`:`orComment`;if(n===`*`)return e.commentDepth+=1,g(t);e.commentDepth===1&&(i.token+=`(`),i.state=t;return}}};for(;i.state!==`done`&&!i.isExprEnd;)_(i.nextChar);return i.nextChar!==`
|
|
17
|
-
`&&
|
|
18
|
-
it has already peeked at`);for(;n>o.lookaheadSize;)i.tokens[o.lookaheadSize]=Ot(e.tokenizer,t),o.lookaheadSize+=1;return ht(t)},f=(n=!1)=>{if(o.lookaheadSize!==0)throw new s(`ParseAlgorithm: GetExpr called after lookahead`);let r=Dt(e.tokenizer,t,n);return i.tokens[0]=e.tokenizer.delimiter,i.columns[0]=e.tokenizer.delimiterCol,i.lines[0]=e.tokenizer.delimiterLine,o.lookaheadSize=1,r},h=(e,t)=>{if(e===`;`){let e=u(1);if(`end begin else elsif or do macro procedure process fair define } {`.split(` `).includes(e))return;if(`if either while with call return goto print assert skip`.split(` `).includes(e))throw new p(`Missing \`;' before line ${i.lines[0]+1}, column ${i.columns[0]+1}`)}let n=l();n!==e&&n!==t&&c(`Expected "${e}" but found "${n}"`)},g=e=>{let t=l();t!==e&&c(`Expected "${e}" but found "${t}"`)},_=()=>{let e=l();return e===`=`?!0:e===`\\in`||e===`∈`?!1:c(`Expected "=" or "\\in" but found "${e}"`)},v=()=>h(u(1)===`,`?`,`:`;`),y=()=>h(o.pSyntax?`begin`:`{`),b=e=>{o.cSyntax?h(`}`):(h(`end`),h(e))},x=()=>{u(1)===`variables`?g(`variables`):h(`variable`)},S=()=>{let e={...R(),kind:`VarDecl`,var:l(),col:a.column,line:a.line,isEq:!0,val:At()};if(![`=`,`\\in`,`∈`].includes(u(1)))return o.hasDefaultInitialization=!0,e;if(e.isEq=_(),e.val=f(),e.val.tokens.length===0)throw new m(`NullPointerException`);return e},C=()=>{x();let e=[],t=[`begin`,`{`,`procedure`,`process`,`fair`,`define`,`macro`];for(;!t.includes(u(1));)e.push(S()),v();return e},w=()=>{let e={...R(),kind:`PVarDecl`,var:l(),col:a.column,line:a.line,val:At()};if(u(1)!==`=`)return o.hasDefaultInitialization=!0,e;if(h(`=`),e.val=f(),e.val.tokens.length===0)throw new m(`NullPointerException`);return e},ee=()=>{x();let e=[];for(;u(1)!==`begin`&&u(1)!==`{`;)e.push(w()),v();return e},T=()=>{if(`while if assert print else elsif either or end with when await skip call return goto`.split(` `).includes(u(1)))return!1;let e=ht(t);return e.length>0&&e[0]===`:`&&!(e.length>1&&e[1]===`=`)},E=()=>{if(!T())return``;let t=l();e.isInMacro&&c(`A label may not appear in a macro.`),t===`Done`&&c("Cannot use `Done' as a label."),t===`Error`&&c("Cannot use `Error' as a label."),h(`:`),o.hasLabel=!0,o.allLabels.add(t);let n=u(1);return n!==`+`&&n!==`-`||(h(n),(n===`+`?o.plusLabels:o.minusLabels).push(t),o.omitPC=!1),t},D=()=>{let e=[],t=e=>o.pSyntax&&[`end`,`else`,`elsif`,`or`].includes(e)||o.cSyntax&&e===`}`;for(;!t(u(1));)e.push(...k());return o.cSyntax&&e.length===0&&c(`Empty statement list`),e},O=e=>{g(`{`);let t=D();if(h(`}`),h(`;`),e!==``){if(t[0].lbl!==``)throw new p(`Duplicate labeling of statement`,t[0]);t[0].lbl=e}return t},k=()=>{let e=E();if(o.cSyntax&&u(1)===`{`)return O(e);let t=te();return t.lbl=e,[t]},te=()=>{let e=u(1);if(e===`if`)return j(0);if(e===`either`)return ne();if(e===`with`)return re(0);if(e===`when`||e===`await`){g(e);let t=a.column,n=a.line,r=f();if(r.tokens.length===0)throw new m(`NullPointerException`);return h(`;`),{...R(),kind:`When`,col:t,line:n,exp:r}}if(e===`print`||e===`assert`){g(e);let t=a.column,n=a.line,r=f();return r.tokens.length===0&&c(`Empty expression in ${e} statement at `),h(`;`),{...R(),kind:e===`print`?`PrintS`:`Assert`,col:t,line:n,exp:r}}if(e===`skip`){g(`skip`);let e={...R(),kind:`Skip`,col:a.column,line:a.line};return h(`;`),e}if(e===`call`)return oe();if(e===`return`){g(`return`);let e={...R(),kind:`Return`,col:a.column,line:a.line,from:o.currentProcedure};return h(`;`),e}if(e===`goto`){g(`goto`);let e=a.column,t=a.line,n=l();return o.gotoUsed=!0,(n===`Done`||n===`"Done"`)&&(o.gotoDoneUsed=!0),h(`;`),{...R(),kind:`Goto`,col:e,line:t,to:n}}return e===`while`?A():d(1)[0]===`(`?se():M()},A=()=>{g(`while`);let e=a.column,t=a.line;o.cSyntax&&h(`(`);let n=f();o.cSyntax&&h(`)`),n.tokens.length===0&&c(`Empty while test at `),o.pSyntax&&h(`do`);let r=o.pSyntax?D():k();return o.pSyntax&&(h(`end`),h(`while`),h(`;`)),r.length===0&&c(`Missing body of while statement at`),{...R(),kind:`While`,col:e,line:t,test:n,unlabDo:r,labDo:[]}},j=e=>{g(e===0?`if`:`elsif`);let t={...R(),kind:`LabelIf`,col:a.column,line:a.line,test:Xe(),unlabThen:[],labThen:[],unlabElse:[],labElse:[]};o.cSyntax&&h(`(`),t.test=f(),o.cSyntax&&h(`)`),t.test.tokens.length===0&&c(`Empty if test at `),o.pSyntax&&h(`then`),t.unlabThen=o.pSyntax?D():k();let n=u(1);return n===`else`&&(g(`else`),t.unlabElse=o.pSyntax?D():k()),o.pSyntax&&n===`elsif`&&(t.unlabElse=[j(e+1)]),o.pSyntax&&![`else`,`elsif`,`end`].includes(n)&&c(`Expecting "else", "elsif", or "end"`),o.pSyntax&&e===0&&(h(`end`),h(`if`),h(`;`)),t.unlabElse.length===0&&qe(t.unlabThen,t.unlabThen.length-1),t},ne=()=>{g(`either`);let e={...R(),kind:`LabelEither`,col:a.column,line:a.line,clauses:[]};for(;;){let t={...R(),kind:`Clause`,unlabOr:o.pSyntax?D():k(),labOr:[]};if(t.unlabOr.length===0)throw new p("`either' statement with empty `or' clause",e);if(e.clauses.push(t),u(1)!==`or`)break;g(`or`)}if(o.pSyntax&&(g(`end`),h(`either`),h(`;`)),e.clauses.length===1)throw new p("`either' statement has no `or'",e);return e},re=e=>{e===0&&(h(`with`),o.cSyntax&&h(`(`));let t={...R(),kind:`With`,col:a.column,line:a.line,var:l(),isEq:!0,exp:Xe(),Do:[]};t.isEq=_(),t.exp=f(),(o.pSyntax||u(1)!==`)`)&&v(),t.exp.tokens.length===0&&c(`Empty with expression at `);let n=o.pSyntax&&u(1)===`do`,r=o.cSyntax&&u(1)===`)`;if(n&&h(`do`),r&&g(`)`),t.Do=n?D():r?k():[re(e+1)],n&&(h(`end`),h(`with`),h(`;`)),t.Do.length===0)throw new p(`Missing body of with statement`,t);return t},ie=()=>{let e=i.columns[0]+1,t=i.lines[0]+1,n={...R(),kind:`Lhs`,col:e,line:t,var:l(),sub:f()};h(`:=`,`≔`);let r=f();return r.tokens.length===0&&c(`Empty right-hand side of assignment at `),{...R(),kind:`SingleAssign`,col:e,line:t,lhs:n,rhs:r}},M=()=>{let e={...R(),kind:`Assign`,col:i.columns[0]+1,line:i.lines[0]+1,ass:[ie()]};for(;u(1)===`||`||u(1)===`‖`;){l();try{e.ass.push(ie())}catch(e){if(!(e instanceof p))throw e;c(`Bad assignment statement at `)}}return h(`;`),e},ae=()=>{let e=[];if(d(0)[0]!==`)`)for(;;){let t=f();if(e.push(t),t.tokens.length===0&&c(`Empty argument in call statement at `),u(1)===`)`)break;h(`,`)}return h(`)`),h(`;`),e},N=()=>{g(`call`);let e={...R(),kind:`Call`,col:a.column,line:a.line,returnTo:``,to:l(),args:[]};return h(`(`),e.args=ae(),o.proceduresCalled.includes(e.to)||o.proceduresCalled.push(e.to),e},oe=()=>{let e=N();if(u(1)===`return`)return g(`return`),h(`;`),{...R(),kind:`CallReturn`,col:e.col,line:e.line,to:e.to,from:o.currentProcedure,args:e.args};if(u(1)!==`goto`)return e;g(`goto`);let t={...R(),kind:`CallGoto`,col:e.col,line:e.line,to:e.to,after:l(),args:e.args};return o.gotoUsed=!0,(t.to===`Done`||t.to===`"Done"`)&&(o.gotoDoneUsed=!0),h(`;`),t},se=()=>{let e={...R(),kind:`MacroCall`,name:l(),col:a.column,line:a.line,args:[]};return g(`(`),e.args=ae(),e},ce=t=>{e.isInMacro=!0,g(`macro`);let n={...R(),kind:`Macro`,col:a.column,line:a.line,name:l(),params:[],body:[]};for(h(`(`);u(1)!==`)`;)n.params.length>0&&h(`,`),n.params.push(l());return g(`)`),y(),n.body=D(),b(`macro`),u(1)===`;`&&l(),be(n.body,t),e.isInMacro=!1,n},le=()=>{h(`procedure`);let e={...R(),kind:`Procedure`,col:a.column,line:a.line,name:l(),minusLabels:[],plusLabels:[],proceduresCalled:[],params:[],decls:[],body:[]};for(o.currentProcedure=e.name,o.plusLabels=[],o.minusLabels=[],o.proceduresCalled=[],h(`(`);u(1)!==`)`;)e.params.length>0&&h(`,`),e.params.push(w());return g(`)`),u(1)!==`begin`&&u(1)!==`{`&&(e.decls=ee()),y(),e.body=D(),b(`procedure`),u(1)===`;`&&l(),o.currentProcedure=void 0,e.plusLabels=o.plusLabels,e.minusLabels=o.minusLabels,e.proceduresCalled=o.proceduresCalled,e},ue=()=>{h(`process`);let e=a.column,t=a.line;o.cSyntax&&h(`(`);let n=l(),r=_(),i=f();o.plusLabels=[],o.minusLabels=[],o.proceduresCalled=[],o.cSyntax&&h(`)`),i.tokens.length===0&&c(`Empty process id at `);let s=u(1)===`begin`||u(1)===`{`?[]:C();y();let d=D();return b(`process`),u(1)===`;`&&l(),{...R(),kind:`Process`,col:e,line:t,name:n,fairness:0,minusLabels:o.minusLabels,plusLabels:o.plusLabels,proceduresCalled:o.proceduresCalled,isEq:r,id:i,decls:s,body:d}},de=()=>{let e=`${r.labelRoot}${o.nextLabelNum}`;return o.nextLabelNum+=1,o.allLabels.has(e)?de():e},fe=e=>{e.lbl===``&&(e.lbl=de(),o.addedLabels.push(e.lbl),o.addedLabelsLocs.push(Ge(e)))},pe=(e,t,n,r,i)=>{Nt(r,i);let a={isNextLabeled:t,hasLabel:!1},s=e=>{fe(e),a.hasLabel=!0,i.length=0};return e.forEach(e=>{if(e.lbl!==``&&(a.hasLabel=!0,i.length=0,n))throw new p("Label in `with' statement",e);if(a.isNextLabeled){if(n)throw new p("Statement follows `call' or `return' inside a `with' statement.",e);s(e),a.isNextLabeled=!1}switch(e.kind){case`LabelIf`:{let t=[],r=[],o=pe(e.unlabThen,!1,n,i,t);a.isNextLabeled=pe(e.unlabElse,!1,n,i,r)||o,Nt(jt(t,r),i);return}case`LabelEither`:{let t=[];e.clauses.forEach(e=>{let r=[];a.isNextLabeled=pe(e.unlabOr,!1,n,i,r)||a.isNextLabeled,Nt(jt(r,t),t)}),Nt(t,i);return}case`While`:if(n)throw new p("`while' inside a `with' statement",e);s(e),pe(e.unlabDo,!1,!1,i,[]),a.isNextLabeled=!1;return;case`With`:{let t=[];a.isNextLabeled=pe(e.Do,!1,!0,n?[...r]:[],t),Nt(t,i),!n&&!Mt(r,i)&&s(e);return}}let t=e.kind===`Call`||e.kind===`CallGoto`,c=e.kind===`Return`||e.kind===`CallReturn`,l=e.kind===`Assign`?jt([],e.ass.map(e=>e.lhs.var)):t||c?[`stack`,...c||e.to===o.currentProcedure?o.procedures.flatMap(e=>[...e.params,...e.decls].map(e=>e.var)):[]]:[];if(a.isNextLabeled=t||c||e.kind===`Goto`,Mt(i,l))Nt(jt(i,l),i);else{if(n)throw new p(e.kind===`Assign`?"Second assignment to same variable inside a `with' statement":"Call or return makes second assignment to a variable inside a `with' statement",e);s(e),Nt(l,i)}}),a.hasLabel||a.isNextLabeled},me=e=>{let t=e=>{let t=e.findIndex(e=>e.lbl!==``),n=t===-1?e:e.slice(0,t);return me(n),{unlabeled:n,labeled:he(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}}})},he=e=>{let t=[];return e.forEach(e=>{if(e.lbl===``&&t.length>0)t[t.length-1].stmts.push(e);else{if(e.lbl===``)throw new s(`Failure of assertion: Missing Label in MakeLabeledStmtSeq`);t.push({...R(),kind:`LabeledStmt`,col:e.col,line:e.line,macroCol:e.macroCol,macroLine:e.macroLine,label:e.lbl,stmts:[e]})}}),t.forEach(e=>me(e.stmts)),t},ge=(e,t)=>{let n=e[t];switch(n.kind){case`LabelIf`:{let r=P(n.unlabThen);n.labThen.forEach(e=>P(e.stmts));let i=P(n.unlabElse);return n.labElse.forEach(e=>P(e.stmts)),n.labThen.length>0||n.labElse.length>0||r===2||i===2?2:(e[t]={...R(),kind:`If`,test:n.test,Then:n.unlabThen,Else:n.unlabElse},+(r+i>0))}case`LabelEither`:{let r=n.clauses.reduce((e,t)=>{let n=Math.max(e,P(t.unlabOr));return t.labOr.forEach(e=>P(e.stmts)),t.labOr.length>0?2:n},0);return r===2?2:(e[t]={...R(),kind:`Either`,ors:n.clauses.map(e=>e.unlabOr)},r)}case`With`:{let e=P(n.Do);if(e===2)throw new p(`with statement at ${Ge(n)} contains a labeled statement`);return e}case`While`:if(t!==0)throw new s("ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.");return P(n.unlabDo),n.labDo.forEach(e=>P(e.stmts)),0;case`Call`:return e[t+1]?.kind===`Return`?0:1;case`Return`:case`CallReturn`:if(o.currentProcedure===void 0)throw new p(`return statement not in a procedure at ${Ge(n)}`);return 1;case`Goto`:case`CallGoto`:return 1;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`MacroCall`:return 0;default:throw new s(`ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${n.kind}`)}},P=e=>{for(let t=0;t<e.length;t++){let n=ge(e,t);if(n!==0){if(t===e.length-1)return n;throw new s(`Translator discovered later than it should have that\n Statement at ${Ge(e[t+1])} must have a label`)}}return 0},_e=e=>{pe(e,!0,!1,[],[]);let t=he(e);return t.forEach(e=>P(e.stmts)),t},ve=(e,t,n,r,i)=>{let a=e=>ct(e,t,n),o=e=>e.map(e=>ve(e,t,n,r,i)),c=e=>e.map(e=>({...R(),kind:`LabeledStmt`,label:e.label,stmts:e.stmts.map(e=>ve(e,t,n,-1,0))})),l={...R(),col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine};switch(e.kind){case`Assign`:return{...l,kind:`Assign`,ass:e.ass.map(e=>ye(e,t,n,r,i))};case`If`:return{...l,kind:`If`,test:a(e.test),Then:o(e.Then),Else:o(e.Else)};case`Either`:return{...l,kind:`Either`,ors:e.ors.map(o)};case`With`:return{...l,kind:`With`,var:e.var,isEq:e.isEq,exp:a(e.exp),Do:o(e.Do)};case`When`:case`Assert`:case`PrintS`:return{...l,kind:e.kind,exp:a(e.exp)};case`Skip`:return{...l,kind:`Skip`,macroCol:r>0?i:0,macroLine:r>0?r:-1};case`While`:return{...l,kind:`While`,test:a(e.test),unlabDo:o(e.unlabDo),labDo:c(e.labDo)};case`LabelIf`:return{...l,kind:`LabelIf`,test:a(e.test),unlabThen:o(e.unlabThen),labThen:c(e.labThen),unlabElse:o(e.unlabElse),labElse:c(e.labElse)};case`LabelEither`:return{...l,kind:`LabelEither`,clauses:e.clauses.map(e=>({...R(),kind:`Clause`,labOr:c(e.labOr),unlabOr:o(e.unlabOr)}))};case`Call`:return{...l,kind:`Call`,to:e.to,returnTo:e.returnTo,args:lt(e.args,t,n)};case`Return`:return{...l,kind:`Return`,from:e.from};case`CallReturn`:return{...l,kind:`CallReturn`,to:e.to,from:e.from,args:lt(e.args,t,n)};case`CallGoto`:return{...l,kind:`CallGoto`,to:e.to,after:e.after,args:lt(e.args,t,n)};case`Goto`:return{...l,kind:`Goto`,to:e.to};default:throw new s(`Found unexpected statement type in macro at${Ge(e)}`)}},ye=(e,t,n,r,i)=>{let a=ct(e.rhs,t,n),o={...R(),kind:`Lhs`,var:e.lhs.var,sub:e.lhs.sub.tokens.length===0?e.lhs.sub:ct(e.lhs.sub,t,n)},s={...R(),kind:`SingleAssign`,col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine,lhs:o,rhs:a},c=n.indexOf(o.var);if(c===-1)return s;let l=t[c],u=rt(l,{line:0,item:0});if(u.type!==L.ident)throw new p(`Macro expansion substitutes \`${u.string}' for assignment variable\n at ${Ge(s)}`);if(o.var=u.string,it(l,{line:0,item:0},1)===void 0)return s;let d=et(l);return d.tokens[0].splice(0,1),Ze(d),o.sub.tokens.length===0?o.sub=d:tt(o.sub,d,0),s},be=(e,t)=>{let n=e.flatMap(e=>{switch(e.kind){case`LabelIf`:return be(e.unlabThen,t),be(e.unlabElse,t),[e];case`LabelEither`:return e.clauses.forEach(e=>be(e.unlabOr,t)),[e];case`With`:return be(e.Do,t),[e];case`While`:return be(e.unlabDo,t),[e];case`MacroCall`:return xe(e,t);default:return[e]}});e.splice(0,e.length,...n)},xe=(e,t)=>{let n=t.findLast(t=>t.name===e.name);if(n===void 0)throw new p(`Macro ${e.name} undefined,\n at ${Ge(e)}`);if(n.params.length!==e.args.length)throw new p(`Macro ${e.name} called with wrong number of arguments at \n ${Ge(e)}`);let r=n.body.map(t=>ve(t,e.args,n.params,e.line,e.col));return r.length>0&&(r[0].lbl=e.lbl),r},Se=e=>{e.forEach((t,n)=>{if(e.slice(n+1).some(e=>e.name===t.name))throw new p(`Multiple definitions of macro name \`${t.name}'`)})},Ce=e=>{if(e.length===0)return;let t=()=>{o.omitPC=!1,o.omitStutteringWhenDone=!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`||!nt(r.test)||r.test.tokens[0][0].string!==`TRUE`)return t();r.labDo.length>0&&(o.omitPC=!1),r.unlabDo.some(e=>[`LabelIf`,`LabelEither`,`LabeledStmt`].includes(e.kind))&&(o.omitPC=!1)},we=()=>{let e=o.addedLabels.length>1?`Missing labels at the following locations:`:`Missing label at the following location:`;throw new p([e,...o.addedLabelsLocs].join(`
|
|
19
|
-
`))},Te=()=>{r.reportLabelsFlag?(e.log(o.addedLabels.length>1?`The following labels were added:`:`The following label was added:`),o.addedLabels.forEach((t,n)=>e.log(` ${t} at ${o.addedLabelsLocs[n]}`))):e.log(`Labels added.`)},Ee=e=>o.procedures.forEach(t=>{o.currentProcedure=t.name,be(t.body,e),t.body=_e(t.body)}),F=()=>{n&&(l()!==`algorithm`&&c("`--fair' not followed by `algorithm'"),r.fairAlgorithm=!0);let t=l();o.cSyntax=u(1)===`{`,o.pSyntax=!o.cSyntax,o.cSyntax&&g(`{`);let i=u(1)===`variable`||u(1)===`variables`?C():[],a={value:Xe()};u(1)===`define`&&(g(`define`),o.cSyntax&&h(`{`),a.value=f(!0),b(`define`),h(`;`));let s=[];for(;u(1)===`macro`;)s.push(ce(s));for(;u(1)===`procedure`;)o.procedures.push(le()),o.omitPC=!1;if(u(1)===`fair`&&(u(2)===`process`||u(2)===`+`&&u(3)===`process`)||u(1)===`process`){let e=[];for(;u(1)===`fair`||u(1)===`process`;){let t=u(1)===`fair`;t&&g(`fair`);let n=t&&u(1)===`+`;n&&g(`+`);let i=n||!t&&r.fairnessOption===`sf`?2:t||r.fairnessOption===`wf`?1:0;e.push({...ue(),fairness:i})}b(`algorithm`),Se(s);let n=e.map(e=>(be(e.body,s),e.body=_e(e.body),o.omitStutteringWhenDone=!0,Ce(e.body),o.omitStutteringWhenDone));return o.omitStutteringWhenDone=n.includes(!0),Ee(s),o.addedLabels.length>0&&(r.labelFlag||we(),Te()),o.gotoDoneUsed&&(o.omitPC=!1,o.omitStutteringWhenDone=!1),o.gotoUsed&&(o.omitPC=!1),{...R(),kind:`Multiprocess`,name:t,decls:i,defs:a.value,macros:s,prcds:o.procedures,procs:e}}r.inputVersionNumber===1500&&u(1)===`fair`&&(h(`fair`),u(1)===`+`&&h(`+`),r.fairnessOption=`wf`),n&&([``,`wf`,`wfNext`].includes(r.fairnessOption)||e.log(`Warning: Option \`${r.fairnessOption}' specified for --fair algorithm.`),r.fairnessOption=`wf`),y();let d=D();Se(s),be(d,s),Ee(s),o.cSyntax&&h(`}`),b(`algorithm`);let p=_e(d);return o.addedLabels.length>0&&(o.hasLabel&&!r.labelFlag&&we(),Te()),o.gotoUsed&&(o.omitPC=!1),o.gotoDoneUsed||Ce(p),o.gotoDoneUsed&&(o.omitPC=!1,o.omitStutteringWhenDone=!1),{...R(),kind:`Uniprocess`,name:t,decls:i,defs:a.value,macros:s,prcds:o.procedures,body:p}};try{return{ast:F(),omitPC:o.omitPC,omitStutteringWhenDone:o.omitStutteringWhenDone,hasDefaultInitialization:o.hasDefaultInitialization}}catch(e){if(!(e instanceof m))throw e;return c(`Unknown error at or before`)}},B={global:0,label:1,procedure:2,process:3,processVar:4,procedureVar:5,parameter:6},Ft=[`Global variable`,`Label`,`Procedure`,`Process`,`Process variable`,`Procedure variable`,`Parameter`],It=/* @__PURE__ */ new Set([B.global,B.processVar,B.procedureVar,B.parameter]),Lt=(e,t,n,r)=>e.symbols.find(e=>e.id===n&&e.context===r&&e.type===t),Rt=(e,t,n)=>e.symbols.find(e=>e.id===t&&e.context===n),zt=(e,t)=>{let n=e.procedures.findIndex(e=>e.name===t);return n===-1?e.procedures.length:n},Bt=(e,t)=>{let n=e.processes.findIndex(e=>e.name===t);return n===-1?e.processes.length:n},Vt=(e,t,n,r,i,a,o)=>!(t===B.procedureVar||t===B.processVar||t===B.parameter?Lt(e,B.global,n,``)!==void 0||Rt(e,n,r)!==void 0:Lt(e,t,n,r)!==void 0)&&(e.symbols.push({type:t,id:n,context:r,contextType:i,line:a,col:o,useThis:n}),!0),Ht=(e,t,n,r)=>Lt(e,t,n,r)?.useThis??n,Ut=(e,t,n)=>{let r=Rt(e,t,n);return r===void 0?t:It.has(r.type)?r.useThis:t},Wt=e=>{let t={symbols:[],procedures:[],processes:[],disambiguateReport:[],errorReport:``,initialPC:void 0},n=(e,n,i)=>{Vt(t,B.label,e.label,n,i,e.line,e.col)||(t.errorReport+=`\nLabel ${e.label} redefined at line ${e.line}, column ${e.col}`),e.stmts.forEach(e=>r(e,n,i))},r=(e,t,i)=>{let a=e=>e.forEach(e=>r(e,t,i)),o=e=>e.forEach(e=>n(e,t,i));switch(e.kind){case`While`:a(e.unlabDo),o(e.labDo);return;case`If`:a(e.Then),a(e.Else);return;case`With`:a(e.Do);return;case`LabelIf`:a(e.unlabThen),o(e.labThen),a(e.unlabElse),o(e.labElse);return;case`Either`:e.ors.forEach(a);return;case`LabelEither`:e.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 s(`Unexpected AST type ${e.kind}`)}},i=(e,n,r=`process`,i=n===``?B.global:B.processVar)=>{Vt(t,i,e.var,n,r,e.line,e.col)||(t.errorReport+=`\n${Ft[i]} ${e.var} redefined at line ${e.line}, column ${e.col}`)};if(Vt(t,B.global,`pc`,``,``,0,0),e.prcds.length>0&&Vt(t,B.global,`stack`,``,``,0,0),e.decls.forEach(e=>i(e,``)),e.prcds.forEach(e=>{let r=zt(t,e.name)<t.procedures.length;r&&(t.errorReport+=`\nProcedure ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.procedures.push({name:e.name,params:e.params,decls:e.decls,initialPC:e.body.length===0?void 0:Ke(e.body[0]).label}),Vt(t,B.procedure,e.name,``,`procedure`,e.line,e.col),e.decls.forEach(t=>i(t,e.name,`procedure`,B.procedureVar)),e.params.forEach(t=>i(t,e.name,`procedure`,B.parameter)),e.body.forEach(t=>n(Ke(t),e.name,`procedure`))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>{let r=Bt(t,e.name)<t.processes.length;r&&(t.errorReport+=`\nProcess ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.processes.push({name:e.name,initialPC:e.body.length===0?void 0:Ke(e.body[0]).label}),Vt(t,B.process,e.name,``,`process`,e.line,e.col),e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>n(Ke(t),e.name,`process`))}),e.kind===`Uniprocess`&&(e.body.length>0&&(t.initialPC=Ke(e.body[0]).label),e.body.forEach(e=>n(Ke(e),``,``))),t.errorReport.length>0)throw new p(t.errorReport);return t},Gt=e=>{let t=t=>e.symbols.filter(e=>e.useThis===t).length>1;for(let n=0;n<=7;n+=1)e.symbols.forEach(r=>{if(r.type!==n)return;r.useThis=r.id;for(let e=1;n>0&&t(r.useThis);e+=1)r.useThis+=e===1?`_`:r.context[e-2]??String(n);if(r.id===r.useThis)return;let i=r.context.length===0?``:` of ${r.contextType} ${r.context}`;e.disambiguateReport.push(`\\* ${Ft[r.type]} ${r.id}${i} at line ${r.line} col ${r.col} changed to ${r.useThis}`)})},Kt=e=>{let t=e.symbols.filter(e=>e.id===`defaultInitValue`).map(e=>`${Ft[e.type]} name`);if(t.length>0)throw new p(`Cannot use \`defaultInitValue' as ${t.join(` or `)}`)},qt=(e,t,n)=>{let r=(e,n)=>{let r=[],i=[];e.tokens.forEach(e=>e.forEach(e=>{if(e.type!==L.ident)return;let a=Ut(t,e.string,n);r.includes(e.string)||a===e.string||(r.push(e.string),i.push(Qe([[Xt(a)]])))})),i.length>0&&st(e,i,r,!1)},i=(e,n)=>{e.var=Ut(t,e.var,n),r(e.val,n)},a=(e,n)=>e.forEach((r,i)=>{e[i]=Ht(t,B.label,r,n)}),o=(e,n)=>e===void 0?void 0:Ht(t,B.procedure,e,n),c=(e,n)=>{e.label=Ht(t,B.label,e.label,n),e.stmts.forEach(e=>l(e,n))},l=(e,n)=>{let i=e=>e.forEach(e=>l(e,n)),a=e=>e.forEach(e=>c(e,n)),u=e=>e.forEach(e=>r(e,n));switch(e.kind){case`LabeledStmt`:c(e,n);return;case`While`:i(e.unlabDo),a(e.labDo),r(e.test,n);return;case`Assign`:e.ass.forEach(e=>{e.lhs.var=Ut(t,e.lhs.var,n),r(e.lhs.sub,n),r(e.rhs,n)});return;case`If`:i(e.Then),i(e.Else),r(e.test,n);return;case`With`:r(e.exp,n),i(e.Do);return;case`When`:case`PrintS`:case`Assert`:r(e.exp,n);return;case`Skip`:return;case`LabelIf`:r(e.test,n),i(e.unlabThen),a(e.labThen),i(e.unlabElse),a(e.labElse);return;case`Call`:e.returnTo=Ht(t,B.procedure,e.returnTo,n),e.to=Ht(t,B.procedure,e.to,n),u(e.args);return;case`Return`:e.from=o(e.from,n);return;case`CallReturn`:e.from=o(e.from,n),e.to=Ht(t,B.procedure,e.to,n),u(e.args);return;case`CallGoto`:e.after=Ht(t,B.procedure,e.after,n),e.to=Ht(t,B.procedure,e.to,n),u(e.args);return;case`Goto`:if(Lt(t,B.label,e.to,n)===void 0&&e.to!==`Done`)throw new p(`goto to non-existent label \`${e.to}' at line ${e.line}, column ${e.col}`);e.to=Ht(t,B.label,e.to,n);return;case`Either`:e.ors.forEach(i);return;case`LabelEither`:e.clauses.forEach(e=>{i(e.unlabOr),a(e.labOr)});return;default:throw new s(`Unexpected AST type${e.kind}`)}},u=e=>{e.decls.forEach(t=>i(t,e.name)),e.params.forEach(t=>i(t,e.name)),e.body.forEach(t=>c(Ke(t),e.name));let n=qe(t.procedures,zt(t,e.name));a(e.plusLabels,e.name),a(e.minusLabels,e.name),n.initialPC!==void 0&&(n.initialPC=Ht(t,B.label,n.initialPC,e.name)),e.name=Ht(t,B.procedure,e.name,``),n.name=e.name},d=e=>{e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>c(Ke(t),e.name));let n=qe(t.processes,Bt(t,e.name));a(e.plusLabels,e.name),a(e.minusLabels,e.name),n.initialPC!==void 0&&(n.initialPC=Ht(t,B.label,n.initialPC,e.name)),e.name=Ht(t,B.process,e.name,``),n.name=e.name};e.decls.forEach(e=>i(e,``)),e.kind===`Multiprocess`&&((e,t)=>{e.forEach(u);let r=e.map(e=>e.name),i=e.map(e=>r.map(t=>e.proceduresCalled.includes(t)));r.forEach((e,t)=>i.forEach(e=>e.forEach((n,r)=>{e[r]=n||e[t]&&i[t][r]}))),e.forEach((e,t)=>{e.proceduresCalled=r.filter((e,n)=>i[t][n])});for(let e of t){d(e);let t=e.proceduresCalled;for(let e=0;e<t.length;e+=1){let a=r.indexOf(t[e]);if(a===-1){n(`\nUnrecoverable error:\n -- Could not find procedure name \`${t[e]}'.\n`);return}r.forEach((e,n)=>{i[a][n]&&!t.includes(e)&&t.push(e)})}}})(e.prcds,e.procs),e.kind===`Uniprocess`&&(e.prcds.forEach(u),e.body.forEach(e=>c(Ke(e),``))),t.initialPC!==void 0&&(t.initialPC=Ht(t,B.label,t.initialPC,``))},Jt=e=>Je(e,0,L.string),Yt=e=>Je(e,0,L.added),V=e=>Je(e,0,L.builtin),Xt=e=>Je(e,0,L.ident),Zt=(e,t)=>{let n=[];return e.forEach(e=>{let r=n.at(-1),i=r===void 0?0:r.column+Ye(r)+t;n.push(Je(e.string,i,e.type))}),Qe([n])},Qt=e=>e.tokens.forEach((t,n)=>{let r={column:n===0||n===e.tokens.length-1?1:6};t.forEach(e=>{if(e.column=r.column,r.column+=Ye(e),e.type===L.builtin)switch(e.string){case`|->`:case`↦`:e.column=Math.max(16,e.column+1),r.column=e.column+5;return;case`[`:case`<<`:r.column+=1;return;case`]`:case`>>`:e.column+=1,r.column+=1;return;case`\\o`:e.column+=1,r.column+=2}})}),$t=(e,t,n,r=0,i=0)=>({...R(),kind:`SingleAssign`,line:r,col:i,lhs:{...R(),kind:`Lhs`,var:e,sub:t},rhs:n}),en=(e,t=0,n=0)=>({...R(),kind:`Assign`,line:t,col:n,ass:e}),tn=(e,t,n=0,r=0)=>en([$t(e,Qe([]),t,n,r)],n,r),nn=e=>{if(e.tokens.length>1)return!1;let t=qe(e.tokens,0);return t.length===1?t[0].string===`TRUE`:t.length===3&&t[0].string===`(`&&t[1].string===`TRUE`&&t[2].string===`)`},rn=e=>({...R(),kind:`When`,exp:Zt([Yt(`pc`),V(`=`),Jt(e)],1)}),an=e=>tn(`pc`,Qe([[Jt(e??`null`)]])),on=e=>[Xt(`Head`),V(`(`),Yt(`stack`),V(`)`),V(`.`),Xt(e)],sn=()=>[Xt(`Tail`),V(`(`),Yt(`stack`),V(`)`)],cn=e=>Qe([on(e)]),ln=(e,t,n,r)=>{let i=[[V(`<<`),V(`[`),Xt(`procedure`),V(`|->`),Jt(e),V(`,`)],[Xt(`pc`),V(`|->`),...t]];n.forEach(e=>{i[i.length-1].push(V(`,`)),i.push([Xt(e.var),V(`|->`),Xt(e.var)])}),i[i.length-1].push(V(`]`),V(`>>`)),i.push(r);let a=Xe(i);return Qt(a),Ze(a),a},un=(e,t,n)=>{if(t.params.length!==n.args.length)throw new p(`Procedure ${n.to} called with wrong number of arguments`,n);return t.params.forEach((t,r)=>e.ass.push($t(t.var,Qe([]),n.args[r],n.line,n.col))),[e,...t.decls.map(e=>tn(e.var,e.val,n.line,n.col)),an(t.initialPC)]},dn=(e,t,n)=>{let r={procedure:void 0},i=(e,n)=>{let r=zt(t,e.to);if(r===t.procedures.length)throw new p(`Call of non-existent procedure ${e.to}`,e);let i=t.procedures[r],a=ln(e.to,[Jt(n)],[...i.decls,...i.params],[V(`\\o`),Yt(`stack`)]);return un(tn(`stack`,a,e.line,e.col),i,e)},a=e=>{e.from??=r.procedure;let n=e.from;if(n===void 0)throw new p("`return' statement not in procedure",e);let i=zt(t,n);if(i>=t.procedures.length)throw new p(`Error in procedure (perhaps name used elsewhere)`,e);let a=t.procedures[i],o=(t,n)=>en([$t(t,Xe(),n,e.line,e.col)],e.line,e.col);return[o(`pc`,cn(`pc`)),...a.decls.map(e=>o(e.var,cn(e.var))),...a.params.map(e=>o(e.var,cn(e.var))),o(`stack`,Qe([sn()]))]},o=e=>{let n=e.from;if(n===void 0)throw new p(`\`return' statement following \`call' at ${Ge(e)} not in a procedure`);let r=qe(t.procedures,zt(t,n)),i=zt(t,e.to);if(i===t.procedures.length)throw new p(`Call of non-existent procedure ${e.to}`,e);let a=t.procedures[i],o=en([],e.line,e.col);if(n!==e.to){r.decls.forEach(t=>o.ass.push($t(t.var,Xe(),cn(t.var),e.line,e.col)));let t=ln(e.to,on(`pc`),[...a.decls,...a.params],[V(`\\o`),...sn()]);o.ass.push($t(`stack`,Qe([]),t,e.line,e.col))}return un(o,a,e)},s=(e,t)=>{if(e.length===0)return{stmts:[],labeledStmts:[],needsGoto:!n};let r={stmts:e,labeledStmts:[],needsGoto:!1},c=e[e.length-1];switch(c.kind){case`LabelIf`:case`LabelEither`:{let n=c.kind===`LabelIf`?f(c,t):m(c,t);e.pop(),e.push(n.stmt),r.labeledStmts=n.labeledStmts;break}case`Goto`:e.pop(),e.push(an(c.to));break;case`Call`:e.pop(),e.push(...i(c,t));break;case`Return`:e.pop(),e.push(...a(c));break;case`CallReturn`:e.pop(),e.push(...o(c));break;case`CallGoto`:e.pop(),e.push(...i({...R(),kind:`Call`,returnTo:``,to:c.to,args:c.args,line:c.line,col:c.col},c.after));break;case`If`:{let e=s(c.Then,t),i=s(c.Else,t);r.labeledStmts.push(...e.labeledStmts,...i.labeledStmts),c.Then=e.stmts,c.Else=i.stmts,n||(r.needsGoto=e.needsGoto&&i.needsGoto,r.needsGoto||(e.needsGoto&&c.Then.push(an(t)),i.needsGoto&&c.Else.push(an(t))));break}case`Either`:{let e=c.ors.map((e,n)=>{let i=s(e,t);return c.ors[n]=i.stmts,r.labeledStmts.push(...i.labeledStmts),i});r.needsGoto=e.every(e=>e.needsGoto),!n&&!r.needsGoto&&e.forEach((e,n)=>{e.needsGoto&&c.ors[n].push(an(t))});break}case`With`:{let e=s(c.Do,t);c.Do=e.stmts,r.labeledStmts.push(...e.labeledStmts),r.needsGoto=e.needsGoto;break}default:r.needsGoto=!0}return n&&(r.needsGoto=!1),r},c=(e,t)=>{let n=s(e,t);return n.needsGoto&&n.stmts.push(an(t)),n},l=(e,t)=>{let r=e.stmts.at(0);if(r?.kind===`While`)return d(e,r,t);let i=c([...e.stmts],t),a=[];return n||(i.stmts.unshift(rn(e.label)),a.push({...R(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:i.stmts})),a.push(...i.labeledStmts),a},u=(e,t)=>e.flatMap((n,r)=>l(n,r<e.length-1?e[r+1].label:t)),d=(e,t,r)=>{let i=t.labDo.length===0?e.label:t.labDo[0].label,a=c([...t.unlabDo],i),o=c(e.stmts.slice(1),r),s=nn(t.test),l=s?a.stmts:[{...R(),kind:`If`,test:t.test,Then:a.stmts,Else:o.stmts}];return[{...R(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:[...n?[]:[rn(e.label)],...l]},...u(t.labDo,e.label),...a.labeledStmts,...s?[]:o.labeledStmts]},f=(e,t)=>{let n=c(e.unlabThen,e.labThen.length===0?t:e.labThen[0].label),r=c(e.unlabElse,e.labElse.length===0?t:e.labElse[0].label),i=u(e.labThen,t);return i.push(...u(e.labElse,t)),i.push(...n.labeledStmts,...r.labeledStmts),{stmt:{...R(),kind:`If`,col:e.col,line:e.line,test:e.test,Then:n.stmts,Else:r.stmts},labeledStmts:i}},m=(e,t)=>{let n=[],r=[];return e.clauses.forEach(e=>{let i=c(e.unlabOr,e.labOr.length>0?e.labOr[0].label:t);n.push(i.stmts),r.push(...i.labeledStmts),r.push(...u(e.labOr,t))}),{stmt:{...R(),kind:`Either`,col:e.col,line:e.line,ors:n},labeledStmts:r}},h=(e,t)=>u(e.map(Ke),t),g=e=>{r.procedure=e.name;let n=h(e.body,Ht(t,B.label,`Error`,``));return r.procedure=void 0,{...R(),kind:`Procedure`,col:e.col,line:e.line,name:e.name,minusLabels:[],plusLabels:[],proceduresCalled:[],params:e.params,decls:e.decls,body:n}},_=e=>({...R(),kind:`Process`,col:e.col,line:e.line,name:e.name,fairness:0,minusLabels:[],plusLabels:[],proceduresCalled:[],isEq:e.isEq,id:e.id,decls:e.decls,body:h(e.body,`Done`)}),v=e.prcds.map(g);return e.kind===`Uniprocess`?{...R(),kind:`Uniprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:v,body:h(e.body,`Done`)}:{...R(),kind:`Multiprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:v,procs:e.procs.map(_)}},fn=(e,t)=>{let n=t?[]:[`pc`];if(n.push(...e.decls.map(e=>e.var)),e.prcds.length>0&&n.push(`stack`),e.prcds.forEach(e=>{n.push(...e.params.map(e=>e.var)),n.push(...e.decls.map(e=>e.var))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>n.push(...e.decls.map(e=>e.var))),n.length===0)throw new p(`The algorithm has no variables.`);let r=(e,t)=>{let r=n.indexOf(t);return r===-1?0:(e[r]+=1,e[r])},i=(e,t)=>t.forEach((t,n)=>{e[n]=Math.max(e[n],t)}),a=e=>[...e].sort((e,t)=>e.lhs.var<t.lhs.var?-1:+(e.lhs.var>t.lhs.var)),o=(e,t)=>{let o=[...t];e.ass=a(e.ass),new Set(e.ass.map(e=>e.lhs.var)).forEach(t=>{let i=e.ass.filter(e=>e.lhs.var===t);if(!n.includes(t))throw new p(`Assignment to undeclared variable ${t}`,i[0]);let a=i.some(e=>e.lhs.sub.tokens.length===0);if(r(o,t)>1||i.length>1&&a)throw new p(`Multiple assignment to ${t}`,e)}),i(t,o)},c=(e,t)=>{switch(e.kind){case`Assign`:o(e,t);return;case`If`:{let n=[...t],r=[...t];e.Then.forEach(e=>c(e,n)),e.Else.forEach(e=>c(e,r)),i(t,n),i(t,r);return}case`Either`:{let n=[...t];e.ors.forEach(e=>{let r=[...t];e.forEach(e=>c(e,r)),i(n,r)}),i(t,n);return}case`With`:e.Do.forEach(e=>c(e,t));return;case`When`:case`PrintS`:case`Assert`:case`Skip`:return;default:throw new s(`Unexpected AST type ${e.kind}`)}},l=e=>e.forEach(e=>{let t=n.map(()=>0);Ke(e).stmts.forEach(e=>c(e,t))});e.prcds.forEach(e=>l(e.body)),(e.kind===`Uniprocess`?[e.body]:e.procs.map(e=>e.body)).forEach(l)},pn=(e,t,n,r)=>{let i=Wt(e);Gt(i),i.disambiguateReport.length>0&&r(`Warning: symbols were renamed.`),qt(e,i,r),fn(dn(e,i,t),t),n&&Kt(i)},mn=`[ \\t\\n\\x0B\\f\\r]`,hn=RegExp(`\\\\\\* BEGIN TRANSLATION${mn}+\\(${mn}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${mn}*(=${mn}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${mn}*STRING)${mn}*\\/\\\\${mn}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${mn}*(=${mn}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${mn}*STRING)${mn}*\\)`),gn=e=>process.getBuiltinModule(`node:zlib`).crc32(Buffer.from(e,`utf8`)).toString(16),_n=(e,t)=>e.log(`\nUnrecoverable error:\n -- ${t}.\n`),vn=(e,t)=>_n(e,t.node===void 0||t.node.line===0?t.message:`${t.message}\n at ${Ge(t.node)}`),yn=e=>e.map(e=>`${Array.from(e).reduce((e,t)=>t===` `?e+` `.repeat(8-e.length%8):e+t,``)} `),bn=(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},xn=(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``},Sn=(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},Cn=e=>/^[\p{L}\p{Nd}_]$/u.test(e),wn=(e,t,n)=>{for(;t.line<e.length;){let r=xn(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=Sn(r,e,` `),!0}t.column=Sn(r,t.column,` `)}return!1},Tn=(e,t)=>_n(e,`Command-line error: ${t}`),En=(e,t)=>{let n=e.params,r={isFirst:!0,isExplicitNof:!1},i=t=>(r.isFirst&&=(n.fairnessOption=``,!1),n.fairnessOption===``?(n.fairnessOption=t,!0):(Tn(e,`Can only have one of -wf, -sf, -wfNext, and -nof options`),!1));for(let a=0;a<t.length;a++){let o=t[a],s=t[a+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){Tn(e,`
|
|
20
|
-
Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){Tn(e,`Specification name must follow \`-${t?`myspec`:`spec`}' option`);return}n.specFile=s,a+=1;continue}case`-termination`:case`termination`:n.checkTermination=!0;continue;case`-noold`:n.noOld=!0;continue;case`-nocfg`:n.nocfg=!0;continue;case`-noDoneDisjunct`:case`noDoneDisjunct`:n.noDoneDisjunct=!0;continue;case`-wf`:case`wf`:case`-sf`:case`sf`:case`-wfNext`:case`wfNext`:case`-nof`:case`nof`:if(!i(o.replace(/^-/,``)))return;o.endsWith(`nof`)&&(r.isExplicitNof=!0);continue;case`-label`:case`label`:n.labelFlag=!0;continue;case`-labelRoot`:case`labelRoot`:if(s===void 0){Tn(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){Tn(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,a+=1;continue;case`-version`:case`version`:{if(s===void 0){Tn(e,"Version number must follow `-version' option");return}let t=Ue(s);if(t<0||t>1903){_n(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),Tn(e,`Bad version number`);return}n.inputVersionNumber=t,a+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){Tn(e,"Integer value at least 60 must follow `-lineWidth' option");return}a+=1;continue;default:Tn(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!r.isExplicitNof&&(n.fairnessOption=`wf`)},Dn=(e,t,n)=>{if(xn(t,n),n.column+=7,!xn(t,n).slice(n.column).startsWith(`(`)){_n(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=xn(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=Sn(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?_n(e,`No closing ')' found in options statement`):En(e,r)},On=(e,t,n)=>{let r={depth:0,isDone:!1,isInString:!1};for(let i=t;!r.isDone&&i<e.length;i++){let a=e[i],o=i===t?n:0,s=[a.slice(0,o)];r.isInString=!1;for(let e=o;!r.isDone&&e<a.length;e++){let t=a[e],n=a.slice(e,e+2);if(n===`(*`&&!r.isInString)r.depth+=1,s.push(` `),e+=1;else if(n===`*)`&&!r.isInString&&r.depth===0)s.push(n),r.isDone=!0;else if(n===`*)`&&!r.isInString)--r.depth,s.push(` `),e+=1;else if(r.depth>0)s.push(` `);else if(r.isInString&&t===`\\`&&n.length===2)s.push(n),e+=1;else{if(!r.isInString&&n===`\\*`){s.push(` `);break}t===`"`&&(r.isInString=!r.isInString),s.push(t)}}if(r.isInString)return new p(`Unterminated string in line ${i+1}`);e[i]=s.join(``)}},kn=(e,t)=>{let n=10*2**Math.max(0,Math.ceil(Math.log2(t/10)));throw new m(`java.lang.ArrayIndexOutOfBoundsException: Index ${e} out of bounds for length ${n}`)},An=(e,t,n)=>{if(!t.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let r=yn(t),i={line:0,column:0};for(;wn(r,i,`PlusCal`);){let t=xn(r,i).slice(i.column),n=Array.from(t).findIndex(e=>!Cn(e));if(t.startsWith(`options`)&&(n===-1?t.length:n)===7){e.params.optionsInFile=!0,Dn(e,r,i);break}}let a={line:0,column:-1,isFound:!1,isFair:!1};for(;a.line<r.length;a.line++){let e=r[a.line];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){a.column=t+11,a.isFound=!0;break}if(n!==-1){a.column=n+6,a.isFound=!0,a.isFair=!0;break}}let o=/* @__PURE__ */ new Set,s=bn(r,0,`BEGIN`,`TRANSLATION`);s===-1&&o.add(`NO_TRANSLATION_EXISTS`);let c=bn(r,s+1,`END`,`TRANSLATION`);if(c===-1&&o.add(`NO_TRANSLATION_EXISTS`),s===-1&&c===-1)return o;if(!a.isFound)return o.add(`NO_PLUSCAL_EXISTS`),o;let l=On(r,a.line,a.column);if(l!==void 0)return vn(e,l),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let u={ast:void 0};try{let n=ft(r,a.line,a.column,t.length,0),i=Pt(e,n,a.isFair);u.ast=i.ast,pn(i.ast,i.omitPC,i.hasDefaultInitialization,e.log)}catch(t){if(!(t instanceof p))throw t;vn(e,t)}s===-1&&kn(-1,r.length);let d=hn.exec(r[s]);if(d===null)return o.add(`NO_PCAL_CHECKSUMS_EXIST`),o;let f=d.groups?.pcal,h=a.isFair&&n!==`1.7.4`?`fair`:u.ast===void 0?void 0:dt(u.ast,e.params.inputVersionNumber,n);f!==void 0&&(h===void 0||f!==gn(h))&&o.add(`PCAL_DIVERGENCE_EXISTS`);let g=d.groups?.tla;if(g!==void 0){if(c===-1)throw new m(`java.lang.IllegalArgumentException: fromIndex(${s+1}) > toIndex(-1)`);let e=t.slice(s+1,c).join(``);g!==gn(e)&&o.add(`TLA_DIVERGENCE_EXISTS`)}return o.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):o},jn=[[`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]]],Mn={file:`--TLA+ BUILTINS--`,beginLine:0,beginColumn:0,endLine:0,endColumn:0},H=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}),Nn=e=>jn.map(([t,n,r,i,a])=>{let o=e(),s=n<0?void 0:Array.from({length:n},(t,n)=>({...H(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{...H(o),levelChecked:c?99:0,level:r,kind:`OpDef`,defKind:`BuiltIn`,name:t,arity:n,params:s,body:void 0,isLocal:!1,location:Mn,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}}),Pn=(e,t)=>{let n=JSON.stringify(t);e.some(e=>JSON.stringify(e)===n)||e.push(t)},Fn=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}`,In=e=>e?.kind===`OpAppl`&&e.isAbsent===!0,Ln=e=>{let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;return t},Rn=()=>({buckets:Array.from({length:11},()=>[]),count:0,threshold:8}),zn=(e,t)=>(e&2147483647)%t,Bn=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[zn(e.hash,t)].unshift(e));e.buckets=n,e.threshold=Math.floor(t*.75)},Vn=(e,t,n=t)=>e.buckets[zn(Ln(n),e.buckets.length)].find(e=>e.key===t)?.value,Hn=(e,t,n,r=t)=>{let i=Ln(r),a=e.buckets[zn(i,e.buckets.length)].find(e=>e.key===t);a?a.value=n:(e.count>=e.threshold&&Bn(e),e.buckets[zn(i,e.buckets.length)].unshift({hash:i,key:t,value:n}),e.count++)},Un=e=>e.buckets.toReversed().flatMap(e=>e.map(e=>e.value)),Wn=`\0module `,U=()=>({table:Rn(),symbols:[]}),Gn=e=>e.kind===`Module`?Wn+e.name:e.name,Kn=(e,t)=>{Hn(e.table,Gn(t),t,t.name),e.symbols.push(t)},qn=e=>e.kind===`ThmOrAssumpDef`?e.params.length:e.kind===`Module`?0:e.arity,Jn=(e,t)=>Vn(e.table,t),Yn=(e,t)=>Vn(e.table,Wn+t,t),Xn=e=>e.context.symbols.filter(e=>e.kind===`OpDef`&&e.defKind===`UserDefined`),Zn=(e,t)=>Un(e.context.table).filter(e=>e.kind===`OpDecl`&&e.declKind===t).toReversed(),Qn=e=>e.context.symbols.filter(e=>e.kind===`ThmOrAssumpDef`),$n=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),er=e=>{let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},tr=e=>{switch(e.kind){case`Identifier`:return er(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=er(e.operator),n=e.argumentCounts??t.map((n,r)=>r===t.length-1?e.args.length:0),r={value:0};return t.map((t,i)=>{let a=e.args.slice(r.value,r.value+n[i]);return r.value+=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}}})}},nr=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},rr=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,ir=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,ar=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),or=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,sr=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],cr=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},lr=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):Jn(u.letInContext,p)),f===void 0&&(p!==void 0&&(u.name=p,u.nameLocation=cr(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: \`${rr(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=cr(u.nameLocation,l(u.index)),u.name=p,ar(f)&&t.length!==1)return e.addError(l(u.index),`Cannot take subexpression of \`${u.name}'.`);let h=qn(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 \`${rr(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
|
|
21
|
-
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(
|
|
22
|
-
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`?
|
|
23
|
-
`&&r.push(e+1);return{name:e,source:t,tokens:n,lineOffsets:r,tokenIndexes:new Map(n.map((e,t)=>[
|
|
24
|
-
`,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},Tr=(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},Er=(e,t,n,r)=>{for(let i=t;i<=n;i++)if(W(e,i,r))return i;return-1},Dr=new Map(ee.flatMap(([e,...t])=>t.map(t=>[t,e]))),Or=e=>e.split(`!`).map(e=>Dr.get(e)??(e===`~`?`\\lnot`:e)).join(`!`),kr={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}},Ar=e=>/^[A-Za-z0-9_]+$/.test(e),jr=e=>e!==`!!`&&e.includes(`!`),Mr=e=>e.contexts[e.contexts.length-1],Nr=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=Jn(e.contexts[n],t);if(r)return r}},Pr=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,Fr=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,Ir=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||Lr(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&Lr(n.module)}return!1},Lr=e=>Zn(e,2).length===0&&Zn(e,3).length===0,Rr=e=>[...e.kind===`Let`?e.instances??[]:[],...S(e).flatMap(Rr)],zr=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:zr(e)):Rr(e),Br=(e,t)=>{let n=/* @__PURE__ */ new Set;for(let r of e.units)if(r.kind===`Module`&&n.add(r.module.name),r.kind===`Instance`&&r.instance.module===t)return n.has(t);return!1},Vr=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`?Rr(e.definition.body):e.kind===`Theorem`&&s?zr(e.theorem.statement):e.kind===`Assumption`&&s?Rr(e.assumption.expression):[]).map(e=>e.module).filter(e=>l(e)&&!Br(a,e)),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}},Hr=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),Ur=e=>{let t=e.kind===`Apply`?tr(e):void 0;return Hr.has(e.kind)||t!==void 0&&nr(t)},Wr=/* @__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`]]),Gr=/* @__PURE__ */ new Set([`N_GeneralId`,`N_OpApplication`,`N_PrefixExpr`,`N_InfixExpr`,`N_PostfixExpr`,`N_FcnAppl`,`N_RecordComponent`]),Kr=/* @__PURE__ */ new Set([`'`,`^+`,`^*`,`^#`]),qr=(e,t)=>Kr.has(t)?`N_GenPostfixOp`:e.kind===`Lambda`||t===`~`||t===`-.`?`N_GenNonExpPrefixOp`:`N_GenInfixOp`,Jr=(e,n,r={})=>{let a=[],o=(e,t)=>Pn(a,{location:e,text:t,isWarning:!1}),s=(e,t)=>Pn(a,{location:e,text:t,isWarning:!0}),c={value:r.version===`1.7.4`?-1:0},l=()=>++c.value,u={id:0},f=(e,t)=>{let n=Nr(e,t.name);if(n===t)return;if(n===void 0){Kn(Mr(e),t);return}let i=t.kind===`FormalParam`||Pr(n)!==Pr(t)||qn(n)!==qn(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(i&&r.version===`1.7.4`)?o(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):i?o(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${Fn(n.location)}.`):Ir(t,n)||s(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${Fn(n.location)}.`)};r.version!==`1.7.4`&&Nn(l);let p=Nn(l);l();let m=new Map(p.map(e=>[e.name,e])),g=/* @__PURE__ */ new Map,v=/* @__PURE__ */ new Map,y=(e,n)=>{let a=e===r.rootFileName&&r.rootFilePath||`${e}.tla`,o=t=>new i(`Could not parse module ${e} from file ${a}`,e,t),s=r.version===`1.7.4`?_(n):void 0;if(s!==void 0)throw o(s);try{return ae(Cr(n))}catch(e){throw e instanceof t?o(M(n)??`***Parse Error***\n${e.message}`):e}},b=(e,t,n)=>{let a=v.get(e);if(a)return a;if(t===void 0)throw new h(e,n,r.version!==`1.7.4`);r.onParse?.(e);let o=y(e,t);if(o.name!==e)throw new i(`File name '${e}' does not match the name '${o.name}' of the top level module it contains.`,void 0);let s={file:fr(o.name,t),module:o};return v.set(e,s),s},x=[],S=/* @__PURE__ */ new Set,C=[],w=(e,t,r)=>{let a=C.indexOf(e);if(a!==-1)throw new i(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...C.slice(a),e].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(S.has(e))return;S.add(e),C.push(e);let o=k(e,b(e,t,r).module);[...o.extendees,...o.instancees].forEach(t=>w(t,n(t),e)),C.pop(),x.push(e)},ee=/* @__PURE__ */ new Set,T=(e,t)=>ee.has(`${e} ${t}`),E=(e,t,n)=>{let r=v.get(e);if(!r||n.has(e))return;n.add(e);let i=k(e,r.module),a=i[t].find(t=>!T(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=T(e,r)?E(r,t,n):void 0;if(i)return i}},D=t=>{b(t,e);let r=()=>E(t,`extendees`,/* @__PURE__ */ new Set)??E(t,`instancees`,/* @__PURE__ */ new Set);for(let e=r();e!==void 0;e=r())v.has(e.name)||b(e.name,n(e.name),e.namingModule),ee.add(`${e.importer} ${e.name}`)},O=r.rootFileName??y(``,e).name,k=(e,t)=>{let n=Vr(t);return e!==O||r.rootExtendees===void 0||(n.extendees.splice(t.extends.length,0,...r.rootExtendees),r.rootExtendees.forEach(t=>{n.importers.has(t)||n.importers.set(t,e)})),n};D(O),w(O,e);let te=(e,n,i,a)=>{let c={curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSectionCount:0},p=[],h=[],_=[],v=[],y=/* @__PURE__ */ new WeakSet,b=()=>v.push({labels:/* @__PURE__ */ new Map,params:[]}),x=()=>v.pop()?.labels??/* @__PURE__ */ new Map,S={depth:0,isDeclared:[],goal:void 0,goalClause:0},C=/* @__PURE__ */ new WeakMap,w=/* @__PURE__ */ new WeakMap,ee=e=>{let t=e.kind===`AssumeProve`?C.get(e):void 0;t&&(t.isInProof=!1)},T=e=>K(n,G(n,e)),E=e=>e.range?_r(n,e.range):{start:mr(n,e),end:mr(n,e)},D={kind:`Module`,id:l(),name:e.name,location:K(n,E(e.location)),extendees:[],context:Mr(a),topLevel:[],definitions:[],opDefsInRecursiveSection:[],isLevelChecked:!1,levelCorrect:!0,argLevelParams:/* @__PURE__ */ new Map,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map,records:[]};i&&i.definitions.push(D);let O=e=>{for(let t=a.contexts.length-1;t>=0;t--){let n=Yn(a.contexts[t],e);if(n?.kind===`Module`)return n}return g.get(e)},k=e=>{let n=O(e);if(n===void 0)throw new t(`Could not find module ${e}`);return n},A=(e,t)=>{a.contexts.push(e);let n=t();return a.contexts.pop(),n},j=(e,t,n,r)=>{let i={...H(l()),kind:`FormalParam`,name:e,arity:t,location:n};return r&&f(a,i),i},ne=e=>({...H(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}),re=e=>{e.letInLevel=c.curLevel,c.unresolvedSum>0&&(e.recursiveSection=c.recursiveSectionCount,e.inRecursiveSection=c.unresolvedCount[c.curLevel]>0,D.opDefsInRecursiveSection.push(e))},ie=(e,t,n,r={},i=l())=>({...H(i),kind:`OpAppl`,operator:e,operands:t,unbounded:r.unbounded,bounded:r.bounded,tupleOrs:r.tupleOrs,ranges:r.ranges??[],location:n}),M=()=>({...ie(ae(`$Nop`),[],Mn,{},u.id),isNull:!0}),ae=e=>{let t=m.get(e);if(!t)throw new d(`SANY has no builtin operator ${e}`);return t},N=(e,t,n,r={})=>ie(ae(e),t,n,r),oe=(e,t)=>({...H(l()),kind:`String`,value:e,location:t}),se=(e,t)=>({...H(l()),kind:`OpArg`,op:e,location:t}),ce=(e,n)=>{let r=Nr(a,Or(e));if(r===void 0||r.kind===`Module`)throw new t(`Unknown operator: \`${e}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},le=(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`&&qn(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.`)},ue=lr({version:r.version,resolveSymbol:e=>Nr(a,e),resolveSynonym:Or,generateExpression:e=>I(e),generateArgument:(e,t,n,r)=>be(e,t,n,r),createOpAppl:(e,t,n)=>{let r=ie(e,t,n);return le(e,t,n),r},createOpArg:se,createFormalParam:(e,t,n)=>j(e,t,n,!1),createLambda:(e,t,r)=>ne({name:`LAMBDA`,params:e,body:t,location:r,preComments:wr(n,mr(n,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>He(`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:ae,addError:(e,t)=>(o(e,t),M()),isOutOfLabelScope:e=>{let t=w.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=C.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}}),de=(e,t)=>{let r={value:t.start};return e.map(e=>{let i=e.op===`Name`?e.name:e.op===`Null`?`(`:String(e.op),a=Er(n,r.value,t.end,i);if(a===-1)return e;if(e.op===`Null`){let t=gr(n,a);return r.value=t+1,{...e,location:K(n,{start:a,end:t})}}r.value=a+1;let o=q(n,a);if(e.args===void 0||!W(n,a+1,`(`))return{...e,location:o};let s=gr(n,a+1);return r.value=s+1,{...e,location:o,argsLocation:K(n,{start:a+1,end:s})}})},fe=(e,r,i,a)=>{let o=tr(e);if(o===void 0)throw new t(`Expected a name, found ${e.kind}`);return ue(de(o,G(n,e)),r,i,a,T(e))},pe=e=>{let n=fe(e,0,!1,!1);if(n.kind!==`OpAppl`)throw new t(`Expected an expression`);return n},me=e=>{if(e.kind!==`OpAppl`)return;let t=p.find(t=>t.name===e.operator.name);t&&(t.node.operator=ae(`$RecursiveFcnSpec`))},he=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},[]),ge=(e,t)=>Me(e,t,he(e).map(e=>I(e[0].set))),P=(e,t)=>{let n=v.at(-1);n?.params.push(e);let r=I(t);return n?.params.pop(),r},_e=e=>{let t=G(n,e),r=Tr(n,t.start,t.end,e.params);return A(U(),()=>{let i=e.params.map((e,t)=>j(e,0,q(n,r[t]),!0)),a=P(i,e.body);return ne({name:`LAMBDA`,params:i,body:a,location:K(n,t),preComments:wr(n,t.start)})})},ve=e=>e.kind===`OperatorReference`?e.operator:e.kind===`Lambda`&&e.body.kind===`Apply`?e.body.operator:n.tokens[mr(n,e.location)].text,ye=(e,n)=>{let r=T(e);if(e.kind===`Lambda`)return e.location.range===void 0?se(ce(ve(e),r),r):se(_e(e),r);if(!Ur(e))return o(r,`Arity ${n.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${n.name}'.`),M();if(e.kind===`OperatorReference`)return se(ce(e.operator,r),r);let i=fe(e,n.arity,!1,!1);if(i.kind===`OpArg`||i.kind===`OpAppl`&&i.isNull===!0)return i;throw new t(`Expected an operator argument at line ${r.beginLine}, column ${r.beginColumn}`)},be=(e,r,i,s)=>{let c=e.kind===`OpDef`&&(e.defKind===`UserDefined`||e.defKind===`ModuleInstance`)?e.params?.[r]?.arity??0:0;if(c===0)return I(i);let l=G(n,i),u=K(n,l),d=`${r+1} (counting from 1)`,f=yr(n,l);if(f!==l||!Ur(i))return o(K(n,f),`An expression appears as argument number ${d} to operator '${e.name}', in a position an operator is required.`),M();if(i.kind===`Identifier`||i.kind===`Subexpression`||i.kind===`Apply`){let e=fe(i,c,!1,!1);if(e.kind===`OpArg`||e.kind===`OpAppl`)return e;throw new t(`Expected an operator argument at ${Fn(u)}`)}if(i.kind===`Lambda`&&i.location.range!==void 0){let t=_e(i),n=qn(t);return n===c?se(t,u):(o(s,`Lambda expression with arity ${n} used as argument ${r+1} of operator \`${e.name}', \nbut an operator of arity ${c} is required.`),M())}let p=ve(i),m=Nr(a,Or(p));if(m===void 0)return o(u,`Could not find declaration or definition of symbol '${p}'.`),M();let h=qn(m);return h===c?se(m,u):(o(s,`Operator with incorrect arity passed as argument. \nOperator '${m.name}' of arity ${h} is argument number ${d} to operator \`${Fn(e.location)}', \nbut an operator of arity ${c} was expected.`),M())},xe=e=>{let t=T(e);if(e.isBulleted)return N(e.kind===`And`?`$ConjList`:`$DisjList`,e.operands.map(I),t);let r=G(n,e),i=e.kind===`And`?`\\land`:`\\lor`,[a,...o]=e.operands;return o.reduce((e,t,a)=>{let s=vr(n,G(n,t)),c=a===o.length-1?r.end:s.end;return N(i,[e,I(t)],K(n,{start:r.start,end:c}))},I(a))},Se=e=>{let t=G(n,e),r=e.arms.map((r,i)=>{let a=vr(n,G(n,r.condition)),o=i===e.arms.length-1&&e.other===void 0,s=vr(n,G(n,r.body)),c=[I(r.condition),I(r.body)];return N(`$Pair`,c,K(n,{start:a.start,end:o?t.end:s.end}))}),i=e.other;if(i){let e=vr(n,G(n,i)),a=Ce(e.start,`OTHER`);r.push(N(`$Pair`,[void 0,I(i)],K(n,{start:a,end:t.end})))}return N(`$Case`,r,K(n,t))},Ce=(e,t)=>{for(let r=e;r>=0;r--)if(W(n,r,t))return r;return e},we=e=>{let t=G(n,e),r=K(n,t),i=[I(e.function)],a=N(`$Except`,i,r),o=G(n,e.function),s={value:Er(n,o.end+1,t.end,`EXCEPT`)+1};return e.updates.forEach(e=>{let r=Er(n,s.value,t.end,`!`),o=vr(n,G(n,e.value)),c=K(n,{start:r,end:o.end}),l={value:r+1},u=e.path.map(e=>{if(e.kind===`Field`){let t=Te(l.value,e.name);return l.value=t+1,oe(e.name,q(n,t))}let r=Er(n,l.value,t.end,`[`),i=gr(n,r);return l.value=i+1,e.args.length===1?I(e.args[0]):N(`$Tuple`,e.args.map(I),K(n,{start:r,end:i}))}),d=N(`$Seq`,u,c),f=N(`$Pair`,[d],c);_.push(f),h.push(a),f.operands.push(I(e.value)),_.pop(),h.pop(),i.push(f),s.value=o.end+1}),a},Te=(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},Ee=(e,t)=>{let r=G(n,t),i={value:r.start+1},a=t.fields.map((e,r)=>{let a=Te(i.value,e.name),s=vr(n,G(n,e.value));return i.value=s.end+1,t.fields.slice(0,r).some(t=>t.name===e.name)&&o(q(n,a),`Non-unique fields in constructor.`),N(`$Pair`,[oe(e.name,q(n,a)),I(e.value)],K(n,{start:a,end:s.end}))}),s=N(e,a,K(n,r));return D.records.push(s),s},F=e=>({line:n.tokens[e].line,column:n.tokens[e].column}),De=e=>{let t=[],r=e;for(;n.tokens[r]?.kind===`Identifier`;){let e=W(n,r+1,`(`)?gr(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:{...F(r),range:{module:n.name,start:F(r),end:F(e)}}}),!W(n,e+1,`,`))break;r=e+2}return t},Oe=e=>{let t=[...e.definitions.map(e=>({unit:{kind:`Definition`,definition:e},span:Fe(e)})),...(e.instances??[]).map(e=>({unit:{kind:`Instance`,instance:e},span:Fe(e)}))],r=G(n,e).start,i=vr(n,G(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);W(n,e,`RECURSIVE`)&&!r&&a.push({unit:{kind:`Recursive`,declarations:De(e+1)},span:{start:e,end:e}})}return[...t,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},ke=e=>{let t=U();return A(t,()=>{c.curLevel++,c.unresolvedCount[c.curLevel]=0;let n=[],r=[];Oe(e).forEach(e=>{e.kind===`Recursive`?Be(e.declarations):e.kind===`Instance`?Ue(e.instance,n,r):e.definition.kind===`Function`?Re(e.definition,n):Ie(e.definition,n)}),Ve(),c.curLevel=Math.max(c.curLevel-1,0);let i=I(e.body);return{...H(l()),kind:`LetIn`,opDefs:n,instances:r,body:i,context:t,location:T(e)}})},Ae=e=>{let t=G(n,e),r=K(n,t);return A(U(),()=>{let i=e.pattern,a=i.kind===`Name`?[i.name]:i.names;if(e.set===void 0){let o=Tr(n,t.start,t.end,a),s=a.map((e,r)=>j(e,0,q(n,i.kind===`Name`?t.start:o[r]),!0)),c=P(s,e.body);return N(`$UnboundedChoose`,[c],r,{unbounded:s})}let o=I(e.set),s=G(n,e.set),c=Tr(n,t.start,s.start,a),l=a.map((e,t)=>j(e,0,q(n,c[t]),!0)),u=P(l,e.body);return N(`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},je=e=>{if(Ar(e.operator)||jr(e.operator)||e.args.length>2||Nr(a,Or(e.operator))!==void 0)return;let t=G(n,e);if(n.tokens[t.start].text===e.operator&&W(n,t.start+1,`(`))return;let r=vr(n,G(n,e.args[0])),i=e.args.length===1&&r.start!==t.start,o=i?t.start:r.end+1,s=xr(n,o);return{index:o,name:i&&s===`-`?`-.`:s,fixity:i?`prefix`:e.args.length===2?`infix`:`postfix`}},I=e=>{let t=T(e);switch(e.kind){case`Number`:return{...H(l()),kind:`Numeral`,value:Yr(e.text??String(e.value)),location:t};case`Decimal`:{let[n,r]=e.text.split(`.`),i=BigInt(n+r),a=i<=9223372036854775807n;return{...H(l()),kind:`Decimal`,mantissa:i.toString(),exponent:String(a?-r.length:r.length),integralPart:n,fractionalPart:r,location:t}}case`String`:return oe(e.value,t);case`Identifier`:{let t=pe(e);return me(t),t}case`Apply`:{let r=je(e);if(r!==void 0)return o(q(n,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),o(t,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...M(),isAbsent:!0};let i=pe(e);return(jr(e.operator)||Ar(e.operator))&&me(i),i}case`Bracket`:return o(q(n,G(n,e).start),"Unsupported expression type `['."),{...M(),isAbsent:!0};case`OperatorReference`:case`Lambda`:{let r=n.tokens[G(n,e).start].text;return o(t,r===`LAMBDA`?`LAMBDA expression used where an expression is required.`:`Unsupported expression type \`${qr(e,r)}'.`),{...M(),isAbsent:!0}}case`And`:case`Or`:return xe(e);case`Prime`:return N(`'`,[I(e.expression)],t);case`Unchanged`:return N(`UNCHANGED`,[I(e.expression)],t);case`Enabled`:return N(`ENABLED`,[I(e.expression)],t);case`Always`:return N(`[]`,[I(e.expression)],t);case`Eventually`:return N(`<>`,[I(e.expression)],t);case`If`:return N(`$IfThenElse`,[I(e.condition),I(e.consequent),I(e.alternative)],t);case`Case`:return Se(e);case`Let`:return ke(e);case`Forall`:case`Exists`:{let r=G(n,e);return A(U(),()=>{let n=ge(e.bounds,r.start),i=P(n.bounded.flat(),e.body);return N(e.kind===`Forall`?`$BoundedForall`:`$BoundedExists`,[i],t,n)})}case`UnboundedQuantifier`:{let r=G(n,e),i=G(n,e.body),a=Tr(n,r.start,i.start,e.names),o=e.isTemporal?e.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:e.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return A(U(),()=>{let r=e.names.map((e,t)=>j(e,0,q(n,a[t]),!0)),i=P(r,e.body);return N(o,[i],t,{unbounded:r})})}case`Choose`:return Ae(e);case`SetEnumeration`:return N(`$SetEnumerate`,e.elements.map(I),t);case`Tuple`:return N(`$Tuple`,e.elements.map(I),t);case`SetFilter`:{let r=I(e.bound.set),i=G(n,e);return A(U(),()=>{let n=Me([e.bound],i.start,[r]),a=P(n.bounded.flat(),e.predicate);return N(`$SubsetOf`,[a],t,n)})}case`SetMap`:{let r=G(n,e.expression);return A(U(),()=>{let n=ge(e.bounds,r.end+1),i=P(n.bounded.flat(),e.expression);return N(`$SetOfAll`,[i],t,n)})}case`FunctionConstruction`:{let r=G(n,e);return A(U(),()=>{let n=ge(e.bounds,r.start),i=P(n.bounded.flat(),e.body);return N(`$FcnConstructor`,[i],t,n)})}case`FunctionSet`:return N(`$SetOfFcns`,[I(e.domain),I(e.range)],t);case`Record`:return Ee(`$RcdConstructor`,e);case`RecordSet`:return Ee(`$SetOfRcds`,e);case`Except`:return we(e);case`ExceptAt`:{let e=h[h.length-1],n=_[_.length-1];return e===void 0||n===void 0?(o(t,`@ used where its meaning is not defined.`),M()):{...H(l()),kind:`At`,except:e,component:n,location:n.location}}case`FunctionApplication`:{let n=I(e.function);if(In(n))return n;me(n);let r=e.args.length===1?I(e.args[0]):N(`$Tuple`,e.args.map(I),t);return N(`$FcnApply`,[n,r],t)}case`FieldAccess`:{let r=I(e.record),i=G(n,e);return N(`$RcdSelect`,[r,oe(e.field,q(n,i.end))],t)}case`Product`:return N(`$CartesianProd`,e.factors.map(I),t);case`BoxAction`:case`AngleAction`:return N(e.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[I(e.action),I(e.subscript)],t);case`WeakFairness`:case`StrongFairness`:return N(e.kind===`WeakFairness`?`$WF`:`$SF`,[I(e.subscript),I(e.action)],t);case`Label`:return Ne(e);case`Subexpression`:return pe(e)}},Me=(e,t,r)=>{let i=he(e),a={value:t};return{bounded:i.map(e=>{let t=G(n,e[0].set),r=e.flatMap(e=>e.pattern.kind===`Name`?[e.pattern.name]:e.pattern.names),i=Tr(n,a.value,t.start,r);return a.value=t.end+1,r.map((e,t)=>j(e,0,q(n,i[t]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},Ne=e=>{let t=T(e),r=v.at(-1);if(r===void 0)return o(t,`Label not in definition or proof step.`),M();if(S.isDeclared.slice(2,S.depth+1).some(Boolean))return o(t,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),M();if(h.length>0&&_.length>0)return o(t,`Labels inside EXCEPT clauses are not yet implemented.`),M();b();let i=I(e.body),s=x(),c=Tr(n,G(n,e).start,G(n,e.body).start,e.params),u=e.params.map((t,r)=>{let i=Nr(a,t);if(i?.kind===`FormalParam`)return i;let s=q(n,c[r]);return o(s,`Illegal parameter ${t} of label \`${e.name}'.`),j(t,0,s,!1)}),d={...H(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=S.goal;return p&&w.set(d,{scope:p,clause:S.goalClause}),d},Pe=(e,t,r)=>{let i={value:t.start};return e.params.map(e=>{let t=e.location?mr(n,e.location):Te(i.value,e.name),a=dt(t,e.arity);return i.value=a.end+1,j(Or(e.name),e.arity,K(n,a),r)})},Fe=e=>{let t=E(e.location);return e.isLocal&&!W(n,t.start,`LOCAL`)&&W(n,t.start-1,`LOCAL`)?{start:t.start-1,end:t.end}:t},Ie=(e,t)=>{let r=Fe(e),i=K(n,r),s=Or(e.name),l={start:e.isLocal?r.start+1:r.start,end:r.end},u=A(U(),()=>{let t=Pe(e,l,!0),n=Nr(a,s);if(n?.kind===`OpDef`&&n.inRecursive&&!n.isDefined){let e=n.params?.length===t.length&&(t.length===0||t[t.length-1].arity===0);n.letInLevel===c.curLevel?e||o(i,`Definition of ${n.name} has different arity than its RECURSIVE declaration.`):o(i,`Recursive operator ${s} defined at wrong LET/IN level.`)}else n!==void 0&&o(i,`Operator ${s} already defined or declared.`);return b(),{params:t,body:I(e.body),existing:n}}),d=x(),p=u.existing,m=u.params,h=wr(n,r.start);if(p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined&&p.letInLevel===c.curLevel){p.params=m,p.weights=m.map(()=>0),p.maxLevels=m.map(()=>3),p.isLeibnizArg=m.map(()=>!0),p.labels=d,Le(p,u.body,i,h),D.definitions.push(p),t?.push(p);return}let g=ne({name:s,params:m,body:u.body,isLocal:e.isLocal,location:i,preComments:h,labels:d});f(a,g),re(g),D.definitions.push(g),t?.push(g)},Le=(e,t,n,r)=>{e.isDefined=!0,e.body=t,e.location=n,e.preComments=r,e.inRecursive&&(c.unresolvedCount[c.curLevel]--,c.unresolvedSum--)},Re=(e,t)=>{let r=Fe(e),i=K(n,r),s=U(),l=e.isLocal?r.start+1:r.start,u=A(s,()=>ge(e.bounds,l+1)),d=Nr(a,e.name),m=A(s,()=>j(e.name,0,i,d===void 0)),h=N(`$NonRecursiveFcnSpec`,[],i,{unbounded:[m],...u}),g=d?.kind===`OpDef`&&d.inRecursive&&!d.isDefined,_=g&&d.letInLevel===c.curLevel;_?d.arity!==0&&o(i,`Function ${d.name} has operator arguments in its RECURSIVE declaration.`):g?o(i,`Recursive function ${e.name} defined at wrong LET/IN level.`):d!==void 0&&o(i,`Function name \`${e.name}' already defined or declared.`);let v=wr(n,r.start),y=d===void 0?ne({name:e.name,params:[],body:h,isLocal:e.isLocal,location:i,preComments:v}):d.kind===`OpDef`&&(_||!g)?d:void 0;_?d.arity===0&&Le(d,h,i,v):d===void 0&&y!==void 0&&(f(a,y),re(y)),y!==void 0&&(D.definitions.push(y),t?.push(y)),p.unshift({name:e.name,node:h}),b();let S=()=>P(u.bounded.flat(),e.body),C=y===void 0?S():A(s,S),w=x();y!==void 0&&(y.labels=w),p.shift(),h.operands=[C],h.operator.name===`$NonRecursiveFcnSpec`&&(h.unbounded=void 0)},ze=[],Be=e=>{c.unresolvedSum===0&&c.recursiveSectionCount++,c.unresolvedCount[c.curLevel]+=e.length,c.unresolvedSum+=e.length,e.forEach(e=>{let t=ft(e);l();let r=Array.from({length:e.arity},()=>j(``,0,void 0,!1)),i=ne({name:Or(e.name),params:r,location:K(n,t),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:c.recursiveSectionCount,letInLevel:c.curLevel});f(a,i),ze.push(i),D.opDefsInRecursiveSection.push(i)})},Ve=()=>{c.unresolvedCount[c.curLevel]!==0&&(ze.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])},L=(e,t,i)=>{l();let s=Un(t.table).filter(e=>e.kind===`OpDecl`),c=s.flatMap(e=>{let t=Nr(a,e.name);return t===void 0?[]:[{op:e,expr:e.declKind===3||e.declKind===2&&e.arity===0?ie(t,[],i):se(t,i),isImplicit:!0}]}),u=(e,t)=>{let n=t.kind===`OpArg`?qn(t.op):0,r=e.arity>0&&t.kind===`OpAppl`&&t.isNull===!0;n!==e.arity&&!r&&o(t.location,`An operator must be substituted for symbol '${e.name}', and it must have arity ${e.arity}.`)},d=Fe(e),f={value:Er(n,d.start,d.end,`WITH`)+1};return e.substitutions.forEach(e=>{let r=Er(n,f.value,d.end,e.name);r!==-1&&(f.value=G(n,e.expression).end+1);let a=Jn(t,Or(e.name));if(a?.kind!==`OpDecl`){o(r===-1?i:q(n,r),`Identifier '${r===-1?e.name:xr(n,r)}' 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?I(e.expression):ye(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&&r.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(i,`Substitution missing for symbol ${e.name} declared at ${Fn(e.location)} \nand instantiated in module ${D.name}.`)),c},He=(e,t,n,r,i,a=D)=>(In(n)&&o(i,e===`SubstIn`?`Substitution error, probably due to error
|
|
25
|
-
in module being instantiated.`:`Substitution error, probably due to error in module being instantiated.`),{...
|
|
26
|
-
the name of a theorem, assumption, or step.`)),{...H(l()),kind:`UseOrHide`,facts:r,defs:i,isOnly:e.isOnly,isHide:e.kind===`Hide`,location:t}},nt=e=>{let t=E(e.location),r=e.set&&I(e.set),i=Te(t.start,e.name),o=kr[e.level],s={...H(l()),levelChecked:1,level:o.level,kind:`OpDecl`,name:Or(e.name),arity:e.arity,declKind:o.declKind,location:K(n,dt(i,e.arity)),module:D};return f(a,s),{...H(l()),kind:`NewSymb`,declaration:s,set:r,location:K(n,t)}},rt=(e,t,r)=>{let i=E(e.location),s=Sr(n,i.start-1),c=G(n,e.conclusion).start,u=n.tokens.findLastIndex((e,t)=>t<c&&e.kind===`Keyword`&&e.text===`PROVE`),d=K(n,{start:s?i.start-1:i.start,end:i.start});s!==Sr(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(U()),s&&a.contexts.some(e=>y.has(e))&&o(d,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),s||y.add(Mr(a));let p={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};S.depth=t,S.isDeclared[t]=!1,t===1&&(S.goal=r&&p,S.goalClause=0);let m=e.assumptions.map((e,n)=>{let r=e.kind===`NewSymbol`,i=e.kind===`AssumeProve`?rt(e,t+1):r?nt(e):I(e);return S.depth=t,r&&(S.isDeclared[t]=!0),p.isDeclaredBefore.push(p.isDeclaredBefore[n]||r),t===1&&S.goalClause++,i}),h=I(e.conclusion);t>1&&a.contexts.pop(),S.depth=t-1,t===1&&(S.goal=void 0);let g={...H(f),kind:`AssumeProve`,assumptions:m,goal:h,isSuffices:p.isSuffices,isBoxed:s,location:K(n,{start:s?i.start-1:i.start,end:i.end})};return C.set(g,p),g},it=(e,t,n,r,i,a=!0)=>({...H(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:[]}),at=e=>{let t=K(n,E(e.location));e.kind===`By`&&et(e,t);let r=e.kind===`By`?Ge(e.facts):[],i=e.kind===`By`?$e(e.defs):[];return e.kind===`By`&&l(),e.kind===`By`&&r.length+i.length===0&&o(t,`Empty BY`),{...H(l()),kind:`LeafProof`,facts:r,defs:i,isOmitted:e.kind===`Omitted`,isOnly:e.kind===`By`&&e.isOnly,location:t}},ot=(e,t)=>{let r=e.body,i=K(n,t);switch(r.kind){case`Have`:return{node:N(`$Have`,[I(r.expression)],i),isPick:!1};case`Case`:return{node:N(`$Pfcase`,[I(r.expression)],i),isPick:!1};case`Witness`:return{node:N(`$Witness`,r.expressions.map(I),i),isPick:!1};case`Qed`:return{node:N(`$Qed`,[],i),isPick:!1};case`Take`:case`Pick`:{let e=r.kind===`Pick`,o=e?`$Pick`:`$Take`;e&&a.contexts.push(U());let s=e=>r.kind===`Pick`?[P(e,r.body)]:[];if(r.bounds.length>0){let n=ge(r.bounds,t.start),a=s(n.bounded.flat());return{node:N(o,a,i,n),isPick:e}}let c=Tr(n,t.start,t.end+1,r.names),l=r.names.map((e,t)=>j(e,0,q(n,c[t]),!0)),u=s(l);return{node:N(o,u,i,{unbounded:l}),isPick:e}}}},st=e=>{if((e.kind===`And`||e.kind===`Or`)&&!e.isBulleted)return!0;if(e.kind!==`Apply`||e.args.length!==2)return!1;let t=vr(n,G(n,e.args[0])),r=G(n,e).start;return t.start===r&&!W(n,t.end+1,`(`)},ct=e=>{if(e.kind!==`Steps`)return at(e);let r=U();a.contexts.push(r);let i=[],o=[],s={previousRight:void 0},c=(e,r,a)=>{if(e.kind===`Define`){let r=e.definitions.map(e=>{let n=[];e.kind===`Instance`?Ue(e,n,i):e.kind===`Function`?Re(e,n):Ie(e,n);let r=n[e.kind===`Instance`?n.length-1:0];if(r?.kind!==`OpDef`)throw new t(`A DEFINE step defines no operator`);return r});return{...H(l()),kind:`DefStep`,defs:r,location:K(n,a)}}if(e.kind===`Use`||e.kind===`Hide`)return{...tt(e),location:K(n,r)};if(e.kind===`Instance`)return We(e,!1,K(n,a))},u=e.steps.map(e=>{let r=E(e.location),i=_r(n,e.head),u={start:i.start+1,end:i.end},d=e.body;e.name!==void 0&&b();let p=e.name===void 0?void 0:l();d.kind!==`Assert`&&(s.previousRight=void 0);let m=c(d,r,u);if(m!==void 0)return e.name!==void 0&&f(a,ne({defKind:`NumberedProofStep`,name:e.name,location:K(n,r),labels:x(),step:m})),m;let h=d.kind===`Assert`&&d.statement.kind===`AssumeProve`;h&&(s.previousRight=void 0);let g=d.kind===`Assert`&&d.isSuffices,_=U(),v=d.kind===`Assert`?{node:(t=>{if(t.kind===`AssumeProve`){let n=A(_,()=>rt(t,1,e.name===void 0?void 0:{isSuffices:g}));return n.isSuffices=g,n}if(g){let e=I(t);return N(`$Suffices`,[e],K(n,u))}let r=s.previousRight,i=r!==void 0&&t.kind===`Apply`&&st(t)&&t.args[0].kind===`ExceptAt`,a=i?I(t.args[1]):void 0,o=i?ie(ce(t.operator,T(t)),[N(`$Nop`,[r],T(t.args[0])),a],T(t)):I(t),c=o.kind===`OpAppl`?o.operands[1]:void 0;return s.previousRight=st(t)?c:void 0,o})(d.statement),isPick:!1}:ot(e,u);if(v===void 0)throw new t(`Unexpected proof step ${d.kind}`);let y=v.isPick?a.contexts.pop():void 0,S=e.name===void 0||p===void 0?void 0:it(p,e.name,v.node,q(n,mr(n,e.location)),x());S&&f(a,S);let C=h&&!g;C&&a.contexts.push(_);let w=e.proof&&ct(e.proof);return C&&a.contexts.pop(),ee(v.node),h&&g&&(o.push(_),a.contexts.push(_)),y?.symbols.forEach(e=>f(a,e)),{...H(l()),kind:`Theorem`,definition:S,body:v.node,proof:w,isSuffices:g,location:K(n,r)}});return o.forEach(()=>{a.contexts.pop()?.symbols.forEach(e=>Kn(r,e))}),a.contexts.pop(),{...H(l()),kind:`NonLeafProof`,steps:u,instances:i,proofLevel:e.level,location:K(n,E(e.location))}},lt=e=>{let t=K(n,E(e.location)),r=e.statement,i=U();e.name!==void 0&&b();let o=e.name===void 0?void 0:l();r.kind===`AssumeProve`&&a.contexts.push(i);let s=r.kind===`AssumeProve`?rt(r,1,e.name===void 0?void 0:{isSuffices:!1}):I(r),c=e.name===void 0||o===void 0?void 0:it(o,e.name,s,t,x());c&&(r.kind===`AssumeProve`&&a.contexts.pop(),f(a,c),D.definitions.push(c),r.kind===`AssumeProve`&&a.contexts.push(i));let u=e.proof&&ct(e.proof);r.kind===`AssumeProve`&&a.contexts.pop(),ee(s);let d={...H(l()),kind:`Theorem`,definition:c,body:s,proof:u,isSuffices:!1,location:t};D.topLevel.push(d)},ut=e=>{let t=E(e.location),r=K(n,t);e.name!==void 0&&b();let i=I(e.expression),o=e.name===void 0?void 0:it(l(),e.name,i,r,x(),!1);o&&(f(a,o),D.definitions.push(o));let s={...H(l()),kind:`Assume`,definition:o,body:i,location:r};D.topLevel.push(s)},dt=(e,t)=>t===0?{start:e,end:e}:W(n,e,`_`)?{start:e,end:W(n,e+2,`_`)?e+2:e+1}:W(n,e+1,`(`)?{start:e,end:gr(n,e+1)}:{start:e,end:W(n,e+1,`_`)?e+1:e},ft=e=>dt(E(e.location).start,e.arity),pt=(e,t)=>{let r=ft(e);e.name===`@`&&t===3&&o(K(n,r),`Attempted to declare '@' as a variable.`);let i={...H(l()),levelChecked:1,level:+(t===3),kind:`OpDecl`,name:Or(e.name),arity:e.arity,declKind:t,location:K(n,r),module:D};return t===2&&(i.levelParams.add(i),i.allParams.add(i)),f(a,i),i};e.extends.forEach(e=>{let t=k(e);D.extendees.push(t);let n=Mr(a);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?Yn(n,e.name):Jn(n,e.name);t===void 0?Kn(n,e):t!==e&&t.kind!==e.kind?o(e.location,`The ${Fr(e)} of '${e.name}' conflicts with \nits ${Fr(t)} at ${Fn(t.location)}.`):t!==e&&!Ir(t,e)&&s(e.location,`Warning: the ${Fr(t)} of '${e.name}' conflicts with \nits ${Fr(t)} at ${Fn(t.location)}.`)}),D.topLevel.push(...t.topLevel)});let mt=(e,t)=>{c.unresolvedSum!==0&&o(K(n,E(e)),`${t} may not appear within a recursive definition section.`)};return e.units.forEach(e=>{switch(e.kind){case`Variables`:mt(e.location,`A VARIABLE declaration`),e.declarations.forEach(e=>pt(e,3));break;case`Constants`:mt(e.location,`A declaration`),e.declarations.forEach(e=>pt(e,2));break;case`Recursive`:Be(e.declarations);break;case`Definition`:e.definition.kind===`Function`?Re(e.definition,void 0):Ie(e.definition,void 0);break;case`Instance`:e.instance.name===void 0?We(e.instance):Ue(e.instance,void 0,void 0);break;case`Assumption`:mt(e.assumption.location,`An ASSUME`),ut(e.assumption);break;case`Theorem`:mt(e.theorem.location,`A THEOREM`),lt(e.theorem);break;case`Use`:mt(e.use.location,`A USE or HIDE`),D.topLevel.push(tt(e.use));break;case`Module`:{mt(e.module.location,`A MODULE `);let t={contexts:[...a.contexts,U()]},r=te(e.module,n,D,t),i=O(r.name);i===void 0?Kn(Mr(a),r):i!==r&&o(r.location,`Multiply-defined module '${r.name}': this definition or declaration conflicts \nwith the one at ${Fn(i.location)}.`);break}}}),Ve(),D},A=x.map(e=>{r.onAnalyze?.(e),u.id=Array.from({length:4},l)[1];let t=b(e,void 0),n=U();p.toReversed().forEach(e=>Kn(n,e));let i=te(t.module,t.file,void 0,{contexts:[n]});return g.set(e,i),r.onModule?.(i,a),i});return{root:A[A.length-1],modules:A,messages:a}},Yr=e=>{let t=e.toLowerCase(),n=t.startsWith(`\\b`)?2:t.startsWith(`\\o`)?8:t.startsWith(`\\h`)?16:10;return[...n===10?t:t.slice(2)].reduce((e,t)=>e*BigInt(n)+BigInt(parseInt(t,n)),0n).toString()},J=(e,t,n,r)=>Pn(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)},Xr=(e,t,n)=>`${e.id}:${t}:${n.id}`,Zr=(e,t,n,r)=>{e.set(Xr(t,n,r),{op:t,index:n,param:r})},Qr=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},$r=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},ei=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&$r(e,r,t)})},ti=(e,t)=>`${e.id}:${t}`,ni=(e,t,n,r)=>{let i=ti(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},ri=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&ni(e,t.param,t.position,t.level)})},ii=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},ai=(e,t)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),ei(e.levelConstraints,t.levelConstraints),ri(e.argLevelConstraints,t.argLevelConstraints),Qr(e.argLevelParams,t.argLevelParams)},oi=(e,t)=>t.includes(e.op)||t.includes(e.param),si=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,ci=e=>e.kind!==`Module`,li=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,ui=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,di=(e,t)=>e.kind===`OpDef`?e.weights[ui(e,t)]??0:0,fi=(e,t)=>e.maxLevels[ui(e,t)]??3,pi=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,mi=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[ui(e,t)]??!0:e.isLeibnizArg[t]??!0,hi=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,gi=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],_i=(e,t)=>t.find(t=>t.op===e)?.expr,vi=(e,t,n)=>{let r=_i(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},yi=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=_i(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!si(i.op))return;let a=i.op;vi(e.param,t,!1).forEach(t=>Zr(n,a,e.index,t))}),n},bi=(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;vi(r,t,!1).forEach(e=>$r(a,e,i))}),e.argLevelParams.forEach(e=>{let n=_i(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;X(n.op,r,i);let o=fi(n.op,e.index);vi(e.param,t,!1).forEach(e=>$r(a,e,o))}),a},xi=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=_i(e.param,t);n===void 0?ni(i,e.param,e.position,e.level):n.kind===`OpArg`&&si(n.op)&&ni(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=_i(e.param,t);if(a===void 0)return;let o=_i(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&si(s)&&(X(a,n,r),ni(i,s,e.index,a.level))}),i},Si=(e,t)=>Zn(e,3).length>0||(ji(e,t),Xn(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),Ci=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(ti(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(Xr(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(ti(t,n))}),Qr(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},wi=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>fi(t,o)&&(n&&X(a,r,i)&&J(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`||!li(a.op)))return;let s=a.op;X(s,r,i);let c=qn(s);for(let l=0;l<c;l++){let c=pi(t,o,l);fi(s,l)>=c||(n&&X(a,r,i)&&J(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||!hi(t,o,l,u)||n.level<=fi(s,u)||(X(a,r,i)&&X(n,r,i)&&J(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&&J(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${Fn(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},Ti=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);ei(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&ei(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>ei(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=fi(t,r);n?.levelParams.forEach(t=>$r(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!li(n.op))return;let o=n.op;X(o,r,i);let s=qn(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!hi(t,a,r,i))continue;let s=fi(o,i);n?.levelParams.forEach(t=>$r(e.levelConstraints,t,s)),!o.isLeibniz&&!mi(o,i)&&n&&Y(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&li(n.op)&&(X(n.op,r,i),$r(e.levelConstraints,t.param,fi(n.op,t.index)))}),ri(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&ri(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>ri(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!si(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)ni(e.argLevelConstraints,i,n,pi(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&hi(t,r,a,o)&&ni(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(X(n,r,i),ni(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&Qr(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>Qr(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=>Zr(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&si(a.op)&&Zr(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!si(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&hi(t,r,a,o)&&n.levelParams.forEach(t=>Zr(e.argLevelParams,i,o,t))})})},Ei=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),Di=(e,t)=>{let n=(n,r)=>{J(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=Ei.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.`)})},Oi=(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(li(i)){let r=X(i,t,n);wi(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&di(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&&(di(i,n)===1&&Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),mi(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(gi(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),Ti(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),ei(e.levelConstraints,t.levelConstraints),ni(e.argLevelConstraints,i,n,t.level),ri(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>Zr(e.argLevelParams,i,n,t)),Qr(e.argLevelParams,t.argLevelParams)});return Di(e,n),e.levelCorrect},ki=(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))}),Ci(e,i,r),e.levelCorrect},Ai=(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)}),Ci(e,e.params,e.body)),e.levelCorrect),ji=(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),ki(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||J(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),ki(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(ji(e,t)));let a=Xn(e);return a.forEach(e=>i(ki(e,1,t))),Qn(e).forEach(e=>i(Ai(e,1,t))),e.topLevel.forEach(e=>i(X(e,1,t))),Si(e,t)||Zn(e,2).forEach(t=>$r(e.levelConstraints,t,0)),a.forEach(t=>{ei(e.levelConstraints,t.levelConstraints),ri(e.argLevelConstraints,t.argLevelConstraints),Qr(e.argLevelParams,t.argLevelParams,e=>!oi(e,t.params??[]))}),e.topLevel.forEach(t=>{ei(e.levelConstraints,t.levelConstraints),ri(e.argLevelConstraints,t.argLevelConstraints),Qr(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},Mi=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{ci(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=X(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),ai(e,t),Y(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),Ni=(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&&J(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&J(t,e.body.location,`Non-constant CASE for temporal goal.`),Ni(e.proof,t)):n===`$Qed`&&Ni(e.proof,t)})},Pi=(e,t,n,r,i,a)=>{e.levelConstraints=bi(t,n,r,i,a),e.argLevelConstraints=xi(t,n,i,a),e.argLevelParams=yi(t.argLevelParams,n)},Fi=(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;ji(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(r.expr,t,n)||(e.levelCorrect=!1)});let i=Si(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(X(a.expr,t,n)&&J(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||J(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)&&J(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(ti(i.op,t))?.level;a===void 0||fi(o,t)>=a||(s&&J(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=fi(s,i.index);o.expr.level<=l||(c&&X(o.expr,t,n)&&J(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 ei(e.levelConstraints,bi(r,e.substs,i,t,n),a),e.substs.forEach(t=>ei(e.levelConstraints,t.expr.levelConstraints,a)),ri(e.argLevelConstraints,xi(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>ri(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),Qr(e.argLevelParams,yi(r.argLevelParams,e.substs),t=>!oi(t,e.params)),e.substs.forEach(t=>Qr(e.argLevelParams,t.expr.argLevelParams,t=>!oi(t,e.params))),e.levelCorrect},X=(e,t,n)=>{if(!ci(e))return ji(e,n);switch(e.kind){case`OpAppl`:return Oi(e,t,n);case`OpDef`:return ki(e,t,n);case`ThmOrAssumpDef`:return Ai(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,ii(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),ei(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>ei(e.levelConstraints,t.levelConstraints)),ri(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>ri(e.argLevelConstraints,t.argLevelConstraints)),Qr(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];Qr(e.argLevelParams,t.argLevelParams,e=>!oi(e,n))}),e.instances.forEach(t=>Qr(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,ii(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=>ai(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,vi(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>Y(e.allParams,vi(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=Si(e.instantiatedModule,n);return Pi(e,r,e.substs,i,t,n),e.levelCorrect}case`Instance`:return Fi(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,ii(e,e.body),e.level!==0&&J(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=Mi(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&&J(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&Ni(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return Mi(e,e.facts,t,n);case`NonLeafProof`:return Mi(e,[...e.steps,...e.instances],t,n);case`DefStep`:return Mi(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,J(n,e.location,`Level error:
|
|
27
|
-
Temporal formula used as set.`)),ii(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=>ai(e,t)),e.levelCorrect&&e.levelParams.forEach(t=>{t.kind===`OpDecl`&&t.declKind===2&&$r(e.levelConstraints,t,2)})),e.levelCorrect}},Ii=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[]}},Li=/* @__PURE__ */ new Map([[`Integers`,`Int`],[`Naturals`,`Nat`],[`Reals`,`Reals`]]),Ri=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&&Li.get(e)===t.name||n(t))return!0}}return Ii(e).some(n)};return n(e)},zi=e=>e.operands.filter(e=>e?.kind===`OpAppl`),Bi=e=>{let t=e.operands[0];return t?.kind===`String`?t:void 0},Vi=(e,t)=>{if(e===t)return!0;if(e.operands.length!==t.operands.length)return!1;let n=new Set(zi(t).map(e=>Bi(e)?.value));return zi(e).every(e=>n.has(Bi(e)?.value))},Hi=(e,t=/* @__PURE__ */ new Set)=>(e.extendees.forEach(e=>{t.has(e)||(t.add(e),Hi(e,t))}),t),Ui=e=>{let t=[...[...Hi(e)].flatMap(e=>e.records),...e.records];return e.records.flatMap(n=>t.filter(e=>Vi(e,n)).flatMap(zi).some(Ri)?[]:zi(n).flatMap(t=>{let n=Bi(t),r=n&&Jn(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 ${Fn(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}]}))},Wi=e=>`${Fn(e.location)}\n\n${e.text}`,Gi=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=>`${Wi(e)}\n\n\n`),n.length>0?`*** Warnings: ${n.length}\n\n`:``,...n.map(e=>`${Wi(e)}\n\n\n`)].join(``)},Ki=/* @__PURE__ */ new Set([`FiniteSets`,`Sequences`,`Bags`,`Naturals`,`Integers`,`Reals`,`RealTime`,`Randomization`,`TLC`]),qi=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))},Ji=e=>{try{return ae(Cr(e))}catch(e){if(e instanceof t)return;throw e}},Yi=(e,t)=>t===`1.7.4`&&_(e)!==void 0?void 0:Ji(e)?.name,Xi=(e,t=()=>void 0,n={})=>{let r=xe(e,`.tla`),a=k(n.version),o=n.fileName??r,s=F(e)?ke(e,`utf8`):a.get(r),c=[],l=e=>{c.push(e),n.onPrint?.(e)},u=e=>l(`${e}\n`),d=n.version===`1.7.4`,f=d&&n.isXmlExport,p=e=>{n.isXmlExport||u(e)},h=n.describeFile,g=/* @__PURE__ */ new Map([[r,F(e)?`file`:`standard`]]),_={value:!1},v=[],y={isReported:!1,isAborted:!1},x=kt(He(),u),S=/* @__PURE__ */ new Map,C=[],w=()=>C.splice(0).forEach(e=>e.isError?n.onPrintError?.(`${e.text}\n`):u(e.text)),ee=e=>{let t=S.get(e),r=t?.module.location.range;if(t===void 0||r===void 0)return;let i=t.text.split(/\r\n|\r|\n/),a=An(x,i.slice(r.start.line-1,r.end.line),n.version),o=a.has(`TLA_DIVERGENCE_EXISTS`),s=a.has(`PCAL_DIVERGENCE_EXISTS`),c=o===s?void 0:`The ${o?`TLA+ translation`:`PlusCal algorithm`} in module ${e} has changed since its last translation.`;if(d){let t=o&&s?`The PlusCal algorithm and its TLA+ translation in module ${e} filename since the last translation.`:c;t===void 0?a.has(`ERROR_ENCOUNTERED`)&&C.push({text:`A unexpected problem was encountered attempting to validate the specification for ${e}`,isError:!0}):C.push({text:`!! WARNING: ${t}`,isError:!1});return}let l=o&&s?`Both the PlusCal algorithm and its TLA+ translation in module ${e} have changed since the last translation.`:c??(a.has(`ERROR_ENCOUNTERED`)?`An unexpected problem was encountered attempting to validate the specification for ${e}`:void 0);if(l===void 0)return;let u=!a.has(`ERROR_ENCOUNTERED`)||o||s;v.some(e=>e.text===l)||v.push({location:e,text:l,isWarning:u})},T=(e,t)=>{if(n.isXmlExport||S.has(e))return;let r=Ji(t);if(r===void 0||r.name!==e)return;let i=[...S.values()].filter(t=>qi(t.module).includes(e));S.set(e,{text:t,module:r}),i.forEach(()=>ee(e)),qi(r).filter(t=>t!==e&&S.has(t)).forEach(ee)},E=()=>{if(w(),y.isReported)return;y.isReported=!0;let e=v.filter(e=>e.isWarning);e.length>0&&(p(`Warnings (${e.length}) during syntax parsing of ${o}:\n\n`),e.forEach(e=>p(`${Wi(e)}\n\n\n`))),e.length!==v.length&&(u(Gi(v)),_.value=!0,y.isAborted=!0)},D=e=>{let n=a.get(e),r=t(e),i=r===void 0&&n===void 0&&s!==void 0&&!d?b(s,e):void 0,o=r??i;return g.set(e,r===void 0?i===void 0?`standard`:`root file`:`file`),o!==void 0&&T(e,o),o??n},O=(()=>{try{if(s===void 0)throw new i(`Cannot find source file for module ${o}`,void 0);return T(r,s),Jr(s,D,{rootFileName:r,rootFilePath:n.isXmlExport?`${o.replace(/\.tla$/,``)}.tla`:void 0,version:n.version,rootExtendees:n.rootExtendees,onParse:e=>{h&&u(`Parsing file ${h(e,g.get(e)??`file`)}`),e===r&&ee(r),w()},onAnalyze:e=>{E(),(h||f)&&!y.isAborted&&u(`Semantic processing of module ${e}`)},onModule:(e,t)=>{if(y.isAborted||(t.every(e=>e.isWarning)&&ji(e,{messages:t,isTlc174:d}),t.length===0))return;if(t.some(e=>!e.isWarning)&&(_.value=!0),d)return u(`Semantic errors:\n\n${Gi(t)}`);let n=t.filter(e=>e.isWarning);n.length>0&&(p(`*** Warnings: ${n.length}\n`),n.forEach(e=>p(`${Wi(e)}\n\n\n`)));let r=t.filter(e=>!e.isWarning);r.length!==0&&(u(`Semantic errors:\n\n*** Errors: ${r.length}\n`),r.forEach(e=>u(`${Wi(e)}\n\n`)))}})}catch(e){if(_.value=!0,e instanceof m){u(`\nFatal errors while parsing TLA+ spec in file ${o}\n`),u(e.message),u(Gi(v));return}if(!(e instanceof i))throw e;let t={location:e.location,text:e.message,isWarning:!1},n=d&&e.parseError?.includes(` and token "" `);if(e.parseError!==void 0&&!n&&!f&&u(e.parseError),u(`\nFatal errors while parsing TLA+ spec in file ${o}\n`),n){u(`java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null`);return}if(d){u(`tla2sany.semantic.AbortException`),l(`*** Abort messages: 1\n\n${Wi(t)}\n\n\n`);return}u(Wi(t)),u(Gi(y.isReported?[t]:[...v,t]))}})();if(O!==void 0&&E(),O!==void 0&&!_.value&&!n.isXmlExport&&!d){let e=O.modules.filter(e=>!Ki.has(e.name));h&&e.forEach(e=>u(`Linting of module ${e.name}`)),e.flatMap(Ui).forEach(e=>u(`${Wi(e)}\n\n\n`))}return{text:c.join(``),isFailed:_.value,specification:y.isAborted?void 0:O}},Zi={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},Qi=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:[]}),$i={"&":`&`,"<":`<`,">":`>`,"\r":` `},ea=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:$i[e]),ta=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,na=e=>{let t=(e.cdata??e.text)?.match(ta)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=na(t);if(e)return e}},ra=(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}>${ea(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)ra(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},ia=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)]),aa=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)`}},oa={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)`}}},sa={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},ca=Fn(`--TLA+ BUILTINS--`),la=(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}]},ua=(e,t=16)=>e>t*.75?ua(e,t*2):t,da=(e,t)=>(e^e>>>16)&t-1,fa=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},pa=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),ma=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,ha=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=fa(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(ma,``)}).join(`
|
|
28
|
-
`)},
|
|
29
|
-
`)},
|
|
30
|
-
`),i=n.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${r}\n`).join(``);return a(new c(r,i),
|
|
31
|
-
`),r=n.isUncommented?
|
|
32
|
-
`)}\n`},
|
|
33
|
-
`)})(),
|
|
34
|
-
`),
|
|
35
|
-
`},
|
|
36
|
-
`: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`,
|
|
37
|
-
`;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`},
|
|
38
|
-
`))}if(e.failure?.isWithoutStatistics)return;e.status!==`success`&&Ja(t,r),t.isTool&&Ga(t,e,r.start),i(w.stats,O.none,`${e.generatedStates} states generated, ${e.distinctStates} distinct states found, ${e.queuedStates} states left on queue.`);let s=t.version===`1.7.4`,c=s?e.outDegrees??e.violationOutDegrees:e.outDegrees;(!s||c)&&i(w.searchDepth,O.none,`The depth of the complete state graph search is ${s?Math.max(e.depth,1):e.depth}.`);let u=c&&le(c);u&&i(w.stateGraphOutdegree,O.none,u)},Qa=(e,t)=>e.map(e=>Te(e,`${t}.tla`)).find(F),$a=e=>t=>{let n=Qa(e,t);return n===void 0?void 0:ke(n,`utf8`)},eo=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),to=e=>`jar:file:${Le(Ee(e)).pathname}!/tla2sany/StandardModules/`,no=e=>x([e]).toString(),ro=(e,t,n,r,i)=>{let a=n.temporaryDirectory??Fe(),o=F(a)?je(a):Ee(a),s=Te(o,`tlc-${no(Ee(e))}`),c=Lo(n);return(n,a)=>{let l=`${n}.tla`;if(a===`file`)return je(Qa(t,n)??e);if(i===`1.7.4`)return Te(o,l);if(a===`root file`){let t=r===void 0?o:Ee(r),i=je(e);return`${Te(t,no(`${i} ${n}`),l)} (${i})`}let u=Te(s,l);return c===void 0?u:`${u} (${to(c)}${l})`}},io=e=>e.print(w.version,O.none,`TLC2 Version ${ze} (rev: tla-ts)`),ao=(e,t)=>(io(e),e.print(w.commandLineError,O.error,`${t}\nUsage: java tlc2.TLC [-help] [-option] inputfile`),1),oo=(e,t,n)=>e.print(w.modelChecking,O.none,`Running breadth-first search Model-Checking with fp 0 and seed ${BigInt(t)} with ${n} worker${n===1?``:`s`} on ${Ne()} cores with ${Math.floor(Re().heap_size_limit/1024/1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${Ie()} ${Pe()} ${Me()}, Node.js ${process.versions.node} ${process.arch.endsWith(`64`)?64:32}bit, MemFPSet, MemStateQueue).`),so=(e,t)=>{let n=[...e.unknown,...e.options.map(e=>e.name)],r=(e,t=e)=>n.some(n=>n===e||n.toLowerCase()===t.toLowerCase()),i=r(`-generateSpecTE`)||!r(`-noGenerateSpecTE`,`-noTE`)&&!r(`-tool`)&&!r(`-continue`);return t!==`1.7.4`&&i&&!r(`-noGenerateSpecTEBin`,`-noTEBin`)},co=async(e,n,a,s)=>{let c=n.has(`-seed`)?n.get(`-seed`)?.[0]:`0`;if(c===void 0)return ao(s,`Error: seed required.`);if(!ja(c))return ao(s,`Error: An integer for seed required. But encountered ${c}`);let l=n.has(`-lncheck`)?n.get(`-lncheck`)?.[0]?.toLowerCase():`default`;if(l===void 0)return ao(s,`Error: expect a strategy such as final for -lncheck option.`);let d=n.get(`-dump`);if(d?.length===0)return ao(s,`Error: A file name for dumping states required.`);let p=d?.length===2&&Na.find(e=>d[0].toLowerCase().includes(e));if(p)return console.error(`Error: tla-ts does not support the -dump format ${p}.`),1;let m=n.get(`-fp`)?.[0];if(m!==void 0&&Number(m)!==0)return console.error(`Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${m}.`),1;let h=Ma(n.get(`-workers`)),_=s.version;io(s),oo(s,c,h);let v=n.get(`-config`)?.[0]??(n.has(`-config`)?void 0:e.replace(/\.tla$/,`.cfg`));if(!v||!F(v))return s.print(w.configFileError,O.error,`TLC encountered the following error when trying to read the configuration file ${v??``}:\nFile not found.`),o.configParseError;let b=xe(e,`.tla`),x={start:Date.now(),liveness:void 0,isParsed:!1},S=()=>{let e=Date.now()-x.start;s.print(w.finished,O.none,`Finished in ${s.isTool?`${e}ms`:te(e)} at (${C(/* @__PURE__ */ new Date)})`)},ee=()=>s.print(w.parsingFailed,O.error,`Parsing or semantic analysis failed.`),T=e=>(e instanceof t?ee():uo(e,s),S(),r(e)),k=(()=>{try{return D(ke(v,`utf8`),_)}catch(e){if(!(e instanceof f))throw e;return e}})();if(k instanceof f&&_===`1.7.4`)return s.print(w.general,O.error,`${g(`tlc2.tool.ConfigFileException`)}${A(k.message,s.isTool)}`),S(),o.error;if(k instanceof f)return T(k);n.has(`-deadlock`)&&(k.checkDeadlock=!1);let j=Ce(e),ne=[j,...a.libraries],re=$a(ne),ie=so(n,_),M=async()=>{let t=ke(e,`utf8`),r=E(t).name;if(r!==b)throw new i(`File name '${b}' does not match the name '${r}' of the top level module it contains.`,void 0);let a=await he({workers:h,livenessCheck:[`final`,`seqfinal`,`off`].includes(l)?`final`:`default`,seed:BigInt(c),dump:d&&Fa(d),isTool:s.isTool,isTraceRecorded:ie,isSanyReported:!0,isWarningEnabled:!n.has(`-nowarning`),version:_,onProgress:e=>qa(s,e,x,j),source:t,config:k,onPause:()=>Ae(0,Buffer.alloc(1)),loadModule:re,loadClass:e=>{let t=Ka(j,e);return F(t)?ke(t):void 0},readFile:e=>F(e)?ke(e,`utf8`):void 0,writeFile:(e,t)=>{Oe(Ce(Ee(e)),{recursive:!0}),I(e,t)}});return Za(a,s,x),S(),a.failure?.exitCode??xa[a.status]};s.isTool&&s.print(w.startingSany,O.none,`Starting SANY...`);let ae=we(e),N=ae?b:e.replace(/\.tla$/,``),oe=Lo(a),se=_===`1.7.4`?Mo(e,a,oe):void 0;if(se?!F(e)&&!y.has(b)&&se(`${b}.tla`):!F(e)&&!ue.has(b)&&eo(ae?j:process.cwd(),ae?`${b}.tla`:`./${N}.tla`,[...ae||j===`.`?[]:[j],...a.libraries]),Xi(e,se?No(re,se):re,{fileName:N,describeFile:ro(e,ne,a,n.get(`-metadir`)?.[0],_),version:_,rootExtendees:ie?[`_TLCTrace`]:void 0,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}).isFailed)return qa(s,{kind:`parsed`},x,j),ee(),S(),o.specParseError;try{return await M()}catch(e){if(!(e instanceof u))throw e;return e instanceof t&&console.log(lo(e,b)),x.isParsed||qa(s,{kind:`parsed`},x,j),T(e)}},lo=(e,t)=>{let n=e instanceof i;if(!n&&!e.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${e.message}\n\n`;let r=n?e.location===void 0?`Unknown location\n\n${e.message}`:`In module ${e.location}\n\n${e.message}`:`In module ${t}\n\nCould not parse module ${t} from file ${t}.tla`;return`${e.failure?`***Parse Error***\n${e.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${t}\n\n${r}\n*** Errors: 1\n\n${r}\n\n\n`},uo=(e,t)=>{if(e instanceof f||e instanceof l){let n=j(e.message),r=n&&!n.isEvalException?n.code:w.general;return t.print(r,O.error,v(r,e.message,t.isTool))}console.error(`${e.name}: ${e.message}`)},fo=async(e,t=de(!1))=>{try{return await e()}catch(e){if(!(e instanceof u))throw e;return uo(e,t),r(e)}},po=async(e,t,n)=>{let r=[];for(let[i,a]of e.entries()){i>0&&console.log(``);let e=n();r.push(await fo(()=>t(a,e),e))}return r.find(e=>e!==o.success)??o.success},mo=()=>be().map(e=>Te(Ce(Ce(je(e))),`lib/tlapm/stdlib`)).find(e=>F(e)),ho=e=>e.flatMap(e=>ka.test(e)?De(e).sort():[e]),go=e=>F(e)?{file:e,source:ke(e,`utf8`)}:void 0,_o=e=>console.error(`@!!BEGIN\n${e.map(e=>`@!!${e}\n`).join(``)}@!!END\n`),vo=e=>/^[+,\-./0-9:=@A-Z_a-z]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`,yo=e=>console.log(`\n\\* TLAPM version 5f5037f\n\\* launched at ${C(/* @__PURE__ */ new Date)} with command line:\n\\* ${[`tla-ts`,`prove`,...e].map(vo).join(` `)}\n`),bo={incomplete:11,emptyTarget:12},xo=(e,t,n)=>{let r=e.summary;n||(r.absent.forEach(e=>console.error(`Missing proof at ${pe(e)}`)),r.omitted.forEach(e=>console.error(`Omitted proof at ${pe(e)}`)));let i=r.absent.length+r.omitted.length>0;i&&console.error(`${ve(e.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(e.name)}: ${r.absent.length} missing, ${r.omitted.length} omitted proof step(s).`);let a=t&&e.obligations.length===0;return a&&console.error(`${ve(e.location)}[ERROR]: No proof obligation found for the selected target.`),[...i?[bo.incomplete]:[],...a?[bo.emptyTarget]:[]]},So=t=>{try{return t()}catch(t){if(!(t instanceof e))throw t;console.error(` tlapm ending abnormally with ${t.exception}\n`);return}},Co=e=>{let t=wa.parse(e),n=t.get(`--backend`)?.[0];if(t.unknown[0]!==void 0||t.incomplete||n!==void 0&&!ge(n))return console.error(`Usage: ${wa.usage}`),1;let r=ho(t.positionals).map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(r.length===0)return console.error(`Usage: ${wa.usage}`),1;let i=mo(),a=t.options.flatMap(e=>e.name===`-I`?e.values:[]);return po(r,async e=>{let r=[Ce(e),`.`,...i?[i]:[],...a.toReversed()],s=await _e({source:ke(e,`utf8`),loadModule:e=>r.map(t=>go(`${t}/${e}.tla`)).find(Boolean)?.source,backend:n,workers:Ma(t.get(`-workers`)),onObligation:t=>console.log(`${e}:${t.location}: ${t.status}${t.status===`proved`?` by ${t.prover}`:``}${t.status===`failed`||t.status===`unsupported`?` (${t.reason})`:``}`)}),c=Map.groupBy(s.obligations,e=>e.status),l=e=>c.get(e)?.length??0;return console.log(`${s.obligations.length} obligations: ${l(`proved`)} proved, ${l(`trivial`)} trivial, ${l(`failed`)} failed, ${l(`unsupported`)} unsupported`),l(`failed`)+l(`unsupported`)===0?o.success:1},()=>de(!1))},wo=t=>{if(!t.includes(`-N`)&&!t.includes(`--summary`))return Co(t);let n=Ca.parse(t),r=n.unknown[0];if(r!==void 0)return console.error(`Error: tla-ts prove does not support the tlapm option ${r}.`),1;if(n.incomplete)return console.error(`Error: option '${n.incomplete.name}' needs an argument.`),1;let i=n.options.find(e=>e.name!==`-I`&&e.values.some(e=>!/^-?\d+$/.test(e)));if(i)return console.error(`Error: option '${i.name}' expects an integer.`),1;let a=ho(n.positionals),s=a.map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(s.length===0)return console.error(Oa),1;let c=n.has(`--toolbox`)||n.has(`--line`);c&&yo(t);let l=n.options.reduce((e,t)=>{let[n,r]=t.values.map(Number);return t.name===`--toolbox`?{start:n,end:r===0?1/0:r}:t.name===`--line`?n===0?me:{start:n,end:n}:e},me),u=mo(),d=n.options.flatMap(e=>e.name===`-I`?e.values:[]),f=s.reduce((e,t)=>e.includes(Ce(t))?e:[Ce(t),...e],[`.`,...u?[u]:[],...d.toReversed()]),p=So(()=>{let t=s.findIndex(e=>!F(e));if(t!==-1){let n=a[t];throw console.error(`File "<unknown>":\nError: File ${JSON.stringify(n)} not found`),new e(`File ${n} not found`,{failure:`Module.Parser.parse_file`})}return P(s.map(e=>({file:`./${e}`,source:ke(e,`utf8`)})),e=>f.map(t=>go(`${t}/${e}.tla`)).find(Boolean),{lines:l,onWarning:e=>{if(e.channel===`stdout`)return console.log(e.text);let t=e.channel===`toolbox`||e.channel===`toolboxOnly`;if(c&&t)return _o([`type:warning`,`msg:${e.text}`]);e.channel!==`toolboxOnly`&&console.error(e.text)}})});if(!p)return 3;let m=p.flatMap(e=>(n.has(`--summary`)&&console.log(fe(e)),c&&(e.obligations.forEach(e=>_o([`type:obligation`,`id:${e.id}`,`loc:${e.location}`,`status:to be proved`,...n.has(`--printallobs`)?[`obl:${e.text}`]:[]])),_o([`type:obligationsnumber`,`count:${e.obligations.length}`])),n.has(`--strict`)?xo(e,l.start>0||l.end<1/0,n.has(`--summary`)):[]));return m.includes(bo.incomplete)?bo.incomplete:m[0]??o.success},To=async(e,t)=>{let n=Sa.parse(e),r=Aa(n.positionals),i=n.has(`-config`),a=r.map(e=>({...e,path:e.isGlobbed||/\.(tla|cfg)$/.test(e.path)?e.path.replace(/\.cfg$/,`.tla`):`${e.path}.tla`})).filter(e=>e.path.endsWith(`.tla`)&&(!e.isGlobbed||i||F(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(a.length===0)return console.error(Oa),1;if(i&&a.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let o=[...new Set(a.map(e=>F(e)||we(e)?e:t.libraries.map(t=>Te(t,e)).find(F)??e))],s=t.tlcVersion??`master`;return po(o,(e,r)=>(o.length>1&&console.log(`Checking ${xe(e)} with ${xe(e,`.tla`)}.cfg`),co(e,n,t,r)),()=>de(n.has(`-tool`),!n.has(`-nowarning`),s))},Eo=e=>(process.stderr.write(`ERROR: ${e}\n${Da}`),Zi.argsParsingFailure),Do=(e,t)=>{try{return process.stdout.write(va(e,t)),o.success}catch(e){if(!(e instanceof d))throw e;let t=r(e),n=e instanceof c?e.unwound:``;return console.error(t===Zi.uncaughtException?`${n}Exception in thread "main" ${e.message}`:`ERROR: ${e.message}`),t}},Oo=(e,t)=>{let n={flags:/* @__PURE__ */ new Set,includes:[],error:void 0},r={flag:-1};for(let i=0;i<e.length-1;i++)if(t.has(e[i]))n.flags.add(e[i]),r.flag=i;else if(e[i]===`-I`){if(i++,i>e.length-2)return{...n,error:`missing-include`};n.includes.push(e[i]),r.flag=i}return r.flag===e.length-2?n:{...n,error:`several-files`}},ko=e=>{if(e.length===0)return Eo(`at least one .tla file must be given`);let t=Oo(e,Ta);if(t.error===`missing-include`)return Eo(`the -I flag must be followed by a directory and at least one .tla file`);if(t.error===`several-files`)return Eo(`Only one TLA file to check allowed!`);let n=e[e.length-1];if(n===`-help`)return process.stdout.write(Da),o.success;let r=n.endsWith(`.tla`)?n:`${n}.tla`,i=[`.`,...t.includes],a=i.map(e=>Ee(e,r)).find(F);a===void 0&&!ue.has(r.slice(0,-4))&&eo(process.cwd(),`./${r}`,t.includes);let s=Xi(a??r,$a(i),{fileName:n,isXmlExport:!0});return process.stderr.write(s.text),s.isFailed||s.specification===void 0?(console.error(`ERROR: Failed to parse module.`),Zi.specParsingFailure):Do(s.specification,{version:`master`,isRestricted:t.flags.has(`-r`),isUncommented:t.flags.has(`-u`),isTerse:t.flags.has(`-t`)})},Ao=(e,t,n)=>console.error(`File does not exist: ${we(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,...n===void 0?[]:[to(n)]].join(`, `)}`),jo=e=>e.endsWith(`/`)?e:`${e}/`,Mo=(e,t,n)=>{let r=e.slice(0,e.lastIndexOf(`/`)+1),i=(!we(e)&&r!==``?[r]:t.libraries).map(jo),a=i.length>0?i[i.length-1]:we(e)?r:``;return e=>Ao(`${a}${e}`,i,n)},No=(e,t)=>n=>{let r=e(n);return r===void 0&&!y.has(n)&&t(`${n}.tla`),r},Po=(e,t)=>(console.error(`Exception in thread "main" ${e}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${t})`),Zi.uncaughtException),Fo=(e,t)=>{if(e.length===0)return Po(`java.lang.IllegalArgumentException: at least one .tla file must be given`,59);let n=Oo(e,Ea);if(n.error===`missing-include`)return Po(`java.lang.IllegalArgumentException: the -I flag must be followed by a directory and at least one .tla file`,71);if(n.error===`several-files`)return Po(`java.lang.IllegalArgumentException: Only one TLA file to check allowed!`,83);let r=e[e.length-1],i=`${r.replace(/\.tla$/i,``)}.tla`,a=(n.includes.length===0?[`/`]:n.includes).map(jo),s=[`.`,...a],c=e=>Ao(`${a[a.length-1]}${e}`,a,t),l=s.map(e=>Ee(e,i)).find(F);if(l===void 0&&!y.has(xe(i,`.tla`)))return c(i),o.success;let u=Xi(l??i,No($a(s),c),{fileName:r,isXmlExport:!0,version:`1.7.4`});return process.stderr.write(u.text),u.specification===void 0?Po(`tla2sany.xml.XMLExportingException: spec ${(l&&Yi(ke(l,`utf8`),`1.7.4`))??`null`} is malformed - does not have a root module`,110):Do(u.specification,{version:`1.7.4`,isRestricted:!1,isUncommented:!1,isTerse:!0})},Io=[`tlc2.TLC`,`tla2sany.xml.XMLExporter`],Lo=e=>e.classPath?.split(Se).find(e=>e.endsWith(`.jar`)),Ro=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(Se));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||Io.includes(r)?{mainClass:r,args:e.slice(n+1),java:t}:void 0}},zo=e=>e.mainClass===`tlc2.TLC`?To(e.args,e.java):e.mainClass===`tla2sany.xml.XMLExporter`?fo(()=>e.java.tlcVersion===`1.7.4`?Fo(e.args,Lo(e.java)):ko(e.args)):(console.error(`Error: tla-ts runs the Java classes ${Io.join(` and `)}, not ${e.mainClass}.`),1),Bo=async e=>{if(e[0]===`prove`)return fo(()=>wo(e.slice(1)));let t=Ro(e);return t===void 0?To(e,{libraries:[]}):(t.java.tlcVersion??=await ba(Lo(t.java)),zo(t))},Vo=async()=>{process.exitCode=await Bo(process.argv.slice(2))};export{Vo as runCli};
|
|
17
|
+
`&&Xt(t),Pt(i.lines)},un=(e,t,n)=>ln(e,t,!0,n),dn=(e,t)=>(ln(e,t,!1,!1),e.delimiter),fn=(e,t)=>({params:e,tokenizer:cn(),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}),pn=()=>Pt([[At(`defaultInitValue`,0,0)]]),mn=(e,t)=>[...e,...t.filter((n,r)=>!e.includes(n)&&t.indexOf(n)===r)],hn=(e,t)=>!t.some(t=>e.includes(t)),gn=(e,t)=>{t.splice(0,t.length,...e)},_n=(e,t,n)=>{let r=e.params,i=e.lookahead,a=e.lastToken,o={lookaheadSize:0,addedLabels:[],addedLabelsLocs:[],nextLabelNum:1,allLabels:/* @__PURE__ */ new Set,hasLabel:!1,hasDefaultInitialization:!1,currentProcedure:void 0,procedures:[],pSyntax:!1,cSyntax:!1,plusLabels:[],minusLabels:[],proceduresCalled:[],gotoUsed:!1,gotoDoneUsed:!1,omitPC:r.inputVersionNumber>=1500,omitStutteringWhenDone:r.inputVersionNumber>=1500},c=e=>{throw new p(`${e}\n line ${a.line}, column ${a.column}`)},l=()=>{if(o.lookaheadSize===0)return Zt(t),a.column=t.vcolumn+1,a.line=t.line+1,a.text=dn(e.tokenizer,t),a.text;a.column=i.columns[0]+1,a.line=i.lines[0]+1;let n=i.tokens[0];for(let e=1;e<o.lookaheadSize;e++)i.tokens[e-1]=i.tokens[e],i.columns[e-1]=i.columns[e],i.lines[e-1]=i.lines[e];return--o.lookaheadSize,a.text=n,n},u=n=>{for(;o.lookaheadSize<n;){let n=o.lookaheadSize;if(Zt(t)===` `)throw new p(`Premature end of file, perhaps because of unclosed comment, near\n line ${i.lines[n]+1}, column ${i.columns[n]+1}`);i.columns[n]=t.vcolumn,i.lines[n]=t.line,i.tokens[n]=dn(e.tokenizer,t),o.lookaheadSize+=1}return i.tokens[n-1]},d=n=>{if(n<o.lookaheadSize)throw new s(`ParseAlgorithm.PeekPastAlgToken called to peek after a token
|
|
18
|
+
it has already peeked at`);for(;n>o.lookaheadSize;)i.tokens[o.lookaheadSize]=dn(e.tokenizer,t),o.lookaheadSize+=1;return Zt(t)},f=(n=!1)=>{if(o.lookaheadSize!==0)throw new s(`ParseAlgorithm: GetExpr called after lookahead`);let r=un(e.tokenizer,t,n);return i.tokens[0]=e.tokenizer.delimiter,i.columns[0]=e.tokenizer.delimiterCol,i.lines[0]=e.tokenizer.delimiterLine,o.lookaheadSize=1,r},h=(e,t)=>{if(e===`;`){let e=u(1);if(`end begin else elsif or do macro procedure process fair define } {`.split(` `).includes(e))return;if(`if either while with call return goto print assert skip`.split(` `).includes(e))throw new p(`Missing \`;' before line ${i.lines[0]+1}, column ${i.columns[0]+1}`)}let n=l();n!==e&&n!==t&&c(`Expected "${e}" but found "${n}"`)},g=e=>{let t=l();t!==e&&c(`Expected "${e}" but found "${t}"`)},_=()=>{let e=l();return e===`=`?!0:e===`\\in`||e===`∈`?!1:c(`Expected "=" or "\\in" but found "${e}"`)},v=()=>h(u(1)===`,`?`,`:`;`),y=()=>h(o.pSyntax?`begin`:`{`),b=e=>{o.cSyntax?h(`}`):(h(`end`),h(e))},x=()=>{u(1)===`variables`?g(`variables`):h(`variable`)},S=()=>{let e={...B(),kind:`VarDecl`,var:l(),col:a.column,line:a.line,isEq:!0,val:pn()};if(![`=`,`\\in`,`∈`].includes(u(1)))return o.hasDefaultInitialization=!0,e;if(e.isEq=_(),e.val=f(),e.val.tokens.length===0)throw new m(`NullPointerException`);return e},C=()=>{x();let e=[],t=[`begin`,`{`,`procedure`,`process`,`fair`,`define`,`macro`];for(;!t.includes(u(1));)e.push(S()),v();return e},w=()=>{let e={...B(),kind:`PVarDecl`,var:l(),col:a.column,line:a.line,val:pn()};if(u(1)!==`=`)return o.hasDefaultInitialization=!0,e;if(h(`=`),e.val=f(),e.val.tokens.length===0)throw new m(`NullPointerException`);return e},ee=()=>{x();let e=[];for(;u(1)!==`begin`&&u(1)!==`{`;)e.push(w()),v();return e},T=()=>{if(`while if assert print else elsif either or end with when await skip call return goto`.split(` `).includes(u(1)))return!1;let e=Zt(t);return e.length>0&&e[0]===`:`&&!(e.length>1&&e[1]===`=`)},E=()=>{if(!T())return``;let t=l();e.isInMacro&&c(`A label may not appear in a macro.`),t===`Done`&&c("Cannot use `Done' as a label."),t===`Error`&&c("Cannot use `Error' as a label."),h(`:`),o.hasLabel=!0,o.allLabels.add(t);let n=u(1);return n!==`+`&&n!==`-`||(h(n),(n===`+`?o.plusLabels:o.minusLabels).push(t),o.omitPC=!1),t},D=()=>{let e=[],t=e=>o.pSyntax&&[`end`,`else`,`elsif`,`or`].includes(e)||o.cSyntax&&e===`}`;for(;!t(u(1));)e.push(...k());return o.cSyntax&&e.length===0&&c(`Empty statement list`),e},O=e=>{g(`{`);let t=D();if(h(`}`),h(`;`),e!==``){if(t[0].lbl!==``)throw new p(`Duplicate labeling of statement`,t[0]);t[0].lbl=e}return t},k=()=>{let e=E();if(o.cSyntax&&u(1)===`{`)return O(e);let t=te();return t.lbl=e,[t]},te=()=>{let e=u(1);if(e===`if`)return j(0);if(e===`either`)return ne();if(e===`with`)return re(0);if(e===`when`||e===`await`){g(e);let t=a.column,n=a.line,r=f();if(r.tokens.length===0)throw new m(`NullPointerException`);return h(`;`),{...B(),kind:`When`,col:t,line:n,exp:r}}if(e===`print`||e===`assert`){g(e);let t=a.column,n=a.line,r=f();return r.tokens.length===0&&c(`Empty expression in ${e} statement at `),h(`;`),{...B(),kind:e===`print`?`PrintS`:`Assert`,col:t,line:n,exp:r}}if(e===`skip`){g(`skip`);let e={...B(),kind:`Skip`,col:a.column,line:a.line};return h(`;`),e}if(e===`call`)return oe();if(e===`return`){g(`return`);let e={...B(),kind:`Return`,col:a.column,line:a.line,from:o.currentProcedure};return h(`;`),e}if(e===`goto`){g(`goto`);let e=a.column,t=a.line,n=l();return o.gotoUsed=!0,(n===`Done`||n===`"Done"`)&&(o.gotoDoneUsed=!0),h(`;`),{...B(),kind:`Goto`,col:e,line:t,to:n}}return e===`while`?A():d(1)[0]===`(`?se():M()},A=()=>{g(`while`);let e=a.column,t=a.line;o.cSyntax&&h(`(`);let n=f();o.cSyntax&&h(`)`),n.tokens.length===0&&c(`Empty while test at `),o.pSyntax&&h(`do`);let r=o.pSyntax?D():k();return o.pSyntax&&(h(`end`),h(`while`),h(`;`)),r.length===0&&c(`Missing body of while statement at`),{...B(),kind:`While`,col:e,line:t,test:n,unlabDo:r,labDo:[]}},j=e=>{g(e===0?`if`:`elsif`);let t={...B(),kind:`LabelIf`,col:a.column,line:a.line,test:Mt(),unlabThen:[],labThen:[],unlabElse:[],labElse:[]};o.cSyntax&&h(`(`),t.test=f(),o.cSyntax&&h(`)`),t.test.tokens.length===0&&c(`Empty if test at `),o.pSyntax&&h(`then`),t.unlabThen=o.pSyntax?D():k();let n=u(1);return n===`else`&&(g(`else`),t.unlabElse=o.pSyntax?D():k()),o.pSyntax&&n===`elsif`&&(t.unlabElse=[j(e+1)]),o.pSyntax&&![`else`,`elsif`,`end`].includes(n)&&c(`Expecting "else", "elsif", or "end"`),o.pSyntax&&e===0&&(h(`end`),h(`if`),h(`;`)),t.unlabElse.length===0&&kt(t.unlabThen,t.unlabThen.length-1),t},ne=()=>{g(`either`);let e={...B(),kind:`LabelEither`,col:a.column,line:a.line,clauses:[]};for(;;){let t={...B(),kind:`Clause`,unlabOr:o.pSyntax?D():k(),labOr:[]};if(t.unlabOr.length===0)throw new p("`either' statement with empty `or' clause",e);if(e.clauses.push(t),u(1)!==`or`)break;g(`or`)}if(o.pSyntax&&(g(`end`),h(`either`),h(`;`)),e.clauses.length===1)throw new p("`either' statement has no `or'",e);return e},re=e=>{e===0&&(h(`with`),o.cSyntax&&h(`(`));let t={...B(),kind:`With`,col:a.column,line:a.line,var:l(),isEq:!0,exp:Mt(),Do:[]};t.isEq=_(),t.exp=f(),(o.pSyntax||u(1)!==`)`)&&v(),t.exp.tokens.length===0&&c(`Empty with expression at `);let n=o.pSyntax&&u(1)===`do`,r=o.cSyntax&&u(1)===`)`;if(n&&h(`do`),r&&g(`)`),t.Do=n?D():r?k():[re(e+1)],n&&(h(`end`),h(`with`),h(`;`)),t.Do.length===0)throw new p(`Missing body of with statement`,t);return t},ie=()=>{let e=i.columns[0]+1,t=i.lines[0]+1,n={...B(),kind:`Lhs`,col:e,line:t,var:l(),sub:f()};h(`:=`,`≔`);let r=f();return r.tokens.length===0&&c(`Empty right-hand side of assignment at `),{...B(),kind:`SingleAssign`,col:e,line:t,lhs:n,rhs:r}},M=()=>{let e={...B(),kind:`Assign`,col:i.columns[0]+1,line:i.lines[0]+1,ass:[ie()]};for(;u(1)===`||`||u(1)===`‖`;){l();try{e.ass.push(ie())}catch(e){if(!(e instanceof p))throw e;c(`Bad assignment statement at `)}}return h(`;`),e},ae=()=>{let e=[];if(d(0)[0]!==`)`)for(;;){let t=f();if(e.push(t),t.tokens.length===0&&c(`Empty argument in call statement at `),u(1)===`)`)break;h(`,`)}return h(`)`),h(`;`),e},N=()=>{g(`call`);let e={...B(),kind:`Call`,col:a.column,line:a.line,returnTo:``,to:l(),args:[]};return h(`(`),e.args=ae(),o.proceduresCalled.includes(e.to)||o.proceduresCalled.push(e.to),e},oe=()=>{let e=N();if(u(1)===`return`)return g(`return`),h(`;`),{...B(),kind:`CallReturn`,col:e.col,line:e.line,to:e.to,from:o.currentProcedure,args:e.args};if(u(1)!==`goto`)return e;g(`goto`);let t={...B(),kind:`CallGoto`,col:e.col,line:e.line,to:e.to,after:l(),args:e.args};return o.gotoUsed=!0,(t.to===`Done`||t.to===`"Done"`)&&(o.gotoDoneUsed=!0),h(`;`),t},se=()=>{let e={...B(),kind:`MacroCall`,name:l(),col:a.column,line:a.line,args:[]};return g(`(`),e.args=ae(),e},ce=t=>{e.isInMacro=!0,g(`macro`);let n={...B(),kind:`Macro`,col:a.column,line:a.line,name:l(),params:[],body:[]};for(h(`(`);u(1)!==`)`;)n.params.length>0&&h(`,`),n.params.push(l());return g(`)`),y(),n.body=D(),b(`macro`),u(1)===`;`&&l(),be(n.body,t),e.isInMacro=!1,n},le=()=>{h(`procedure`);let e={...B(),kind:`Procedure`,col:a.column,line:a.line,name:l(),minusLabels:[],plusLabels:[],proceduresCalled:[],params:[],decls:[],body:[]};for(o.currentProcedure=e.name,o.plusLabels=[],o.minusLabels=[],o.proceduresCalled=[],h(`(`);u(1)!==`)`;)e.params.length>0&&h(`,`),e.params.push(w());return g(`)`),u(1)!==`begin`&&u(1)!==`{`&&(e.decls=ee()),y(),e.body=D(),b(`procedure`),u(1)===`;`&&l(),o.currentProcedure=void 0,e.plusLabels=o.plusLabels,e.minusLabels=o.minusLabels,e.proceduresCalled=o.proceduresCalled,e},ue=()=>{h(`process`);let e=a.column,t=a.line;o.cSyntax&&h(`(`);let n=l(),r=_(),i=f();o.plusLabels=[],o.minusLabels=[],o.proceduresCalled=[],o.cSyntax&&h(`)`),i.tokens.length===0&&c(`Empty process id at `);let s=u(1)===`begin`||u(1)===`{`?[]:C();y();let d=D();return b(`process`),u(1)===`;`&&l(),{...B(),kind:`Process`,col:e,line:t,name:n,fairness:0,minusLabels:o.minusLabels,plusLabels:o.plusLabels,proceduresCalled:o.proceduresCalled,isEq:r,id:i,decls:s,body:d}},de=()=>{let e=`${r.labelRoot}${o.nextLabelNum}`;return o.nextLabelNum+=1,o.allLabels.has(e)?de():e},fe=e=>{e.lbl===``&&(e.lbl=de(),o.addedLabels.push(e.lbl),o.addedLabelsLocs.push(Dt(e)))},pe=(e,t,n,r,i)=>{gn(r,i);let a={isNextLabeled:t,hasLabel:!1},s=e=>{fe(e),a.hasLabel=!0,i.length=0};return e.forEach(e=>{if(e.lbl!==``&&(a.hasLabel=!0,i.length=0,n))throw new p("Label in `with' statement",e);if(a.isNextLabeled){if(n)throw new p("Statement follows `call' or `return' inside a `with' statement.",e);s(e),a.isNextLabeled=!1}switch(e.kind){case`LabelIf`:{let t=[],r=[],o=pe(e.unlabThen,!1,n,i,t);a.isNextLabeled=pe(e.unlabElse,!1,n,i,r)||o,gn(mn(t,r),i);return}case`LabelEither`:{let t=[];e.clauses.forEach(e=>{let r=[];a.isNextLabeled=pe(e.unlabOr,!1,n,i,r)||a.isNextLabeled,gn(mn(r,t),t)}),gn(t,i);return}case`While`:if(n)throw new p("`while' inside a `with' statement",e);s(e),pe(e.unlabDo,!1,!1,i,[]),a.isNextLabeled=!1;return;case`With`:{let t=[];a.isNextLabeled=pe(e.Do,!1,!0,n?[...r]:[],t),gn(t,i),!n&&!hn(r,i)&&s(e);return}}let t=e.kind===`Call`||e.kind===`CallGoto`,c=e.kind===`Return`||e.kind===`CallReturn`,l=e.kind===`Assign`?mn([],e.ass.map(e=>e.lhs.var)):t||c?[`stack`,...c||e.to===o.currentProcedure?o.procedures.flatMap(e=>[...e.params,...e.decls].map(e=>e.var)):[]]:[];if(a.isNextLabeled=t||c||e.kind===`Goto`,hn(i,l))gn(mn(i,l),i);else{if(n)throw new p(e.kind===`Assign`?"Second assignment to same variable inside a `with' statement":"Call or return makes second assignment to a variable inside a `with' statement",e);s(e),gn(l,i)}}),a.hasLabel||a.isNextLabeled},me=e=>{let t=e=>{let t=e.findIndex(e=>e.lbl!==``),n=t===-1?e:e.slice(0,t);return me(n),{unlabeled:n,labeled:he(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}}})},he=e=>{let t=[];return e.forEach(e=>{if(e.lbl===``&&t.length>0)t[t.length-1].stmts.push(e);else{if(e.lbl===``)throw new s(`Failure of assertion: Missing Label in MakeLabeledStmtSeq`);t.push({...B(),kind:`LabeledStmt`,col:e.col,line:e.line,macroCol:e.macroCol,macroLine:e.macroLine,label:e.lbl,stmts:[e]})}}),t.forEach(e=>me(e.stmts)),t},ge=(e,t)=>{let n=e[t];switch(n.kind){case`LabelIf`:{let r=P(n.unlabThen);n.labThen.forEach(e=>P(e.stmts));let i=P(n.unlabElse);return n.labElse.forEach(e=>P(e.stmts)),n.labThen.length>0||n.labElse.length>0||r===2||i===2?2:(e[t]={...B(),kind:`If`,test:n.test,Then:n.unlabThen,Else:n.unlabElse},+(r+i>0))}case`LabelEither`:{let r=n.clauses.reduce((e,t)=>{let n=Math.max(e,P(t.unlabOr));return t.labOr.forEach(e=>P(e.stmts)),t.labOr.length>0?2:n},0);return r===2?2:(e[t]={...B(),kind:`Either`,ors:n.clauses.map(e=>e.unlabOr)},r)}case`With`:{let e=P(n.Do);if(e===2)throw new p(`with statement at ${Dt(n)} contains a labeled statement`);return e}case`While`:if(t!==0)throw new s("ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.");return P(n.unlabDo),n.labDo.forEach(e=>P(e.stmts)),0;case`Call`:return e[t+1]?.kind===`Return`?0:1;case`Return`:case`CallReturn`:if(o.currentProcedure===void 0)throw new p(`return statement not in a procedure at ${Dt(n)}`);return 1;case`Goto`:case`CallGoto`:return 1;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`MacroCall`:return 0;default:throw new s(`ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${n.kind}`)}},P=e=>{for(let t=0;t<e.length;t++){let n=ge(e,t);if(n!==0){if(t===e.length-1)return n;throw new s(`Translator discovered later than it should have that\n Statement at ${Dt(e[t+1])} must have a label`)}}return 0},_e=e=>{pe(e,!0,!1,[],[]);let t=he(e);return t.forEach(e=>P(e.stmts)),t},ve=(e,t,n,r,i)=>{let a=e=>Wt(e,t,n),o=e=>e.map(e=>ve(e,t,n,r,i)),c=e=>e.map(e=>({...B(),kind:`LabeledStmt`,label:e.label,stmts:e.stmts.map(e=>ve(e,t,n,-1,0))})),l={...B(),col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine};switch(e.kind){case`Assign`:return{...l,kind:`Assign`,ass:e.ass.map(e=>ye(e,t,n,r,i))};case`If`:return{...l,kind:`If`,test:a(e.test),Then:o(e.Then),Else:o(e.Else)};case`Either`:return{...l,kind:`Either`,ors:e.ors.map(o)};case`With`:return{...l,kind:`With`,var:e.var,isEq:e.isEq,exp:a(e.exp),Do:o(e.Do)};case`When`:case`Assert`:case`PrintS`:return{...l,kind:e.kind,exp:a(e.exp)};case`Skip`:return{...l,kind:`Skip`,macroCol:r>0?i:0,macroLine:r>0?r:-1};case`While`:return{...l,kind:`While`,test:a(e.test),unlabDo:o(e.unlabDo),labDo:c(e.labDo)};case`LabelIf`:return{...l,kind:`LabelIf`,test:a(e.test),unlabThen:o(e.unlabThen),labThen:c(e.labThen),unlabElse:o(e.unlabElse),labElse:c(e.labElse)};case`LabelEither`:return{...l,kind:`LabelEither`,clauses:e.clauses.map(e=>({...B(),kind:`Clause`,labOr:c(e.labOr),unlabOr:o(e.unlabOr)}))};case`Call`:return{...l,kind:`Call`,to:e.to,returnTo:e.returnTo,args:Gt(e.args,t,n)};case`Return`:return{...l,kind:`Return`,from:e.from};case`CallReturn`:return{...l,kind:`CallReturn`,to:e.to,from:e.from,args:Gt(e.args,t,n)};case`CallGoto`:return{...l,kind:`CallGoto`,to:e.to,after:e.after,args:Gt(e.args,t,n)};case`Goto`:return{...l,kind:`Goto`,to:e.to};default:throw new s(`Found unexpected statement type in macro at${Dt(e)}`)}},ye=(e,t,n,r,i)=>{let a=Wt(e.rhs,t,n),o={...B(),kind:`Lhs`,var:e.lhs.var,sub:e.lhs.sub.tokens.length===0?e.lhs.sub:Wt(e.lhs.sub,t,n)},s={...B(),kind:`SingleAssign`,col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine,lhs:o,rhs:a},c=n.indexOf(o.var);if(c===-1)return s;let l=t[c],u=zt(l,{line:0,item:0});if(u.type!==Ct.ident)throw new p(`Macro expansion substitutes \`${u.string}' for assignment variable\n at ${Dt(s)}`);if(o.var=u.string,Bt(l,{line:0,item:0},1)===void 0)return s;let d=It(l);return d.tokens[0].splice(0,1),Nt(d),o.sub.tokens.length===0?o.sub=d:Lt(o.sub,d,0),s},be=(e,t)=>{let n=e.flatMap(e=>{switch(e.kind){case`LabelIf`:return be(e.unlabThen,t),be(e.unlabElse,t),[e];case`LabelEither`:return e.clauses.forEach(e=>be(e.unlabOr,t)),[e];case`With`:return be(e.Do,t),[e];case`While`:return be(e.unlabDo,t),[e];case`MacroCall`:return xe(e,t);default:return[e]}});e.splice(0,e.length,...n)},xe=(e,t)=>{let n=t.findLast(t=>t.name===e.name);if(n===void 0)throw new p(`Macro ${e.name} undefined,\n at ${Dt(e)}`);if(n.params.length!==e.args.length)throw new p(`Macro ${e.name} called with wrong number of arguments at \n ${Dt(e)}`);let r=n.body.map(t=>ve(t,e.args,n.params,e.line,e.col));return r.length>0&&(r[0].lbl=e.lbl),r},Se=e=>{e.forEach((t,n)=>{if(e.slice(n+1).some(e=>e.name===t.name))throw new p(`Multiple definitions of macro name \`${t.name}'`)})},Ce=e=>{if(e.length===0)return;let t=()=>{o.omitPC=!1,o.omitStutteringWhenDone=!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`||!Rt(r.test)||r.test.tokens[0][0].string!==`TRUE`)return t();r.labDo.length>0&&(o.omitPC=!1),r.unlabDo.some(e=>[`LabelIf`,`LabelEither`,`LabeledStmt`].includes(e.kind))&&(o.omitPC=!1)},we=()=>{let e=o.addedLabels.length>1?`Missing labels at the following locations:`:`Missing label at the following location:`;throw new p([e,...o.addedLabelsLocs].join(`
|
|
19
|
+
`))},Te=()=>{r.reportLabelsFlag?(e.log(o.addedLabels.length>1?`The following labels were added:`:`The following label was added:`),o.addedLabels.forEach((t,n)=>e.log(` ${t} at ${o.addedLabelsLocs[n]}`))):e.log(`Labels added.`)},Ee=e=>o.procedures.forEach(t=>{o.currentProcedure=t.name,be(t.body,e),t.body=_e(t.body)}),De=()=>{n&&(l()!==`algorithm`&&c("`--fair' not followed by `algorithm'"),r.fairAlgorithm=!0);let t=l();o.cSyntax=u(1)===`{`,o.pSyntax=!o.cSyntax,o.cSyntax&&g(`{`);let i=u(1)===`variable`||u(1)===`variables`?C():[],a={value:Mt()};u(1)===`define`&&(g(`define`),o.cSyntax&&h(`{`),a.value=f(!0),b(`define`),h(`;`));let s=[];for(;u(1)===`macro`;)s.push(ce(s));for(;u(1)===`procedure`;)o.procedures.push(le()),o.omitPC=!1;if(u(1)===`fair`&&(u(2)===`process`||u(2)===`+`&&u(3)===`process`)||u(1)===`process`){let e=[];for(;u(1)===`fair`||u(1)===`process`;){let t=u(1)===`fair`;t&&g(`fair`);let n=t&&u(1)===`+`;n&&g(`+`);let i=n||!t&&r.fairnessOption===`sf`?2:t||r.fairnessOption===`wf`?1:0;e.push({...ue(),fairness:i})}b(`algorithm`),Se(s);let n=e.map(e=>(be(e.body,s),e.body=_e(e.body),o.omitStutteringWhenDone=!0,Ce(e.body),o.omitStutteringWhenDone));return o.omitStutteringWhenDone=n.includes(!0),Ee(s),o.addedLabels.length>0&&(r.labelFlag||we(),Te()),o.gotoDoneUsed&&(o.omitPC=!1,o.omitStutteringWhenDone=!1),o.gotoUsed&&(o.omitPC=!1),{...B(),kind:`Multiprocess`,name:t,decls:i,defs:a.value,macros:s,prcds:o.procedures,procs:e}}r.inputVersionNumber===1500&&u(1)===`fair`&&(h(`fair`),u(1)===`+`&&h(`+`),r.fairnessOption=`wf`),n&&([``,`wf`,`wfNext`].includes(r.fairnessOption)||e.log(`Warning: Option \`${r.fairnessOption}' specified for --fair algorithm.`),r.fairnessOption=`wf`),y();let d=D();Se(s),be(d,s),Ee(s),o.cSyntax&&h(`}`),b(`algorithm`);let p=_e(d);return o.addedLabels.length>0&&(o.hasLabel&&!r.labelFlag&&we(),Te()),o.gotoUsed&&(o.omitPC=!1),o.gotoDoneUsed||Ce(p),o.gotoDoneUsed&&(o.omitPC=!1,o.omitStutteringWhenDone=!1),{...B(),kind:`Uniprocess`,name:t,decls:i,defs:a.value,macros:s,prcds:o.procedures,body:p}};try{return{ast:De(),omitPC:o.omitPC,omitStutteringWhenDone:o.omitStutteringWhenDone,hasDefaultInitialization:o.hasDefaultInitialization}}catch(e){if(!(e instanceof m))throw e;return c(`Unknown error at or before`)}},H={global:0,label:1,procedure:2,process:3,processVar:4,procedureVar:5,parameter:6},vn=[`Global variable`,`Label`,`Procedure`,`Process`,`Process variable`,`Procedure variable`,`Parameter`],yn=/* @__PURE__ */ new Set([H.global,H.processVar,H.procedureVar,H.parameter]),bn=(e,t,n,r)=>e.symbols.find(e=>e.id===n&&e.context===r&&e.type===t),xn=(e,t,n)=>e.symbols.find(e=>e.id===t&&e.context===n),Sn=(e,t)=>{let n=e.procedures.findIndex(e=>e.name===t);return n===-1?e.procedures.length:n},Cn=(e,t)=>{let n=e.processes.findIndex(e=>e.name===t);return n===-1?e.processes.length:n},wn=(e,t,n,r,i,a,o)=>!(t===H.procedureVar||t===H.processVar||t===H.parameter?bn(e,H.global,n,``)!==void 0||xn(e,n,r)!==void 0:bn(e,t,n,r)!==void 0)&&(e.symbols.push({type:t,id:n,context:r,contextType:i,line:a,col:o,useThis:n}),!0),Tn=(e,t,n,r)=>bn(e,t,n,r)?.useThis??n,En=(e,t,n)=>{let r=xn(e,t,n);return r===void 0?t:yn.has(r.type)?r.useThis:t},Dn=e=>{let t={symbols:[],procedures:[],processes:[],disambiguateReport:[],errorReport:``,initialPC:void 0},n=(e,n,i)=>{wn(t,H.label,e.label,n,i,e.line,e.col)||(t.errorReport+=`\nLabel ${e.label} redefined at line ${e.line}, column ${e.col}`),e.stmts.forEach(e=>r(e,n,i))},r=(e,t,i)=>{let a=e=>e.forEach(e=>r(e,t,i)),o=e=>e.forEach(e=>n(e,t,i));switch(e.kind){case`While`:a(e.unlabDo),o(e.labDo);return;case`If`:a(e.Then),a(e.Else);return;case`With`:a(e.Do);return;case`LabelIf`:a(e.unlabThen),o(e.labThen),a(e.unlabElse),o(e.labElse);return;case`Either`:e.ors.forEach(a);return;case`LabelEither`:e.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 s(`Unexpected AST type ${e.kind}`)}},i=(e,n,r=`process`,i=n===``?H.global:H.processVar)=>{wn(t,i,e.var,n,r,e.line,e.col)||(t.errorReport+=`\n${vn[i]} ${e.var} redefined at line ${e.line}, column ${e.col}`)};if(wn(t,H.global,`pc`,``,``,0,0),e.prcds.length>0&&wn(t,H.global,`stack`,``,``,0,0),e.decls.forEach(e=>i(e,``)),e.prcds.forEach(e=>{let r=Sn(t,e.name)<t.procedures.length;r&&(t.errorReport+=`\nProcedure ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.procedures.push({name:e.name,params:e.params,decls:e.decls,initialPC:e.body.length===0?void 0:Ot(e.body[0]).label}),wn(t,H.procedure,e.name,``,`procedure`,e.line,e.col),e.decls.forEach(t=>i(t,e.name,`procedure`,H.procedureVar)),e.params.forEach(t=>i(t,e.name,`procedure`,H.parameter)),e.body.forEach(t=>n(Ot(t),e.name,`procedure`))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>{let r=Cn(t,e.name)<t.processes.length;r&&(t.errorReport+=`\nProcess ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.processes.push({name:e.name,initialPC:e.body.length===0?void 0:Ot(e.body[0]).label}),wn(t,H.process,e.name,``,`process`,e.line,e.col),e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>n(Ot(t),e.name,`process`))}),e.kind===`Uniprocess`&&(e.body.length>0&&(t.initialPC=Ot(e.body[0]).label),e.body.forEach(e=>n(Ot(e),``,``))),t.errorReport.length>0)throw new p(t.errorReport);return t},On=e=>{let t=t=>e.symbols.filter(e=>e.useThis===t).length>1;for(let n=0;n<=7;n+=1)e.symbols.forEach(r=>{if(r.type!==n)return;r.useThis=r.id;for(let e=1;n>0&&t(r.useThis);e+=1)r.useThis+=e===1?`_`:r.context[e-2]??String(n);if(r.id===r.useThis)return;let i=r.context.length===0?``:` of ${r.contextType} ${r.context}`;e.disambiguateReport.push(`\\* ${vn[r.type]} ${r.id}${i} at line ${r.line} col ${r.col} changed to ${r.useThis}`)})},kn=e=>{let t=e.symbols.filter(e=>e.id===`defaultInitValue`).map(e=>`${vn[e.type]} name`);if(t.length>0)throw new p(`Cannot use \`defaultInitValue' as ${t.join(` or `)}`)},An=(e,t,n)=>{let r=(e,n)=>{let r=[],i=[];e.tokens.forEach(e=>e.forEach(e=>{if(e.type!==Ct.ident)return;let a=En(t,e.string,n);r.includes(e.string)||a===e.string||(r.push(e.string),i.push(Pt([[Nn(a)]])))})),i.length>0&&Ut(e,i,r,!1)},i=(e,n)=>{e.var=En(t,e.var,n),r(e.val,n)},a=(e,n)=>e.forEach((r,i)=>{e[i]=Tn(t,H.label,r,n)}),o=(e,n)=>e===void 0?void 0:Tn(t,H.procedure,e,n),c=(e,n)=>{e.label=Tn(t,H.label,e.label,n),e.stmts.forEach(e=>l(e,n))},l=(e,n)=>{let i=e=>e.forEach(e=>l(e,n)),a=e=>e.forEach(e=>c(e,n)),u=e=>e.forEach(e=>r(e,n));switch(e.kind){case`LabeledStmt`:c(e,n);return;case`While`:i(e.unlabDo),a(e.labDo),r(e.test,n);return;case`Assign`:e.ass.forEach(e=>{e.lhs.var=En(t,e.lhs.var,n),r(e.lhs.sub,n),r(e.rhs,n)});return;case`If`:i(e.Then),i(e.Else),r(e.test,n);return;case`With`:r(e.exp,n),i(e.Do);return;case`When`:case`PrintS`:case`Assert`:r(e.exp,n);return;case`Skip`:return;case`LabelIf`:r(e.test,n),i(e.unlabThen),a(e.labThen),i(e.unlabElse),a(e.labElse);return;case`Call`:e.returnTo=Tn(t,H.procedure,e.returnTo,n),e.to=Tn(t,H.procedure,e.to,n),u(e.args);return;case`Return`:e.from=o(e.from,n);return;case`CallReturn`:e.from=o(e.from,n),e.to=Tn(t,H.procedure,e.to,n),u(e.args);return;case`CallGoto`:e.after=Tn(t,H.procedure,e.after,n),e.to=Tn(t,H.procedure,e.to,n),u(e.args);return;case`Goto`:if(bn(t,H.label,e.to,n)===void 0&&e.to!==`Done`)throw new p(`goto to non-existent label \`${e.to}' at line ${e.line}, column ${e.col}`);e.to=Tn(t,H.label,e.to,n);return;case`Either`:e.ors.forEach(i);return;case`LabelEither`:e.clauses.forEach(e=>{i(e.unlabOr),a(e.labOr)});return;default:throw new s(`Unexpected AST type${e.kind}`)}},u=e=>{e.decls.forEach(t=>i(t,e.name)),e.params.forEach(t=>i(t,e.name)),e.body.forEach(t=>c(Ot(t),e.name));let n=kt(t.procedures,Sn(t,e.name));a(e.plusLabels,e.name),a(e.minusLabels,e.name),n.initialPC!==void 0&&(n.initialPC=Tn(t,H.label,n.initialPC,e.name)),e.name=Tn(t,H.procedure,e.name,``),n.name=e.name},d=e=>{e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>c(Ot(t),e.name));let n=kt(t.processes,Cn(t,e.name));a(e.plusLabels,e.name),a(e.minusLabels,e.name),n.initialPC!==void 0&&(n.initialPC=Tn(t,H.label,n.initialPC,e.name)),e.name=Tn(t,H.process,e.name,``),n.name=e.name};e.decls.forEach(e=>i(e,``)),e.kind===`Multiprocess`&&((e,t)=>{e.forEach(u);let r=e.map(e=>e.name),i=e.map(e=>r.map(t=>e.proceduresCalled.includes(t)));r.forEach((e,t)=>i.forEach(e=>e.forEach((n,r)=>{e[r]=n||e[t]&&i[t][r]}))),e.forEach((e,t)=>{e.proceduresCalled=r.filter((e,n)=>i[t][n])});for(let e of t){d(e);let t=e.proceduresCalled;for(let e=0;e<t.length;e+=1){let a=r.indexOf(t[e]);if(a===-1){n(`\nUnrecoverable error:\n -- Could not find procedure name \`${t[e]}'.\n`);return}r.forEach((e,n)=>{i[a][n]&&!t.includes(e)&&t.push(e)})}}})(e.prcds,e.procs),e.kind===`Uniprocess`&&(e.prcds.forEach(u),e.body.forEach(e=>c(Ot(e),``))),t.initialPC!==void 0&&(t.initialPC=Tn(t,H.label,t.initialPC,``))},jn=e=>At(e,0,Ct.string),Mn=e=>At(e,0,Ct.added),U=e=>At(e,0,Ct.builtin),Nn=e=>At(e,0,Ct.ident),Pn=(e,t)=>{let n=[];return e.forEach(e=>{let r=n.at(-1),i=r===void 0?0:r.column+jt(r)+t;n.push(At(e.string,i,e.type))}),Pt([n])},Fn=e=>e.tokens.forEach((t,n)=>{let r={column:n===0||n===e.tokens.length-1?1:6};t.forEach(e=>{if(e.column=r.column,r.column+=jt(e),e.type===Ct.builtin)switch(e.string){case`|->`:case`↦`:e.column=Math.max(16,e.column+1),r.column=e.column+5;return;case`[`:case`<<`:r.column+=1;return;case`]`:case`>>`:e.column+=1,r.column+=1;return;case`\\o`:e.column+=1,r.column+=2}})}),In=(e,t,n,r=0,i=0)=>({...B(),kind:`SingleAssign`,line:r,col:i,lhs:{...B(),kind:`Lhs`,var:e,sub:t},rhs:n}),Ln=(e,t=0,n=0)=>({...B(),kind:`Assign`,line:t,col:n,ass:e}),Rn=(e,t,n=0,r=0)=>Ln([In(e,Pt([]),t,n,r)],n,r),zn=e=>{if(e.tokens.length>1)return!1;let t=kt(e.tokens,0);return t.length===1?t[0].string===`TRUE`:t.length===3&&t[0].string===`(`&&t[1].string===`TRUE`&&t[2].string===`)`},Bn=e=>({...B(),kind:`When`,exp:Pn([Mn(`pc`),U(`=`),jn(e)],1)}),Vn=e=>Rn(`pc`,Pt([[jn(e??`null`)]])),Hn=e=>[Nn(`Head`),U(`(`),Mn(`stack`),U(`)`),U(`.`),Nn(e)],Un=()=>[Nn(`Tail`),U(`(`),Mn(`stack`),U(`)`)],Wn=e=>Pt([Hn(e)]),Gn=(e,t,n,r)=>{let i=[[U(`<<`),U(`[`),Nn(`procedure`),U(`|->`),jn(e),U(`,`)],[Nn(`pc`),U(`|->`),...t]];n.forEach(e=>{i[i.length-1].push(U(`,`)),i.push([Nn(e.var),U(`|->`),Nn(e.var)])}),i[i.length-1].push(U(`]`),U(`>>`)),i.push(r);let a=Mt(i);return Fn(a),Nt(a),a},Kn=(e,t,n)=>{if(t.params.length!==n.args.length)throw new p(`Procedure ${n.to} called with wrong number of arguments`,n);return t.params.forEach((t,r)=>e.ass.push(In(t.var,Pt([]),n.args[r],n.line,n.col))),[e,...t.decls.map(e=>Rn(e.var,e.val,n.line,n.col)),Vn(t.initialPC)]},qn=(e,t,n)=>{let r={procedure:void 0},i=(e,n)=>{let r=Sn(t,e.to);if(r===t.procedures.length)throw new p(`Call of non-existent procedure ${e.to}`,e);let i=t.procedures[r],a=Gn(e.to,[jn(n)],[...i.decls,...i.params],[U(`\\o`),Mn(`stack`)]);return Kn(Rn(`stack`,a,e.line,e.col),i,e)},a=e=>{e.from??=r.procedure;let n=e.from;if(n===void 0)throw new p("`return' statement not in procedure",e);let i=Sn(t,n);if(i>=t.procedures.length)throw new p(`Error in procedure (perhaps name used elsewhere)`,e);let a=t.procedures[i],o=(t,n)=>Ln([In(t,Mt(),n,e.line,e.col)],e.line,e.col);return[o(`pc`,Wn(`pc`)),...a.decls.map(e=>o(e.var,Wn(e.var))),...a.params.map(e=>o(e.var,Wn(e.var))),o(`stack`,Pt([Un()]))]},o=e=>{let n=e.from;if(n===void 0)throw new p(`\`return' statement following \`call' at ${Dt(e)} not in a procedure`);let r=kt(t.procedures,Sn(t,n)),i=Sn(t,e.to);if(i===t.procedures.length)throw new p(`Call of non-existent procedure ${e.to}`,e);let a=t.procedures[i],o=Ln([],e.line,e.col);if(n!==e.to){r.decls.forEach(t=>o.ass.push(In(t.var,Mt(),Wn(t.var),e.line,e.col)));let t=Gn(e.to,Hn(`pc`),[...a.decls,...a.params],[U(`\\o`),...Un()]);o.ass.push(In(`stack`,Pt([]),t,e.line,e.col))}return Kn(o,a,e)},s=(e,t)=>{if(e.length===0)return{stmts:[],labeledStmts:[],needsGoto:!n};let r={stmts:e,labeledStmts:[],needsGoto:!1},c=e[e.length-1];switch(c.kind){case`LabelIf`:case`LabelEither`:{let n=c.kind===`LabelIf`?f(c,t):m(c,t);e.pop(),e.push(n.stmt),r.labeledStmts=n.labeledStmts;break}case`Goto`:e.pop(),e.push(Vn(c.to));break;case`Call`:e.pop(),e.push(...i(c,t));break;case`Return`:e.pop(),e.push(...a(c));break;case`CallReturn`:e.pop(),e.push(...o(c));break;case`CallGoto`:e.pop(),e.push(...i({...B(),kind:`Call`,returnTo:``,to:c.to,args:c.args,line:c.line,col:c.col},c.after));break;case`If`:{let e=s(c.Then,t),i=s(c.Else,t);r.labeledStmts.push(...e.labeledStmts,...i.labeledStmts),c.Then=e.stmts,c.Else=i.stmts,n||(r.needsGoto=e.needsGoto&&i.needsGoto,r.needsGoto||(e.needsGoto&&c.Then.push(Vn(t)),i.needsGoto&&c.Else.push(Vn(t))));break}case`Either`:{let e=c.ors.map((e,n)=>{let i=s(e,t);return c.ors[n]=i.stmts,r.labeledStmts.push(...i.labeledStmts),i});r.needsGoto=e.every(e=>e.needsGoto),!n&&!r.needsGoto&&e.forEach((e,n)=>{e.needsGoto&&c.ors[n].push(Vn(t))});break}case`With`:{let e=s(c.Do,t);c.Do=e.stmts,r.labeledStmts.push(...e.labeledStmts),r.needsGoto=e.needsGoto;break}default:r.needsGoto=!0}return n&&(r.needsGoto=!1),r},c=(e,t)=>{let n=s(e,t);return n.needsGoto&&n.stmts.push(Vn(t)),n},l=(e,t)=>{let r=e.stmts.at(0);if(r?.kind===`While`)return d(e,r,t);let i=c([...e.stmts],t),a=[];return n||(i.stmts.unshift(Bn(e.label)),a.push({...B(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:i.stmts})),a.push(...i.labeledStmts),a},u=(e,t)=>e.flatMap((n,r)=>l(n,r<e.length-1?e[r+1].label:t)),d=(e,t,r)=>{let i=t.labDo.length===0?e.label:t.labDo[0].label,a=c([...t.unlabDo],i),o=c(e.stmts.slice(1),r),s=zn(t.test),l=s?a.stmts:[{...B(),kind:`If`,test:t.test,Then:a.stmts,Else:o.stmts}];return[{...B(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:[...n?[]:[Bn(e.label)],...l]},...u(t.labDo,e.label),...a.labeledStmts,...s?[]:o.labeledStmts]},f=(e,t)=>{let n=c(e.unlabThen,e.labThen.length===0?t:e.labThen[0].label),r=c(e.unlabElse,e.labElse.length===0?t:e.labElse[0].label),i=u(e.labThen,t);return i.push(...u(e.labElse,t)),i.push(...n.labeledStmts,...r.labeledStmts),{stmt:{...B(),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=c(e.unlabOr,e.labOr.length>0?e.labOr[0].label:t);n.push(i.stmts),r.push(...i.labeledStmts),r.push(...u(e.labOr,t))}),{stmt:{...B(),kind:`Either`,col:e.col,line:e.line,ors:n},labeledStmts:r}},h=(e,t)=>u(e.map(Ot),t),g=e=>{r.procedure=e.name;let n=h(e.body,Tn(t,H.label,`Error`,``));return r.procedure=void 0,{...B(),kind:`Procedure`,col:e.col,line:e.line,name:e.name,minusLabels:[],plusLabels:[],proceduresCalled:[],params:e.params,decls:e.decls,body:n}},_=e=>({...B(),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=e.prcds.map(g);return e.kind===`Uniprocess`?{...B(),kind:`Uniprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:v,body:h(e.body,`Done`)}:{...B(),kind:`Multiprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:v,procs:e.procs.map(_)}},Jn=(e,t)=>{let n=t?[]:[`pc`];if(n.push(...e.decls.map(e=>e.var)),e.prcds.length>0&&n.push(`stack`),e.prcds.forEach(e=>{n.push(...e.params.map(e=>e.var)),n.push(...e.decls.map(e=>e.var))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>n.push(...e.decls.map(e=>e.var))),n.length===0)throw new p(`The algorithm has no variables.`);let r=(e,t)=>{let r=n.indexOf(t);return r===-1?0:(e[r]+=1,e[r])},i=(e,t)=>t.forEach((t,n)=>{e[n]=Math.max(e[n],t)}),a=e=>[...e].sort((e,t)=>e.lhs.var<t.lhs.var?-1:+(e.lhs.var>t.lhs.var)),o=(e,t)=>{let o=[...t];e.ass=a(e.ass),new Set(e.ass.map(e=>e.lhs.var)).forEach(t=>{let i=e.ass.filter(e=>e.lhs.var===t);if(!n.includes(t))throw new p(`Assignment to undeclared variable ${t}`,i[0]);let a=i.some(e=>e.lhs.sub.tokens.length===0);if(r(o,t)>1||i.length>1&&a)throw new p(`Multiple assignment to ${t}`,e)}),i(t,o)},c=(e,t)=>{switch(e.kind){case`Assign`:o(e,t);return;case`If`:{let n=[...t],r=[...t];e.Then.forEach(e=>c(e,n)),e.Else.forEach(e=>c(e,r)),i(t,n),i(t,r);return}case`Either`:{let n=[...t];e.ors.forEach(e=>{let r=[...t];e.forEach(e=>c(e,r)),i(n,r)}),i(t,n);return}case`With`:e.Do.forEach(e=>c(e,t));return;case`When`:case`PrintS`:case`Assert`:case`Skip`:return;default:throw new s(`Unexpected AST type ${e.kind}`)}},l=e=>e.forEach(e=>{let t=n.map(()=>0);Ot(e).stmts.forEach(e=>c(e,t))});e.prcds.forEach(e=>l(e.body)),(e.kind===`Uniprocess`?[e.body]:e.procs.map(e=>e.body)).forEach(l)},Yn=(e,t,n,r)=>{let i=Dn(e);On(i),i.disambiguateReport.length>0&&r(`Warning: symbols were renamed.`),An(e,i,r),Jn(qn(e,i,t),t),n&&kn(i)},Xn=`[ \\t\\n\\x0B\\f\\r]`,Zn=RegExp(`\\\\\\* BEGIN TRANSLATION${Xn}+\\(${Xn}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${Xn}*(=${Xn}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${Xn}*STRING)${Xn}*\\/\\\\${Xn}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${Xn}*(=${Xn}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${Xn}*STRING)${Xn}*\\)`),Qn=e=>process.getBuiltinModule(`node:zlib`).crc32(Buffer.from(e,`utf8`)).toString(16),$n=(e,t)=>e.log(`\nUnrecoverable error:\n -- ${t}.\n`),er=(e,t)=>$n(e,t.node===void 0||t.node.line===0?t.message:`${t.message}\n at ${Dt(t.node)}`),tr=e=>e.map(e=>`${Array.from(e).reduce((e,t)=>t===` `?e+` `.repeat(8-e.length%8):e+t,``)} `),nr=(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},rr=(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``},ir=(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},ar=e=>/^[\p{L}\p{Nd}_]$/u.test(e),or=(e,t,n)=>{for(;t.line<e.length;){let r=rr(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=ir(r,e,` `),!0}t.column=ir(r,t.column,` `)}return!1},sr=(e,t)=>$n(e,`Command-line error: ${t}`),cr=(e,t)=>{let n=e.params,r={isFirst:!0,isExplicitNof:!1},i=t=>(r.isFirst&&=(n.fairnessOption=``,!1),n.fairnessOption===``?(n.fairnessOption=t,!0):(sr(e,`Can only have one of -wf, -sf, -wfNext, and -nof options`),!1));for(let a=0;a<t.length;a++){let o=t[a],s=t[a+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){sr(e,`
|
|
20
|
+
Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){sr(e,`Specification name must follow \`-${t?`myspec`:`spec`}' option`);return}n.specFile=s,a+=1;continue}case`-termination`:case`termination`:n.checkTermination=!0;continue;case`-noold`:n.noOld=!0;continue;case`-nocfg`:n.nocfg=!0;continue;case`-noDoneDisjunct`:case`noDoneDisjunct`:n.noDoneDisjunct=!0;continue;case`-wf`:case`wf`:case`-sf`:case`sf`:case`-wfNext`:case`wfNext`:case`-nof`:case`nof`:if(!i(o.replace(/^-/,``)))return;o.endsWith(`nof`)&&(r.isExplicitNof=!0);continue;case`-label`:case`label`:n.labelFlag=!0;continue;case`-labelRoot`:case`labelRoot`:if(s===void 0){sr(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){sr(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,a+=1;continue;case`-version`:case`version`:{if(s===void 0){sr(e,"Version number must follow `-version' option");return}let t=Tt(s);if(t<0||t>1903){$n(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),sr(e,`Bad version number`);return}n.inputVersionNumber=t,a+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){sr(e,"Integer value at least 60 must follow `-lineWidth' option");return}a+=1;continue;default:sr(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!r.isExplicitNof&&(n.fairnessOption=`wf`)},lr=(e,t,n)=>{if(rr(t,n),n.column+=7,!rr(t,n).slice(n.column).startsWith(`(`)){$n(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=rr(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=ir(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?$n(e,`No closing ')' found in options statement`):cr(e,r)},ur=(e,t,n)=>{let r={depth:0,isDone:!1,isInString:!1};for(let i=t;!r.isDone&&i<e.length;i++){let a=e[i],o=i===t?n:0,s=[a.slice(0,o)];r.isInString=!1;for(let e=o;!r.isDone&&e<a.length;e++){let t=a[e],n=a.slice(e,e+2);if(n===`(*`&&!r.isInString)r.depth+=1,s.push(` `),e+=1;else if(n===`*)`&&!r.isInString&&r.depth===0)s.push(n),r.isDone=!0;else if(n===`*)`&&!r.isInString)--r.depth,s.push(` `),e+=1;else if(r.depth>0)s.push(` `);else if(r.isInString&&t===`\\`&&n.length===2)s.push(n),e+=1;else{if(!r.isInString&&n===`\\*`){s.push(` `);break}t===`"`&&(r.isInString=!r.isInString),s.push(t)}}if(r.isInString)return new p(`Unterminated string in line ${i+1}`);e[i]=s.join(``)}},dr=(e,t)=>{let n=10*2**Math.max(0,Math.ceil(Math.log2(t/10)));throw new m(`java.lang.ArrayIndexOutOfBoundsException: Index ${e} out of bounds for length ${n}`)},fr=(e,t,n)=>{if(!t.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let r=tr(t),i={line:0,column:0};for(;or(r,i,`PlusCal`);){let t=rr(r,i).slice(i.column),n=Array.from(t).findIndex(e=>!ar(e));if(t.startsWith(`options`)&&(n===-1?t.length:n)===7){e.params.optionsInFile=!0,lr(e,r,i);break}}let a={line:0,column:-1,isFound:!1,isFair:!1};for(;a.line<r.length;a.line++){let e=r[a.line];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){a.column=t+11,a.isFound=!0;break}if(n!==-1){a.column=n+6,a.isFound=!0,a.isFair=!0;break}}let o=/* @__PURE__ */ new Set,s=nr(r,0,`BEGIN`,`TRANSLATION`);s===-1&&o.add(`NO_TRANSLATION_EXISTS`);let c=nr(r,s+1,`END`,`TRANSLATION`);if(c===-1&&o.add(`NO_TRANSLATION_EXISTS`),s===-1&&c===-1)return o;if(!a.isFound)return o.add(`NO_PLUSCAL_EXISTS`),o;let l=ur(r,a.line,a.column);if(l!==void 0)return er(e,l),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let u={ast:void 0};try{let n=Jt(r,a.line,a.column,t.length,0),i=_n(e,n,a.isFair);u.ast=i.ast,Yn(i.ast,i.omitPC,i.hasDefaultInitialization,e.log)}catch(t){if(!(t instanceof p))throw t;er(e,t)}s===-1&&dr(-1,r.length);let d=Zn.exec(r[s]);if(d===null)return o.add(`NO_PCAL_CHECKSUMS_EXIST`),o;let f=d.groups?.pcal,h=a.isFair&&n!==`1.7.4`?`fair`:u.ast===void 0?void 0:qt(u.ast,e.params.inputVersionNumber,n);f!==void 0&&(h===void 0||f!==Qn(h))&&o.add(`PCAL_DIVERGENCE_EXISTS`);let g=d.groups?.tla;if(g!==void 0){if(c===-1)throw new m(`java.lang.IllegalArgumentException: fromIndex(${s+1}) > toIndex(-1)`);let e=t.slice(s+1,c).join(``);g!==Qn(e)&&o.add(`TLA_DIVERGENCE_EXISTS`)}return o.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):o},pr=[[`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]]],mr={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}),hr=e=>pr.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:mr,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}}),gr=(e,t)=>{let n=JSON.stringify(t);e.some(e=>JSON.stringify(e)===n)||e.push(t)},_r=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}`,vr=e=>e?.kind===`OpAppl`&&e.isAbsent===!0,yr=e=>{let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;return t},br=()=>({buckets:Array.from({length:11},()=>[]),count:0,threshold:8}),xr=(e,t)=>(e&2147483647)%t,Sr=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[xr(e.hash,t)].unshift(e));e.buckets=n,e.threshold=Math.floor(t*.75)},Cr=(e,t,n=t)=>e.buckets[xr(yr(n),e.buckets.length)].find(e=>e.key===t)?.value,wr=(e,t,n,r=t)=>{let i=yr(r),a=e.buckets[xr(i,e.buckets.length)].find(e=>e.key===t);a?a.value=n:(e.count>=e.threshold&&Sr(e),e.buckets[xr(i,e.buckets.length)].unshift({hash:i,key:t,value:n}),e.count++)},Tr=e=>e.buckets.toReversed().flatMap(e=>e.map(e=>e.value)),Er=`\0module `,G=()=>({table:br(),symbols:[]}),Dr=e=>e.kind===`Module`?Er+e.name:e.name,Or=(e,t)=>{wr(e.table,Dr(t),t,t.name),e.symbols.push(t)},kr=e=>e.kind===`ThmOrAssumpDef`?e.params.length:e.kind===`Module`?0:e.arity,Ar=(e,t)=>Cr(e.table,t),jr=(e,t)=>Cr(e.table,Er+t,t),Mr=e=>e.context.symbols.filter(e=>e.kind===`OpDef`&&e.defKind===`UserDefined`),Nr=(e,t)=>Tr(e.context.table).filter(e=>e.kind===`OpDecl`&&e.declKind===t).toReversed(),Pr=e=>e.context.symbols.filter(e=>e.kind===`ThmOrAssumpDef`),Fr=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),Ir=e=>{let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},Lr=e=>{switch(e.kind){case`Identifier`:return Ir(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=Ir(e.operator),n=e.argumentCounts??t.map((n,r)=>r===t.length-1?e.args.length:0),r={value:0};return t.map((t,i)=>{let a=e.args.slice(r.value,r.value+n[i]);return r.value+=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}}})}},Rr=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},zr=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,Br=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,Vr=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),Hr=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,Ur=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],Wr=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},Gr=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):Ar(u.letInContext,p)),f===void 0&&(p!==void 0&&(u.name=p,u.nameLocation=Wr(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: \`${zr(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=Wr(u.nameLocation,l(u.index)),u.name=p,Vr(f)&&t.length!==1)return e.addError(l(u.index),`Cannot take subexpression of \`${u.name}'.`);let h=kr(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 \`${zr(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
|
|
21
|
+
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(Br(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=Br(f.op,a.length);if(o){let e=Br(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=Br(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=Ur(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=Br(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(Br(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=Br(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
|
|
22
|
+
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`?kr(f.op):u.previousMode===`FindingOpName`&&Hr(f)?kr(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:kr(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`||p.kind===`Label`&&p.isAssumeProve)return e.addError(a,`ASSUME/PROVE used where an expression is required.`);if(p.kind===`ThmOrAssumpDef`&&p.body.kind===`OpAppl`){let t=Fr.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}.`)},Kr=/* @__PURE__ */ new Map([[`(`,`)`],[`[`,`]`],[`{`,`}`],[`<<`,`>>`]]),qr=(e,t)=>`${e}:${t}`,Jr=(e,t)=>{let n=oe(t).filter(e=>e.kind!==`End`).map(ce),r=[0,0];for(let e=0;e<t.length;e++)t[e]===`
|
|
23
|
+
`&&r.push(e+1);return{name:e,source:t,tokens:n,lineOffsets:r,tokenIndexes:new Map(n.map((e,t)=>[qr(e.line,e.column),t]))}},K=(e,t,n)=>e.tokens[t]!==void 0&&e.tokens[t].text===n&&e.tokens[t].kind!==`String`,Yr=(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},Xr=(e,t)=>e.tokenIndexes.get(qr(t.line,t.column))??Math.min(Yr(e,t,!1),e.tokens.length-1),Zr=(e,t)=>Math.max(Yr(e,t,!0)-1,0),Qr=(e,t)=>{let n=e.tokens[t].text,r=Kr.get(n);if(r===void 0)return t;let i=0;for(let a=t;a<e.tokens.length;a++)if(K(e,a,n))i++;else if(K(e,a,r)&&(i--,i===0))return a;return t},$r=(e,t)=>({start:Xr(e,t.start),end:Zr(e,t.end)}),q=(e,t)=>{let n=t.location.range;if(n)return $r(e,n);let r=Xr(e,t.location);return{start:r,end:Qr(e,r)}},ei=(e,t)=>{let n=t.start-1,r=t.end+1;return K(e,n,`(`)&&K(e,r,`)`)&&Qr(e,n)===r?ei(e,{start:n,end:r}):t},ti=(e,t)=>{let n=t.start-1,r=t.end+1;return K(e,n,`(`)&&Qr(e,n)===r&&(K(e,n-1,`(`)||K(e,n-1,`,`))?ti(e,{start:n,end:r}):t},J=(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}),ni=(e,t)=>J(e,{start:t,end:t}),ri=(e,t,n)=>{let r=0,i=e.lineOffsets[t];for(;i<e.source.length;){if(r=e.source[i]===` `?re(r):r+1,r>=n)return i;i++}return i},ii=(e,t)=>{let n=e.tokens[t],r=ri(e,n.line,n.column);return e.source.slice(r,ri(e,n.line,n.endColumn)+1)},ai=(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},oi=e=>{let n=Jr(``,e),r=n.tokens.reduce((e,t,r)=>{if(!ai(n,r))return e;let i=ri(n,t.line,t.column);return`${e.slice(0,i)} ${e.slice(i+2)}`},e);if(r!==e&&M(e)!==void 0)throw new t(`SANY rejects a []ASSUME or []PROVE outside an ASSUME/PROVE`);return r},si=(e,t)=>{let n=e.tokens[t-1],r=e.tokens[t],i=n===void 0?0:ri(e,n.line,n.endColumn)+1,a=e.source.slice(i,ri(e,r.line,r.column)),o=[],s=0;for(;s<a.length;)if(a.startsWith(`\\*`,s)){let e=a.indexOf(`
|
|
24
|
+
`,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},ci=(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},li=(e,t,n,r)=>{for(let i=t;i<=n;i++)if(K(e,i,r))return i;return-1},ui=new Map(ee.flatMap(([e,...t])=>t.map(t=>[t,e]))),di=e=>e.split(`!`).map(e=>ui.get(e)??(e===`~`?`\\lnot`:e)).join(`!`),fi={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}},pi=e=>/^[A-Za-z0-9_]+$/.test(e),mi=e=>e!==`!!`&&e.includes(`!`),hi=e=>e.contexts[e.contexts.length-1],gi=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=Ar(e.contexts[n],t);if(r)return r}},_i=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,vi=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,yi=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||bi(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&bi(n.module)}return!1},bi=e=>Nr(e,2).length===0&&Nr(e,3).length===0,xi=e=>[...e.kind===`Let`?e.instances??[]:[],...S(e).flatMap(xi)],Si=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:Si(e)):xi(e),Ci=(e,t)=>{let n=/* @__PURE__ */ new Set;for(let r of e.units)if(r.kind===`Module`&&n.add(r.module.name),r.kind===`Instance`&&r.instance.module===t)return n.has(t);return!1},wi=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`?xi(e.definition.body):e.kind===`Theorem`&&s?Si(e.theorem.statement):e.kind===`Assumption`&&s?xi(e.assumption.expression):[]).map(e=>e.module).filter(e=>l(e)&&!Ci(a,e)),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}},Ti=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),Ei=e=>{let t=e.kind===`Apply`?Lr(e):void 0;return Ti.has(e.kind)||t!==void 0&&Rr(t)},Di=/* @__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`]]),Oi=/* @__PURE__ */ new Set([`N_GeneralId`,`N_OpApplication`,`N_PrefixExpr`,`N_InfixExpr`,`N_PostfixExpr`,`N_FcnAppl`,`N_RecordComponent`]),ki=/* @__PURE__ */ new Set([`'`,`^+`,`^*`,`^#`]),Ai=(e,t)=>ki.has(t)?`N_GenPostfixOp`:e.kind===`Lambda`||t===`~`||t===`-.`?`N_GenNonExpPrefixOp`:`N_GenInfixOp`,ji=(e,n,r={})=>{let a=[],o=(e,t)=>gr(a,{location:e,text:t,isWarning:!1}),s=(e,t)=>gr(a,{location:e,text:t,isWarning:!0}),c={value:r.version===`1.7.4`?-1:0},l=()=>++c.value,u={id:0},f=(e,t)=>{let n=gi(e,t.name);if(n===t)return;if(n===void 0){Or(hi(e),t);return}let i=t.kind===`FormalParam`||_i(n)!==_i(t)||kr(n)!==kr(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(i&&r.version===`1.7.4`)?o(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):i?o(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${_r(n.location)}.`):yi(t,n)||s(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${_r(n.location)}.`)};r.version!==`1.7.4`&&hr(l);let p=hr(l);l();let m=new Map(p.map(e=>[e.name,e])),g=/* @__PURE__ */ new Map,v=/* @__PURE__ */ new Map,y=(e,n)=>{let a=e===r.rootFileName&&r.rootFilePath||`${e}.tla`,o=t=>new i(`Could not parse module ${e} from file ${a}`,e,t),s=r.version===`1.7.4`?_(n):void 0;if(s!==void 0)throw o(s);try{return ae(oi(n))}catch(e){throw e instanceof t?o(M(n)??`***Parse Error***\n${e.message}`):e}},b=(e,t,n)=>{let a=v.get(e);if(a)return a;if(t===void 0)throw new h(e,n,r.version!==`1.7.4`);r.onParse?.(e);let o=y(e,t);if(o.name!==e)throw new i(`File name '${e}' does not match the name '${o.name}' of the top level module it contains.`,void 0);let s={file:Jr(o.name,t),module:o};return v.set(e,s),s},x=[],S=/* @__PURE__ */ new Set,C=[],w=(e,t,r)=>{let a=C.indexOf(e);if(a!==-1)throw new i(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...C.slice(a),e].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(S.has(e))return;S.add(e),C.push(e);let o=k(e,b(e,t,r).module);[...o.extendees,...o.instancees].forEach(t=>w(t,n(t),e)),C.pop(),x.push(e)},ee=/* @__PURE__ */ new Set,T=(e,t)=>ee.has(`${e} ${t}`),E=(e,t,n)=>{let r=v.get(e);if(!r||n.has(e))return;n.add(e);let i=k(e,r.module),a=i[t].find(t=>!T(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=T(e,r)?E(r,t,n):void 0;if(i)return i}},D=t=>{b(t,e);let r=()=>E(t,`extendees`,/* @__PURE__ */ new Set)??E(t,`instancees`,/* @__PURE__ */ new Set);for(let e=r();e!==void 0;e=r())v.has(e.name)||b(e.name,n(e.name),e.namingModule),ee.add(`${e.importer} ${e.name}`)},O=r.rootFileName??y(``,e).name,k=(e,t)=>{let n=wi(t);return e!==O||r.rootExtendees===void 0||(n.extendees.splice(t.extends.length,0,...r.rootExtendees),r.rootExtendees.forEach(t=>{n.importers.has(t)||n.importers.set(t,e)})),n};D(O),w(O,e);let te=(e,n,i,a)=>{let c={curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSectionCount:0},p=[],h=[],_=[],v=[],y=/* @__PURE__ */ new WeakSet,b=()=>v.push({labels:/* @__PURE__ */ new Map,params:[]}),x=()=>v.pop()?.labels??/* @__PURE__ */ new Map,S={depth:0,isDeclared:[],goal:void 0,goalClause:0},C=/* @__PURE__ */ new WeakMap,w=/* @__PURE__ */ new WeakMap,ee=e=>{let t=e.kind===`AssumeProve`?C.get(e):void 0;t&&(t.isInProof=!1)},T=e=>J(n,q(n,e)),E=e=>e.range?$r(n,e.range):{start:Xr(n,e),end:Xr(n,e)},D={kind:`Module`,id:l(),name:e.name,location:J(n,E(e.location)),extendees:[],context:hi(a),topLevel:[],definitions:[],opDefsInRecursiveSection:[],isLevelChecked:!1,levelCorrect:!0,argLevelParams:/* @__PURE__ */ new Map,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map,records:[]};i&&i.definitions.push(D);let O=e=>{for(let t=a.contexts.length-1;t>=0;t--){let n=jr(a.contexts[t],e);if(n?.kind===`Module`)return n}return g.get(e)},k=e=>{let n=O(e);if(n===void 0)throw new t(`Could not find module ${e}`);return n},A=(e,t)=>{a.contexts.push(e);let n=t();return a.contexts.pop(),n},j=(e,t,n,r)=>{let i={...W(l()),kind:`FormalParam`,name:e,arity:t,location:n};return r&&f(a,i),i},ne=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}),re=e=>{e.letInLevel=c.curLevel,c.unresolvedSum>0&&(e.recursiveSection=c.recursiveSectionCount,e.inRecursiveSection=c.unresolvedCount[c.curLevel]>0,D.opDefsInRecursiveSection.push(e))},ie=(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}),M=()=>({...ie(ae(`$Nop`),[],mr,{},u.id),isNull:!0}),ae=e=>{let t=m.get(e);if(!t)throw new d(`SANY has no builtin operator ${e}`);return t},N=(e,t,n,r={})=>ie(ae(e),t,n,r),oe=(e,t)=>({...W(l()),kind:`String`,value:e,location:t}),se=(e,t)=>({...W(l()),kind:`OpArg`,op:e,location:t}),ce=(e,n)=>{let r=gi(a,di(e));if(r===void 0||r.kind===`Module`)throw new t(`Unknown operator: \`${e}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},le=(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`&&kr(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.`)},ue=Gr({version:r.version,resolveSymbol:e=>gi(a,e),resolveSynonym:di,generateExpression:e=>F(e),generateArgument:(e,t,n,r)=>be(e,t,n,r),createOpAppl:(e,t,n)=>{let r=ie(e,t,n);return le(e,t,n),r},createOpArg:se,createFormalParam:(e,t,n)=>j(e,t,n,!1),createLambda:(e,t,r)=>ne({name:`LAMBDA`,params:e,body:t,location:r,preComments:si(n,Xr(n,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>He(`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:ae,addError:(e,t)=>(o(e,t),M()),isOutOfLabelScope:e=>{let t=w.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=C.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}}),de=(e,t)=>{let r={value:t.start};return e.map(e=>{let i=e.op===`Name`?e.name:e.op===`Null`?`(`:String(e.op),a=li(n,r.value,t.end,i);if(a===-1)return e;if(e.op===`Null`){let t=Qr(n,a);return r.value=t+1,{...e,location:J(n,{start:a,end:t})}}r.value=a+1;let o=ni(n,a);if(e.args===void 0||!K(n,a+1,`(`))return{...e,location:o};let s=Qr(n,a+1);return r.value=s+1,{...e,location:o,argsLocation:J(n,{start:a+1,end:s})}})},fe=(e,r,i,a)=>{let o=Lr(e);if(o===void 0)throw new t(`Expected a name, found ${e.kind}`);return ue(de(o,q(n,e)),r,i,a,T(e))},pe=e=>{let n=fe(e,0,!1,!1);if(n.kind!==`OpAppl`)throw new t(`Expected an expression`);return n},me=e=>{if(e.kind!==`OpAppl`)return;let t=p.find(t=>t.name===e.operator.name);t&&(t.node.operator=ae(`$RecursiveFcnSpec`))},he=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},[]),ge=(e,t)=>I(e,t,he(e).map(e=>F(e[0].set))),P=(e,t)=>{let n=v.at(-1);n?.params.push(e);let r=F(t);return n?.params.pop(),r},_e=e=>{let t=q(n,e),r=ci(n,t.start,t.end,e.params);return A(G(),()=>{let i=e.params.map((e,t)=>j(e,0,ni(n,r[t]),!0)),a=P(i,e.body);return ne({name:`LAMBDA`,params:i,body:a,location:J(n,t),preComments:si(n,t.start)})})},ve=e=>e.kind===`OperatorReference`?e.operator:e.kind===`Lambda`&&e.body.kind===`Apply`?e.body.operator:n.tokens[Xr(n,e.location)].text,ye=(e,n)=>{let r=T(e);if(e.kind===`Lambda`)return e.location.range===void 0?se(ce(ve(e),r),r):se(_e(e),r);if(!Ei(e))return o(r,`Arity ${n.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${n.name}'.`),M();if(e.kind===`OperatorReference`)return se(ce(e.operator,r),r);let i=fe(e,n.arity,!1,!1);if(i.kind===`OpArg`||i.kind===`OpAppl`&&i.isNull===!0)return i;throw new t(`Expected an operator argument at line ${r.beginLine}, column ${r.beginColumn}`)},be=(e,r,i,s)=>{let c=e.kind===`OpDef`&&(e.defKind===`UserDefined`||e.defKind===`ModuleInstance`)?e.params?.[r]?.arity??0:0;if(c===0)return F(i);let l=q(n,i),u=J(n,l),d=`${r+1} (counting from 1)`,f=ti(n,l);if(f!==l||!Ei(i))return o(J(n,f),`An expression appears as argument number ${d} to operator '${e.name}', in a position an operator is required.`),M();if(i.kind===`Identifier`||i.kind===`Subexpression`||i.kind===`Apply`){let e=fe(i,c,!1,!1);if(e.kind===`OpArg`||e.kind===`OpAppl`)return e;throw new t(`Expected an operator argument at ${_r(u)}`)}if(i.kind===`Lambda`&&i.location.range!==void 0){let t=_e(i),n=kr(t);return n===c?se(t,u):(o(s,`Lambda expression with arity ${n} used as argument ${r+1} of operator \`${e.name}', \nbut an operator of arity ${c} is required.`),M())}let p=ve(i),m=gi(a,di(p));if(m===void 0)return o(u,`Could not find declaration or definition of symbol '${p}'.`),M();let h=kr(m);return h===c?se(m,u):(o(s,`Operator with incorrect arity passed as argument. \nOperator '${m.name}' of arity ${h} is argument number ${d} to operator \`${_r(e.location)}', \nbut an operator of arity ${c} was expected.`),M())},xe=e=>{let t=T(e);if(e.isBulleted)return N(e.kind===`And`?`$ConjList`:`$DisjList`,e.operands.map(F),t);let r=q(n,e),i=e.kind===`And`?`\\land`:`\\lor`,[a,...o]=e.operands;return o.reduce((e,t,a)=>{let s=ei(n,q(n,t)),c=a===o.length-1?r.end:s.end;return N(i,[e,F(t)],J(n,{start:r.start,end:c}))},F(a))},Se=e=>{let t=q(n,e),r=e.arms.map((r,i)=>{let a=ei(n,q(n,r.condition)),o=i===e.arms.length-1&&e.other===void 0,s=ei(n,q(n,r.body)),c=[F(r.condition),F(r.body)];return N(`$Pair`,c,J(n,{start:a.start,end:o?t.end:s.end}))}),i=e.other;if(i){let e=ei(n,q(n,i)),a=Ce(e.start,`OTHER`);r.push(N(`$Pair`,[void 0,F(i)],J(n,{start:a,end:t.end})))}return N(`$Case`,r,J(n,t))},Ce=(e,t)=>{for(let r=e;r>=0;r--)if(K(n,r,t))return r;return e},we=e=>{let t=q(n,e),r=J(n,t),i=[F(e.function)],a=N(`$Except`,i,r),o=q(n,e.function),s={value:li(n,o.end+1,t.end,`EXCEPT`)+1};return e.updates.forEach(e=>{let r=li(n,s.value,t.end,`!`),o=ei(n,q(n,e.value)),c=J(n,{start:r,end:o.end}),l={value:r+1},u=e.path.map(e=>{if(e.kind===`Field`){let t=Te(l.value,e.name);return l.value=t+1,oe(e.name,ni(n,t))}let r=li(n,l.value,t.end,`[`),i=Qr(n,r);return l.value=i+1,e.args.length===1?F(e.args[0]):N(`$Tuple`,e.args.map(F),J(n,{start:r,end:i}))}),d=N(`$Seq`,u,c),f=N(`$Pair`,[d],c);_.push(f),h.push(a),f.operands.push(F(e.value)),_.pop(),h.pop(),i.push(f),s.value=o.end+1}),a},Te=(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},Ee=(e,t)=>{let r=q(n,t),i={value:r.start+1},a=t.fields.map((e,r)=>{let a=Te(i.value,e.name),s=ei(n,q(n,e.value));return i.value=s.end+1,t.fields.slice(0,r).some(t=>t.name===e.name)&&o(ni(n,a),`Non-unique fields in constructor.`),N(`$Pair`,[oe(e.name,ni(n,a)),F(e.value)],J(n,{start:a,end:s.end}))}),s=N(e,a,J(n,r));return D.records.push(s),s},De=e=>({line:n.tokens[e].line,column:n.tokens[e].column}),Oe=e=>{let t=[],r=e;for(;n.tokens[r]?.kind===`Identifier`;){let e=K(n,r+1,`(`)?Qr(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:{...De(r),range:{module:n.name,start:De(r),end:De(e)}}}),!K(n,e+1,`,`))break;r=e+2}return t},ke=e=>{let t=[...e.definitions.map(e=>({unit:{kind:`Definition`,definition:e},span:L(e)})),...(e.instances??[]).map(e=>({unit:{kind:`Instance`,instance:e},span:L(e)}))],r=q(n,e).start,i=ei(n,q(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);K(n,e,`RECURSIVE`)&&!r&&a.push({unit:{kind:`Recursive`,declarations:Oe(e+1)},span:{start:e,end:e}})}return[...t,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},Ae=e=>{let t=G();return A(t,()=>{c.curLevel++,c.unresolvedCount[c.curLevel]=0;let n=[],r=[];ke(e).forEach(e=>{e.kind===`Recursive`?ze(e.declarations):e.kind===`Instance`?Ue(e.instance,n,r):e.definition.kind===`Function`?Le(e.definition,n):Fe(e.definition,n)}),Be(),c.curLevel=Math.max(c.curLevel-1,0);let i=F(e.body);return{...W(l()),kind:`LetIn`,opDefs:n,instances:r,body:i,context:t,location:T(e)}})},je=e=>{let t=q(n,e),r=J(n,t);return A(G(),()=>{let i=e.pattern,a=i.kind===`Name`?[i.name]:i.names;if(e.set===void 0){let o=ci(n,t.start,t.end,a),s=a.map((e,r)=>j(e,0,ni(n,i.kind===`Name`?t.start:o[r]),!0)),c=P(s,e.body);return N(`$UnboundedChoose`,[c],r,{unbounded:s})}let o=F(e.set),s=q(n,e.set),c=ci(n,t.start,s.start,a),l=a.map((e,t)=>j(e,0,ni(n,c[t]),!0)),u=P(l,e.body);return N(`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},Me=e=>{if(pi(e.operator)||mi(e.operator)||e.args.length>2||gi(a,di(e.operator))!==void 0)return;let t=q(n,e);if(n.tokens[t.start].text===e.operator&&K(n,t.start+1,`(`))return;let r=ei(n,q(n,e.args[0])),i=e.args.length===1&&r.start!==t.start,o=i?t.start:r.end+1,s=ii(n,o);return{index:o,name:i&&s===`-`?`-.`:s,fixity:i?`prefix`:e.args.length===2?`infix`:`postfix`}},F=e=>{let t=T(e);switch(e.kind){case`Number`:return{...W(l()),kind:`Numeral`,value:Mi(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 oe(e.value,t);case`Identifier`:{let t=pe(e);return me(t),t}case`Apply`:{let r=Me(e);if(r!==void 0)return o(ni(n,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),o(t,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...M(),isAbsent:!0};let i=pe(e);return(mi(e.operator)||pi(e.operator))&&me(i),i}case`Bracket`:return o(ni(n,q(n,e).start),"Unsupported expression type `['."),{...M(),isAbsent:!0};case`OperatorReference`:case`Lambda`:{let r=n.tokens[q(n,e).start].text;return o(t,r===`LAMBDA`?`LAMBDA expression used where an expression is required.`:`Unsupported expression type \`${Ai(e,r)}'.`),{...M(),isAbsent:!0}}case`And`:case`Or`:return xe(e);case`Prime`:return N(`'`,[F(e.expression)],t);case`Unchanged`:return N(`UNCHANGED`,[F(e.expression)],t);case`Enabled`:return N(`ENABLED`,[F(e.expression)],t);case`Always`:return N(`[]`,[F(e.expression)],t);case`Eventually`:return N(`<>`,[F(e.expression)],t);case`If`:return N(`$IfThenElse`,[F(e.condition),F(e.consequent),F(e.alternative)],t);case`Case`:return Se(e);case`Let`:return Ae(e);case`Forall`:case`Exists`:{let r=q(n,e);return A(G(),()=>{let n=ge(e.bounds,r.start),i=P(n.bounded.flat(),e.body);return N(e.kind===`Forall`?`$BoundedForall`:`$BoundedExists`,[i],t,n)})}case`UnboundedQuantifier`:{let r=q(n,e),i=q(n,e.body),a=ci(n,r.start,i.start,e.names),o=e.isTemporal?e.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:e.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return A(G(),()=>{let r=e.names.map((e,t)=>j(e,0,ni(n,a[t]),!0)),i=P(r,e.body);return N(o,[i],t,{unbounded:r})})}case`Choose`:return je(e);case`SetEnumeration`:return N(`$SetEnumerate`,e.elements.map(F),t);case`Tuple`:return N(`$Tuple`,e.elements.map(F),t);case`SetFilter`:{let r=F(e.bound.set),i=q(n,e);return A(G(),()=>{let n=I([e.bound],i.start,[r]),a=P(n.bounded.flat(),e.predicate);return N(`$SubsetOf`,[a],t,n)})}case`SetMap`:{let r=q(n,e.expression);return A(G(),()=>{let n=ge(e.bounds,r.end+1),i=P(n.bounded.flat(),e.expression);return N(`$SetOfAll`,[i],t,n)})}case`FunctionConstruction`:{let r=q(n,e);return A(G(),()=>{let n=ge(e.bounds,r.start),i=P(n.bounded.flat(),e.body);return N(`$FcnConstructor`,[i],t,n)})}case`FunctionSet`:return N(`$SetOfFcns`,[F(e.domain),F(e.range)],t);case`Record`:return Ee(`$RcdConstructor`,e);case`RecordSet`:return Ee(`$SetOfRcds`,e);case`Except`:return we(e);case`ExceptAt`:{let e=h[h.length-1],n=_[_.length-1];return e===void 0||n===void 0?(o(t,`@ used where its meaning is not defined.`),M()):{...W(l()),kind:`At`,except:e,component:n,location:n.location}}case`FunctionApplication`:{let n=F(e.function);if(vr(n))return n;me(n);let r=e.args.length===1?F(e.args[0]):N(`$Tuple`,e.args.map(F),t);return N(`$FcnApply`,[n,r],t)}case`FieldAccess`:{let r=F(e.record),i=q(n,e);return N(`$RcdSelect`,[r,oe(e.field,ni(n,i.end))],t)}case`Product`:return N(`$CartesianProd`,e.factors.map(F),t);case`BoxAction`:case`AngleAction`:return N(e.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[F(e.action),F(e.subscript)],t);case`WeakFairness`:case`StrongFairness`:return N(e.kind===`WeakFairness`?`$WF`:`$SF`,[F(e.subscript),F(e.action)],t);case`Label`:return Ne(e);case`Subexpression`:return pe(e)}},I=(e,t,r)=>{let i=he(e),a={value:t};return{bounded:i.map(e=>{let t=q(n,e[0].set),r=e.flatMap(e=>e.pattern.kind===`Name`?[e.pattern.name]:e.pattern.names),i=ci(n,a.value,t.start,r);return a.value=t.end+1,r.map((e,t)=>j(e,0,ni(n,i[t]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},Ne=e=>{let t=T(e),r=v.at(-1);if(r===void 0)return o(t,`Label not in definition or proof step.`),M();if(S.isDeclared.slice(2,S.depth+1).some(Boolean))return o(t,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),M();if(h.length>0&&_.length>0)return o(t,`Labels inside EXCEPT clauses are not yet implemented.`),M();b();let i=F(e.body),s=x(),c=ci(n,q(n,e).start,q(n,e.body).start,e.params),u=e.params.map((t,r)=>{let i=gi(a,t);if(i?.kind===`FormalParam`)return i;let s=ni(n,c[r]);return o(s,`Illegal parameter ${t} of label \`${e.name}'.`),j(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=S.goal;return p&&w.set(d,{scope:p,clause:S.goalClause}),d},Pe=(e,t,r)=>{let i={value:t.start};return e.params.map(e=>{let t=e.location?Xr(n,e.location):Te(i.value,e.name),a=ut(t,e.arity);return i.value=a.end+1,j(di(e.name),e.arity,J(n,a),r)})},L=e=>{let t=E(e.location);return e.isLocal&&!K(n,t.start,`LOCAL`)&&K(n,t.start-1,`LOCAL`)?{start:t.start-1,end:t.end}:t},Fe=(e,t)=>{let r=L(e),i=J(n,r),s=di(e.name),l={start:e.isLocal?r.start+1:r.start,end:r.end},u=A(G(),()=>{let t=Pe(e,l,!0),n=gi(a,s);if(n?.kind===`OpDef`&&n.inRecursive&&!n.isDefined){let e=n.params?.length===t.length&&(t.length===0||t[t.length-1].arity===0);n.letInLevel===c.curLevel?e||o(i,`Definition of ${n.name} has different arity than its RECURSIVE declaration.`):o(i,`Recursive operator ${s} defined at wrong LET/IN level.`)}else n!==void 0&&o(i,`Operator ${s} already defined or declared.`);return b(),{params:t,body:F(e.body),existing:n}}),d=x(),p=u.existing,m=u.params,h=si(n,r.start);if(p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined&&p.letInLevel===c.curLevel){p.params=m,p.weights=m.map(()=>0),p.maxLevels=m.map(()=>3),p.isLeibnizArg=m.map(()=>!0),p.labels=d,Ie(p,u.body,i,h),D.definitions.push(p),t?.push(p);return}let g=ne({name:s,params:m,body:u.body,isLocal:e.isLocal,location:i,preComments:h,labels:d});f(a,g),re(g),D.definitions.push(g),t?.push(g)},Ie=(e,t,n,r)=>{e.isDefined=!0,e.body=t,e.location=n,e.preComments=r,e.inRecursive&&(c.unresolvedCount[c.curLevel]--,c.unresolvedSum--)},Le=(e,t)=>{let r=L(e),i=J(n,r),s=G(),l=e.isLocal?r.start+1:r.start,u=A(s,()=>ge(e.bounds,l+1)),d=gi(a,e.name),m=A(s,()=>j(e.name,0,i,d===void 0)),h=N(`$NonRecursiveFcnSpec`,[],i,{unbounded:[m],...u}),g=d?.kind===`OpDef`&&d.inRecursive&&!d.isDefined,_=g&&d.letInLevel===c.curLevel;_?d.arity!==0&&o(i,`Function ${d.name} has operator arguments in its RECURSIVE declaration.`):g?o(i,`Recursive function ${e.name} defined at wrong LET/IN level.`):d!==void 0&&o(i,`Function name \`${e.name}' already defined or declared.`);let v=si(n,r.start),y=d===void 0?ne({name:e.name,params:[],body:h,isLocal:e.isLocal,location:i,preComments:v}):d.kind===`OpDef`&&(_||!g)?d:void 0;_?d.arity===0&&Ie(d,h,i,v):d===void 0&&y!==void 0&&(f(a,y),re(y)),y!==void 0&&(D.definitions.push(y),t?.push(y)),p.unshift({name:e.name,node:h}),b();let S=()=>P(u.bounded.flat(),e.body),C=y===void 0?S():A(s,S),w=x();y!==void 0&&(y.labels=w),p.shift(),h.operands=[C],h.operator.name===`$NonRecursiveFcnSpec`&&(h.unbounded=void 0)},Re=[],ze=e=>{c.unresolvedSum===0&&c.recursiveSectionCount++,c.unresolvedCount[c.curLevel]+=e.length,c.unresolvedSum+=e.length,e.forEach(e=>{let t=dt(e);l();let r=Array.from({length:e.arity},()=>j(``,0,void 0,!1)),i=ne({name:di(e.name),params:r,location:J(n,t),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:c.recursiveSectionCount,letInLevel:c.curLevel});f(a,i),Re.push(i),D.opDefsInRecursiveSection.push(i)})},Be=()=>{c.unresolvedCount[c.curLevel]!==0&&(Re.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])},Ve=(e,t,i)=>{l();let s=Tr(t.table).filter(e=>e.kind===`OpDecl`),c=s.flatMap(e=>{let t=gi(a,e.name);return t===void 0?[]:[{op:e,expr:e.declKind===3||e.declKind===2&&e.arity===0?ie(t,[],i):se(t,i),isImplicit:!0}]}),u=(e,t)=>{let n=t.kind===`OpArg`?kr(t.op):0,r=e.arity>0&&t.kind===`OpAppl`&&t.isNull===!0;n!==e.arity&&!r&&o(t.location,`An operator must be substituted for symbol '${e.name}', and it must have arity ${e.arity}.`)},d=L(e),f={value:li(n,d.start,d.end,`WITH`)+1};return e.substitutions.forEach(e=>{let r=li(n,f.value,d.end,e.name);r!==-1&&(f.value=q(n,e.expression).end+1);let a=Ar(t,di(e.name));if(a?.kind!==`OpDecl`){o(r===-1?i:ni(n,r),`Identifier '${r===-1?e.name:ii(n,r)}' 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?F(e.expression):ye(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&&r.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(i,`Substitution missing for symbol ${e.name} declared at ${_r(e.location)} \nand instantiated in module ${D.name}.`)),c},He=(e,t,n,r,i,a=D)=>(vr(n)&&o(i,e===`SubstIn`?`Substitution error, probably due to error
|
|
25
|
+
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}),Ue=(e,t,i)=>{let o=L(e),s=J(n,o),c=si(n,o.start),u=e.name??``,d=G(),p=e.isLocal?o.start+1:o.start;e.params.length>0&&a.contexts.push(d);let m=Pe(e,{start:p,end:o.end},e.params.length>0),h=k(e.module),g=h.context,_=Ve(e,g,s);e.params.length>0&&a.contexts.pop(),Tr(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`?ne({name:i,params:r,body:_.length>0&&n.body?He(`SubstIn`,_,n.body,h,s):n.body,isLocal:e.isLocal,location:s,source:n.source??n,preComments:c,labels:n.labels}):ne({defKind:`ModuleInstance`,name:i,params:r,isLocal:e.isLocal,location:s,module:n.module,source:n.source??n,preComments:c});f(a,o),n.defKind===`UserDefined`&&re(o),(t??D.definitions).push(o)}),Tr(g.table).forEach(n=>{if(n.kind!==`ThmOrAssumpDef`||n.isLocal)return;let r=_.length>0?He(`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:[]};f(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};(i??D.topLevel).push(v);let y=ne({defKind:`ModuleInstance`,name:u,params:m,isLocal:e.isLocal,location:s,preComments:c});f(a,y),r.version!==`1.7.4`&&t?.push(y)},We=(e,t=!0,r)=>{let i=L(e),o=r??J(n,i),s=si(n,i.start),c=k(e.module),u=c.context,d=Ve(e,u,o),p=e.isLocal,m=bi(c);Tr(u.table).forEach(e=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`||e.isLocal)return;let t=(t,n)=>{let r=ne({name:e.name,params:e.params,body:n,isLocal:p,location:o,module:t,source:e.source??e,preComments:s,labels:e.labels});return f(a,r),r},n=()=>(f(a,e),e),r=e.module===void 0||bi(e.module),i=m||r?p?t(e.module,e.body):n():t(D,e.body&&He(`SubstIn`,d,e.body,c,o));D.definitions.push(i),re(i)}),Tr(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 f(a,r),r},r=m?p?n(e.module,e.body):(f(a,e),e):bi(e.module)?p?n(D,e.body):e:n(D,He(`APSubstIn`,d,e.body,c,o));t&&D.definitions.push(r)});let h={...W(l()),kind:`Instance`,name:void 0,isLocal:p,params:[],module:c,substs:d,location:o};return t&&D.topLevel.push(h),h},Ge=e=>{let t=O(e.name)??(e.name===D.name?D:void 0);return t===void 0?(o(ni(n,Xr(n,e.location)+1),`Module \`${e.name}' used without being extended or instantiated.`),[]):[t]},Ke=e=>e.flatMap(e=>{if(e.kind===`ModuleFact`)return Ge(e);let n=Lr(e);if(n===void 0||!Rr(n))return[F(e)];let r=fe(e,0,!0,!1);if(r.kind===`ThmOrAssumpDef`)throw new t(`Expected a fact`);return[r]}),qe=e=>K(n,e.start,`(`)&&Qr(n,e.start)===e.end,Je=e=>ei(n,q(n,e)),Ye=(e,t)=>Je(e.args[0]).start===t.start?e.args.length===2?`N_InfixExpr`:`N_PostfixExpr`:n.tokens[t.start].kind===`Identifier`?`N_OpApplication`:`N_PrefixExpr`,Xe=(e,t)=>qe(t)?`N_ParenExpr`:e.kind===`String`?ii(n,t.start):e.kind===`Apply`?Ye(e,t):Di.get(e.kind),Ze=(e,t)=>{if(e.kind===`String`&&!qe(t))return!1;if(e.kind===`Identifier`&&!e.name.includes(`!`))return!0;let n=Xe(e,t);return n===void 0||Oi.has(n)?void 0:!0},Qe=(e,t)=>{let r=(e,t=Je(e))=>({last:t,lastKind:Xe(e,t)});if(qe(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:Ze(e.expression,Je(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=Je(t),i=r.end+1;return{hasChildlessFirstChild:Ze(t,r),last:{start:i,end:i},lastKind:n.tokens[i].text}}case`Apply`:{let n=Ye(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=Je(e.args[0]),a=i.end+1;return{hasChildlessFirstChild:Ze(e.args[0],i),last:{start:a,end:a},lastKind:n===`N_InfixExpr`?`N_GenInfixOp`:`N_GenPostfixOp`}}}},R=e=>{let t=ei(n,q(n,e));if((e.kind===`Identifier`||e.kind===`Subexpression`||e.kind===`OperatorReference`)&&!qe(t))return!1;let r=Qe(e,t);if(r?.hasChildlessFirstChild===void 0||r.lastKind===void 0)return!1;let i=J(n,r.last);return r.hasChildlessFirstChild&&o(J(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(J(n,t),`DEF clause entry should describe a defined operator.`),!0},$e=e=>e.flatMap(e=>{if(e.kind===`ModuleFact`)return Ge(e);if(R(e))return[];let t=fe(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.`),[])}),z=(e,t)=>{e.isOnly||e.facts.length+e.defs.length>0||o(t,`Empty BY, USE, or HIDE`)},et=e=>{let t=J(n,E(e.location));z(e,t);let r=Ke(e.facts),i=$e(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
|
|
26
|
+
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}},tt=e=>{let t=E(e.location),r=e.set&&F(e.set),i=Te(t.start,e.name),o=fi[e.level],s={...W(l()),levelChecked:1,level:o.level,kind:`OpDecl`,name:di(e.name),arity:e.arity,declKind:o.declKind,location:J(n,ut(i,e.arity)),module:D};return f(a,s),{...W(l()),kind:`NewSymb`,declaration:s,set:r,location:J(n,t)}},nt=(e,t,r)=>{let i=E(e.location),s=ai(n,i.start-1),c=q(n,e.conclusion).start,u=n.tokens.findLastIndex((e,t)=>t<c&&e.kind===`Keyword`&&e.text===`PROVE`),d=J(n,{start:s?i.start-1:i.start,end:i.start});s!==ai(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(G()),s&&a.contexts.some(e=>y.has(e))&&o(d,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),s||y.add(hi(a));let p={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};S.depth=t,S.isDeclared[t]=!1,t===1&&(S.goal=r&&p,S.goalClause=0);let m=e.assumptions.map((e,n)=>{let r=e.kind===`NewSymbol`,i=e.kind===`AssumeProve`?nt(e,t+1):r?tt(e):F(e);return S.depth=t,r&&(S.isDeclared[t]=!0),p.isDeclaredBefore.push(p.isDeclaredBefore[n]||r),t===1&&S.goalClause++,i}),h=F(e.conclusion);t>1&&a.contexts.pop(),S.depth=t-1,t===1&&(S.goal=void 0);let g={...W(f),kind:`AssumeProve`,assumptions:m,goal:h,isSuffices:p.isSuffices,isBoxed:s,location:J(n,{start:s?i.start-1:i.start,end:i.end})};return C.set(g,p),g},rt=(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:[]}),it=e=>{let t=J(n,E(e.location));e.kind===`By`&&z(e,t);let r=e.kind===`By`?Ke(e.facts):[],i=e.kind===`By`?$e(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}},at=(e,t)=>{let r=e.body,i=J(n,t);switch(r.kind){case`Have`:return{node:N(`$Have`,[F(r.expression)],i),isPick:!1};case`Case`:return{node:N(`$Pfcase`,[F(r.expression)],i),isPick:!1};case`Witness`:return{node:N(`$Witness`,r.expressions.map(F),i),isPick:!1};case`Qed`:return{node:N(`$Qed`,[],i),isPick:!1};case`Take`:case`Pick`:{let e=r.kind===`Pick`,o=e?`$Pick`:`$Take`;e&&a.contexts.push(G());let s=e=>r.kind===`Pick`?[P(e,r.body)]:[];if(r.bounds.length>0){let n=ge(r.bounds,t.start),a=s(n.bounded.flat());return{node:N(o,a,i,n),isPick:e}}let c=ci(n,t.start,t.end+1,r.names),l=r.names.map((e,t)=>j(e,0,ni(n,c[t]),!0)),u=s(l);return{node:N(o,u,i,{unbounded:l}),isPick:e}}}},ot=e=>{if((e.kind===`And`||e.kind===`Or`)&&!e.isBulleted)return!0;if(e.kind!==`Apply`||e.args.length!==2)return!1;let t=ei(n,q(n,e.args[0])),r=q(n,e).start;return t.start===r&&!K(n,t.end+1,`(`)},st=e=>{if(e.kind!==`Steps`)return it(e);let r=G();a.contexts.push(r);let i=[],o=[],s={previousRight:void 0},c=(e,r,a)=>{if(e.kind===`Define`){let r=e.definitions.map(e=>{let n=[];e.kind===`Instance`?Ue(e,n,i):e.kind===`Function`?Le(e,n):Fe(e,n);let r=n[e.kind===`Instance`?n.length-1:0];if(r?.kind!==`OpDef`)throw new t(`A DEFINE step defines no operator`);return r});return{...W(l()),kind:`DefStep`,defs:r,location:J(n,a)}}if(e.kind===`Use`||e.kind===`Hide`)return{...et(e),location:J(n,r)};if(e.kind===`Instance`)return We(e,!1,J(n,a))},u=e.steps.map(e=>{let r=E(e.location),i=$r(n,e.head),u={start:i.start+1,end:i.end},d=e.body;e.name!==void 0&&b();let p=e.name===void 0?void 0:l();d.kind!==`Assert`&&(s.previousRight=void 0);let m=c(d,r,u);if(m!==void 0)return e.name!==void 0&&f(a,ne({defKind:`NumberedProofStep`,name:e.name,location:J(n,r),labels:x(),step:m})),m;let h=d.kind===`Assert`&&d.statement.kind===`AssumeProve`;h&&(s.previousRight=void 0);let g=d.kind===`Assert`&&d.isSuffices,_=G(),v=d.kind===`Assert`?{node:(t=>{if(t.kind===`AssumeProve`){let n=A(_,()=>nt(t,1,e.name===void 0?void 0:{isSuffices:g}));return n.isSuffices=g,n}if(g){let e=F(t);return N(`$Suffices`,[e],J(n,u))}let r=s.previousRight,i=r!==void 0&&t.kind===`Apply`&&ot(t)&&t.args[0].kind===`ExceptAt`,a=i?F(t.args[1]):void 0,o=i?ie(ce(t.operator,T(t)),[N(`$Nop`,[r],T(t.args[0])),a],T(t)):F(t),c=o.kind===`OpAppl`?o.operands[1]:void 0;return s.previousRight=ot(t)?c:void 0,o})(d.statement),isPick:!1}:at(e,u);if(v===void 0)throw new t(`Unexpected proof step ${d.kind}`);let y=v.isPick?a.contexts.pop():void 0,S=e.name===void 0||p===void 0?void 0:rt(p,e.name,v.node,ni(n,Xr(n,e.location)),x());S&&f(a,S);let C=h&&!g;C&&a.contexts.push(_);let w=e.proof&&st(e.proof);return C&&a.contexts.pop(),ee(v.node),h&&g&&(o.push(_),a.contexts.push(_)),y?.symbols.forEach(e=>f(a,e)),{...W(l()),kind:`Theorem`,definition:S,body:v.node,proof:w,isSuffices:g,location:J(n,r)}});return o.forEach(()=>{a.contexts.pop()?.symbols.forEach(e=>Or(r,e))}),a.contexts.pop(),{...W(l()),kind:`NonLeafProof`,steps:u,instances:i,proofLevel:e.level,location:J(n,E(e.location))}},ct=e=>{let t=J(n,E(e.location)),r=e.statement,i=G();e.name!==void 0&&b();let o=e.name===void 0?void 0:l();r.kind===`AssumeProve`&&a.contexts.push(i);let s=r.kind===`AssumeProve`?nt(r,1,e.name===void 0?void 0:{isSuffices:!1}):F(r),c=e.name===void 0||o===void 0?void 0:rt(o,e.name,s,t,x());c&&(r.kind===`AssumeProve`&&a.contexts.pop(),f(a,c),D.definitions.push(c),r.kind===`AssumeProve`&&a.contexts.push(i));let u=e.proof&&st(e.proof);r.kind===`AssumeProve`&&a.contexts.pop(),ee(s);let d={...W(l()),kind:`Theorem`,definition:c,body:s,proof:u,isSuffices:!1,location:t};D.topLevel.push(d)},lt=e=>{let t=E(e.location),r=J(n,t);e.name!==void 0&&b();let i=F(e.expression),o=e.name===void 0?void 0:rt(l(),e.name,i,r,x(),!1);o&&(f(a,o),D.definitions.push(o));let s={...W(l()),kind:`Assume`,definition:o,body:i,location:r};D.topLevel.push(s)},ut=(e,t)=>t===0?{start:e,end:e}:K(n,e,`_`)?{start:e,end:K(n,e+2,`_`)?e+2:e+1}:K(n,e+1,`(`)?{start:e,end:Qr(n,e+1)}:{start:e,end:K(n,e+1,`_`)?e+1:e},dt=e=>ut(E(e.location).start,e.arity),ft=(e,t)=>{let r=dt(e);e.name===`@`&&t===3&&o(J(n,r),`Attempted to declare '@' as a variable.`);let i={...W(l()),levelChecked:1,level:+(t===3),kind:`OpDecl`,name:di(e.name),arity:e.arity,declKind:t,location:J(n,r),module:D};return t===2&&(i.levelParams.add(i),i.allParams.add(i)),f(a,i),i};e.extends.forEach(e=>{let t=k(e);D.extendees.push(t);let n=hi(a);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?jr(n,e.name):Ar(n,e.name);t===void 0?Or(n,e):t!==e&&t.kind!==e.kind?o(e.location,`The ${vi(e)} of '${e.name}' conflicts with \nits ${vi(t)} at ${_r(t.location)}.`):t!==e&&!yi(t,e)&&s(e.location,`Warning: the ${vi(t)} of '${e.name}' conflicts with \nits ${vi(t)} at ${_r(t.location)}.`)}),D.topLevel.push(...t.topLevel)});let pt=(e,t)=>{c.unresolvedSum!==0&&o(J(n,E(e)),`${t} may not appear within a recursive definition section.`)};return e.units.forEach(e=>{switch(e.kind){case`Variables`:pt(e.location,`A VARIABLE declaration`),e.declarations.forEach(e=>ft(e,3));break;case`Constants`:pt(e.location,`A declaration`),e.declarations.forEach(e=>ft(e,2));break;case`Recursive`:ze(e.declarations);break;case`Definition`:e.definition.kind===`Function`?Le(e.definition,void 0):Fe(e.definition,void 0);break;case`Instance`:e.instance.name===void 0?We(e.instance):Ue(e.instance,void 0,void 0);break;case`Assumption`:pt(e.assumption.location,`An ASSUME`),lt(e.assumption);break;case`Theorem`:pt(e.theorem.location,`A THEOREM`),ct(e.theorem);break;case`Use`:pt(e.use.location,`A USE or HIDE`),D.topLevel.push(et(e.use));break;case`Module`:{pt(e.module.location,`A MODULE `);let t={contexts:[...a.contexts,G()]},r=te(e.module,n,D,t),i=O(r.name);i===void 0?Or(hi(a),r):i!==r&&o(r.location,`Multiply-defined module '${r.name}': this definition or declaration conflicts \nwith the one at ${_r(i.location)}.`);break}}}),Be(),D},A=x.map(e=>{r.onAnalyze?.(e),u.id=Array.from({length:4},l)[1];let t=b(e,void 0),n=G();p.toReversed().forEach(e=>Or(n,e));let i=te(t.module,t.file,void 0,{contexts:[n]});return g.set(e,i),r.onModule?.(i,a),i});return{root:A[A.length-1],modules:A,messages:a}},Mi=e=>{let t=e.toLowerCase(),n=t.startsWith(`\\b`)?2:t.startsWith(`\\o`)?8:t.startsWith(`\\h`)?16:10;return[...n===10?t:t.slice(2)].reduce((e,t)=>e*BigInt(n)+BigInt(parseInt(t,n)),0n).toString()},Ni=(e,t,n,r)=>gr(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)},Pi=(e,t,n)=>`${e.id}:${t}:${n.id}`,Fi=(e,t,n,r)=>{e.set(Pi(t,n,r),{op:t,index:n,param:r})},Ii=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},Li=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},Ri=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&Li(e,r,t)})},zi=(e,t)=>`${e.id}:${t}`,Bi=(e,t,n,r)=>{let i=zi(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},Vi=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&Bi(e,t.param,t.position,t.level)})},Hi=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},Ui=(e,t)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Ri(e.levelConstraints,t.levelConstraints),Vi(e.argLevelConstraints,t.argLevelConstraints),Ii(e.argLevelParams,t.argLevelParams)},Wi=(e,t)=>t.includes(e.op)||t.includes(e.param),Gi=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,Ki=e=>e.kind!==`Module`,qi=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,Ji=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,Yi=(e,t)=>e.kind===`OpDef`?e.weights[Ji(e,t)]??0:0,Xi=(e,t)=>e.maxLevels[Ji(e,t)]??3,Zi=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,Qi=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[Ji(e,t)]??!0:e.isLeibnizArg[t]??!0,$i=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,ea=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],ta=(e,t)=>t.find(t=>t.op===e)?.expr,na=(e,t,n)=>{let r=ta(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},ra=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=ta(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!Gi(i.op))return;let a=i.op;na(e.param,t,!1).forEach(t=>Fi(n,a,e.index,t))}),n},ia=(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;na(r,t,!1).forEach(e=>Li(a,e,i))}),e.argLevelParams.forEach(e=>{let n=ta(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;X(n.op,r,i);let o=Xi(n.op,e.index);na(e.param,t,!1).forEach(e=>Li(a,e,o))}),a},aa=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=ta(e.param,t);n===void 0?Bi(i,e.param,e.position,e.level):n.kind===`OpArg`&&Gi(n.op)&&Bi(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=ta(e.param,t);if(a===void 0)return;let o=ta(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&Gi(s)&&(X(a,n,r),Bi(i,s,e.index,a.level))}),i},oa=(e,t)=>Nr(e,3).length>0||(ha(e,t),Mr(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),sa=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(zi(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(Pi(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(zi(t,n))}),Ii(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},ca=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>Xi(t,o)&&(n&&X(a,r,i)&&Ni(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`||!qi(a.op)))return;let s=a.op;X(s,r,i);let c=kr(s);for(let l=0;l<c;l++){let c=Zi(t,o,l);Xi(s,l)>=c||(n&&X(a,r,i)&&Ni(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||!$i(t,o,l,u)||n.level<=Xi(s,u)||(X(a,r,i)&&X(n,r,i)&&Ni(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&&Ni(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${_r(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},la=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);Ri(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&Ri(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>Ri(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=Xi(t,r);n?.levelParams.forEach(t=>Li(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!qi(n.op))return;let o=n.op;X(o,r,i);let s=kr(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!$i(t,a,r,i))continue;let s=Xi(o,i);n?.levelParams.forEach(t=>Li(e.levelConstraints,t,s)),!o.isLeibniz&&!Qi(o,i)&&n&&Y(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&qi(n.op)&&(X(n.op,r,i),Li(e.levelConstraints,t.param,Xi(n.op,t.index)))}),Vi(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&Vi(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>Vi(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!Gi(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)Bi(e.argLevelConstraints,i,n,Zi(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&$i(t,r,a,o)&&Bi(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(X(n,r,i),Bi(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&Ii(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>Ii(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=>Fi(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&Gi(a.op)&&Fi(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!Gi(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&$i(t,r,a,o)&&n.levelParams.forEach(t=>Fi(e.argLevelParams,i,o,t))})})},ua=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),da=(e,t)=>{let n=(n,r)=>{Ni(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=ua.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.`)})},fa=(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(qi(i)){let r=X(i,t,n);ca(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&Yi(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&&(Yi(i,n)===1&&Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),Qi(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(ea(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),la(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),Ri(e.levelConstraints,t.levelConstraints),Bi(e.argLevelConstraints,i,n,t.level),Vi(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>Fi(e.argLevelParams,i,n,t)),Ii(e.argLevelParams,t.argLevelParams)});return da(e,n),e.levelCorrect},pa=(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))}),sa(e,i,r),e.levelCorrect},ma=(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)}),sa(e,e.params,e.body)),e.levelCorrect),ha=(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),pa(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||Ni(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),pa(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(ha(e,t)));let a=Mr(e);return a.forEach(e=>i(pa(e,1,t))),Pr(e).forEach(e=>i(ma(e,1,t))),e.topLevel.forEach(e=>i(X(e,1,t))),oa(e,t)||Nr(e,2).forEach(t=>Li(e.levelConstraints,t,0)),a.forEach(t=>{Ri(e.levelConstraints,t.levelConstraints),Vi(e.argLevelConstraints,t.argLevelConstraints),Ii(e.argLevelParams,t.argLevelParams,e=>!Wi(e,t.params??[]))}),e.topLevel.forEach(t=>{Ri(e.levelConstraints,t.levelConstraints),Vi(e.argLevelConstraints,t.argLevelConstraints),Ii(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},ga=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{Ki(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=X(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),Ui(e,t),Y(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),_a=(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&&Ni(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&Ni(t,e.body.location,`Non-constant CASE for temporal goal.`),_a(e.proof,t)):n===`$Qed`&&_a(e.proof,t)})},va=(e,t,n,r,i,a)=>{e.levelConstraints=ia(t,n,r,i,a),e.argLevelConstraints=aa(t,n,i,a),e.argLevelParams=ra(t.argLevelParams,n)},ya=(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;ha(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(r.expr,t,n)||(e.levelCorrect=!1)});let i=oa(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(X(a.expr,t,n)&&Ni(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||Ni(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)&&Ni(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(zi(i.op,t))?.level;a===void 0||Xi(o,t)>=a||(s&&Ni(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=Xi(s,i.index);o.expr.level<=l||(c&&X(o.expr,t,n)&&Ni(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 Ri(e.levelConstraints,ia(r,e.substs,i,t,n),a),e.substs.forEach(t=>Ri(e.levelConstraints,t.expr.levelConstraints,a)),Vi(e.argLevelConstraints,aa(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>Vi(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),Ii(e.argLevelParams,ra(r.argLevelParams,e.substs),t=>!Wi(t,e.params)),e.substs.forEach(t=>Ii(e.argLevelParams,t.expr.argLevelParams,t=>!Wi(t,e.params))),e.levelCorrect},X=(e,t,n)=>{if(!Ki(e))return ha(e,n);switch(e.kind){case`OpAppl`:return fa(e,t,n);case`OpDef`:return pa(e,t,n);case`ThmOrAssumpDef`:return ma(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,Hi(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),Ri(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>Ri(e.levelConstraints,t.levelConstraints)),Vi(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>Vi(e.argLevelConstraints,t.argLevelConstraints)),Ii(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];Ii(e.argLevelParams,t.argLevelParams,e=>!Wi(e,n))}),e.instances.forEach(t=>Ii(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,Hi(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=>Ui(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,na(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>Y(e.allParams,na(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=oa(e.instantiatedModule,n);return va(e,r,e.substs,i,t,n),e.levelCorrect}case`Instance`:return ya(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,Hi(e,e.body),e.level!==0&&Ni(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=ga(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&&Ni(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&_a(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return ga(e,e.facts,t,n);case`NonLeafProof`:return ga(e,[...e.steps,...e.instances],t,n);case`DefStep`:return ga(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,Ni(n,e.location,`Level error:
|
|
27
|
+
Temporal formula used as set.`)),Hi(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=>Ui(e,t)),e.levelCorrect&&e.levelParams.forEach(t=>{t.kind===`OpDecl`&&t.declKind===2&&Li(e.levelConstraints,t,2)})),e.levelCorrect}},ba=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[]}},xa=/* @__PURE__ */ new Map([[`Integers`,`Int`],[`Naturals`,`Nat`],[`Reals`,`Reals`]]),Sa=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&&xa.get(e)===t.name||n(t))return!0}}return ba(e).some(n)};return n(e)},Ca=e=>e.operands.filter(e=>e?.kind===`OpAppl`),wa=e=>{let t=e.operands[0];return t?.kind===`String`?t:void 0},Ta=(e,t)=>{if(e===t)return!0;if(e.operands.length!==t.operands.length)return!1;let n=new Set(Ca(t).map(e=>wa(e)?.value));return Ca(e).every(e=>n.has(wa(e)?.value))},Ea=(e,t=/* @__PURE__ */ new Set)=>(e.extendees.forEach(e=>{t.has(e)||(t.add(e),Ea(e,t))}),t),Da=e=>{let t=[...[...Ea(e)].flatMap(e=>e.records),...e.records];return e.records.flatMap(n=>t.filter(e=>Ta(e,n)).flatMap(Ca).some(Sa)?[]:Ca(n).flatMap(t=>{let n=wa(t),r=n&&Ar(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 ${_r(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}]}))},Oa=e=>`${_r(e.location)}\n\n${e.text}`,ka=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=>`${Oa(e)}\n\n\n`),n.length>0?`*** Warnings: ${n.length}\n\n`:``,...n.map(e=>`${Oa(e)}\n\n\n`)].join(``)},Aa=/* @__PURE__ */ new Set([`FiniteSets`,`Sequences`,`Bags`,`Naturals`,`Integers`,`Reals`,`RealTime`,`Randomization`,`TLC`]),ja=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))},Ma=e=>{try{return ae(oi(e))}catch(e){if(e instanceof t)return;throw e}},Na=(e,t)=>t===`1.7.4`&&_(e)!==void 0?void 0:Ma(e)?.name,Pa=(e,t=()=>void 0,n={})=>{let r=De(e,`.tla`),a=k(n.version),o=n.fileName??r,s=I(e)?L(e,`utf8`):a.get(r),c=[],l=e=>{c.push(e),n.onPrint?.(e)},u=e=>l(`${e}\n`),d=n.version===`1.7.4`,f=d&&n.isXmlExport,p=e=>{n.isXmlExport||u(e)},h=n.describeFile,g=/* @__PURE__ */ new Map([[r,I(e)?`file`:`standard`]]),_={value:!1},v=[],y={isReported:!1,isAborted:!1},x=fn(wt(),u),S=/* @__PURE__ */ new Map,C=[],w=()=>C.splice(0).forEach(e=>e.isError?n.onPrintError?.(`${e.text}\n`):u(e.text)),ee=e=>{let t=S.get(e),r=t?.module.location.range;if(t===void 0||r===void 0)return;let i=t.text.split(/\r\n|\r|\n/),a=fr(x,i.slice(r.start.line-1,r.end.line),n.version),o=a.has(`TLA_DIVERGENCE_EXISTS`),s=a.has(`PCAL_DIVERGENCE_EXISTS`),c=o===s?void 0:`The ${o?`TLA+ translation`:`PlusCal algorithm`} in module ${e} has changed since its last translation.`;if(d){let t=o&&s?`The PlusCal algorithm and its TLA+ translation in module ${e} filename since the last translation.`:c;t===void 0?a.has(`ERROR_ENCOUNTERED`)&&C.push({text:`A unexpected problem was encountered attempting to validate the specification for ${e}`,isError:!0}):C.push({text:`!! WARNING: ${t}`,isError:!1});return}let l=o&&s?`Both the PlusCal algorithm and its TLA+ translation in module ${e} have changed since the last translation.`:c??(a.has(`ERROR_ENCOUNTERED`)?`An unexpected problem was encountered attempting to validate the specification for ${e}`:void 0);if(l===void 0)return;let u=!a.has(`ERROR_ENCOUNTERED`)||o||s;v.some(e=>e.text===l)||v.push({location:e,text:l,isWarning:u})},T=(e,t)=>{if(n.isXmlExport||S.has(e))return;let r=Ma(t);if(r===void 0||r.name!==e)return;let i=[...S.values()].filter(t=>ja(t.module).includes(e));S.set(e,{text:t,module:r}),i.forEach(()=>ee(e)),ja(r).filter(t=>t!==e&&S.has(t)).forEach(ee)},E=()=>{if(w(),y.isReported)return;y.isReported=!0;let e=v.filter(e=>e.isWarning);e.length>0&&(p(`Warnings (${e.length}) during syntax parsing of ${o}:\n\n`),e.forEach(e=>p(`${Oa(e)}\n\n\n`))),e.length!==v.length&&(u(ka(v)),_.value=!0,y.isAborted=!0)},D=e=>{let n=a.get(e),r=t(e),i=r===void 0&&n===void 0&&s!==void 0&&!d?b(s,e):void 0,o=r??i;return g.set(e,r===void 0?i===void 0?`standard`:`root file`:`file`),o!==void 0&&T(e,o),o??n},O=(()=>{try{if(s===void 0)throw new i(`Cannot find source file for module ${o}`,void 0);return T(r,s),ji(s,D,{rootFileName:r,rootFilePath:n.isXmlExport?`${o.replace(/\.tla$/,``)}.tla`:void 0,version:n.version,rootExtendees:n.rootExtendees,onParse:e=>{h&&u(`Parsing file ${h(e,g.get(e)??`file`)}`),e===r&&ee(r),w()},onAnalyze:e=>{E(),(h||f)&&!y.isAborted&&u(`Semantic processing of module ${e}`)},onModule:(e,t)=>{if(y.isAborted||(t.every(e=>e.isWarning)&&ha(e,{messages:t,isTlc174:d}),t.length===0))return;if(t.some(e=>!e.isWarning)&&(_.value=!0),d)return u(`Semantic errors:\n\n${ka(t)}`);let n=t.filter(e=>e.isWarning);n.length>0&&(p(`*** Warnings: ${n.length}\n`),n.forEach(e=>p(`${Oa(e)}\n\n\n`)));let r=t.filter(e=>!e.isWarning);r.length!==0&&(u(`Semantic errors:\n\n*** Errors: ${r.length}\n`),r.forEach(e=>u(`${Oa(e)}\n\n`)))}})}catch(e){if(_.value=!0,e instanceof m){u(`\nFatal errors while parsing TLA+ spec in file ${o}\n`),u(e.message),u(ka(v));return}if(!(e instanceof i))throw e;let t={location:e.location,text:e.message,isWarning:!1},n=d&&e.parseError?.includes(` and token "" `);if(e.parseError!==void 0&&!n&&!f&&u(e.parseError),u(`\nFatal errors while parsing TLA+ spec in file ${o}\n`),n){u(`java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null`);return}if(d){u(`tla2sany.semantic.AbortException`),l(`*** Abort messages: 1\n\n${Oa(t)}\n\n\n`);return}u(Oa(t)),u(ka(y.isReported?[t]:[...v,t]))}})();if(O!==void 0&&E(),O!==void 0&&!_.value&&!n.isXmlExport&&!d){let e=O.modules.filter(e=>!Aa.has(e.name));h&&e.forEach(e=>u(`Linting of module ${e.name}`)),e.flatMap(Da).forEach(e=>u(`${Oa(e)}\n\n\n`))}return{text:c.join(``),isFailed:_.value,specification:y.isAborted?void 0:O}},Fa={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},Ia=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:[]}),La={"&":`&`,"<":`<`,">":`>`,"\r":` `},Ra=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:La[e]),za=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,Ba=e=>{let t=(e.cdata??e.text)?.match(za)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=Ba(t);if(e)return e}},Va=(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}>${Ra(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)Va(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},Ha=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)]),Ua=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)`}},Wa={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)`}}},Ga={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},Ka=_r(`--TLA+ BUILTINS--`),qa=(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}]},Ja=(e,t=16)=>e>t*.75?Ja(e,t*2):t,Ya=(e,t)=>(e^e>>>16)&t-1,Xa=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},Za=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),Qa=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,$a=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=Xa(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(Qa,``)}).join(`
|
|
28
|
+
`)},eo=e=>{let t=Xa(e),n=e=>Za(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(`
|
|
29
|
+
`)},to=(e,t,n)=>{let r=n.version===`1.7.4`,i=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Map,s={isSet:!1},l=[],u=(e,t)=>{if(!r)return t();l.push(...e);let n=t();return l.length-=e.length,n},f=(e,t)=>{let n=[...l,...t].reverse(),r=[e,...n.map(e=>`\tat tla2sany.${e.at}`)].join(`
|
|
30
|
+
`),i=n.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${r}\n`).join(``);return a(new c(r,i),Fa.uncaughtException)},p=e=>f(`java.lang.NullPointerException: Cannot invoke "tla2sany.semantic.${e.nullType}.export(org.w3c.dom.Document, tla2sany.xml.SymbolContext)" because ${e.nullValue} is null`,[e]),m=(e,t)=>(i.has(e.id)||(i.add(e.id),o.set(e.id,u([...t?[t]:[],...qa(e.kind,_r(e.location))],()=>v(e)))),Z(Ua(e),[Q(`UID`,e.id)])),h=(e,t,n)=>{let r=t.levelChecked===0?[]:[Q(`level`,t.level)],i=n?[Ha(n),...r]:r;return{...e,children:[...i,...e.children]}},g=(e,t,n)=>Z(`params`,e.map((e,r)=>Z(`leibnizparam`,[m(e,n),...t?.[r]?[Z(`leibniz`)]:[]]))),_=e=>{let t=e.map(e=>e.trimEnd()).filter(e=>e.length>0).join(`
|
|
31
|
+
`),r=n.isUncommented?eo($a(t)):t;return e.length>0?[{tag:`pre-comments`,cdata:r,children:[]}]:[]},v=e=>{switch(e.kind){case`FormalParam`:return h(Z(`FormalParamNode`,[Q(`uniquename`,e.name),Q(`arity`,e.arity)]),e,e.location);case`OpDecl`:return h(Z(`OpDeclNode`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),Q(`kind`,e.declKind)]),e,e.location);case`OpDef`:{if(e.defKind===`NumberedProofStep`)throw r?f(Ia(37),[Ga]):a(new d(Ia(37)),Fa.uncaughtException);if(e.defKind===`ModuleInstance`)return h(Z(`ModuleInstanceKind`,[Q(`uniquename`,e.name),...e.isLocal&&!r?[Z(`local`)]:[]]),e,e.location);let t=e.params??[];if(e.defKind===`BuiltIn`)return h(Z(`BuiltInKind`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),...e.params?[g(t,e.isLeibnizArg,$.builtInParam)]:[]]),e,e.location);let n=e.body,i=e.module;if(n===void 0&&r)throw p($.body);if(n===void 0||i===void 0)throw Error(`The definition of ${e.name} has no body`);return h(r?Z(`UserDefinedOpKind`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),Z(`body`,[C(n,$.body)]),...e.params?[g(t,e.isLeibnizArg,$.param)]:[],...e.inRecursive?[Z(`recursive`)]:[]]):Z(`UserDefinedOpKind`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),Z(`originalOperator`,[m(e.source??e)]),Z(`originallyDefinedInModule`,[m(i)]),Z(`body`,[C(n,$.body)]),g(t,e.isLeibnizArg,$.param),..._(e.preComments),...e.inRecursive?[Z(`recursive`)]:[],...e.recursiveSection>=0?[Q(`recursiveSection`,e.recursiveSection)]:[],...e.isLocal?[Z(`local`)]:[]]),e,e.location)}case`ThmOrAssumpDef`:return h(Z(e.isTheorem?`TheoremDefNode`:`AssumeDef`,[Q(`uniquename`,e.name),C(e.body,$.theoremDefinitionBody)]),e,e.location);case`Module`:return Z(`ModuleNode`,[Ha(e.location),...y(e)]);case`Theorem`:return h(Z(`TheoremNode`,[...e.definition?[Z(`definition`,[m(e.definition,$.theoremDefinition)])]:[],Z(`body`,[C(e.body,$.theorem)]),...e.proof?[C(e.proof,$.proof)]:[],...e.isSuffices?[Z(`suffices`)]:[]]),e,e.location);case`Assume`:return Z(`AssumeNode`,[Ha(e.location),...e.body.levelChecked===0?[]:[Q(`level`,e.body.level)],...e.definition?[Z(`definition`,[m(e.definition,$.assumeDefinition)])]:[],Z(`body`,[C(e.body,$.assume)])])}},y=e=>{let t=t=>!n.isRestricted||t.module===e;return[Q(`uniquename`,e.name),...r?[]:[Z(`extends`,[...new Set(e.extendees.map(e=>e.name))].toSorted().map(e=>Q(`uniquename`,e)))],...Nr(e,2).filter(t).map(e=>m(e,$.constant)),...Nr(e,3).filter(t).map(e=>m(e,$.variable)),...Mr(e).filter(t).map(e=>m(e,$.definition)),...e.topLevel.map(e=>e.kind===`Instance`||e.kind===`UseOrHide`?C(e,$.topLevel):m(e,$.topLevel)),...e.definitions.filter(e=>!r&&e.kind===`Module`).map(e=>m(e))]},b=(e,t)=>u([t],()=>Z(`Subst`,[m(e.op,$.substOperator),C(e.expr,$.substExpression)])),x=e=>{if(e.isNull&&r)throw f(Ia(0),[$.operator,...qa(`OpDef`,Ka),Ga]);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.isSet=!0);let n=m(e.operator,$.operator),i=e.operands.map((e,t)=>e===void 0||t===0&&s.isSet&&vr(e)?r?Q(`StringNode`,`$Other`):Z(`StringNode`,[Q(`StringValue`,`$Other`)]):C(e,$.operand)),a=e.tupleOrs,o=e.unbounded===void 0&&e.bounded===void 0?[]:[Z(`boundSymbols`,[...(e.unbounded??[]).map((e,t)=>Z(`unbound`,[m(e,$.unbound),...a?.[t]?[Z(`tuple`)]:[]])),...(e.bounded??[]).map((t,n)=>Z(`bound`,[...t.map(e=>m(e,$.bound)),...a?.[n]?[Z(`tuple`)]:[],C(e.ranges[n],$.range)]))])];return Z(`OpApplNode`,[Z(`operator`,[n]),Z(`operands`,i),...o])},S=(e,t)=>e.kind===`Module`||e.kind===`OpDef`?m(e,t):C(e,t),C=(e,t)=>{if(!r)return w(e);if(e.kind===`OpAppl`&&e.isAbsent&&`nullType`in t)throw p(t);let n=[t,{at:`semantic.SemanticNode.export(SemanticNode.java:379)`,failedFor:_r(e.location)},{at:`semantic.LevelNode.getSemanticElement(LevelNode.java:333)`}];return u(n,()=>w(e))},w=e=>{switch(e.kind){case`OpAppl`:return h(x(e),e,e.location);case`Numeral`:return h(Z(`NumeralNode`,[Q(`IntValue`,e.value)]),e,e.location);case`String`:return h(Z(`StringNode`,[Q(`StringValue`,e.value)]),e,e.location);case`Decimal`:return h(Z(`DecimalNode`,[Q(`mantissa`,e.mantissa),Q(`exponent`,e.exponent),...r?[]:[Q(`integralPart`,e.integralPart),Q(`fractionalPart`,e.fractionalPart)]]),e,e.location);case`LetIn`:{let t=C(e.body,$.letBody);return h(Z(`LetInNode`,[Z(`body`,[t]),Z(`opDefs`,e.opDefs.map(e=>m(e,$.letDefinition)))]),e,e.location)}case`Label`:return h(Z(`LabelNode`,[Q(`uniquename`,e.name),Q(`arity`,e.params.length),Z(`body`,[C(e.body,$.labelBody)]),Z(`params`,e.params.map(e=>m(e,$.labelParam)))]),e,e.location);case`OpArg`:return h(Z(`OpArgNode`,[Z(`argument`,[m(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 h(Z(`AtNode`,[C(t,$.exceptObject),C(n,$.exceptComponents)]),e,e.location)}case`SubstIn`:case`APSubstIn`:{let t=Wa[e.kind],n=e.substs.map(e=>b(e,t.subst)),r=C(e.body,t.body);return h(Z(e.kind===`SubstIn`?`SubstInNode`:`APSubstInNode`,[Z(`substs`,n),Z(`body`,[r]),Z(`instFrom`,[m(e.instantiatingModule,t.from)]),Z(`instTo`,[m(e.instantiatedModule,t.to)])]),e,e.location)}case`Instance`:{let t=e.substs.map(e=>b(e,$.instanceSubst)),n=e.params.map(e=>m(e,$.instanceParam));return Z(`InstanceNode`,[Ha(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&&!r?[Z(`local`)]:[]])}case`UseOrHide`:return h(Z(`UseOrHideNode`,[Z(`facts`,e.facts.map(e=>S(e,$.useFact))),Z(`defs`,e.defs.map(e=>m(e,$.useDefinition))),...e.isOnly?[Z(`only`)]:[],...e.isHide?[Z(`hide`)]:[]]),e,e.location);case`NewSymb`:return h(Z(`NewSymbNode`,[m(e.declaration,$.newDeclaration),...e.set&&!(r&&vr(e.set))?[C(e.set,$.newSet)]:[]]),e,e.location);case`AssumeProve`:return h(Z(`AssumeProveNode`,[Z(`assumes`,e.assumptions.map(e=>C(e,$.assumption))),Z(`prove`,[C(e.goal,$.goal)]),...e.isSuffices?[Z(`suffices`)]:[],...e.isBoxed?[Z(`boxed`)]:[]]),e,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=>S(e,$.byFact))),Z(`defs`,e.defs.map(e=>m(e,$.byDefinition))),...e.isOnly?[Z(`only`)]:[]]);return h(n,e,e.location)}case`NonLeafProof`:return h(Z(`steps`,[...r?[]:[Q(`proofLevel`,e.proofLevel)],...e.steps.map(e=>e.kind===`Theorem`?m(e,$.step):C(e,$.step))]),e,e.location);case`DefStep`:return h(Z(`DefStepNode`,e.defs.map(e=>m(e,$.defStep))),e,e.location)}},ee=(n.isRestricted?[t]:e).map(e=>m(e,$.main)),T=Ja(o.size),E=Z(`context`,[...o.entries()].toSorted(([e],[t])=>Ya(e,T)-Ya(t,T)).map(([e,t])=>Z(`entry`,[Q(`UID`,e),t])));return Z(`modules`,[Q(`RootModule`,t.name),E,...ee])},no=(e,t={version:`master`,isRestricted:!1,isUncommented:!1,isTerse:!1})=>{let n=to(e.modules,e.root,t),r=Ba(n);if(r){let e=r.character.codePointAt(0)??0;throw a(new d(`The spec contains the character U+${e.toString(16).toUpperCase().padStart(4,`0`)} in the ${r.tag} element. XML 1.0 cannot represent that character in character data, not even as a numeric character reference, so the spec cannot be exported until the character is removed from it.`),Fa.unrepresentableCharacter)}let i=[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>`];return Va(n,0,t.isTerse?0:2,i),t.isTerse?i.join(``):`${i.join(`
|
|
32
|
+
`)}\n`},ro=`META-INF/MANIFEST.MF`,io=async e=>{if(e===void 0||!I(e))return`master`;let t=await import(`fflate`),n=t.unzipSync(L(e),{filter:e=>e.name===ro})[ro];return(n&&/^X-Git-Tag: *(\S*)/m.exec(t.strFromU8(n))?.[1])===`v1.7.4`?`1.7.4`:`master`},ao={success:o.success,"assumption-violation":o.assumptionViolation,deadlock:o.deadlock,"invariant-violation":o.safetyViolation,"property-violation":o.safetyViolation,"liveness-violation":o.livenessViolation,"postcondition-violation":o.assumptionViolation,error:o.error},oo=Ze(`tla-ts <Spec.tla|Spec.cfg|glob>... {options}`,[{flag:`-config <Spec.cfg>`},{flag:`-deadlock`},{flag:`-dump [<format>] <file>`,getArity:e=>e.length>1&&e[0].startsWith(`dot`)?2:1},{flag:`-fp <num>`},{flag:`-lncheck <final|default>`},{flag:`-metadir <directory>`},{flag:`-nowarning`},{flag:`-seed <num>`},{flag:`-tool`},{flag:`-workers <count|auto>`}]),so=Ze(`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>`}]),co=/* @__PURE__ */ new Set([`--toolbox`,`--line`,`--threads`,`--nofpl`]),lo=Ze(`tla-ts prove {options} <Module.tla|glob>...`,[{flag:`--backend <${we.join(`|`)}>`},{flag:`-I <directory>`,isRepeatable:!0},{flag:`-workers <count|auto>`}]),uo=/* @__PURE__ */ new Set([`-o`,`-t`,`-r`,`-u`]),fo=/* @__PURE__ */ new Set([`-o`]),po=(()=>{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(`
|
|
33
|
+
`)})(),mo=[`Usage: ${oo.usage}`,` ${lo.usage}`,` ${so.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(`
|
|
34
|
+
`),ho=/[*?[{]/,go=e=>e.flatMap(e=>ho.test(e)?Ne(e).sort().map(e=>({path:e,isGlobbed:!0})):[{path:e,isGlobbed:!1}]),_o=e=>/^[+-]?\d+$/.test(e)&&BigInt.asIntN(64,BigInt(e))===BigInt(e),vo=e=>e?e[0]===`auto`?Ue():Math.max(1,Number.parseInt(e[0],10)||1):1,yo=[`constrained`,`stuttering`,`strict`],bo=(e,t)=>e.endsWith(t)?e:`${e}${t}`,xo=e=>{if(e.length===1)return{path:bo(e[0],`.dump`)};let t=e[0].toLowerCase();return{path:bo(e[1],`.dot`),dot:!0,colorize:t.includes(`colorize`),actionLabels:t.includes(`actionlabels`),snapshot:t.includes(`snapshot`)}},So=(e,t)=>e.print(w.computingInitProgress,O.none,`Computed ${t} initial states...`),Co=(e,t)=>e===`invariant-violation`?{code:w.invariantViolatedInitial,text:`Invariant ${t} is violated by the initial state:`}:{code:w.propertyViolatedInitial,text:`Property ${t} is violated by the initial state:`},wo=(e,t)=>t?.forEach(t=>{if(typeof t==`string`)return console.log(t);if(t.kind===`initial-states-progress`)return So(e,t.count);let n=Co(t.status,t.name);e.print(n.code,O.error,`${n.text}\n${se(t.state)}`)}),To=(e,t,n={code:w.behaviorUpToThisPoint,text:`The behavior up to this point is:`},r=!1)=>{t.length>0&&e.print(n.code,O.error,n.text),t.forEach((t,n)=>{(n>0||r)&&wo(e,t.output),e.print(w.statePrint2,O.state,`${n+1}: <${t.label??t.action??`Initial predicate`}>\n${se(t.state)}`)})},Eo={code:w.counterExample,text:`The following behavior constitutes a counter-example:
|
|
35
|
+
`},Do=(e,t)=>t===`1.7.4`||e.length===0?`Temporal properties were violated.
|
|
36
|
+
`: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`,Oo=e=>e.filter((t,n)=>t!==e[n-1]).map((e,t)=>`${t}) ${T(e)}\n`).toReversed().join(``),ko=e=>{if(e.length===0)return` The error call stack is empty.
|
|
37
|
+
`;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`},Ao=(e,t)=>{let n=t.generated,r=t.distinct,i=C(/* @__PURE__ */ new Date);n===r?e.print(w.initGenerated1,O.none,`Finished computing initial states: ${r} distinct state${r===1?``:`s`} generated at ${i}.`):e.print(w.initGenerated2,O.none,`Finished computing initial states: ${n} state${n===1?``:`s`} generated, with ${r} of them distinct at ${i}.`)},jo=(e,t,n)=>{let r=Math.max(Date.now()-(n??0),1)/6e4,i=e=>e.toLocaleString(`en-US`),a=(e,t)=>n===void 0?``:` (${i(Math.floor(e/r))} ${t}/min)`;e.print(w.progress,O.none,`Progress(${Math.max(t.depth,1)}) at ${C(/* @__PURE__ */ new Date)}: ${i(t.generatedStates)} states generated${a(t.generatedStates,`s`)}, ${i(t.distinctStates)} distinct states found${a(t.distinctStates,`ds`)}, ${i(t.queuedStates)} states left on queue.`)},Mo=(e,t)=>je(e,`${t}.class`),No=(e,t,n,r)=>{let i=e.print;switch(t.kind){case`parsed`:n.isParsed=!0,e.isTool&&i(w.sanyFinished,O.none,`SANY finished.`),i(w.starting,O.none,`Starting... (${C(/* @__PURE__ */ new Date)})`);return;case`constant-level-invariant`:if(e.version===`1.7.4`)return;i(w.constantLevelInvariant,O.warning,`The invariant ${t.name} is a constant-level formula (i.e., it contains no variables, primes, or temporal operators) and evaluates to TRUE. To assert constant-level formulas in your spec, use ASSUME ConstInv. If you optionally want to give the assumption a name, write ASSUME YourAssumption == ConstInv instead. See https://explain.tlapl.us/assumptions-and-invariants for additional details.`);return;case`state-level-property`:if(e.version===`1.7.4`)return;i(w.stateLevelProperty,O.warning,`The formula ${t.name} is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ${t.name} holds in all states of every behavior, use INVARIANT ${t.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${t.name} changes it into a temporal formula, asserting that ${t.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`);return;case`liveness-initializing`:t.isSymmetric&&i(w.livenessSymmetry,O.warning,`Declaring symmetry during liveness checking is dangerous. It might cause TLC to miss violations of the stated liveness properties. Please check liveness without symmetry defined.`),t.isConstrained&&e.version===`1.7.4`&&i(w.livenessConstraints,O.warning,`Declaring state or action constraints during liveness checking is dangerous: Please read section 14.3.5 on page 247 of Specifying Systems (https://lamport.azurewebsites.net/tla/book.html) and optionally the discussion at https://discuss.tlapl.us/msg00994.html for more details.`);return;case`liveness-prepared`:i(w.temporalBranches,O.none,`Implied-temporal checking--satisfiability problem has ${t.branches} branches.`);return;case`java-override`:{let e=qe(Me(Mo(r,t.module))).href;i(t.isMatched?w.javaOverrideLoaded:w.javaOverrideMismatch,t.isMatched?O.none:O.warning,`${t.isMatched?`Loading`:`Failed to match`} ${t.operator} operator override from ${e.replace(`file:///`,`file:/`)} with signature: <Java Method: ${t.signature}>.`);return}case`initial-states-started`:i(w.computingInit,O.none,`Computing initial states...`);return;case`initial-states-progress`:So(e,t.count);return;case`initial-states-computed`:Ao(e,t.initialStates);return;case`progress`:jo(e,t.statistics,n.start);return;case`liveness-started`:{n.liveness=Date.now(),t.isComplete&&jo(e,t.statistics);let r=t.branches>1?`${t.branches} branches of `:``,a=t.branches*t.states;i(w.checkingTemporal,O.none,`Checking ${r}temporal properties for the ${t.isComplete?`complete`:`current`} state space with ${a} total distinct states at (${C(/* @__PURE__ */ new Date)})`);return}case`liveness-finished`:Po(e,n);return;case`warning`:i(t.code,O.warning,t.text)}},Po=(e,t)=>{t.liveness!==void 0&&(e.print(w.checkingTemporalEnd,O.none,`Finished checking temporal properties in ${te(Date.now()-t.liveness)} at ${C(/* @__PURE__ */ new Date)}`),t.liveness=void 0)},Fo=(e,t,n)=>{let r=n.print,i=t.name,a=t.loopStart,o=a===void 0&&t.trace.length===1&&(e===`invariant-violation`||e===`liveness-violation`),s={code:w.temporalPropertyViolated,text:Do(t.properties??[i],n.version)},c={success:void 0,error:void 0,"assumption-violation":t.message?{code:w.assumptionEvaluationError,text:v(w.assumptionEvaluationError,`Evaluating assumption ${i} failed.\n${t.message}`,n.isTool)}:{code:w.assumptionFalse,text:`Assumption ${i} is false.`},deadlock:{code:w.deadlockReached,text:`Deadlock reached.`},"invariant-violation":o?Co(`invariant-violation`,i):{code:w.invariantViolatedBehavior,text:`Invariant ${i} is violated.`},"property-violation":s,"liveness-violation":a===void 0?o?Co(`liveness-violation`,i):{code:w.actionPropertyViolatedBehavior,text:`Action property ${i} is violated.`}:s,"postcondition-violation":{code:t.postcondition?.code??w.general,text:t.message??`Postcondition ${i} is false.`}}[e],l=e===`property-violation`,u=a!==void 0&&!l,d=l||u,f=d&&n.version!==`1.7.4`;if(f&&wo(n,t.trace[0]?.output),t.counts&&console.log(t.counts),c){let e=o?`${c.text}\n${se(t.trace[0].state)}`:c.text;r(c.code,O.error,e)}if(o||(d||wo(n,t.trace[0]?.output),To(n,t.trace,d?Eo:void 0,d&&!f),wo(n,t.traceOutput)),u){let e=t.loopLabel;a===t.trace.length-1?r(w.statePrint3,O.state,`${a+2}: Stuttering`):n.isTool?r(w.backToState,O.state,`${a+1}: Back to state${e?`: <${e}>\n`:``}`):console.log(`Back to state ${a+1}${e?`: <${e}>\n`:``}`)}t.warning&&n.version!==`1.7.4`&&r(t.warning.code,O.warning,t.warning.text);let p=t.unwitnessed??(e===`postcondition-violation`?void 0:t.postcondition);return p?.counts&&console.log(p.counts),p&&r(p.code,O.error,p.message),!o&&e!==`assumption-violation`},Io=(e,t)=>e.print(w.nestedExpression,O.error,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${ko(t)}`),Lo=(e,t,r)=>{let i=t.print;if(e.failure){let r=e.failure,s=t.isTool?r.toolMessage:r.message,c=()=>{let e=r.fingerprint;if(e){let n=r.callStack?.length&&t.version!==`1.7.4`?ko(r.callStack):Oo(e.sources);i(w.fingerprintFailed,O.error,`TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${n}\nReason:\n${A(e.reason,t.isTool)}`)}else r.callStack&&Io(t,r.callStack)};r.isCallStackFirst&&c();let u=r.initialState&&(()=>{try{return`While working on the initial state:\n${se(r.initialState)}`}catch(e){throw e instanceof l?a(new l(`${n}${e.message}`),o.error):e}})();i(u?w.initialState:r.code,O.error,u?`${s}\n${u}`:s),wo(t,r.trace[0]?.output),To(t,r.trace);let d=r.traceFailure;d&&i(d.code,O.error,t.isTool?d.toolMessage:d.message),wo(t,r.traceOutput);let f=r.postcondition;f?.counts&&console.log(f.counts),f&&i(f.code,O.error,f.message),r.isCallStackFirst||c()}else if(e.violation){if(!Fo(e.status,e.violation,t))return;let n=e.additionalViolation;n&&Fo(`property-violation`,n,t),e.liveCallStack&&Io(t,e.liveCallStack)}else{Po(t,r);let n=ne(e.distinctStates,e.generatedStates),a=e.fingerprintDistance===void 0?[]:[` based on the actual fingerprints: val = ${N(ie(e.fingerprintDistance))}`];i(w.success,O.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 = ${N(n)}`,...a].join(`
|
|
38
|
+
`))}if(e.failure?.isWithoutStatistics)return;e.status!==`success`&&Po(t,r),t.isTool&&jo(t,e,r.start),i(w.stats,O.none,`${e.generatedStates} states generated, ${e.distinctStates} distinct states found, ${e.queuedStates} states left on queue.`);let s=t.version===`1.7.4`,c=s?e.outDegrees??e.violationOutDegrees:e.outDegrees;(!s||c)&&i(w.searchDepth,O.none,`The depth of the complete state graph search is ${s?Math.max(e.depth,1):e.depth}.`);let u=c&&le(c);u&&i(w.stateGraphOutdegree,O.none,u)},Ro=(e,t)=>e.map(e=>je(e,`${t}.tla`)).find(I),zo=e=>t=>{let n=Ro(e,t);return n===void 0?void 0:L(n,`utf8`)},Bo=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),Vo=e=>`jar:file:${qe(Me(e)).pathname}!/tla2sany/StandardModules/`,Ho=e=>x([e]).toString(),Uo=(e,t,n,r,i)=>{let a=n.temporaryDirectory??Ge(),o=I(a)?Le(a):Me(a),s=je(o,`tlc-${Ho(Me(e))}`),c=Ds(n);return(n,a)=>{let l=`${n}.tla`;if(a===`file`)return Le(Ro(t,n)??e);if(i===`1.7.4`)return je(o,l);if(a===`root file`){let t=r===void 0?o:Me(r),i=Le(e);return`${je(t,Ho(`${i} ${n}`),l)} (${i})`}let u=je(s,l);return c===void 0?u:`${u} (${Vo(c)}${l})`}},Wo=e=>e.print(w.version,O.none,`TLC2 Version ${Ye} (rev: tla-ts)`),Go=(e,t)=>(Wo(e),e.print(w.commandLineError,O.error,`${t}\nUsage: java tlc2.TLC [-help] [-option] inputfile`),1),Ko=(e,t,n)=>e.print(w.modelChecking,O.none,`Running breadth-first search Model-Checking with fp 0 and seed ${BigInt(t)} with ${n} worker${n===1?``:`s`} on ${Ue()} cores with ${Math.floor(Je().heap_size_limit/1024/1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${Ke()} ${We()} ${He()}, Node.js ${process.versions.node} ${process.arch.endsWith(`64`)?64:32}bit, MemFPSet, MemStateQueue).`),qo=(e,t)=>{let n=[...e.unknown,...e.options.map(e=>e.name)],r=(e,t=e)=>n.some(n=>n===e||n.toLowerCase()===t.toLowerCase()),i=r(`-generateSpecTE`)||!r(`-noGenerateSpecTE`,`-noTE`)&&!r(`-tool`)&&!r(`-continue`);return t!==`1.7.4`&&i&&!r(`-noGenerateSpecTEBin`,`-noTEBin`)},Jo=async(e,n,a,s)=>{let c=n.has(`-seed`)?n.get(`-seed`)?.[0]:`0`;if(c===void 0)return Go(s,`Error: seed required.`);if(!_o(c))return Go(s,`Error: An integer for seed required. But encountered ${c}`);let l=n.has(`-lncheck`)?n.get(`-lncheck`)?.[0]?.toLowerCase():`default`;if(l===void 0)return Go(s,`Error: expect a strategy such as final for -lncheck option.`);let d=n.get(`-dump`);if(d?.length===0)return Go(s,`Error: A file name for dumping states required.`);let p=d?.length===2&&yo.find(e=>d[0].toLowerCase().includes(e));if(p)return console.error(`Error: tla-ts does not support the -dump format ${p}.`),1;let m=n.get(`-fp`)?.[0];if(m!==void 0&&Number(m)!==0)return console.error(`Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${m}.`),1;let h=vo(n.get(`-workers`)),_=s.version;Wo(s),Ko(s,c,h);let v=n.get(`-config`)?.[0]??(n.has(`-config`)?void 0:e.replace(/\.tla$/,`.cfg`));if(!v||!I(v))return s.print(w.configFileError,O.error,`TLC encountered the following error when trying to read the configuration file ${v??``}:\nFile not found.`),o.configParseError;let b=De(e,`.tla`),x={start:Date.now(),liveness:void 0,isParsed:!1},S=()=>{let e=Date.now()-x.start;s.print(w.finished,O.none,`Finished in ${s.isTool?`${e}ms`:te(e)} at (${C(/* @__PURE__ */ new Date)})`)},ee=()=>s.print(w.parsingFailed,O.error,`Parsing or semantic analysis failed.`),T=e=>(e instanceof t?ee():Xo(e,s),S(),r(e)),k=(()=>{try{return D(L(v,`utf8`),_)}catch(e){if(!(e instanceof f))throw e;return e}})();if(k instanceof f&&_===`1.7.4`)return s.print(w.general,O.error,`${g(`tlc2.tool.ConfigFileException`)}${A(k.message,s.isTool)}`),S(),o.error;if(k instanceof f)return T(k);n.has(`-deadlock`)&&(k.checkDeadlock=!1);let j=ke(e),ne=[j,...a.libraries],re=zo(ne),ie=qo(n,_),M=async()=>{let t=L(e,`utf8`),r=E(t).name;if(r!==b)throw new i(`File name '${b}' does not match the name '${r}' of the top level module it contains.`,void 0);let a=await ge({workers:h,livenessCheck:[`final`,`seqfinal`,`off`].includes(l)?`final`:`default`,seed:BigInt(c),dump:d&&xo(d),isTool:s.isTool,isTraceRecorded:ie,isSanyReported:!0,isWarningEnabled:!n.has(`-nowarning`),version:_,onProgress:e=>No(s,e,x,j),source:t,config:k,onPause:()=>Fe(0,Buffer.alloc(1)),loadModule:re,loadClass:e=>{let t=Mo(j,e);return I(t)?L(t):void 0},readFile:e=>I(e)?L(e,`utf8`):void 0,writeFile:(e,t)=>{Pe(ke(Me(e)),{recursive:!0}),Ve(e,t)}});return Lo(a,s,x),S(),a.failure?.exitCode??ao[a.status]};s.isTool&&s.print(w.startingSany,O.none,`Starting SANY...`);let ae=Ae(e),N=ae?b:e.replace(/\.tla$/,``),oe=Ds(a),se=_===`1.7.4`?Ss(e,a,oe):void 0;if(se?!I(e)&&!y.has(b)&&se(`${b}.tla`):!I(e)&&!ue.has(b)&&Bo(ae?j:process.cwd(),ae?`${b}.tla`:`./${N}.tla`,[...ae||j===`.`?[]:[j],...a.libraries]),Pa(e,se?Cs(re,se):re,{fileName:N,describeFile:Uo(e,ne,a,n.get(`-metadir`)?.[0],_),version:_,rootExtendees:ie?[`_TLCTrace`]:void 0,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}).isFailed)return No(s,{kind:`parsed`},x,j),ee(),S(),o.specParseError;try{return await M()}catch(e){if(!(e instanceof u))throw e;return e instanceof t&&console.log(Yo(e,b)),x.isParsed||No(s,{kind:`parsed`},x,j),T(e)}},Yo=(e,t)=>{let n=e instanceof i;if(!n&&!e.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${e.message}\n\n`;let r=n?e.location===void 0?`Unknown location\n\n${e.message}`:`In module ${e.location}\n\n${e.message}`:`In module ${t}\n\nCould not parse module ${t} from file ${t}.tla`;return`${e.failure?`***Parse Error***\n${e.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${t}\n\n${r}\n*** Errors: 1\n\n${r}\n\n\n`},Xo=(e,t)=>{if(e instanceof f||e instanceof l){let n=j(e.message),r=n&&!n.isEvalException?n.code:w.general;return t.print(r,O.error,v(r,e.message,t.isTool))}console.error(`${e.name}: ${e.message}`)},Zo=async(e,t=de(!1))=>{try{return await e()}catch(e){if(!(e instanceof u))throw e;return Xo(e,t),r(e)}},Qo=async(e,t,n)=>{let r=[];for(let[i,a]of e.entries()){i>0&&console.log(``);let e=n();r.push(await Zo(()=>t(a,e),e))}return r.find(e=>e!==o.success)??o.success},$o=()=>Ee().map(e=>je(ke(ke(Le(e))),`lib/tlapm/stdlib`)).find(e=>I(e)),es=e=>e.flatMap(e=>ho.test(e)?Ne(e).sort():[e]),ts=e=>I(e)?{file:e,source:L(e,`utf8`)}:void 0,ns=e=>console.error(`@!!BEGIN\n${e.map(e=>`@!!${e}\n`).join(``)}@!!END\n`),rs=(e,t,n)=>ns([`type:obligation`,`id:${e.id}`,`loc:${e.location}`,`status:${t}`,...n]),is=`9ed0376`,as=e=>/^[+,\-./0-9:=@A-Z_a-z]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`,os=e=>console.log(`\n\\* TLAPM version ${is}\n\\* launched at ${C(/* @__PURE__ */ new Date)} with command line:\n\\* ${[`tla-ts`,`tlapm`,...e].map(as).join(` `)}\n`),ss={failed:10,incomplete:11,emptyTarget:12},cs=(e,t,n)=>{let r=e.summary;n||(r.absent.forEach(e=>console.error(`Missing proof at ${P(e)}`)),r.omitted.forEach(e=>console.error(`Omitted proof at ${P(e)}`)));let i=r.absent.length+r.omitted.length>0;i&&console.error(`${ye(e.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(e.name)}: ${r.absent.length} missing, ${r.omitted.length} omitted proof step(s).`);let a=t&&e.obligations.length===0;return a&&console.error(`${ye(e.location)}[ERROR]: No proof obligation found for the selected target.`),[...i?[ss.incomplete]:[],...a?[ss.emptyTarget]:[]]},ls=t=>{try{return t()}catch(t){if(!(t instanceof e))throw t;console.error(` tlapm ending abnormally with ${t.exception}\n`);return}},us=e=>{let t=lo.parse(e),n=t.get(`--backend`)?.[0];if(t.unknown[0]!==void 0||t.incomplete||n!==void 0&&!_e(n))return console.error(`Usage: ${lo.usage}`),1;let r=es(t.positionals).map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(r.length===0)return console.error(`Usage: ${lo.usage}`),1;let i=$o(),a=t.options.flatMap(e=>e.name===`-I`?e.values:[]);return Qo(r,async e=>{let r=[ke(e),`.`,...i?[i]:[],...a.toReversed()],s=await fe({source:L(e,`utf8`),loadModule:e=>r.map(t=>ts(`${t}/${e}.tla`)).find(Boolean)?.source,backend:n,workers:vo(t.get(`-workers`)),onObligation:t=>console.log(`${e}:${t.location}: ${t.status}${t.status===`proved`?` by ${t.prover}`:``}${t.status===`failed`||t.status===`unsupported`?` (${t.reason})`:``}`)}),c=Map.groupBy(s.obligations,e=>e.status),l=e=>c.get(e)?.length??0;return console.log(`${s.obligations.length} obligations: ${l(`proved`)} proved, ${l(`trivial`)} trivial, ${l(`failed`)} failed, ${l(`unsupported`)} unsupported`),l(`failed`)+l(`unsupported`)===0?o.success:1},()=>de(!1))},ds=(e,t)=>{let n=t.method.timeLimitMs,r=t.timeUsedMs===void 0?``:`; time-used: ${(t.timeUsedMs/1e3).toFixed(1)} (${Math.round(100*t.timeUsedMs/n)}%)`,i=n===0?``:`time-limit: ${n===1/0?`inf`:Number((n/1e3).toPrecision(6))}${r}`,a=[t.method.tactic,i].filter(Boolean).join(`; `),o=(t.method.prover===`smt`||t.method.prover===`z3`)&&t.reason===`false`&&t.verdict?`(* SMT failed with status = ${t.verdict}\n *)\n`:``;rs(e,t.isProved?`proved`:`failed`,[`prover:${t.method.prover}`,...a===``?[]:[`meth:${a}`],...t.reason===void 0?[]:[`reason:${t.reason}`],`already:${t.isReused}`,...t.isProved?[]:[`obl:${t.isReused?``:`\n${o}`}${Ce(e,t.isReused)}`]])},fs=(e,t)=>rs(e,`failed`,[`prover:fail`,`meth:time-limit: inf`,`reason:${t}`,`already:false`,`obl:${e.text}`]),ps=async(e,t,n,r,i)=>{xt(n,r);let a=gt(i.fingerprints),o=await xe(e.obligations,{workers:i.workers,results:a,isFingerprinted:i.isFingerprinted,isProving:i.isProving,onReport:(e,t)=>{if(i.isToolbox){if(e.obligation.status===`trivial`)return rs(t,`trivial`,[`prover:tlapm`,`already:false`]);if(t.kind.kind===`Error`)return fs(t,`user error`);e.attempts.forEach(e=>ds(t,e))}}});if(Ve(t,be(e.name,o,e.obligations)),console.log(`(* created new ${JSON.stringify(t)} *)`),vt(i.fingerprints,a),St(i.fingerprints,n),console.log(`(* fingerprints written in ${JSON.stringify(n)} *)`),!i.isProving)return!1;let s=o.flatMap((t,n)=>`reason`in t.obligation?[{report:t,obligation:e.obligations[n]}]:[]);i.isToolbox&&s.filter(e=>e.report.attempts.length===0&&e.obligation.kind.kind!==`Error`).forEach(e=>fs(e.obligation,`unexpected error`)),s.toReversed().forEach(e=>console.error(`${ye(e.obligation.locus)}${Se(he(`[ERROR]: @[<v2>Could not prove or check:@,%a@]`,me(e.obligation.sequent)),35)}`));let c=`${e.obligations.length} obligation${e.obligations.length>1?`s`:``}`;return console.error(s.length===0?`${ye(e.location)}[INFO]: All ${c} proved.`:`${ye(e.location)}[ERROR]: ${s.length}/${c} failed.\nThere were backend errors processing module \`${JSON.stringify(e.name)}\`.`),s.length>0},ms=async t=>{let n=so.parse(t),r=!n.has(`-N`)&&!n.has(`--summary`),i=n.unknown[0]??(r&&n.has(`--printallobs`)?`--printallobs`:void 0);if(i!==void 0)return console.error(`Error: tla-ts tlapm does not support the tlapm option ${i}.`),1;if(n.incomplete)return console.error(`Error: option '${n.incomplete.name}' needs an argument.`),1;let a=n.options.find(e=>co.has(e.name)&&e.values.some(e=>!/^-?\d+$/.test(e)));if(a)return console.error(`Error: option '${a.name}' expects an integer.`),1;if(n.has(`--version`))return console.log(is),o.success;let s=es(n.positionals),c=s.map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(c.length===0)return console.error(mo),1;let l=n.has(`--toolbox`)||n.has(`--line`);l&&os(t);let u=n.options.reduce((e,t)=>{let[n,r]=t.values.map(Number);return t.name===`--toolbox`?{start:n,end:r===0?1/0:r}:t.name===`--line`?n===0?pe:{start:n,end:n}:e},pe),d=$o(),f=n.options.flatMap(e=>e.name===`-I`?e.values:[]),p=c.reduce((e,t)=>e.includes(ke(t))?e:[ke(t),...e],[`.`,...d?[d]:[],...f.toReversed()]),m=/* @__PURE__ */ new Set,h=ls(()=>{let t=c.findIndex(e=>!I(e));if(t!==-1){let n=s[t];throw console.error(`File "<unknown>":\nError: File ${JSON.stringify(n)} not found`),new e(`File ${n} not found`,{failure:`Module.Parser.parse_file`})}return Te(c.map(e=>({file:`./${e}`,source:L(e,`utf8`)})),e=>(m.add(e),p.map(t=>ts(`${t}/${e}.tla`)).find(Boolean)??(e===`TLAPS`?{file:`TLAPS.tla`,source:`------------------------------- MODULE TLAPS --------------------------------
|
|
39
|
+
|
|
40
|
+
(* Backend pragmas. *)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
(***************************************************************************)
|
|
44
|
+
(* Each of these pragmas can be cited with a BY or a USE. The pragma that *)
|
|
45
|
+
(* is added to the context of an obligation most recently is the one whose *)
|
|
46
|
+
(* effects are triggered. *)
|
|
47
|
+
(***************************************************************************)
|
|
48
|
+
|
|
49
|
+
(***************************************************************************)
|
|
50
|
+
(* The following pragmas should be used only as a last resource. They are *)
|
|
51
|
+
(* dependent upon the particular backend provers, and are unlikely to have *)
|
|
52
|
+
(* any effect if the set of backend provers changes. Moreover, they are *)
|
|
53
|
+
(* meaningless to a reader of the proof. *)
|
|
54
|
+
(***************************************************************************)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
(**************************************************************************)
|
|
58
|
+
(* Backend pragma: use the SMT solver for arithmetic. *)
|
|
59
|
+
(* *)
|
|
60
|
+
(* This method exists under this name for historical reasons. *)
|
|
61
|
+
(**************************************************************************)
|
|
62
|
+
|
|
63
|
+
SimpleArithmetic == TRUE (*{ by (prover:"smt3") }*)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
(**************************************************************************)
|
|
67
|
+
(* Backend pragma: SMT solver *)
|
|
68
|
+
(* *)
|
|
69
|
+
(* This method translates the proof obligation to SMTLIB2. The supported *)
|
|
70
|
+
(* fragment includes first-order logic, set theory, functions and *)
|
|
71
|
+
(* records. *)
|
|
72
|
+
(* SMT calls the smt-solver with the default timeout of 5 seconds *)
|
|
73
|
+
(* while SMTT(n) calls the smt-solver with a timeout of n seconds. *)
|
|
74
|
+
(* *)
|
|
75
|
+
(* SMTT also accepts a string argument of the form "rN" to bound the *)
|
|
76
|
+
(* underlying Z3 solver by a deterministic \`rlimit\` budget instead of a *)
|
|
77
|
+
(* wall-clock timeout, e.g. SMTT("r5"). N is a multiple of a fixed base *)
|
|
78
|
+
(* resource count, so a small readable budget like "r5" is meaningful. *)
|
|
79
|
+
(* Unlike a wall-clock timeout, an \`rlimit\` budget does not depend on CPU *)
|
|
80
|
+
(* speed or load, so the proof's pass/fail outcome reproduces on any *)
|
|
81
|
+
(* machine and every rerun (for a fixed Z3 build); how long it takes to *)
|
|
82
|
+
(* consume the budget still varies by machine. This is Z3-specific. *)
|
|
83
|
+
(**************************************************************************)
|
|
84
|
+
|
|
85
|
+
SMT == TRUE (*{ by (prover:"smt3") }*)
|
|
86
|
+
SMTT(X) == TRUE (*{ by (prover:"smt3"; timeout:@) }*)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
(**************************************************************************)
|
|
90
|
+
(* Backend pragma: CVC4 SMT solver *)
|
|
91
|
+
(* *)
|
|
92
|
+
(* These methods translate the proof obligation to SMTLIB2 and call CVC4. *)
|
|
93
|
+
(**************************************************************************)
|
|
94
|
+
|
|
95
|
+
(* The CVC3* methods are here for backward compatibility. They call CVC4. *)
|
|
96
|
+
CVC3 == TRUE (*{ by (prover: "cvc33") }*)
|
|
97
|
+
CVC3T(X) == TRUE (*{ by (prover:"cvc33"; timeout:@) }*)
|
|
98
|
+
|
|
99
|
+
CVC4 == TRUE (*{ by (prover: "cvc33") }*)
|
|
100
|
+
CVC4T(X) == TRUE (*{ by (prover:"cvc33"; timeout:@) }*)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
(**************************************************************************)
|
|
104
|
+
(* Backend pragma: Yices SMT solver *)
|
|
105
|
+
(* *)
|
|
106
|
+
(* This method translates the proof obligation to Yices native language. *)
|
|
107
|
+
(**************************************************************************)
|
|
108
|
+
|
|
109
|
+
Yices == TRUE (*{ by (prover: "yices3") }*)
|
|
110
|
+
YicesT(X) == TRUE (*{ by (prover:"yices3"; timeout:@) }*)
|
|
111
|
+
|
|
112
|
+
(**************************************************************************)
|
|
113
|
+
(* Backend pragma: veriT SMT solver *)
|
|
114
|
+
(* *)
|
|
115
|
+
(* This method translates the proof obligation to SMTLIB2 and calls veriT.*)
|
|
116
|
+
(**************************************************************************)
|
|
117
|
+
|
|
118
|
+
veriT == TRUE (*{ by (prover: "verit") }*)
|
|
119
|
+
veriTT(X) == TRUE (*{ by (prover:"verit"; timeout:@) }*)
|
|
120
|
+
|
|
121
|
+
(**************************************************************************)
|
|
122
|
+
(* Backend pragma: Zipperposition solver *)
|
|
123
|
+
(* *)
|
|
124
|
+
(* This method translates the proof obligation to TPTP and *)
|
|
125
|
+
(* calls Zipperposition. *)
|
|
126
|
+
(**************************************************************************)
|
|
127
|
+
|
|
128
|
+
Zipper == TRUE (*{ by (prover: "zipper") }*)
|
|
129
|
+
ZipperT(X) == TRUE (*{ by (prover:"zipper"; timeout:@) }*)
|
|
130
|
+
|
|
131
|
+
(**************************************************************************)
|
|
132
|
+
(* Backend pragma: Z3 SMT solver *)
|
|
133
|
+
(* *)
|
|
134
|
+
(* This method translates the proof obligation to SMTLIB2 and calls Z3. *)
|
|
135
|
+
(* Z3 is used by default but you can also explicitly call it. *)
|
|
136
|
+
(* Z3T(n) bounds Z3 by a wall-clock timeout of n seconds, while Z3T("rN") *)
|
|
137
|
+
(* bounds it by a deterministic \`rlimit\` budget of N base units, which *)
|
|
138
|
+
(* reproduces the same outcome on any machine (see SMTT). *)
|
|
139
|
+
(**************************************************************************)
|
|
140
|
+
|
|
141
|
+
Z3 == TRUE (*{ by (prover: "z33") }*)
|
|
142
|
+
Z3T(X) == TRUE (*{ by (prover:"z33"; timeout:@) }*)
|
|
143
|
+
|
|
144
|
+
(**************************************************************************)
|
|
145
|
+
(* Backend pragma: SPASS superposition prover *)
|
|
146
|
+
(* *)
|
|
147
|
+
(* This method translates the proof obligation to the DFG format language *)
|
|
148
|
+
(* supported by the ATP SPASS. The translation is based on the SMT one. *)
|
|
149
|
+
(**************************************************************************)
|
|
150
|
+
|
|
151
|
+
Spass == TRUE (*{ by (prover: "spass") }*)
|
|
152
|
+
SpassT(X) == TRUE (*{ by (prover:"spass"; timeout:@) }*)
|
|
153
|
+
|
|
154
|
+
(**************************************************************************)
|
|
155
|
+
(* Backend pragma: The PTL propositional linear time temporal logic *)
|
|
156
|
+
(* prover. It currently is the LS4 backend. *)
|
|
157
|
+
(* *)
|
|
158
|
+
(* This method translates the negetation of the proof obligation to *)
|
|
159
|
+
(* Seperated Normal Form (TRP++ format) and checks for unsatisfiability *)
|
|
160
|
+
(**************************************************************************)
|
|
161
|
+
|
|
162
|
+
LS4 == TRUE (*{ by (prover: "ls4") }*)
|
|
163
|
+
LS4T(X) == TRUE (*{ by (prover: "ls4"; timeout:@) }*)
|
|
164
|
+
PTL == TRUE (*{ by (prover: "ls4") }*)
|
|
165
|
+
|
|
166
|
+
(**************************************************************************)
|
|
167
|
+
(* Backend pragma: Zenon with different timeouts (default is 10 seconds) *)
|
|
168
|
+
(* *)
|
|
169
|
+
(**************************************************************************)
|
|
170
|
+
|
|
171
|
+
Zenon == TRUE (*{ by (prover:"zenon") }*)
|
|
172
|
+
ZenonT(X) == TRUE (*{ by (prover:"zenon"; timeout:@) }*)
|
|
173
|
+
|
|
174
|
+
(********************************************************************)
|
|
175
|
+
(* Backend pragma: Isabelle with different timeouts and tactics *)
|
|
176
|
+
(* (default is 30 seconds/auto) *)
|
|
177
|
+
(********************************************************************)
|
|
178
|
+
|
|
179
|
+
Isa == TRUE (*{ by (prover:"isabelle") }*)
|
|
180
|
+
IsaT(X) == TRUE (*{ by (prover:"isabelle"; timeout:@) }*)
|
|
181
|
+
IsaM(X) == TRUE (*{ by (prover:"isabelle"; tactic:@) }*)
|
|
182
|
+
IsaMT(X,Y) == TRUE (*{ by (prover:"isabelle"; tactic:@; timeout:@) }*)
|
|
183
|
+
|
|
184
|
+
(***************************************************************************)
|
|
185
|
+
(* The following theorem expresses the (useful implication of the) law of *)
|
|
186
|
+
(* set extensionality, which can be written as *)
|
|
187
|
+
(* *)
|
|
188
|
+
(* THEOREM \\A S, T : (S = T) <=> (\\A x : (x \\in S) <=> (x \\in T)) *)
|
|
189
|
+
(* *)
|
|
190
|
+
(* Theorem SetExtensionality is sometimes required by the SMT backend for *)
|
|
191
|
+
(* reasoning about sets. It is usually counterproductive to include *)
|
|
192
|
+
(* theorem SetExtensionality in a BY clause for the Zenon or Isabelle *)
|
|
193
|
+
(* backends. Instead, use the pragma IsaWithSetExtensionality to instruct *)
|
|
194
|
+
(* the Isabelle backend to use the rule of set extensionality. *)
|
|
195
|
+
(***************************************************************************)
|
|
196
|
+
IsaWithSetExtensionality == TRUE
|
|
197
|
+
(*{ by (prover:"isabelle"; tactic:"(auto intro: setEqualI)")}*)
|
|
198
|
+
|
|
199
|
+
THEOREM SetExtensionality == \\A S,T : (\\A x : x \\in S <=> x \\in T) => S = T
|
|
200
|
+
OBVIOUS
|
|
201
|
+
|
|
202
|
+
(***************************************************************************)
|
|
203
|
+
(* The following theorem is needed to deduce NotInSetS \\notin SetS from *)
|
|
204
|
+
(* the definition *)
|
|
205
|
+
(* *)
|
|
206
|
+
(* NotInSetS == CHOOSE v : v \\notin SetS *)
|
|
207
|
+
(***************************************************************************)
|
|
208
|
+
THEOREM NoSetContainsEverything == \\A S : \\E x : x \\notin S
|
|
209
|
+
OBVIOUS (*{by (isabelle "(auto intro: inIrrefl)")}*)
|
|
210
|
+
-----------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
(********************************************************************)
|
|
215
|
+
(********************************************************************)
|
|
216
|
+
(********************************************************************)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
(********************************************************************)
|
|
220
|
+
(* Old versions of Zenon and Isabelle pragmas below *)
|
|
221
|
+
(* (kept for compatibility) *)
|
|
222
|
+
(********************************************************************)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
(**************************************************************************)
|
|
226
|
+
(* Backend pragma: Zenon with different timeouts (default is 10 seconds) *)
|
|
227
|
+
(* *)
|
|
228
|
+
(**************************************************************************)
|
|
229
|
+
|
|
230
|
+
SlowZenon == TRUE (*{ by (prover:"zenon"; timeout:20) }*)
|
|
231
|
+
SlowerZenon == TRUE (*{ by (prover:"zenon"; timeout:40) }*)
|
|
232
|
+
VerySlowZenon == TRUE (*{ by (prover:"zenon"; timeout:80) }*)
|
|
233
|
+
SlowestZenon == TRUE (*{ by (prover:"zenon"; timeout:160) }*)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
(********************************************************************)
|
|
238
|
+
(* Backend pragma: Isabelle's automatic search ("auto") *)
|
|
239
|
+
(* *)
|
|
240
|
+
(* This pragma bypasses Zenon. It is useful in situations involving *)
|
|
241
|
+
(* essentially simplification and equational reasoning. *)
|
|
242
|
+
(* Default imeout for all isabelle tactics is 30 seconds. *)
|
|
243
|
+
(********************************************************************)
|
|
244
|
+
Auto == TRUE (*{ by (prover:"isabelle"; tactic:"auto") }*)
|
|
245
|
+
SlowAuto == TRUE (*{ by (prover:"isabelle"; tactic:"auto"; timeout:120) }*)
|
|
246
|
+
SlowerAuto == TRUE (*{ by (prover:"isabelle"; tactic:"auto"; timeout:480) }*)
|
|
247
|
+
SlowestAuto == TRUE (*{ by (prover:"isabelle"; tactic:"auto"; timeout:960) }*)
|
|
248
|
+
|
|
249
|
+
(********************************************************************)
|
|
250
|
+
(* Backend pragma: Isabelle's "force" tactic *)
|
|
251
|
+
(* *)
|
|
252
|
+
(* This pragma bypasses Zenon. It is useful in situations involving *)
|
|
253
|
+
(* quantifier reasoning. *)
|
|
254
|
+
(********************************************************************)
|
|
255
|
+
Force == TRUE (*{ by (prover:"isabelle"; tactic:"force") }*)
|
|
256
|
+
SlowForce == TRUE (*{ by (prover:"isabelle"; tactic:"force"; timeout:120) }*)
|
|
257
|
+
SlowerForce == TRUE (*{ by (prover:"isabelle"; tactic:"force"; timeout:480) }*)
|
|
258
|
+
SlowestForce == TRUE (*{ by (prover:"isabelle"; tactic:"force"; timeout:960) }*)
|
|
259
|
+
|
|
260
|
+
(***********************************************************************)
|
|
261
|
+
(* Backend pragma: Isabelle's "simplification" tactics *)
|
|
262
|
+
(* *)
|
|
263
|
+
(* These tactics simplify the goal before running one of the automated *)
|
|
264
|
+
(* tactics. They are often necessary for obligations involving record *)
|
|
265
|
+
(* or tuple projections. Use the SimplfyAndSolve tactic unless you're *)
|
|
266
|
+
(* sure you can get away with just Simplification *)
|
|
267
|
+
(***********************************************************************)
|
|
268
|
+
SimplifyAndSolve == TRUE
|
|
269
|
+
(*{ by (prover:"isabelle"; tactic:"clarsimp auto?") }*)
|
|
270
|
+
SlowSimplifyAndSolve == TRUE
|
|
271
|
+
(*{ by (prover:"isabelle"; tactic:"clarsimp auto?"; timeout:120) }*)
|
|
272
|
+
SlowerSimplifyAndSolve == TRUE
|
|
273
|
+
(*{ by (prover:"isabelle"; tactic:"clarsimp auto?"; timeout:480) }*)
|
|
274
|
+
SlowestSimplifyAndSolve == TRUE
|
|
275
|
+
(*{ by (prover:"isabelle"; tactic:"clarsimp auto?"; timeout:960) }*)
|
|
276
|
+
|
|
277
|
+
Simplification == TRUE (*{ by (prover:"isabelle"; tactic:"clarsimp") }*)
|
|
278
|
+
SlowSimplification == TRUE
|
|
279
|
+
(*{ by (prover:"isabelle"; tactic:"clarsimp"; timeout:120) }*)
|
|
280
|
+
SlowerSimplification == TRUE
|
|
281
|
+
(*{ by (prover:"isabelle"; tactic:"clarsimp"; timeout:480) }*)
|
|
282
|
+
SlowestSimplification == TRUE
|
|
283
|
+
(*{ by (prover:"isabelle"; tactic:"clarsimp"; timeout:960) }*)
|
|
284
|
+
|
|
285
|
+
(**************************************************************************)
|
|
286
|
+
(* Backend pragma: Isabelle's tableau prover ("blast") *)
|
|
287
|
+
(* *)
|
|
288
|
+
(* This pragma bypasses Zenon and uses Isabelle's built-in theorem *)
|
|
289
|
+
(* prover, Blast. It is almost never better than Zenon by itself, but *)
|
|
290
|
+
(* becomes very useful in combination with the Auto pragma above. The *)
|
|
291
|
+
(* AutoBlast pragma first attempts Auto and then uses Blast to prove what *)
|
|
292
|
+
(* Auto could not prove. (There is currently no way to use Zenon on the *)
|
|
293
|
+
(* results left over from Auto.) *)
|
|
294
|
+
(**************************************************************************)
|
|
295
|
+
Blast == TRUE (*{ by (prover:"isabelle"; tactic:"blast") }*)
|
|
296
|
+
SlowBlast == TRUE (*{ by (prover:"isabelle"; tactic:"blast"; timeout:120) }*)
|
|
297
|
+
SlowerBlast == TRUE (*{ by (prover:"isabelle"; tactic:"blast"; timeout:480) }*)
|
|
298
|
+
SlowestBlast == TRUE (*{ by (prover:"isabelle"; tactic:"blast"; timeout:960) }*)
|
|
299
|
+
|
|
300
|
+
AutoBlast == TRUE (*{ by (prover:"isabelle"; tactic:"auto, blast") }*)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
(**************************************************************************)
|
|
304
|
+
(* Backend pragmas: multi-back-ends *)
|
|
305
|
+
(* *)
|
|
306
|
+
(* These pragmas just run a bunch of back-ends one after the other in the *)
|
|
307
|
+
(* hope that one will succeed. This saves time and effort for the user at *)
|
|
308
|
+
(* the expense of computation time. *)
|
|
309
|
+
(**************************************************************************)
|
|
310
|
+
|
|
311
|
+
(* CVC3 goes first because it's bundled with TLAPS, then the other SMT
|
|
312
|
+
solvers are unlikely to succeed if CVC3 fails, so we run zenon and
|
|
313
|
+
Isabelle before them. *)
|
|
314
|
+
AllProvers == TRUE (*{
|
|
315
|
+
by (prover:"cvc33")
|
|
316
|
+
by (prover:"zenon")
|
|
317
|
+
by (prover:"isabelle"; tactic:"auto")
|
|
318
|
+
by (prover:"spass")
|
|
319
|
+
by (prover:"smt3")
|
|
320
|
+
by (prover:"yices3")
|
|
321
|
+
by (prover:"verit")
|
|
322
|
+
by (prover:"z33")
|
|
323
|
+
by (prover:"isabelle"; tactic:"force")
|
|
324
|
+
by (prover:"isabelle"; tactic:"(auto intro: setEqualI)")
|
|
325
|
+
by (prover:"isabelle"; tactic:"clarsimp auto?")
|
|
326
|
+
by (prover:"isabelle"; tactic:"clarsimp")
|
|
327
|
+
by (prover:"isabelle"; tactic:"auto, blast")
|
|
328
|
+
}*)
|
|
329
|
+
AllProversT(X) == TRUE (*{
|
|
330
|
+
by (prover:"cvc33"; timeout:@)
|
|
331
|
+
by (prover:"zenon"; timeout:@)
|
|
332
|
+
by (prover:"isabelle"; tactic:"auto"; timeout:@)
|
|
333
|
+
by (prover:"spass"; timeout:@)
|
|
334
|
+
by (prover:"smt3"; timeout:@)
|
|
335
|
+
by (prover:"yices3"; timeout:@)
|
|
336
|
+
by (prover:"verit"; timeout:@)
|
|
337
|
+
by (prover:"z33"; timeout:@)
|
|
338
|
+
by (prover:"isabelle"; tactic:"force"; timeout:@)
|
|
339
|
+
by (prover:"isabelle"; tactic:"(auto intro: setEqualI)"; timeout:@)
|
|
340
|
+
by (prover:"isabelle"; tactic:"clarsimp auto?"; timeout:@)
|
|
341
|
+
by (prover:"isabelle"; tactic:"clarsimp"; timeout:@)
|
|
342
|
+
by (prover:"isabelle"; tactic:"auto, blast"; timeout:@)
|
|
343
|
+
}*)
|
|
344
|
+
|
|
345
|
+
AllSMT == TRUE (*{
|
|
346
|
+
by (prover:"cvc33")
|
|
347
|
+
by (prover:"smt3")
|
|
348
|
+
by (prover:"yices3")
|
|
349
|
+
by (prover:"verit")
|
|
350
|
+
by (prover:"z33")
|
|
351
|
+
}*)
|
|
352
|
+
AllSMTT(X) == TRUE (*{
|
|
353
|
+
by (prover:"cvc33"; timeout:@)
|
|
354
|
+
by (prover:"smt3"; timeout:@)
|
|
355
|
+
by (prover:"yices3"; timeout:@)
|
|
356
|
+
by (prover:"verit"; timeout:@)
|
|
357
|
+
by (prover:"z33"; timeout:@)
|
|
358
|
+
}*)
|
|
359
|
+
|
|
360
|
+
AllIsa == TRUE (*{
|
|
361
|
+
by (prover:"isabelle"; tactic:"auto")
|
|
362
|
+
by (prover:"isabelle"; tactic:"force")
|
|
363
|
+
by (prover:"isabelle"; tactic:"(auto intro: setEqualI)")
|
|
364
|
+
by (prover:"isabelle"; tactic:"clarsimp auto?")
|
|
365
|
+
by (prover:"isabelle"; tactic:"clarsimp")
|
|
366
|
+
by (prover:"isabelle"; tactic:"auto, blast")
|
|
367
|
+
}*)
|
|
368
|
+
AllIsaT(X) == TRUE (*{
|
|
369
|
+
by (prover:"isabelle"; tactic:"auto"; timeout:@)
|
|
370
|
+
by (prover:"isabelle"; tactic:"force"; timeout:@)
|
|
371
|
+
by (prover:"isabelle"; tactic:"(auto intro: setEqualI)"; timeout:@)
|
|
372
|
+
by (prover:"isabelle"; tactic:"clarsimp auto?"; timeout:@)
|
|
373
|
+
by (prover:"isabelle"; tactic:"clarsimp"; timeout:@)
|
|
374
|
+
by (prover:"isabelle"; tactic:"auto, blast"; timeout:@)
|
|
375
|
+
}*)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
(**************************************************************************)
|
|
379
|
+
(* The pragma ExpandEnabled invokes expansion of the operator ENABLED. *)
|
|
380
|
+
(* *)
|
|
381
|
+
(* The pragma ExpandCdot invokes expansion of the operator \\cdot. *)
|
|
382
|
+
(* *)
|
|
383
|
+
(* The pragma AutoUSE invokes automated expansion of definitions, *)
|
|
384
|
+
(* for both of ExpandEnabled and ExpandCdot, when each is present. *)
|
|
385
|
+
(* *)
|
|
386
|
+
(* The pragma Lambdify invokes expansion of the operators *)
|
|
387
|
+
(* ENABLED and \\cdot to an intermediate form with bound VARIABLES, *)
|
|
388
|
+
(* which is a form before introducing rigid quantifiers. *)
|
|
389
|
+
(* The pragma Lambdify is sound for occurrences of ENABLED and \\cdot *)
|
|
390
|
+
(* that are not nested. *)
|
|
391
|
+
(**************************************************************************)
|
|
392
|
+
ExpandENABLED == TRUE (*{ by (prover:"expandenabled") }*)
|
|
393
|
+
ExpandCdot == TRUE (*{ by (prover:"expandcdot") }*)
|
|
394
|
+
AutoUSE == TRUE (*{ by (prover:"autouse") }*)
|
|
395
|
+
Lambdify == TRUE (*{ by (prover:"lambdify") }*)
|
|
396
|
+
ENABLEDaxioms == TRUE (*{ by (prover:"enabledaxioms") }*)
|
|
397
|
+
LevelComparison == TRUE (*{ by (prover:"levelcomparison") }*)
|
|
398
|
+
|
|
399
|
+
(* The operators EnabledWrapper and CdotWrapper occur in an intermediate *)
|
|
400
|
+
(* representation within TLAPM. *)
|
|
401
|
+
EnabledWrapper(Op(_)) == FALSE
|
|
402
|
+
CdotWrapper(Op(_)) == FALSE
|
|
403
|
+
|
|
404
|
+
(***************************************************************************)
|
|
405
|
+
(* The following may be used in a \`BY ONLY ThmName\` for unit testing the *)
|
|
406
|
+
(* triviality checks in TLAPM. *)
|
|
407
|
+
(***************************************************************************)
|
|
408
|
+
Trivial == TRUE (*{ by (prover:"trivial") }*)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
=============================================================================
|
|
412
|
+
|
|
413
|
+
The material below is obsolete: the TLA proof rules below are superseded by
|
|
414
|
+
the PTL decision procedure, and their formulation is unsound for the semantics
|
|
415
|
+
of temporal reasoning that TLAPS adopts.
|
|
416
|
+
|
|
417
|
+
----------------------------------------------------------------------------
|
|
418
|
+
(***************************************************************************)
|
|
419
|
+
(* TEMPORAL LOGIC *)
|
|
420
|
+
(* *)
|
|
421
|
+
(* The following rules are intended to be used when TLAPS handles temporal *)
|
|
422
|
+
(* logic. They will not work now. Moreover when temporal reasoning is *)
|
|
423
|
+
(* implemented, these rules may be changed or omitted, and additional *)
|
|
424
|
+
(* rules will probably be added. However, they are included mainly so *)
|
|
425
|
+
(* their names will be defined, preventing the use of identifiers that are *)
|
|
426
|
+
(* likely to produce name clashes with future versions of this module. *)
|
|
427
|
+
(***************************************************************************)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
(***************************************************************************)
|
|
431
|
+
(* The following proof rules (and their names) are from the paper "The *)
|
|
432
|
+
(* Temporal Logic of Actions". *)
|
|
433
|
+
(***************************************************************************)
|
|
434
|
+
THEOREM RuleTLA1 == ASSUME STATE P, STATE f,
|
|
435
|
+
P /\\ (f' = f) => P'
|
|
436
|
+
PROVE []P <=> P /\\ [][P => P']_f
|
|
437
|
+
|
|
438
|
+
THEOREM RuleTLA2 == ASSUME STATE P, STATE Q, STATE f, STATE g,
|
|
439
|
+
ACTION A, ACTION B,
|
|
440
|
+
P /\\ [A]_f => Q /\\ [B]_g
|
|
441
|
+
PROVE []P /\\ [][A]_f => []Q /\\ [][B]_g
|
|
442
|
+
|
|
443
|
+
THEOREM RuleINV1 == ASSUME STATE I, STATE F, ACTION N,
|
|
444
|
+
I /\\ [N]_F => I'
|
|
445
|
+
PROVE I /\\ [][N]_F => []I
|
|
446
|
+
|
|
447
|
+
THEOREM RuleINV2 == ASSUME STATE I, STATE f, ACTION N
|
|
448
|
+
PROVE []I => ([][N]_f <=> [][N /\\ I /\\ I']_f)
|
|
449
|
+
|
|
450
|
+
THEOREM RuleWF1 == ASSUME STATE P, STATE Q, STATE f, ACTION N, ACTION A,
|
|
451
|
+
P /\\ [N]_f => (P' \\/ Q'),
|
|
452
|
+
P /\\ <<N /\\ A>>_f => Q',
|
|
453
|
+
P => ENABLED <<A>>_f
|
|
454
|
+
PROVE [][N]_f /\\ WF_f(A) => (P ~> Q)
|
|
455
|
+
|
|
456
|
+
THEOREM RuleSF1 == ASSUME STATE P, STATE Q, STATE f,
|
|
457
|
+
ACTION N, ACTION A, TEMPORAL F,
|
|
458
|
+
P /\\ [N]_f => (P' \\/ Q'),
|
|
459
|
+
P /\\ <<N /\\ A>>_f => Q',
|
|
460
|
+
[]P /\\ [][N]_f /\\ []F => <> ENABLED <<A>>_f
|
|
461
|
+
PROVE [][N]_f /\\ SF_f(A) /\\ []F => (P ~> Q)
|
|
462
|
+
|
|
463
|
+
(***************************************************************************)
|
|
464
|
+
(* The rules WF2 and SF2 in "The Temporal Logic of Actions" are obtained *)
|
|
465
|
+
(* from the following two rules by the following substitutions: \`. *)
|
|
466
|
+
(* *)
|
|
467
|
+
(* ___ ___ _______________ *)
|
|
468
|
+
(* M <- M , g <- g , EM <- ENABLED <<M>>_g .' *)
|
|
469
|
+
(***************************************************************************)
|
|
470
|
+
THEOREM RuleWF2 == ASSUME STATE P, STATE f, STATE g, STATE EM,
|
|
471
|
+
ACTION A, ACTION B, ACTION N, ACTION M,
|
|
472
|
+
TEMPORAL F,
|
|
473
|
+
<<N /\\ B>>_f => <<M>>_g,
|
|
474
|
+
P /\\ P' /\\ <<N /\\ A>>_f /\\ EM => B,
|
|
475
|
+
P /\\ EM => ENABLED A,
|
|
476
|
+
[][N /\\ ~B]_f /\\ WF_f(A) /\\ []F /\\ <>[]EM => <>[]P
|
|
477
|
+
PROVE [][N]_f /\\ WF_f(A) /\\ []F => []<><<M>>_g \\/ []<>(~EM)
|
|
478
|
+
|
|
479
|
+
THEOREM RuleSF2 == ASSUME STATE P, STATE f, STATE g, STATE EM,
|
|
480
|
+
ACTION A, ACTION B, ACTION N, ACTION M,
|
|
481
|
+
TEMPORAL F,
|
|
482
|
+
<<N /\\ B>>_f => <<M>>_g,
|
|
483
|
+
P /\\ P' /\\ <<N /\\ A>>_f /\\ EM => B,
|
|
484
|
+
P /\\ EM => ENABLED A,
|
|
485
|
+
[][N /\\ ~B]_f /\\ SF_f(A) /\\ []F /\\ []<>EM => <>[]P
|
|
486
|
+
PROVE [][N]_f /\\ SF_f(A) /\\ []F => []<><<M>>_g \\/ <>[](~EM)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
(***************************************************************************)
|
|
490
|
+
(* The following rule is a special case of the general temporal logic *)
|
|
491
|
+
(* proof rule STL4 from the paper "The Temporal Logic of Actions". The *)
|
|
492
|
+
(* general rule is for arbitrary temporal formulas F and G, but it cannot *)
|
|
493
|
+
(* yet be handled by TLAPS. *)
|
|
494
|
+
(***************************************************************************)
|
|
495
|
+
THEOREM RuleInvImplication ==
|
|
496
|
+
ASSUME STATE F, STATE G,
|
|
497
|
+
F => G
|
|
498
|
+
PROVE []F => []G
|
|
499
|
+
PROOF OMITTED
|
|
500
|
+
|
|
501
|
+
(***************************************************************************)
|
|
502
|
+
(* The following rule is a special case of rule TLA2 from the paper "The *)
|
|
503
|
+
(* Temporal Logic of Actions". *)
|
|
504
|
+
(***************************************************************************)
|
|
505
|
+
THEOREM RuleStepSimulation ==
|
|
506
|
+
ASSUME STATE I, STATE f, STATE g,
|
|
507
|
+
ACTION M, ACTION N,
|
|
508
|
+
I /\\ I' /\\ [M]_f => [N]_g
|
|
509
|
+
PROVE []I /\\ [][M]_f => [][N]_g
|
|
510
|
+
PROOF OMITTED
|
|
511
|
+
|
|
512
|
+
(***************************************************************************)
|
|
513
|
+
(* The following may be used to invoke a decision procedure for *)
|
|
514
|
+
(* propositional temporal logic. *)
|
|
515
|
+
(***************************************************************************)
|
|
516
|
+
PropositionalTemporalLogic == TRUE
|
|
517
|
+
=============================================================================
|
|
518
|
+
`}:void 0)),{lines:u,onWarning:e=>{if(e.channel===`stdout`)return console.log(e.text);let t=e.channel===`toolbox`||e.channel===`toolboxOnly`;if(l&&t)return ns([`type:warning`,`msg:${e.text}`]);e.channel!==`toolboxOnly`&&console.error(e.text)}})});if(!h)return 3;let g=n.get(`--cache-dir`)?.[0]??process.env.TLAPM_CACHE_DIR??`.tlacache`,_=n.get(`--nofpl`)?.map(Number)??[0,0],v={isToolbox:l,isProving:!n.has(`--noproving`),workers:Math.max(1,Number(n.get(`--threads`)?.[0]??Ue())),isFingerprinted:e=>!n.has(`--nofp`)&&!(e.locus&&e.locus.startLine>=_[0]&&e.locus.endLine<=_[1]),fingerprints:/* @__PURE__ */ new Map},y=[];for(let[e,t]of h.entries()){let i=`${g}/${t.name}.tlaps`,a=`${i}/fingerprints`,o=n.get(`--usefp`)?.[0]??a;if(Pe(i,{recursive:!0}),n.has(`--cleanfp`)?I(a)&&(ze(a),console.log(`(* fingerprints file ${JSON.stringify(a)} removed *)`)):I(o)&&t.summary.total!==0&&(console.log(n.has(`--nofp`)?`(* will not use fingerprints (because of option \`--nofp\`), but will now load fingerprints from the file \`${o}\`, in order to overwrite with the new fingerprints, and then save the results at the end. *)`:`(* loading fingerprints in ${JSON.stringify(o)} *)`),mt(v.fingerprints,o,n.has(`--safefp`))),n.has(`--summary`)&&console.log(ve(t)),l&&(t.obligations.forEach(e=>rs(e,`to be proved`,n.has(`--printallobs`)?[`obl:${e.text}`]:[])),ns([`type:obligationsnumber`,`count:${t.obligations.length}`])),n.has(`--strict`)&&y.push(...cs(t,u.start>0||u.end<1/0,n.has(`--summary`))),!r)continue;let s=[...m,...h.slice(0,e+1).map(e=>e.name)].map(e=>`${e}.tla`);if(await ps(t,`${i}/${t.name}.thy`,a,s,v)){if(n.has(`--strict`))y.push(ss.failed);else if(!l)return console.error(` tlapm ending abnormally with Failure("backend errors: there are unproved obligations")
|
|
519
|
+
Raised at Stdlib.failwith in file "stdlib.ml", line 29, characters 17-33
|
|
520
|
+
Called from Tlapm_lib.process_module in file "src/tlapm_lib.ml", lines 492-493, characters 12-37
|
|
521
|
+
Called from Tlapm_lib.main.f in file "src/tlapm_lib.ml", line 640, characters 23-43
|
|
522
|
+
Called from Stdlib__List.fold_left in file "list.ml", line 125, characters 24-34
|
|
523
|
+
Called from Tlapm_lib.main in file "src/tlapm_lib.ml", line 643, characters 13-40
|
|
524
|
+
Called from Tlapm_lib.init in file "src/tlapm_lib.ml", line 659, characters 8-59
|
|
525
|
+
`),3}}return Object.values(ss).find(e=>y.includes(e))??o.success},hs=async(e,t)=>{let n=oo.parse(e),r=go(n.positionals),i=n.has(`-config`),a=r.map(e=>({...e,path:e.isGlobbed||/\.(tla|cfg)$/.test(e.path)?e.path.replace(/\.cfg$/,`.tla`):`${e.path}.tla`})).filter(e=>e.path.endsWith(`.tla`)&&(!e.isGlobbed||i||I(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(a.length===0)return console.error(mo),1;if(i&&a.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let o=[...new Set(a.map(e=>I(e)||Ae(e)?e:t.libraries.map(t=>je(t,e)).find(I)??e))],s=t.tlcVersion??`master`;return Qo(o,(e,r)=>(o.length>1&&console.log(`Checking ${De(e)} with ${De(e,`.tla`)}.cfg`),Jo(e,n,t,r)),()=>de(n.has(`-tool`),!n.has(`-nowarning`),s))},gs=e=>(process.stderr.write(`ERROR: ${e}\n${po}`),Fa.argsParsingFailure),_s=(e,t)=>{try{return process.stdout.write(no(e,t)),o.success}catch(e){if(!(e instanceof d))throw e;let t=r(e),n=e instanceof c?e.unwound:``;return console.error(t===Fa.uncaughtException?`${n}Exception in thread "main" ${e.message}`:`ERROR: ${e.message}`),t}},vs=(e,t)=>{let n={flags:/* @__PURE__ */ new Set,includes:[],error:void 0},r={flag:-1};for(let i=0;i<e.length-1;i++)if(t.has(e[i]))n.flags.add(e[i]),r.flag=i;else if(e[i]===`-I`){if(i++,i>e.length-2)return{...n,error:`missing-include`};n.includes.push(e[i]),r.flag=i}return r.flag===e.length-2?n:{...n,error:`several-files`}},ys=e=>{if(e.length===0)return gs(`at least one .tla file must be given`);let t=vs(e,uo);if(t.error===`missing-include`)return gs(`the -I flag must be followed by a directory and at least one .tla file`);if(t.error===`several-files`)return gs(`Only one TLA file to check allowed!`);let n=e[e.length-1];if(n===`-help`)return process.stdout.write(po),o.success;let r=n.endsWith(`.tla`)?n:`${n}.tla`,i=[`.`,...t.includes],a=i.map(e=>Me(e,r)).find(I);a===void 0&&!ue.has(r.slice(0,-4))&&Bo(process.cwd(),`./${r}`,t.includes);let s=Pa(a??r,zo(i),{fileName:n,isXmlExport:!0});return process.stderr.write(s.text),s.isFailed||s.specification===void 0?(console.error(`ERROR: Failed to parse module.`),Fa.specParsingFailure):_s(s.specification,{version:`master`,isRestricted:t.flags.has(`-r`),isUncommented:t.flags.has(`-u`),isTerse:t.flags.has(`-t`)})},bs=(e,t,n)=>console.error(`File does not exist: ${Ae(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,...n===void 0?[]:[Vo(n)]].join(`, `)}`),xs=e=>e.endsWith(`/`)?e:`${e}/`,Ss=(e,t,n)=>{let r=e.slice(0,e.lastIndexOf(`/`)+1),i=(!Ae(e)&&r!==``?[r]:t.libraries).map(xs),a=i.length>0?i[i.length-1]:Ae(e)?r:``;return e=>bs(`${a}${e}`,i,n)},Cs=(e,t)=>n=>{let r=e(n);return r===void 0&&!y.has(n)&&t(`${n}.tla`),r},ws=(e,t)=>(console.error(`Exception in thread "main" ${e}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${t})`),Fa.uncaughtException),Ts=(e,t)=>{if(e.length===0)return ws(`java.lang.IllegalArgumentException: at least one .tla file must be given`,59);let n=vs(e,fo);if(n.error===`missing-include`)return ws(`java.lang.IllegalArgumentException: the -I flag must be followed by a directory and at least one .tla file`,71);if(n.error===`several-files`)return ws(`java.lang.IllegalArgumentException: Only one TLA file to check allowed!`,83);let r=e[e.length-1],i=`${r.replace(/\.tla$/i,``)}.tla`,a=(n.includes.length===0?[`/`]:n.includes).map(xs),s=[`.`,...a],c=e=>bs(`${a[a.length-1]}${e}`,a,t),l=s.map(e=>Me(e,i)).find(I);if(l===void 0&&!y.has(De(i,`.tla`)))return c(i),o.success;let u=Pa(l??i,Cs(zo(s),c),{fileName:r,isXmlExport:!0,version:`1.7.4`});return process.stderr.write(u.text),u.specification===void 0?ws(`tla2sany.xml.XMLExportingException: spec ${(l&&Na(L(l,`utf8`),`1.7.4`))??`null`} is malformed - does not have a root module`,110):_s(u.specification,{version:`1.7.4`,isRestricted:!1,isUncommented:!1,isTerse:!0})},Es=[`tlc2.TLC`,`tla2sany.xml.XMLExporter`],Ds=e=>e.classPath?.split(Oe).find(e=>e.endsWith(`.jar`)),Os=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(Oe));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||Es.includes(r)?{mainClass:r,args:e.slice(n+1),java:t}:void 0}},ks=e=>e.mainClass===`tlc2.TLC`?hs(e.args,e.java):e.mainClass===`tla2sany.xml.XMLExporter`?Zo(()=>e.java.tlcVersion===`1.7.4`?Ts(e.args,Ds(e.java)):ys(e.args)):(console.error(`Error: tla-ts runs the Java classes ${Es.join(` and `)}, not ${e.mainClass}.`),1),As=async e=>{if(e[0]===`prove`)return Zo(()=>us(e.slice(1)));if(e[0]===`tlapm`)return Zo(()=>ms(e.slice(1)));let t=Os(e);return t===void 0?hs(e,{libraries:[]}):(t.java.tlcVersion??=await io(Ds(t.java)),ks(t))},js=async()=>{process.exitCode=await As(process.argv.slice(2))};export{js as runCli};
|