tla-ts 0.0.3-dev.fe239f8 → 0.0.4-dev.5f6a4bf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/run-cli.cjs CHANGED
@@ -6,1355 +6,50 @@
6
6
  * This source code is licensed under the MIT license found in the
7
7
  * LICENSE file in the root directory of this source tree.
8
8
  */
9
- const e=require("./transfer.cjs"),t=require("./parallel.cjs");let n=require("node:path"),r=require("node:fs"),i=require("node:child_process"),a=require("node:crypto"),o=require("node:os"),s=require("node:url"),c=require("node:v8"),l=require("fflate");var u=`0.0.3-dev.fe239f8`;const d=e=>{let t=e.isRequired?e.flag:`[${e.flag}]`;return e.isRepeatable?`${t}...`:t},f=(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(d).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}}}},p=e=>{let t=e.endColumn-1;return e.startLine===e.endLine?e.startColumn>=t?`line ${e.startLine}, character ${e.startColumn}`:`line ${e.startLine}, characters ${e.startColumn}-${t}`:`line ${e.startLine}, character ${e.startColumn} to line ${e.endLine}, character ${t}`},m=e=>`File ${JSON.stringify(e.file)}, ${p(e)}`,h=e=>`${e?m(e):`<unknown location>`}:\n`,g=(e,t)=>({text:`${h(e)}Error: ${t}`,channel:`stderr`}),_=e=>e?`${m(e)} :\n`:``,v=e=>({kind:`Shift`,amount:e}),y=(e,t)=>({kind:`Cons`,expression:e,rest:t}),b=(e,t)=>e.reduce((e,t)=>y(t,e),t),x=(e,t)=>t.kind===`Bump`?{kind:`Bump`,amount:t.amount+e,rest:t.rest}:{kind:`Bump`,amount:e,rest:t},S=(e,t)=>{let n=t.location?{...e,location:t.location}:e;return t.isAtomic?{...n,isAtomic:!0}:n},C=e=>{switch(e.kind){case`Fresh`:case`Flex`:return e.name;case`Defn`:return e.definition.name;case`Fact`:return}},w=(e,t,n)=>S({kind:`Apply`,operator:S({kind:`Internal`,builtin:e},n),args:t},n),T=e=>e.context.length===0?e.active:{kind:`Sequent`,sequent:e},E=(e,t)=>({hyp:t,rest:e,size:(e?.size??0)+1}),ee=(e,t)=>t.reduce(E,e),D=e=>{let t=[];for(let n=e;n;n=n.rest)t.push(n.hyp);return t.reverse()},te=(e,t)=>{let n=0;for(let r=e;r;r=r.rest){if(C(r.hyp)===t)return{depth:n,hyp:r.hyp};n++}},ne=(e,t)=>{let n=e;for(let e=0;e<t&&n;e++)n=n.rest;return n},O=(e,t,n)=>{let r=[];return[t.reduce((e,t)=>{let[i,a]=n(e,t);return r.push(a),i},e),r]},k=(e,t,n=0)=>({kind:`Fresh`,name:e,shape:n,level:t,domain:void 0,domainVisibility:`Visible`}),A=(e,t)=>({kind:`Fresh`,name:e,shape:0,level:`Constant`,domain:t,domainVisibility:`Visible`}),re=(e,t,n)=>{switch(e.kind){case`Shift`:return S({kind:`Ix`,index:e.amount+t},n);case`Cons`:return t===1?S(M(e.expression),n):re(e.rest,t-1,n);case`Compose`:return P(e.outer,re(e.inner,t,n));case`Bump`:return t<=e.amount?S({kind:`Ix`,index:t},n):P(v(e.amount),re(e.rest,t-e.amount,n))}},j=(e,t)=>t.map(t=>P(e,t)),ie=(t,n)=>{if(t.kind===`Lambda`){if(t.params.length!==n.length)throw new e.ut(`Arity mismatch`);return M(P(b(n,v(0)),t.body))}return t.kind===`Apply`?{kind:`Apply`,operator:t.operator,args:[...t.args,...n]}:n.length===0?M(t):{kind:`Apply`,operator:t,args:n}},M=e=>{if(!e.location&&!e.isAtomic)return e;let{location:t,isAtomic:n,...r}=e;return r},N=(e,t)=>[x(t.length,e),me(t,t=>P(e,t))],ae=(e,t)=>{switch(t.kind){case`Recursive`:case`Operator`:case`Bpragma`:return _e(t,t=>P(e,t));case`Instance`:{let n=x(t.instance.args.length,e);return{...t,instance:{...t.instance,substitutions:t.instance.substitutions.map(e=>({name:e.name,expression:P(n,e.expression)}))}}}}},oe=(e,t)=>{switch(t.kind){case`Fresh`:return t.domain?{...t,domain:P(e,t.domain)}:t;case`Flex`:return t;case`Defn`:return{...t,definition:ae(e,t.definition)};case`Fact`:return{...t,expression:P(e,t.expression)}}},se=(e,t)=>{let[n,r]=O(e,t.context,(e,t)=>[x(1,e),oe(e,t)]);return{context:r,active:P(n,t.active)}},P=(e,t)=>{let n=t=>P(e,t);switch(t.kind){case`Internal`:case`Opaque`:case`String`:case`Num`:case`At`:return t;case`Ix`:return re(e,t.index,t);case`Apply`:return S(ie(n(t.operator),j(e,t.args)),t);case`Bang`:return{...t,expression:n(t.expression),selectors:t.selectors.map(e=>he(e,n))};case`Lambda`:return{...t,body:P(x(t.params.length,e),t.body)};case`Let`:{let[n,r]=O(e,t.definitions,(e,t)=>[x(1,e),ae(e,t)]);return{...t,definitions:r,body:P(n,t.body)}}case`Sequent`:return{...t,sequent:se(e,t.sequent)};case`With`:return{...t,expression:n(t.expression)};case`If`:return{...t,condition:n(t.condition),consequent:n(t.consequent),alternative:n(t.alternative)};case`List`:return{...t,items:j(e,t.items)};case`Quant`:{let[n,r]=N(e,t.bounds);return{...t,bounds:r,body:P(n,t.body)}}case`Tquant`:return{...t,body:P(x(t.names.length,e),t.body)};case`Choose`:return{...t,domain:t.domain&&n(t.domain),body:P(x(1,e),t.body)};case`SetSt`:return{...t,domain:n(t.domain),body:P(x(1,e),t.body)};case`SetOf`:{let[n,r]=N(e,t.bounds);return{...t,bounds:r,element:P(n,t.element)}}case`SetEnum`:return{...t,elements:j(e,t.elements)};case`Arrow`:return{...t,domain:n(t.domain),range:n(t.range)};case`Fcn`:{let[n,r]=N(e,t.bounds);return{...t,bounds:r,body:P(n,t.body)}}case`FcnApp`:return{...t,function:n(t.function),args:j(e,t.args)};case`Product`:return{...t,factors:j(e,t.factors)};case`Tuple`:return{...t,elements:j(e,t.elements)};case`Rect`:case`Record`:return{...t,fields:t.fields.map(e=>({name:e.name,value:n(e.value)}))};case`Except`:return{...t,function:n(t.function),specs:ge(t.specs,n)};case`Dot`:return{...t,expression:n(t.expression)};case`Sub`:case`Tsub`:return{...t,action:n(t.action),subscript:n(t.subscript)};case`Fair`:return{...t,subscript:n(t.subscript),action:n(t.action)};case`Case`:return{...t,arms:t.arms.map(e=>({condition:n(e.condition),body:n(e.body)})),other:t.other&&n(t.other)};case`Parens`:return{...t,expression:n(t.expression)}}},F=(e,t)=>e===0?t:P(v(e),t),I=(e,t,n)=>e.length===t.length&&e.every((e,r)=>n(e,t[r])),ce=(e,t)=>{let n=new Map(e.map(e=>[e.name,e.value])),r=new Map(t.map(e=>[e.name,e.value]));if(n.size!==r.size)return!1;for(let[e,t]of n){let n=r.get(e);if(!n||!L(t,n))return!1}return!0},le=(e,t)=>e.level===t.level&&e.domain.kind===t.domain.kind&&(e.domain.kind!==`Domain`||t.domain.kind===`Domain`&&L(e.domain.expression,t.domain.expression)),ue=(e,t)=>{if(e.kind!==t.kind)return!1;switch(e.kind){case`Number`:return t.kind===`Number`&&e.value===t.value;case`Instance`:return t.kind===`Instance`&&I(e.args,t.args,L);case`Label`:return t.kind===`Label`&&e.label===t.label&&I(e.args,t.args,L);default:return!0}},de=(e,t)=>{if(e.kind===`Operator`&&t.kind===`Operator`||e.kind===`Bpragma`&&t.kind===`Bpragma`)return L(e.body,t.body);if(e.kind===`Instance`&&t.kind===`Instance`){let n=e.instance.substitutions.map(e=>({name:e.name,value:e.expression})),r=t.instance.substitutions.map(e=>({name:e.name,value:e.expression}));return I(e.instance.args,t.instance.args,(e,t)=>e===t)&&e.instance.module===t.instance.module&&ce(n,r)}return!1},fe=(e,t)=>e.kind===`Fresh`&&t.kind===`Fresh`?e.level!==t.level||e.shape!==t.shape?!1:!e.domain||!t.domain?!e.domain&&!t.domain:L(e.domain,t.domain):e.kind===`Flex`&&t.kind===`Flex`?!0:e.kind===`Defn`&&t.kind===`Defn`?de(e.definition,t.definition)&&e.isLocal===t.isLocal:e.kind===`Fact`&&t.kind===`Fact`&&L(e.expression,t.expression),pe=(e,t)=>I(e.context,t.context,fe)&&L(e.active,t.active),L=(e,t)=>{if(e.kind===`Parens`)return L(e.expression,t);if(t.kind===`Parens`)return L(e,t.expression);switch(e.kind){case`Ix`:return t.kind===`Ix`&&e.index===t.index;case`Opaque`:return t.kind===`Opaque`&&e.name===t.name;case`Internal`:return t.kind===`Internal`&&e.builtin===t.builtin;case`Lambda`:return t.kind===`Lambda`&&e.params.length===t.params.length&&L(e.body,t.body);case`Apply`:return t.kind===`Apply`&&L(e.operator,t.operator)&&I(e.args,t.args,L);case`Sequent`:return t.kind===`Sequent`&&pe(e.sequent,t.sequent);case`Bang`:return t.kind===`Bang`&&L(e.expression,t.expression)&&I(e.selectors,t.selectors,ue);case`With`:return t.kind===`With`&&L(e.expression,t.expression);case`Let`:return t.kind===`Let`&&I(e.definitions,t.definitions,de)&&L(e.body,t.body);case`If`:return t.kind===`If`&&L(e.condition,t.condition)&&L(e.consequent,t.consequent)&&L(e.alternative,t.alternative);case`List`:return t.kind===`List`&&e.bullet===t.bullet&&I(e.items,t.items,L);case`Quant`:return t.kind===`Quant`&&e.quantifier===t.quantifier&&I(e.bounds,t.bounds,le)&&L(e.body,t.body);case`Tquant`:return t.kind===`Tquant`&&e.quantifier===t.quantifier&&I(e.names,t.names,(e,t)=>e===t)&&L(e.body,t.body);case`Choose`:return t.kind===`Choose`?e.domain&&t.domain?L(e.domain,t.domain)&&L(e.body,t.body):!e.domain&&!t.domain&&L(e.body,t.body):!1;case`SetSt`:return t.kind===`SetSt`&&L(e.domain,t.domain)&&L(e.body,t.body);case`SetOf`:return t.kind===`SetOf`&&L(e.element,t.element)&&I(e.bounds,t.bounds,le);case`SetEnum`:return t.kind===`SetEnum`&&I(e.elements,t.elements,L);case`Arrow`:return t.kind===`Arrow`&&L(e.domain,t.domain)&&L(e.range,t.range);case`Fcn`:return t.kind===`Fcn`&&I(e.bounds,t.bounds,le)&&L(e.body,t.body);case`FcnApp`:return t.kind===`FcnApp`&&I([e.function,...e.args],[t.function,...t.args],L);case`Tuple`:return t.kind===`Tuple`&&I(e.elements,t.elements,L);case`Product`:return t.kind===`Product`&&I(e.factors,t.factors,L);case`Rect`:return t.kind===`Rect`&&ce(e.fields,t.fields);case`Record`:return t.kind===`Record`&&ce(e.fields,t.fields);case`Except`:return t.kind===`Except`&&L(e.function,t.function)&&I(e.specs,t.specs,(e,t)=>I(e.trail,t.trail,(e,t)=>e.kind===`Dot`?t.kind===`Dot`&&e.field===t.field:t.kind===`Apply`&&L(e.expression,t.expression))&&L(e.value,t.value));case`Dot`:return t.kind===`Dot`&&L(e.expression,t.expression)&&e.field===t.field;case`Sub`:case`Tsub`:return t.kind===e.kind&&e.modal===t.modal&&L(e.action,t.action)&&L(e.subscript,t.subscript);case`Fair`:return t.kind===`Fair`&&e.fairness===t.fairness&&L(e.subscript,t.subscript)&&L(e.action,t.action);case`Case`:return t.kind!==`Case`||!(e.arms.length===0||t.arms.length===0?e.arms.length===t.arms.length:L(e.arms[0].condition,t.arms[0].condition)&&L(e.arms[0].body,t.arms[0].body))?!1:e.other&&t.other?L(e.other,t.other):!e.other&&!t.other;case`String`:return t.kind===`String`&&e.value===t.value;case`Num`:return t.kind===`Num`&&e.integer===t.integer&&e.fraction===t.fraction;case`At`:return t.kind===`At`&&e.isExcept===t.isExcept}},me=(e,t)=>e.map(e=>e.domain.kind===`Domain`?{...e,domain:{kind:`Domain`,expression:t(e.domain.expression)}}:e),he=(e,t)=>e.kind===`Instance`||e.kind===`Label`?{...e,args:e.args.map(t)}:e,ge=(e,t)=>e.map(e=>{let n=t(e.value);return{trail:e.trail.map(e=>e.kind===`Apply`?{kind:`Apply`,expression:t(e.expression)}:e),value:n}}),_e=(e,t)=>e.kind===`Operator`||e.kind===`Bpragma`?{...e,body:t(e.body)}:e,ve=(e,t,n)=>e.kind===`Fresh`?e.domain?{...e,domain:t(e.domain)}:e:e.kind===`Flex`||n===`visible`&&e.visibility===`Hidden`?e:e.kind===`Defn`?{...e,definition:_e(e.definition,t)}:{...e,expression:t(e.expression)},ye=(e,t,n,r,i=`visible`)=>{let a=t=>n(e,t),o=t=>t.reduce((e,t)=>r(e,k(t.name,t.level)),e);switch(t.kind){case`Ix`:case`Internal`:case`Opaque`:case`String`:case`Num`:case`At`:return t;case`Lambda`:{let i=t.params.reduce((e,t)=>{let n=k(t.name,`Unknown`,t.shape);return r(e,t.location?{...n,location:t.location}:n)},e);return{...t,body:n(i,t.body)}}case`Sequent`:{let[a,o]=O(e,t.sequent.context,(e,t)=>{let a=ve(t,t=>n(e,t),i);return[r(e,a),a]});return{...t,sequent:{context:o,active:n(a,t.sequent.active)}}}case`Let`:{let[i,a]=O(e,t.definitions,(e,t)=>{let i=_e(t,t=>n(e,t));return[r(e,{kind:`Defn`,definition:i,whereDefined:`User`,visibility:`Visible`,isLocal:!0}),i]});return{...t,definitions:a,body:n(i,t.body)}}case`Quant`:case`Fcn`:{let e=me(t.bounds,a);return{...t,bounds:e,body:n(o(e),t.body)}}case`SetOf`:{let e=me(t.bounds,a);return{...t,bounds:e,element:n(o(e),t.element)}}case`Tquant`:{let i=t.names.reduce((e,t)=>r(e,{kind:`Flex`,name:t}),e);return{...t,body:n(i,t.body)}}case`Choose`:{let i=t.domain&&a(t.domain),o=i?A(t.name,i):k(t.name,`Constant`);return{...t,domain:i,body:n(r(e,o),t.body)}}case`SetSt`:{let i=a(t.domain),o=A(t.name,i);return{...t,domain:i,body:n(r(e,o),t.body)}}case`Bang`:{let e=t.selectors.map(e=>he(e,a));return{...t,expression:a(t.expression),selectors:e}}case`Apply`:{let e=t.args.map(a);return{...t,operator:a(t.operator),args:e}}case`With`:case`Dot`:case`Parens`:return{...t,expression:a(t.expression)};case`If`:{let e=a(t.alternative),n=a(t.consequent);return{...t,condition:a(t.condition),consequent:n,alternative:e}}case`List`:return{...t,items:t.items.map(a)};case`SetEnum`:case`Tuple`:return{...t,elements:t.elements.map(a)};case`Product`:return{...t,factors:t.factors.map(a)};case`FcnApp`:{let e=t.args.map(a);return{...t,function:a(t.function),args:e}}case`Arrow`:{let e=a(t.range);return{...t,domain:a(t.domain),range:e}}case`Rect`:case`Record`:return{...t,fields:t.fields.map(e=>({name:e.name,value:a(e.value)}))};case`Except`:{let e=ge(t.specs,a);return{...t,function:a(t.function),specs:e}}case`Sub`:case`Tsub`:case`Fair`:return{...t,subscript:a(t.subscript),action:a(t.action)};case`Case`:{let e=t.other&&a(t.other),n=t.arms.map(e=>{let t=a(e.body);return{condition:a(e.condition),body:t}});return{...t,arms:n,other:e}}}},be=(e,t)=>ye(void 0,e,(e,n)=>t(n),()=>void 0,`all`),xe=e=>{let t=[];return be(e,e=>(t.push(e),e)),t},Se={kind:`Opaque`,name:`$Bad`},Ce=e=>e.kind===`Opaque`&&e.name===Se.name,we=e=>{let t=e.kind===`Parens`?we(e.expression):be(e,we);if(!t.isAtomic)return t;let{isAtomic:n,...r}=t;return r},Te=e=>e.kind===`Let`?S({kind:`Let`,definitions:e.definitions,body:Te(e.body)},e.body):e.kind===`Parens`?Te(e.expression):be(e,Te),Ee=e=>e.kind===`Ix`?e.index<=0:xe(e).some(Ee),De=(e,t,n)=>{let r=(e,r=n)=>De(e,t,r),i=(e,t)=>e.reduce((e,t)=>e??(t.domain.kind===`Domain`?r(t.domain.expression):void 0),void 0)??r(t,[...n,...e.map(e=>k(e.name,e.level))]);switch(e.kind){case`Parens`:return e.form.kind===`Xlabel`?e.form.label===t?{context:n,expression:e.expression,indices:e.form.indices}:void 0:r(e.expression);case`Lambda`:return r(e.body,[...n,...e.params.map(e=>k(e.name,`Unknown`,e.shape))]);case`Let`:{let t=[...n];for(let n of e.definitions){let e=n.kind===`Operator`||n.kind===`Bpragma`?r(n.body,[...t]):void 0;if(e)return e;t.push({kind:`Defn`,definition:n,whereDefined:`Builtin`,visibility:`Visible`,isLocal:!0})}return r(e.body,t)}case`Quant`:case`Fcn`:return i(e.bounds,e.body);case`SetOf`:return i(e.bounds,e.element);case`Tquant`:return r(e.body,[...n,...e.names.map(e=>({kind:`Flex`,name:e}))]);case`Choose`:case`SetSt`:return(e.domain&&r(e.domain))??r(e.body,[...n,k(e.name,`Constant`)]);case`Sequent`:{let t=[...n];for(let n of e.sequent.context){if(n.kind!==`Fact`)return;let e=r(n.expression,[...t]);if(e)return e;t.push(n)}return r(e.sequent.active,t)}default:for(let t of xe(e)){let e=r(t);if(e)return e}return}},Oe=(e,t)=>b(Array.from({length:e},(e,t)=>({kind:`Ix`,index:t+1})),v(e+t)),R=e=>Array.from({length:e},(t,n)=>({kind:`Ix`,index:e-n})),ke=(t,n,r)=>{switch(n.kind){case`Quant`:case`Fcn`:case`SetOf`:{if(n.bounds.length!==r.length){let i=n.bounds.length,a=`Arity mismatch in subexpression instance.\nExpected ${i} argument${i===1?``:`s`}, but found${r.length<i?` only`:``} ${r.length}.`;throw t(g(n.location,a)),new e.ut(a,{failure:`Expr.Deref.deref_inst`})}let i=n.kind===`SetOf`?n.element:n.body;return P(b(r,v(0)),i)}case`Tquant`:return ke(t,S({kind:`Quant`,quantifier:n.quantifier,bounds:n.names.map(e=>({name:e,level:`State`,domain:{kind:`NoDomain`}})),body:n.body},n),r);case`Lambda`:return ke(t,S({kind:`Quant`,quantifier:`Forall`,bounds:n.params.map(e=>({name:e.name,level:`Unknown`,domain:{kind:`NoDomain`}})),body:n.body},n),r);case`SetSt`:case`Choose`:if(r.length!==1){let i=`Arity mismatch in subexpression instance.\nExpected 1 argument, but found ${r.length}.`;throw t(g(n.location,i)),new e.ut(i,{failure:`Expr.Deref.deref_inst`})}return P(b(r,v(0)),n.body);default:{let r=`Cannot instantiate non-binding expression`;throw t(g(n.location,r)),new e.ut(r,{failure:`Expr.Deref.deref_inst`})}}},Ae=(t,n,r)=>{let i=(()=>{switch(r.kind){case`Quant`:case`Fcn`:case`SetOf`:return r.bounds.map(e=>({name:e.name,shape:0}));case`Tquant`:return r.names.map(e=>({name:e,shape:0}));case`Lambda`:return r.params;case`SetSt`:case`Choose`:return[{name:r.name,shape:0}];default:{let n=`Cannot abstract over bound variables in a non-binding expression`;throw t(g(r.location,n)),new e.ut(n,{failure:`Expr.Deref.deref_at`})}}})(),a=P(Oe(n,i.length),r);return[i,ke(t,a,R(i.length))]},je=(t,n,r,i,a,o)=>{let s=n=>{if(!(i<=n))throw t(g(a.location,o)),new e.ut(o,{failure:`Expr.Deref.deref_num`})},c=e=>(s(e.length),e[i-1]),l=(()=>{switch(r.kind){case`Sequent`:{let a=r.sequent;s(a.context.length+1);let o=a.context[i-1];if(o&&o.kind!==`Fact`){let n=`subexpression reference does not resolve to an expression`;throw t(g(r.location,n)),new e.ut(n,{failure:`Expr.Deref.deref_num`})}let c=P(v(-(i-1)),o?o.expression:a.active);if(Ee(c))throw t(g(r.location,`subexpression of ASSUME/PROVE uses identifiers declared therein
9
+ const e=require("./transfer.cjs"),t=require("./parallel.cjs");let n=require("node:path"),r=require("node:fs"),i=require("node:child_process"),a=require("node:crypto"),o=require("node:os"),s=require("node:url"),c=require("node:v8"),l=require("fflate");var u=`0.0.4-dev.5f6a4bf`;const d=e=>{let t=e.isRequired?e.flag:`[${e.flag}]`;return e.isRepeatable?`${t}...`:t},f=(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(d).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}}}},p=e=>{let t=e.endColumn-1;return e.startLine===e.endLine?e.startColumn>=t?`line ${e.startLine}, character ${e.startColumn}`:`line ${e.startLine}, characters ${e.startColumn}-${t}`:`line ${e.startLine}, character ${e.startColumn} to line ${e.endLine}, character ${t}`},m=e=>`File ${JSON.stringify(e.file)}, ${p(e)}`,h=e=>`${e?m(e):`<unknown location>`}:\n`,g=(e,t)=>({text:`${h(e)}Error: ${t}`,channel:`stderr`}),_=e=>e?`${m(e)} :\n`:``,v=e=>({kind:`Shift`,amount:e}),y=(e,t)=>({kind:`Cons`,expression:e,rest:t}),b=(e,t)=>e.reduce((e,t)=>y(t,e),t),x=(e,t)=>t.kind===`Bump`?{kind:`Bump`,amount:t.amount+e,rest:t.rest}:{kind:`Bump`,amount:e,rest:t},S=(e,t)=>{let n=t.location?{...e,location:t.location}:e;return t.isAtomic?{...n,isAtomic:!0}:n},C=e=>{switch(e.kind){case`Fresh`:case`Flex`:return e.name;case`Defn`:return e.definition.name;case`Fact`:return}},w=(e,t,n)=>S({kind:`Apply`,operator:S({kind:`Internal`,builtin:e},n),args:t},n),T=e=>e.context.length===0?e.active:{kind:`Sequent`,sequent:e},E=(e,t)=>({hyp:t,rest:e,size:(e?.size??0)+1}),ee=(e,t)=>t.reduce(E,e),D=e=>{let t=[];for(let n=e;n;n=n.rest)t.push(n.hyp);return t.reverse()},te=(e,t)=>{let n=0;for(let r=e;r;r=r.rest){if(C(r.hyp)===t)return{depth:n,hyp:r.hyp};n++}},ne=(e,t)=>{let n=e;for(let e=0;e<t&&n;e++)n=n.rest;return n},O=(e,t,n)=>{let r=[];return[t.reduce((e,t)=>{let[i,a]=n(e,t);return r.push(a),i},e),r]},k=(e,t,n=0)=>({kind:`Fresh`,name:e,shape:n,level:t,domain:void 0,domainVisibility:`Visible`}),re=(e,t)=>({kind:`Fresh`,name:e,shape:0,level:`Constant`,domain:t,domainVisibility:`Visible`}),ie=(e,t,n)=>{switch(e.kind){case`Shift`:return S({kind:`Ix`,index:e.amount+t},n);case`Cons`:return t===1?S(M(e.expression),n):ie(e.rest,t-1,n);case`Compose`:return P(e.outer,ie(e.inner,t,n));case`Bump`:return t<=e.amount?S({kind:`Ix`,index:t},n):P(v(e.amount),ie(e.rest,t-e.amount,n))}},A=(e,t)=>t.map(t=>P(e,t)),j=(t,n)=>{if(t.kind===`Lambda`){if(t.params.length!==n.length)throw new e.ut(`Arity mismatch`);return M(P(b(n,v(0)),t.body))}return t.kind===`Apply`?{kind:`Apply`,operator:t.operator,args:[...t.args,...n]}:n.length===0?M(t):{kind:`Apply`,operator:t,args:n}},M=e=>{if(!e.location&&!e.isAtomic)return e;let{location:t,isAtomic:n,...r}=e;return r},N=(e,t)=>[x(t.length,e),me(t,t=>P(e,t))],ae=(e,t)=>{switch(t.kind){case`Recursive`:case`Operator`:case`Bpragma`:return _e(t,t=>P(e,t));case`Instance`:{let n=x(t.instance.args.length,e);return{...t,instance:{...t.instance,substitutions:t.instance.substitutions.map(e=>({name:e.name,expression:P(n,e.expression)}))}}}}},oe=(e,t)=>{switch(t.kind){case`Fresh`:return t.domain?{...t,domain:P(e,t.domain)}:t;case`Flex`:return t;case`Defn`:return{...t,definition:ae(e,t.definition)};case`Fact`:return{...t,expression:P(e,t.expression)}}},se=(e,t)=>{let[n,r]=O(e,t.context,(e,t)=>[x(1,e),oe(e,t)]);return{context:r,active:P(n,t.active)}},P=(e,t)=>{let n=t=>P(e,t);switch(t.kind){case`Internal`:case`Opaque`:case`String`:case`Num`:case`At`:return t;case`Ix`:return ie(e,t.index,t);case`Apply`:return S(j(n(t.operator),A(e,t.args)),t);case`Bang`:return{...t,expression:n(t.expression),selectors:t.selectors.map(e=>he(e,n))};case`Lambda`:return{...t,body:P(x(t.params.length,e),t.body)};case`Let`:{let[n,r]=O(e,t.definitions,(e,t)=>[x(1,e),ae(e,t)]);return{...t,definitions:r,body:P(n,t.body)}}case`Sequent`:return{...t,sequent:se(e,t.sequent)};case`With`:return{...t,expression:n(t.expression)};case`If`:return{...t,condition:n(t.condition),consequent:n(t.consequent),alternative:n(t.alternative)};case`List`:return{...t,items:A(e,t.items)};case`Quant`:{let[n,r]=N(e,t.bounds);return{...t,bounds:r,body:P(n,t.body)}}case`Tquant`:return{...t,body:P(x(t.names.length,e),t.body)};case`Choose`:return{...t,domain:t.domain&&n(t.domain),body:P(x(1,e),t.body)};case`SetSt`:return{...t,domain:n(t.domain),body:P(x(1,e),t.body)};case`SetOf`:{let[n,r]=N(e,t.bounds);return{...t,bounds:r,element:P(n,t.element)}}case`SetEnum`:return{...t,elements:A(e,t.elements)};case`Arrow`:return{...t,domain:n(t.domain),range:n(t.range)};case`Fcn`:{let[n,r]=N(e,t.bounds);return{...t,bounds:r,body:P(n,t.body)}}case`FcnApp`:return{...t,function:n(t.function),args:A(e,t.args)};case`Product`:return{...t,factors:A(e,t.factors)};case`Tuple`:return{...t,elements:A(e,t.elements)};case`Rect`:case`Record`:return{...t,fields:t.fields.map(e=>({name:e.name,value:n(e.value)}))};case`Except`:return{...t,function:n(t.function),specs:ge(t.specs,n)};case`Dot`:return{...t,expression:n(t.expression)};case`Sub`:case`Tsub`:return{...t,action:n(t.action),subscript:n(t.subscript)};case`Fair`:return{...t,subscript:n(t.subscript),action:n(t.action)};case`Case`:return{...t,arms:t.arms.map(e=>({condition:n(e.condition),body:n(e.body)})),other:t.other&&n(t.other)};case`Parens`:return{...t,expression:n(t.expression)}}},F=(e,t)=>e===0?t:P(v(e),t),I=(e,t,n)=>e.length===t.length&&e.every((e,r)=>n(e,t[r])),ce=(e,t)=>{let n=new Map(e.map(e=>[e.name,e.value])),r=new Map(t.map(e=>[e.name,e.value]));if(n.size!==r.size)return!1;for(let[e,t]of n){let n=r.get(e);if(!n||!L(t,n))return!1}return!0},le=(e,t)=>e.level===t.level&&e.domain.kind===t.domain.kind&&(e.domain.kind!==`Domain`||t.domain.kind===`Domain`&&L(e.domain.expression,t.domain.expression)),ue=(e,t)=>{if(e.kind!==t.kind)return!1;switch(e.kind){case`Number`:return t.kind===`Number`&&e.value===t.value;case`Instance`:return t.kind===`Instance`&&I(e.args,t.args,L);case`Label`:return t.kind===`Label`&&e.label===t.label&&I(e.args,t.args,L);default:return!0}},de=(e,t)=>{if(e.kind===`Operator`&&t.kind===`Operator`||e.kind===`Bpragma`&&t.kind===`Bpragma`)return L(e.body,t.body);if(e.kind===`Instance`&&t.kind===`Instance`){let n=e.instance.substitutions.map(e=>({name:e.name,value:e.expression})),r=t.instance.substitutions.map(e=>({name:e.name,value:e.expression}));return I(e.instance.args,t.instance.args,(e,t)=>e===t)&&e.instance.module===t.instance.module&&ce(n,r)}return!1},fe=(e,t)=>e.kind===`Fresh`&&t.kind===`Fresh`?e.level!==t.level||e.shape!==t.shape?!1:!e.domain||!t.domain?!e.domain&&!t.domain:L(e.domain,t.domain):e.kind===`Flex`&&t.kind===`Flex`?!0:e.kind===`Defn`&&t.kind===`Defn`?de(e.definition,t.definition)&&e.isLocal===t.isLocal:e.kind===`Fact`&&t.kind===`Fact`&&L(e.expression,t.expression),pe=(e,t)=>I(e.context,t.context,fe)&&L(e.active,t.active),L=(e,t)=>{if(e.kind===`Parens`)return L(e.expression,t);if(t.kind===`Parens`)return L(e,t.expression);switch(e.kind){case`Ix`:return t.kind===`Ix`&&e.index===t.index;case`Opaque`:return t.kind===`Opaque`&&e.name===t.name;case`Internal`:return t.kind===`Internal`&&e.builtin===t.builtin;case`Lambda`:return t.kind===`Lambda`&&e.params.length===t.params.length&&L(e.body,t.body);case`Apply`:return t.kind===`Apply`&&L(e.operator,t.operator)&&I(e.args,t.args,L);case`Sequent`:return t.kind===`Sequent`&&pe(e.sequent,t.sequent);case`Bang`:return t.kind===`Bang`&&L(e.expression,t.expression)&&I(e.selectors,t.selectors,ue);case`With`:return t.kind===`With`&&L(e.expression,t.expression);case`Let`:return t.kind===`Let`&&I(e.definitions,t.definitions,de)&&L(e.body,t.body);case`If`:return t.kind===`If`&&L(e.condition,t.condition)&&L(e.consequent,t.consequent)&&L(e.alternative,t.alternative);case`List`:return t.kind===`List`&&e.bullet===t.bullet&&I(e.items,t.items,L);case`Quant`:return t.kind===`Quant`&&e.quantifier===t.quantifier&&I(e.bounds,t.bounds,le)&&L(e.body,t.body);case`Tquant`:return t.kind===`Tquant`&&e.quantifier===t.quantifier&&I(e.names,t.names,(e,t)=>e===t)&&L(e.body,t.body);case`Choose`:return t.kind===`Choose`?e.domain&&t.domain?L(e.domain,t.domain)&&L(e.body,t.body):!e.domain&&!t.domain&&L(e.body,t.body):!1;case`SetSt`:return t.kind===`SetSt`&&L(e.domain,t.domain)&&L(e.body,t.body);case`SetOf`:return t.kind===`SetOf`&&L(e.element,t.element)&&I(e.bounds,t.bounds,le);case`SetEnum`:return t.kind===`SetEnum`&&I(e.elements,t.elements,L);case`Arrow`:return t.kind===`Arrow`&&L(e.domain,t.domain)&&L(e.range,t.range);case`Fcn`:return t.kind===`Fcn`&&I(e.bounds,t.bounds,le)&&L(e.body,t.body);case`FcnApp`:return t.kind===`FcnApp`&&I([e.function,...e.args],[t.function,...t.args],L);case`Tuple`:return t.kind===`Tuple`&&I(e.elements,t.elements,L);case`Product`:return t.kind===`Product`&&I(e.factors,t.factors,L);case`Rect`:return t.kind===`Rect`&&ce(e.fields,t.fields);case`Record`:return t.kind===`Record`&&ce(e.fields,t.fields);case`Except`:return t.kind===`Except`&&L(e.function,t.function)&&I(e.specs,t.specs,(e,t)=>I(e.trail,t.trail,(e,t)=>e.kind===`Dot`?t.kind===`Dot`&&e.field===t.field:t.kind===`Apply`&&L(e.expression,t.expression))&&L(e.value,t.value));case`Dot`:return t.kind===`Dot`&&L(e.expression,t.expression)&&e.field===t.field;case`Sub`:case`Tsub`:return t.kind===e.kind&&e.modal===t.modal&&L(e.action,t.action)&&L(e.subscript,t.subscript);case`Fair`:return t.kind===`Fair`&&e.fairness===t.fairness&&L(e.subscript,t.subscript)&&L(e.action,t.action);case`Case`:return t.kind!==`Case`||!(e.arms.length===0||t.arms.length===0?e.arms.length===t.arms.length:L(e.arms[0].condition,t.arms[0].condition)&&L(e.arms[0].body,t.arms[0].body))?!1:e.other&&t.other?L(e.other,t.other):!e.other&&!t.other;case`String`:return t.kind===`String`&&e.value===t.value;case`Num`:return t.kind===`Num`&&e.integer===t.integer&&e.fraction===t.fraction;case`At`:return t.kind===`At`&&e.isExcept===t.isExcept}},me=(e,t)=>e.map(e=>e.domain.kind===`Domain`?{...e,domain:{kind:`Domain`,expression:t(e.domain.expression)}}:e),he=(e,t)=>e.kind===`Instance`||e.kind===`Label`?{...e,args:e.args.map(t)}:e,ge=(e,t)=>e.map(e=>{let n=t(e.value);return{trail:e.trail.map(e=>e.kind===`Apply`?{kind:`Apply`,expression:t(e.expression)}:e),value:n}}),_e=(e,t)=>e.kind===`Operator`||e.kind===`Bpragma`?{...e,body:t(e.body)}:e,ve=(e,t,n)=>e.kind===`Fresh`?e.domain?{...e,domain:t(e.domain)}:e:e.kind===`Flex`||n===`visible`&&e.visibility===`Hidden`?e:e.kind===`Defn`?{...e,definition:_e(e.definition,t)}:{...e,expression:t(e.expression)},ye=(e,t,n,r,i=`visible`)=>{let a=t=>n(e,t),o=t=>t.reduce((e,t)=>r(e,k(t.name,t.level)),e);switch(t.kind){case`Ix`:case`Internal`:case`Opaque`:case`String`:case`Num`:case`At`:return t;case`Lambda`:{let i=t.params.reduce((e,t)=>{let n=k(t.name,`Unknown`,t.shape);return r(e,t.location?{...n,location:t.location}:n)},e);return{...t,body:n(i,t.body)}}case`Sequent`:{let[a,o]=O(e,t.sequent.context,(e,t)=>{let a=ve(t,t=>n(e,t),i);return[r(e,a),a]});return{...t,sequent:{context:o,active:n(a,t.sequent.active)}}}case`Let`:{let[i,a]=O(e,t.definitions,(e,t)=>{let i=_e(t,t=>n(e,t));return[r(e,{kind:`Defn`,definition:i,whereDefined:`User`,visibility:`Visible`,isLocal:!0}),i]});return{...t,definitions:a,body:n(i,t.body)}}case`Quant`:case`Fcn`:{let e=me(t.bounds,a);return{...t,bounds:e,body:n(o(e),t.body)}}case`SetOf`:{let e=me(t.bounds,a);return{...t,bounds:e,element:n(o(e),t.element)}}case`Tquant`:{let i=t.names.reduce((e,t)=>r(e,{kind:`Flex`,name:t}),e);return{...t,body:n(i,t.body)}}case`Choose`:{let i=t.domain&&a(t.domain),o=i?re(t.name,i):k(t.name,`Constant`);return{...t,domain:i,body:n(r(e,o),t.body)}}case`SetSt`:{let i=a(t.domain),o=re(t.name,i);return{...t,domain:i,body:n(r(e,o),t.body)}}case`Bang`:{let e=t.selectors.map(e=>he(e,a));return{...t,expression:a(t.expression),selectors:e}}case`Apply`:{let e=t.args.map(a);return{...t,operator:a(t.operator),args:e}}case`With`:case`Dot`:case`Parens`:return{...t,expression:a(t.expression)};case`If`:{let e=a(t.alternative),n=a(t.consequent);return{...t,condition:a(t.condition),consequent:n,alternative:e}}case`List`:return{...t,items:t.items.map(a)};case`SetEnum`:case`Tuple`:return{...t,elements:t.elements.map(a)};case`Product`:return{...t,factors:t.factors.map(a)};case`FcnApp`:{let e=t.args.map(a);return{...t,function:a(t.function),args:e}}case`Arrow`:{let e=a(t.range);return{...t,domain:a(t.domain),range:e}}case`Rect`:case`Record`:return{...t,fields:t.fields.map(e=>({name:e.name,value:a(e.value)}))};case`Except`:{let e=ge(t.specs,a);return{...t,function:a(t.function),specs:e}}case`Sub`:case`Tsub`:case`Fair`:return{...t,subscript:a(t.subscript),action:a(t.action)};case`Case`:{let e=t.other&&a(t.other),n=t.arms.map(e=>{let t=a(e.body);return{condition:a(e.condition),body:t}});return{...t,arms:n,other:e}}}},be=(e,t)=>ye(void 0,e,(e,n)=>t(n),()=>void 0,`all`),xe=e=>{let t=[];return be(e,e=>(t.push(e),e)),t},Se={kind:`Opaque`,name:`$Bad`},Ce=e=>e.kind===`Opaque`&&e.name===Se.name,we=e=>{let t=e.kind===`Parens`?we(e.expression):be(e,we);if(!t.isAtomic)return t;let{isAtomic:n,...r}=t;return r},Te=e=>e.kind===`Let`?S({kind:`Let`,definitions:e.definitions,body:Te(e.body)},e.body):e.kind===`Parens`?Te(e.expression):be(e,Te),Ee=e=>e.kind===`Ix`?e.index<=0:xe(e).some(Ee),De=(e,t,n)=>{let r=(e,r=n)=>De(e,t,r),i=(e,t)=>e.reduce((e,t)=>e??(t.domain.kind===`Domain`?r(t.domain.expression):void 0),void 0)??r(t,[...n,...e.map(e=>k(e.name,e.level))]);switch(e.kind){case`Parens`:return e.form.kind===`Xlabel`?e.form.label===t?{context:n,expression:e.expression,indices:e.form.indices}:void 0:r(e.expression);case`Lambda`:return r(e.body,[...n,...e.params.map(e=>k(e.name,`Unknown`,e.shape))]);case`Let`:{let t=[...n];for(let n of e.definitions){let e=n.kind===`Operator`||n.kind===`Bpragma`?r(n.body,[...t]):void 0;if(e)return e;t.push({kind:`Defn`,definition:n,whereDefined:`Builtin`,visibility:`Visible`,isLocal:!0})}return r(e.body,t)}case`Quant`:case`Fcn`:return i(e.bounds,e.body);case`SetOf`:return i(e.bounds,e.element);case`Tquant`:return r(e.body,[...n,...e.names.map(e=>({kind:`Flex`,name:e}))]);case`Choose`:case`SetSt`:return(e.domain&&r(e.domain))??r(e.body,[...n,k(e.name,`Constant`)]);case`Sequent`:{let t=[...n];for(let n of e.sequent.context){if(n.kind!==`Fact`)return;let e=r(n.expression,[...t]);if(e)return e;t.push(n)}return r(e.sequent.active,t)}default:for(let t of xe(e)){let e=r(t);if(e)return e}return}},Oe=(e,t)=>b(Array.from({length:e},(e,t)=>({kind:`Ix`,index:t+1})),v(e+t)),R=e=>Array.from({length:e},(t,n)=>({kind:`Ix`,index:e-n})),ke=(t,n,r)=>{switch(n.kind){case`Quant`:case`Fcn`:case`SetOf`:{if(n.bounds.length!==r.length){let i=n.bounds.length,a=`Arity mismatch in subexpression instance.\nExpected ${i} argument${i===1?``:`s`}, but found${r.length<i?` only`:``} ${r.length}.`;throw t(g(n.location,a)),new e.ut(a,{failure:`Expr.Deref.deref_inst`})}let i=n.kind===`SetOf`?n.element:n.body;return P(b(r,v(0)),i)}case`Tquant`:return ke(t,S({kind:`Quant`,quantifier:n.quantifier,bounds:n.names.map(e=>({name:e,level:`State`,domain:{kind:`NoDomain`}})),body:n.body},n),r);case`Lambda`:return ke(t,S({kind:`Quant`,quantifier:`Forall`,bounds:n.params.map(e=>({name:e.name,level:`Unknown`,domain:{kind:`NoDomain`}})),body:n.body},n),r);case`SetSt`:case`Choose`:if(r.length!==1){let i=`Arity mismatch in subexpression instance.\nExpected 1 argument, but found ${r.length}.`;throw t(g(n.location,i)),new e.ut(i,{failure:`Expr.Deref.deref_inst`})}return P(b(r,v(0)),n.body);default:{let r=`Cannot instantiate non-binding expression`;throw t(g(n.location,r)),new e.ut(r,{failure:`Expr.Deref.deref_inst`})}}},Ae=(t,n,r)=>{let i=(()=>{switch(r.kind){case`Quant`:case`Fcn`:case`SetOf`:return r.bounds.map(e=>({name:e.name,shape:0}));case`Tquant`:return r.names.map(e=>({name:e,shape:0}));case`Lambda`:return r.params;case`SetSt`:case`Choose`:return[{name:r.name,shape:0}];default:{let n=`Cannot abstract over bound variables in a non-binding expression`;throw t(g(r.location,n)),new e.ut(n,{failure:`Expr.Deref.deref_at`})}}})(),a=P(Oe(n,i.length),r);return[i,ke(t,a,R(i.length))]},je=(t,n,r,i,a,o)=>{let s=n=>{if(!(i<=n))throw t(g(a.location,o)),new e.ut(o,{failure:`Expr.Deref.deref_num`})},c=e=>(s(e.length),e[i-1]),l=(()=>{switch(r.kind){case`Sequent`:{let a=r.sequent;s(a.context.length+1);let o=a.context[i-1];if(o&&o.kind!==`Fact`){let n=`subexpression reference does not resolve to an expression`;throw t(g(r.location,n)),new e.ut(n,{failure:`Expr.Deref.deref_num`})}let c=P(v(-(i-1)),o?o.expression:a.active);if(Ee(c))throw t(g(r.location,`subexpression of ASSUME/PROVE uses identifiers declared therein
10
10
  Tlapm does not handle yet such subexpression namings.`)),new e.ut(`Subexpression of ASSUME/PROVE uses identifiers declared therein
11
11
 
12
12
  Tlapm does not handle yet such subexpression namings.`,{failure:`Expr.Deref.deref_num`});return[n,c]}case`Apply`:return[n,c(r.args)];case`With`:return je(t,n,r.expression,i,a,o);case`If`:return[n,c([r.condition,r.consequent,r.alternative])];case`List`:return[n,c(r.items)];case`SetEnum`:case`Tuple`:return[n,c(r.elements)];case`Product`:return[n,c(r.factors)];case`Let`:return s(1),[[...n,...r.definitions],r.body];case`Quant`:case`SetOf`:case`Fcn`:return[n,c(r.bounds.flatMap(e=>e.domain.kind===`Domain`?[e.domain.expression]:[]))];case`Choose`:case`SetSt`:if(!r.domain)break;return[n,c([r.domain])];case`Arrow`:return[n,c([r.domain,r.range])];case`FcnApp`:{let e=r.args.length===1?r.args[0]:S({kind:`Tuple`,elements:r.args},r);return[n,c([r.function,e])]}case`Rect`:case`Record`:return[n,c(r.fields.map(e=>e.value))];case`Dot`:return[n,c([r.expression,S({kind:`String`,value:r.field},r)])];case`Except`:return[n,c([r.function,...r.specs.map(e=>e.value)])];case`Sub`:case`Tsub`:return[n,c([r.action,r.subscript])];case`Fair`:return[n,c([r.subscript,r.action])];case`Case`:return[n,c([...r.arms.map(e=>S({kind:`Tuple`,elements:[e.condition,e.body]},e.body)),...r.other?[S({kind:`Tuple`,elements:[Se,r.other]},r.other)]:[]])]}let l=`Expression has no subexpressions`;throw t(g(r.location,l)),new e.ut(l,{failure:`Expr.Deref.deref_num`})})();if(Ce(l[1])){let n=`Cannot resolve subexpression reference !${i}`;throw t(g(r.location,n)),new e.ut(n,{failure:`Expr.Deref.deref_num`})}return l},Me=(e,t)=>{let n=e.length,r=e;for(let e=n-1;e>=0;e--)r.includes(n-e)||(r=r.map(t=>t+e<n?t:t-1));return r.map(e=>t[n-e])},Ne=(t,n,r,i,a)=>{let o=De(r,i,[]);if(!o)return t(g(r.location,`Could not find label ${i}`)),{params:[],definitions:[],expression:Se};let s=o.indices;if(s.length!==a.length&&a.length>0){let n=s.length===1?``:`s`,r=`Expected ${s.length} argument${n} for labelled reference !${i}, but found ${a.length}`;throw t(g(o.expression.location,r)),new e.ut(r,{failure:`Expr.Deref.deref_lsub`})}let c=a.length===0?s.map(e=>({name:e.name,shape:0})):[],l=a.length===0?R(s.length):a,u=o.context.reduceRight((e,t)=>t.kind===`Defn`?S({kind:`Let`,definitions:[t.definition],body:e},e):t.kind===`Fresh`?S({kind:`Quant`,quantifier:`Forall`,bounds:[{name:t.name,level:`Constant`,domain:{kind:`NoDomain`}}],body:e},e):P(v(-1),e),o.expression),d=P(Oe(n,c.length),u),f=[],p=d,m=Me(s.map(e=>e.index),l);for(;m.length>0;)if(p.kind===`Let`&&p.definitions.length===1)f.push(p.definitions[0]),p=p.body,m=m.map(e=>P(v(1),e));else{if(p.kind!==`Quant`||p.bounds.length!==1)throw new e.mt(`File "src/expr/e_deref.ml", line 477, characters 21-33: Assertion failed`);p=P(y(m[0],v(0)),p.body),m=m.slice(1)}return{params:c,definitions:f,expression:p}},Pe=(t,n,r,i,a)=>{if(r.kind!==`Let`)throw t(g(r.location,`not a LET expression`)),new e.ut(`not a LET expression`,{failure:`Expr.Deref.deref_letop`});let o=r.definitions.findIndex(e=>e.kind===`Operator`&&e.name===i),s=r.definitions[o];if(!s||s.kind!==`Operator`){let n=`no definition of operator ${i}`;throw t(g(r.location,n)),new e.ut(n,{failure:`Expr.Deref.deref_letop`})}let c=s.body,l=c.kind===`Lambda`?S({...c,body:S({kind:`Parens`,expression:c.body,form:{kind:`Xlabel`,label:i,indices:c.params.map((e,t)=>({name:e.name,index:c.params.length-t}))}},c.body)},c):S({kind:`Parens`,expression:c,form:{kind:`Xlabel`,label:i,indices:[]}},c);return Ne(t,n,S({kind:`Let`,definitions:r.definitions.slice(0,o),body:l},c),i,a)},Fe=(t,n,r,i)=>{let[a,...o]=i;if(!a){let e=r.definitions.length===0?r.expression:S({kind:`Let`,definitions:r.definitions,body:r.expression},r.expression),t=r.params.length===0?e:S({kind:`Lambda`,params:r.params,body:e},e);return{...we(t),isAtomic:!0}}if(r.expression.isAtomic)return t(g(r.expression.location,`Expression has no subexpressions`)),Se;let s=n?r.expression:Te(r.expression),c=r.definitions.length,l=(()=>{let i=(e,n)=>{let[i,a]=je(t,[],s,e,r.expression,n);return{params:[],definitions:i,expression:a,rest:o,isLabel:!1}};switch(a.kind){case`Down`:{let[r,...i]=o;if(s.kind===`Let`&&r?.kind===`Label`&&n)return{...Pe(t,c,s,r.label,r.args),rest:i,isLabel:!0};if(n)return{params:[],definitions:[],expression:s,rest:o,isLabel:!1};throw new e.ut(`!: is forbidden for this expression.
13
- `,{failure:`Expr.Deref.deref: !:`})}case`Number`:return i(a.value,`Cannot resolve !${a.value}`);case`Left`:return i(1,`Cannot resolve !<<`);case`Right`:return i(2,`Cannot resolve !>>`);case`Instance`:return{params:[],definitions:[],expression:ke(t,s,a.args),rest:o,isLabel:!1};case`Label`:return{...s.kind===`Let`&&!n?Pe(t,c,s,a.label,a.args):Ne(t,c,s,a.label,a.args),rest:o,isLabel:!0};case`At`:{let[e,n]=Ae(t,c,s);return{params:e,definitions:[],expression:n,rest:o,isLabel:!1}}}})();return Fe(t,l.isLabel,{params:[...r.params,...l.params],definitions:[...r.definitions,...l.definitions],expression:l.expression},l.rest.map(e=>he(e,e=>P(v(l.definitions.length),e))))},Ie=(e,t,n)=>{if(n.length>0)return{params:[],definitions:[],expression:ke(e,t,n)};if(t.kind!==`Lambda`)return{params:[],definitions:[],expression:t};let[r,i]=Ae(e,0,t);return{params:r,definitions:[],expression:i}},Le=(t,n,r,i)=>{let a=Fe(t,!0,Ie(t,n,r),i);if(Ce(a)){let r=`Could not resolve subexpression reference`;throw t(g(n.location,r)),new e.ut(r,{failure:`Expr.Anon: 2`})}return a},Re=e=>e.kind===`Named`?`<${e.level}>${e.label}`:`<${e.level}>`,ze=e=>++e.value,Be={kind:`Fact`,expression:{kind:`At`,isExcept:!1},visibility:`Visible`},Ve={Number:`1NUM`,Down:`1DOWN`,At:`1AT`,Instance:`1INST`,Left:`1`,Right:`1`},He={kind:`Opaque`,name:`$badexp`},Ue=(t,n,r)=>{let i,a=e=>e.scope?.size??0,o=(e,t)=>{if(t.kind===`At`&&t.isExcept)return i?F(a(e)-i.size,i.expression):t;if(t.kind!==`Except`)return d(e,t);let n=o(e,t.function);return t.specs.reduce((n,r)=>{let[s,c]=O(n,r.trail,(t,n)=>{if(n.kind===`Dot`)return[S({kind:`Dot`,expression:t,field:n.field},t),n];let r=o(e,n.expression);return[S({kind:`FcnApp`,function:t,args:[r]},t),{kind:`Apply`,expression:r}]}),l=i;i={expression:s,size:a(e)};let u=o(e,r.value);return i=l,S({kind:`Except`,function:n,specs:[{trail:c,value:u}]},t)},n)},s=(e,t,n)=>{let r=S({kind:`Ix`,index:e},n);return t.length===0?r:S({kind:`Apply`,operator:r,args:t},n)},c=(e,t,n,r,i)=>{if(t!==`Builtin`)return s(e,r,i);let a=F(e,n);return S(r.length===0?a:ie(a,r),i)},l=(t,n,i,a)=>{let o=te(t.scope,n);if(!o){let t=`Operator "${n}" not found`;throw r(g(a.location,t)),new e.ut(t,{failure:`Expr.Anon: 4`})}let l=o.depth+1,u=o.hyp;switch(u.kind){case`Defn`:{let t=u.definition;if(t.kind===`Operator`)return c(l,u.whereDefined,t.body,i,a);if(t.kind===`Recursive`)throw new e.ut(`Recursive operators not supported by TLAPS`,{failure:`Expr.Anon: Recursive`});return s(l,i,a)}case`Fresh`:return s(l,i,a);case`Flex`:return S({kind:`Ix`,index:l},a);case`Fact`:throw new e.mt(`File "src/expr/e_anon.ml", line 230, characters 24-36: Assertion failed`)}},u=(t,n,i,a,s,l)=>{let d=te(t.scope,n);if(!d){let[s,...c]=a;if(s?.kind===`Label`){let e=s.args.map(e=>o(t,e));return u(t,`${n}!${s.label}`,[...i,...e],c,!0,l)}let d=`Operator "${n}" not found`;throw s&&r(g(l.location,d)),new e.ut(d,{failure:`Expr.Anon: ${s?Ve[s.kind]:`1EMPTY`}`})}let f=d.hyp;if(f.kind!==`Defn`||f.definition.kind!==`Operator`&&f.definition.kind!==`Bpragma`)throw new e.ut(`invalid subexpression reference`);let p=d.depth+1;if(a.length===0&&s)return i.length===0?S({kind:`Ix`,index:p},l):c(p,f.whereDefined,f.definition.body,i,l);let m=We(F(p,f.definition.body),l);return We(Le(r,m,i,a),l)},d=(e,t)=>{switch(t.kind){case`Bang`:{let n=t.expression;if(n.kind===`Apply`&&n.operator.kind===`Opaque`){let r=t.selectors.map(t=>he(t,t=>o(e,t))),i=n.args.map(t=>o(e,t)),a={warnedSteps:[],scope:e.scope};return u(a,n.operator.name,i,r,!1,t)}return o(e,{...t,expression:S({kind:`Apply`,operator:n,args:[]},n)})}case`Apply`:{if(t.operator.kind!==`Opaque`)return b(e,t);let n=t.operator.name;if(e.warnedSteps.includes(n))return r({text:`${_(t.location)}Warning: ${n} does not introduce any assumptions. It does not make sense to use it here.\n`,channel:`toolbox`}),S({kind:`Internal`,builtin:`TRUE`},t);let i=t.args.map(t=>o(e,t));return l(e,n,i,t)}case`Opaque`:return o(e,S({kind:`Apply`,operator:t,args:[]},t));case`Parens`:return t.form.kind===`Syntax`?o(e,t.expression):{...t,expression:o(e,t.expression),form:f(e,t.form)};default:return b(e,t)}},f=(t,n)=>n.kind===`Nlabel`?{kind:`Xlabel`,label:n.label,indices:n.names.map(n=>{let r=te(t.scope,n);if(!r)throw new e.ut(`Identifier "${n}" in label parameters not found`);return{name:n,index:r.depth+1}})}:n,p=(e,t)=>({warnedSteps:e.warnedSteps,scope:t}),m=(e,t)=>p(e,E(e.scope,t)),h=(e,t)=>{let n=me(t,t=>o(e,t));return[n.reduce((e,t)=>m(e,k(t.name,t.level)),e),n]},b=(e,t)=>{if(t.kind===`Sequent`)return{...t,sequent:A(e,t.sequent)[1]};if(t.kind===`Let`){let[n,r]=C(e,t.definitions);return{...t,definitions:r,body:o(n,t.body)}}return ye(e,t,o,m)},x=(e,t)=>{if(t.kind!==`Operator`)return t;let n=t.body;if(n.kind!==`Fcn`)return{...t,body:o(e,n)};let r=o(m(e,k(t.name,`Constant`)),n);if(L(P(y({kind:`Opaque`,name:`%%%`},v(1)),r),r))return{...t,body:F(-1,r)};let i=w(`Eq`,[S({kind:`Ix`,index:1},r),r],r);return{...t,body:S({kind:`Choose`,name:t.name,domain:void 0,body:i},r)}},C=(e,t)=>{let r=e,i=[...t],a=[];for(let e=0;e<i.length;e++){let t=i[e];if(t.kind===`Instance`){i.splice(e+1,0,...n(r.scope,t));continue}let o=x(r,t);r=m(r,{kind:`Defn`,definition:o,whereDefined:`User`,visibility:`Visible`,isLocal:!0}),a.push(o)}return[r,a]},D=(e,t)=>{let n=(()=>{switch(t.kind){case`Fresh`:return t.domain?{...t,domain:o(e,t.domain)}:t;case`Flex`:return t;case`Defn`:return{...t,definition:x(e,t.definition)};case`Fact`:return{...t,expression:o(e,t.expression)}}})();return[m(e,n),n]},A=(e,t)=>{let[n,r]=O(e,t.context,D);return[n,{context:r,active:o(n,t.active)}]},re=(e,t)=>({warnedSteps:[Re(t),...e.warnedSteps],scope:e.scope}),j=(e,t,n,r)=>m(e,{kind:`Defn`,definition:{kind:`Operator`,name:Re(t),body:n,location:r.location},whereDefined:`Proof`,visibility:`Visible`,isLocal:!0,location:r.location}),M=(e,t)=>p(e,ee(e.scope,Array.from({length:t},()=>Be))),N=e=>{let t=[...e.context.map((t,n)=>{let r=e.context.length-n+1;if(t.kind===`Fact`)return F(r,t.expression);if(t.kind!==`Fresh`||!t.domain)return He;let i=w(`Mem`,[S({kind:`Ix`,index:0},t.domain),t.domain],t.domain);return F(r,i)}),F(1,e.active)];return t.length===1?t[0]:{kind:`Tuple`,elements:t}},ae=e=>e.kind!==`Use`&&e.kind!==`Hide`&&e.kind!==`Define`,oe=(e,t)=>({facts:t.facts.map(t=>o(e,t)),defs:t.defs.flatMap(t=>{if(t.kind===`Dx`)return[t];let n=o(e,S({kind:`Opaque`,name:t.name},t));return n.kind===`Ix`?ne(e.scope,n.index-1)?.hyp.kind===`Defn`?[{kind:`Dx`,index:n.index,location:t.location}]:(r({text:`${_(t.location)}${JSON.stringify(t.name)} is not a definition and cannot be used in a DEF clause.`,channel:`toolbox`}),[]):(r({text:`${_(t.location)}Ignored unexpandable identifier ${JSON.stringify(t.name)} in BY DEF.`,channel:`stderr`}),[])})}),se=(e,t)=>{switch(t.kind){case`Steps`:{let[n,r]=O(e,t.steps,I),i=se(t.step?re(n,t.step):n,t.qed.proof);return{...t,steps:r,qed:{...t.qed,proof:i}}}case`By`:return{...t,usable:oe(e,t.usable)};default:return t}},I=(n,r)=>{let i=r.step?.kind===`Unnamed`&&ae(r)?{kind:`Named`,level:r.step.level,label:`_a${ze(t)}`,isAnonymous:!0}:r.step;if(!i)throw new e.mt;let a={...r,step:i};switch(a.kind){case`Assert`:{let[,e]=A(n,a.sequent),t=e.context.reduce(m,n),r=M(j(M(t,1),i,S(N(e),a),a),1),o=e.context.length===0?re(r,i):r,s={...a,sequent:e,proof:se(o,a.proof)};return[M(j(n,i,S(T(e),a),a),1),s]}case`Pcase`:{let e=o(n,a.expression),t=S({kind:`Tuple`,elements:[F(2,e)]},a),r=M(j(M(n,2),i,t,a),1),s={...a,expression:e,proof:se(r,a.proof)},c=j(n,i,S({kind:`Tuple`,elements:[e]},a),a);return[M(c,1),s]}case`Suffices`:{let[,e]=A(n,a.sequent),t=S({kind:`Tuple`,elements:[S(T(e),a)]},a),r=M(j(n,i,t,a),1),o={...a,sequent:e,proof:se(r,a.proof)},s=e.context.reduce(m,n),c=S({kind:`Tuple`,elements:[S(N(e),a)]},a);return[M(j(M(s,1),i,c,a),1),o]}case`Have`:{let e=o(n,a.expression),t=S({kind:`Tuple`,elements:[F(2,e)]},a);return[M(j(M(n,2),i,t,a),1),{...a,expression:e}]}case`Take`:{let[e,t]=h(n,a.bounds),r=S({kind:`Quant`,quantifier:`Forall`,bounds:t,body:He},a);return[M(j(M(e,1),i,r,a),1),{...a,bounds:t}]}case`Witness`:{let e=a.expressions.map(e=>o(n,e)),t=S({kind:`Tuple`,elements:e},a);return[M(j(M(n,1),i,t,a),1),{...a,expressions:e}]}case`Pick`:{let[e,t]=h(n,a.bounds),r=o(e,a.expression),s=S({kind:`Quant`,quantifier:`Exists`,bounds:t,body:r},a),c=re(M(j(M(n,1),i,s,a),1),i),l={...a,bounds:t,expression:r,proof:se(c,a.proof)},u=t.reduce((e,t)=>m(e,k(t.name,t.level)),M(n,2)),d=F(4+t.length,s);return[M(j(M(u,2),i,d,a),1),l]}case`Use`:{let e=oe(n,a.usable);return[M(n,e.facts.length),{...a,usable:e}]}case`Hide`:return[n,{...a,usable:oe(n,a.usable)}];case`Define`:{let[e,t]=C(n,a.definitions);return[e,{...a,definitions:t}]}case`Forget`:return[n,a]}};return{expr:(e,t)=>o({warnedSteps:[],scope:e},t),defn:(e,t)=>x({warnedSteps:[],scope:e},t),sequent:(e,t)=>A({warnedSteps:[],scope:e},t)[1],usable:(e,t)=>oe({warnedSteps:[],scope:e},t),proof:(e,t)=>se({warnedSteps:[],scope:e},t)}},We=(e,t)=>t.location?{...e,location:t.location}:e,Ge=1000000010,Ke=new TextEncoder,qe=e=>{for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>127)return Ke.encode(e).length;return e.length},Je=()=>({leftTotal:-1,element:{size:-1,token:{kind:`Text`,text:``},length:0}}),Ye=()=>{let e={size:-1,token:{kind:`Begin`,indent:0,box:`hov`},length:0};return{queue:[e],queueStart:0,scanStack:[Je(),{leftTotal:1,element:e}],formatStack:[],margin:78,maxIndent:68,spaceLeft:78,currentIndent:0,isNewLine:!0,leftTotal:1,rightTotal:1,depth:1,output:[]}},Xe=(e,t)=>{e.rightTotal+=t.length,e.queue.push(t)},Ze=(e,t,n)=>{e.output.push(`
13
+ `,{failure:`Expr.Deref.deref: !:`})}case`Number`:return i(a.value,`Cannot resolve !${a.value}`);case`Left`:return i(1,`Cannot resolve !<<`);case`Right`:return i(2,`Cannot resolve !>>`);case`Instance`:return{params:[],definitions:[],expression:ke(t,s,a.args),rest:o,isLabel:!1};case`Label`:return{...s.kind===`Let`&&!n?Pe(t,c,s,a.label,a.args):Ne(t,c,s,a.label,a.args),rest:o,isLabel:!0};case`At`:{let[e,n]=Ae(t,c,s);return{params:e,definitions:[],expression:n,rest:o,isLabel:!1}}}})();return Fe(t,l.isLabel,{params:[...r.params,...l.params],definitions:[...r.definitions,...l.definitions],expression:l.expression},l.rest.map(e=>he(e,e=>P(v(l.definitions.length),e))))},Ie=(e,t,n)=>{if(n.length>0)return{params:[],definitions:[],expression:ke(e,t,n)};if(t.kind!==`Lambda`)return{params:[],definitions:[],expression:t};let[r,i]=Ae(e,0,t);return{params:r,definitions:[],expression:i}},Le=(t,n,r,i)=>{let a=Fe(t,!0,Ie(t,n,r),i);if(Ce(a)){let r=`Could not resolve subexpression reference`;throw t(g(n.location,r)),new e.ut(r,{failure:`Expr.Anon: 2`})}return a},Re=e=>e.kind===`Named`?`<${e.level}>${e.label}`:`<${e.level}>`,ze=e=>++e.value,Be={kind:`Fact`,expression:{kind:`At`,isExcept:!1},visibility:`Visible`},Ve={Number:`1NUM`,Down:`1DOWN`,At:`1AT`,Instance:`1INST`,Left:`1`,Right:`1`},He={kind:`Opaque`,name:`$badexp`},Ue=(t,n,r)=>{let i,a=e=>e.scope?.size??0,o=(e,t)=>{if(t.kind===`At`&&t.isExcept)return i?F(a(e)-i.size,i.expression):t;if(t.kind!==`Except`)return d(e,t);let n=o(e,t.function);return t.specs.reduce((n,r)=>{let[s,c]=O(n,r.trail,(t,n)=>{if(n.kind===`Dot`)return[S({kind:`Dot`,expression:t,field:n.field},t),n];let r=o(e,n.expression);return[S({kind:`FcnApp`,function:t,args:[r]},t),{kind:`Apply`,expression:r}]}),l=i;i={expression:s,size:a(e)};let u=o(e,r.value);return i=l,S({kind:`Except`,function:n,specs:[{trail:c,value:u}]},t)},n)},s=(e,t,n)=>{let r=S({kind:`Ix`,index:e},n);return t.length===0?r:S({kind:`Apply`,operator:r,args:t},n)},c=(e,t,n,r,i)=>{if(t!==`Builtin`)return s(e,r,i);let a=F(e,n);return S(r.length===0?a:j(a,r),i)},l=(t,n,i,a)=>{let o=te(t.scope,n);if(!o){let t=`Operator "${n}" not found`;throw r(g(a.location,t)),new e.ut(t,{failure:`Expr.Anon: 4`})}let l=o.depth+1,u=o.hyp;switch(u.kind){case`Defn`:{let t=u.definition;if(t.kind===`Operator`)return c(l,u.whereDefined,t.body,i,a);if(t.kind===`Recursive`)throw new e.ut(`Recursive operators not supported by TLAPS`,{failure:`Expr.Anon: Recursive`});return s(l,i,a)}case`Fresh`:return s(l,i,a);case`Flex`:return S({kind:`Ix`,index:l},a);case`Fact`:throw new e.mt(`File "src/expr/e_anon.ml", line 230, characters 24-36: Assertion failed`)}},u=(t,n,i,a,s,l)=>{let d=te(t.scope,n);if(!d){let[s,...c]=a;if(s?.kind===`Label`){let e=s.args.map(e=>o(t,e));return u(t,`${n}!${s.label}`,[...i,...e],c,!0,l)}let d=`Operator "${n}" not found`;throw s&&r(g(l.location,d)),new e.ut(d,{failure:`Expr.Anon: ${s?Ve[s.kind]:`1EMPTY`}`})}let f=d.hyp;if(f.kind!==`Defn`||f.definition.kind!==`Operator`&&f.definition.kind!==`Bpragma`)throw new e.ut(`invalid subexpression reference`);let p=d.depth+1;if(a.length===0&&s)return i.length===0?S({kind:`Ix`,index:p},l):c(p,f.whereDefined,f.definition.body,i,l);let m=We(F(p,f.definition.body),l);return We(Le(r,m,i,a),l)},d=(e,t)=>{switch(t.kind){case`Bang`:{let n=t.expression;if(n.kind===`Apply`&&n.operator.kind===`Opaque`){let r=t.selectors.map(t=>he(t,t=>o(e,t))),i=n.args.map(t=>o(e,t)),a={warnedSteps:[],scope:e.scope};return u(a,n.operator.name,i,r,!1,t)}return o(e,{...t,expression:S({kind:`Apply`,operator:n,args:[]},n)})}case`Apply`:{if(t.operator.kind!==`Opaque`)return b(e,t);let n=t.operator.name;if(e.warnedSteps.includes(n))return r({text:`${_(t.location)}Warning: ${n} does not introduce any assumptions. It does not make sense to use it here.\n`,channel:`toolbox`}),S({kind:`Internal`,builtin:`TRUE`},t);let i=t.args.map(t=>o(e,t));return l(e,n,i,t)}case`Opaque`:return o(e,S({kind:`Apply`,operator:t,args:[]},t));case`Parens`:return t.form.kind===`Syntax`?o(e,t.expression):{...t,expression:o(e,t.expression),form:f(e,t.form)};default:return b(e,t)}},f=(t,n)=>n.kind===`Nlabel`?{kind:`Xlabel`,label:n.label,indices:n.names.map(n=>{let r=te(t.scope,n);if(!r)throw new e.ut(`Identifier "${n}" in label parameters not found`);return{name:n,index:r.depth+1}})}:n,p=(e,t)=>({warnedSteps:e.warnedSteps,scope:t}),m=(e,t)=>p(e,E(e.scope,t)),h=(e,t)=>{let n=me(t,t=>o(e,t));return[n.reduce((e,t)=>m(e,k(t.name,t.level)),e),n]},b=(e,t)=>{if(t.kind===`Sequent`)return{...t,sequent:re(e,t.sequent)[1]};if(t.kind===`Let`){let[n,r]=C(e,t.definitions);return{...t,definitions:r,body:o(n,t.body)}}return ye(e,t,o,m)},x=(e,t)=>{if(t.kind!==`Operator`)return t;let n=t.body;if(n.kind!==`Fcn`)return{...t,body:o(e,n)};let r=o(m(e,k(t.name,`Constant`)),n);if(L(P(y({kind:`Opaque`,name:`%%%`},v(1)),r),r))return{...t,body:F(-1,r)};let i=w(`Eq`,[S({kind:`Ix`,index:1},r),r],r);return{...t,body:S({kind:`Choose`,name:t.name,domain:void 0,body:i},r)}},C=(e,t)=>{let r=e,i=[...t],a=[];for(let e=0;e<i.length;e++){let t=i[e];if(t.kind===`Instance`){i.splice(e+1,0,...n(r.scope,t));continue}let o=x(r,t);r=m(r,{kind:`Defn`,definition:o,whereDefined:`User`,visibility:`Visible`,isLocal:!0}),a.push(o)}return[r,a]},D=(e,t)=>{let n=(()=>{switch(t.kind){case`Fresh`:return t.domain?{...t,domain:o(e,t.domain)}:t;case`Flex`:return t;case`Defn`:return{...t,definition:x(e,t.definition)};case`Fact`:return{...t,expression:o(e,t.expression)}}})();return[m(e,n),n]},re=(e,t)=>{let[n,r]=O(e,t.context,D);return[n,{context:r,active:o(n,t.active)}]},ie=(e,t)=>({warnedSteps:[Re(t),...e.warnedSteps],scope:e.scope}),A=(e,t,n,r)=>m(e,{kind:`Defn`,definition:{kind:`Operator`,name:Re(t),body:n,location:r.location},whereDefined:`Proof`,visibility:`Visible`,isLocal:!0,location:r.location}),M=(e,t)=>p(e,ee(e.scope,Array.from({length:t},()=>Be))),N=e=>{let t=[...e.context.map((t,n)=>{let r=e.context.length-n+1;if(t.kind===`Fact`)return F(r,t.expression);if(t.kind!==`Fresh`||!t.domain)return He;let i=w(`Mem`,[S({kind:`Ix`,index:0},t.domain),t.domain],t.domain);return F(r,i)}),F(1,e.active)];return t.length===1?t[0]:{kind:`Tuple`,elements:t}},ae=e=>e.kind!==`Use`&&e.kind!==`Hide`&&e.kind!==`Define`,oe=(e,t)=>({facts:t.facts.map(t=>o(e,t)),defs:t.defs.flatMap(t=>{if(t.kind===`Dx`)return[t];let n=o(e,S({kind:`Opaque`,name:t.name},t));return n.kind===`Ix`?ne(e.scope,n.index-1)?.hyp.kind===`Defn`?[{kind:`Dx`,index:n.index,location:t.location}]:(r({text:`${_(t.location)}${JSON.stringify(t.name)} is not a definition and cannot be used in a DEF clause.`,channel:`toolbox`}),[]):(r({text:`${_(t.location)}Ignored unexpandable identifier ${JSON.stringify(t.name)} in BY DEF.`,channel:`stderr`}),[])})}),se=(e,t)=>{switch(t.kind){case`Steps`:{let[n,r]=O(e,t.steps,I),i=se(t.step?ie(n,t.step):n,t.qed.proof);return{...t,steps:r,qed:{...t.qed,proof:i}}}case`By`:return{...t,usable:oe(e,t.usable)};default:return t}},I=(n,r)=>{let i=r.step?.kind===`Unnamed`&&ae(r)?{kind:`Named`,level:r.step.level,label:`_a${ze(t)}`,isAnonymous:!0}:r.step;if(!i)throw new e.mt;let a={...r,step:i};switch(a.kind){case`Assert`:{let[,e]=re(n,a.sequent),t=e.context.reduce(m,n),r=M(A(M(t,1),i,S(N(e),a),a),1),o=e.context.length===0?ie(r,i):r,s={...a,sequent:e,proof:se(o,a.proof)};return[M(A(n,i,S(T(e),a),a),1),s]}case`Pcase`:{let e=o(n,a.expression),t=S({kind:`Tuple`,elements:[F(2,e)]},a),r=M(A(M(n,2),i,t,a),1),s={...a,expression:e,proof:se(r,a.proof)},c=A(n,i,S({kind:`Tuple`,elements:[e]},a),a);return[M(c,1),s]}case`Suffices`:{let[,e]=re(n,a.sequent),t=S({kind:`Tuple`,elements:[S(T(e),a)]},a),r=M(A(n,i,t,a),1),o={...a,sequent:e,proof:se(r,a.proof)},s=e.context.reduce(m,n),c=S({kind:`Tuple`,elements:[S(N(e),a)]},a);return[M(A(M(s,1),i,c,a),1),o]}case`Have`:{let e=o(n,a.expression),t=S({kind:`Tuple`,elements:[F(2,e)]},a);return[M(A(M(n,2),i,t,a),1),{...a,expression:e}]}case`Take`:{let[e,t]=h(n,a.bounds),r=S({kind:`Quant`,quantifier:`Forall`,bounds:t,body:He},a);return[M(A(M(e,1),i,r,a),1),{...a,bounds:t}]}case`Witness`:{let e=a.expressions.map(e=>o(n,e)),t=S({kind:`Tuple`,elements:e},a);return[M(A(M(n,1),i,t,a),1),{...a,expressions:e}]}case`Pick`:{let[e,t]=h(n,a.bounds),r=o(e,a.expression),s=S({kind:`Quant`,quantifier:`Exists`,bounds:t,body:r},a),c=ie(M(A(M(n,1),i,s,a),1),i),l={...a,bounds:t,expression:r,proof:se(c,a.proof)},u=t.reduce((e,t)=>m(e,k(t.name,t.level)),M(n,2)),d=F(4+t.length,s);return[M(A(M(u,2),i,d,a),1),l]}case`Use`:{let e=oe(n,a.usable);return[M(n,e.facts.length),{...a,usable:e}]}case`Hide`:return[n,{...a,usable:oe(n,a.usable)}];case`Define`:{let[e,t]=C(n,a.definitions);return[e,{...a,definitions:t}]}case`Forget`:return[n,a]}};return{expr:(e,t)=>o({warnedSteps:[],scope:e},t),defn:(e,t)=>x({warnedSteps:[],scope:e},t),sequent:(e,t)=>re({warnedSteps:[],scope:e},t)[1],usable:(e,t)=>oe({warnedSteps:[],scope:e},t),proof:(e,t)=>se({warnedSteps:[],scope:e},t)}},We=(e,t)=>t.location?{...e,location:t.location}:e,Ge=1000000010,Ke=new TextEncoder,qe=e=>{for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>127)return Ke.encode(e).length;return e.length},Je=()=>({leftTotal:-1,element:{size:-1,token:{kind:`Text`,text:``},length:0}}),Ye=()=>{let e={size:-1,token:{kind:`Begin`,indent:0,box:`hov`},length:0};return{queue:[e],queueStart:0,scanStack:[Je(),{leftTotal:1,element:e}],formatStack:[],margin:78,maxIndent:68,spaceLeft:78,currentIndent:0,isNewLine:!0,leftTotal:1,rightTotal:1,depth:1,output:[]}},Xe=(e,t)=>{e.rightTotal+=t.length,e.queue.push(t)},Ze=(e,t,n)=>{e.output.push(`
14
14
  `),e.isNewLine=!0,e.currentIndent=Math.min(e.maxIndent,e.margin-n+t),e.spaceLeft=e.margin-e.currentIndent,e.output.push(` `.repeat(e.currentIndent))},Qe=(e,t)=>{e.spaceLeft-=t,e.output.push(` `.repeat(t))},$e=e=>{let t=e.formatStack.at(-1);t?t.width>e.spaceLeft&&t.box!==`fits`&&t.box!==`h`&&Ze(e,0,t.width):e.output.push(`
15
15
  `)},et=(e,t,n)=>{switch(n.kind){case`Text`:e.spaceLeft-=t,e.output.push(n.text),e.isNewLine=!1;return;case`Begin`:{e.margin-e.spaceLeft>e.maxIndent&&$e(e);let r=e.spaceLeft-n.indent,i=n.box===`v`||t>e.spaceLeft?n.box:`fits`;e.formatStack.push({box:i,width:r});return}case`End`:e.formatStack.pop();return;case`Newline`:{let t=e.formatStack.at(-1);t?Ze(e,0,t.width):e.output.push(`
16
16
  `);return}case`Break`:{let r=e.formatStack.at(-1);if(!r)return;let i=r.width;switch(r.box){case`hov`:t>e.spaceLeft?Ze(e,n.offset,i):Qe(e,n.width);return;case`b`:e.isNewLine?Qe(e,n.width):t>e.spaceLeft||e.currentIndent>e.margin-i+n.offset?Ze(e,n.offset,i):Qe(e,n.width);return;case`hv`:case`v`:Ze(e,n.offset,i);return;case`fits`:case`h`:Qe(e,n.width);return}}}},tt=e=>{for(;e.queueStart<e.queue.length;){let t=e.queue[e.queueStart],n=t.size>=0;if(!n&&e.rightTotal-e.leftTotal<e.spaceLeft)return;e.queueStart++,et(e,n?t.size:Ge,t.token),e.leftTotal+=t.length}e.queue.length=0,e.queueStart=0},nt=(e,t)=>{Xe(e,t),tt(e)},rt=(e,t)=>{let n=e.scanStack.at(-1);n&&(n.leftTotal<e.leftTotal?e.scanStack=[Je()]:n.element.token.kind===(t?`Break`:`Begin`)&&(n.element.size=e.rightTotal+n.element.size,e.scanStack.pop()))},it=(e,t,n)=>{Xe(e,n),t&&rt(e,!0),e.scanStack.push({leftTotal:e.rightTotal,element:n})},at=(e,t,n)=>{e.depth++,it(e,!1,{size:-e.rightTotal,token:{kind:`Begin`,indent:n,box:t},length:0})},ot=e=>{e.depth<=1||(Xe(e,{size:0,token:{kind:`End`},length:0}),rt(e,!0),rt(e,!1),e.depth--)},st=(e,t,n)=>nt(e,{size:t,token:{kind:`Text`,text:n},length:t}),ct=(e,t,n)=>it(e,!0,{size:-e.rightTotal,token:{kind:`Break`,width:t,offset:n},length:t}),lt=e=>nt(e,{size:0,token:{kind:`Newline`},length:0}),ut=e=>{for(;e.depth>1;)ot(e);return e.rightTotal=Ge,tt(e),e.output.join(``)},dt=e=>{ut(e);let t=[...e.output,`
17
17
  `];Object.assign(e,Ye()),e.output=t},ft={h:`h`,v:`v`,hv:`hv`,hov:`hov`,b:`b`},pt=e=>({kind:`Text`,text:e,size:qe(e)}),mt=e=>e===``?[]:[pt(e)],ht={kind:`Break`,width:1,offset:0},gt={kind:`Break`,width:0,offset:0},_t=e=>{let t=e.search(/\d|$/);return{kind:`Open`,box:ft[e.slice(0,t)],indent:Number(e.slice(t)||0)}},z=(e,...t)=>{let n=[],r=0,i=``,a=()=>{i!==``&&(n.push(pt(i)),i=``)};for(let o=0;o<e.length;o++){let s=e[o];if(s===`%`){a();let e=t[r++];typeof e==`string`?e!==``&&n.push(pt(e)):n.push(e),o++}else if(s!==`@`)i+=s;else switch(a(),e[o+1]){case`[`:{if(e[o+2]!==`<`){n.push({kind:`Open`,box:`b`,indent:0}),o++;break}let t=e.indexOf(`>`,o);n.push(_t(e.slice(o+3,t))),o=t;break}case`]`:n.push({kind:`Close`}),o++;break;case` `:n.push(ht),o++;break;case`,`:n.push(gt),o++;break;case`
18
18
  `:n.push({kind:`Newline`}),o++;break;case`.`:n.push({kind:`Flush`}),o++;break;case`;`:{let t=e.indexOf(`>`,o),r=e.slice(o+3,t).split(` `);n.push({kind:`Break`,width:Number(r[0]),offset:Number(r[1])}),o=t;break}case`<`:{let i=e.indexOf(`>`,o);n.push({kind:`Text`,text:String(t[r++]),size:Number(e.slice(o+2,i))}),o=i+2;break}}}return a(),n},B=(e,t,n=[pt(`,`),ht])=>e.flatMap((e,r)=>r===0?[t(e)]:[n,t(e)]),vt=(e,t)=>{for(let n of t)if(Array.isArray(n))vt(e,n);else switch(n.kind){case`Open`:at(e,n.box,n.indent);break;case`Close`:ot(e);break;case`Text`:st(e,n.size,n.text);break;case`Break`:ct(e,n.width,n.offset);break;case`Newline`:lt(e);break;case`Flush`:dt(e)}},yt=e=>{let t=Ye();return vt(t,e),ut(t)},bt=[[`=>`,1,1,`InfixNon`,[]],[`<=>`,2,2,`InfixNon`,[`\\equiv`]],[`/\\`,3,3,`InfixLeft`,[`\\land`]],[`\\/`,3,3,`InfixLeft`,[`\\lor`]],[`~`,4,4,`Prefix`,[`\\neg`,`\\lnot`]],[`=`,5,5,`InfixNon`,[]],[`#`,5,5,`InfixNon`,[`/=`]],[`SUBSET`,8,8,`Prefix`,[]],[`UNION`,8,8,`Prefix`,[]],[`DOMAIN`,9,9,`Prefix`,[]],[`\\subseteq`,5,5,`InfixNon`,[]],[`\\in`,5,5,`InfixNon`,[]],[`\\notin`,5,5,`InfixNon`,[]],[`\\`,8,8,`InfixNon`,[]],[`\\cap`,8,8,`InfixLeft`,[`\\intersect`]],[`\\cup`,8,8,`InfixLeft`,[`\\union`]],[`\\X`,10,13,`Prefix`,[`\\times`]],[`'`,15,15,`Postfix`,[]],[`~>`,2,2,`InfixNon`,[`\\leadsto`]],[`ENABLED`,4,15,`Prefix`,[]],[`UNCHANGED`,4,15,`Prefix`,[]],[`\\cdot`,5,14,`InfixLeft`,[]],[`-+->`,2,2,`InfixNon`,[]],[`[]`,4,15,`Prefix`,[]],[`<>`,4,15,`Prefix`,[]],[`^`,14,14,`InfixNon`,[]],[`/`,13,13,`InfixNon`,[]],[`*`,13,13,`InfixLeft`,[]],[`-.`,12,12,`Prefix`,[`-`]],[`-`,11,11,`InfixLeft`,[]],[`+`,10,10,`InfixLeft`,[]],[`^+`,15,15,`Postfix`,[]],[`^*`,15,15,`Postfix`,[]],[`^#`,15,15,`Postfix`,[]],[`<`,5,5,`InfixNon`,[]],[`=<`,5,5,`InfixNon`,[`<=`,`\\leq`]],[`>`,5,5,`InfixNon`,[]],[`>=`,5,5,`InfixNon`,[`\\geq`]],[`...`,9,9,`InfixNon`,[]],[`..`,9,9,`InfixNon`,[]],[`|`,10,11,`InfixLeft`,[]],[`||`,10,11,`InfixLeft`,[]],[`&&`,13,13,`InfixLeft`,[]],[`&`,13,13,`InfixLeft`,[]],[`$$`,9,13,`InfixLeft`,[]],[`$`,9,13,`InfixLeft`,[]],[`??`,9,13,`InfixLeft`,[]],[`%%`,10,11,`InfixLeft`,[]],[`%`,10,11,`InfixLeft`,[`\\mod`]],[`##`,9,13,`InfixLeft`,[]],[`++`,10,10,`InfixLeft`,[]],[`--`,11,11,`InfixLeft`,[]],[`**`,13,13,`InfixLeft`,[]],[`//`,13,13,`InfixNon`,[]],[`^^`,14,14,`InfixNon`,[]],[`@@`,6,6,`InfixLeft`,[]],[`!!`,9,13,`InfixNon`,[]],[`|-`,5,5,`InfixNon`,[]],[`|=`,5,5,`InfixNon`,[]],[`-|`,5,5,`InfixNon`,[]],[`=|`,5,5,`InfixNon`,[]],[`<:`,7,7,`InfixNon`,[]],[`:>`,7,7,`InfixNon`,[]],[`:=`,5,5,`InfixNon`,[]],[`::=`,5,5,`InfixNon`,[]],[`(+)`,10,10,`InfixLeft`,[`\\oplus`]],[`(-)`,11,11,`InfixLeft`,[`\\ominus`]],[`(.)`,13,13,`InfixLeft`,[`\\odot`]],[`(/)`,13,13,`InfixNon`,[`\\oslash`]],[`(\\X)`,13,13,`InfixLeft`,[`\\otimes`]],[`\\uplus`,9,13,`InfixLeft`,[]],[`\\sqcap`,9,13,`InfixLeft`,[]],[`\\sqcup`,9,13,`InfixLeft`,[]],[`\\div`,13,13,`InfixNon`,[]],[`\\wr`,9,14,`InfixNon`,[]],[`\\star`,13,13,`InfixLeft`,[]],[`\\o`,13,13,`InfixLeft`,[`\\circ`]],[`\\bigcirc`,13,13,`InfixLeft`,[]],[`\\bullet`,13,13,`InfixLeft`,[]],[`\\prec`,5,5,`InfixNon`,[]],[`\\succ`,5,5,`InfixNon`,[]],[`\\preceq`,5,5,`InfixNon`,[]],[`\\succeq`,5,5,`InfixNon`,[]],[`\\sim`,5,5,`InfixNon`,[]],[`\\simeq`,5,5,`InfixNon`,[]],[`\\ll`,5,5,`InfixNon`,[]],[`\\gg`,5,5,`InfixNon`,[]],[`\\asymp`,5,5,`InfixNon`,[]],[`\\subset`,5,5,`InfixNon`,[]],[`\\supset`,5,5,`InfixNon`,[]],[`\\supseteq`,5,5,`InfixNon`,[]],[`\\approx`,5,5,`InfixNon`,[]],[`\\cong`,5,5,`InfixNon`,[]],[`\\sqsubset`,5,5,`InfixNon`,[]],[`\\sqsubseteq`,5,5,`InfixNon`,[]],[`\\sqsupset`,5,5,`InfixNon`,[]],[`\\sqsupseteq`,5,5,`InfixNon`,[]],[`\\doteq`,5,5,`InfixNon`,[]],[`\\propto`,5,5,`InfixNon`,[]]],xt=/* @__PURE__ */ new Map;for(let[e,t,n,r,i]of bt){let a={name:e,low:t,high:n,fixity:r};for(let t of[e,...i])xt.set(t,a)}const St=e=>({name:e,low:-1,high:-1,fixity:`Nonfix`}),Ct=e=>xt.get(e)??St(e),wt={Implies:`=>`,Equiv:`<=>`,Conj:`/\\`,Disj:`\\/`,Neg:`~`,Eq:`=`,Neq:`#`,SUBSET:`SUBSET`,UNION:`UNION`,DOMAIN:`DOMAIN`,Subseteq:`\\subseteq`,Mem:`\\in`,Notmem:`\\notin`,Setminus:`\\`,Cap:`\\cap`,Cup:`\\cup`,Prime:`'`,StrongPrime:`'`,Leadsto:`~>`,ENABLED:`ENABLED`,UNCHANGED:`UNCHANGED`,Cdot:`\\cdot`,Actplus:`-+->`,BoxTrue:`[]`,BoxFalse:`[]`,Diamond:`<>`,Plus:`+`,Minus:`-`,Times:`*`,Ratio:`/`,Quotient:`\\div`,Remainder:`%`,Exp:`^`,Lteq:`=<`,Lt:`<`,Gteq:`>=`,Gt:`>`,Range:`..`,Cat:`\\o`,OneArg:`:>`,Extend:`@@`},Tt=e=>{if(e===`Divides`)return{name:`?|`,low:10,high:11,fixity:`InfixNon`};if(e===`Uminus`)return{...Ct(`-.`),name:`-`};let t=wt[e];return t?Ct(t):St(e)},Et=e=>e.salt===0?e.rep:`${e.rep}_${e.salt}`,Dt=()=>({stack:[],idents:/* @__PURE__ */ new Map,defined:/* @__PURE__ */ new Map}),Ot=(e,t)=>{let n=e.idents.get(t)?.at(-1),r=n?{rep:t,salt:n.salt+1}:{rep:t,salt:0};for(;e.defined.has(Et(r));)r={rep:t,salt:r.salt+1};e.stack.push(r);let i=e.idents.get(t);i?i.push(r):e.idents.set(t,[r]);let a=Et(r);return e.defined.set(a,(e.defined.get(a)??0)+1),a},kt=(e,t)=>{for(let n=0;n<t;n++){let t=e.stack.pop();if(!t)return;e.idents.get(t.rep)?.pop();let n=Et(t),r=(e.defined.get(n)??1)-1;r===0?e.defined.delete(n):e.defined.set(n,r)}},At=(e,t,n)=>{let r=n(t.map(t=>Ot(e,t)));return kt(e,t.length),r},jt=(e,t)=>t.kind===`Atm`||t.kind===`Op`&&e<t.low,Mt=e=>[z(`(`),e,z(`)`)],Nt=(e,t)=>t?Pt(e):Mt(Pt(e)),Pt=e=>{if(e.kind!==`Op`)return e.doc;let t=e.skeleton,n=t=>jt(e.high,t);switch(t.kind){case`Prefix`:case`Postfix`:{let r=t.operand,i=Nt(r,n(r)||r.kind===`Op`&&r.skeleton.kind===t.kind),a=t.kind===`Prefix`?[e.doc,i]:[i,e.doc];return[z(`@[<h>`),...a,z(`@]`)]}case`Infix`:{let r=t.left,i=t.right,a=n(r)||r.kind===`Op`&&r.name===e.name&&t.assoc===`Left`,o=n(i)||t.assoc===`Right`&&i.kind===`Op`&&i.skeleton.kind===`Infix`&&i.skeleton.assoc===`Right`;return[z(`@[<b0>`),Nt(r,a),e.doc,Nt(i,o),z(`@]`)]}}},V=e=>({kind:`Atm`,doc:e}),Ft=e=>({kind:`Big`,doc:e}),It=e=>e.kind===`Lambda`?It(e.body):e.kind===`Sequent`?It(e.sequent.active):e.kind===`With`,Lt=e=>{if(e.kind===`Defn`){let t=e.definition,n=t.kind===`Operator`&&It(t.body);return e.visibility===`Hidden`||n||e.whereDefined!==`User`}return e.kind===`Fact`?e.visibility===`Hidden`||It(e.expression):!1},Rt=e=>e===0?[]:z(`@[<hov1>(%a)@]`,B(Array.from({length:e},()=>`_`),mt)),zt=e=>z(`%s%a`,e.name,Rt(e.shape)),Bt={Constant:`CONSTANT`,State:`STATE`,Action:`ACTION`,Temporal:`TEMPORAL`,Unknown:`UNKNOWN`},Vt=(t=[])=>{let n=Dt(),r=e=>Pt(u(e)),i=(e,t)=>At(n,e.map(e=>e.name),()=>z(`@[<b2>LAMBDA @[<hv0>%a@] :@ %a@]`,B(e,zt),r(t))),a=(e,t)=>{let i=e.map(e=>e.domain.kind===`Domain`?r(e.domain.expression):void 0);return At(n,e.map(e=>e.name),n=>{let r=[];return e.forEach((e,t)=>{t>0&&e.domain.kind===`Ditto`?r.at(-1)?.names.push(n[t]):r.push({names:[n[t]],index:t})}),t(B(r,t=>{let n=B(t.names,mt),r=e[t.index].domain;return r.kind===`NoDomain`?n:r.kind===`Ditto`?z(`@[<hov0>%a@ \\in ??????@]`,n):z(`@[<hov0>%a@ \\in %a@]`,n,i[t.index]??[])}))})},o=e=>{switch(e.kind){case`Down`:return z(`:`);case`Left`:return z(`<<`);case`Right`:return z(`>>`);case`At`:return mt(`@`);case`Number`:return mt(String(e.value));case`Instance`:return z(`@[<b1>(%a)@]`,B(e.args,r));case`Label`:return e.args.length===0?mt(e.label):z(`@[<b2>%s@,@[<b1>(%a)@]@]`,e.label,B(e.args,r))}},s=e=>e.length===0?[]:[z(`!`),B(e,o,z(`!`))],c=e=>{if(e<0)return`#$$${Math.abs(e)}`;if(e===0)return`#$0`;if(e<=n.stack.length)return Et(n.stack[n.stack.length-e]);let r=t[t.length-(e-n.stack.length)];return r?C(r)??`??? FACT ???`:`#$${e}`},l=(t,n)=>{if(t.kind===`Lambda`)return{kind:`Op`,name:` `,doc:z(`@ `),low:20,high:20,skeleton:{kind:`Infix`,assoc:`Left`,left:Ft(i(t.params,t.body)),right:V(z(`(%a)`,B(n,r)))}};if(t.kind===`Bang`)return n.length===0?u(t):V(z(`@[<b2>%a@[<b1>(%a)@]@]`,r(t),B(n,r)));if(t.kind===`Internal`&&n.length===1){if(t.builtin===`BoxFalse`||t.builtin===`Unprimable`)return u(n[0]);if(t.builtin===`Irregular`)return V(z(`@[<h>@<1>%s%a@<1>%s@]`,`<[`,r(n[0]),`]>`))}let a=(()=>{switch(t.kind){case`Ix`:return Ct(c(t.index));case`Opaque`:{let e=Ct(t.name);return{...e,name:`?${e.name}`}}case`Internal`:return Tt(t.builtin);default:throw new e.ut(`Cannot print this operator`)}})(),o=(e,t)=>({kind:`Op`,name:a.name,doc:e,low:a.low,high:a.high,skeleton:t});if(n.length===0)return V(mt(a.name));if(a.fixity===`Nonfix`)return V(z(`@[<b2>%s@[<b1>(%a)@]@]`,a.name,B(n,r)));if(a.fixity===`Prefix`&&n.length===1)return o(/[A-Za-z]$/.test(a.name)?z(`%s@ `,a.name):mt(a.name),{kind:`Prefix`,operand:u(n[0])});if(a.fixity===`Postfix`&&n.length===1)return o(mt(a.name),{kind:`Postfix`,operand:u(n[0])});if(a.fixity.startsWith(`Infix`)&&n.length===2){let e=a.fixity===`InfixLeft`?`Left`:a.fixity===`InfixRight`?`Right`:`Non`;return o(a.name===`..`?mt(a.name):z(`@ %s `,a.name),{kind:`Infix`,assoc:e,left:u(n[0]),right:u(n[1])})}throw new e.ut(`Arity mismatch for operator ${a.name}`)},u=t=>{switch(t.kind){case`Ix`:case`Opaque`:case`Internal`:return l(t,[]);case`Lambda`:return Ft(i(t.params,t.body));case`Bang`:return V([r(t.expression),s(t.selectors)]);case`Apply`:return l(t.operator,t.args);case`Sequent`:return Ft(p(t.sequent));case`With`:return u(t.expression);case`If`:return Ft(z(`@[<hv2>@[<b2>IF@ %a@]@ @[<b2>THEN %a@]@ @[<b2>ELSE %a@]@]`,r(t.condition),r(t.consequent),r(t.alternative)));case`List`:{if(t.bullet===`Refs`&&t.items.length===0)return V(z(`TRUE`));if(t.bullet===`Refs`&&t.items.length===1)return u(t.items[0]);let e=t.bullet===`Or`?`\\/`:`/\\`;return Ft(z(`@[<v0>%a@]`,B(t.items,t=>z(`@[<h>%s %a@]`,e,r(t)),z(`@,`))))}case`Let`:{let e=B(t.definitions,d,z(`@,`)),i=r(t.body);return kt(n,t.definitions.length),Ft([z(`@[<hv0>LET @[<v0>`),e,z(`@]@
19
19
  IN %a@]`,i)])}case`Quant`:return a(t.bounds,e=>Ft(z(`@[<b3>%s @[<b0>%a@] :@ %a@]`,t.quantifier===`Forall`?`\\A`:`\\E`,e,r(t.body))));case`Tquant`:return At(n,t.names,e=>Ft(z(`@[<b4>%s @[<b0>%a@] : %a@]`,t.quantifier===`Forall`?`\\AA`:`\\EE`,B(e,mt),r(t.body))));case`Choose`:{let e=t.domain&&r(t.domain);return At(n,[t.name],([n])=>Ft(e?z(`@[<b2>CHOOSE @[<b2>%s \\in@ %a@] :@ %a@]`,n,e,r(t.body)):z(`@[<b2>CHOOSE %s :@ %a@]`,n,r(t.body))))}case`SetSt`:{let e=r(t.domain);return At(n,[t.name],([n])=>V(z(`@[<b3>{@[<b2>%s \\in@ %a@] :@ %a}@]`,n,e,r(t.body))))}case`SetOf`:return a(t.bounds,e=>V(z(`@[<b3>{%a :@ %a}@]`,r(t.element),e)));case`SetEnum`:return V(z(`@[<h>{@[<b0>%a@]}@]`,B(t.elements,r)));case`Arrow`:return V(z(`@[<b3>[%a ->@ %a]@]`,r(t.domain),r(t.range)));case`Fcn`:return a(t.bounds,e=>V(z(`@[<b3>[%a |->@ %a]@]`,e,r(t.body))));case`FcnApp`:{let e=u(t.function),n=e.kind===`Atm`;return V(z(`@[<h>%s%a%s@[<b1>[%a]@]@]`,n?``:`(`,Pt(e),n?``:`)`,B(t.args,r)))}case`Product`:if(t.factors.length===1)return u(t.factors[0]);if(t.factors.length===0)throw new e.ut(`Expr.Fmt.fmt_expr: PRODUCT []`);return{kind:`Op`,name:`\\X`,doc:z(`@ \\X `),low:10,high:13,skeleton:{kind:`Infix`,assoc:`Right`,left:u(t.factors[0]),right:u({...t,factors:t.factors.slice(1)})}};case`Tuple`:return V(z(`@[<b2><<%a>>@]`,B(t.elements,r)));case`Rect`:return V(z(`@[<b1>[%a]@]`,B(t.fields,e=>z(`@[<h>%s : %a@]`,e.name,r(e.value)))));case`Record`:return V(z(`@[<b1>[%a]@]`,B(t.fields,e=>z(`@[<h>%s |-> %a@]`,e.name,r(e.value)))));case`Except`:return V(z(`@[<b3>[%a EXCEPT@ @[<v0>%a@]]@]`,r(t.function),B(t.specs,e=>z(`!@[<h>%a = %a@]`,e.trail.map(e=>e.kind===`Dot`?z(`.%s`,e.field):z(`[%a]`,r(e.expression))),r(e.value)))));case`Dot`:return{kind:`Op`,name:`.`,doc:z(`.`),low:16,high:16,skeleton:{kind:`Infix`,assoc:`Left`,left:u(t.expression),right:V(mt(t.field))}};case`Sub`:case`Tsub`:{let e=t.modal===`Box`,n=t.kind===`Sub`?e?`[`:`<<`:e?`[][`:`<><<`;return V(z(`@[<h>%s@[<b2>%a@]%s%a@]`,n,r(t.action),e?`]_`:`>>_`,r(t.subscript)))}case`Fair`:return Ft(z(`@[<h>%s_%a (%a)@]`,t.fairness===`Weak`?`WF`:`SF`,Mt(r(t.subscript)),r(t.action)));case`Case`:return Ft(z(`@[<v2>CASE %a%a@]`,B(t.arms,e=>z(`@[<b2>%a ->@ %a@]`,r(e.condition),r(e.body)),z(`@,[] `)),t.other?z(`@,[] @[<b2>OTHER ->@ %a@]`,r(t.other)):[]));case`String`:return V(z(`"%s"`,t.value));case`Num`:return V(mt(t.fraction===``?t.integer:`${t.integer}.${t.fraction}`));case`At`:return V(mt(`@`));case`Parens`:{let e=t.form;if(e.kind===`Syntax`)return u(t.expression);let r=e.kind===`Nlabel`?e.names:e.indices.map(e=>e.index>=1&&e.index<=n.stack.length?c(e.index):`¶${e.index}`),i=u(t.expression);if(r.length===0){let t=i.kind===`Op`?`%s::(%a)`:`%s::%a`;return V(z(t,e.label,Pt(i)))}let a=B(r,mt);return i.kind===`Atm`?V(z(`%s(%a)::%a`,e.label,a,Pt(i))):i.kind===`Big`?V(z(`%s(%a)::(%a)`,e.label,a,Pt(i))):V(z(`(%s(%a):: %a)`,e.label,a,Pt(i)))}}},d=e=>{switch(e.kind){case`Operator`:case`Bpragma`:{let t=e.body;if(t.kind===`Lambda`){let i=At(n,t.params.map(e=>e.name),()=>r(t.body)),a=Ot(n,e.name);return z(`@[<b2>%s@[<b1>(%a)@] ==@ %a@]`,a,B(t.params,zt),i)}let i=r(t);return z(`@[<b2>%s ==@ %a@]`,Ot(n,e.name),i)}case`Instance`:{let t=e.instance,i=At(n,t.args,e=>({doc:z(`@[<b2>INSTANCE %s%a@]`,t.module,t.substitutions.length===0?[]:z(`@ WITH@ %a`,B(t.substitutions,e=>z(`@[<b2>%s <- %a@]`,e.name,r(e.expression))))),args:e})),a=Ot(n,e.name),o=t.args.length===0?mt(a):z(`%s (@[<b0>%a@])`,a,B(i.args,mt));return z(`@[<b2>%a == %a@]`,o,i.doc)}case`Recursive`:{let t=Ot(n,e.name);return z(`@[<b2>NEW CONSTANT %s%a@]`,t,Rt(e.shape))}}},f=e=>{switch(e.kind){case`Fresh`:{let t=e.domain&&e.domainVisibility===`Visible`?r(e.domain):void 0,i=Ot(n,e.name);return[z(`NEW %s %s%a`,Bt[e.level],i,Rt(e.shape)),t?z(` \\in %a`,t):[]]}case`Flex`:return z(`NEW VARIABLE %s`,Ot(n,e.name));case`Defn`:return d(e.definition);case`Fact`:{let t=z(`@[<h>%a @]`,r(e.expression));return Ot(n,``),t}}},p=e=>{if(e.context.length===0)return r(e.active);let t=[];for(let r of e.context)Lt(r)?Ot(n,C(r)??``):t.push(f(r));let i=r(e.active);return kt(n,e.context.length),t.length===0?i:[z(`@[<v0>ASSUME @[<v0>`),B(t,e=>e),z(`@]@
20
- PROVE %a@]`,i)]};return{printSequent:p,printExpr:r}},Ht=(e,t)=>Vt(e).printExpr(t),Ut=e=>{let t=Vt();return yt(z(`@[<b0>%a@]`,t.printSequent(e))).trimEnd()},Wt={kind:`At`,isExcept:!1},Gt=e=>({location:e.location,step:e.step,isSuppressed:e.isSuppressed}),Kt=e=>e?.kind===`Named`&&e.isAnonymous,qt=e=>e?.level??0,Jt=e=>S({kind:`Internal`,builtin:`TRUE`},e),Yt=(e,t)=>e.kind===`Apply`&&e.operator.kind===`Internal`&&e.operator.builtin===t&&e.args.length===2,Xt=(e,...t)=>yt(z(e,...t)),Zt=e=>Qt(e).map((e,t)=>{let n=e.domain.kind===`Domain`?F(t,e.domain.expression):void 0;return{kind:`Fresh`,name:e.name,shape:0,level:n?`Constant`:e.level,domain:n,domainVisibility:`Visible`}}),Qt=e=>{let t={kind:`NoDomain`};return e.map(e=>e.domain.kind===`Ditto`?{...e,domain:t}:(t=e.domain,e))},$t=(e,t)=>t.context.flatMap((n,r)=>n.kind===`Fact`&&n.visibility===`Visible`?[F(e+t.context.length-1-r,n.expression)]:[]),en=(t,n)=>{if(!t.step)throw new e.mt;return{kind:`Defn`,definition:{kind:`Operator`,name:Re(t.step),body:n,location:t.location},whereDefined:`Proof`,visibility:`Visible`,isLocal:!0,location:t.location}},tn=(e,t,n)=>{let r=Kt(n.step)?`Visible`:`Hidden`,i=t.context.map(e=>e.kind===`Fact`?{...e,visibility:r}:e),a=S({kind:`List`,bullet:`Refs`,items:$t(2,t)},n);return{context:[...e,...i,{kind:`Fact`,expression:Jt(n),visibility:`Hidden`,location:n.location},en(n,a),{kind:`Fact`,expression:S({kind:`Ix`,index:1},n),visibility:`Hidden`,location:n.location}],active:F(3,t.active)}},nn=(e,t,n,r,i)=>{let a=e||Kt(i.step)?`Visible`:`Hidden`;return{context:[...t,en(i,S(T(r),i)),{kind:`Fact`,expression:S({kind:`Ix`,index:1},i),visibility:a,location:i.location}],active:F(2,n)}},rn=(t,n,r)=>{if(r.kind!==`Dx`)throw new e.ut(`Unknown definition ${r.name}`);let i=n.length-r.index,a=n[i];if(!a)return n;if(a.kind!==`Defn`)throw new e.ut(`Indicated point is not a definition`);return n.map((e,n)=>n===i?{...a,visibility:t}:e)},an=(e,t)=>e.kind===`Apply`&&e.operator.kind===`Internal`&&e.operator.builtin===`Mem`&&e.args[0]?.kind===`Ix`&&e.args[0].index===0&&L(t,e.args[1]),on=(t,n,r,i)=>{let a=!1,o=r,s=[...i];for(let e=i.length-1;e>=0;e--){o=F(-1,o);let t=i[e];t.kind===`Fact`&&L(t.expression,o)?(a=!0,s[e]={...t,visibility:n}):t.kind===`Fresh`&&t.domain&&an(o,t.domain)&&(a=!0,s[e]={...t,domainVisibility:n})}if(!a){let n=`This expression does not appear in the context and cannot be hidden.`;throw t(g(r.location,`${n}\n`)),new e.ut(n,{failure:`proof.Gen.set_expr`})}return s},sn=(e,t)=>{let n=N(v(1),t)[1];return n[0].domain.kind===`Ditto`&&e.domain.kind===`Domain`?[{...n[0],domain:{kind:`Domain`,expression:F(1,e.domain.expression)}},...n.slice(1)]:n},cn=(e,t)=>{if(e.isSuppressed||t.length===0)return{kind:`Obvious`,...Gt(e)};let n=t.map((e,t)=>{let n=F(2*t+2,e);return{kind:`Assert`,sequent:{context:[],active:n},proof:{kind:`By`,usable:{facts:[F(3,n)],defs:[]},isOnly:!1,location:e.location},location:e.location}}),r={kind:`By`,usable:{facts:[S({kind:`Ix`,index:2*t.length+2},e),...t.map((n,r)=>S({kind:`Ix`,index:2*(t.length-r)},e))],defs:[]},isOnly:!0,...Gt(e)};return{kind:`Steps`,steps:n,qed:{proof:r,location:r.location},...Gt(e)}},ln=(e,t,n)=>({sequent:e,location:t.location,kind:n}),un={total:0,absent:[],omitted:[]},dn=(e,t)=>({total:e.total+t.total,absent:[...e.absent,...t.absent],omitted:[...e.omitted,...t.omitted]}),fn=e=>{switch(e.kind){case`Use`:return{...un,total:e.obligations?.length??0};case`Assert`:case`Suffices`:case`Pcase`:case`Pick`:return pn(e.proof);default:return un}},pn=e=>e.kind===`Steps`?[...e.steps.map(fn),pn(e.qed.proof)].reduce(dn):e.kind!==`Omitted`||!e.obligations||!e.location?{...un,total:e.obligations?.length??0}:{total:e.obligations.length,absent:e.omission===`Implicit`?[e.location]:[],omitted:e.omission===`Explicit`?[e.location]:[]},mn=(e,t)=>e.kind===`At`&&!e.isExcept?S(M(t),e):be(e,e=>mn(e,t)),hn=(t,n,r,i)=>{let a=(t,i)=>{let s=i.location;if(!s||!n.has(s.file)||s.endLine<r.start||s.startLine>r.end)return i;switch(i.kind){case`Obvious`:return{...i,obligations:[ln(t,i,{kind:`Main`})]};case`Omitted`:return{...i,obligations:[ln(t,i,{kind:`Omitted`,omission:i.omission})]};case`Error`:return{...i,obligations:[ln(t,i,{kind:`Error`,message:i.message})]};case`By`:throw new e.ut(`Proof.Gen.generate`);case`Steps`:{let[e,n]=O(t,i.steps,o),r=a(e,i.qed.proof);return{...i,steps:n,qed:{...i.qed,proof:r}}}}},o=(t,n)=>{switch(n.kind){case`Forget`:{let e=t.context.length,r=t.context.map((t,r)=>t.kind===`Fact`&&t.visibility===`Visible`&&n.count+r<e?{...t,visibility:`Hidden`}:t);return[{...t,context:r},n]}case`Use`:{let r=n.usable;if(r.defs.length===0&&r.facts.length===1){let e=r.facts[0],i=ln({...t,active:e},n,{kind:`Support`});return[{context:[...t.context,{kind:`Fact`,expression:e,visibility:`Visible`,location:e.location}],active:F(1,t.active)},{...n,obligations:[i]}]}if(r.facts.length>0)throw new e.ut(`Proof.Gen.gen_step: USE with facts and definitions`);let i=r.defs.reduce((e,t)=>rn(`Visible`,e,t),t.context);return[{...t,context:i},n]}case`Hide`:{let e=n.usable.defs.reduce((e,t)=>rn(`Hidden`,e,t),t.context),r=n.usable.facts.reduceRight((e,t)=>on(i,`Hidden`,t,e),e);return[{...t,context:r},n]}case`Define`:return[{context:[...t.context,...n.definitions.map(e=>({kind:`Defn`,definition:e,whereDefined:`User`,visibility:`Visible`,isLocal:!0,location:e.location}))],active:F(n.definitions.length,t.active)},n];case`Assert`:{let e=a(tn(t.context,n.sequent,n),n.proof),r={...n,proof:e};return[nn(!1,t.context,t.active,n.sequent,r),r]}case`Suffices`:{let e=a(nn(!0,t.context,t.active,n.sequent,n),n.proof),r={...n,proof:e};return[tn(t.context,n.sequent,r),r]}default:throw new e.ut(`Proof.Gen.gen_step`)}},s=(e,t,n,r)=>{let i={kind:`Unnamed`,level:0,id:0},[a,s]=o({context:e,active:{...Wt,location:r}},t===`Use`?{kind:`Use`,usable:n,isOnly:!1,location:r,step:i}:{kind:`Hide`,usable:n,location:r,step:i});return[a.context,s.obligations??[]]},c=(e,t,n,r)=>{if(n.defs.length===0&&n.facts.length===0)return[e,[]];let i=n.defs.length>0,[a,...o]=n.facts,[l,u]=s(e,t,i?{defs:n.defs,facts:[]}:{defs:[],facts:[a]},r),d=i?n.facts:o.map(e=>F(1,e)),[f,p]=c(l,t,{defs:[],facts:d},r);return[f,[...u,...p]]},l=e=>{let t=[],n=e=>{e.kind===`Steps`?(n(e.qed.proof),e.steps.forEach(r)):e.obligations&&!e.isSuppressed&&t.push(...e.obligations)},r=e=>{e.kind===`Use`&&e.obligations&&!e.isSuppressed&&t.push(...e.obligations),(e.kind===`Assert`||e.kind===`Suffices`||e.kind===`Pcase`||e.kind===`Pick`)&&n(e.proof)};return n(e),t},u=e=>({kind:`Named`,level:e,label:`_a${ze(t)}`,isAnonymous:!0}),d=(e,t)=>t?.kind===`Named`?{...t,level:e}:u(e),f=(e,t)=>{let n={...t,step:d(e,t.step)};if(n.kind!==`Steps`)return n;let r=n.steps.map(t=>p(e,t));return{...n,steps:r,qed:{...n.qed,proof:f(e+1,n.qed.proof)}}},p=(e,t)=>{let n={...t,step:d(e,t.step)};switch(n.kind){case`Assert`:case`Suffices`:case`Pcase`:case`Pick`:return{...n,proof:f(e+1,n.proof)};default:return n}},m=(t,n)=>{let r=n.kind===`Apply`?n.operator:n;if(r.kind===`Ix`){let i=t[t.length-r.index];if(!i)throw new e.ut(`expose_connective`);if(i.kind!==`Defn`||i.definition.kind!==`Operator`)return n;let a=F(r.index,i.definition.body);if(n.kind!==`Apply`)return m(t,a);let o={...a,location:n.location};return m(t,S(ie(o,n.args),o))}if(n.kind===`Apply`&&n.operator.kind===`Internal`&&n.operator.builtin===`Prime`){let e=m(t,n.args[0]),r=e=>w(`Prime`,[e],e);return e.kind===`Quant`?S({kind:`Quant`,quantifier:e.quantifier,bounds:e.bounds.map(e=>e.domain.kind===`Domain`?{...e,domain:{kind:`Domain`,expression:r(e.domain.expression)}}:e),body:r(e.body)},n):Yt(e,`Implies`)||Yt(e,`Mem`)?S({kind:`Apply`,operator:e.operator,args:[r(e.args[0]),r(e.args[1])]},n):r(e)}return n.kind===`Parens`?m(t,n.expression):n},h=e=>{if(e.kind!==`Assert`)return;let t=e.sequent.active;return t.kind===`Apply`&&t.args.length===2?t.args[1]:void 0},g=e=>{if(e.kind!==`Steps`)return e;let t=[];return e.steps.forEach(e=>{let n=t.at(-1),r=n&&h(n);if(e.kind!==`Assert`||!r){t.push(e);return}let i=mn(e.sequent.active,F(2,r));t.push({...e,sequent:{...e.sequent,active:i}})}),{...e,steps:t}},_=(e,t,n)=>{let r=g(n);switch(r.kind){case`Obvious`:case`Omitted`:case`Error`:return r;case`By`:{let e=r.usable,t=e.defs.length===0?[]:[{kind:`Use`,usable:{facts:[],defs:e.defs},isOnly:!1,location:r.location}],n=e.facts.map((e,t)=>({kind:`Use`,usable:{facts:[F(t,e)],defs:[]},isOnly:!1,location:e.location,isSuppressed:r.isSuppressed})),i=r.isOnly?[{kind:`Forget`,count:e.facts.length,location:r.location}]:[],a=qt(r.step),o=[...t,...n,...i].map(e=>({...e,step:u(a)})),s={kind:`Obvious`,location:r.location,step:u(a),isSuppressed:r.isSuppressed};return{kind:`Steps`,steps:o,qed:{proof:s,location:s.location,step:s.step},location:r.location,step:r.step,isSuppressed:r.isSuppressed}}case`Steps`:{let n=e,i=t,a=r.steps.flatMap(e=>{let[t,r,a]=b(n,i,e);return n=t,i=r,a}),o=_(n,i,r.qed.proof);return{...r,steps:a,qed:{...r.qed,proof:o}}}}},b=(t,n,r)=>{let i=qt(r.step);switch(r.kind){case`Forget`:return[t,n,[r]];case`Assert`:{let e=tn(t,r.sequent,r),i={...r,proof:_(e.context,e.active,r.proof)},a=nn(!1,t,n,r.sequent,i);return[a.context,a.active,[i]]}case`Suffices`:{let e=nn(!0,t,n,r.sequent,r),i={...r,proof:_(e.context,e.active,r.proof)},a=tn(t,r.sequent,i);return[a.context,a.active,[i]]}case`Use`:{let i={kind:`By`,usable:r.usable,isOnly:r.isOnly,location:r.location,step:r.step,isSuppressed:r.isSuppressed},a=_(t,n,i);if(a.kind!==`Steps`)throw new e.ut(`simplifying BY does not produce a non-leaf proof!`);let o=r.usable.facts.map(()=>({kind:`Fact`,expression:Wt,visibility:`Visible`,location:r.location}));return[[...t,...o],F(r.usable.facts.length,n),a.steps]}case`Hide`:return[r.usable.defs.reduce((t,n)=>{if(n.kind!==`Dx`)throw new e.ut(`set_vis`);let i=t.length-n.index,a=t[i];if(a?.kind!==`Defn`){let t=a?a.kind===`Fact`?`??? FACT ???`:a.name:``;throw new e.ut(`USE DEF ${t} invalid because ${t} is not a defined operator`)}return t.map((e,t)=>t===i?{...a,visibility:`Hidden`,location:r.location}:e)},t),n,[r]];case`Define`:return[[...t,...r.definitions.map(e=>({kind:`Defn`,definition:e,whereDefined:`Proof`,visibility:`Visible`,isLocal:!0,location:r.location}))],F(r.definitions.length,n),[r]];case`Have`:{let e=m(t,n),a={kind:`Fact`,expression:r.expression,visibility:`Visible`,location:r.location},o=Yt(e,`Implies`),s={context:[a],active:o?F(1,e.args[1]):e},c=o?{kind:`By`,usable:{facts:[S({kind:`Ix`,index:2},r)],defs:[]},isOnly:!0,...Gt(r)}:{kind:`Error`,message:Xt(`@.@[<v2>@[%s@ %s@]@,%a@]@.`,`Error: this HAVE step is applied to the following goal,`,`which is not an implication:`,Ht(t,n)),...Gt(r)},l=p(i,{kind:`Suffices`,sequent:s,proof:c,location:r.location,step:r.step});return b(t,n,l)}case`Take`:return b(t,n,p(i,C(t,n,r)));case`Witness`:return b(t,n,p(i,T(t,n,r)));case`Pcase`:{let e={kind:`Assert`,sequent:{context:[{kind:`Fact`,expression:r.expression,visibility:`Visible`,location:r.location}],active:F(1,n)},proof:r.proof,...Gt(r)};return b(t,n,p(i,e))}case`Pick`:{let i=S({kind:`Quant`,quantifier:`Exists`,bounds:r.bounds,body:r.expression},r),a=x(r.step,`ex`),[o,s,c]=b(t,n,{kind:`Assert`,sequent:{context:[],active:i},proof:r.proof,...Gt(r),step:a}),l=F(2,i);if(l.kind!==`Quant`)throw new e.ut(`Proof.Simplify.simplify_step/PICK`);let u=[...Zt(l.bounds),{kind:`Fact`,expression:l.body,visibility:`Visible`,location:l.body.location}],[d,f,p]=b(o,s,{kind:`Suffices`,sequent:{context:u,active:F(u.length,s)},proof:{kind:`Omitted`,omission:`Elsewhere`,...Gt(r)},...Gt(r)});return[d,f,[...c,...p]]}}},x=(e,n)=>({kind:`Named`,level:qt(e),label:`${e?.kind===`Named`?e.label:`_a`}${n}${ze(t)}`,isAnonymous:!1}),C=(e,t,n)=>{let r=Qt(n.bounds),i=(t,n,r,a)=>{let o=a[0];if(!o)return{aux:n,goal:r};let s=m(e,r);if(s.kind!==`Quant`||s.quantifier!==`Forall`||s.bounds.length===0)return Xt(`@.@[<v2>@[<b0>%s@ %s@]@,%a@]@.`,`Error: this TAKE step is applied to the following goal,`,`which is not a universal formula:`,Ht(e,r));let c=s.bounds[0],l=Qt(s.bounds).slice(1),u=o.domain,d=c.domain;if(u.kind===`NoDomain`&&d.kind===`Domain`)return Xt(`@.@[<b0>%s (%s)@ %s (%s \\in %a)@]@.`,`Error: the TAKE argument`,o.name,`does not match the pattern`,c.name,Ht(e,d.expression));if(u.kind===`Domain`&&d.kind===`NoDomain`)return Xt(`@.@[<b0>%s (%s \\in %a)@ %s (%s)@]@.`,`Error: the TAKE argument`,o.name,Ht(e,u.expression),`does not match the pattern`,c.name);let f=u.kind===`Domain`&&d.kind===`Domain`&&!L(u.expression,d.expression)?[{kind:`Apply`,operator:{kind:`Internal`,builtin:`Subseteq`},args:[d.expression,u.expression]},...n]:n;if(l.length===0)return i(1,f,s.body,a.slice(1));let p=a.length===1?l.map(e=>N(v(t),[e])[1][0]):l;return i(t+1,f,S({kind:`Quant`,quantifier:`Forall`,bounds:p,body:s.body},s),a.slice(1))},a=i(1,[],t,r);if(typeof a==`string`)return{kind:`Suffices`,sequent:{context:[{kind:`Fact`,expression:Jt(t),visibility:`Visible`,location:n.location}],active:t},proof:{kind:`Error`,message:a,...Gt(n)},...Gt(n)};let o=a.aux.filter((e,t)=>a.aux.findIndex(t=>L(e,t))===t),s=[S({kind:`Ix`,index:2},n),...o.map(e=>F(2,e))];return{kind:`Suffices`,sequent:{context:Zt(r),active:a.goal},proof:{kind:`By`,usable:{facts:s,defs:[]},isOnly:!0,...Gt(n)},...Gt(n)}},T=(e,t,n)=>{let r=[],i=``,a=t;for(let t of n.expressions){let n=m(e,a);if(n.kind!==`Quant`||n.quantifier!==`Exists`||n.bounds.length===0){i||=Xt(`@.@[<v2>@[<b0>%s@ %s@]@,%a@]@.`,`Error: this WITNESS step is applied to the following goal,`,`which is not an existential formula:`,Ht(e,n)),a=n;break}let[o,...s]=n.bounds,c=s.length===0?n.body:S({kind:`Quant`,quantifier:`Exists`,bounds:sn(o,s),body:n.body},n),l=t;if(o.domain.kind===`Domain`){let n=o.domain.expression,a=m(e,t);if(Yt(a,`Mem`)){let[e,t]=a.args,i=L(t,n)?[]:[w(`Subseteq`,[t,n],t)];r.push(...i,a),l=e}else i||=Xt(`@.@[<b0>%s (%a)@ %s (%s \\in %a)@]@.`,`Error: the WITNESS argument`,Ht(e,a),`does not match the pattern`,o.name,Ht(e,n)),l=a}let u=w(`Unprimable`,[l],l);a=P(y(u,v(0)),c)}let o=i===``?cn(n,r):{kind:`Error`,message:i,...Gt(n)};return{kind:`Suffices`,sequent:{context:[],active:a},proof:o,...Gt(n)}};return{generate:a,collect:l,mutate:c,simplify:_}},gn=(e,t=0)=>({level:e,weights:Array.from({length:t},()=>!0),params:/* @__PURE__ */ new Set}),_n={TRUE:[0,0],FALSE:[0,0],Implies:[0,2],Equiv:[0,2],Conj:[0,2],Disj:[0,2],Neg:[0,1],Eq:[0,2],Neq:[0,2],STRING:[0,0],BOOLEAN:[0,0],SUBSET:[0,1],UNION:[0,1],DOMAIN:[0,1],Subseteq:[0,2],Mem:[0,2],Notmem:[0,2],Setminus:[0,2],Cap:[0,2],Cup:[0,2],Actplus:[3,2],BoxTrue:[3,1],BoxFalse:[3,1],Diamond:[3,1],Prime:[2,1],StrongPrime:[2,1],ENABLED:[1,1],UNCHANGED:[2,1],Leadsto:[3,2],Cdot:[2,2],Nat:[0,0],Int:[0,0],Real:[0,0],Infinity:[0,0],Plus:[0,2],Minus:[0,2],Times:[0,2],Ratio:[0,2],Quotient:[0,2],Remainder:[0,2],Exp:[0,2],Divides:[0,2],Lteq:[0,2],Lt:[0,2],Gteq:[0,2],Gt:[0,2],Range:[0,2],Uminus:[0,1],Seq:[0,1],Len:[0,1],BSeq:[0,2],Cat:[0,2],Append:[0,2],Head:[0,1],Tail:[0,1],SubSeq:[0,3],SelectSeq:[0,2],OneArg:[0,2],Extend:[0,2],Print:[0,2],PrintT:[0,1],Assert:[0,2],JavaTime:[0,0],TLCGet:[0,1],TLCSet:[0,2],Permutations:[0,1],SortSeq:[0,2],RandomElement:[0,1],Any:[0,0],ToString:[0,1],Unprimable:[0,1]},vn={Constant:0,State:1,Action:2,Temporal:3,Unknown:0},yn=e=>new Set(e.flatMap(e=>[...e])),bn=e=>({level:Math.max(0,...e.map(e=>e.level)),weights:[],params:yn(e.map(e=>e.params))}),xn=/* @__PURE__ */ new WeakMap,Sn=t=>{let n=t.hyp;switch(n.kind){case`Flex`:return gn(1);case`Fresh`:return{...gn(vn[n.level],n.shape),params:/* @__PURE__ */ new Set([n.name])};case`Defn`:{let r=n.definition;if(r.kind!==`Operator`&&r.kind!==`Bpragma`)throw new e.mt;return En(t.rest,r.body)}case`Fact`:return En(t.rest,n.expression)}},Cn=e=>{let t=xn.get(e);if(t)return t;let n=Sn(e);return xn.set(e,n),n},wn=(e,t,n)=>{let r=t.flatMap(t=>t.domain.kind===`Domain`?[En(e,t.domain.expression)]:[]),i=t.reduce((e,t)=>E(e,k(t.name,t.level)),e);return bn([En(i,n),...r])},Tn=(t,n)=>{if(t.weights.length!==n.length)throw new e.ut(`Invalid number of arguments`);let r=n.filter((e,n)=>t.weights[n]);return{level:Math.max(t.level,...r.map(e=>e.level)),weights:[],params:yn([t.params,...r.map(e=>e.params)])}},En=(t,n)=>{let r=e=>En(t,e);switch(n.kind){case`Ix`:{let r=ne(t,n.index-1);if(!r)throw new e.mt;return Cn(r)}case`Internal`:{let t=_n[n.builtin];if(!t)throw new e.mt;return gn(t[0],t[1])}case`Opaque`:case`String`:case`Num`:return gn(0);case`Lambda`:{let e=n.params.reduce((e,t)=>E(e,k(t.name,`Unknown`,t.shape)),t),r=En(e,n.body),i=new Set(n.params.map(e=>e.name));return{level:r.level,weights:n.params.map(e=>r.params.has(e.name)),params:new Set([...r.params].filter(e=>!i.has(e)))}}case`Apply`:{let t=n.operator;if(t.kind===`Opaque`)return Tn(gn(0,n.args.length),n.args.map(r));if(t.kind===`Internal`&&n.args.length===1){let i=n.args[0];switch(t.builtin){case`Prime`:case`StrongPrime`:if(r(i).level>1)throw new e.mt;return gn(2,1);case`ENABLED`:{let t=r(i);if(t.level>2)throw new e.mt;return{level:1,weights:[],params:t.params}}case`UNCHANGED`:{let t=r(i);if(t.level>1)throw new e.mt;return{level:2,weights:[],params:t.params}}}}return t.kind===`Internal`&&t.builtin===`Cdot`?(n.args.forEach(r),gn(2)):t.kind===`Internal`&&t.builtin===`Leadsto`?(n.args.forEach(r),gn(3,2)):Tn(r(t),n.args.map(r))}case`Sequent`:{let[e,r]=O(t,n.sequent.context,(e,t)=>{let n=E(e,t);return[n,Cn(n).level]});return gn(Math.max(0,...r,En(e,n.sequent.active).level))}case`With`:case`Dot`:case`Parens`:return r(n.expression);case`Let`:{let e=n.definitions.reduce((e,t)=>E(e,{kind:`Defn`,definition:t,whereDefined:`User`,visibility:`Visible`,isLocal:!0}),t);return En(e,n.body)}case`If`:return bn([n.condition,n.consequent,n.alternative].map(r));case`List`:return bn(n.items.map(r));case`Quant`:case`Fcn`:return wn(t,n.bounds,n.body);case`SetOf`:return wn(t,n.bounds,n.element);case`Tquant`:return En(n.names.reduce((e,t)=>E(e,{kind:`Flex`,name:t}),t),n.body),gn(3);case`Choose`:case`SetSt`:{let e=n.domain&&r(n.domain),i=n.domain?A(n.name,n.domain):k(n.name,`Constant`);return bn([En(E(t,i),n.body),...e?[e]:[]])}case`SetEnum`:case`Tuple`:return bn(n.elements.map(r));case`Product`:return bn(n.factors.map(r));case`FcnApp`:return bn([n.function,...n.args].map(r));case`Arrow`:return bn([r(n.domain),r(n.range)]);case`Rect`:case`Record`:return bn(n.fields.map(e=>r(e.value)));case`Except`:return bn([r(n.function),...n.specs.flatMap(e=>[...e.trail.flatMap(e=>e.kind===`Apply`?[r(e.expression)]:[]),r(e.value)])]);case`Sub`:return{...bn([r(n.action),r(n.subscript)]),level:2};case`Tsub`:case`Fair`:return r(n.action),r(n.subscript),gn(3);case`Case`:return bn([...n.arms.flatMap(e=>[r(e.condition),r(e.body)]),...n.other?[r(n.other)]:[]]);case`Bang`:case`At`:throw new e.mt}},Dn=(t,n)=>{let r=ne(t,n-1)?.hyp;if(!r)throw new e.mt;return r},On=e=>e.kind===`Internal`&&(e.builtin===`ENABLED`||e.builtin===`Cdot`),kn=e=>e.kind===`Apply`&&e.args.length===1&&e.args[0].kind===`Lambda`&&(On(e.operator)||e.operator.kind===`Opaque`&&(e.operator.name===`EnabledWrapper`||e.operator.name===`CdotWrapper`)),An=e=>e===void 0?2:Math.min(2,e),jn=e=>e===void 0?void 0:Math.max(1,e-1),Mn=(t,n,r,i)=>{let a=(e,r=i)=>Mn(t,n,e,r);if(kn(r))return r;if(r.kind===`Sub`)return{...r,action:a(r.action),subscript:a(r.subscript,jn(i))};if(r.kind===`Apply`&&r.operator.kind===`Internal`){let e=r.operator.builtin,[t,n]=r.args;if(e===`Cdot`&&r.args.length===2)return{...r,args:[a(t,An(i)),a(n,1)]};if(e===`ENABLED`&&r.args.length===1)return{...r,args:[a(t,An(i))]};if((e===`Prime`||e===`UNCHANGED`)&&r.args.length===1)return{...r,args:[a(t,jn(i))]}}let o=r.kind===`Apply`&&r.operator.kind===`Ix`?r.operator:r;if(o.kind!==`Ix`)return ye(n,r,(e,n)=>Mn(t,e,n,i),E);if(i===void 0)return r;let s=En(n,r).level,c=Dn(n,o.index),l=e=>`The operator \`${e}\` is declared at:\n${c.location?m(c.location):`<unknown location>`}`;if(c.kind===`Fresh`&&c.level===`Unknown`)throw t(g(r.location,`Declared operator \`${c.name}\` has unknown level and occurs within the scope of \`ENABLED\` or \`\\cdot\` where soundness requires expanding expressions of level >= ${i}.\nIf a constant operator is substituted for this operator, then the expression that results from applying this declared operator has expression level ${s}.\n May need expansion. A declared operator cannot be expanded.\n${l(c.name)}\n and has arity: ${c.shape}`)),new e.mt(`File "src/expr/e_action.ml", line 367, characters 20-26: Assertion failed`);if(s<i)return r;if(s>2||c.kind===`Fact`)throw new e.mt;if(c.kind===`Flex`){if(r.kind!==`Ix`)throw new e.mt;return r}if(c.kind===`Fresh`){let n=`The expression that results from applying the declared operator \`${c.name}\` has expression level ${s} within the scope of \`ENABLED\` or \`\\cdot\` where soundness requires expanding expressions of level >= ${i}. A declared operator cannot be expanded.\n${l(c.name)}\n and has level: ${vn[c.level]}\n and arity: ${c.shape}`;throw t(g(r.location,n)),new e.ut(n)}let u=c.definition;if(u.kind!==`Operator`&&u.kind!==`Bpragma`)throw new e.mt;t({text:`${h(r.location)}[INFO]: Auto-expanding the definition of operator: ${u.name}\n`,channel:`stdout`});let d=P(v(o.index),u.body);return a(M(r.kind===`Apply`?ie(d,r.args):d))},Nn=e=>w(`Eq`,[w(`Prime`,[e],e),e],e),Pn=e=>{let t=e=>e.kind===`Tuple`?e.elements.flatMap(t):[e],n=t(e);return n.length===0?S({kind:`Internal`,builtin:`TRUE`},e):n.length===1?Nn(n[0]):S({kind:`List`,bullet:`And`,items:n.map(Nn)},e)},Fn=t=>{if(t.kind===`Apply`&&t.args.length===1)return Pn(t.args[0]);if(t.kind!==`Sub`)throw new e.mt;let n=Pn(t.subscript),r=t.modal===`Box`?n:w(`Neg`,[n],t);return w(t.modal===`Box`?`Disj`:`Conj`,[t.action,r],t)},In=e=>{let t=(e,t)=>e<<t|e>>>32-t,n=(e,n)=>{let r=Math.imul(t(Math.imul(n,3432918353),15),461845907);return Math.imul(t(e^r,13),5)+3864292196|0},r=new TextEncoder().encode(e),i=r.length-r.length%4,a=0;for(let e=0;e<i;e+=4)a=n(a,r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24);let o=r.subarray(i).reduceRight((e,t)=>e<<8|t,0);return r.length>i&&(a=n(a,o)),a^=r.length,a=Math.imul(a^a>>>16,2246822507),a=Math.imul(a^a>>>13,3266489909),(a^a>>>16)&1073741823},Ln=e=>{let t=Array.from({length:16},()=>[]);return e.forEach((e,n)=>{if(t[In(e)&t.length-1].unshift(e),n+1<=t.length*2)return;let r=Array.from({length:t.length*2},()=>[]);t.flat().forEach(e=>r[In(e)&r.length-1].push(e)),t=r}),t.flat()},Rn=(t,n,r,i,a)=>{let o=e=>Rn(t,n,r,i,e),s=n!==void 0||r!==void 0,c=(e,o)=>{let s={names:[],depth:Math.max(n?.depth??0,r?.depth??0)+1},[c,l]=o,u=[Rn(t,n,s,i,c),...l?[Rn(t,s,r,i,l)]:[]],d=s.names.length===0?[`r#0`]:Ln(s.names);return S({kind:`Apply`,operator:e,args:[{kind:`Lambda`,params:[`_`,...d].map(e=>({name:e,shape:0})),body:u.length===1?u[0]:{kind:`List`,bullet:`And`,items:u}}]},a)};if(kn(a))return a;if(a.kind===`Apply`&&a.operator.kind===`Internal`){let e=a.operator.builtin;if(e===`ENABLED`&&a.args.length===1||e===`Cdot`&&a.args.length===2)return c(a.operator,a.args);if(e===`Prime`&&a.args.length===1){let e=Rn(t,r,void 0,i,a.args[0]);return r?e:{...a,args:[e]}}if(e===`UNCHANGED`&&s)return o(Fn(a))}if(a.kind===`Sub`&&s)return o(Fn(a));if(a.kind===`Ix`){if(!n)return a;let t=Dn(i,a.index);if(t.kind===`Fact`)throw new e.mt;if(t.kind!==`Flex`)return a;let r=`${t.name}#enabled#prime${n.depth}`;return n.names.includes(r)||n.names.push(r),S({kind:`Opaque`,name:r},a)}if(a.kind===`Apply`&&a.operator.kind===`Opaque`)throw t(g(a.location,`Named operator \`${a.operator.name}\` unexpected after anonymization.`)),new e.mt(`File "src/expr/e_action.ml", line 1048, characters 12-18: Assertion failed`);return ye(i,a,(e,i)=>Rn(t,n,r,e,i),E)},zn=(t,n)=>{if(n.kind===`Apply`&&On(n.operator)){let[r]=n.args;if(n.args.length!==1||r.kind!==`Lambda`)throw new e.mt;let[i,...a]=r.params;if(i.name!==`_`)return n;let o=zn({kind:`Compose`,outer:t,inner:v(a.length)},r.body);return{kind:`Apply`,operator:n.operator,args:[{kind:`Lambda`,params:a,body:o}]}}return n.kind===`Ix`?P(t,n):n.kind===`Apply`?S(ie(zn(t,n.operator),n.args.map(e=>zn(t,e))),n):ye(t,n,zn,e=>x(1,e))},Bn=t=>{if(t.kind===`Apply`&&On(t.operator)){let[n]=t.args;if(t.args.length!==1||n.kind!==`Lambda`||n.params[0].name===`_`)throw new e.mt;let r=t.operator.builtin===`Cdot`?`CdotWrapper`:`EnabledWrapper`;return{kind:`Apply`,operator:S({kind:`Opaque`,name:r},t.operator),args:[{kind:`Lambda`,params:n.params.map((e,t)=>({name:`r#${t}`,shape:0})),body:Bn(n.body)}]}}return ye(void 0,t,(e,t)=>Bn(t),()=>void 0)},Vn=t=>{if(t.kind===`Apply`&&t.operator.kind===`Internal`&&t.operator.builtin===`Cdot`&&t.args.length===1&&t.args[0].kind!==`Lambda`)throw new e.mt;return ye(void 0,t,(e,t)=>Vn(t),()=>void 0)},Hn=(e,t,n,r)=>{let i=Mn(t,n,r,void 0),a=zn(v(0),Rn(t,void 0,void 0,n,i));return Vn(Bn(e.expr(n,a)))},Un=(e,t)=>({kind:`Definition`,definition:{kind:`Operator`,name:e,body:{kind:`Internal`,builtin:t}},whereDefined:`Builtin`,visibility:`Visible`,isLocal:!1}),H=(e,t,n)=>({kind:`Definition`,definition:{kind:`Operator`,name:t,body:{kind:`Lambda`,params:Array.from({length:e},(e,t)=>({name:`x${t+1}`,shape:0})),body:{kind:`Apply`,operator:{kind:`Internal`,builtin:n},args:Array.from({length:e},(t,n)=>({kind:`Ix`,index:e-n}))}}},whereDefined:`Builtin`,visibility:`Visible`,isLocal:!1}),Wn=[Un(`Nat`,`Nat`),H(2,`+`,`Plus`),H(2,`-`,`Minus`),H(2,`*`,`Times`),H(2,`^`,`Exp`),H(2,`<`,`Lt`),H(2,`>`,`Gt`),H(2,`=<`,`Lteq`),H(2,`>=`,`Gteq`),H(2,`%`,`Remainder`),H(2,`\\div`,`Quotient`),H(2,`..`,`Range`)],Gn=[...Wn,Un(`Int`,`Int`),H(1,`-.`,`Uminus`)],Kn=[...Gn,Un(`Real`,`Real`),H(2,`/`,`Ratio`),Un(`Infinity`,`Infinity`)],qn=[H(1,`Seq`,`Seq`),H(1,`Len`,`Len`),H(2,`BSeq`,`BSeq`),H(2,`\\o`,`Cat`),H(2,`Append`,`Append`),H(1,`Head`,`Head`),H(1,`Tail`,`Tail`),H(3,`SubSeq`,`SubSeq`),H(2,`SelectSeq`,`SelectSeq`)],Jn=[H(2,`Print`,`Print`),H(1,`PrintT`,`PrintT`),H(2,`Assert`,`Assert`),Un(`JavaTime`,`JavaTime`),H(1,`TLCGet`,`TLCGet`),H(2,`TLCSet`,`TLCSet`),H(2,`:>`,`OneArg`),H(2,`@@`,`Extend`),H(1,`Permutations`,`Permutations`),H(2,`SortSeq`,`SortSeq`),H(1,`RandomElement`,`RandomElement`),Un(`Any`,`Any`),H(1,`ToString`,`ToString`)],Yn=(e,t)=>({name:e,extendees:[],body:t,isImportant:!1,isStandard:!0}),Xn=new Map([Yn(`Naturals`,Wn),Yn(`Integers`,Gn),Yn(`Reals`,Kn),Yn(`Sequences`,qn),Yn(`TLC`,Jn)].map(e=>[e.name,e])),Zn=e=>{let t=e.location;switch(e.kind){case`Constants`:return e.declarations.map(e=>({kind:`Fresh`,name:e.name,shape:e.shape,level:`Constant`,domain:void 0,domainVisibility:`Visible`,location:t}));case`Recursives`:return e.declarations.map(e=>({kind:`Defn`,definition:{kind:`Recursive`,name:e.name,shape:e.shape,location:t},whereDefined:`User`,visibility:`Hidden`,isLocal:!1,location:t}));case`Variables`:return e.names.map(e=>({kind:`Flex`,name:e,location:t}));case`Definition`:return[{kind:`Defn`,definition:e.definition,whereDefined:e.whereDefined,visibility:e.visibility,isLocal:e.isLocal,location:t}];case`Axiom`:return e.name===void 0?[{kind:`Fact`,expression:e.expression,visibility:`Hidden`,location:t}]:$n(e.name,e.expression,t);case`Theorem`:{let n=se(v(-e.axiomCount),{...e.sequent,context:e.sequent.context.slice(e.axiomCount)}),r=S(T(n),e);return e.name===void 0?[{kind:`Fact`,expression:r,visibility:`Hidden`,location:t}]:$n(e.name,r,t)}case`Mutate`:return e.mode===`Use`?e.usable.facts.map((e,n)=>({kind:`Fact`,expression:F(n,e),visibility:`Visible`,location:t})):[];case`Submod`:case`Anoninst`:return[]}},Qn=e=>e.kind===`Axiom`||e.kind===`Theorem`?e.name===void 0?1:2:Zn(e).length,$n=(e,t,n)=>[{kind:`Defn`,definition:{kind:`Operator`,name:e,body:t,location:n},whereDefined:`User`,visibility:`Visible`,isLocal:!1,location:n},{kind:`Fact`,expression:{kind:`Ix`,index:1,location:n},visibility:`Hidden`,location:n}],er=e=>e.body.flatMap(e=>{switch(e.kind){case`Definition`:return[{...e,whereDefined:e.isLocal?`Builtin`:e.whereDefined}];case`Mutate`:return[];case`Theorem`:return[{...e,proof:{kind:`Omitted`,omission:`Elsewhere`,location:e.location}}];case`Submod`:return[{...e,module:{...e.module,body:er(e.module)}}];default:return[e]}}),tr=(t,n,r,i=/* @__PURE__ */ new Set([n.name]))=>{let a=[];for(let o of n.extendees){if(r.has(o))continue;if(i.has(o))throw new e.mt(`Stack overflow`);let n=t.get(o);if(!n)throw new e.ut(`Module "${o}" unknown`);a.push(...er(tr(t,n,r,/* @__PURE__ */ new Set([...i,o])))),r.add(o)}return{...n,body:[...a,...n.body].map(e=>e.kind===`Submod`?{...e,module:tr(t,e.module,/* @__PURE__ */ new Set)}:e)}},nr=e=>{let t=/* @__PURE__ */ new Map,n=(e,n)=>{t.has(e)||t.set(e,n)},r=e=>e.extendees.forEach((t,r)=>n(t,e.extendeeLocations?.[r])),i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Map,o=e=>{typeof e==`object`&&e&&(`instance`in e&&rr(e.instance)&&n(e.instance.module,e.instance.location),Object.values(e).forEach(o))},s=e=>{e.kind===`Theorem`?o(e.sequent):e.kind!==`Submod`&&o(e),e.kind===`Submod`&&(i.add(e.module.name),a.set(e.module.name,e.module),r(e.module),e.module.body.forEach(s))};return e.body.forEach(s),i.forEach(e=>t.delete(e)),r(e),{dependencies:[...t.keys()].sort(ir),locations:t,submodules:a}},rr=e=>typeof e==`object`&&!!e&&`module`in e&&typeof e.module==`string`&&`substitutions`in e,ir=(e,t)=>e<t?-1:+(e>t),ar=(t,n)=>({facts:j(t,n.facts),defs:n.defs.map(n=>{if(n.kind===`Dvar`)return n;let r=P(t,{kind:`Ix`,index:n.index});if(r.kind!==`Ix`)throw new e.ut(`substitution produced bad definition`);return{...n,index:r.index}})}),or=(e,t)=>{switch(t.kind){case`Constants`:case`Recursives`:return[x(t.declarations.length,e),t];case`Variables`:return[x(t.names.length,e),t];case`Definition`:return[x(1,e),{...t,definition:ae(e,t.definition)}];case`Axiom`:return[x(Qn(t),e),{...t,expression:P(e,t.expression)}];case`Theorem`:return[x(Qn(t),e),{...t,sequent:se(e,t.sequent)}];case`Submod`:return[e,{...t,module:{...t.module,body:sr(e,t.module.body)}}];case`Mutate`:return[t.mode===`Hide`?e:x(t.usable.facts.length,e),{...t,usable:ar(e,t.usable)}];case`Anoninst`:return[e,{...t,instance:{...t.instance,substitutions:t.instance.substitutions.map(t=>({name:t.name,expression:P(e,t.expression)}))}}]}},sr=(e,t)=>O(e,t,or)[1],cr=(t,n,r,i)=>{try{let r=Hn(t.anonymizer,t.onWarning,n,{kind:`Sequent`,sequent:i});if(r.kind!==`Sequent`)throw new e.mt;return r.sequent}catch(n){if(!(n instanceof e.ut)||n.failure===void 0)throw n;let a=i.active.location,o=`${n.failure}\nCould not instantiate the theorem ${r===void 0?``:`named: ${r}, `}at: ${a?m(a):`<unknown location>`}`;return t.onWarning({text:`${h(a)}[ERROR]${o}`,channel:`stdout`}),t.onWarning({text:o,channel:`toolboxOnly`}),{context:[],active:S({kind:`Internal`,builtin:`TRUE`},i.active)}}},lr=(e,t,n)=>{if(n.kind===`Theorem`)return{...n,sequent:cr(e,t,n.name,n.sequent)};if(n.kind!==`Definition`)return n;let r=n.definition;if(r.kind!==`Operator`&&r.kind!==`Bpragma`)return n;let i=Hn(e.anonymizer,e.onWarning,t,r.body);return{...n,definition:{...r,body:i}}},ur=(e,t,n)=>O(t,n,(t,n)=>{if(n.kind===`Submod`){let[r,i]=ur(e,t,n.module.body);return[r,{...n,module:{...n.module,body:i}}]}let r=lr(e,t,n);return[ee(t,Zn(r)),r]}),dr=(t,n)=>{let r=[],i=0,a=t;for(;a.length>0;){let[t,...o]=a,s=t.kind===`Constants`?{name:t.declarations[0].name,remaining:{...t,declarations:t.declarations.slice(1)}}:t.kind===`Variables`?{name:t.names[0],remaining:{...t,names:t.names.slice(1)}}:void 0;if(s){let t=n.get(s.name);if(!t)throw new e.ut(`Parameter ${s.name} has no substitute`);let r=Qn(s.remaining)===0;a=sr(y(F(i,t),v(0)),r?o:[s.remaining,...o])}else r.push(t),i+=Qn(t),a=o}return r},fr=(e,t,n)=>{let r=Array.from({length:t},(e,r)=>S({kind:`Ix`,index:t-r},{location:n})),i=Array.from({length:t},(e,t)=>S({kind:`Ix`,index:t+1},{location:n})),a=Array.from({length:e},(e,i)=>{let a=S({kind:`Ix`,index:i+t+1},{location:n});return t>0?S({kind:`Apply`,operator:a,args:r},{location:n}):a});return b([...a,...i].reverse(),v(e+t))},pr=(e,t)=>{let n=t.map(e=>({name:e,shape:0}));return e.kind===`Lambda`?{...e,params:[...n,...e.params]}:t.length===0?e:S({kind:`Lambda`,params:n,body:e},e)},mr=(t,n,r,i,a,o)=>{let s=e=>r===``?e:`${r}!${e}`,c=i.args.length,l=[],u=0,d=n,f=c===0,p=e=>{f||(f=!0,t.onWarning({text:e,channel:`stderr`}))};for(;d.length>0;){let[n,...r]=d;d=r;let f=e=>pr(P(fr(u,c,o),e),i.args);switch(n.kind){case`Definition`:{let r=n.definition;if(r.kind!==`Operator`&&r.kind!==`Bpragma`)throw new e.ut(`Module.Elab.localize`);let i=n.isLocal?`${r.name}$${ze(t.salts)}`:r.name;l.push({...n,definition:{...r,name:s(i),body:f(r.body)},whereDefined:n.isLocal?`Builtin`:n.whereDefined,isLocal:n.isLocal||a}),u+=1;continue}case`Axiom`:{p(`${_(o)}Instancing produces parametric axioms.\nSuch axioms will be forcibly hidden and cannot be cited.\n(This warning appears at-most once per INSTANCE declaration.)`);let e={...n,name:n.name===void 0?void 0:s(n.name),expression:f(n.expression)};l.push(e),u+=Qn(e);continue}case`Theorem`:{p(`${h(o)}Warning: Instancing produces parametric theorems.\nSuch theorems will be forcibly hidden and cannot be cited.\n(This warning appears at-most once per INSTANCE declaration.)`);let e=f(S(T(n.sequent),n));l.push({...n,name:n.name===void 0?void 0:s(n.name),sequent:e.kind===`Sequent`?e.sequent:{context:[],active:e},proof:{kind:`Omitted`,omission:`Elsewhere`,location:n.location}}),u+=1;continue}case`Mutate`:n.mode===`Use`&&(d=sr(v(-n.usable.facts.length),d));continue;case`Submod`:continue;default:throw new e.ut(`Module.Elab.localize`)}}return l},hr=e=>{let t=[],n=e;for(;n.length>0;){let[e,...r]=n;if(e.kind!==`Axiom`){t.push(e),n=r;continue}let i=e.location;e.name!==void 0&&t.push({kind:`Definition`,definition:{kind:`Operator`,name:e.name,body:e.expression,location:i},whereDefined:`Proof`,visibility:`Visible`,isLocal:!1,location:i});let a={kind:`Fact`,expression:e.name===void 0?F(1,e.expression):S({kind:`Ix`,index:2},e),visibility:`Visible`,location:i},o=0,s=r.map(e=>{let t=o;if(o+=Qn(e),e.kind!==`Theorem`)return e;let n=se(v(1),e.sequent);return{...e,sequent:{...n,context:[oe(v(t),a),...n.context]},axiomCount:e.axiomCount+1}});n=sr(v(-1),s)}return t},gr=e=>new Set(e.body.flatMap(e=>e.kind===`Constants`?e.declarations.map(e=>e.name):e.kind===`Variables`?e.names:[])),_r=(t,n,r,i,a,o,s)=>{let c=n.get(i.module);if(!c)throw new e.ut(`Module "${i.module}" unknown`);let l=gr(c);for(let t of i.substitutions)if(!l.has(t.name))throw new e.ut(`Parameter ${t.name} occurs in the statement \`INSTANCE ${i.module} WITH\`, and is not declared in the module ${i.module}`);let u=ee(r,i.args.map(e=>k(e,`Unknown`))),d=new Map(i.substitutions.map(e=>[e.name,e.expression]));for(let t of[...l].sort(ir))if(!d.has(t)){if(!te(u,t))throw new e.ut(`Required parameter ${t} for module ${i.module} could not be inferred.`);d.set(t,S({kind:`Opaque`,name:t},{location:s}))}let f=new Map([...d].map(([e,n])=>[e,t.anonymizer.expr(u,n)])),p=sr(v((u?.size??0)-(c.depth??0)),c.body.map(e=>e.kind===`Theorem`?{...e,proof:{kind:`Omitted`,omission:`Implicit`,location:e.proof.location}}:e)),[,m]=ur(t,u,p);return hr(mr(t,dr(m,f),o,i,a,s))},vr=(e,t,n)=>e===void 0?{hyps:[],sequent:t}:{hyps:[{kind:`Defn`,definition:{kind:`Operator`,name:e,body:S(T(t),{location:n}),location:n},whereDefined:`Proof`,visibility:`Visible`,isLocal:!1,location:n}],sequent:se(v(1),t)},yr=(t,n,r)=>{let i=r.instance.module;if(!t.latestModules.has(i))throw t.onWarning({text:`${_(r.instance.location)}Module ${JSON.stringify(i)} unknown\n`,channel:`toolbox`}),new e.ut(`Module ${JSON.stringify(i)} unknown`,{failure:`Module.Elab.anon#defns`});let a=_r(t,t.latestModules,n,r.instance,!0,r.name,r.location),o=[],s=a;for(;s.length>0;){let[e,...t]=s;e.kind===`Definition`?(o.push(e.definition),s=t):s=sr(v(-Qn(e)),t)}return o},br=(e,t,n,r)=>{let i=[],a=n,o=e=>{i.push(e),a=ee(a,Zn(e))},s=e=>e!==void 0&&te(a,e)!==void 0,c=r.body.map(e=>({unit:e,isAnonymized:!1}));for(let n=0;n<c.length;n++){let i=c[n].unit,l=(r,o,s)=>{let l=_r(e,t,a,r,o,s,i.location);c.splice(n+1,0,...l.map(e=>({unit:e,isAnonymized:!0})))};switch(i.kind){case`Anoninst`:l(i.instance,i.isLocal,``);continue;case`Definition`:{let t=i.definition;if(t.kind===`Instance`){l(t.instance,i.isLocal,t.name);continue}let r=t.kind===`Recursive`||c[n].isAnonymized?t:e.anonymizer.defn(a,t),s={...i,definition:r};if(t.kind===`Recursive`){o(s);continue}let u=Zn(s)[0],d=te(a,t.name);if(d?.hyp.kind===`Defn`&&(d.hyp.definition.kind===`Recursive`||fe(oe(v(d.depth+1),d.hyp),u))){let e=c.slice(n+1),t=sr(y(S({kind:`Ix`,index:d.depth+1},i),v(0)),e.map(e=>e.unit));c.splice(n+1,e.length,...e.map((e,n)=>({...e,unit:t[n]})));continue}o(s);continue}case`Recursives`:case`Constants`:case`Variables`:o(i);continue;case`Axiom`:if(s(i.name))continue;e.latestModules=new Map(t),o({...i,expression:e.anonymizer.expr(a,i.expression)});continue;case`Theorem`:{let n=s(i.name),c=n?`(redundant)${i.name}`:i.name,l=n?{kind:`Obvious`,location:i.proof.location}:i.proof;e.latestModules=new Map(t);let u=e.anonymizer.sequent(a,i.sequent),d=vr(c,u,i.location),f=ee(ee(a,d.hyps),d.sequent.context),p=e.anonymizer.proof(f,l),m=r.isImportant?e.generator.simplify(D(f),d.sequent.active,p):p;o({...i,name:c,sequent:u,proof:m});continue}case`Mutate`:e.latestModules=new Map(t),o({...i,usable:e.anonymizer.usable(a,i.usable)});continue;case`Submod`:o({...i,module:br(e,t,a,i.module)});continue}}let l={...r,body:i,depth:n?.size??0};return t.set(r.name,l),l},xr=(e,t,n)=>{let r=[],i=[],a=un,o=t;for(let t of n.body)switch(t.kind){case`Theorem`:{let n=vr(t.name,t.sequent,t.location),s=[...o,...n.hyps],c=e.generator.generate({context:[...s,...n.sequent.context],active:n.sequent.active},t.proof);r.push(...e.generator.collect(c));let l=pn(c);i.push({...l,location:t.location}),a=dn(a,l);let u=t.name===void 0?S(T(t.sequent),t):{kind:`Ix`,index:1,location:t.location};o=[...s,{kind:`Fact`,expression:u,visibility:`Hidden`,location:t.location}];continue}case`Submod`:{let n=xr(e,o,t.module);r.push(...n.obligations),a=dn(a,n.summary);continue}case`Mutate`:{let[n,i]=e.generator.mutate(o,t.mode,t.usable,t.location);r.push(...i),o=n;continue}default:o=[...o,...Zn(t)]}return{obligations:r,summary:{...a,theorems:i}}},Sr=e=>({kind:`Opaque`,name:e}),Cr=e=>({kind:`Tuple`,elements:e.map(Sr)}),wr=(e,t)=>({kind:`Apply`,operator:{kind:`Internal`,builtin:`Eq`},args:[e,t]}),Tr=e=>e.map(e=>({name:e,level:`Constant`,domain:{kind:`NoDomain`}})),Er=(e,t)=>e?.kind===`Product`&&e.factors.length===t.length?e.factors:void 0,Dr=(e,t)=>t.map((t,n)=>({kind:`Operator`,name:t,body:{kind:`FcnApp`,function:Sr(e),args:[{kind:`Num`,integer:String(n+1),fraction:``}]}})),Or=(e,t)=>e.map((e,n)=>({name:e,level:`Constant`,domain:{kind:`Domain`,expression:t[n]}})),kr=e=>({name:e.name,level:`Constant`,domain:e.domain}),Ar=(e,t,n)=>{let r=[];return t.forEach(e=>{e.kind===`Name`&&e.domain.kind===`Ditto`?r.at(-1)?.push(e):r.push([e])}),r.reduceRight((t,n)=>{let r=n[0];if(r.kind===`Name`)return{kind:`Quant`,quantifier:e,bounds:n.flatMap(e=>e.kind===`Name`?[kr(e)]:[]),body:t,location:t.location};let i=Er(r.domain,r.names);if(i)return{kind:`Quant`,quantifier:e,bounds:Or(r.names,i),body:t,location:t.location};let a={kind:`Apply`,operator:{kind:`Internal`,builtin:e===`Exists`?`Mem`:`Notmem`},args:[Cr(r.names),r.domain]};return{kind:`Quant`,quantifier:e,bounds:Tr(r.names),body:{kind:`List`,bullet:e===`Exists`?`And`:`Or`,items:[a,t]},location:t.location}},n)},jr=(e,t,n,r)=>Er(n,t)?{kind:`Let`,definitions:Dr(e,t),body:r}:{kind:`Quant`,quantifier:`Exists`,bounds:Tr(t),body:{kind:`List`,bullet:`And`,items:[wr(Sr(e),Cr(t)),r]}},Mr=(e,t,n)=>{let r=`choose#${e[0]}`;return{kind:`Choose`,name:r,domain:t,body:jr(r,e,t,n)}},Nr=(e,t,n)=>{let r=`setst#${e[0]}`;return{kind:`SetSt`,name:r,domain:t,body:jr(r,e,t,n)}},Pr=(e,t,n)=>{let r=e.map(e=>{if(e.kind===`Name`)return{bounds:[kr(e)],definitions:[]};let t=Er(e.domain,e.names);if(t&&n)return{bounds:Or(e.names,t),definitions:[]};let r=`fcn#${e.names[0]}`,i={name:r,level:`Constant`,domain:{kind:`Domain`,expression:e.domain}};if(t)return{bounds:[i],definitions:Dr(r,e.names)};let a=`choose#${r}`;return{bounds:[i],definitions:[{kind:`Operator`,name:a,body:Mr(e.names,void 0,wr(Sr(r),Cr(e.names)))},...Dr(a,e.names)]}}),i=r.flatMap(e=>e.definitions);return{bounds:r.flatMap(e=>e.bounds),value:i.length===0?t:{kind:`Let`,definitions:i,body:t}}},Fr=(e,t)=>{let n=Pr(t,e,!0);return{kind:`SetOf`,element:n.value,bounds:n.bounds}},Ir=(e,t)=>{let n=Pr(e,t,!1);return{kind:`Fcn`,bounds:n.bounds,body:n.value}},Lr={"=>":`Implies`,"<=>":`Equiv`,"/\\":`Conj`,"\\/":`Disj`,"~":`Neg`,"=":`Eq`,"#":`Neq`,SUBSET:`SUBSET`,UNION:`UNION`,DOMAIN:`DOMAIN`,"\\subseteq":`Subseteq`,"\\in":`Mem`,"\\notin":`Notmem`,"\\":`Setminus`,"\\cap":`Cap`,"\\cup":`Cup`,"'":`Prime`,"~>":`Leadsto`,ENABLED:`ENABLED`,UNCHANGED:`UNCHANGED`,"\\cdot":`Cdot`,"-+->":`Actplus`,"[]":`BoxTrue`,"<>":`Diamond`,TRUE:`TRUE`,FALSE:`FALSE`,BOOLEAN:`BOOLEAN`,STRING:`STRING`},Rr=(e,t=!1)=>t&&e===`-`?`-.`:Ct(e).name,zr=/^<(\d+|\*|\+)>([A-Za-z0-9_]*)\.*$/,Br=(e,t)=>{if(!e||!t)return e??t;let n=e.startLine<t.startLine||e.startLine===t.startLine&&e.startColumn<=t.startColumn,r=e.endLine>t.endLine||e.endLine===t.endLine&&e.endColumn>=t.endColumn;return{file:e.file,startLine:n?e.startLine:t.startLine,startColumn:n?e.startColumn:t.startColumn,endLine:r?e.endLine:t.endLine,endColumn:r?e.endColumn:t.endColumn}},Vr={Always:`[]`,Eventually:`<>`,Enabled:`ENABLED`,Unchanged:`UNCHANGED`},Hr=(e,t)=>e!==void 0&&t!==void 0&&e.line===t.line&&e.column===t.column,Ur=e=>e.location.range?.start,Wr=e=>e.location.range?.end,Gr=(e,t)=>{let n=e.location.range;return n&&t?{...e,location:{...e.location,range:{...n,end:t}}}:e},Kr=e=>{if(e.kind===`Apply`){let t=Ct(e.operator),n=e.args.length===2&&t.fixity.startsWith(`Infix`),r=e.args.length===1&&t.fixity===`Prefix`;if(!n&&!r)return;let i=e.args.length-1;return{operator:t,isInfix:n,operand:e.args[i],replace:t=>({...e,args:[...e.args.slice(0,i),t]})}}let t=Vr[e.kind];if(t!==void 0&&`expression`in e)return{operator:Ct(t),isInfix:!1,operand:e.expression,replace:t=>({...e,expression:t})}},qr=(e,t)=>e.high<t.low,Jr=e=>{let t=Ct(e.operator),[n,r]=e.args,i=Wr(e),a=t=>{let n=e.location.range,i=Ur(t);return{...e,args:[t,r],location:n&&i?{...e.location,range:{...n,start:i}}:e.location}},o=(e,n)=>{let r=n?Kr(e):void 0;if(!r)return{kind:`Reduced`,isFinal:!1};let s=o(r.operand,Hr(Wr(r.operand),Wr(e)));return s.kind===`Attached`?{kind:`Attached`,expression:Gr(r.replace(s.expression),i)}:!s.isFinal&&(qr(t,r.operator)||r.isInfix&&t.fixity===`InfixLeft`&&r.operator.fixity===`InfixLeft`&&!qr(r.operator,t))?{kind:`Reduced`,isFinal:!qr(t,r.operator)}:{kind:`Attached`,expression:Gr(r.replace(a(r.operand)),i)}},s=o(n,Hr(Ur(n),Ur(e)));return s.kind===`Attached`?s.expression:e},Yr="use instead the class`E_visit.iter_concrete`",Xr=(t,n,r,i)=>{let a=n.split(`
20
+ PROVE %a@]`,i)]};return{printSequent:p,printExpr:r}},Ht=(e,t)=>Vt(e).printExpr(t),Ut=e=>{let t=Vt();return yt(z(`@[<b0>%a@]`,t.printSequent(e))).trimEnd()},Wt={kind:`At`,isExcept:!1},Gt=e=>({location:e.location,step:e.step,isSuppressed:e.isSuppressed}),Kt=e=>e?.kind===`Named`&&e.isAnonymous,qt=e=>e?.level??0,Jt=e=>S({kind:`Internal`,builtin:`TRUE`},e),Yt=(e,t)=>e.kind===`Apply`&&e.operator.kind===`Internal`&&e.operator.builtin===t&&e.args.length===2,Xt=(e,...t)=>yt(z(e,...t)),Zt=e=>Qt(e).map((e,t)=>{let n=e.domain.kind===`Domain`?F(t,e.domain.expression):void 0;return{kind:`Fresh`,name:e.name,shape:0,level:n?`Constant`:e.level,domain:n,domainVisibility:`Visible`}}),Qt=e=>{let t={kind:`NoDomain`};return e.map(e=>e.domain.kind===`Ditto`?{...e,domain:t}:(t=e.domain,e))},$t=(e,t)=>t.context.flatMap((n,r)=>n.kind===`Fact`&&n.visibility===`Visible`?[F(e+t.context.length-1-r,n.expression)]:[]),en=(t,n)=>{if(!t.step)throw new e.mt;return{kind:`Defn`,definition:{kind:`Operator`,name:Re(t.step),body:n,location:t.location},whereDefined:`Proof`,visibility:`Visible`,isLocal:!0,location:t.location}},tn=(e,t,n)=>{let r=Kt(n.step)?`Visible`:`Hidden`,i=t.context.map(e=>e.kind===`Fact`?{...e,visibility:r}:e),a=S({kind:`List`,bullet:`Refs`,items:$t(2,t)},n);return{context:[...e,...i,{kind:`Fact`,expression:Jt(n),visibility:`Hidden`,location:n.location},en(n,a),{kind:`Fact`,expression:S({kind:`Ix`,index:1},n),visibility:`Hidden`,location:n.location}],active:F(3,t.active)}},nn=(e,t,n,r,i)=>{let a=e||Kt(i.step)?`Visible`:`Hidden`;return{context:[...t,en(i,S(T(r),i)),{kind:`Fact`,expression:S({kind:`Ix`,index:1},i),visibility:a,location:i.location}],active:F(2,n)}},rn=(t,n,r)=>{if(r.kind!==`Dx`)throw new e.ut(`Unknown definition ${r.name}`);let i=n.length-r.index,a=n[i];if(!a)return n;if(a.kind!==`Defn`)throw new e.ut(`Indicated point is not a definition`);return n.map((e,n)=>n===i?{...a,visibility:t}:e)},an=(e,t)=>e.kind===`Apply`&&e.operator.kind===`Internal`&&e.operator.builtin===`Mem`&&e.args[0]?.kind===`Ix`&&e.args[0].index===0&&L(t,e.args[1]),on=(t,n,r,i)=>{let a=!1,o=r,s=[...i];for(let e=i.length-1;e>=0;e--){o=F(-1,o);let t=i[e];t.kind===`Fact`&&L(t.expression,o)?(a=!0,s[e]={...t,visibility:n}):t.kind===`Fresh`&&t.domain&&an(o,t.domain)&&(a=!0,s[e]={...t,domainVisibility:n})}if(!a){let n=`This expression does not appear in the context and cannot be hidden.`;throw t(g(r.location,`${n}\n`)),new e.ut(n,{failure:`proof.Gen.set_expr`})}return s},sn=(e,t)=>{let n=N(v(1),t)[1];return n[0].domain.kind===`Ditto`&&e.domain.kind===`Domain`?[{...n[0],domain:{kind:`Domain`,expression:F(1,e.domain.expression)}},...n.slice(1)]:n},cn=(e,t)=>{if(e.isSuppressed||t.length===0)return{kind:`Obvious`,...Gt(e)};let n=t.map((e,t)=>{let n=F(2*t+2,e);return{kind:`Assert`,sequent:{context:[],active:n},proof:{kind:`By`,usable:{facts:[F(3,n)],defs:[]},isOnly:!1,location:e.location},location:e.location}}),r={kind:`By`,usable:{facts:[S({kind:`Ix`,index:2*t.length+2},e),...t.map((n,r)=>S({kind:`Ix`,index:2*(t.length-r)},e))],defs:[]},isOnly:!0,...Gt(e)};return{kind:`Steps`,steps:n,qed:{proof:r,location:r.location},...Gt(e)}},ln=(e,t,n)=>({sequent:e,location:t.location,kind:n}),un={total:0,absent:[],omitted:[]},dn=(e,t)=>({total:e.total+t.total,absent:[...e.absent,...t.absent],omitted:[...e.omitted,...t.omitted]}),fn=e=>{switch(e.kind){case`Use`:return{...un,total:e.obligations?.length??0};case`Assert`:case`Suffices`:case`Pcase`:case`Pick`:return pn(e.proof);default:return un}},pn=e=>e.kind===`Steps`?[...e.steps.map(fn),pn(e.qed.proof)].reduce(dn):e.kind!==`Omitted`||!e.obligations||!e.location?{...un,total:e.obligations?.length??0}:{total:e.obligations.length,absent:e.omission===`Implicit`?[e.location]:[],omitted:e.omission===`Explicit`?[e.location]:[]},mn=(e,t)=>e.kind===`At`&&!e.isExcept?S(M(t),e):be(e,e=>mn(e,t)),hn=(t,n,r,i)=>{let a=(t,i)=>{let s=i.location;if(!s||!n.has(s.file)||s.endLine<r.start||s.startLine>r.end)return i;switch(i.kind){case`Obvious`:return{...i,obligations:[ln(t,i,{kind:`Main`})]};case`Omitted`:return{...i,obligations:[ln(t,i,{kind:`Omitted`,omission:i.omission})]};case`Error`:return{...i,obligations:[ln(t,i,{kind:`Error`,message:i.message})]};case`By`:throw new e.ut(`Proof.Gen.generate`);case`Steps`:{let[e,n]=O(t,i.steps,o),r=a(e,i.qed.proof);return{...i,steps:n,qed:{...i.qed,proof:r}}}}},o=(t,n)=>{switch(n.kind){case`Forget`:{let e=t.context.length,r=t.context.map((t,r)=>t.kind===`Fact`&&t.visibility===`Visible`&&n.count+r<e?{...t,visibility:`Hidden`}:t);return[{...t,context:r},n]}case`Use`:{let r=n.usable;if(r.defs.length===0&&r.facts.length===1){let e=r.facts[0],i=ln({...t,active:e},n,{kind:`Support`});return[{context:[...t.context,{kind:`Fact`,expression:e,visibility:`Visible`,location:e.location}],active:F(1,t.active)},{...n,obligations:[i]}]}if(r.facts.length>0)throw new e.ut(`Proof.Gen.gen_step: USE with facts and definitions`);let i=r.defs.reduce((e,t)=>rn(`Visible`,e,t),t.context);return[{...t,context:i},n]}case`Hide`:{let e=n.usable.defs.reduce((e,t)=>rn(`Hidden`,e,t),t.context),r=n.usable.facts.reduceRight((e,t)=>on(i,`Hidden`,t,e),e);return[{...t,context:r},n]}case`Define`:return[{context:[...t.context,...n.definitions.map(e=>({kind:`Defn`,definition:e,whereDefined:`User`,visibility:`Visible`,isLocal:!0,location:e.location}))],active:F(n.definitions.length,t.active)},n];case`Assert`:{let e=a(tn(t.context,n.sequent,n),n.proof),r={...n,proof:e};return[nn(!1,t.context,t.active,n.sequent,r),r]}case`Suffices`:{let e=a(nn(!0,t.context,t.active,n.sequent,n),n.proof),r={...n,proof:e};return[tn(t.context,n.sequent,r),r]}default:throw new e.ut(`Proof.Gen.gen_step`)}},s=(e,t,n,r)=>{let i={kind:`Unnamed`,level:0,id:0},[a,s]=o({context:e,active:{...Wt,location:r}},t===`Use`?{kind:`Use`,usable:n,isOnly:!1,location:r,step:i}:{kind:`Hide`,usable:n,location:r,step:i});return[a.context,s.obligations??[]]},c=(e,t,n,r)=>{if(n.defs.length===0&&n.facts.length===0)return[e,[]];let i=n.defs.length>0,[a,...o]=n.facts,[l,u]=s(e,t,i?{defs:n.defs,facts:[]}:{defs:[],facts:[a]},r),d=i?n.facts:o.map(e=>F(1,e)),[f,p]=c(l,t,{defs:[],facts:d},r);return[f,[...u,...p]]},l=e=>{let t=[],n=e=>{e.kind===`Steps`?(n(e.qed.proof),e.steps.forEach(r)):e.obligations&&!e.isSuppressed&&t.push(...e.obligations)},r=e=>{e.kind===`Use`&&e.obligations&&!e.isSuppressed&&t.push(...e.obligations),(e.kind===`Assert`||e.kind===`Suffices`||e.kind===`Pcase`||e.kind===`Pick`)&&n(e.proof)};return n(e),t},u=e=>({kind:`Named`,level:e,label:`_a${ze(t)}`,isAnonymous:!0}),d=(e,t)=>t?.kind===`Named`?{...t,level:e}:u(e),f=(e,t)=>{let n={...t,step:d(e,t.step)};if(n.kind!==`Steps`)return n;let r=n.steps.map(t=>p(e,t));return{...n,steps:r,qed:{...n.qed,proof:f(e+1,n.qed.proof)}}},p=(e,t)=>{let n={...t,step:d(e,t.step)};switch(n.kind){case`Assert`:case`Suffices`:case`Pcase`:case`Pick`:return{...n,proof:f(e+1,n.proof)};default:return n}},m=(t,n)=>{let r=n.kind===`Apply`?n.operator:n;if(r.kind===`Ix`){let i=t[t.length-r.index];if(!i)throw new e.ut(`expose_connective`);if(i.kind!==`Defn`||i.definition.kind!==`Operator`)return n;let a=F(r.index,i.definition.body);if(n.kind!==`Apply`)return m(t,a);let o={...a,location:n.location};return m(t,S(j(o,n.args),o))}if(n.kind===`Apply`&&n.operator.kind===`Internal`&&n.operator.builtin===`Prime`){let e=m(t,n.args[0]),r=e=>w(`Prime`,[e],e);return e.kind===`Quant`?S({kind:`Quant`,quantifier:e.quantifier,bounds:e.bounds.map(e=>e.domain.kind===`Domain`?{...e,domain:{kind:`Domain`,expression:r(e.domain.expression)}}:e),body:r(e.body)},n):Yt(e,`Implies`)||Yt(e,`Mem`)?S({kind:`Apply`,operator:e.operator,args:[r(e.args[0]),r(e.args[1])]},n):r(e)}return n.kind===`Parens`?m(t,n.expression):n},h=e=>{if(e.kind!==`Assert`)return;let t=e.sequent.active;return t.kind===`Apply`&&t.args.length===2?t.args[1]:void 0},g=e=>{if(e.kind!==`Steps`)return e;let t=[];return e.steps.forEach(e=>{let n=t.at(-1),r=n&&h(n);if(e.kind!==`Assert`||!r){t.push(e);return}let i=mn(e.sequent.active,F(2,r));t.push({...e,sequent:{...e.sequent,active:i}})}),{...e,steps:t}},_=(e,t,n)=>{let r=g(n);switch(r.kind){case`Obvious`:case`Omitted`:case`Error`:return r;case`By`:{let e=r.usable,t=e.defs.length===0?[]:[{kind:`Use`,usable:{facts:[],defs:e.defs},isOnly:!1,location:r.location}],n=e.facts.map((e,t)=>({kind:`Use`,usable:{facts:[F(t,e)],defs:[]},isOnly:!1,location:e.location,isSuppressed:r.isSuppressed})),i=r.isOnly?[{kind:`Forget`,count:e.facts.length,location:r.location}]:[],a=qt(r.step),o=[...t,...n,...i].map(e=>({...e,step:u(a)})),s={kind:`Obvious`,location:r.location,step:u(a),isSuppressed:r.isSuppressed};return{kind:`Steps`,steps:o,qed:{proof:s,location:s.location,step:s.step},location:r.location,step:r.step,isSuppressed:r.isSuppressed}}case`Steps`:{let n=e,i=t,a=r.steps.flatMap(e=>{let[t,r,a]=b(n,i,e);return n=t,i=r,a}),o=_(n,i,r.qed.proof);return{...r,steps:a,qed:{...r.qed,proof:o}}}}},b=(t,n,r)=>{let i=qt(r.step);switch(r.kind){case`Forget`:return[t,n,[r]];case`Assert`:{let e=tn(t,r.sequent,r),i={...r,proof:_(e.context,e.active,r.proof)},a=nn(!1,t,n,r.sequent,i);return[a.context,a.active,[i]]}case`Suffices`:{let e=nn(!0,t,n,r.sequent,r),i={...r,proof:_(e.context,e.active,r.proof)},a=tn(t,r.sequent,i);return[a.context,a.active,[i]]}case`Use`:{let i={kind:`By`,usable:r.usable,isOnly:r.isOnly,location:r.location,step:r.step,isSuppressed:r.isSuppressed},a=_(t,n,i);if(a.kind!==`Steps`)throw new e.ut(`simplifying BY does not produce a non-leaf proof!`);let o=r.usable.facts.map(()=>({kind:`Fact`,expression:Wt,visibility:`Visible`,location:r.location}));return[[...t,...o],F(r.usable.facts.length,n),a.steps]}case`Hide`:return[r.usable.defs.reduce((t,n)=>{if(n.kind!==`Dx`)throw new e.ut(`set_vis`);let i=t.length-n.index,a=t[i];if(a?.kind!==`Defn`){let t=a?a.kind===`Fact`?`??? FACT ???`:a.name:``;throw new e.ut(`USE DEF ${t} invalid because ${t} is not a defined operator`)}return t.map((e,t)=>t===i?{...a,visibility:`Hidden`,location:r.location}:e)},t),n,[r]];case`Define`:return[[...t,...r.definitions.map(e=>({kind:`Defn`,definition:e,whereDefined:`Proof`,visibility:`Visible`,isLocal:!0,location:r.location}))],F(r.definitions.length,n),[r]];case`Have`:{let e=m(t,n),a={kind:`Fact`,expression:r.expression,visibility:`Visible`,location:r.location},o=Yt(e,`Implies`),s={context:[a],active:o?F(1,e.args[1]):e},c=o?{kind:`By`,usable:{facts:[S({kind:`Ix`,index:2},r)],defs:[]},isOnly:!0,...Gt(r)}:{kind:`Error`,message:Xt(`@.@[<v2>@[%s@ %s@]@,%a@]@.`,`Error: this HAVE step is applied to the following goal,`,`which is not an implication:`,Ht(t,n)),...Gt(r)},l=p(i,{kind:`Suffices`,sequent:s,proof:c,location:r.location,step:r.step});return b(t,n,l)}case`Take`:return b(t,n,p(i,C(t,n,r)));case`Witness`:return b(t,n,p(i,T(t,n,r)));case`Pcase`:{let e={kind:`Assert`,sequent:{context:[{kind:`Fact`,expression:r.expression,visibility:`Visible`,location:r.location}],active:F(1,n)},proof:r.proof,...Gt(r)};return b(t,n,p(i,e))}case`Pick`:{let i=S({kind:`Quant`,quantifier:`Exists`,bounds:r.bounds,body:r.expression},r),a=x(r.step,`ex`),[o,s,c]=b(t,n,{kind:`Assert`,sequent:{context:[],active:i},proof:r.proof,...Gt(r),step:a}),l=F(2,i);if(l.kind!==`Quant`)throw new e.ut(`Proof.Simplify.simplify_step/PICK`);let u=[...Zt(l.bounds),{kind:`Fact`,expression:l.body,visibility:`Visible`,location:l.body.location}],[d,f,p]=b(o,s,{kind:`Suffices`,sequent:{context:u,active:F(u.length,s)},proof:{kind:`Omitted`,omission:`Elsewhere`,...Gt(r)},...Gt(r)});return[d,f,[...c,...p]]}}},x=(e,n)=>({kind:`Named`,level:qt(e),label:`${e?.kind===`Named`?e.label:`_a`}${n}${ze(t)}`,isAnonymous:!1}),C=(e,t,n)=>{let r=Qt(n.bounds),i=(t,n,r,a)=>{let o=a[0];if(!o)return{aux:n,goal:r};let s=m(e,r);if(s.kind!==`Quant`||s.quantifier!==`Forall`||s.bounds.length===0)return Xt(`@.@[<v2>@[<b0>%s@ %s@]@,%a@]@.`,`Error: this TAKE step is applied to the following goal,`,`which is not a universal formula:`,Ht(e,r));let c=s.bounds[0],l=Qt(s.bounds).slice(1),u=o.domain,d=c.domain;if(u.kind===`NoDomain`&&d.kind===`Domain`)return Xt(`@.@[<b0>%s (%s)@ %s (%s \\in %a)@]@.`,`Error: the TAKE argument`,o.name,`does not match the pattern`,c.name,Ht(e,d.expression));if(u.kind===`Domain`&&d.kind===`NoDomain`)return Xt(`@.@[<b0>%s (%s \\in %a)@ %s (%s)@]@.`,`Error: the TAKE argument`,o.name,Ht(e,u.expression),`does not match the pattern`,c.name);let f=u.kind===`Domain`&&d.kind===`Domain`&&!L(u.expression,d.expression)?[{kind:`Apply`,operator:{kind:`Internal`,builtin:`Subseteq`},args:[d.expression,u.expression]},...n]:n;if(l.length===0)return i(1,f,s.body,a.slice(1));let p=a.length===1?l.map(e=>N(v(t),[e])[1][0]):l;return i(t+1,f,S({kind:`Quant`,quantifier:`Forall`,bounds:p,body:s.body},s),a.slice(1))},a=i(1,[],t,r);if(typeof a==`string`)return{kind:`Suffices`,sequent:{context:[{kind:`Fact`,expression:Jt(t),visibility:`Visible`,location:n.location}],active:t},proof:{kind:`Error`,message:a,...Gt(n)},...Gt(n)};let o=a.aux.filter((e,t)=>a.aux.findIndex(t=>L(e,t))===t),s=[S({kind:`Ix`,index:2},n),...o.map(e=>F(2,e))];return{kind:`Suffices`,sequent:{context:Zt(r),active:a.goal},proof:{kind:`By`,usable:{facts:s,defs:[]},isOnly:!0,...Gt(n)},...Gt(n)}},T=(e,t,n)=>{let r=[],i=``,a=t;for(let t of n.expressions){let n=m(e,a);if(n.kind!==`Quant`||n.quantifier!==`Exists`||n.bounds.length===0){i||=Xt(`@.@[<v2>@[<b0>%s@ %s@]@,%a@]@.`,`Error: this WITNESS step is applied to the following goal,`,`which is not an existential formula:`,Ht(e,n)),a=n;break}let[o,...s]=n.bounds,c=s.length===0?n.body:S({kind:`Quant`,quantifier:`Exists`,bounds:sn(o,s),body:n.body},n),l=t;if(o.domain.kind===`Domain`){let n=o.domain.expression,a=m(e,t);if(Yt(a,`Mem`)){let[e,t]=a.args,i=L(t,n)?[]:[w(`Subseteq`,[t,n],t)];r.push(...i,a),l=e}else i||=Xt(`@.@[<b0>%s (%a)@ %s (%s \\in %a)@]@.`,`Error: the WITNESS argument`,Ht(e,a),`does not match the pattern`,o.name,Ht(e,n)),l=a}let u=w(`Unprimable`,[l],l);a=P(y(u,v(0)),c)}let o=i===``?cn(n,r):{kind:`Error`,message:i,...Gt(n)};return{kind:`Suffices`,sequent:{context:[],active:a},proof:o,...Gt(n)}};return{generate:a,collect:l,mutate:c,simplify:_}},gn=(e,t=0)=>({level:e,weights:Array.from({length:t},()=>!0),params:/* @__PURE__ */ new Set}),_n={TRUE:[0,0],FALSE:[0,0],Implies:[0,2],Equiv:[0,2],Conj:[0,2],Disj:[0,2],Neg:[0,1],Eq:[0,2],Neq:[0,2],STRING:[0,0],BOOLEAN:[0,0],SUBSET:[0,1],UNION:[0,1],DOMAIN:[0,1],Subseteq:[0,2],Mem:[0,2],Notmem:[0,2],Setminus:[0,2],Cap:[0,2],Cup:[0,2],Actplus:[3,2],BoxTrue:[3,1],BoxFalse:[3,1],Diamond:[3,1],Prime:[2,1],StrongPrime:[2,1],ENABLED:[1,1],UNCHANGED:[2,1],Leadsto:[3,2],Cdot:[2,2],Nat:[0,0],Int:[0,0],Real:[0,0],Infinity:[0,0],Plus:[0,2],Minus:[0,2],Times:[0,2],Ratio:[0,2],Quotient:[0,2],Remainder:[0,2],Exp:[0,2],Divides:[0,2],Lteq:[0,2],Lt:[0,2],Gteq:[0,2],Gt:[0,2],Range:[0,2],Uminus:[0,1],Seq:[0,1],Len:[0,1],BSeq:[0,2],Cat:[0,2],Append:[0,2],Head:[0,1],Tail:[0,1],SubSeq:[0,3],SelectSeq:[0,2],OneArg:[0,2],Extend:[0,2],Print:[0,2],PrintT:[0,1],Assert:[0,2],JavaTime:[0,0],TLCGet:[0,1],TLCSet:[0,2],Permutations:[0,1],SortSeq:[0,2],RandomElement:[0,1],Any:[0,0],ToString:[0,1],Unprimable:[0,1]},vn={Constant:0,State:1,Action:2,Temporal:3,Unknown:0},yn=e=>new Set(e.flatMap(e=>[...e])),bn=e=>({level:Math.max(0,...e.map(e=>e.level)),weights:[],params:yn(e.map(e=>e.params))}),xn=/* @__PURE__ */ new WeakMap,Sn=t=>{let n=t.hyp;switch(n.kind){case`Flex`:return gn(1);case`Fresh`:return{...gn(vn[n.level],n.shape),params:/* @__PURE__ */ new Set([n.name])};case`Defn`:{let r=n.definition;if(r.kind!==`Operator`&&r.kind!==`Bpragma`)throw new e.mt;return En(t.rest,r.body)}case`Fact`:return En(t.rest,n.expression)}},Cn=e=>{let t=xn.get(e);if(t)return t;let n=Sn(e);return xn.set(e,n),n},wn=(e,t,n)=>{let r=t.flatMap(t=>t.domain.kind===`Domain`?[En(e,t.domain.expression)]:[]),i=t.reduce((e,t)=>E(e,k(t.name,t.level)),e);return bn([En(i,n),...r])},Tn=(t,n)=>{if(t.weights.length!==n.length)throw new e.ut(`Invalid number of arguments`);let r=n.filter((e,n)=>t.weights[n]);return{level:Math.max(t.level,...r.map(e=>e.level)),weights:[],params:yn([t.params,...r.map(e=>e.params)])}},En=(t,n)=>{let r=e=>En(t,e);switch(n.kind){case`Ix`:{let r=ne(t,n.index-1);if(!r)throw new e.mt;return Cn(r)}case`Internal`:{let t=_n[n.builtin];if(!t)throw new e.mt;return gn(t[0],t[1])}case`Opaque`:case`String`:case`Num`:return gn(0);case`Lambda`:{let e=n.params.reduce((e,t)=>E(e,k(t.name,`Unknown`,t.shape)),t),r=En(e,n.body),i=new Set(n.params.map(e=>e.name));return{level:r.level,weights:n.params.map(e=>r.params.has(e.name)),params:new Set([...r.params].filter(e=>!i.has(e)))}}case`Apply`:{let t=n.operator;if(t.kind===`Opaque`)return Tn(gn(0,n.args.length),n.args.map(r));if(t.kind===`Internal`&&n.args.length===1){let i=n.args[0];switch(t.builtin){case`Prime`:case`StrongPrime`:if(r(i).level>1)throw new e.mt;return gn(2,1);case`ENABLED`:{let t=r(i);if(t.level>2)throw new e.mt;return{level:1,weights:[],params:t.params}}case`UNCHANGED`:{let t=r(i);if(t.level>1)throw new e.mt;return{level:2,weights:[],params:t.params}}}}return t.kind===`Internal`&&t.builtin===`Cdot`?(n.args.forEach(r),gn(2)):t.kind===`Internal`&&t.builtin===`Leadsto`?(n.args.forEach(r),gn(3,2)):Tn(r(t),n.args.map(r))}case`Sequent`:{let[e,r]=O(t,n.sequent.context,(e,t)=>{let n=E(e,t);return[n,Cn(n).level]});return gn(Math.max(0,...r,En(e,n.sequent.active).level))}case`With`:case`Dot`:case`Parens`:return r(n.expression);case`Let`:{let e=n.definitions.reduce((e,t)=>E(e,{kind:`Defn`,definition:t,whereDefined:`User`,visibility:`Visible`,isLocal:!0}),t);return En(e,n.body)}case`If`:return bn([n.condition,n.consequent,n.alternative].map(r));case`List`:return bn(n.items.map(r));case`Quant`:case`Fcn`:return wn(t,n.bounds,n.body);case`SetOf`:return wn(t,n.bounds,n.element);case`Tquant`:return En(n.names.reduce((e,t)=>E(e,{kind:`Flex`,name:t}),t),n.body),gn(3);case`Choose`:case`SetSt`:{let e=n.domain&&r(n.domain),i=n.domain?re(n.name,n.domain):k(n.name,`Constant`);return bn([En(E(t,i),n.body),...e?[e]:[]])}case`SetEnum`:case`Tuple`:return bn(n.elements.map(r));case`Product`:return bn(n.factors.map(r));case`FcnApp`:return bn([n.function,...n.args].map(r));case`Arrow`:return bn([r(n.domain),r(n.range)]);case`Rect`:case`Record`:return bn(n.fields.map(e=>r(e.value)));case`Except`:return bn([r(n.function),...n.specs.flatMap(e=>[...e.trail.flatMap(e=>e.kind===`Apply`?[r(e.expression)]:[]),r(e.value)])]);case`Sub`:return{...bn([r(n.action),r(n.subscript)]),level:2};case`Tsub`:case`Fair`:return r(n.action),r(n.subscript),gn(3);case`Case`:return bn([...n.arms.flatMap(e=>[r(e.condition),r(e.body)]),...n.other?[r(n.other)]:[]]);case`Bang`:case`At`:throw new e.mt}},Dn=(t,n)=>{let r=ne(t,n-1)?.hyp;if(!r)throw new e.mt;return r},On=e=>e.kind===`Internal`&&(e.builtin===`ENABLED`||e.builtin===`Cdot`),kn=e=>e.kind===`Apply`&&e.args.length===1&&e.args[0].kind===`Lambda`&&(On(e.operator)||e.operator.kind===`Opaque`&&(e.operator.name===`EnabledWrapper`||e.operator.name===`CdotWrapper`)),An=e=>e===void 0?2:Math.min(2,e),jn=e=>e===void 0?void 0:Math.max(1,e-1),Mn=(t,n,r,i)=>{let a=(e,r=i)=>Mn(t,n,e,r);if(kn(r))return r;if(r.kind===`Sub`)return{...r,action:a(r.action),subscript:a(r.subscript,jn(i))};if(r.kind===`Apply`&&r.operator.kind===`Internal`){let e=r.operator.builtin,[t,n]=r.args;if(e===`Cdot`&&r.args.length===2)return{...r,args:[a(t,An(i)),a(n,1)]};if(e===`ENABLED`&&r.args.length===1)return{...r,args:[a(t,An(i))]};if((e===`Prime`||e===`UNCHANGED`)&&r.args.length===1)return{...r,args:[a(t,jn(i))]}}let o=r.kind===`Apply`&&r.operator.kind===`Ix`?r.operator:r;if(o.kind!==`Ix`)return ye(n,r,(e,n)=>Mn(t,e,n,i),E);if(i===void 0)return r;let s=En(n,r).level,c=Dn(n,o.index),l=e=>`The operator \`${e}\` is declared at:\n${c.location?m(c.location):`<unknown location>`}`;if(c.kind===`Fresh`&&c.level===`Unknown`)throw t(g(r.location,`Declared operator \`${c.name}\` has unknown level and occurs within the scope of \`ENABLED\` or \`\\cdot\` where soundness requires expanding expressions of level >= ${i}.\nIf a constant operator is substituted for this operator, then the expression that results from applying this declared operator has expression level ${s}.\n May need expansion. A declared operator cannot be expanded.\n${l(c.name)}\n and has arity: ${c.shape}`)),new e.mt(`File "src/expr/e_action.ml", line 367, characters 20-26: Assertion failed`);if(s<i)return r;if(s>2||c.kind===`Fact`)throw new e.mt;if(c.kind===`Flex`){if(r.kind!==`Ix`)throw new e.mt;return r}if(c.kind===`Fresh`){let n=`The expression that results from applying the declared operator \`${c.name}\` has expression level ${s} within the scope of \`ENABLED\` or \`\\cdot\` where soundness requires expanding expressions of level >= ${i}. A declared operator cannot be expanded.\n${l(c.name)}\n and has level: ${vn[c.level]}\n and arity: ${c.shape}`;throw t(g(r.location,n)),new e.ut(n)}let u=c.definition;if(u.kind!==`Operator`&&u.kind!==`Bpragma`)throw new e.mt;t({text:`${h(r.location)}[INFO]: Auto-expanding the definition of operator: ${u.name}\n`,channel:`stdout`});let d=P(v(o.index),u.body);return a(M(r.kind===`Apply`?j(d,r.args):d))},Nn=e=>w(`Eq`,[w(`Prime`,[e],e),e],e),Pn=e=>{let t=e=>e.kind===`Tuple`?e.elements.flatMap(t):[e],n=t(e);return n.length===0?S({kind:`Internal`,builtin:`TRUE`},e):n.length===1?Nn(n[0]):S({kind:`List`,bullet:`And`,items:n.map(Nn)},e)},Fn=t=>{if(t.kind===`Apply`&&t.args.length===1)return Pn(t.args[0]);if(t.kind!==`Sub`)throw new e.mt;let n=Pn(t.subscript),r=t.modal===`Box`?n:w(`Neg`,[n],t);return w(t.modal===`Box`?`Disj`:`Conj`,[t.action,r],t)},In=e=>{let t=(e,t)=>e<<t|e>>>32-t,n=(e,n)=>{let r=Math.imul(t(Math.imul(n,3432918353),15),461845907);return Math.imul(t(e^r,13),5)+3864292196|0},r=new TextEncoder().encode(e),i=r.length-r.length%4,a=0;for(let e=0;e<i;e+=4)a=n(a,r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24);let o=r.subarray(i).reduceRight((e,t)=>e<<8|t,0);return r.length>i&&(a=n(a,o)),a^=r.length,a=Math.imul(a^a>>>16,2246822507),a=Math.imul(a^a>>>13,3266489909),(a^a>>>16)&1073741823},Ln=e=>{let t=Array.from({length:16},()=>[]);return e.forEach((e,n)=>{if(t[In(e)&t.length-1].unshift(e),n+1<=t.length*2)return;let r=Array.from({length:t.length*2},()=>[]);t.flat().forEach(e=>r[In(e)&r.length-1].push(e)),t=r}),t.flat()},Rn=(t,n,r,i,a)=>{let o=e=>Rn(t,n,r,i,e),s=n!==void 0||r!==void 0,c=(e,o)=>{let s={names:[],depth:Math.max(n?.depth??0,r?.depth??0)+1},[c,l]=o,u=[Rn(t,n,s,i,c),...l?[Rn(t,s,r,i,l)]:[]],d=s.names.length===0?[`r#0`]:Ln(s.names);return S({kind:`Apply`,operator:e,args:[{kind:`Lambda`,params:[`_`,...d].map(e=>({name:e,shape:0})),body:u.length===1?u[0]:{kind:`List`,bullet:`And`,items:u}}]},a)};if(kn(a))return a;if(a.kind===`Apply`&&a.operator.kind===`Internal`){let e=a.operator.builtin;if(e===`ENABLED`&&a.args.length===1||e===`Cdot`&&a.args.length===2)return c(a.operator,a.args);if(e===`Prime`&&a.args.length===1){let e=Rn(t,r,void 0,i,a.args[0]);return r?e:{...a,args:[e]}}if(e===`UNCHANGED`&&s)return o(Fn(a))}if(a.kind===`Sub`&&s)return o(Fn(a));if(a.kind===`Ix`){if(!n)return a;let t=Dn(i,a.index);if(t.kind===`Fact`)throw new e.mt;if(t.kind!==`Flex`)return a;let r=`${t.name}#enabled#prime${n.depth}`;return n.names.includes(r)||n.names.push(r),S({kind:`Opaque`,name:r},a)}if(a.kind===`Apply`&&a.operator.kind===`Opaque`)throw t(g(a.location,`Named operator \`${a.operator.name}\` unexpected after anonymization.`)),new e.mt(`File "src/expr/e_action.ml", line 1048, characters 12-18: Assertion failed`);return ye(i,a,(e,i)=>Rn(t,n,r,e,i),E)},zn=(t,n)=>{if(n.kind===`Apply`&&On(n.operator)){let[r]=n.args;if(n.args.length!==1||r.kind!==`Lambda`)throw new e.mt;let[i,...a]=r.params;if(i.name!==`_`)return n;let o=zn({kind:`Compose`,outer:t,inner:v(a.length)},r.body);return{kind:`Apply`,operator:n.operator,args:[{kind:`Lambda`,params:a,body:o}]}}return n.kind===`Ix`?P(t,n):n.kind===`Apply`?S(j(zn(t,n.operator),n.args.map(e=>zn(t,e))),n):ye(t,n,zn,e=>x(1,e))},Bn=t=>{if(t.kind===`Apply`&&On(t.operator)){let[n]=t.args;if(t.args.length!==1||n.kind!==`Lambda`||n.params[0].name===`_`)throw new e.mt;let r=t.operator.builtin===`Cdot`?`CdotWrapper`:`EnabledWrapper`;return{kind:`Apply`,operator:S({kind:`Opaque`,name:r},t.operator),args:[{kind:`Lambda`,params:n.params.map((e,t)=>({name:`r#${t}`,shape:0})),body:Bn(n.body)}]}}return ye(void 0,t,(e,t)=>Bn(t),()=>void 0)},Vn=t=>{if(t.kind===`Apply`&&t.operator.kind===`Internal`&&t.operator.builtin===`Cdot`&&t.args.length===1&&t.args[0].kind!==`Lambda`)throw new e.mt;return ye(void 0,t,(e,t)=>Vn(t),()=>void 0)},Hn=(e,t,n,r)=>{let i=Mn(t,n,r,void 0),a=zn(v(0),Rn(t,void 0,void 0,n,i));return Vn(Bn(e.expr(n,a)))},Un=(e,t)=>({kind:`Definition`,definition:{kind:`Operator`,name:e,body:{kind:`Internal`,builtin:t}},whereDefined:`Builtin`,visibility:`Visible`,isLocal:!1}),H=(e,t,n)=>({kind:`Definition`,definition:{kind:`Operator`,name:t,body:{kind:`Lambda`,params:Array.from({length:e},(e,t)=>({name:`x${t+1}`,shape:0})),body:{kind:`Apply`,operator:{kind:`Internal`,builtin:n},args:Array.from({length:e},(t,n)=>({kind:`Ix`,index:e-n}))}}},whereDefined:`Builtin`,visibility:`Visible`,isLocal:!1}),Wn=[Un(`Nat`,`Nat`),H(2,`+`,`Plus`),H(2,`-`,`Minus`),H(2,`*`,`Times`),H(2,`^`,`Exp`),H(2,`<`,`Lt`),H(2,`>`,`Gt`),H(2,`=<`,`Lteq`),H(2,`>=`,`Gteq`),H(2,`%`,`Remainder`),H(2,`\\div`,`Quotient`),H(2,`..`,`Range`)],Gn=[...Wn,Un(`Int`,`Int`),H(1,`-.`,`Uminus`)],Kn=[...Gn,Un(`Real`,`Real`),H(2,`/`,`Ratio`),Un(`Infinity`,`Infinity`)],qn=[H(1,`Seq`,`Seq`),H(1,`Len`,`Len`),H(2,`BSeq`,`BSeq`),H(2,`\\o`,`Cat`),H(2,`Append`,`Append`),H(1,`Head`,`Head`),H(1,`Tail`,`Tail`),H(3,`SubSeq`,`SubSeq`),H(2,`SelectSeq`,`SelectSeq`)],Jn=[H(2,`Print`,`Print`),H(1,`PrintT`,`PrintT`),H(2,`Assert`,`Assert`),Un(`JavaTime`,`JavaTime`),H(1,`TLCGet`,`TLCGet`),H(2,`TLCSet`,`TLCSet`),H(2,`:>`,`OneArg`),H(2,`@@`,`Extend`),H(1,`Permutations`,`Permutations`),H(2,`SortSeq`,`SortSeq`),H(1,`RandomElement`,`RandomElement`),Un(`Any`,`Any`),H(1,`ToString`,`ToString`)],Yn=(e,t)=>({name:e,extendees:[],body:t,isImportant:!1,isStandard:!0}),Xn=new Map([Yn(`Naturals`,Wn),Yn(`Integers`,Gn),Yn(`Reals`,Kn),Yn(`Sequences`,qn),Yn(`TLC`,Jn)].map(e=>[e.name,e])),Zn=e=>{let t=e.location;switch(e.kind){case`Constants`:return e.declarations.map(e=>({kind:`Fresh`,name:e.name,shape:e.shape,level:`Constant`,domain:void 0,domainVisibility:`Visible`,location:t}));case`Recursives`:return e.declarations.map(e=>({kind:`Defn`,definition:{kind:`Recursive`,name:e.name,shape:e.shape,location:t},whereDefined:`User`,visibility:`Hidden`,isLocal:!1,location:t}));case`Variables`:return e.names.map(e=>({kind:`Flex`,name:e,location:t}));case`Definition`:return[{kind:`Defn`,definition:e.definition,whereDefined:e.whereDefined,visibility:e.visibility,isLocal:e.isLocal,location:t}];case`Axiom`:return e.name===void 0?[{kind:`Fact`,expression:e.expression,visibility:`Hidden`,location:t}]:$n(e.name,e.expression,t);case`Theorem`:{let n=se(v(-e.axiomCount),{...e.sequent,context:e.sequent.context.slice(e.axiomCount)}),r=S(T(n),e);return e.name===void 0?[{kind:`Fact`,expression:r,visibility:`Hidden`,location:t}]:$n(e.name,r,t)}case`Mutate`:return e.mode===`Use`?e.usable.facts.map((e,n)=>({kind:`Fact`,expression:F(n,e),visibility:`Visible`,location:t})):[];case`Submod`:case`Anoninst`:return[]}},Qn=e=>e.kind===`Axiom`||e.kind===`Theorem`?e.name===void 0?1:2:Zn(e).length,$n=(e,t,n)=>[{kind:`Defn`,definition:{kind:`Operator`,name:e,body:t,location:n},whereDefined:`User`,visibility:`Visible`,isLocal:!1,location:n},{kind:`Fact`,expression:{kind:`Ix`,index:1,location:n},visibility:`Hidden`,location:n}],er=e=>e.body.flatMap(e=>{switch(e.kind){case`Definition`:return[{...e,whereDefined:e.isLocal?`Builtin`:e.whereDefined}];case`Mutate`:return[];case`Theorem`:return[{...e,proof:{kind:`Omitted`,omission:`Elsewhere`,location:e.location}}];case`Submod`:return[{...e,module:{...e.module,body:er(e.module)}}];default:return[e]}}),tr=(t,n,r,i=/* @__PURE__ */ new Set([n.name]))=>{let a=[];for(let o of n.extendees){if(r.has(o))continue;if(i.has(o))throw new e.mt(`Stack overflow`);let n=t.get(o);if(!n)throw new e.ut(`Module "${o}" unknown`);a.push(...er(tr(t,n,r,/* @__PURE__ */ new Set([...i,o])))),r.add(o)}return{...n,body:[...a,...n.body].map(e=>e.kind===`Submod`?{...e,module:tr(t,e.module,/* @__PURE__ */ new Set)}:e)}},nr=e=>{let t=/* @__PURE__ */ new Map,n=(e,n)=>{t.has(e)||t.set(e,n)},r=e=>e.extendees.forEach((t,r)=>n(t,e.extendeeLocations?.[r])),i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Map,o=e=>{typeof e==`object`&&e&&(`instance`in e&&rr(e.instance)&&n(e.instance.module,e.instance.location),Object.values(e).forEach(o))},s=e=>{e.kind===`Theorem`?o(e.sequent):e.kind!==`Submod`&&o(e),e.kind===`Submod`&&(i.add(e.module.name),a.set(e.module.name,e.module),r(e.module),e.module.body.forEach(s))};return e.body.forEach(s),i.forEach(e=>t.delete(e)),r(e),{dependencies:[...t.keys()].sort(ir),locations:t,submodules:a}},rr=e=>typeof e==`object`&&!!e&&`module`in e&&typeof e.module==`string`&&`substitutions`in e,ir=(e,t)=>e<t?-1:+(e>t),ar=(t,n)=>({facts:A(t,n.facts),defs:n.defs.map(n=>{if(n.kind===`Dvar`)return n;let r=P(t,{kind:`Ix`,index:n.index});if(r.kind!==`Ix`)throw new e.ut(`substitution produced bad definition`);return{...n,index:r.index}})}),or=(e,t)=>{switch(t.kind){case`Constants`:case`Recursives`:return[x(t.declarations.length,e),t];case`Variables`:return[x(t.names.length,e),t];case`Definition`:return[x(1,e),{...t,definition:ae(e,t.definition)}];case`Axiom`:return[x(Qn(t),e),{...t,expression:P(e,t.expression)}];case`Theorem`:return[x(Qn(t),e),{...t,sequent:se(e,t.sequent)}];case`Submod`:return[e,{...t,module:{...t.module,body:sr(e,t.module.body)}}];case`Mutate`:return[t.mode===`Hide`?e:x(t.usable.facts.length,e),{...t,usable:ar(e,t.usable)}];case`Anoninst`:return[e,{...t,instance:{...t.instance,substitutions:t.instance.substitutions.map(t=>({name:t.name,expression:P(e,t.expression)}))}}]}},sr=(e,t)=>O(e,t,or)[1],cr=(t,n,r,i)=>{try{let r=Hn(t.anonymizer,t.onWarning,n,{kind:`Sequent`,sequent:i});if(r.kind!==`Sequent`)throw new e.mt;return r.sequent}catch(n){if(!(n instanceof e.ut)||n.failure===void 0)throw n;let a=i.active.location,o=`${n.failure}\nCould not instantiate the theorem ${r===void 0?``:`named: ${r}, `}at: ${a?m(a):`<unknown location>`}`;return t.onWarning({text:`${h(a)}[ERROR]${o}`,channel:`stdout`}),t.onWarning({text:o,channel:`toolboxOnly`}),{context:[],active:S({kind:`Internal`,builtin:`TRUE`},i.active)}}},lr=(e,t,n)=>{if(n.kind===`Theorem`)return{...n,sequent:cr(e,t,n.name,n.sequent)};if(n.kind!==`Definition`)return n;let r=n.definition;if(r.kind!==`Operator`&&r.kind!==`Bpragma`)return n;let i=Hn(e.anonymizer,e.onWarning,t,r.body);return{...n,definition:{...r,body:i}}},ur=(e,t,n)=>O(t,n,(t,n)=>{if(n.kind===`Submod`){let[r,i]=ur(e,t,n.module.body);return[r,{...n,module:{...n.module,body:i}}]}let r=lr(e,t,n);return[ee(t,Zn(r)),r]}),dr=(t,n)=>{let r=[],i=0,a=t;for(;a.length>0;){let[t,...o]=a,s=t.kind===`Constants`?{name:t.declarations[0].name,remaining:{...t,declarations:t.declarations.slice(1)}}:t.kind===`Variables`?{name:t.names[0],remaining:{...t,names:t.names.slice(1)}}:void 0;if(s){let t=n.get(s.name);if(!t)throw new e.ut(`Parameter ${s.name} has no substitute`);let r=Qn(s.remaining)===0;a=sr(y(F(i,t),v(0)),r?o:[s.remaining,...o])}else r.push(t),i+=Qn(t),a=o}return r},fr=(e,t,n)=>{let r=Array.from({length:t},(e,r)=>S({kind:`Ix`,index:t-r},{location:n})),i=Array.from({length:t},(e,t)=>S({kind:`Ix`,index:t+1},{location:n})),a=Array.from({length:e},(e,i)=>{let a=S({kind:`Ix`,index:i+t+1},{location:n});return t>0?S({kind:`Apply`,operator:a,args:r},{location:n}):a});return b([...a,...i].reverse(),v(e+t))},pr=(e,t)=>{let n=t.map(e=>({name:e,shape:0}));return e.kind===`Lambda`?{...e,params:[...n,...e.params]}:t.length===0?e:S({kind:`Lambda`,params:n,body:e},e)},mr=(t,n,r,i,a,o)=>{let s=e=>r===``?e:`${r}!${e}`,c=i.args.length,l=[],u=0,d=n,f=c===0,p=e=>{f||(f=!0,t.onWarning({text:e,channel:`stderr`}))};for(;d.length>0;){let[n,...r]=d;d=r;let f=e=>pr(P(fr(u,c,o),e),i.args);switch(n.kind){case`Definition`:{let r=n.definition;if(r.kind!==`Operator`&&r.kind!==`Bpragma`)throw new e.ut(`Module.Elab.localize`);let i=n.isLocal?`${r.name}$${ze(t.salts)}`:r.name;l.push({...n,definition:{...r,name:s(i),body:f(r.body)},whereDefined:n.isLocal?`Builtin`:n.whereDefined,isLocal:n.isLocal||a}),u+=1;continue}case`Axiom`:{p(`${_(o)}Instancing produces parametric axioms.\nSuch axioms will be forcibly hidden and cannot be cited.\n(This warning appears at-most once per INSTANCE declaration.)`);let e={...n,name:n.name===void 0?void 0:s(n.name),expression:f(n.expression)};l.push(e),u+=Qn(e);continue}case`Theorem`:{p(`${h(o)}Warning: Instancing produces parametric theorems.\nSuch theorems will be forcibly hidden and cannot be cited.\n(This warning appears at-most once per INSTANCE declaration.)`);let e=f(S(T(n.sequent),n));l.push({...n,name:n.name===void 0?void 0:s(n.name),sequent:e.kind===`Sequent`?e.sequent:{context:[],active:e},proof:{kind:`Omitted`,omission:`Elsewhere`,location:n.location}}),u+=1;continue}case`Mutate`:n.mode===`Use`&&(d=sr(v(-n.usable.facts.length),d));continue;case`Submod`:continue;default:throw new e.ut(`Module.Elab.localize`)}}return l},hr=e=>{let t=[],n=e;for(;n.length>0;){let[e,...r]=n;if(e.kind!==`Axiom`){t.push(e),n=r;continue}let i=e.location;e.name!==void 0&&t.push({kind:`Definition`,definition:{kind:`Operator`,name:e.name,body:e.expression,location:i},whereDefined:`Proof`,visibility:`Visible`,isLocal:!1,location:i});let a={kind:`Fact`,expression:e.name===void 0?F(1,e.expression):S({kind:`Ix`,index:2},e),visibility:`Visible`,location:i},o=0,s=r.map(e=>{let t=o;if(o+=Qn(e),e.kind!==`Theorem`)return e;let n=se(v(1),e.sequent);return{...e,sequent:{...n,context:[oe(v(t),a),...n.context]},axiomCount:e.axiomCount+1}});n=sr(v(-1),s)}return t},gr=e=>new Set(e.body.flatMap(e=>e.kind===`Constants`?e.declarations.map(e=>e.name):e.kind===`Variables`?e.names:[])),_r=(t,n,r,i,a,o,s)=>{let c=n.get(i.module);if(!c)throw new e.ut(`Module "${i.module}" unknown`);let l=gr(c);for(let t of i.substitutions)if(!l.has(t.name))throw new e.ut(`Parameter ${t.name} occurs in the statement \`INSTANCE ${i.module} WITH\`, and is not declared in the module ${i.module}`);let u=ee(r,i.args.map(e=>k(e,`Unknown`))),d=new Map(i.substitutions.map(e=>[e.name,e.expression]));for(let t of[...l].sort(ir))if(!d.has(t)){if(!te(u,t))throw new e.ut(`Required parameter ${t} for module ${i.module} could not be inferred.`);d.set(t,S({kind:`Opaque`,name:t},{location:s}))}let f=new Map([...d].map(([e,n])=>[e,t.anonymizer.expr(u,n)])),p=sr(v((u?.size??0)-(c.depth??0)),c.body.map(e=>e.kind===`Theorem`?{...e,proof:{kind:`Omitted`,omission:`Implicit`,location:e.proof.location}}:e)),[,m]=ur(t,u,p);return hr(mr(t,dr(m,f),o,i,a,s))},vr=(e,t,n)=>e===void 0?{hyps:[],sequent:t}:{hyps:[{kind:`Defn`,definition:{kind:`Operator`,name:e,body:S(T(t),{location:n}),location:n},whereDefined:`Proof`,visibility:`Visible`,isLocal:!1,location:n}],sequent:se(v(1),t)},yr=(t,n,r)=>{let i=r.instance.module;if(!t.latestModules.has(i))throw t.onWarning({text:`${_(r.instance.location)}Module ${JSON.stringify(i)} unknown\n`,channel:`toolbox`}),new e.ut(`Module ${JSON.stringify(i)} unknown`,{failure:`Module.Elab.anon#defns`});let a=_r(t,t.latestModules,n,r.instance,!0,r.name,r.location),o=[],s=a;for(;s.length>0;){let[e,...t]=s;e.kind===`Definition`?(o.push(e.definition),s=t):s=sr(v(-Qn(e)),t)}return o},br=(e,t,n,r)=>{let i=[],a=n,o=e=>{i.push(e),a=ee(a,Zn(e))},s=e=>e!==void 0&&te(a,e)!==void 0,c=r.body.map(e=>({unit:e,isAnonymized:!1}));for(let n=0;n<c.length;n++){let i=c[n].unit,l=(r,o,s)=>{let l=_r(e,t,a,r,o,s,i.location);c.splice(n+1,0,...l.map(e=>({unit:e,isAnonymized:!0})))};switch(i.kind){case`Anoninst`:l(i.instance,i.isLocal,``);continue;case`Definition`:{let t=i.definition;if(t.kind===`Instance`){l(t.instance,i.isLocal,t.name);continue}let r=t.kind===`Recursive`||c[n].isAnonymized?t:e.anonymizer.defn(a,t),s={...i,definition:r};if(t.kind===`Recursive`){o(s);continue}let u=Zn(s)[0],d=te(a,t.name);if(d?.hyp.kind===`Defn`&&(d.hyp.definition.kind===`Recursive`||fe(oe(v(d.depth+1),d.hyp),u))){let e=c.slice(n+1),t=sr(y(S({kind:`Ix`,index:d.depth+1},i),v(0)),e.map(e=>e.unit));c.splice(n+1,e.length,...e.map((e,n)=>({...e,unit:t[n]})));continue}o(s);continue}case`Recursives`:case`Constants`:case`Variables`:o(i);continue;case`Axiom`:if(s(i.name))continue;e.latestModules=new Map(t),o({...i,expression:e.anonymizer.expr(a,i.expression)});continue;case`Theorem`:{let n=s(i.name),c=n?`(redundant)${i.name}`:i.name,l=n?{kind:`Obvious`,location:i.proof.location}:i.proof;e.latestModules=new Map(t);let u=e.anonymizer.sequent(a,i.sequent),d=vr(c,u,i.location),f=ee(ee(a,d.hyps),d.sequent.context),p=e.anonymizer.proof(f,l),m=r.isImportant?e.generator.simplify(D(f),d.sequent.active,p):p;o({...i,name:c,sequent:u,proof:m});continue}case`Mutate`:e.latestModules=new Map(t),o({...i,usable:e.anonymizer.usable(a,i.usable)});continue;case`Submod`:o({...i,module:br(e,t,a,i.module)});continue}}let l={...r,body:i,depth:n?.size??0};return t.set(r.name,l),l},xr=(e,t,n)=>{let r=[],i=[],a=un,o=t;for(let t of n.body)switch(t.kind){case`Theorem`:{let n=vr(t.name,t.sequent,t.location),s=[...o,...n.hyps],c=e.generator.generate({context:[...s,...n.sequent.context],active:n.sequent.active},t.proof);r.push(...e.generator.collect(c));let l=pn(c);i.push({...l,location:t.location}),a=dn(a,l);let u=t.name===void 0?S(T(t.sequent),t):{kind:`Ix`,index:1,location:t.location};o=[...s,{kind:`Fact`,expression:u,visibility:`Hidden`,location:t.location}];continue}case`Submod`:{let n=xr(e,o,t.module);r.push(...n.obligations),a=dn(a,n.summary);continue}case`Mutate`:{let[n,i]=e.generator.mutate(o,t.mode,t.usable,t.location);r.push(...i),o=n;continue}default:o=[...o,...Zn(t)]}return{obligations:r,summary:{...a,theorems:i}}},Sr=e=>({kind:`Opaque`,name:e}),Cr=e=>({kind:`Tuple`,elements:e.map(Sr)}),wr=(e,t)=>({kind:`Apply`,operator:{kind:`Internal`,builtin:`Eq`},args:[e,t]}),Tr=e=>e.map(e=>({name:e,level:`Constant`,domain:{kind:`NoDomain`}})),Er=(e,t)=>e?.kind===`Product`&&e.factors.length===t.length?e.factors:void 0,Dr=(e,t)=>t.map((t,n)=>({kind:`Operator`,name:t,body:{kind:`FcnApp`,function:Sr(e),args:[{kind:`Num`,integer:String(n+1),fraction:``}]}})),Or=(e,t)=>e.map((e,n)=>({name:e,level:`Constant`,domain:{kind:`Domain`,expression:t[n]}})),kr=e=>({name:e.name,level:`Constant`,domain:e.domain}),Ar=(e,t,n)=>{let r=[];return t.forEach(e=>{e.kind===`Name`&&e.domain.kind===`Ditto`?r.at(-1)?.push(e):r.push([e])}),r.reduceRight((t,n)=>{let r=n[0];if(r.kind===`Name`)return{kind:`Quant`,quantifier:e,bounds:n.flatMap(e=>e.kind===`Name`?[kr(e)]:[]),body:t,location:t.location};let i=Er(r.domain,r.names);if(i)return{kind:`Quant`,quantifier:e,bounds:Or(r.names,i),body:t,location:t.location};let a={kind:`Apply`,operator:{kind:`Internal`,builtin:e===`Exists`?`Mem`:`Notmem`},args:[Cr(r.names),r.domain]};return{kind:`Quant`,quantifier:e,bounds:Tr(r.names),body:{kind:`List`,bullet:e===`Exists`?`And`:`Or`,items:[a,t]},location:t.location}},n)},jr=(e,t,n,r)=>Er(n,t)?{kind:`Let`,definitions:Dr(e,t),body:r}:{kind:`Quant`,quantifier:`Exists`,bounds:Tr(t),body:{kind:`List`,bullet:`And`,items:[wr(Sr(e),Cr(t)),r]}},Mr=(e,t,n)=>{let r=`choose#${e[0]}`;return{kind:`Choose`,name:r,domain:t,body:jr(r,e,t,n)}},Nr=(e,t,n)=>{let r=`setst#${e[0]}`;return{kind:`SetSt`,name:r,domain:t,body:jr(r,e,t,n)}},Pr=(e,t,n)=>{let r=e.map(e=>{if(e.kind===`Name`)return{bounds:[kr(e)],definitions:[]};let t=Er(e.domain,e.names);if(t&&n)return{bounds:Or(e.names,t),definitions:[]};let r=`fcn#${e.names[0]}`,i={name:r,level:`Constant`,domain:{kind:`Domain`,expression:e.domain}};if(t)return{bounds:[i],definitions:Dr(r,e.names)};let a=`choose#${r}`;return{bounds:[i],definitions:[{kind:`Operator`,name:a,body:Mr(e.names,void 0,wr(Sr(r),Cr(e.names)))},...Dr(a,e.names)]}}),i=r.flatMap(e=>e.definitions);return{bounds:r.flatMap(e=>e.bounds),value:i.length===0?t:{kind:`Let`,definitions:i,body:t}}},Fr=(e,t)=>{let n=Pr(t,e,!0);return{kind:`SetOf`,element:n.value,bounds:n.bounds}},Ir=(e,t)=>{let n=Pr(e,t,!1);return{kind:`Fcn`,bounds:n.bounds,body:n.value}},Lr={"=>":`Implies`,"<=>":`Equiv`,"/\\":`Conj`,"\\/":`Disj`,"~":`Neg`,"=":`Eq`,"#":`Neq`,SUBSET:`SUBSET`,UNION:`UNION`,DOMAIN:`DOMAIN`,"\\subseteq":`Subseteq`,"\\in":`Mem`,"\\notin":`Notmem`,"\\":`Setminus`,"\\cap":`Cap`,"\\cup":`Cup`,"'":`Prime`,"~>":`Leadsto`,ENABLED:`ENABLED`,UNCHANGED:`UNCHANGED`,"\\cdot":`Cdot`,"-+->":`Actplus`,"[]":`BoxTrue`,"<>":`Diamond`,TRUE:`TRUE`,FALSE:`FALSE`,BOOLEAN:`BOOLEAN`,STRING:`STRING`},Rr=(e,t=!1)=>t&&e===`-`?`-.`:Ct(e).name,zr=/^<(\d+|\*|\+)>([A-Za-z0-9_]*)\.*$/,Br=(e,t)=>{if(!e||!t)return e??t;let n=e.startLine<t.startLine||e.startLine===t.startLine&&e.startColumn<=t.startColumn,r=e.endLine>t.endLine||e.endLine===t.endLine&&e.endColumn>=t.endColumn;return{file:e.file,startLine:n?e.startLine:t.startLine,startColumn:n?e.startColumn:t.startColumn,endLine:r?e.endLine:t.endLine,endColumn:r?e.endColumn:t.endColumn}},Vr={Always:`[]`,Eventually:`<>`,Enabled:`ENABLED`,Unchanged:`UNCHANGED`},Hr=(e,t)=>e!==void 0&&t!==void 0&&e.line===t.line&&e.column===t.column,Ur=e=>e.location.range?.start,Wr=e=>e.location.range?.end,Gr=(e,t)=>{let n=e.location.range;return n&&t?{...e,location:{...e.location,range:{...n,end:t}}}:e},Kr=e=>{if(e.kind===`Apply`){let t=Ct(e.operator),n=e.args.length===2&&t.fixity.startsWith(`Infix`),r=e.args.length===1&&t.fixity===`Prefix`;if(!n&&!r)return;let i=e.args.length-1;return{operator:t,isInfix:n,operand:e.args[i],replace:t=>({...e,args:[...e.args.slice(0,i),t]})}}let t=Vr[e.kind];if(t!==void 0&&`expression`in e)return{operator:Ct(t),isInfix:!1,operand:e.expression,replace:t=>({...e,expression:t})}},qr=(e,t)=>e.high<t.low,Jr=e=>{let t=Ct(e.operator),[n,r]=e.args,i=Wr(e),a=t=>{let n=e.location.range,i=Ur(t);return{...e,args:[t,r],location:n&&i?{...e.location,range:{...n,start:i}}:e.location}},o=(e,n)=>{let r=n?Kr(e):void 0;if(!r)return{kind:`Reduced`,isFinal:!1};let s=o(r.operand,Hr(Wr(r.operand),Wr(e)));return s.kind===`Attached`?{kind:`Attached`,expression:Gr(r.replace(s.expression),i)}:!s.isFinal&&(qr(t,r.operator)||r.isInfix&&t.fixity===`InfixLeft`&&r.operator.fixity===`InfixLeft`&&!qr(r.operator,t))?{kind:`Reduced`,isFinal:!qr(t,r.operator)}:{kind:`Attached`,expression:Gr(r.replace(a(r.operand)),i)}},s=o(n,Hr(Ur(n),Ur(e)));return s.kind===`Attached`?s.expression:e},Yr="use instead the class`E_visit.iter_concrete`",Xr=(t,n,r,i)=>{let a=n.split(`
21
21
  `),o=e=>({file:t,startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column+1}),s=e=>{let t={line:e.endLine-1,column:e.endColumn-1},n=e=>e===` `||e===`\r`;for(;t.line<a.length;){let e=a[t.line];for(;n(e[t.column]);)t.column++;if(t.column<e.length)break;t.line++,t.column=0}if(!(a[t.line]??``).startsWith(`(*{`,t.column))return e;for(let n=t.line;n<a.length;n++){let r=a[n].indexOf(`}*)`,n===t.line?t.column:0);if(r!==-1)return{...e,endLine:n+1,endColumn:r+4}}return e},c=(e,n)=>({file:t,startLine:n.line,startColumn:n.column,endLine:n.line,endColumn:n.column+e.length}),l=e=>e.range?o(e.range):{file:t,startLine:e.line,startColumn:e.column,endLine:e.line,endColumn:e.column+1},u=(e,t)=>{let n=Rr(e),r=Lr[n];return S(r?{kind:`Internal`,builtin:r}:{kind:`Opaque`,name:n},{location:t})},d=(e,t,n,r)=>{if(e.startsWith(`<`)){let t=S({kind:`Opaque`,name:e},{location:n});return S({kind:`Bang`,expression:t,selectors:[]},{location:n})}let i=Lr[e];if(i&&t.length===0)return S({kind:`Internal`,builtin:i},{location:n});let a=e.split(`!`);if(a.length===1){let r=S({kind:`Opaque`,name:e},{location:n});return t.length===0?r:S({kind:`Apply`,operator:r,args:t},{location:n})}let o=r??a.map((e,n)=>n===a.length-1?t.length:0),s=o.map((e,t)=>o.slice(0,t).reduce((e,t)=>e+t,0)),c=e=>t.slice(s[e],s[e]+o[e]),l=S({kind:`Opaque`,name:a[0]},{location:n});return S({kind:`Bang`,expression:o[0]===0?l:S({kind:`Apply`,operator:l,args:c(0)},{location:n}),selectors:a.slice(1).map((e,t)=>({kind:`Label`,label:Rr(e),args:c(t+1)}))},{location:n})},f=(t,n)=>t.map((r,i)=>{if(r.pattern.kind===`Tuple`)throw new e.ut(`Unexpected tuple declaration`,{failure:Yr});let a=i>0&&t[i-1].set===r.set;return{name:r.pattern.name,level:`Constant`,domain:a?{kind:`Ditto`}:{kind:`Domain`,expression:g(r.set,n)}}}),p=(e,t)=>e.map((n,r)=>{let i=g(n.set,t);if(n.pattern.kind===`Tuple`)return{kind:`Tuple`,names:n.pattern.names,domain:i};let a=r>0&&e[r-1].set===n.set;return{kind:`Name`,name:n.pattern.name,domain:a?{kind:`Ditto`}:{kind:`Domain`,expression:i}}}),m=(t,n)=>{if(!i)throw new e.ut(`Unexpected tuple declaration`,{failure:Yr});return S(t(),{location:n})},h=e=>e.some(e=>e.pattern.kind===`Tuple`),g=(t,n)=>{let r=l(t.location),i=e=>g(e,n),a=(e,t)=>e.length===2?Br(e[0].location,e[1].location):e.length!==1||!e[0].location?r:t===`Prefix`?Br({...r,endLine:r.startLine,endColumn:r.startColumn+1},e[0].location):t===`Postfix`?Br({...r,startLine:r.endLine,startColumn:r.endColumn-1},e[0].location):r,o=(e,t)=>S({kind:`Apply`,operator:{kind:`Internal`,builtin:e},args:[t]},{location:a([t],`Prefix`)});switch(t.kind){case`Number`:return S({kind:`Num`,integer:t.text??String(t.value),fraction:``},{location:r});case`Decimal`:{let[e,n]=t.text.split(`.`);return S({kind:`Num`,integer:e,fraction:n},{location:r})}case`String`:return S({kind:`String`,value:t.value},{location:r});case`Identifier`:return d(t.name,[],r);case`Apply`:{if(t.args.length===2){let e=Jr(t);if(e!==t)return i(e)}let e=t.args.map(i),n=Ct(t.operator);return n.fixity===`Nonfix`?d(t.operator,e,r,t.argumentCounts):S({kind:`Apply`,operator:u(t.operator,void 0),args:e},{location:a(e,n.fixity)})}case`OperatorReference`:return u(t.operator,r);case`Lambda`:return S({kind:`Lambda`,params:t.params.map(e=>({name:e,shape:0})),body:i(t.body)},{location:r});case`And`:case`Or`:{let e=t.operands.map(i);if(t.isBulleted)return S({kind:`List`,bullet:t.kind,items:e},{location:r});let n=t.kind===`And`?`Conj`:`Disj`;return e.reduce((e,t)=>S({kind:`Apply`,operator:{kind:`Internal`,builtin:n},args:[e,t]},{location:Br(e.location,t.location)}))}case`Prime`:{let e=i(t.expression);return S({kind:`Apply`,operator:{kind:`Internal`,builtin:`Prime`},args:[e]},{location:a([e],`Postfix`)})}case`Unchanged`:return o(`UNCHANGED`,i(t.expression));case`Enabled`:return o(`ENABLED`,i(t.expression));case`If`:return S({kind:`If`,condition:i(t.condition),consequent:i(t.consequent),alternative:i(t.alternative)},{location:r});case`Case`:return S({kind:`Case`,arms:t.arms.map(e=>({condition:i(e.condition),body:i(e.body)})),other:t.other&&i(t.other)},{location:r});case`Let`:return S({kind:`Let`,definitions:[...t.definitions,...t.instances??[]].sort((e,t)=>e.location.line-t.location.line||e.location.column-t.location.column).map(e=>v(e,n)),body:i(t.body)},{location:r});case`Forall`:case`Exists`:if(h(t.bounds)){let e=p(t.bounds,n),a=i(t.body);return m(()=>Ar(t.kind,e,a),r)}return S({kind:`Quant`,quantifier:t.kind,bounds:f(t.bounds,n),body:i(t.body)},{location:r});case`UnboundedQuantifier`:{let e=i(t.body),n=t.quantifier;return t.isTemporal?S({kind:`Tquant`,quantifier:n,names:t.names,body:e},{location:r}):S({kind:`Quant`,quantifier:n,bounds:Tr(t.names),body:e},{location:r})}case`Choose`:if(t.pattern.kind===`Tuple`){let e=t.pattern.names,n=t.set&&i(t.set),a=i(t.body);return m(()=>Mr(e,n,a),r)}return S({kind:`Choose`,name:t.pattern.name,domain:t.set&&i(t.set),body:i(t.body)},{location:r});case`SetEnumeration`:return S({kind:`SetEnum`,elements:t.elements.map(i)},{location:r});case`SetFilter`:if(t.bound.pattern.kind===`Tuple`){let e=t.bound.pattern.names,n=i(t.bound.set),a=i(t.predicate);return m(()=>Nr(e,n,a),r)}return S({kind:`SetSt`,name:t.bound.pattern.name,domain:i(t.bound.set),body:i(t.predicate)},{location:r});case`SetMap`:if(h(t.bounds)){let e=i(t.expression),a=p(t.bounds,n);return m(()=>Fr(e,a),r)}return S({kind:`SetOf`,element:i(t.expression),bounds:f(t.bounds,n)},{location:r});case`Tuple`:return S({kind:`Tuple`,elements:t.elements.map(i)},{location:{...r,startLine:r.endLine,startColumn:r.endColumn-2}});case`FunctionConstruction`:if(h(t.bounds)){let e=p(t.bounds,n),a=i(t.body);return m(()=>Ir(e,a),r)}return S({kind:`Fcn`,bounds:f(t.bounds,n),body:i(t.body)},{location:r});case`FunctionSet`:return S({kind:`Arrow`,domain:i(t.domain),range:i(t.range)},{location:r});case`Record`:case`RecordSet`:return S({kind:t.kind===`Record`?`Record`:`Rect`,fields:t.fields.map(e=>({name:e.name,value:i(e.value)}))},{location:r});case`Except`:return S({kind:`Except`,function:i(t.function),specs:t.updates.map(e=>({trail:e.path.map(e=>e.kind===`Field`?{kind:`Dot`,field:e.name}:{kind:`Apply`,expression:e.args.length===1?i(e.args[0]):{kind:`Tuple`,elements:e.args.map(i)}}),value:g(e.value,!0)}))},{location:r});case`ExceptAt`:return S({kind:`At`,isExcept:n},{location:r});case`Bracket`:throw new e.ut(`Unexpected [ without a function or subscript`);case`FunctionApplication`:return S({kind:`FcnApp`,function:i(t.function),args:t.args.map(i)},{location:r});case`FieldAccess`:return S({kind:`Dot`,expression:i(t.record),field:t.field},{location:r});case`Product`:return S({kind:`Product`,factors:t.factors.map(i)},{location:r});case`Always`:case`Eventually`:{let e=t.expression;return t.kind===`Always`&&e.kind===`BoxAction`?S({kind:`Tsub`,modal:`Box`,action:i(e.action),subscript:i(e.subscript)},{location:r}):t.kind===`Eventually`&&e.kind===`AngleAction`?S({kind:`Tsub`,modal:`Dia`,action:i(e.action),subscript:i(e.subscript)},{location:r}):o(t.kind===`Always`?`BoxTrue`:`Diamond`,i(e))}case`BoxAction`:case`AngleAction`:return S({kind:`Sub`,modal:t.kind===`BoxAction`?`Box`:`Dia`,action:i(t.action),subscript:i(t.subscript)},{location:r});case`WeakFairness`:case`StrongFairness`:return S({kind:`Fair`,fairness:t.kind===`WeakFairness`?`Weak`:`Strong`,subscript:i(t.subscript),action:i(t.action)},{location:r});case`Label`:return S({kind:`Parens`,expression:i(t.body),form:{kind:`Nlabel`,label:t.name,names:t.params}},{location:r});case`Subexpression`:{let[n,...a]=t.selectors;if(n.kind!==`Name`)throw new e.ut(`Unexpected subexpression reference`);let o=S({kind:`Opaque`,name:n.name},{location:r}),s=n.args.length===0?o:S({kind:`Apply`,operator:o,args:n.args.map(i)},{location:r});return S({kind:`Bang`,expression:s,selectors:a.map(e=>{switch(e.kind){case`Name`:return{kind:`Label`,label:Rr(e.name),args:e.args.map(i)};case`Operand`:return e.operand===`<<`?{kind:`Left`}:e.operand===`>>`?{kind:`Right`}:{kind:`Number`,value:e.operand};case`Bound`:return{kind:`Instance`,args:e.args.map(i)};case`At`:return{kind:`At`};case`Colon`:return{kind:`Down`}}})},{location:r})}}},_=e=>({location:o(e.definitionRange??e.instanceRange),args:e.params.map(e=>e.name),module:e.module,substitutions:e.substitutions.map(e=>({name:Rr(e.name),expression:g(e.expression,!1)}))}),v=(t,n=!1)=>{let r=l(t.location);if(t.kind===`Instance`){if(t.name===void 0)throw new e.ut(`Unexpected keyword INSTANCE`);return{kind:`Instance`,name:t.name,instance:_(t),location:r}}let i=Rr(t.name,t.kind===`Operator`&&t.params.length===1&&t.name===`-`),a=g(t.body,n);if(t.kind===`Function`&&h(t.bounds)){let e=p(t.bounds,n);return{kind:`Operator`,name:i,body:m(()=>Ir(e,a),r),location:r}}if(t.kind===`Function`){let e=f(t.bounds,n);return{kind:`Operator`,name:i,body:S({kind:`Fcn`,bounds:e,body:a},{location:r}),location:r}}return t.params.length===0?{kind:`Operator`,name:i,body:a,location:r}:{kind:`Operator`,name:i,body:S({kind:`Lambda`,params:t.params.map(e=>({name:Rr(e.name),shape:e.arity,...e.location&&{location:c(e.name,e.location)}})),body:a},{location:r}),location:r}},y=e=>{let t=l(e.location);return e.level===`Variable`?{kind:`Flex`,name:e.name,location:t}:{kind:`Fresh`,name:e.name,shape:e.arity,level:e.level,domain:e.set&&g(e.set,!1),domainVisibility:`Visible`,location:t}},b=e=>e.kind===`AssumeProve`?{context:e.assumptions.map(e=>{if(e.kind===`NewSymbol`)return y(e);if(e.kind===`AssumeProve`){let t=l(e.location);return{kind:`Fact`,expression:S({kind:`Sequent`,sequent:b(e)},{location:t}),visibility:`Visible`,location:t}}let t=x(e);return{kind:`Fact`,expression:t,visibility:`Visible`,location:t.location}}),active:g(e.conclusion,!1)}:{context:[],active:g(e,!1)},x=e=>{if(e.kind!==`Label`||e.params.length>0)return g(e,!1);let t=l(e.location);return S({kind:`Parens`,expression:g(e.body,!1),form:{kind:`Xlabel`,label:e.name,indices:[]}},{location:t})},C=t=>{if(t.kind===`ModuleFact`)throw new e.pt(`MODULE facts in proof obligations are not supported`);let n=g(t,!1);return n.kind===`Bang`&&n.selectors.length===0?n.expression:n},w=t=>{let n=l(t.location);if(t.kind===`ModuleFact`)return{kind:`Dvar`,name:t.name,location:n};if(t.kind===`Identifier`)return{kind:`Dvar`,name:Rr(t.name),location:n};if(t.kind===`OperatorReference`)return{kind:`Dvar`,name:Rr(t.operator),location:n};throw new e.pt(`This DEF clause in proof obligations is not supported`)},T=e=>({facts:e.facts.map(C),defs:e.defs.map(w)}),E=(e,t)=>{let n=e?e[2]:``;return n===``?{kind:`Unnamed`,level:t,id:ze(r)}:{kind:`Named`,level:t,label:n,isAnonymous:!1}},ee=(e,t,n)=>{if(!e)return{kind:`Omitted`,omission:`Implicit`,location:n};switch(e.kind){case`Obvious`:return{kind:`Obvious`,location:s(o(e.keyword))};case`Omitted`:return{kind:`Omitted`,omission:`Explicit`,location:o(e.keyword)};case`By`:return{kind:`By`,usable:T(e),isOnly:e.isOnly,location:o(e.keyword),step:{kind:`Unnamed`,level:t,id:0}};case`Steps`:{let n=e.steps.map(e=>zr.exec(e.token)),r=n[0],i=r&&r[1]!==`*`&&r[1]!==`+`?Number(r[1]):t,a=e.steps.slice(0,-1).map((e,t)=>te(e,E(n[t],i),i)),s=e.steps[e.steps.length-1],c=E(n[n.length-1],i),l=o(s.head),u=ee(s.proof,i+1,l),d={proof:u,location:Br(l,u.location),step:c};return{kind:`Steps`,steps:a,qed:d,location:a.reduce((e,t)=>Br(e,t.location),d.location),step:d.step}}}},D=e=>Br(o(e.keyword),e.defs.length>0?l(e.defs[e.defs.length-1].location):void 0),te=(t,n,r)=>{let i=o(t.head),a=t.body,s=e=>{let a=ee(t.proof,r+1,i);return{...e(a),location:Br(i,a.location),step:n}},c=e=>({...e,location:i,step:n});switch(a.kind){case`Use`:case`Hide`:{let e=Br(o({...t.head,end:t.head.start}),D(a)),r=T(a);return a.kind===`Use`?{kind:`Use`,usable:r,isOnly:a.isOnly,location:e,step:n}:{kind:`Hide`,usable:r,location:e,step:n}}case`Instance`:throw new e.ut(`Unexpected keyword INSTANCE`);case`Define`:return c({kind:`Define`,definitions:a.definitions.map(e=>v(e))});case`Have`:return c({kind:`Have`,expression:g(a.expression,!1)});case`Take`:return c({kind:`Take`,bounds:a.names.length>0?Tr(a.names):f(a.bounds,!1)});case`Witness`:return c({kind:`Witness`,expressions:a.expressions.map(e=>g(e,!1))});case`Pick`:{let e=a.names.length>0?Tr(a.names):f(a.bounds,!1),t=g(a.body,!1);return s(n=>({kind:`Pick`,bounds:e,expression:t,proof:n}))}case`Case`:{let e=g(a.expression,!1);return s(t=>({kind:`Pcase`,expression:e,proof:t}))}case`Assert`:{let e=b(a.statement);return s(t=>a.isSuffices?{kind:`Suffices`,sequent:e,proof:t}:{kind:`Assert`,sequent:e,proof:t})}case`Qed`:throw new e.pt(`QED in the middle of a proof`)}},ne=e=>({name:e.name,extendees:e.extends,extendeeLocations:e.extendsRanges.map(o),isImportant:!1,location:l(e.location),body:e.units.map(e=>{switch(e.kind){case`Constants`:case`Recursive`:return{kind:e.kind===`Constants`?`Constants`:`Recursives`,declarations:e.declarations.map(e=>({name:Rr(e.name),shape:e.arity})),location:l(e.declarations[0].location)};case`Variables`:return{kind:`Variables`,names:e.declarations.map(e=>e.name),location:l(e.declarations[0].location)};case`Definition`:return{kind:`Definition`,definition:v(e.definition),whereDefined:`User`,visibility:`Hidden`,isLocal:e.definition.isLocal,location:l(e.definition.location)};case`Instance`:{let t=e.instance,n=l(t.location);return t.name===void 0?{kind:`Anoninst`,instance:_(t),isLocal:t.isLocal,location:n}:{kind:`Definition`,definition:v(t),whereDefined:`User`,visibility:`Hidden`,isLocal:t.isLocal,location:o(t.instanceRange)}}case`Assumption`:return{kind:`Axiom`,name:e.assumption.name,expression:g(e.assumption.expression,!1),location:l(e.assumption.location)};case`Theorem`:{let t=e.theorem,n=l(t.location),r=s(n);return{kind:`Theorem`,name:t.name,sequent:b(t.statement),axiomCount:0,proof:ee(t.proof,0,{...r,startLine:r.endLine,startColumn:r.endColumn}),location:n}}case`Use`:return{kind:`Mutate`,mode:e.use.kind,isSuppressed:!1,usable:T(e.use),location:D(e.use)};case`Module`:return{kind:`Submod`,module:{...ne(e.module),isImportant:!0}}}})});return{convertModule:ne}},Zr={start:0,end:1/0},Qr=/-{4,} *MODULE/,$r=`Unexpected EOF`,ei=e=>e?`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`:``,ti=t=>{let n=e.tt(t),r=t.split(`
22
22
  `),i=n.at(-1)?.line??r.length,a=r.slice(0,i-1).reduce((e,t)=>e+t.length+1,0)+r[i-1].indexOf(`====`),o=t.indexOf(` `,t.search(Qr));if(o===-1||o>=a)return;let s=t.slice(0,o).split(`
23
23
  `).length,c=o-t.lastIndexOf(`
24
- `,o-1),l=n.findLast(e=>e.kind!==`End`&&(e.line<s||e.line===s&&e.column<c));return{offset:o,line:s,column:c,end:{reason:$r,line:l?.line??s,column:l?l.endColumn+1:c,isEnd:!0}}},ni=t=>{try{return t()}catch(t){if(!(t instanceof e.ft)||!t.failure)throw t;return t.failure}},ri=e=>typeof e==`object`&&!!e&&`reason`in e,ii=t=>{let n=ni(()=>ti(t));if(ri(n))return[n];let r=ni(()=>e.E(n?t.slice(0,n.offset):t));return n&&(!ri(r)||r.isEnd)?[{reason:`Unexpected TAB character. TLAPS does not handle TAB characters in source files.`,line:n.line,column:n.column,isEnd:!1},ri(r)&&r.reason===$r?r:n.end]:ri(r)?[r]:r},ai=(t,n,r,i,a)=>{if(!Qr.test(t.source))throw new e.ut(`No tokens in file`);let o=ii(t.source);if(Array.isArray(o)){o.forEach(e=>{let n=`File ${JSON.stringify(t.file)}, line ${e.line}, character ${e.column}\n${e.reason}`;i({text:n,channel:`stderr`}),i({text:`${n}\n`,channel:`toolboxOnly`})});let n=`Could not parse ${JSON.stringify(t.file)} successfully.`;throw i({text:`${a}Error: ${n}`,channel:`stderr`}),new e.ut(n,{failure:`Module.Parser.parse_file`})}let s=Xr(t.file,t.source,n,r).convertModule(o),c=t.file.slice(t.file.lastIndexOf(`/`)+1),l=c.replace(/\.tla$/,``);return s.name===l?s:(i({text:`${_(s.location)}Warning: module name ${JSON.stringify(s.name)} does not match file name ${JSON.stringify(c)}.`,channel:`toolbox`}),{...s,name:l})},oi=t=>{let n=new Map([...t].map(([e,t])=>[e,nr(t).dependencies])),r=/* @__PURE__ */ new Set,i=[],a=o=>{if(r.has(o))return;r.add(o);let s=t.get(o);if(!s)throw new e.ut(`Module "${o}" not found`);(n.get(o)??[]).forEach(a),i.push(s)};return[...t.keys()].sort(ir).forEach(a),i},si=(e,t,n)=>t.length===0?[]:[` ${e}_proofs_count = ${t.length}`,...t.map((t,r)=>` ${e}_proof_${n+r+1} at ${p(t)}`)],ci=(e,t,n)=>{let r=e.location;return[` ---- incomplete proof of theorem at ${r?p({...r,endLine:r.startLine,endColumn:r.startColumn}):`<unknown location>`} ----`,...si(`missing`,e.absent,t),...si(`omitted`,e.omitted,n),` ====`]},li=e=>{let t=e.summary,n=t.theorems.reduce((e,t)=>t.absent.length+t.omitted.length===0?e:{lines:[...e.lines,...ci(t,e.missing,e.omitted)],missing:e.missing+t.absent.length,omitted:e.omitted+t.omitted.length},{lines:[],missing:0,omitted:0});return[`---- summary of module ${JSON.stringify(e.name)} ----`,` obligations_count = ${t.total}`,...t.absent.length>0?[` missing_proofs_count = ${t.absent.length}`]:[],...t.omitted.length>0?[` omitted_proofs_count = ${t.omitted.length}`]:[],...n.lines,`====`].join(`
24
+ `,o-1),l=n.findLast(e=>e.kind!==`End`&&(e.line<s||e.line===s&&e.column<c));return{offset:o,line:s,column:c,end:{reason:$r,line:l?.line??s,column:l?l.endColumn+1:c,isEnd:!0}}},ni=t=>{try{return t()}catch(t){if(!(t instanceof e.ft)||!t.failure)throw t;return t.failure}},ri=e=>typeof e==`object`&&!!e&&`reason`in e,ii=t=>{let n=ni(()=>ti(t));if(ri(n))return[n];let r=ni(()=>e.k(n?t.slice(0,n.offset):t));return n&&(!ri(r)||r.isEnd)?[{reason:`Unexpected TAB character. TLAPS does not handle TAB characters in source files.`,line:n.line,column:n.column,isEnd:!1},ri(r)&&r.reason===$r?r:n.end]:ri(r)?[r]:r},ai=(t,n,r,i,a)=>{if(!Qr.test(t.source))throw new e.ut(`No tokens in file`);let o=ii(t.source);if(Array.isArray(o)){o.forEach(e=>{let n=`File ${JSON.stringify(t.file)}, line ${e.line}, character ${e.column}\n${e.reason}`;i({text:n,channel:`stderr`}),i({text:`${n}\n`,channel:`toolboxOnly`})});let n=`Could not parse ${JSON.stringify(t.file)} successfully.`;throw i({text:`${a}Error: ${n}`,channel:`stderr`}),new e.ut(n,{failure:`Module.Parser.parse_file`})}let s=Xr(t.file,t.source,n,r).convertModule(o),c=t.file.slice(t.file.lastIndexOf(`/`)+1),l=c.replace(/\.tla$/,``);return s.name===l?s:(i({text:`${_(s.location)}Warning: module name ${JSON.stringify(s.name)} does not match file name ${JSON.stringify(c)}.`,channel:`toolbox`}),{...s,name:l})},oi=t=>{let n=new Map([...t].map(([e,t])=>[e,nr(t).dependencies])),r=/* @__PURE__ */ new Set,i=[],a=o=>{if(r.has(o))return;r.add(o);let s=t.get(o);if(!s)throw new e.ut(`Module "${o}" not found`);(n.get(o)??[]).forEach(a),i.push(s)};return[...t.keys()].sort(ir).forEach(a),i},si=(e,t,n)=>t.length===0?[]:[` ${e}_proofs_count = ${t.length}`,...t.map((t,r)=>` ${e}_proof_${n+r+1} at ${p(t)}`)],ci=(e,t,n)=>{let r=e.location;return[` ---- incomplete proof of theorem at ${r?p({...r,endLine:r.startLine,endColumn:r.startColumn}):`<unknown location>`} ----`,...si(`missing`,e.absent,t),...si(`omitted`,e.omitted,n),` ====`]},li=e=>{let t=e.summary,n=t.theorems.reduce((e,t)=>t.absent.length+t.omitted.length===0?e:{lines:[...e.lines,...ci(t,e.missing,e.omitted)],missing:e.missing+t.absent.length,omitted:e.omitted+t.omitted.length},{lines:[],missing:0,omitted:0});return[`---- summary of module ${JSON.stringify(e.name)} ----`,` obligations_count = ${t.total}`,...t.absent.length>0?[` missing_proofs_count = ${t.absent.length}`]:[],...t.omitted.length>0?[` omitted_proofs_count = ${t.omitted.length}`]:[],...n.lines,`====`].join(`
25
25
  `)},ui=(t,n,r={})=>{let i=r.lines??Zr,a=r.onWarning??(()=>{}),o={value:0},s=new Map(Xn);t.forEach(e=>{let t={...ai(e,o,!0,a,`File "<unknown>":
26
- `),isImportant:!0};s.set(t.name,t)});let c=[...s.values()].sort((e,t)=>ir(e.name,t.name)),l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Set;for(let e=0;e<c.length;e++){let t=nr(c[e]);t.submodules.forEach((e,t)=>{u.add(t),s.has(t)||s.set(t,e)});for(let e of t.dependencies){if(s.has(e)&&!Xn.has(e))continue;let r=n(e);if(!r){!s.has(e)&&!l.has(e)&&l.set(e,t.locations.get(e));continue}let i=ai(r,o,!1,a,h(t.locations.get(e)));s.set(e,i),c.push(i)}}let d=[...l.keys()].filter(e=>!u.has(e)).sort(ir);if(d.forEach(e=>a(g(l.get(e),`Unknown module ${JSON.stringify(e)}`))),d.length>0)throw new e.ut(`Unknown module ${JSON.stringify(d[0])}`,{failure:`Module.Parser.load_module`});let f={anonymizer:Ue(o,(e,t)=>yr(f,e,t),a),generator:hn(o,new Set(t.map(e=>e.file)),i,a),salts:{value:0},latestModules:/* @__PURE__ */ new Map,onWarning:a},p=oi(s).map(e=>e.isStandard?e:tr(s,e,/* @__PURE__ */ new Set)),m=new Map(p.map(e=>[e.name,e]));return p.flatMap(e=>{if(e.isStandard)return[];let t=br(f,m,void 0,e);if(!e.isImportant)return[];let n=xr(f,[],t),r=n.obligations.flatMap((e,t)=>{let n=e.location;if(e.kind.kind===`Omitted`||n&&(n.startLine<i.start||n.endLine>i.end))return[];let r=e.kind.kind===`Error`?e.kind.message:`${Ut(e.sequent)}\n`;return[{id:t+1,location:ei(n),text:r}]});return[{name:e.name,location:e.location,obligations:r,summary:n.summary}]})},di=`----------------------------- MODULE Bags --------------------------------
27
- (**************************************************************************)
28
- (* A bag, also called a multiset, is a set that can contain multiple *)
29
- (* copies of the same element. A bag can have infinitely many elements, *)
30
- (* but only finitely many copies of any single element. *)
31
- (* *)
32
- (* We represent a bag in the usual way as a function whose range is a *)
33
- (* subset of the positive integers. An element e belongs to bag B iff e *)
34
- (* is in the domain of B, in which case bag B contains B[e] copies of e. *)
35
- (**************************************************************************)
36
- (**************************************************************************)
37
- (* All these definitions other than SubBag are overridden by TLC in the *)
38
- (* Java class tlc2.module.Bags. Each operator is overridden by the Java *)
39
- (* method with the same name, except that the mapping for TLA+ infix *)
40
- (* operators is defined in the static block at the beginning of the Java *)
41
- (* class. *)
42
- (**************************************************************************)
43
- LOCAL INSTANCE Naturals
44
-
45
- IsABag(B) ==
46
- (************************************************************************)
47
- (* True iff B is a bag. *)
48
- (************************************************************************)
49
- B \\in [DOMAIN B -> {n \\in Nat : n > 0}]
50
-
51
- BagToSet(B) == DOMAIN B
52
- (************************************************************************)
53
- (* The set of elements at least one copy of which is in B. *)
54
- (************************************************************************)
55
-
56
- SetToBag(S) == [e \\in S |-> 1]
57
- (************************************************************************)
58
- (* The bag that contains one copy of every element of the set S. *)
59
- (************************************************************************)
60
-
61
- BagIn(e,B) == e \\in BagToSet(B)
62
- (************************************************************************)
63
- (* The \\in operator for bags. *)
64
- (************************************************************************)
65
-
66
- EmptyBag == SetToBag({})
67
-
68
- B1 (+) B2 ==
69
- (************************************************************************)
70
- (* The union of bags B1 and B2. *)
71
- (************************************************************************)
72
- [e \\in (DOMAIN B1) \\cup (DOMAIN B2) |->
73
- (IF e \\in DOMAIN B1 THEN B1[e] ELSE 0)
74
- + (IF e \\in DOMAIN B2 THEN B2[e] ELSE 0) ]
75
-
76
- B1 (-) B2 ==
77
- (************************************************************************)
78
- (* The bag B1 with the elements of B2 removed--that is, with one copy *)
79
- (* of an element removed from B1 for each copy of the same element in *)
80
- (* B2. If B2 has at least as many copies of e as B1, then B1 (-) B2 *)
81
- (* has no copies of e. *)
82
- (************************************************************************)
83
- LET B == [e \\in DOMAIN B1 |-> IF e \\in DOMAIN B2 THEN B1[e] - B2[e]
84
- ELSE B1[e]]
85
- IN [e \\in {d \\in DOMAIN B : B[d] > 0} |-> B[e]]
86
-
87
- LOCAL Sum(f) ==
88
- (******************************************************************)
89
- (* The sum of f[x] for all x in DOMAIN f. The definition assumes *)
90
- (* that f is a Nat-valued function and that f[x] equals 0 for all *)
91
- (* but a finite number of elements x in DOMAIN f. *)
92
- (******************************************************************)
93
- LET DSum[S \\in SUBSET DOMAIN f] ==
94
- LET elt == CHOOSE e \\in S : TRUE
95
- IN IF S = {} THEN 0
96
- ELSE f[elt] + DSum[S \\ {elt}]
97
- IN DSum[DOMAIN f]
98
-
99
- BagUnion(S) ==
100
- (************************************************************************)
101
- (* The bag union of all elements of the set S of bags. *)
102
- (************************************************************************)
103
- [e \\in UNION {BagToSet(B) : B \\in S} |->
104
- Sum( [B \\in S |-> IF BagIn(e, B) THEN B[e] ELSE 0] ) ]
105
-
106
- B1 \\sqsubseteq B2 ==
107
- (************************************************************************)
108
- (* The subset operator for bags. B1 \\sqsubseteq B2 iff, for all e, bag *)
109
- (* B2 has at least as many copies of e as bag B1 does. *)
110
- (************************************************************************)
111
- /\\ (DOMAIN B1) \\subseteq (DOMAIN B2)
112
- /\\ \\A e \\in DOMAIN B1 : B1[e] \\leq B2[e]
113
-
114
- SubBag(B) ==
115
- (************************************************************************)
116
- (* The set of all subbags of bag B. *)
117
- (* *)
118
- (* The following definition is not the one described in the TLA+ book, *)
119
- (* but rather one that TLC can evaluate. *)
120
- (************************************************************************)
121
-
122
- LET RemoveFromDom(x, f) == [y \\in (DOMAIN f) \\ {x} |-> f[y]]
123
- Combine(x, BagSet) ==
124
- BagSet \\cup
125
- {[y \\in (DOMAIN f) \\cup {x} |-> IF y = x THEN i ELSE f[y]] :
126
- f \\in BagSet, i \\in 1..B[x]}
127
- Biggest == LET Range == {B[x] : x \\in DOMAIN B}
128
- IN IF Range = {} THEN 0
129
- ELSE CHOOSE r \\in Range :
130
- \\A s \\in Range : r \\geq s
131
- RSB[BB \\in UNION {[S -> 1..Biggest] : S \\in SUBSET DOMAIN B}] ==
132
- IF BB = << >> THEN {<< >>}
133
- ELSE LET x == CHOOSE x \\in DOMAIN BB : TRUE
134
- IN Combine(x, RSB[RemoveFromDom(x, BB)])
135
- IN RSB[B]
136
-
137
- (******************* Here is the definition from the TLA+ book. ********
138
- LET AllBagsOfSubset ==
139
- (******************************************************************)
140
- (* The set of all bags SB such that BagToSet(SB) \\subseteq *)
141
- (* BagToSet(B). *)
142
- (******************************************************************)
143
- UNION {[SB -> {n \\in Nat : n > 0}] : SB \\in SUBSET BagToSet(B)}
144
- IN {SB \\in AllBagsOfSubset : \\A e \\in DOMAIN SB : SB[e] \\leq B[e]}
145
- ***************************************************************************)
146
-
147
- BagOfAll(F(_), B) ==
148
- (************************************************************************)
149
- (* The bag analog of the set {F(x) : x \\in B} for a set B. It's the bag *)
150
- (* that contains, for each element e of B, one copy of F(e) for every *)
151
- (* copy of e in B. This defines a bag iff, for any value v, the set of *)
152
- (* e in B such that F(e) = v is finite. *)
153
- (************************************************************************)
154
- [e \\in {F(d) : d \\in BagToSet(B)} |->
155
- Sum( [d \\in BagToSet(B) |-> IF F(d) = e THEN B[d] ELSE 0] ) ]
156
-
157
- BagCardinality(B) ==
158
- (************************************************************************)
159
- (* If B is a finite bag (one such that BagToSet(B) is a finite set), *)
160
- (* then this is its cardinality (the total number of copies of elements *)
161
- (* in B). Its value is unspecified if B is infinite. *)
162
- (************************************************************************)
163
- Sum(B)
164
-
165
- CopiesIn(e, B) ==
166
- (************************************************************************)
167
- (* If B is a bag, then CopiesIn(e, B) is the number of copies of e in *)
168
- (* B. If ~BagIn(e, B), then CopiesIn(e, B) = 0. *)
169
- (************************************************************************)
170
- IF BagIn(e, B) THEN B[e] ELSE 0
171
- =============================================================================
172
-
173
- (* Last modified on Fri 26 Jan 2007 at 8:45:03 PST by lamport *)
174
-
175
- 6 Apr 99 : Modified version for standard module set
176
- 7 Dec 98 : Corrected error found by Stephan Merz.
177
- 6 Dec 98 : Modified comments based on suggestions by Lyle Ramshaw.
178
- 5 Dec 98 : Initial version.
179
- `,fi=/* @__PURE__ */ new Map([[`Bags`,di],[`FiniteSets`,`---------------------------- MODULE FiniteSets -----------------------------
180
- (***************************************************************************)
181
- (* The two definitions in this standard module are overridden by TLC in *)
182
- (* the Java class tlc2.module.FiniteSets. Each operator is overridden by *)
183
- (* the Java method with the same name. *)
184
- (***************************************************************************)
185
- LOCAL INSTANCE Naturals
186
- LOCAL INSTANCE Sequences
187
- (*************************************************************************)
188
- (* Imports the definitions from Naturals and Sequences, but doesn't *)
189
- (* export them. *)
190
- (*************************************************************************)
191
-
192
- IsFiniteSet(S) ==
193
- (*************************************************************************)
194
- (* A set S is finite iff there is a finite sequence containing all its *)
195
- (* elements. *)
196
- (*************************************************************************)
197
- \\E seq \\in Seq(S) : \\A s \\in S : \\E n \\in 1..Len(seq) : seq[n] = s
198
-
199
- Cardinality(S) ==
200
- (*************************************************************************)
201
- (* Cardinality is defined only for finite sets. *)
202
- (*************************************************************************)
203
- LET CS[T \\in SUBSET S] == IF T = {} THEN 0
204
- ELSE 1 + CS[T \\ {CHOOSE x : x \\in T}]
205
- IN CS[S]
206
- =============================================================================
207
- `],[`Integers`,`-------------------------------- MODULE Integers ----------------------------
208
- (***************************************************************************)
209
- (* This module provides dummy definitions of the operators that are *)
210
- (* defined by the real Integers module. It is expected that any tool will *)
211
- (* provide its own implementations of these operators. See the book *)
212
- (* "Specifying Systems" for the real Integers module. *)
213
- (***************************************************************************)
214
- (***************************************************************************)
215
- (* The two definitions here and the definitions imported from the Naturals *)
216
- (* module are overridden by TLC in the Java class tlc2.module.Integers. *)
217
- (* Each operator is overridden by the Java method with the same name, *)
218
- (* except that the mappings for the prefix - operator and the TLA+ infix *)
219
- (* operators are defined in the static block at the beginning of the Java *)
220
- (* class. *)
221
- (***************************************************************************)
222
- EXTENDS Naturals
223
-
224
- Int == { }
225
- (***************************************************************************)
226
- (* This defines the prefix - operator. *)
227
- (***************************************************************************)
228
- -. a == 0 - a
229
- =============================================================================
230
- `],[`Json`,`-------------------------------- MODULE Json --------------------------------
231
-
232
- LOCAL INSTANCE Sequences
233
- LOCAL INSTANCE FiniteSets
234
- LOCAL INSTANCE TLC
235
- (*************************************************************************)
236
- (* Imports the definitions from the modules, but doesn't export them. *)
237
- (*************************************************************************)
238
-
239
- -----------------------------------------------------------------------------
240
-
241
- LOCAL IsSequence(F, D) == TRUE \\/ FALSE
242
-
243
- LOCAL ToJsonKeyValue(F, d) ==
244
- ToString(ToString(d)) \\o ":" \\o ToString(F[d])
245
-
246
- RECURSIVE ToJsonObjectString(_,_)
247
- LOCAL ToJsonObjectString(F, D) == \\* LOCAL just a hint for humans.
248
- LET d == CHOOSE d \\in D: TRUE
249
- IN IF D = DOMAIN F
250
- THEN "{" \\o ToJsonKeyValue(F, d) \\o IF D \\ {d} = {}
251
- THEN "}"
252
- ELSE ToJsonObjectString(F, D \\ {d})
253
- ELSE ", " \\o ToJsonKeyValue(F, d) \\o IF D \\ {d} = {}
254
- THEN "}"
255
- ELSE ToJsonObjectString(F, D \\ {d})
256
-
257
- RECURSIVE ToJsonArrayString(_,_)
258
- LOCAL ToJsonArrayString(F, D) == \\* LOCAL just a hint for humans.
259
- LET d == CHOOSE d \\in D: TRUE
260
- IN IF D = DOMAIN F
261
- THEN "[" \\o ToString(F[d]) \\o IF D \\ {d} = {}
262
- THEN "]"
263
- ELSE ToJsonArrayString(F, D \\ {d})
264
- ELSE ", " \\o ToString(F[d]) \\o IF D \\ {d} = {}
265
- THEN "]"
266
- ELSE ToJsonArrayString(F, D \\ {d})
267
-
268
- RECURSIVE ToJsonString(_,_)
269
- LOCAL ToJsonString(F, D) == \\* LOCAL just a hint for humans.
270
- IF IsFiniteSet(F) \\/ IsSequence(F, D) THEN
271
- ToJsonArrayString(F, D)
272
- ELSE
273
- ToJsonObjectString(F, D)
274
-
275
- ToJson(value) ==
276
- (*************************************************************************)
277
- (* Converts the given value to a JSON string. Records are converted to *)
278
- (* JSON objects, tuples to JSON arrays, and scalar values as their JSON *)
279
- (* representation. *)
280
- (*************************************************************************)
281
- IF DOMAIN value = {} THEN
282
- "{}"
283
- ELSE
284
- ToJsonString(value, DOMAIN value)
285
-
286
- ToJsonArray(value) ==
287
- (*************************************************************************)
288
- (* Converts the given tuple value to a JSON array. *)
289
- (*************************************************************************)
290
- IF DOMAIN value = {} THEN
291
- "[]"
292
- ELSE
293
- ToJsonArrayString(value, DOMAIN value)
294
-
295
- ToJsonObject(value) ==
296
- (*************************************************************************)
297
- (* Converts the given tuple value to a JSON object. *)
298
- (*************************************************************************)
299
- IF DOMAIN value = {} THEN
300
- "{}"
301
- ELSE
302
- ToJsonObjectString(value, DOMAIN value)
303
-
304
- JsonSerialize(absoluteFilename, value) ==
305
- (*************************************************************************)
306
- (* Serializes a tuple of values to the given file as (plain) JSON. *)
307
- (* Records will be serialized as a JSON objects, and tuples as arrays. *)
308
- (*************************************************************************)
309
- TRUE
310
-
311
- JsonDeserialize(absoluteFilename) ==
312
- (*************************************************************************)
313
- (* Deserializes JSON values from the given file. JSON objects will be *)
314
- (* deserialized to records, and arrays will be deserialized to tuples. *)
315
- (*************************************************************************)
316
- CHOOSE val : TRUE
317
-
318
- ndJsonSerialize(absoluteFilename, value) ==
319
- (*************************************************************************)
320
- (* Serializes a tuple of values to the given file as newline delimited *)
321
- (* JSON. Records will be serialized as a JSON objects, and tuples as *)
322
- (* arrays. *)
323
- (*************************************************************************)
324
- TRUE
325
-
326
- ndJsonDeserialize(absoluteFilename) ==
327
- (*************************************************************************)
328
- (* Deserializes JSON values from the given file. JSON values must be *)
329
- (* separated by newlines. JSON objects will be deserialized to records, *)
330
- (* and arrays will be deserialized to tuples. *)
331
- (*************************************************************************)
332
- CHOOSE val : TRUE
333
-
334
- =============================================================================
335
- `],[`Naturals`,`-------------------------------- MODULE Naturals ----------------------------
336
- (***************************************************************************)
337
- (* This module provides dummy definitions of the operators that are *)
338
- (* defined by the real Naturals module. It is expected that any tool will *)
339
- (* provide its own implementations of these operators. See the book *)
340
- (* "Specifying Systems" for the real Naturals module. *)
341
- (***************************************************************************)
342
- (***************************************************************************)
343
- (* These definitions are all overridden by TLC in the Java class *)
344
- (* tlc2.module.Naturals. Each operator is overridden by the Java method *)
345
- (* with the same name, except that the mapping for TLA+ infix operators *)
346
- (* is defined in the static block at the beginning of the Java class. *)
347
- (***************************************************************************)
348
- Nat == { }
349
- a+b == {a, b}
350
-
351
- a-b == CHOOSE n : b + n = a
352
- a*b == TRUE
353
- a^b == {a, b}
354
- a<b == a = b
355
- a>b == a = b
356
- a \\leq b == a = b
357
- a \\geq b == a = b
358
- (***************************************************************************)
359
- (* a .. b is defined to equal {i \\in Int : (a \\leq i) /\\ (i \\leq b)} *)
360
- (* where Int is the set of all integers. *)
361
- (* *)
362
- (* a % b and a \\div b are defined so that for any integers a and b *)
363
- (* with b > 0 , the following formula is true: *)
364
- (* *)
365
- (* a = b * (a \\div b) + (a % b) *)
366
- (***************************************************************************)
367
- a % b == {a, b}
368
- a \\div b == {a, b}
369
- a .. b == {a, b}
370
- =============================================================================
371
- `],[`Randomization`,`-------------------------- MODULE Randomization------------------------------
372
- (***************************************************************************)
373
- (* This module defines operators for choosing pseudo-random subsets of a *)
374
- (* set. It is useful for inductive invariance checking, where the *)
375
- (* operators appear only in the initial predicate. However, it may have *)
376
- (* other uses. *)
377
- (* *)
378
- (* In breadth-first search model checking, the pseudo-random choices made *)
379
- (* when computing possible steps satisfying the next-state relation are *)
380
- (* determined by the first state of the step. Thus, the choices made for *)
381
- (* a particular state will be the same in successive runs of TLC. This is *)
382
- (* done to permit TLC to generate an error trace if an error is found. *)
383
- (* This applies only when TLC is run in breadth-first search mode. In *)
384
- (* particular, the choices made in simulation mode are independent of the *)
385
- (* state for which they are made. *)
386
- (***************************************************************************)
387
-
388
- (***************************************************************************)
389
- (* Except for TestRandomSetOfSubsets, all these definitions are overridden *)
390
- (* by TLC in the Java class tlc2.module.Randomization. Each operator is *)
391
- (* overridden by the Java method with the same name. *)
392
- (***************************************************************************)
393
- LOCAL INSTANCE Naturals
394
- LOCAL INSTANCE FiniteSets
395
-
396
- (***************************************************************************)
397
- (* RandomSubset(k, S) equals a randomly chosen subset of S containing k *)
398
- (* elements, where 0 < k < Cardinality(S). *)
399
- (***************************************************************************)
400
- RandomSubset(k, S) == CHOOSE T \\in SUBSET S : Cardinality(T) = k
401
-
402
- (***************************************************************************)
403
- (* RandomSetOfSubsets(k, n, S) equals a pseudo-randomly chosen set of *)
404
- (* subsets of S -- that is, a randomly chosen subset of SUBSET S . Thus, *)
405
- (* each element T of this set is a subset of S. Each such T is chosen so *)
406
- (* that each element of S has a probability n / Cardinality(S) of being in *)
407
- (* T. Thus, the average number of elements in each chosen subset T is n. *)
408
- (* The set RandomSetOfSubsets(k, n, S) is obtained by making k such *)
409
- (* choices of T . Because this can produce duplicate choices, the number *)
410
- (* of elements T in this set may be less than k. The average number of *)
411
- (* elements in RandomSetOfSubsets(k, n, S) seems to be difficult to *)
412
- (* compute in general. However, there is very little variation in the *)
413
- (* actual number of elements in the chosen set for fixed values of k, n, *)
414
- (* and Cardinality(S). You can therefore use the operator *)
415
- (* TestRandomSetOfSubsets defined below to find out approximately how *)
416
- (* close to k the cardinality of the chosen set of subsets is. *)
417
- (***************************************************************************)
418
- RandomSetOfSubsets(k, n, S) == CHOOSE T \\in SUBSET SUBSET S :
419
- Cardinality(T) \\leq k
420
-
421
- (***************************************************************************)
422
- (* The value of TestRandomSetOfSubsets(k, n, S) is a sequence of five *)
423
- (* values that are the cardinality of the set of subsets produced by five *)
424
- (* executions of RandomSetOfSubsets(k, n, S). For constant values of k, *)
425
- (* n, and S, you can enter TestRandomSetOfSubsets(k, n, S) in the Evaluate *)
426
- (* Constant Expression section of a TLC model in the TLA+ Toolbox. *)
427
- (* Running TLC will then tell you the approximate number of elements in *)
428
- (* the set of subsets produced by RandomSetOfSubsets for these parameters. *)
429
- (* You can then choose k to obtain a set of the desired size. *)
430
- (***************************************************************************)
431
- TestRandomSetOfSubsets(k, n, S) ==
432
- [i \\in 1..5 |-> Cardinality(RandomSetOfSubsets(k, n, S))]
433
-
434
- =============================================================================
435
- `],[`RealTime`,`${e.A}\n`],[`Reals`,`${e.k}\n`],[`Sequences`,`------------------------------ MODULE Sequences -----------------------------
436
- (***************************************************************************)
437
- (* Defines operators on finite sequences, where a sequence of length n is *)
438
- (* represented as a function whose domain is the set 1..n (the set *)
439
- (* {1, 2, ... , n}). This is also how TLA+ defines an n-tuple, so *)
440
- (* tuples are sequences. *)
441
- (***************************************************************************)
442
- (***************************************************************************)
443
- (* These definitions are all overridden by TLC in the Java class *)
444
- (* tlc2.module.Sequences. Each operator is overridden by the Java method *)
445
- (* with the same name, except that the mapping for TLA+ infix operators *)
446
- (* is defined in the static block at the beginning of the Java class. *)
447
- (***************************************************************************)
448
-
449
- LOCAL INSTANCE Naturals
450
- (*************************************************************************)
451
- (* Imports the definitions from Naturals, but doesn't export them. *)
452
- (*************************************************************************)
453
-
454
- Seq(S) == UNION {[1..n -> S] : n \\in Nat}
455
- (*************************************************************************)
456
- (* The set of all sequences of elements in S. *)
457
- (*************************************************************************)
458
-
459
- Len(s) == CHOOSE n \\in Nat : DOMAIN s = 1..n
460
- (*************************************************************************)
461
- (* The length of sequence s. *)
462
- (*************************************************************************)
463
-
464
- s \\o t == [i \\in 1..(Len(s) + Len(t)) |-> IF i \\leq Len(s) THEN s[i]
465
- ELSE t[i-Len(s)]]
466
- (*************************************************************************)
467
- (* The sequence obtained by concatenating sequences s and t. *)
468
- (*************************************************************************)
469
-
470
- Append(s, e) == s \\o <<e>>
471
- (**************************************************************************)
472
- (* The sequence obtained by appending element e to the end of sequence s. *)
473
- (**************************************************************************)
474
-
475
- Head(s) == s[1]
476
- Tail(s) == CASE s # << >> -> [i \\in 1..(Len(s)-1) |-> s[i+1]]
477
- (*************************************************************************)
478
- (* The usual head (first) and tail (rest) operators. (Definition of Tail *)
479
- (* changed on 4 Jun 2013 because original defined Tail(<< >>) = << >> . *)
480
- (*************************************************************************)
481
-
482
- SubSeq(s, m, n) == [i \\in 1..(1+n-m) |-> s[i+m-1]]
483
- (*************************************************************************)
484
- (* The sequence <<s[m], s[m+1], ... , s[n]>>. *)
485
- (*************************************************************************)
486
-
487
- SelectSeq(s, Test(_)) ==
488
- (*************************************************************************)
489
- (* The subsequence of s consisting of all elements s[i] such that *)
490
- (* Test(s[i]) is true. *)
491
- (*************************************************************************)
492
- LET F[i \\in 0..Len(s)] ==
493
- (*******************************************************************)
494
- (* F[i] equals SelectSeq(SubSeq(s, 1, i), Test) . *)
495
- (*******************************************************************)
496
- IF i = 0 THEN << >>
497
- ELSE IF Test(s[i]) THEN Append(F[i-1], s[i])
498
- ELSE F[i-1]
499
- IN F[Len(s)]
500
- =============================================================================
501
- `],[`TLC`,`------------------------------- MODULE TLC ----------------------------------
502
- (***************************************************************************)
503
- (* This is a standard module for use with the TLC model checker. *)
504
- (* Operators not explained by comments here are explained in the book *)
505
- (* "Specifying Systems". *)
506
- (* *)
507
- (* The definitions of all the operators in this module are overridden by *)
508
- (* TLC with methods defined in the Java class tlc2.module.TLC. Each *)
509
- (* definition is overridden with the method of the same name, except that *)
510
- (* the mapping from infix operators to Java methods is specified in the *)
511
- (* static block at the beginning of the Java class. *)
512
- (***************************************************************************)
513
- LOCAL INSTANCE Naturals
514
- LOCAL INSTANCE Sequences
515
- LOCAL INSTANCE FiniteSets
516
- -----------------------------------------------------------------------------
517
- Print(out, val) == val
518
- PrintT(out) == TRUE
519
- (************************************************************************)
520
- (* This expression equals TRUE, but evaluating it causes TLC to print *)
521
- (* the value of out. *)
522
- (************************************************************************)
523
-
524
- Assert(val, out) == IF val = TRUE THEN TRUE
525
- ELSE CHOOSE v : TRUE
526
- JavaTime == CHOOSE n : n \\in Nat
527
-
528
- (***************************************************************************)
529
- (* TLC can read and set a special list of values while evaluating *)
530
- (* expressions using the operators TLCSet and TLCGet. When TLC evaluates *)
531
- (* TLCSet(i,v), for any positive integer i and arbitrary value v, it *)
532
- (* obtains the value TRUE and sets element number i of the list to v. *)
533
- (* When TLC evaluates TLCGet(i), the value it obtains is the current value *)
534
- (* of the element number i of this list. *)
535
- (* *)
536
- (* One use of this feature is to check TLC's progress during long *)
537
- (* computations. For example, suppose TLC is evaluating a formula *)
538
- (* \\A x \\in S : P where S is a large set, so it evaluates P many times. *)
539
- (* You can use TLCGet, TLCSet, and Print to print something after every *)
540
- (* 1000 times TLC evaluates P. *)
541
- (* *)
542
- (* As explained in the description of the TLCEval operator below, you may *)
543
- (* also want to use this feature to count how many times TLC is evaluating *)
544
- (* an expression e. To use value number i as the counter, just replace e *)
545
- (* by *)
546
- (* *)
547
- (* IF TLCSet(i, TLCGet(i)+1) THEN e ELSE 42 *)
548
- (* *)
549
- (* (The ELSE expression is never evaluated.) *)
550
- (* *)
551
- (* TLCGet accepts some pre-defined string values to query TLC state. The *)
552
- (* values are as follows: *)
553
- (* *)
554
- (* - TLCGet("distinct") evaluates to the total number of distinct states *)
555
- (* found by TLC so far, globally. *)
556
- (* - TLCGet("queue") evaluates to the number of states currently in the *)
557
- (* queue to be checked. *)
558
- (* - TLCGet("duration") evaluates to the number of seconds elapsed since *)
559
- (* model checking began. *)
560
- (* - TLCGet("diameter") evaluates to the length of the longest behavior *)
561
- (* found by TLC so far, globally (equals one in the initial predicate).*)
562
- (* - TLCGet("level") is the length of the current behavior (equals zero *)
563
- (* in the evaluation of the initial predicate). *)
564
- (* *)
565
- (* For reasons of efficiency, TLCGet and TLCSet behave somewhat strangely *)
566
- (* when TLC is run with multiple worker threads. Each worker thread *)
567
- (* maintains its own individual copy of the list of values on which it *)
568
- (* evaluates TLCGet and TLCSet. The worker threads are activated only *)
569
- (* after the computation and invariance checking of the initial states. *)
570
- (* Before then, evaluating TLCSet(i,v) sets the element i of the list *)
571
- (* maintained by all threads. Thus, the lists of all the worker threads *)
572
- (* can be initialized by putting the appropriate TLCSet expression in an *)
573
- (* ASSUME expression or in the initial predicate. *)
574
- (***************************************************************************)
575
- TLCGet(i) == CHOOSE n : TRUE
576
- TLCSet(i, v) == TRUE
577
- -----------------------------------------------------------------------------
578
- d :> e == [x \\in {d} |-> e]
579
- f @@ g == [x \\in (DOMAIN f) \\cup (DOMAIN g) |->
580
- IF x \\in DOMAIN f THEN f[x] ELSE g[x]]
581
- Permutations(S) ==
582
- {f \\in [S -> S] : \\A w \\in S : \\E v \\in S : f[v]=w}
583
- -----------------------------------------------------------------------------
584
- (***************************************************************************)
585
- (* In the following definition, we use Op as the formal parameter rather *)
586
- (* than \\prec because TLC Version 1 can't handle infix formal parameters. *)
587
- (***************************************************************************)
588
- SortSeq(s, Op(_, _)) ==
589
- LET Perm == CHOOSE p \\in Permutations(1 .. Len(s)) :
590
- \\A i, j \\in 1..Len(s) :
591
- (i < j) => Op(s[p[i]], s[p[j]]) \\/ (s[p[i]] = s[p[j]])
592
- IN [i \\in 1..Len(s) |-> s[Perm[i]]]
593
-
594
- (***************************************************************************)
595
- (* TLC evaluates RandomElement(S) to be a pseudo-randomly chosen element *)
596
- (* of the set S, where each element of S is chosen with equal probability. *)
597
- (* This feature was added to enable the computation of statistical *)
598
- (* properties of a specification's executions by running TLC in simulation *)
599
- (* mode. We don't know if anyone has ever done this. *)
600
- (* *)
601
- (* In breadth-first search model checking, the pseudo-random choices made *)
602
- (* when computing possible steps satisfying the next-state relation are *)
603
- (* determined by the first state of the step. Thus, the choices made for *)
604
- (* a particular state will be the same in successive runs of TLC. This is *)
605
- (* done to permit TLC to generate an error trace if an error is found. *)
606
- (* This applies only when TLC is run in breadth-first search mode. The *)
607
- (* random choices made in simulation mode are independent of the state for *)
608
- (* which they are made. *)
609
- (***************************************************************************)
610
- RandomElement(s) == CHOOSE x \\in s : TRUE
611
-
612
- (***************************************************************************)
613
- (* The constant value Any has the special property that, for any value v, *)
614
- (* TLC evaluates the expression v \\in Any to equal TRUE. The special *)
615
- (* value Any was introduced because TLA+ originally allowed only functions *)
616
- (* to be defined recursively, and it was sometimes convenient to define a *)
617
- (* function with domain Any. It is retained for backwards compatibility. *)
618
- (***************************************************************************)
619
- Any == CHOOSE x : TRUE
620
-
621
- ToString(v) == (CHOOSE x \\in [a : v, b : STRING] : TRUE).b
622
- (************************************************************************)
623
- (* This equals a string that is the TLA+ representation of the value *)
624
- (* that TLC obtains by evaluating v. *)
625
- (************************************************************************)
626
-
627
- (***************************************************************************)
628
- (* TLC often uses lazy evaluation. For example, it may not enumerate the *)
629
- (* elements of a set of the form {x \\in T : P(x)} unless it has to; and it *)
630
- (* doesn't have to if it only needs to check if an element e is in that *)
631
- (* set. (TLC can do that by evaluating x \\in T and P(e).) TLC uses *)
632
- (* heuristics to determine when it should completely evaluate an *)
633
- (* expression. Those heuristics work well most of the time. However, *)
634
- (* sometimes lazy evaluation can result in the expression ultimately being *)
635
- (* evaluated multiple times instead of just once. This can especially be *)
636
- (* a problem when evaluating a recursively defined operator. You can get *)
637
- (* TLC to fully evaluate an expression exp and not use lazy evaluation by *)
638
- (* replacing exp with TLCEval(exp). *)
639
- (* *)
640
- (* If TLC is taking a long time to evaluate something, you can check if *)
641
- (* lazy evaluation is the source of the problem by using the TLCSet and *)
642
- (* TLCGet operators to count how many times expressions are being *)
643
- (* evaluated. *)
644
- (***************************************************************************)
645
- TLCEval(v) == v
646
-
647
- =============================================================================`],[`TLCExt`,`------------------------------- MODULE TLCExt -------------------------------
648
-
649
- LOCAL INSTANCE TLC
650
- LOCAL INSTANCE Integers
651
- (*************************************************************************)
652
- (* Imports the definitions from the modules, but doesn't export them. *)
653
- (*************************************************************************)
654
-
655
- -----------------------------------------------------------------------------
656
-
657
- \\* AssertEq(a, b) is logically equivalent to the expression 'a = b'. If a and b are not equal,
658
- \\* however, AssertEq(a, b) will print out the values of 'a' and 'b'. If the two values are equal,
659
- \\* nothing will be printed.
660
- AssertEq(a, b) ==
661
- IF a # b THEN
662
- /\\ PrintT("Assertion failed")
663
- /\\ PrintT(a)
664
- /\\ PrintT(b)
665
- /\\ a = b
666
- ELSE a = b
667
-
668
-
669
- AssertError(err, exp) ==
670
- LET FailsEval(e) == CHOOSE b \\in BOOLEAN : TRUE \\* Expression failed to evaluate.
671
- TLCError == CHOOSE s \\in STRING : TRUE \\* TLC error string.
672
- IN IF FailsEval(exp) THEN Assert(err = TLCError, TLCError) ELSE TRUE
673
-
674
- -----------------------------------------------------------------------------
675
-
676
- TLCGetOrDefault(key, defaultVal) ==
677
- CHOOSE n : TRUE
678
-
679
- TLCGetAndSet(key, Op(_,_), val, defaultVal) ==
680
- LET oldVal == TLCGetOrDefault(key, defaultVal)
681
- IN CHOOSE v \\in {oldVal} : TLCSet(key, Op(oldVal, val))
682
-
683
- -----------------------------------------------------------------------------
684
-
685
- (* HERE BE DRAGONS! The operators below are experimental! You will probably not need them! *)
686
-
687
- Trace ==
688
- (******************************************************************************)
689
- (* The sequence of states (represented as a record whose DOMAIN is the set of *)
690
- (* a spec's variables) from an initial state to the current state. In other *)
691
- (* words, a prefix - of a behavior - ending with the current state. A way to *)
692
- (* think about this operator is to see it as an implicit history variable *)
693
- (* that does not have to be explicitly specified at the level of the spec. *)
694
- (* *)
695
- (* Note that op is incompatible with TLC!RandomElement and Randomization (see *)
696
- (* tlc2.tool.TLCTrace.getTrace(LongVec)) and will cause TLC to crash. This *)
697
- (* technical limitation could be removed though. *)
698
- (* *)
699
- (* Beware that Trace is prohibitively expensive when evaluated as part of *)
700
- (* the next-state relation, invariants, properties, or any constraint in *)
701
- (* model-checking mode. Consider using a real history variable instead. *)
702
- (******************************************************************************)
703
- TRUE \\* TODO
704
-
705
- -----------------------------------------------------------------------------
706
-
707
- CounterExample ==
708
- (****************************************************************************)
709
- (* In the scope of POSTCONDITION, the operator CounterExample is equivalent *)
710
- (* to a (directed) graph represented as [state: States, action: Actions] *)
711
- (* with *)
712
- (* States \\subseteq [ Variables -> Values ] *)
713
- (* and *)
714
- (* Actions \\subseteq *)
715
- (* (CounterExample.state \\X Action \\X CounterExample.state). *)
716
- (* If TLC found no violations, then CounterExample.states equals {} and *)
717
- (* CounterExample.actions equals {}. If only initial state violates a *)
718
- (* (safety) property, CounterExample.state is a set of those states, and *)
719
- (* CounterExample.actions = {}. *)
720
- (****************************************************************************)
721
- TRUE
722
-
723
- ToTrace(CE) ==
724
- (*
725
- This definition is implemented by the TLCExt#toTrace Java module override. It
726
- is commented because FiniteSetsExt is part of the CommunityModules, but not
727
- tla2tools.
728
-
729
- LET F == INSTANCE FiniteSetsExt
730
- IN F!FoldSet(LAMBDA a, acc: acc @@ [n \\in {a[1]} |-> a[2]], [n \\in {} |-> n], CounterExample.state)
731
-
732
- *)
733
- TRUE
734
-
735
- -----------------------------------------------------------------------------
736
-
737
- TLCModelValue(str) ==
738
- (******************************************************************************)
739
- (* A model value is an unspecified value that TLC considers to be unequal to *)
740
- (* any value that you can express in TLA+. *)
741
- (* *)
742
- (* In most cases, TLC model values can and should be declared via the TLC *)
743
- (* config file. However, for large sets of model values, it can become *)
744
- (* tedious to enumerate them explicitly. Large sets of model values usually *)
745
- (* appear when simulating TLA+ specs with TLC. The following example defines *)
746
- (* a set of 32 model values: *)
747
- (* *)
748
- (* SetOfModelValues == {TLCModelValue("T_MV" \\o ToString(i)) : i \\in 1..32} *)
749
- (* *)
750
- (* As a matter of fact, the example defines a set of "typed" model values: *)
751
- (* TLC considers a typed model value to be unequal to any other model value *)
752
- (* of the same type. However, it produces an error when evaluating an *)
753
- (* expression requires it to determine if a typed model value is equal to any *)
754
- (* value other than a model value of the same type or an ordinary model *)
755
- (* value. *)
756
- (* *)
757
- (* A model-value type consists of a single letter, so there are 52 different *)
758
- (* types because a and A are different types. (TLC actually accepts *)
759
- (* digits and underscore as types; don't use them.) A model value has type *)
760
- (* T if and only if its name begins with the two characters T_ . *)
761
- (* *)
762
- (* TLCModelValue may only appear in constant definitions! Expect bogus *)
763
- (* behavior if TLCModelValue appears in the behavior spec, constraints, *)
764
- (* invariants, or properties. *)
765
- (******************************************************************************)
766
- CHOOSE v: ToString(v) = str
767
-
768
- TLCDefer(expression) ==
769
- (******************************************************************************)
770
- (* Defer evaluation of expression to some later time or never. *)
771
- (* *)
772
- (* For TLC's simulation mode, later is defined as the point of time when *)
773
- (* simulation has chosen a successor state to extend the prefix of the *)
774
- (* current behavior. *)
775
- (* *)
776
- (* A use case is TLCDefer(TLCSet(42, someVal)), which sets someVal only *)
777
- (* for the states of the behavior and not the set of all successor states *)
778
- (* of all states in the behavior. *)
779
- (******************************************************************************)
780
- TRUE
781
-
782
- -----------------------------------------------------------------------------
783
-
784
- TLCNoOp(val) ==
785
- (******************************************************************************)
786
- (* No-operation operator (does nothing). Only useful to debug TLC's *)
787
- (* evaluator that is written in Java: Insert TLCNoOp into the expression *)
788
- (* whose evaluation you wish to debug and set a breakpoint in this *)
789
- (* operator's Java module override TLCExt#tlcNoOp in TLCExt.java. *)
790
- (******************************************************************************)
791
- val
792
-
793
-
794
- PickSuccessor(exp) ==
795
- (******************************************************************************)
796
- (* When set as an action constraint in the configuration file, interactively *)
797
- (* pick successor states during state exploration, iff the expression exp *)
798
- (* evaluates to FALSE. To always pick successor states manually, use *)
799
- (* PickSuccessor(FALSE). To pick successor states when the current prefix of *)
800
- (* behaviors exceeds 22 states, use PickSuccessor(TLCGet("level") < 23). *)
801
- (* Evaluates to TRUE when evaluated in the context of a constant- or *)
802
- (* state-level formula. Also evaluates to TRUE if PickSuccessor appears as *)
803
- (* part of the next-state relation and the successor state has not been *)
804
- (* fully determined yet. *)
805
- (******************************************************************************)
806
- IF (exp)
807
- THEN TRUE
808
- ELSE CHOOSE bool \\in BOOLEAN : TRUE
809
-
810
- -----------------------------------------------------------------------------
811
-
812
- TLCCache(expression, closure) ==
813
- (******************************************************************************)
814
- (* Equals the value that an earlier evaluation of the expression evaluated to *)
815
- (* iff the closure of the earlier evaluation and this evaluation are equal. *)
816
- (* *)
817
- (* Works in constant and state-level contexts. *)
818
- (******************************************************************************)
819
- expression
820
-
821
- TLCFP(var) ==
822
- (******************************************************************************)
823
- (* Equals the value that TLC gives to the given input when the value is *)
824
- (* being fingerprinted. *)
825
- (* Implementation note: Equals the lower 32 bits until TLC supports longs *)
826
- (******************************************************************************)
827
- CHOOSE i \\in Int: TRUE
828
-
829
- -----------------------------------------------------------------------------
830
-
831
- TLCEvalDefinition(definitionName) ==
832
- (******************************************************************************)
833
- (* Equals the value of the definition with the given name. *)
834
- (* Throws an error if the definition cannot be found. *)
835
- (******************************************************************************)
836
- TRUE \\* TODO
837
-
838
- ============================================================================
839
- `],[`Toolbox`,`${e.j}\n`],[`_DotTrace`,`------------------------------- MODULE _DotTrace -------------------------------
840
- LOCAL INSTANCE TLC
841
- LOCAL INSTANCE TLCExt
842
- LOCAL INSTANCE GraphViz
843
- LOCAL INSTANCE IOUtils
844
- LOCAL INSTANCE Sequences
845
- LOCAL INSTANCE Functions
846
-
847
- CONSTANT _DotTraceFile
848
-
849
- _DotTrace ==
850
- IF CounterExample.state = {} \\/ ("console" \\in DOMAIN CounterExample /\\ CounterExample["console"] = FALSE) THEN TRUE ELSE
851
- /\\ LET N == CounterExample.state
852
- E == { <<e[1], e[3], e[2]>> : e \\in CounterExample.action }
853
- G == [node |-> N, edge |-> E] IN
854
- Serialize(DotDiGraph(G, LAMBDA v: FoldFunctionOnSet(
855
- LAMBDA x, y: ToString(x) \\o "\\n" \\o y, "", v[2], DOMAIN v[2]),
856
- LAMBDA e: e[3].name),
857
- _DotTraceFile,
858
- [
859
- format |-> "TXT",
860
- charset |-> "UTF-8",
861
- openOptions |-> <<"WRITE", "CREATE", "TRUNCATE_EXISTING">>
862
- ]
863
- ).exitValue = 0
864
- /\\ PrintT("CounterExample written: " \\o _DotTraceFile)
865
-
866
- =============================================================================
867
- `],[`_JsonTrace`,`------------------------------- MODULE _JsonTrace -------------------------------
868
- LOCAL INSTANCE TLC
869
- LOCAL INSTANCE TLCExt
870
- LOCAL INSTANCE Json
871
- LOCAL INSTANCE Sequences
872
- LOCAL INSTANCE Naturals
873
-
874
- CONSTANT _JsonTraceFile
875
-
876
- _JsonTrace ==
877
- IF CounterExample.state = {} \\/ ("console" \\in DOMAIN CounterExample /\\ CounterExample["console"] = FALSE) THEN TRUE ELSE
878
- /\\ LET trace == ToTrace(CounterExample)
879
- vars == UNION { DOMAIN trace[i] : i \\in DOMAIN trace }
880
- IN JsonSerialize(_JsonTraceFile, [counterexample |-> CounterExample, vars |-> vars])
881
- /\\ PrintT("CounterExample written: " \\o _JsonTraceFile)
882
-
883
- ----------------------------------------------------------------------------
884
- \\* Deserialize a trace created by _JsonTrace above.
885
-
886
- CONSTANT _JsonTraceInputFile \\* Used by -loadTrace json
887
-
888
- \\* This operator has a Java module override (tlc2.module._JsonTrace#tlcState).
889
- LOCAL _TLCState(level) ==
890
- Trace[level]
891
-
892
- LOCAL _JsonTraceDump == JsonDeserialize(_JsonTraceInputFile)
893
-
894
- \\* A liveness counterexample's action graph contains a closing edge that
895
- \\* completes the lasso. In a forward path s1->s2->...->sn every edge
896
- \\* satisfies target[1] > source[1]; the closing edge is the unique edge
897
- \\* where target[1] <= source[1] (back-to-state: <, stuttering: =).
898
- LOCAL _JsonTraceLassoTarget ==
899
- LET actions == _JsonTraceDump["counterexample"]["action"]
900
- IN IF \\E i \\in DOMAIN actions : actions[i][3][1] <= actions[i][1][1]
901
- THEN LET i == CHOOSE i \\in DOMAIN actions :
902
- actions[i][3][1] <= actions[i][1][1]
903
- IN actions[i][3][1]
904
- ELSE 0
905
-
906
- LOCAL _JsonTraceConstraint ==
907
- LET level == TLCGet("level")
908
- \\* DOMAIN trace is meaningful only because we serialize TLA+ sets as JSON arrays. JSON has
909
- \\* no set type---only the world's favorite least-common-denominator of strings, numbers,
910
- \\* and nested lists---so on the wire every set is an ordered sequence. If that encoding
911
- \\* ever changed (or JSON miraculously grew a real set type), indexing states by DOMAIN
912
- \\* would stop matching what we dump.
913
- \\* Rebuilding vars likewise assumes the array order matches TLC's normalized set order from
914
- \\* when the trace was written; the format does not pin down a stronger invariant.
915
- trace == _JsonTraceDump["counterexample"]["state"]
916
- \\* JSON deserializes sets as tuples, so convert back to a set
917
- vars == {_JsonTraceDump["vars"][i] : i \\in DOMAIN _JsonTraceDump["vars"]}
918
- \\* For liveness properties, TLC trace dumps stop at the state *before* the
919
- \\* lasso is closed. When replaying such a trace, TLC may request a state with
920
- \\* level = Len(trace) + 1,
921
- \\* which does not exist in the dump. In that case, the constraint
922
- \\* is intentionally vacuously satisfied.
923
- \\* Since the names of the spec's variables are not known, Trace[level] is
924
- \\* used as a generic reference to the variables of the current state.
925
- IN level \\in DOMAIN trace =>
926
- \\* When loading a trace with a subset of variables, only check the variables
927
- \\* that exist in both the trace and the current state. This allows trace
928
- \\* replay with specs that have different variable sets than the original spec
929
- \\* that produced the trace. Another scenario is when the spec uses ALIAS
930
- \\* to rename, add, or remove variables.
931
- \\A v \\in vars \\cap (DOMAIN _TLCState(level)):
932
- _TLCState(level)[v] = trace[level][2][v]
933
-
934
- \\* VIEW for trace replay. Includes TLCGet("level") to prevent premature
935
- \\* state collapsing within the trace. For liveness traces, the level
936
- \\* beyond the trace is mapped to the lasso target so the cycle can close.
937
- LOCAL _JsonTraceView ==
938
- LET level == TLCGet("level")
939
- traceLen == Len(_JsonTraceDump["counterexample"]["state"])
940
- lassoTarget == _JsonTraceLassoTarget
941
- IN IF level <= traceLen
942
- THEN << level, _TLCState(level) >>
943
- ELSE << lassoTarget, _TLCState(level) >>
944
-
945
- =============================================================================
946
- `],[`_Possible`,`------------------------------ MODULE _Possible ------------------------------
947
- LOCAL INSTANCE TLC
948
- LOCAL INSTANCE TLCExt
949
- LOCAL INSTANCE Naturals
950
- LOCAL INSTANCE Sequences
951
-
952
- LOCAL _Update(Op(_,_), val) ==
953
- TLCSet("s:_possible", Op(TLCGetOrDefault("s:_possible", <<>>), val))
954
-
955
- _Track(expr, name) ==
956
- _Update(LAMBDA old, b:
957
- IF b
958
- THEN
959
- IF name \\in DOMAIN old
960
- THEN [old EXCEPT ![name] = @ + 1]
961
- ELSE old @@ (name :> 1)
962
- ELSE old @@ (name :> 0), expr)
963
-
964
- LOCAL _Merge(a, b) ==
965
- [name \\in (DOMAIN a) \\cup (DOMAIN b) |->
966
- (IF name \\in DOMAIN a THEN a[name] ELSE 0) +
967
- (IF name \\in DOMAIN b THEN b[name] ELSE 0)]
968
-
969
- _Counts == \\* Java override for efficiency
970
- LET workers == TLCGet("all:named")["s:_possible"]
971
- n == Len(workers)
972
- Fold[i \\in 0..n] ==
973
- IF i = 0 THEN <<>>
974
- ELSE _Merge(Fold[i-1], workers[i])
975
- IN Fold[n]
976
-
977
- _CheckName(name) ==
978
- LET counts == _Counts
979
- IN (name \\notin DOMAIN counts \\/ counts[name] = 0)
980
- => (PrintT(counts) /\\ FALSE)
981
-
982
- _PrintCounts == PrintT(_Counts)
983
-
984
- =============================================================================
985
- `],[`_TLAPlusCounterExample`,`----------------------- MODULE _TLAPlusCounterExample ------------------------
986
- LOCAL INSTANCE IOUtils
987
- LOCAL INSTANCE TLC
988
- LOCAL INSTANCE TLCExt
989
- LOCAL INSTANCE Sequences
990
- LOCAL INSTANCE SequencesExt
991
-
992
- CONSTANT _TLAPlusCounterExampleFile
993
-
994
- LOCAL _TLAPlusCounterExampleModule ==
995
- LET ModuleName == ReplaceFirstSubSeq("", ".tla", _TLAPlusCounterExampleFile) IN
996
- "---- MODULE " \\o ModuleName \\o " ----\\n" \\o
997
- "LOCAL INSTANCE TLC\\n\\n" \\o
998
- "CounterExample == \\n\\t" \\o
999
- ToString(CounterExample) \\o
1000
- "\\n\\n===="
1001
-
1002
- _TLAPlusCounterExample ==
1003
- IF CounterExample.state = {} \\/ ("console" \\in DOMAIN CounterExample /\\ CounterExample["console"] = FALSE) THEN TRUE ELSE
1004
- /\\ Serialize(_TLAPlusCounterExampleModule,
1005
- _TLAPlusCounterExampleFile,
1006
- [
1007
- format |-> "TXT",
1008
- charset |-> "UTF-8",
1009
- openOptions |-> <<"WRITE", "CREATE", "TRUNCATE_EXISTING">>
1010
- ]
1011
- ).exitValue = 0
1012
- /\\ PrintT("CounterExample written: " \\o _TLAPlusCounterExampleFile)
1013
-
1014
- =============================================================================
1015
- `],[`_TLCActionTrace`,`------- MODULE _TLCActionTrace ------
1016
- LOCAL INSTANCE IOUtils
1017
- LOCAL INSTANCE TLC
1018
- LOCAL INSTANCE TLCExt
1019
- LOCAL INSTANCE Sequences
1020
- LOCAL INSTANCE SequencesExt
1021
- LOCAL INSTANCE FiniteSets
1022
- LOCAL INSTANCE FiniteSetsExt
1023
-
1024
- LOCAL _extends ==
1025
- LET M == FoldSet(LAMBDA a, acc: acc \\cup {a[2].location.module}, {}, CounterExample.action)
1026
- IN FoldSet(LAMBDA module, acc: acc \\o (IF acc = "" THEN "EXTENDS " ELSE ", ") \\o module, "", M)
1027
-
1028
- LOCAL _next ==
1029
- LET Params(r) == FoldLeft(LAMBDA acc, p: acc \\o (IF acc = "" THEN "" ELSE ", ") \\o ToString(r.context[p]),
1030
- "", r.parameters)
1031
- Signature(r) == IF "parameters" \\in DOMAIN r THEN r.name \\o "(" \\o Params(r) \\o ")" ELSE r.name
1032
- ToDisjunct(i, r) == "\\\\/ " \\o ToString(i) \\o " = _idx /\\\\ " \\o Signature(r) \\o "\\n"
1033
- IN FoldSet(LAMBDA a, acc: acc \\o ToDisjunct(a[1][1], a[2]), "", CounterExample.action)
1034
-
1035
- CONSTANT _TLCTraceFile
1036
-
1037
- LOCAL _TLCTraceModule ==
1038
- LET ModuleName == ReplaceFirstSubSeq("", ".tla", _TLCTraceFile)
1039
- L == ToString(Cardinality(CounterExample.action)) IN
1040
- "---- MODULE " \\o ModuleName \\o " ----\\n" \\o
1041
- \\*TODO callsignature symbols may not be defined in the same modules where the actions are defined.
1042
- \\*TODO E.g., model values are typically defined in the MC file.
1043
- _extends \\o "\\n\\n" \\o
1044
- "_length == " \\o L \\o "\\n\\n" \\o
1045
- "_next(_idx) ==\\n" \\o _next \\o "\\n" \\o
1046
- "_actionConstraint ==\\n" \\o
1047
- "_next(LET T == INSTANCE TLC IN T!TLCGet(\\"level\\"))\\n" \\o
1048
- "\\n===="
1049
-
1050
- _TLCTrace ==
1051
- IF CounterExample.action = {} \\/ ("console" \\in DOMAIN CounterExample /\\ CounterExample["console"] = FALSE) THEN TRUE ELSE
1052
- /\\ Serialize(_TLCTraceModule,
1053
- _TLCTraceFile,
1054
- [
1055
- format |-> "TXT",
1056
- charset |-> "UTF-8",
1057
- openOptions |-> <<"WRITE", "CREATE", "TRUNCATE_EXISTING">>
1058
- ]
1059
- ).exitValue = 0
1060
- /\\ PrintT("CounterExample written: " \\o _TLCTraceFile)
1061
-
1062
- ======`],[`_TLCTESpec`,`----------------------- MODULE _TLCTESpec ------------------------
1063
- LOCAL INSTANCE IOUtils
1064
- LOCAL INSTANCE TLC
1065
- LOCAL INSTANCE TLCExt
1066
- LOCAL INSTANCE Sequences
1067
- LOCAL INSTANCE SequencesExt
1068
- LOCAL INSTANCE FiniteSets
1069
- LOCAL INSTANCE FiniteSetsExt
1070
-
1071
- LOCAL _extends ==
1072
- LET M == FoldSet(LAMBDA a, acc: acc \\cup {a[2].location.module}, {}, CounterExample.action)
1073
- IN FoldSet(LAMBDA module, acc: acc \\o (IF acc = "" THEN "EXTENDS " ELSE ", ") \\o module, "", M)
1074
-
1075
- LOCAL _Vars ==
1076
- UNION { DOMAIN pair[2] : pair \\in CounterExample.state }
1077
-
1078
- LOCAL _ToConjunt(v, prime, idx) ==
1079
- "/\\\\ " \\o v \\o prime \\o " = Trace[" \\o idx \\o "]." \\o v \\o "\\n"
1080
-
1081
- CONSTANT _TLCTraceFile
1082
-
1083
- LOCAL _conjunct(prime, idx) ==
1084
- FoldSet(LAMBDA v, acc: acc \\o _ToConjunt(v, prime, idx), "", _Vars)
1085
-
1086
- LOCAL _subVars ==
1087
- FoldSet(LAMBDA v, acc: acc \\o (IF acc = "" THEN "" ELSE ", ") \\o v, "", _Vars)
1088
-
1089
- LOCAL _TLCTraceModule ==
1090
- LET ModuleName == ReplaceFirstSubSeq("", ".tla", _TLCTraceFile) IN
1091
- "---- MODULE " \\o ModuleName \\o " ----\\n" \\o
1092
- \\*TODO E.g., model values are typically defined in the MC file.
1093
- _extends \\o "\\n\\n" \\o
1094
- "LOCAL INSTANCE TLC\\n\\n" \\o
1095
- "Trace == \\n\\t" \\o
1096
- ToString(ToTrace(CounterExample)) \\o
1097
- "\\n\\n" \\o
1098
- "_init ==\\n" \\o _conjunct("", "1") \\o
1099
- "\\n" \\o
1100
- "_next ==\\n\\\\E i,j \\\\in DOMAIN Trace:\\n/\\\\ i = TLCGet(\\"level\\")\\n/\\\\ j = i + 1\\n" \\o
1101
- _conjunct("", "i") \\o _conjunct("'", "j") \\o
1102
- "\\n(* Allow infinite stuttering to prevent deadlock on termination. *)" \\o
1103
- "\\n_terminating ==\\n\\tUNCHANGED <<" \\o _subVars \\o ">>" \\o
1104
- "\\n\\n_spec == \\n\\t_init /\\\\ [][_next \\\\/ _terminating]_<<" \\o _subVars \\o ">>\\n" \\o
1105
- "\\n===="
1106
- \\* TODO: Append in-file config here.
1107
-
1108
- _TLCTrace ==
1109
- IF CounterExample.state = {} \\/ ("console" \\in DOMAIN CounterExample /\\ CounterExample["console"] = FALSE) THEN TRUE ELSE
1110
- /\\ Serialize(_TLCTraceModule,
1111
- _TLCTraceFile,
1112
- [
1113
- format |-> "TXT",
1114
- charset |-> "UTF-8",
1115
- openOptions |-> <<"WRITE", "CREATE", "TRUNCATE_EXISTING">>
1116
- ]
1117
- ).exitValue = 0
1118
- /\\ PrintT("CounterExample written: " \\o _TLCTraceFile)
1119
-
1120
- =============================================================================
1121
- `],[`_TLCTrace`,`---------------------------- MODULE _TLCTrace ----------------------------
1122
- LOCAL INSTANCE TLC
1123
- LOCAL INSTANCE TLCExt
1124
- LOCAL INSTANCE Sequences
1125
- LOCAL INSTANCE Naturals
1126
-
1127
- \\* This operator has a Java module override (tlc2.module._TLCTrace#ioDeserialize).
1128
- LOCAL _TLCTraceDeserialize(absoluteFilename) ==
1129
- TRUE
1130
-
1131
- \\* This operator has a Java module override (tlc2.module._TLCTrace#ioSerialize).
1132
- LOCAL _TLCTraceSerialize(val, absoluteFilename) ==
1133
- TRUE
1134
-
1135
- ----------------------------------------------------------------------------
1136
- \\* Serialize a trace to a file.
1137
-
1138
- CONSTANT _TLCTraceFile
1139
-
1140
- LOCAL _TLCTrace0(verbose) ==
1141
- IF CounterExample.state = {} \\/ ("console" \\in DOMAIN CounterExample /\\ CounterExample["console"] = FALSE) THEN TRUE ELSE
1142
- /\\ LET trace == ToTrace(CounterExample)
1143
- vars == UNION { DOMAIN trace[i] : i \\in DOMAIN trace }
1144
- IN _TLCTraceSerialize([counterexample |-> CounterExample, vars |-> vars], _TLCTraceFile)
1145
- /\\ IF verbose THEN PrintT("CounterExample written: " \\o _TLCTraceFile) ELSE TRUE
1146
-
1147
- LOCAL _TLCTraceSilent ==
1148
- _TLCTrace0(FALSE)
1149
-
1150
- _TLCTrace ==
1151
- _TLCTrace0(TRUE)
1152
-
1153
- ----------------------------------------------------------------------------
1154
- \\* Deserialize a trace created by _TLCTrace above.
1155
-
1156
- CONSTANT _TLCTraceInputFile \\* Used by -loadTrace tlc
1157
-
1158
- LOCAL _TLCTraceFileDeserialized ==
1159
- _TLCTraceDeserialize(_TLCTraceInputFile)
1160
-
1161
- \\* This operator has a Java module override (tlc2.module._TLCTrace#tlcState).
1162
- LOCAL _TLCState(level) ==
1163
- Trace[level]
1164
-
1165
- \\* A liveness counterexample's action graph contains a closing edge that
1166
- \\* completes the lasso. In a forward path s1->s2->...->sn every edge
1167
- \\* satisfies target[1] > source[1]; the closing edge is the unique edge
1168
- \\* where target[1] <= source[1] (back-to-state: <, stuttering: =).
1169
- LOCAL _TLCTraceLassoTarget ==
1170
- LET actions == _TLCTraceFileDeserialized["counterexample"]["action"]
1171
- IN IF \\E e \\in actions : e[3][1] <= e[1][1]
1172
- THEN (CHOOSE e \\in actions : e[3][1] <= e[1][1])[3][1]
1173
- ELSE 0
1174
-
1175
- LOCAL _TLCTraceConstraint ==
1176
- LET level == TLCGet("level")
1177
- dump == _TLCTraceFileDeserialized
1178
- trace == dump["counterexample"]["state"]
1179
- vars == dump["vars"]
1180
- \\* The trace (CounterExample.state) is a set of <<level, state>> pairs,
1181
- \\* not a function/sequence.
1182
- \\* For liveness properties, TLC trace dumps stop at the state *before* the
1183
- \\* lasso is closed. When replaying such a trace, TLC may request a state with
1184
- \\* a level that does not exist in the dump. In that case, no pair matches and
1185
- \\* the implication is vacuously satisfied.
1186
- IN \\A pair \\in trace:
1187
- pair[1] = level =>
1188
- \\* When loading a trace with a subset of variables, only check the
1189
- \\* variables that exist in both the trace and the current state.
1190
- \\* This allows trace replay with specs that have different variable
1191
- \\* sets than the original spec that produced the trace. Another
1192
- \\* scenario is when the spec uses ALIAS to rename, add, or remove
1193
- \\* variables.
1194
- \\A v \\in vars \\cap DOMAIN _TLCState(level):
1195
- _TLCState(level)[v] = pair[2][v]
1196
-
1197
- \\* VIEW for trace replay. Includes TLCGet("level") to prevent premature
1198
- \\* state collapsing within the trace. For liveness traces, the level
1199
- \\* beyond the trace is mapped to the lasso target so the cycle can close.
1200
- LOCAL _TLCTraceView ==
1201
- LET level == TLCGet("level")
1202
- trace == _TLCTraceFileDeserialized["counterexample"]["state"]
1203
- lassoTarget == _TLCTraceLassoTarget
1204
- IN IF \\E pair \\in trace : pair[1] = level
1205
- THEN << level, _TLCState(level) >>
1206
- ELSE << lassoTarget, _TLCState(level) >>
1207
-
1208
- =============================================================================
1209
- `],[`_TLCTracePlain`,`----------------------- MODULE _TLCTracePlain ------------------------
1210
- LOCAL INSTANCE IOUtils
1211
- LOCAL INSTANCE TLC
1212
- LOCAL INSTANCE TLCExt
1213
- LOCAL INSTANCE Sequences
1214
- LOCAL INSTANCE SequencesExt
1215
-
1216
- CONSTANT _TLCTraceFile
1217
-
1218
- LOCAL _TLCTraceModule ==
1219
- LET ModuleName == ReplaceFirstSubSeq("", ".tla", _TLCTraceFile) IN
1220
- "---- MODULE " \\o ModuleName \\o " ----\\n" \\o
1221
- "LOCAL INSTANCE TLC\\n\\n" \\o
1222
- "Trace == \\n\\t" \\o
1223
- ToString(ToTrace(CounterExample)) \\o
1224
- "\\n\\n===="
1225
-
1226
- _TLCTrace ==
1227
- IF CounterExample.state = {} \\/ ("console" \\in DOMAIN CounterExample /\\ CounterExample["console"] = FALSE) THEN TRUE ELSE
1228
- /\\ Serialize(_TLCTraceModule,
1229
- _TLCTraceFile,
1230
- [
1231
- format |-> "TXT",
1232
- charset |-> "UTF-8",
1233
- openOptions |-> <<"WRITE", "CREATE", "TRUNCATE_EXISTING">>
1234
- ]
1235
- ).exitValue = 0
1236
- /\\ PrintT("CounterExample written: " \\o _TLCTraceFile)
1237
-
1238
- =============================================================================
1239
- `]]),pi=new Map([...[...fi].filter(([e])=>[`FiniteSets`,`Integers`,`Naturals`,`RealTime`,`Reals`,`Sequences`,`TLC`].includes(e)),[`Bags`,di.replace(`
1240
- LOCAL INSTANCE Naturals
1241
- `,`
1242
- EXTENDS TLC
1243
- LOCAL INSTANCE Naturals
1244
- `)],[`Randomization`,`-------------------------- MODULE Randomization------------------------------
1245
- (***************************************************************************)
1246
- (* This module defines operators for choosing pseudo-random subsets of a *)
1247
- (* set. It is useful for inductive invariance checking, where the *)
1248
- (* operators appear only in the initial predicate. However, it may have *)
1249
- (* other uses. *)
1250
- (* *)
1251
- (* In breadth-first search model checking, the pseudo-random choices made *)
1252
- (* when computing possible steps satisfying the next-state relation are *)
1253
- (* determined by the first state of the step. Thus, the choices made for *)
1254
- (* a particular state will be the same in successive runs of TLC. This is *)
1255
- (* done to permit TLC to generate an error trace if an error is found. *)
1256
- (* This applies only when TLC is run in breadth-first search mode. In *)
1257
- (* particular, the choices made in simulation mode are independent of the *)
1258
- (* state for which they are made. *)
1259
- (***************************************************************************)
1260
-
1261
- (***************************************************************************)
1262
- (* Except for TestRandomSetOfSubsets, all these definitions are overridden *)
1263
- (* by TLC in the Java class tlc2.module.Randomization. Each operator is *)
1264
- (* overridden by the Java method with the same name. *)
1265
- (***************************************************************************)
1266
- LOCAL INSTANCE Naturals
1267
- LOCAL INSTANCE FiniteSets
1268
-
1269
- (***************************************************************************)
1270
- (* RandomSubset(k, S) equals a randomly chosen subset of S containing k *)
1271
- (* elements, where 0 < k < Cardinality(S). *)
1272
- (***************************************************************************)
1273
- RandomSubset(k, S) == CHOOSE T \\in SUBSET S : Cardinality(T) = T
1274
-
1275
- (***************************************************************************)
1276
- (* RandomSetOfSubsets(k, n, S) equals a pseudo-randomly chosen set of *)
1277
- (* subsets of S -- that is, a randomly chosen subset of SUBSET S . Thus, *)
1278
- (* each element T of this set is a subset of S. Each such T is chosen so *)
1279
- (* that each element of S has a probability n / Cardinality(S) of being in *)
1280
- (* T. Thus, the average number of elements in each chosen subset T is n. *)
1281
- (* The set RandomSetOfSubsets(k, n, S) is obtained by making k such *)
1282
- (* choices of T . Because this can produce duplicate choices, the number *)
1283
- (* of elements T in this set may be less than k. The average number of *)
1284
- (* elements in RandomSetOfSubsets(k, n, S) seems to be difficult to *)
1285
- (* compute in general. However, there is very little variation in the *)
1286
- (* actual number of elements in the chosen set for fixed values of k, n, *)
1287
- (* and Cardinality(S). You can therefore use the operator *)
1288
- (* TestRandomSetOfSubsets defined below to find out approximately how *)
1289
- (* close to k the cardinality of the chosen set of subsets is. *)
1290
- (***************************************************************************)
1291
- RandomSetOfSubsets(k, n, S) == CHOOSE T \\in SUBSET SUBSET S :
1292
- Cardinality(T) \\leq k
1293
-
1294
- (***************************************************************************)
1295
- (* The value of TestRandomSetOfSubsets(k, n, S) is a sequence of five *)
1296
- (* values that are the cardinality of the set of subsets produced by five *)
1297
- (* executions of RandomSetOfSubsets(k, n, S). For constant values of k, *)
1298
- (* n, and S, you can enter TestRandomSetOfSubsets(k, n, S) in the Evaluate *)
1299
- (* Constant Expression section of a TLC model in the TLA+ Toolbox. *)
1300
- (* Running TLC will then tell you the approximate number of elements in *)
1301
- (* the set of subsets produced by RandomSetOfSubsets for these parameters. *)
1302
- (* You can then choose k to obtain a set of the desired size. *)
1303
- (***************************************************************************)
1304
- TestRandomSetOfSubsets(k, n, S) ==
1305
- [i \\in 1..5 |-> Cardinality(RandomSetOfSubsets(k, n, S))]
1306
-
1307
- =============================================================================
1308
- `],[`Toolbox`,`----------------------------- MODULE Toolbox --------------------------------
1309
- (***************************************************************************)
1310
- (* *)
1311
- (***************************************************************************)
1312
- LOCAL INSTANCE Naturals \\* a + b
1313
- LOCAL INSTANCE FiniteSets \\* Cardinality
1314
- LOCAL INSTANCE TLC \\* TLCGet
1315
-
1316
- -----------------------------------------------------------------------------
1317
-
1318
- (* Trace Exploration *)
1319
-
1320
- _TETrace ==
1321
- CHOOSE f \\in [ (Nat \\ {0}) -> STRING ] : TRUE
1322
-
1323
- LOCAL _TETraceLength == Cardinality(DOMAIN _TETrace)
1324
-
1325
- _TEPosition ==
1326
- IF TLCGet("level") >= _TETraceLength
1327
- THEN _TETraceLength
1328
- ELSE TLCGet("level") + 1
1329
-
1330
- =============================================================================
1331
- `]]),mi=(e=`master`)=>e===`1.7.4`?pi:fi,hi={builtin:1,number:2,string:3,ident:4,added:5},gi=()=>({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}),_i=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)},vi=[`unfair`,`wf`,`sf`],U=()=>({col:0,line:0,macroCol:0,macroLine:-1,lbl:``}),yi=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}`,bi=t=>{if(t.kind!==`LabeledStmt`)throw new e.it(`ClassCastException: ${t.kind}`);return t},xi=(t,n)=>{if(n<0||n>=t.length)throw new e.it(`ArrayIndexOutOfBoundsException: ${n}`);return t[n]},Si=(e,t,n)=>({string:e,column:t,type:n}),Ci=e=>e.type===hi.string?e.string.length+2:e.string.length,wi=(e=[])=>({tokens:e,anchorTokens:void 0,anchorTokCol:void 0}),Ti=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},Ei=e=>{let t=wi(e);return Ti(t),t},Di=t=>{let n=t.anchorTokens,r=t.anchorTokCol;if(n===void 0||r===void 0)throw new e.it(`NullPointerException: TLAExpr.renormalize`);t.tokens.forEach((t,i)=>{let a=n[i];if(a===void 0)return;let o=a.column-r[i];if(r[i]=a.column,o<0)throw new e.rt(`TLAExpr.renormalize() found anchor has moved to left.`);t.forEach(e=>{e.column+=o})})},Oi=e=>Ei(e.tokens.map(e=>e.map(e=>({...e})))),ki=(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+Ci(o)+n;a.forEach(e=>{e.column+=s}),a.splice(0,0,...i);let c=[...t.anchorTokens??[]],l=[...t.anchorTokCol??[]];for(let t=r;t<e.tokens.length;t++)c.push(e.anchorTokens?.[t-r+1]),l.push(e.anchorTokCol?.[t-r+1]??0);e.anchorTokens=c,e.anchorTokCol=l,Di(e)},Ai=e=>e.tokens.length===1&&e.tokens[0].length===1,ji=(e,t)=>xi(xi(e.tokens,t.line),t.item),Mi=(t,n,r)=>{if(t.tokens.length<=n.line)throw new e.nt(`TLAExpr.StepCoord called with line too big`);if(t.tokens[n.line].length<=n.item)throw new e.nt(`TLAExpr.StepCoord called with col too big`);let i={line:n.line,item:n.item};for(let e=0;e<r;e++)if(i.item+=1,t.tokens[i.line].length===i.item){for(i.item=0,i.line+=1;i.line<t.tokens.length&&t.tokens[i.line].length===0;)i.line+=1;if(i.line===t.tokens.length)return}return i},Ni=(e,t,n)=>{for(let r=e.tokens.length===0?void 0:{...n};r!==void 0;){let n=ji(e,r),i=n.type===hi.string;if(!i&&n.string===t)return r;let a=!i&&(n.string===`[`||n.string===`,`)?Mi(e,r,2):void 0,o=a===void 0?void 0:ji(e,a),s=o!==void 0&&o.type!==hi.string&&[`:`,`|->`,`↦`].includes(o.string),c=i?1:n.string===`.`?2:s?3:1;r=Mi(e,r,c)}},Pi=(e,t,n,r)=>{let i=ji(e,n);if(Ai(e)){let n=Oi(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+Ci(i)):0,s=a.splice(n.item+1),c={lineIndex:n.line,indent:+!!r+i.column,isInserting:!r},l=()=>e.tokens[c.lineIndex];if(Ai(t)){let e=t.tokens[0][0];i.string=e.string,i.type=e.type}else{r&&(i.string=`(`,i.type=hi.builtin);let n=Oi(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(Si(`)`,e.column+Ci(e),hi.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+Ci(e)+o-s[0].column;s.forEach(e=>{e.column+=t,u.push(e)})}return Di(e),Mi(e,d,1)},Fi=(t,n,r,i=!0)=>{let a=r.map(e=>Ni(t,e,{line:0,item:0}));for(;;){let o=a.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(o===void 0)return;let s=Mi(t,o.position,1),c=Pi(t,n[o.index],o.position,i);a[o.index]=c===void 0?void 0:Ni(t,r[o.index],c),a.forEach((t,n)=>{if(n!==o.index&&t!==void 0&&c!==void 0){if(s===void 0)throw new e.it(`NullPointerException: TLAExpr.substituteForAll`);t.line===o.position.line&&(t.item+=c.item-s.item),t.line+=c.line-s.line}})}},Ii=(e,t,n)=>{let r=Oi(e);return Fi(r,t,n),r},Li=(e,t,n)=>e.map(e=>Ii(e,t,n)),Ri=(e,t)=>{let n=e=>t===`1.7.4`?``:`(col${e.column}) `,r=e.tokens.map(e=>e.map(e=>e.type===hi.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(`
1332
- `)} >>`},zi=(e,t,n)=>{let r=e=>Ri(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 |-> "${vi[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)},Bi=(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}),Vi=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]),`
1333
- `;let t=e.currentLine[e.column];return e.column+=1,e.vcolumn+=1,t===` `?(e.vcolumn%8!=0&&(e.isTabToSpaces=!0),` `):t},Hi=t=>{if(t.column>0){--t.column,--t.vcolumn;return}if(t.line===0)throw new e.nt(`PcalCharReader.backspace trying to move past beginning of reader`);--t.line;let n=Array.from(t.lines[t.line]);for(t.currentLine=n,t.column=0,t.vcolumn=0;t.column<n.length-1;)Vi(t)},Ui=e=>{for(;;){let t=Vi(e);if(t===` `)return` `;if(t!==` `&&t!==`
1334
- `)break}return Hi(e),`${(e.currentLine??[]).slice(e.column).join(``)}\n`},Wi=/* @__PURE__ */ new Set([`(`,`[`,`{`,`<<`,`⟨`]),Gi=/* @__PURE__ */ new Set([`>>_`,`⟩_`,`]_`,`)`,`}`,`]`,`>>`,`⟩`]),Ki=/* @__PURE__ */ new Set([...Wi,...Gi,...`_ 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(` `)]),qi=e=>/^[A-Za-z_]$/.test(e),Ji=e=>/^[0-9]$/.test(e),Yi=e=>e===` `||e===`\f`||e===`\r`,Xi=new Set([...Ki].filter(e=>!qi(e[0])&&!(e[0]===`\\`&&qi(e[1]??``))).flatMap(e=>Array.from(e,(t,n)=>e.slice(0,e.length-n)))),Zi=/* @__PURE__ */ new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ~!@#$%^&*()_-+={}[]|:;<,>.?/`'0123456789"),Qi=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(` `)),$i={...hi,dashes:6,endModule:7},ea=()=>({delimiter:``,delimiterLine:0,delimiterCol:0,commentDepth:0}),ta=(t,n,r,i)=>{let a={lines:[],line:[],token:``,state:`start`,column:n.vcolumn,nextColumn:n.vcolumn,nextChar:Vi(n),parenDepth:0,isInQuantifier:!1,isExprEnd:!1,previousToken:` `},o=()=>{a.nextColumn=n.vcolumn,a.nextChar=Vi(n)},s=()=>{a.token+=a.nextChar,o()},c=()=>{a.state=`start`,a.column=a.nextColumn},l=()=>{a.lines.push(a.line),a.line=[],a.column=0},u=t=>{throw new e.rt(`${t} \`${a.token}' found at\n line ${n.line+1}, column ${a.column+1}`)},d=()=>{a.isExprEnd=!0,t.delimiter=a.token,t.delimiterCol=a.column,t.delimiterLine=n.line-+(a.nextChar===`
1335
- `)},f=e=>{if(!r){d(),a.token=``;return}e>$i.ident&&u(`Illegal token in an expression`);let t=a.token;e!==$i.string&&(Qi.has(t)&&!(e===$i.ident&&[`.`,`[`,`,`].includes(a.previousToken))||(t===`,`&&!a.isInQuantifier&&!i||t===`)`||t===`}`)&&a.parenDepth===0)?(a.parenDepth!==0&&u(`Expression with an unmatched (, [, {, or << followed by`),a.isInQuantifier&&u("Expression with \\A or \\E but no following `:` followed by"),d(),a.line.length>0&&l()):(e===$i.builtin&&Wi.has(t)&&(a.parenDepth+=1),e===$i.builtin&&Gi.has(t)&&(--a.parenDepth,a.parenDepth<0&&u(`Extra (unmatching)`)),a.previousToken=e===$i.string?` `:t,[`\\A`,`∀`,`\\E`,`∃`].includes(t)&&a.parenDepth===0&&(a.isInQuantifier=!0),a.isInQuantifier&&t===`:`&&a.parenDepth===0&&(a.isInQuantifier=!1),(t!==``||e===$i.string)&&a.line.push(Si(t,a.column,e)),a.token=``)},p=e=>{f(e),c()},m=e=>{s(),a.state=e},h=e=>{o(),a.state=e},g=r=>{switch(a.state){case`start`:if(Yi(r))return o(),c();if(qi(r))return m(`id`);if(r===`ℕ`||r===`ℤ`||r===`ℝ`)return s(),p($i.ident);if(Ji(r))return m(`numOrId`);if(r===`\\`)return m(`bs`);if(r===`-`)return m(`dash1`);if(r===`=`)return m(`eq1`);if(r===`(`)return h(`leftParen`);if(r===`"`)return h(`string`);if(r===`
1336
- `)return o(),l(),c();if(Xi.has(r))return m(`builtIn`);if(r===` `){a.state=`done`;return}return s(),u(`Illegal lexeme`);case`id`:return a.token===`WF_`||a.token===`SF_`?p($i.builtin):qi(r)||Ji(r)?s():p(Ki.has(a.token)?$i.builtin:$i.ident);case`numOrId`:return Ji(r)?s():qi(r)?m(`id`):p($i.number);case`bs`:if([`b`,`B`,`o`,`O`,`h`,`H`].includes(r))return m(`numOrBi`);if(qi(r)){a.state=`bsBuiltIn`;return}if(r===`*`){o(),a.token=``,a.state=`lineComment`;return}a.state=`builtIn`;return;case`numOrBi`:a.state=Ji(r)?`num`:`bsBuiltIn`;return;case`num`:if(Ji(r))return s();if(!qi(r))return p($i.number);s(),a.token.startsWith(`\\`)&&u(`Illegal lexeme`),a.state=`id`;return;case`bsBuiltIn`:return qi(r)&&r!==`_`?s():Ki.has(a.token)?p($i.builtin):u(`Illegal lexeme `);case`builtIn`:if(Xi.has(a.token+r))return s();if(!Ki.has(a.token)){for(Hi(n);!Ki.has(a.token);)Hi(n),a.token.length===0&&u(`Illegal lexeme`),a.token=Array.from(a.token).slice(0,-1).join(``);o()}return p($i.builtin);case`dash1`:case`dash2`:if(r===`-`)return m(a.state===`dash1`?`dash2`:`dash3`);a.state=`builtIn`;return;case`dash3`:return r!==`-`&&u(`Illegal lexeme`),m(`dashes`);case`dashes`:return r===`-`?s():p($i.dashes);case`eq1`:case`eq2`:if(r===`=`)return m(a.state===`eq1`?`eq2`:`eq3`);a.state=`builtIn`;return;case`eq3`:return r!==`=`&&u(`Illegal lexeme`),m(`eqs`);case`eqs`:return r===`=`?s():p($i.endModule);case`leftParen`:if(r===`*`)return t.commentDepth=1,h(`comment`);a.token=`(`,a.state=`builtIn`;return;case`string`:if(r===`\\`)return m(`escString`);if(r===`"`)return o(),p($i.string);s(),Zi.has(r)||u(`Illegal character in string`);return;case`escString`:s(),[`"`,`\\`,`t`,`n`,`f`,`r`].includes(r)||u(`Illegal character following \\ in string`),a.state=`string`;return;case`lineComment`:return r===`(`?h(`lineComParen`):r===`*`&&t.commentDepth>0?h(`lineComStar`):r===`
26
+ `),isImportant:!0};s.set(t.name,t)});let c=[...s.values()].sort((e,t)=>ir(e.name,t.name)),l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Set;for(let e=0;e<c.length;e++){let t=nr(c[e]);t.submodules.forEach((e,t)=>{u.add(t),s.has(t)||s.set(t,e)});for(let e of t.dependencies){if(s.has(e)&&!Xn.has(e))continue;let r=n(e);if(!r){!s.has(e)&&!l.has(e)&&l.set(e,t.locations.get(e));continue}let i=ai(r,o,!1,a,h(t.locations.get(e)));s.set(e,i),c.push(i)}}let d=[...l.keys()].filter(e=>!u.has(e)).sort(ir);if(d.forEach(e=>a(g(l.get(e),`Unknown module ${JSON.stringify(e)}`))),d.length>0)throw new e.ut(`Unknown module ${JSON.stringify(d[0])}`,{failure:`Module.Parser.load_module`});let f={anonymizer:Ue(o,(e,t)=>yr(f,e,t),a),generator:hn(o,new Set(t.map(e=>e.file)),i,a),salts:{value:0},latestModules:/* @__PURE__ */ new Map,onWarning:a},p=oi(s).map(e=>e.isStandard?e:tr(s,e,/* @__PURE__ */ new Set)),m=new Map(p.map(e=>[e.name,e]));return p.flatMap(e=>{if(e.isStandard)return[];let t=br(f,m,void 0,e);if(!e.isImportant)return[];let n=xr(f,[],t),r=n.obligations.flatMap((e,t)=>{let n=e.location;if(e.kind.kind===`Omitted`||n&&(n.startLine<i.start||n.endLine>i.end))return[];let r=e.kind.kind===`Error`?e.kind.message:`${Ut(e.sequent)}\n`;return[{id:t+1,location:ei(n),text:r}]});return[{name:e.name,location:e.location,obligations:r,summary:n.summary}]})},di={builtin:1,number:2,string:3,ident:4,added:5},fi=()=>({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}),pi=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)},mi=[`unfair`,`wf`,`sf`],U=()=>({col:0,line:0,macroCol:0,macroLine:-1,lbl:``}),hi=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}`,gi=t=>{if(t.kind!==`LabeledStmt`)throw new e.it(`ClassCastException: ${t.kind}`);return t},_i=(t,n)=>{if(n<0||n>=t.length)throw new e.it(`ArrayIndexOutOfBoundsException: ${n}`);return t[n]},vi=(e,t,n)=>({string:e,column:t,type:n}),yi=e=>e.type===di.string?e.string.length+2:e.string.length,bi=(e=[])=>({tokens:e,anchorTokens:void 0,anchorTokCol:void 0}),xi=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},Si=e=>{let t=bi(e);return xi(t),t},Ci=t=>{let n=t.anchorTokens,r=t.anchorTokCol;if(n===void 0||r===void 0)throw new e.it(`NullPointerException: TLAExpr.renormalize`);t.tokens.forEach((t,i)=>{let a=n[i];if(a===void 0)return;let o=a.column-r[i];if(r[i]=a.column,o<0)throw new e.rt(`TLAExpr.renormalize() found anchor has moved to left.`);t.forEach(e=>{e.column+=o})})},wi=e=>Si(e.tokens.map(e=>e.map(e=>({...e})))),Ti=(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+yi(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,Ci(e)},Ei=e=>e.tokens.length===1&&e.tokens[0].length===1,Di=(e,t)=>_i(_i(e.tokens,t.line),t.item),Oi=(t,n,r)=>{if(t.tokens.length<=n.line)throw new e.nt(`TLAExpr.StepCoord called with line too big`);if(t.tokens[n.line].length<=n.item)throw new e.nt(`TLAExpr.StepCoord called with col too big`);let i={line:n.line,item:n.item};for(let e=0;e<r;e++)if(i.item+=1,t.tokens[i.line].length===i.item){for(i.item=0,i.line+=1;i.line<t.tokens.length&&t.tokens[i.line].length===0;)i.line+=1;if(i.line===t.tokens.length)return}return i},ki=(e,t,n)=>{for(let r=e.tokens.length===0?void 0:{...n};r!==void 0;){let n=Di(e,r),i=n.type===di.string;if(!i&&n.string===t)return r;let a=!i&&(n.string===`[`||n.string===`,`)?Oi(e,r,2):void 0,o=a===void 0?void 0:Di(e,a),s=o!==void 0&&o.type!==di.string&&[`:`,`|->`,`↦`].includes(o.string),c=i?1:n.string===`.`?2:s?3:1;r=Oi(e,r,c)}},Ai=(e,t,n,r)=>{let i=Di(e,n);if(Ei(e)){let n=wi(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+yi(i)):0,s=a.splice(n.item+1),c={lineIndex:n.line,indent:+!!r+i.column,isInserting:!r},l=()=>e.tokens[c.lineIndex];if(Ei(t)){let e=t.tokens[0][0];i.string=e.string,i.type=e.type}else{r&&(i.string=`(`,i.type=di.builtin);let n=wi(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(vi(`)`,e.column+yi(e),di.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+yi(e)+o-s[0].column;s.forEach(e=>{e.column+=t,u.push(e)})}return Ci(e),Oi(e,d,1)},ji=(t,n,r,i=!0)=>{let a=r.map(e=>ki(t,e,{line:0,item:0}));for(;;){let o=a.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(o===void 0)return;let s=Oi(t,o.position,1),c=Ai(t,n[o.index],o.position,i);a[o.index]=c===void 0?void 0:ki(t,r[o.index],c),a.forEach((t,n)=>{if(n!==o.index&&t!==void 0&&c!==void 0){if(s===void 0)throw new e.it(`NullPointerException: TLAExpr.substituteForAll`);t.line===o.position.line&&(t.item+=c.item-s.item),t.line+=c.line-s.line}})}},Mi=(e,t,n)=>{let r=wi(e);return ji(r,t,n),r},Ni=(e,t,n)=>e.map(e=>Mi(e,t,n)),Pi=(e,t)=>{let n=e=>t===`1.7.4`?``:`(col${e.column}) `,r=e.tokens.map(e=>e.map(e=>e.type===di.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(`
27
+ `)} >>`},Fi=(e,t,n)=>{let r=e=>Pi(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 |-> "${mi[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)},Ii=(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}),Li=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]),`
28
+ `;let t=e.currentLine[e.column];return e.column+=1,e.vcolumn+=1,t===` `?(e.vcolumn%8!=0&&(e.isTabToSpaces=!0),` `):t},Ri=t=>{if(t.column>0){--t.column,--t.vcolumn;return}if(t.line===0)throw new e.nt(`PcalCharReader.backspace trying to move past beginning of reader`);--t.line;let n=Array.from(t.lines[t.line]);for(t.currentLine=n,t.column=0,t.vcolumn=0;t.column<n.length-1;)Li(t)},zi=e=>{for(;;){let t=Li(e);if(t===` `)return` `;if(t!==` `&&t!==`
29
+ `)break}return Ri(e),`${(e.currentLine??[]).slice(e.column).join(``)}\n`},Bi=/* @__PURE__ */ new Set([`(`,`[`,`{`,`<<`,`⟨`]),Vi=/* @__PURE__ */ new Set([`>>_`,`⟩_`,`]_`,`)`,`}`,`]`,`>>`,`⟩`]),Hi=/* @__PURE__ */ new Set([...Bi,...Vi,...`_ 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(` `)]),Ui=e=>/^[A-Za-z_]$/.test(e),Wi=e=>/^[0-9]$/.test(e),Gi=e=>e===` `||e===`\f`||e===`\r`,Ki=new Set([...Hi].filter(e=>!Ui(e[0])&&!(e[0]===`\\`&&Ui(e[1]??``))).flatMap(e=>Array.from(e,(t,n)=>e.slice(0,e.length-n)))),qi=/* @__PURE__ */ new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ~!@#$%^&*()_-+={}[]|:;<,>.?/`'0123456789"),Ji=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(` `)),Yi={...di,dashes:6,endModule:7},Xi=()=>({delimiter:``,delimiterLine:0,delimiterCol:0,commentDepth:0}),Zi=(t,n,r,i)=>{let a={lines:[],line:[],token:``,state:`start`,column:n.vcolumn,nextColumn:n.vcolumn,nextChar:Li(n),parenDepth:0,isInQuantifier:!1,isExprEnd:!1,previousToken:` `},o=()=>{a.nextColumn=n.vcolumn,a.nextChar=Li(n)},s=()=>{a.token+=a.nextChar,o()},c=()=>{a.state=`start`,a.column=a.nextColumn},l=()=>{a.lines.push(a.line),a.line=[],a.column=0},u=t=>{throw new e.rt(`${t} \`${a.token}' found at\n line ${n.line+1}, column ${a.column+1}`)},d=()=>{a.isExprEnd=!0,t.delimiter=a.token,t.delimiterCol=a.column,t.delimiterLine=n.line-+(a.nextChar===`
30
+ `)},f=e=>{if(!r){d(),a.token=``;return}e>Yi.ident&&u(`Illegal token in an expression`);let t=a.token;e!==Yi.string&&(Ji.has(t)&&!(e===Yi.ident&&[`.`,`[`,`,`].includes(a.previousToken))||(t===`,`&&!a.isInQuantifier&&!i||t===`)`||t===`}`)&&a.parenDepth===0)?(a.parenDepth!==0&&u(`Expression with an unmatched (, [, {, or << followed by`),a.isInQuantifier&&u("Expression with \\A or \\E but no following `:` followed by"),d(),a.line.length>0&&l()):(e===Yi.builtin&&Bi.has(t)&&(a.parenDepth+=1),e===Yi.builtin&&Vi.has(t)&&(--a.parenDepth,a.parenDepth<0&&u(`Extra (unmatching)`)),a.previousToken=e===Yi.string?` `:t,[`\\A`,`∀`,`\\E`,`∃`].includes(t)&&a.parenDepth===0&&(a.isInQuantifier=!0),a.isInQuantifier&&t===`:`&&a.parenDepth===0&&(a.isInQuantifier=!1),(t!==``||e===Yi.string)&&a.line.push(vi(t,a.column,e)),a.token=``)},p=e=>{f(e),c()},m=e=>{s(),a.state=e},h=e=>{o(),a.state=e},g=r=>{switch(a.state){case`start`:if(Gi(r))return o(),c();if(Ui(r))return m(`id`);if(r===`ℕ`||r===`ℤ`||r===`ℝ`)return s(),p(Yi.ident);if(Wi(r))return m(`numOrId`);if(r===`\\`)return m(`bs`);if(r===`-`)return m(`dash1`);if(r===`=`)return m(`eq1`);if(r===`(`)return h(`leftParen`);if(r===`"`)return h(`string`);if(r===`
31
+ `)return o(),l(),c();if(Ki.has(r))return m(`builtIn`);if(r===` `){a.state=`done`;return}return s(),u(`Illegal lexeme`);case`id`:return a.token===`WF_`||a.token===`SF_`?p(Yi.builtin):Ui(r)||Wi(r)?s():p(Hi.has(a.token)?Yi.builtin:Yi.ident);case`numOrId`:return Wi(r)?s():Ui(r)?m(`id`):p(Yi.number);case`bs`:if([`b`,`B`,`o`,`O`,`h`,`H`].includes(r))return m(`numOrBi`);if(Ui(r)){a.state=`bsBuiltIn`;return}if(r===`*`){o(),a.token=``,a.state=`lineComment`;return}a.state=`builtIn`;return;case`numOrBi`:a.state=Wi(r)?`num`:`bsBuiltIn`;return;case`num`:if(Wi(r))return s();if(!Ui(r))return p(Yi.number);s(),a.token.startsWith(`\\`)&&u(`Illegal lexeme`),a.state=`id`;return;case`bsBuiltIn`:return Ui(r)&&r!==`_`?s():Hi.has(a.token)?p(Yi.builtin):u(`Illegal lexeme `);case`builtIn`:if(Ki.has(a.token+r))return s();if(!Hi.has(a.token)){for(Ri(n);!Hi.has(a.token);)Ri(n),a.token.length===0&&u(`Illegal lexeme`),a.token=Array.from(a.token).slice(0,-1).join(``);o()}return p(Yi.builtin);case`dash1`:case`dash2`:if(r===`-`)return m(a.state===`dash1`?`dash2`:`dash3`);a.state=`builtIn`;return;case`dash3`:return r!==`-`&&u(`Illegal lexeme`),m(`dashes`);case`dashes`:return r===`-`?s():p(Yi.dashes);case`eq1`:case`eq2`:if(r===`=`)return m(a.state===`eq1`?`eq2`:`eq3`);a.state=`builtIn`;return;case`eq3`:return r!==`=`&&u(`Illegal lexeme`),m(`eqs`);case`eqs`:return r===`=`?s():p(Yi.endModule);case`leftParen`:if(r===`*`)return t.commentDepth=1,h(`comment`);a.token=`(`,a.state=`builtIn`;return;case`string`:if(r===`\\`)return m(`escString`);if(r===`"`)return o(),p(Yi.string);s(),qi.has(r)||u(`Illegal character in string`);return;case`escString`:s(),[`"`,`\\`,`t`,`n`,`f`,`r`].includes(r)||u(`Illegal character following \\ in string`),a.state=`string`;return;case`lineComment`:return r===`(`?h(`lineComParen`):r===`*`&&t.commentDepth>0?h(`lineComStar`):r===`
1337
32
  `||r===` `?(a.token=``,t.commentDepth=0,c()):t.commentDepth===0?s():o();case`lineComParen`:if(r===`*`)return t.commentDepth+=1,h(`lineComment`);t.commentDepth===0&&(a.token+=`(`),a.state=`lineComment`;return;case`lineComStar`:if(r===`)`){if(--t.commentDepth,t.commentDepth<0)throw new e.nt(`Failure of assertion: case LINE_COM_STAR`);return h(`lineComment`)}t.commentDepth===0&&(a.token+=`*`),a.state=`lineComment`;return;case`comment`:case`orComment`:{let n=a.state===`comment`;if(r===`*`)return h(n?`commentStar`:`orCommentStar`);if(r===`(`)return h(n?`commentParen`:`orCommentParen`);if(r===`
1338
33
  `){a.token=``,o(),l(),a.state=`orComment`;return}if(r===` `)throw new e.rt(n?`Input ended in the middle of a comment`:`Input ended in the middle of a multi-line comment`);return t.commentDepth===1?s():o()}case`commentStar`:case`orCommentStar`:{let n=a.state===`commentStar`?`comment`:`orComment`;if(r!==`)`){t.commentDepth===1&&(a.token+=`*`),a.state=n;return}if(o(),--t.commentDepth,n===`orComment`&&t.commentDepth<0)throw new e.nt(`Assertion failure`);if(t.commentDepth!==0){a.state=n;return}return a.token=``,c()}case`commentParen`:case`orCommentParen`:{let e=a.state===`commentParen`?`comment`:`orComment`;if(r===`*`)return t.commentDepth+=1,h(e);t.commentDepth===1&&(a.token+=`(`),a.state=e;return}}};for(;a.state!==`done`&&!a.isExprEnd;)g(a.nextChar);return a.nextChar!==`
1339
- `&&Hi(n),Ei(a.lines)},na=(e,t,n)=>ta(e,t,!0,n),ra=(e,t)=>(ta(e,t,!1,!1),e.delimiter),ia=(e,t)=>({params:e,tokenizer:ea(),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}),aa=()=>Ei([[Si(`defaultInitValue`,0,0)]]),oa=(e,t)=>[...e,...t.filter((n,r)=>!e.includes(n)&&t.indexOf(n)===r)],sa=(e,t)=>!t.some(t=>e.includes(t)),ca=(e,t)=>{t.splice(0,t.length,...e)},la=(t,n,r)=>{let i=t.params,a=t.lookahead,o=t.lastToken,s={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:i.inputVersionNumber>=1500,omitStutteringWhenDone:i.inputVersionNumber>=1500},c=t=>{throw new e.rt(`${t}\n line ${o.line}, column ${o.column}`)},l=()=>{if(s.lookaheadSize===0)return Ui(n),o.column=n.vcolumn+1,o.line=n.line+1,o.text=ra(t.tokenizer,n),o.text;o.column=a.columns[0]+1,o.line=a.lines[0]+1;let e=a.tokens[0];for(let e=1;e<s.lookaheadSize;e++)a.tokens[e-1]=a.tokens[e],a.columns[e-1]=a.columns[e],a.lines[e-1]=a.lines[e];return--s.lookaheadSize,o.text=e,e},u=r=>{for(;s.lookaheadSize<r;){let r=s.lookaheadSize;if(Ui(n)===` `)throw new e.rt(`Premature end of file, perhaps because of unclosed comment, near\n line ${a.lines[r]+1}, column ${a.columns[r]+1}`);a.columns[r]=n.vcolumn,a.lines[r]=n.line,a.tokens[r]=ra(t.tokenizer,n),s.lookaheadSize+=1}return a.tokens[r-1]},d=r=>{if(r<s.lookaheadSize)throw new e.nt(`ParseAlgorithm.PeekPastAlgToken called to peek after a token
1340
- it has already peeked at`);for(;r>s.lookaheadSize;)a.tokens[s.lookaheadSize]=ra(t.tokenizer,n),s.lookaheadSize+=1;return Ui(n)},f=(r=!1)=>{if(s.lookaheadSize!==0)throw new e.nt(`ParseAlgorithm: GetExpr called after lookahead`);let i=na(t.tokenizer,n,r);return a.tokens[0]=t.tokenizer.delimiter,a.columns[0]=t.tokenizer.delimiterCol,a.lines[0]=t.tokenizer.delimiterLine,s.lookaheadSize=1,i},p=(t,n)=>{if(t===`;`){let t=u(1);if(`end begin else elsif or do macro procedure process fair define } {`.split(` `).includes(t))return;if(`if either while with call return goto print assert skip`.split(` `).includes(t))throw new e.rt(`Missing \`;' before line ${a.lines[0]+1}, column ${a.columns[0]+1}`)}let r=l();r!==t&&r!==n&&c(`Expected "${t}" but found "${r}"`)},m=e=>{let t=l();t!==e&&c(`Expected "${e}" but found "${t}"`)},h=()=>{let e=l();return e===`=`?!0:e===`\\in`||e===`∈`?!1:c(`Expected "=" or "\\in" but found "${e}"`)},g=()=>p(u(1)===`,`?`,`:`;`),_=()=>p(s.pSyntax?`begin`:`{`),v=e=>{s.cSyntax?p(`}`):(p(`end`),p(e))},y=()=>{u(1)===`variables`?m(`variables`):p(`variable`)},b=()=>{let t={...U(),kind:`VarDecl`,var:l(),col:o.column,line:o.line,isEq:!0,val:aa()};if(![`=`,`\\in`,`∈`].includes(u(1)))return s.hasDefaultInitialization=!0,t;if(t.isEq=h(),t.val=f(),t.val.tokens.length===0)throw new e.it(`NullPointerException`);return t},x=()=>{y();let e=[],t=[`begin`,`{`,`procedure`,`process`,`fair`,`define`,`macro`];for(;!t.includes(u(1));)e.push(b()),g();return e},S=()=>{let t={...U(),kind:`PVarDecl`,var:l(),col:o.column,line:o.line,val:aa()};if(u(1)!==`=`)return s.hasDefaultInitialization=!0,t;if(p(`=`),t.val=f(),t.val.tokens.length===0)throw new e.it(`NullPointerException`);return t},C=()=>{y();let e=[];for(;u(1)!==`begin`&&u(1)!==`{`;)e.push(S()),g();return e},w=()=>{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=Ui(n);return e.length>0&&e[0]===`:`&&!(e.length>1&&e[1]===`=`)},T=()=>{if(!w())return``;let e=l();t.isInMacro&&c(`A label may not appear in a macro.`),e===`Done`&&c("Cannot use `Done' as a label."),e===`Error`&&c("Cannot use `Error' as a label."),p(`:`),s.hasLabel=!0,s.allLabels.add(e);let n=u(1);return n!==`+`&&n!==`-`||(p(n),(n===`+`?s.plusLabels:s.minusLabels).push(e),s.omitPC=!1),e},E=()=>{let e=[],t=e=>s.pSyntax&&[`end`,`else`,`elsif`,`or`].includes(e)||s.cSyntax&&e===`}`;for(;!t(u(1));)e.push(...D());return s.cSyntax&&e.length===0&&c(`Empty statement list`),e},ee=t=>{m(`{`);let n=E();if(p(`}`),p(`;`),t!==``){if(n[0].lbl!==``)throw new e.rt(`Duplicate labeling of statement`,n[0]);n[0].lbl=t}return n},D=()=>{let e=T();if(s.cSyntax&&u(1)===`{`)return ee(e);let t=te();return t.lbl=e,[t]},te=()=>{let t=u(1);if(t===`if`)return O(0);if(t===`either`)return k();if(t===`with`)return A(0);if(t===`when`||t===`await`){m(t);let n=o.column,r=o.line,i=f();if(i.tokens.length===0)throw new e.it(`NullPointerException`);return p(`;`),{...U(),kind:`When`,col:n,line:r,exp:i}}if(t===`print`||t===`assert`){m(t);let e=o.column,n=o.line,r=f();return r.tokens.length===0&&c(`Empty expression in ${t} statement at `),p(`;`),{...U(),kind:t===`print`?`PrintS`:`Assert`,col:e,line:n,exp:r}}if(t===`skip`){m(`skip`);let e={...U(),kind:`Skip`,col:o.column,line:o.line};return p(`;`),e}if(t===`call`)return N();if(t===`return`){m(`return`);let e={...U(),kind:`Return`,col:o.column,line:o.line,from:s.currentProcedure};return p(`;`),e}if(t===`goto`){m(`goto`);let e=o.column,t=o.line,n=l();return s.gotoUsed=!0,(n===`Done`||n===`"Done"`)&&(s.gotoDoneUsed=!0),p(`;`),{...U(),kind:`Goto`,col:e,line:t,to:n}}return t===`while`?ne():d(1)[0]===`(`?ae():j()},ne=()=>{m(`while`);let e=o.column,t=o.line;s.cSyntax&&p(`(`);let n=f();s.cSyntax&&p(`)`),n.tokens.length===0&&c(`Empty while test at `),s.pSyntax&&p(`do`);let r=s.pSyntax?E():D();return s.pSyntax&&(p(`end`),p(`while`),p(`;`)),r.length===0&&c(`Missing body of while statement at`),{...U(),kind:`While`,col:e,line:t,test:n,unlabDo:r,labDo:[]}},O=e=>{m(e===0?`if`:`elsif`);let t={...U(),kind:`LabelIf`,col:o.column,line:o.line,test:wi(),unlabThen:[],labThen:[],unlabElse:[],labElse:[]};s.cSyntax&&p(`(`),t.test=f(),s.cSyntax&&p(`)`),t.test.tokens.length===0&&c(`Empty if test at `),s.pSyntax&&p(`then`),t.unlabThen=s.pSyntax?E():D();let n=u(1);return n===`else`&&(m(`else`),t.unlabElse=s.pSyntax?E():D()),s.pSyntax&&n===`elsif`&&(t.unlabElse=[O(e+1)]),s.pSyntax&&![`else`,`elsif`,`end`].includes(n)&&c(`Expecting "else", "elsif", or "end"`),s.pSyntax&&e===0&&(p(`end`),p(`if`),p(`;`)),t.unlabElse.length===0&&xi(t.unlabThen,t.unlabThen.length-1),t},k=()=>{m(`either`);let t={...U(),kind:`LabelEither`,col:o.column,line:o.line,clauses:[]};for(;;){let n={...U(),kind:`Clause`,unlabOr:s.pSyntax?E():D(),labOr:[]};if(n.unlabOr.length===0)throw new e.rt("`either' statement with empty `or' clause",t);if(t.clauses.push(n),u(1)!==`or`)break;m(`or`)}if(s.pSyntax&&(m(`end`),p(`either`),p(`;`)),t.clauses.length===1)throw new e.rt("`either' statement has no `or'",t);return t},A=t=>{t===0&&(p(`with`),s.cSyntax&&p(`(`));let n={...U(),kind:`With`,col:o.column,line:o.line,var:l(),isEq:!0,exp:wi(),Do:[]};n.isEq=h(),n.exp=f(),(s.pSyntax||u(1)!==`)`)&&g(),n.exp.tokens.length===0&&c(`Empty with expression at `);let r=s.pSyntax&&u(1)===`do`,i=s.cSyntax&&u(1)===`)`;if(r&&p(`do`),i&&m(`)`),n.Do=r?E():i?D():[A(t+1)],r&&(p(`end`),p(`with`),p(`;`)),n.Do.length===0)throw new e.rt(`Missing body of with statement`,n);return n},re=()=>{let e=a.columns[0]+1,t=a.lines[0]+1,n={...U(),kind:`Lhs`,col:e,line:t,var:l(),sub:f()};p(`:=`,`≔`);let r=f();return r.tokens.length===0&&c(`Empty right-hand side of assignment at `),{...U(),kind:`SingleAssign`,col:e,line:t,lhs:n,rhs:r}},j=()=>{let t={...U(),kind:`Assign`,col:a.columns[0]+1,line:a.lines[0]+1,ass:[re()]};for(;u(1)===`||`||u(1)===`‖`;){l();try{t.ass.push(re())}catch(t){if(!(t instanceof e.rt))throw t;c(`Bad assignment statement at `)}}return p(`;`),t},ie=()=>{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;p(`,`)}return p(`)`),p(`;`),e},M=()=>{m(`call`);let e={...U(),kind:`Call`,col:o.column,line:o.line,returnTo:``,to:l(),args:[]};return p(`(`),e.args=ie(),s.proceduresCalled.includes(e.to)||s.proceduresCalled.push(e.to),e},N=()=>{let e=M();if(u(1)===`return`)return m(`return`),p(`;`),{...U(),kind:`CallReturn`,col:e.col,line:e.line,to:e.to,from:s.currentProcedure,args:e.args};if(u(1)!==`goto`)return e;m(`goto`);let t={...U(),kind:`CallGoto`,col:e.col,line:e.line,to:e.to,after:l(),args:e.args};return s.gotoUsed=!0,(t.to===`Done`||t.to===`"Done"`)&&(s.gotoDoneUsed=!0),p(`;`),t},ae=()=>{let e={...U(),kind:`MacroCall`,name:l(),col:o.column,line:o.line,args:[]};return m(`(`),e.args=ie(),e},oe=e=>{t.isInMacro=!0,m(`macro`);let n={...U(),kind:`Macro`,col:o.column,line:o.line,name:l(),params:[],body:[]};for(p(`(`);u(1)!==`)`;)n.params.length>0&&p(`,`),n.params.push(l());return m(`)`),_(),n.body=E(),v(`macro`),u(1)===`;`&&l(),he(n.body,e),t.isInMacro=!1,n},se=()=>{p(`procedure`);let e={...U(),kind:`Procedure`,col:o.column,line:o.line,name:l(),minusLabels:[],plusLabels:[],proceduresCalled:[],params:[],decls:[],body:[]};for(s.currentProcedure=e.name,s.plusLabels=[],s.minusLabels=[],s.proceduresCalled=[],p(`(`);u(1)!==`)`;)e.params.length>0&&p(`,`),e.params.push(S());return m(`)`),u(1)!==`begin`&&u(1)!==`{`&&(e.decls=C()),_(),e.body=E(),v(`procedure`),u(1)===`;`&&l(),s.currentProcedure=void 0,e.plusLabels=s.plusLabels,e.minusLabels=s.minusLabels,e.proceduresCalled=s.proceduresCalled,e},P=()=>{p(`process`);let e=o.column,t=o.line;s.cSyntax&&p(`(`);let n=l(),r=h(),i=f();s.plusLabels=[],s.minusLabels=[],s.proceduresCalled=[],s.cSyntax&&p(`)`),i.tokens.length===0&&c(`Empty process id at `);let a=u(1)===`begin`||u(1)===`{`?[]:x();_();let d=E();return v(`process`),u(1)===`;`&&l(),{...U(),kind:`Process`,col:e,line:t,name:n,fairness:0,minusLabels:s.minusLabels,plusLabels:s.plusLabels,proceduresCalled:s.proceduresCalled,isEq:r,id:i,decls:a,body:d}},F=()=>{let e=`${i.labelRoot}${s.nextLabelNum}`;return s.nextLabelNum+=1,s.allLabels.has(e)?F():e},I=e=>{e.lbl===``&&(e.lbl=F(),s.addedLabels.push(e.lbl),s.addedLabelsLocs.push(yi(e)))},ce=(t,n,r,i,a)=>{ca(i,a);let o={isNextLabeled:n,hasLabel:!1},c=e=>{I(e),o.hasLabel=!0,a.length=0};return t.forEach(t=>{if(t.lbl!==``&&(o.hasLabel=!0,a.length=0,r))throw new e.rt("Label in `with' statement",t);if(o.isNextLabeled){if(r)throw new e.rt("Statement follows `call' or `return' inside a `with' statement.",t);c(t),o.isNextLabeled=!1}switch(t.kind){case`LabelIf`:{let e=[],n=[],i=ce(t.unlabThen,!1,r,a,e);o.isNextLabeled=ce(t.unlabElse,!1,r,a,n)||i,ca(oa(e,n),a);return}case`LabelEither`:{let e=[];t.clauses.forEach(t=>{let n=[];o.isNextLabeled=ce(t.unlabOr,!1,r,a,n)||o.isNextLabeled,ca(oa(n,e),e)}),ca(e,a);return}case`While`:if(r)throw new e.rt("`while' inside a `with' statement",t);c(t),ce(t.unlabDo,!1,!1,a,[]),o.isNextLabeled=!1;return;case`With`:{let e=[];o.isNextLabeled=ce(t.Do,!1,!0,r?[...i]:[],e),ca(e,a),!r&&!sa(i,a)&&c(t);return}}let n=t.kind===`Call`||t.kind===`CallGoto`,l=t.kind===`Return`||t.kind===`CallReturn`,u=t.kind===`Assign`?oa([],t.ass.map(e=>e.lhs.var)):n||l?[`stack`,...l||t.to===s.currentProcedure?s.procedures.flatMap(e=>[...e.params,...e.decls].map(e=>e.var)):[]]:[];if(o.isNextLabeled=n||l||t.kind===`Goto`,sa(a,u))ca(oa(a,u),a);else{if(r)throw new e.rt(t.kind===`Assign`?"Second assignment to same variable inside a `with' statement":"Call or return makes second assignment to a variable inside a `with' statement",t);c(t),ca(u,a)}}),o.hasLabel||o.isNextLabeled},le=e=>{let t=e=>{let t=e.findIndex(e=>e.lbl!==``),n=t===-1?e:e.slice(0,t);return le(n),{unlabeled:n,labeled:ue(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}}})},ue=t=>{let n=[];return t.forEach(t=>{if(t.lbl===``&&n.length>0)n[n.length-1].stmts.push(t);else{if(t.lbl===``)throw new e.nt(`Failure of assertion: Missing Label in MakeLabeledStmtSeq`);n.push({...U(),kind:`LabeledStmt`,col:t.col,line:t.line,macroCol:t.macroCol,macroLine:t.macroLine,label:t.lbl,stmts:[t]})}}),n.forEach(e=>le(e.stmts)),n},de=(t,n)=>{let r=t[n];switch(r.kind){case`LabelIf`:{let e=fe(r.unlabThen);r.labThen.forEach(e=>fe(e.stmts));let i=fe(r.unlabElse);return r.labElse.forEach(e=>fe(e.stmts)),r.labThen.length>0||r.labElse.length>0||e===2||i===2?2:(t[n]={...U(),kind:`If`,test:r.test,Then:r.unlabThen,Else:r.unlabElse},+(e+i>0))}case`LabelEither`:{let e=r.clauses.reduce((e,t)=>{let n=Math.max(e,fe(t.unlabOr));return t.labOr.forEach(e=>fe(e.stmts)),t.labOr.length>0?2:n},0);return e===2?2:(t[n]={...U(),kind:`Either`,ors:r.clauses.map(e=>e.unlabOr)},e)}case`With`:{let t=fe(r.Do);if(t===2)throw new e.rt(`with statement at ${yi(r)} contains a labeled statement`);return t}case`While`:if(n!==0)throw new e.nt("ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.");return fe(r.unlabDo),r.labDo.forEach(e=>fe(e.stmts)),0;case`Call`:return t[n+1]?.kind===`Return`?0:1;case`Return`:case`CallReturn`:if(s.currentProcedure===void 0)throw new e.rt(`return statement not in a procedure at ${yi(r)}`);return 1;case`Goto`:case`CallGoto`:return 1;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`MacroCall`:return 0;default:throw new e.nt(`ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${r.kind}`)}},fe=t=>{for(let n=0;n<t.length;n++){let r=de(t,n);if(r!==0){if(n===t.length-1)return r;throw new e.nt(`Translator discovered later than it should have that\n Statement at ${yi(t[n+1])} must have a label`)}}return 0},pe=e=>{ce(e,!0,!1,[],[]);let t=ue(e);return t.forEach(e=>fe(e.stmts)),t},L=(t,n,r,i,a)=>{let o=e=>Ii(e,n,r),s=e=>e.map(e=>L(e,n,r,i,a)),c=e=>e.map(e=>({...U(),kind:`LabeledStmt`,label:e.label,stmts:e.stmts.map(e=>L(e,n,r,-1,0))})),l={...U(),col:t.col,line:t.line,macroCol:i>0?a:t.macroCol,macroLine:i>0?i:t.macroLine};switch(t.kind){case`Assign`:return{...l,kind:`Assign`,ass:t.ass.map(e=>me(e,n,r,i,a))};case`If`:return{...l,kind:`If`,test:o(t.test),Then:s(t.Then),Else:s(t.Else)};case`Either`:return{...l,kind:`Either`,ors:t.ors.map(s)};case`With`:return{...l,kind:`With`,var:t.var,isEq:t.isEq,exp:o(t.exp),Do:s(t.Do)};case`When`:case`Assert`:case`PrintS`:return{...l,kind:t.kind,exp:o(t.exp)};case`Skip`:return{...l,kind:`Skip`,macroCol:i>0?a:0,macroLine:i>0?i:-1};case`While`:return{...l,kind:`While`,test:o(t.test),unlabDo:s(t.unlabDo),labDo:c(t.labDo)};case`LabelIf`:return{...l,kind:`LabelIf`,test:o(t.test),unlabThen:s(t.unlabThen),labThen:c(t.labThen),unlabElse:s(t.unlabElse),labElse:c(t.labElse)};case`LabelEither`:return{...l,kind:`LabelEither`,clauses:t.clauses.map(e=>({...U(),kind:`Clause`,labOr:c(e.labOr),unlabOr:s(e.unlabOr)}))};case`Call`:return{...l,kind:`Call`,to:t.to,returnTo:t.returnTo,args:Li(t.args,n,r)};case`Return`:return{...l,kind:`Return`,from:t.from};case`CallReturn`:return{...l,kind:`CallReturn`,to:t.to,from:t.from,args:Li(t.args,n,r)};case`CallGoto`:return{...l,kind:`CallGoto`,to:t.to,after:t.after,args:Li(t.args,n,r)};case`Goto`:return{...l,kind:`Goto`,to:t.to};default:throw new e.nt(`Found unexpected statement type in macro at${yi(t)}`)}},me=(t,n,r,i,a)=>{let o=Ii(t.rhs,n,r),s={...U(),kind:`Lhs`,var:t.lhs.var,sub:t.lhs.sub.tokens.length===0?t.lhs.sub:Ii(t.lhs.sub,n,r)},c={...U(),kind:`SingleAssign`,col:t.col,line:t.line,macroCol:i>0?a:t.macroCol,macroLine:i>0?i:t.macroLine,lhs:s,rhs:o},l=r.indexOf(s.var);if(l===-1)return c;let u=n[l],d=ji(u,{line:0,item:0});if(d.type!==hi.ident)throw new e.rt(`Macro expansion substitutes \`${d.string}' for assignment variable\n at ${yi(c)}`);if(s.var=d.string,Mi(u,{line:0,item:0},1)===void 0)return c;let f=Oi(u);return f.tokens[0].splice(0,1),Ti(f),s.sub.tokens.length===0?s.sub=f:ki(s.sub,f,0),c},he=(e,t)=>{let n=e.flatMap(e=>{switch(e.kind){case`LabelIf`:return he(e.unlabThen,t),he(e.unlabElse,t),[e];case`LabelEither`:return e.clauses.forEach(e=>he(e.unlabOr,t)),[e];case`With`:return he(e.Do,t),[e];case`While`:return he(e.unlabDo,t),[e];case`MacroCall`:return ge(e,t);default:return[e]}});e.splice(0,e.length,...n)},ge=(t,n)=>{let r=n.findLast(e=>e.name===t.name);if(r===void 0)throw new e.rt(`Macro ${t.name} undefined,\n at ${yi(t)}`);if(r.params.length!==t.args.length)throw new e.rt(`Macro ${t.name} called with wrong number of arguments at \n ${yi(t)}`);let i=r.body.map(e=>L(e,t.args,r.params,t.line,t.col));return i.length>0&&(i[0].lbl=t.lbl),i},_e=t=>{t.forEach((n,r)=>{if(t.slice(r+1).some(e=>e.name===n.name))throw new e.rt(`Multiple definitions of macro name \`${n.name}'`)})},ve=e=>{if(e.length===0)return;let t=()=>{s.omitPC=!1,s.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`||!Ai(r.test)||r.test.tokens[0][0].string!==`TRUE`)return t();r.labDo.length>0&&(s.omitPC=!1),r.unlabDo.some(e=>[`LabelIf`,`LabelEither`,`LabeledStmt`].includes(e.kind))&&(s.omitPC=!1)},ye=()=>{let t=s.addedLabels.length>1?`Missing labels at the following locations:`:`Missing label at the following location:`;throw new e.rt([t,...s.addedLabelsLocs].join(`
1341
- `))},be=()=>{i.reportLabelsFlag?(t.log(s.addedLabels.length>1?`The following labels were added:`:`The following label was added:`),s.addedLabels.forEach((e,n)=>t.log(` ${e} at ${s.addedLabelsLocs[n]}`))):t.log(`Labels added.`)},xe=e=>s.procedures.forEach(t=>{s.currentProcedure=t.name,he(t.body,e),t.body=pe(t.body)}),Se=()=>{r&&(l()!==`algorithm`&&c("`--fair' not followed by `algorithm'"),i.fairAlgorithm=!0);let e=l();s.cSyntax=u(1)===`{`,s.pSyntax=!s.cSyntax,s.cSyntax&&m(`{`);let n=u(1)===`variable`||u(1)===`variables`?x():[],a={value:wi()};u(1)===`define`&&(m(`define`),s.cSyntax&&p(`{`),a.value=f(!0),v(`define`),p(`;`));let o=[];for(;u(1)===`macro`;)o.push(oe(o));for(;u(1)===`procedure`;)s.procedures.push(se()),s.omitPC=!1;if(u(1)===`fair`&&(u(2)===`process`||u(2)===`+`&&u(3)===`process`)||u(1)===`process`){let t=[];for(;u(1)===`fair`||u(1)===`process`;){let e=u(1)===`fair`;e&&m(`fair`);let n=e&&u(1)===`+`;n&&m(`+`);let r=n||!e&&i.fairnessOption===`sf`?2:e||i.fairnessOption===`wf`?1:0;t.push({...P(),fairness:r})}v(`algorithm`),_e(o);let r=t.map(e=>(he(e.body,o),e.body=pe(e.body),s.omitStutteringWhenDone=!0,ve(e.body),s.omitStutteringWhenDone));return s.omitStutteringWhenDone=r.includes(!0),xe(o),s.addedLabels.length>0&&(i.labelFlag||ye(),be()),s.gotoDoneUsed&&(s.omitPC=!1,s.omitStutteringWhenDone=!1),s.gotoUsed&&(s.omitPC=!1),{...U(),kind:`Multiprocess`,name:e,decls:n,defs:a.value,macros:o,prcds:s.procedures,procs:t}}i.inputVersionNumber===1500&&u(1)===`fair`&&(p(`fair`),u(1)===`+`&&p(`+`),i.fairnessOption=`wf`),r&&([``,`wf`,`wfNext`].includes(i.fairnessOption)||t.log(`Warning: Option \`${i.fairnessOption}' specified for --fair algorithm.`),i.fairnessOption=`wf`),_();let d=E();_e(o),he(d,o),xe(o),s.cSyntax&&p(`}`),v(`algorithm`);let h=pe(d);return s.addedLabels.length>0&&(s.hasLabel&&!i.labelFlag&&ye(),be()),s.gotoUsed&&(s.omitPC=!1),s.gotoDoneUsed||ve(h),s.gotoDoneUsed&&(s.omitPC=!1,s.omitStutteringWhenDone=!1),{...U(),kind:`Uniprocess`,name:e,decls:n,defs:a.value,macros:o,prcds:s.procedures,body:h}};try{return{ast:Se(),omitPC:s.omitPC,omitStutteringWhenDone:s.omitStutteringWhenDone,hasDefaultInitialization:s.hasDefaultInitialization}}catch(t){if(!(t instanceof e.it))throw t;return c(`Unknown error at or before`)}},W={global:0,label:1,procedure:2,process:3,processVar:4,procedureVar:5,parameter:6},ua=[`Global variable`,`Label`,`Procedure`,`Process`,`Process variable`,`Procedure variable`,`Parameter`],da=/* @__PURE__ */ new Set([W.global,W.processVar,W.procedureVar,W.parameter]),fa=(e,t,n,r)=>e.symbols.find(e=>e.id===n&&e.context===r&&e.type===t),pa=(e,t,n)=>e.symbols.find(e=>e.id===t&&e.context===n),ma=(e,t)=>{let n=e.procedures.findIndex(e=>e.name===t);return n===-1?e.procedures.length:n},ha=(e,t)=>{let n=e.processes.findIndex(e=>e.name===t);return n===-1?e.processes.length:n},ga=(e,t,n,r,i,a,o)=>!(t===W.procedureVar||t===W.processVar||t===W.parameter?fa(e,W.global,n,``)!==void 0||pa(e,n,r)!==void 0:fa(e,t,n,r)!==void 0)&&(e.symbols.push({type:t,id:n,context:r,contextType:i,line:a,col:o,useThis:n}),!0),_a=(e,t,n,r)=>fa(e,t,n,r)?.useThis??n,va=(e,t,n)=>{let r=pa(e,t,n);return r===void 0?t:da.has(r.type)?r.useThis:t},ya=t=>{let n={symbols:[],procedures:[],processes:[],disambiguateReport:[],errorReport:``,initialPC:void 0},r=(e,t,r)=>{ga(n,W.label,e.label,t,r,e.line,e.col)||(n.errorReport+=`\nLabel ${e.label} redefined at line ${e.line}, column ${e.col}`),e.stmts.forEach(e=>i(e,t,r))},i=(t,n,a)=>{let o=e=>e.forEach(e=>i(e,n,a)),s=e=>e.forEach(e=>r(e,n,a));switch(t.kind){case`While`:o(t.unlabDo),s(t.labDo);return;case`If`:o(t.Then),o(t.Else);return;case`With`:o(t.Do);return;case`LabelIf`:o(t.unlabThen),s(t.labThen),o(t.unlabElse),s(t.labElse);return;case`Either`:t.ors.forEach(o);return;case`LabelEither`:t.clauses.forEach(e=>{o(e.unlabOr),s(e.labOr)});return;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`Call`:case`Return`:case`CallReturn`:case`CallGoto`:case`Goto`:return;default:throw new e.nt(`Unexpected AST type ${t.kind}`)}},a=(e,t,r=`process`,i=t===``?W.global:W.processVar)=>{ga(n,i,e.var,t,r,e.line,e.col)||(n.errorReport+=`\n${ua[i]} ${e.var} redefined at line ${e.line}, column ${e.col}`)};if(ga(n,W.global,`pc`,``,``,0,0),t.prcds.length>0&&ga(n,W.global,`stack`,``,``,0,0),t.decls.forEach(e=>a(e,``)),t.prcds.forEach(e=>{let t=ma(n,e.name)<n.procedures.length;t&&(n.errorReport+=`\nProcedure ${e.name} redefined at line ${e.line}, column ${e.col}`),t||n.procedures.push({name:e.name,params:e.params,decls:e.decls,initialPC:e.body.length===0?void 0:bi(e.body[0]).label}),ga(n,W.procedure,e.name,``,`procedure`,e.line,e.col),e.decls.forEach(t=>a(t,e.name,`procedure`,W.procedureVar)),e.params.forEach(t=>a(t,e.name,`procedure`,W.parameter)),e.body.forEach(t=>r(bi(t),e.name,`procedure`))}),t.kind===`Multiprocess`&&t.procs.forEach(e=>{let t=ha(n,e.name)<n.processes.length;t&&(n.errorReport+=`\nProcess ${e.name} redefined at line ${e.line}, column ${e.col}`),t||n.processes.push({name:e.name,initialPC:e.body.length===0?void 0:bi(e.body[0]).label}),ga(n,W.process,e.name,``,`process`,e.line,e.col),e.decls.forEach(t=>a(t,e.name)),e.body.forEach(t=>r(bi(t),e.name,`process`))}),t.kind===`Uniprocess`&&(t.body.length>0&&(n.initialPC=bi(t.body[0]).label),t.body.forEach(e=>r(bi(e),``,``))),n.errorReport.length>0)throw new e.rt(n.errorReport);return n},ba=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(`\\* ${ua[r.type]} ${r.id}${i} at line ${r.line} col ${r.col} changed to ${r.useThis}`)})},xa=t=>{let n=t.symbols.filter(e=>e.id===`defaultInitValue`).map(e=>`${ua[e.type]} name`);if(n.length>0)throw new e.rt(`Cannot use \`defaultInitValue' as ${n.join(` or `)}`)},Sa=(t,n,r)=>{let i=(e,t)=>{let r=[],i=[];e.tokens.forEach(e=>e.forEach(e=>{if(e.type!==hi.ident)return;let a=va(n,e.string,t);r.includes(e.string)||a===e.string||(r.push(e.string),i.push(Ei([[Ea(a)]])))})),i.length>0&&Fi(e,i,r,!1)},a=(e,t)=>{e.var=va(n,e.var,t),i(e.val,t)},o=(e,t)=>e.forEach((r,i)=>{e[i]=_a(n,W.label,r,t)}),s=(e,t)=>e===void 0?void 0:_a(n,W.procedure,e,t),c=(e,t)=>{e.label=_a(n,W.label,e.label,t),e.stmts.forEach(e=>l(e,t))},l=(t,r)=>{let a=e=>e.forEach(e=>l(e,r)),o=e=>e.forEach(e=>c(e,r)),u=e=>e.forEach(e=>i(e,r));switch(t.kind){case`LabeledStmt`:c(t,r);return;case`While`:a(t.unlabDo),o(t.labDo),i(t.test,r);return;case`Assign`:t.ass.forEach(e=>{e.lhs.var=va(n,e.lhs.var,r),i(e.lhs.sub,r),i(e.rhs,r)});return;case`If`:a(t.Then),a(t.Else),i(t.test,r);return;case`With`:i(t.exp,r),a(t.Do);return;case`When`:case`PrintS`:case`Assert`:i(t.exp,r);return;case`Skip`:return;case`LabelIf`:i(t.test,r),a(t.unlabThen),o(t.labThen),a(t.unlabElse),o(t.labElse);return;case`Call`:t.returnTo=_a(n,W.procedure,t.returnTo,r),t.to=_a(n,W.procedure,t.to,r),u(t.args);return;case`Return`:t.from=s(t.from,r);return;case`CallReturn`:t.from=s(t.from,r),t.to=_a(n,W.procedure,t.to,r),u(t.args);return;case`CallGoto`:t.after=_a(n,W.procedure,t.after,r),t.to=_a(n,W.procedure,t.to,r),u(t.args);return;case`Goto`:if(fa(n,W.label,t.to,r)===void 0&&t.to!==`Done`)throw new e.rt(`goto to non-existent label \`${t.to}' at line ${t.line}, column ${t.col}`);t.to=_a(n,W.label,t.to,r);return;case`Either`:t.ors.forEach(a);return;case`LabelEither`:t.clauses.forEach(e=>{a(e.unlabOr),o(e.labOr)});return;default:throw new e.nt(`Unexpected AST type${t.kind}`)}},u=e=>{e.decls.forEach(t=>a(t,e.name)),e.params.forEach(t=>a(t,e.name)),e.body.forEach(t=>c(bi(t),e.name));let t=xi(n.procedures,ma(n,e.name));o(e.plusLabels,e.name),o(e.minusLabels,e.name),t.initialPC!==void 0&&(t.initialPC=_a(n,W.label,t.initialPC,e.name)),e.name=_a(n,W.procedure,e.name,``),t.name=e.name},d=e=>{e.decls.forEach(t=>a(t,e.name)),e.body.forEach(t=>c(bi(t),e.name));let t=xi(n.processes,ha(n,e.name));o(e.plusLabels,e.name),o(e.minusLabels,e.name),t.initialPC!==void 0&&(t.initialPC=_a(n,W.label,t.initialPC,e.name)),e.name=_a(n,W.process,e.name,``),t.name=e.name};t.decls.forEach(e=>a(e,``)),t.kind===`Multiprocess`&&((e,t)=>{e.forEach(u);let n=e.map(e=>e.name),i=e.map(e=>n.map(t=>e.proceduresCalled.includes(t)));n.forEach((e,t)=>i.forEach(e=>e.forEach((n,r)=>{e[r]=n||e[t]&&i[t][r]}))),e.forEach((e,t)=>{e.proceduresCalled=n.filter((e,n)=>i[t][n])});for(let e of t){d(e);let t=e.proceduresCalled;for(let e=0;e<t.length;e+=1){let a=n.indexOf(t[e]);if(a===-1){r(`\nUnrecoverable error:\n -- Could not find procedure name \`${t[e]}'.\n`);return}n.forEach((e,n)=>{i[a][n]&&!t.includes(e)&&t.push(e)})}}})(t.prcds,t.procs),t.kind===`Uniprocess`&&(t.prcds.forEach(u),t.body.forEach(e=>c(bi(e),``))),n.initialPC!==void 0&&(n.initialPC=_a(n,W.label,n.initialPC,``))},Ca=e=>Si(e,0,hi.string),wa=e=>Si(e,0,hi.added),Ta=e=>Si(e,0,hi.builtin),Ea=e=>Si(e,0,hi.ident),Da=(e,t)=>{let n=[];return e.forEach(e=>{let r=n.at(-1),i=r===void 0?0:r.column+Ci(r)+t;n.push(Si(e.string,i,e.type))}),Ei([n])},Oa=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+=Ci(e),e.type===hi.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}})}),ka=(e,t,n,r=0,i=0)=>({...U(),kind:`SingleAssign`,line:r,col:i,lhs:{...U(),kind:`Lhs`,var:e,sub:t},rhs:n}),Aa=(e,t=0,n=0)=>({...U(),kind:`Assign`,line:t,col:n,ass:e}),ja=(e,t,n=0,r=0)=>Aa([ka(e,Ei([]),t,n,r)],n,r),Ma=e=>{if(e.tokens.length>1)return!1;let t=xi(e.tokens,0);return t.length===1?t[0].string===`TRUE`:t.length===3&&t[0].string===`(`&&t[1].string===`TRUE`&&t[2].string===`)`},Na=e=>({...U(),kind:`When`,exp:Da([wa(`pc`),Ta(`=`),Ca(e)],1)}),Pa=e=>ja(`pc`,Ei([[Ca(e??`null`)]])),Fa=e=>[Ea(`Head`),Ta(`(`),wa(`stack`),Ta(`)`),Ta(`.`),Ea(e)],Ia=()=>[Ea(`Tail`),Ta(`(`),wa(`stack`),Ta(`)`)],La=e=>Ei([Fa(e)]),Ra=(e,t,n,r)=>{let i=[[Ta(`<<`),Ta(`[`),Ea(`procedure`),Ta(`|->`),Ca(e),Ta(`,`)],[Ea(`pc`),Ta(`|->`),...t]];n.forEach(e=>{i[i.length-1].push(Ta(`,`)),i.push([Ea(e.var),Ta(`|->`),Ea(e.var)])}),i[i.length-1].push(Ta(`]`),Ta(`>>`)),i.push(r);let a=wi(i);return Oa(a),Ti(a),a},za=(t,n,r)=>{if(n.params.length!==r.args.length)throw new e.rt(`Procedure ${r.to} called with wrong number of arguments`,r);return n.params.forEach((e,n)=>t.ass.push(ka(e.var,Ei([]),r.args[n],r.line,r.col))),[t,...n.decls.map(e=>ja(e.var,e.val,r.line,r.col)),Pa(n.initialPC)]},Ba=(t,n,r)=>{let i={procedure:void 0},a=(t,r)=>{let i=ma(n,t.to);if(i===n.procedures.length)throw new e.rt(`Call of non-existent procedure ${t.to}`,t);let a=n.procedures[i],o=Ra(t.to,[Ca(r)],[...a.decls,...a.params],[Ta(`\\o`),wa(`stack`)]);return za(ja(`stack`,o,t.line,t.col),a,t)},o=t=>{t.from??=i.procedure;let r=t.from;if(r===void 0)throw new e.rt("`return' statement not in procedure",t);let a=ma(n,r);if(a>=n.procedures.length)throw new e.rt(`Error in procedure (perhaps name used elsewhere)`,t);let o=n.procedures[a],s=(e,n)=>Aa([ka(e,wi(),n,t.line,t.col)],t.line,t.col);return[s(`pc`,La(`pc`)),...o.decls.map(e=>s(e.var,La(e.var))),...o.params.map(e=>s(e.var,La(e.var))),s(`stack`,Ei([Ia()]))]},s=t=>{let r=t.from;if(r===void 0)throw new e.rt(`\`return' statement following \`call' at ${yi(t)} not in a procedure`);let i=xi(n.procedures,ma(n,r)),a=ma(n,t.to);if(a===n.procedures.length)throw new e.rt(`Call of non-existent procedure ${t.to}`,t);let o=n.procedures[a],s=Aa([],t.line,t.col);if(r!==t.to){i.decls.forEach(e=>s.ass.push(ka(e.var,wi(),La(e.var),t.line,t.col)));let e=Ra(t.to,Fa(`pc`),[...o.decls,...o.params],[Ta(`\\o`),...Ia()]);s.ass.push(ka(`stack`,Ei([]),e,t.line,t.col))}return za(s,o,t)},c=(e,t)=>{if(e.length===0)return{stmts:[],labeledStmts:[],needsGoto:!r};let n={stmts:e,labeledStmts:[],needsGoto:!1},i=e[e.length-1];switch(i.kind){case`LabelIf`:case`LabelEither`:{let r=i.kind===`LabelIf`?p(i,t):m(i,t);e.pop(),e.push(r.stmt),n.labeledStmts=r.labeledStmts;break}case`Goto`:e.pop(),e.push(Pa(i.to));break;case`Call`:e.pop(),e.push(...a(i,t));break;case`Return`:e.pop(),e.push(...o(i));break;case`CallReturn`:e.pop(),e.push(...s(i));break;case`CallGoto`:e.pop(),e.push(...a({...U(),kind:`Call`,returnTo:``,to:i.to,args:i.args,line:i.line,col:i.col},i.after));break;case`If`:{let e=c(i.Then,t),a=c(i.Else,t);n.labeledStmts.push(...e.labeledStmts,...a.labeledStmts),i.Then=e.stmts,i.Else=a.stmts,r||(n.needsGoto=e.needsGoto&&a.needsGoto,n.needsGoto||(e.needsGoto&&i.Then.push(Pa(t)),a.needsGoto&&i.Else.push(Pa(t))));break}case`Either`:{let e=i.ors.map((e,r)=>{let a=c(e,t);return i.ors[r]=a.stmts,n.labeledStmts.push(...a.labeledStmts),a});n.needsGoto=e.every(e=>e.needsGoto),!r&&!n.needsGoto&&e.forEach((e,n)=>{e.needsGoto&&i.ors[n].push(Pa(t))});break}case`With`:{let e=c(i.Do,t);i.Do=e.stmts,n.labeledStmts.push(...e.labeledStmts),n.needsGoto=e.needsGoto;break}default:n.needsGoto=!0}return r&&(n.needsGoto=!1),n},l=(e,t)=>{let n=c(e,t);return n.needsGoto&&n.stmts.push(Pa(t)),n},u=(e,t)=>{let n=e.stmts.at(0);if(n?.kind===`While`)return f(e,n,t);let i=l([...e.stmts],t),a=[];return r||(i.stmts.unshift(Na(e.label)),a.push({...U(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:i.stmts})),a.push(...i.labeledStmts),a},d=(e,t)=>e.flatMap((n,r)=>u(n,r<e.length-1?e[r+1].label:t)),f=(e,t,n)=>{let i=t.labDo.length===0?e.label:t.labDo[0].label,a=l([...t.unlabDo],i),o=l(e.stmts.slice(1),n),s=Ma(t.test),c=s?a.stmts:[{...U(),kind:`If`,test:t.test,Then:a.stmts,Else:o.stmts}];return[{...U(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:[...r?[]:[Na(e.label)],...c]},...d(t.labDo,e.label),...a.labeledStmts,...s?[]:o.labeledStmts]},p=(e,t)=>{let n=l(e.unlabThen,e.labThen.length===0?t:e.labThen[0].label),r=l(e.unlabElse,e.labElse.length===0?t:e.labElse[0].label),i=d(e.labThen,t);return i.push(...d(e.labElse,t)),i.push(...n.labeledStmts,...r.labeledStmts),{stmt:{...U(),kind:`If`,col:e.col,line:e.line,test:e.test,Then:n.stmts,Else:r.stmts},labeledStmts:i}},m=(e,t)=>{let n=[],r=[];return e.clauses.forEach(e=>{let i=l(e.unlabOr,e.labOr.length>0?e.labOr[0].label:t);n.push(i.stmts),r.push(...i.labeledStmts),r.push(...d(e.labOr,t))}),{stmt:{...U(),kind:`Either`,col:e.col,line:e.line,ors:n},labeledStmts:r}},h=(e,t)=>d(e.map(bi),t),g=e=>{i.procedure=e.name;let t=h(e.body,_a(n,W.label,`Error`,``));return i.procedure=void 0,{...U(),kind:`Procedure`,col:e.col,line:e.line,name:e.name,minusLabels:[],plusLabels:[],proceduresCalled:[],params:e.params,decls:e.decls,body:t}},_=e=>({...U(),kind:`Process`,col:e.col,line:e.line,name:e.name,fairness:0,minusLabels:[],plusLabels:[],proceduresCalled:[],isEq:e.isEq,id:e.id,decls:e.decls,body:h(e.body,`Done`)}),v=t.prcds.map(g);return t.kind===`Uniprocess`?{...U(),kind:`Uniprocess`,col:t.col,line:t.line,name:t.name,decls:t.decls,defs:t.defs,macros:[],prcds:v,body:h(t.body,`Done`)}:{...U(),kind:`Multiprocess`,col:t.col,line:t.line,name:t.name,decls:t.decls,defs:t.defs,macros:[],prcds:v,procs:t.procs.map(_)}},Va=(t,n)=>{let r=n?[]:[`pc`];if(r.push(...t.decls.map(e=>e.var)),t.prcds.length>0&&r.push(`stack`),t.prcds.forEach(e=>{r.push(...e.params.map(e=>e.var)),r.push(...e.decls.map(e=>e.var))}),t.kind===`Multiprocess`&&t.procs.forEach(e=>r.push(...e.decls.map(e=>e.var))),r.length===0)throw new e.rt(`The algorithm has no variables.`);let i=(e,t)=>{let n=r.indexOf(t);return n===-1?0:(e[n]+=1,e[n])},a=(e,t)=>t.forEach((t,n)=>{e[n]=Math.max(e[n],t)}),o=e=>[...e].sort((e,t)=>e.lhs.var<t.lhs.var?-1:+(e.lhs.var>t.lhs.var)),s=(t,n)=>{let s=[...n];t.ass=o(t.ass),new Set(t.ass.map(e=>e.lhs.var)).forEach(n=>{let a=t.ass.filter(e=>e.lhs.var===n);if(!r.includes(n))throw new e.rt(`Assignment to undeclared variable ${n}`,a[0]);let o=a.some(e=>e.lhs.sub.tokens.length===0);if(i(s,n)>1||a.length>1&&o)throw new e.rt(`Multiple assignment to ${n}`,t)}),a(n,s)},c=(t,n)=>{switch(t.kind){case`Assign`:s(t,n);return;case`If`:{let e=[...n],r=[...n];t.Then.forEach(t=>c(t,e)),t.Else.forEach(e=>c(e,r)),a(n,e),a(n,r);return}case`Either`:{let e=[...n];t.ors.forEach(t=>{let r=[...n];t.forEach(e=>c(e,r)),a(e,r)}),a(n,e);return}case`With`:t.Do.forEach(e=>c(e,n));return;case`When`:case`PrintS`:case`Assert`:case`Skip`:return;default:throw new e.nt(`Unexpected AST type ${t.kind}`)}},l=e=>e.forEach(e=>{let t=r.map(()=>0);bi(e).stmts.forEach(e=>c(e,t))});t.prcds.forEach(e=>l(e.body)),(t.kind===`Uniprocess`?[t.body]:t.procs.map(e=>e.body)).forEach(l)},Ha=(e,t,n,r)=>{let i=ya(e);ba(i),i.disambiguateReport.length>0&&r(`Warning: symbols were renamed.`),Sa(e,i,r),Va(Ba(e,i,t),t),n&&xa(i)},Ua=`[ \\t\\n\\x0B\\f\\r]`,Wa=RegExp(`\\\\\\* BEGIN TRANSLATION${Ua}+\\(${Ua}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${Ua}*(=${Ua}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${Ua}*STRING)${Ua}*\\/\\\\${Ua}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${Ua}*(=${Ua}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${Ua}*STRING)${Ua}*\\)`),Ga=e=>process.getBuiltinModule(`node:zlib`).crc32(Buffer.from(e,`utf8`)).toString(16),Ka=(e,t)=>e.log(`\nUnrecoverable error:\n -- ${t}.\n`),qa=(e,t)=>Ka(e,t.node===void 0||t.node.line===0?t.message:`${t.message}\n at ${yi(t.node)}`),Ja=e=>e.map(e=>`${Array.from(e).reduce((e,t)=>t===` `?e+` `.repeat(8-e.length%8):e+t,``)} `),Ya=(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},Xa=(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``},Za=(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},Qa=e=>/^[\p{L}\p{Nd}_]$/u.test(e),$a=(e,t,n)=>{for(;t.line<e.length;){let r=Xa(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=Za(r,e,` `),!0}t.column=Za(r,t.column,` `)}return!1},eo=(e,t)=>Ka(e,`Command-line error: ${t}`),to=(e,t)=>{let n=e.params,r={isFirst:!0,isExplicitNof:!1},i=t=>(r.isFirst&&=(n.fairnessOption=``,!1),n.fairnessOption===``?(n.fairnessOption=t,!0):(eo(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){eo(e,`
1342
- Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){eo(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){eo(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){eo(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){eo(e,"Version number must follow `-version' option");return}let t=_i(s);if(t<0||t>1903){Ka(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),eo(e,`Bad version number`);return}n.inputVersionNumber=t,a+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){eo(e,"Integer value at least 60 must follow `-lineWidth' option");return}a+=1;continue;default:eo(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!r.isExplicitNof&&(n.fairnessOption=`wf`)},no=(e,t,n)=>{if(Xa(t,n),n.column+=7,!Xa(t,n).slice(n.column).startsWith(`(`)){Ka(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=Xa(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=Za(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?Ka(e,`No closing ')' found in options statement`):to(e,r)},ro=(t,n,r)=>{let i={depth:0,isDone:!1,isInString:!1};for(let a=n;!i.isDone&&a<t.length;a++){let o=t[a],s=a===n?r:0,c=[o.slice(0,s)];i.isInString=!1;for(let e=s;!i.isDone&&e<o.length;e++){let t=o[e],n=o.slice(e,e+2);if(n===`(*`&&!i.isInString)i.depth+=1,c.push(` `),e+=1;else if(n===`*)`&&!i.isInString&&i.depth===0)c.push(n),i.isDone=!0;else if(n===`*)`&&!i.isInString)--i.depth,c.push(` `),e+=1;else if(i.depth>0)c.push(` `);else if(i.isInString&&t===`\\`&&n.length===2)c.push(n),e+=1;else{if(!i.isInString&&n===`\\*`){c.push(` `);break}t===`"`&&(i.isInString=!i.isInString),c.push(t)}}if(i.isInString)return new e.rt(`Unterminated string in line ${a+1}`);t[a]=c.join(``)}},io=(t,n)=>{let r=10*2**Math.max(0,Math.ceil(Math.log2(n/10)));throw new e.it(`java.lang.ArrayIndexOutOfBoundsException: Index ${t} out of bounds for length ${r}`)},ao=(t,n,r)=>{if(!n.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let i=Ja(n),a={line:0,column:0};for(;$a(i,a,`PlusCal`);){let e=Xa(i,a).slice(a.column),n=Array.from(e).findIndex(e=>!Qa(e));if(e.startsWith(`options`)&&(n===-1?e.length:n)===7){t.params.optionsInFile=!0,no(t,i,a);break}}let o={line:0,column:-1,isFound:!1,isFair:!1};for(;o.line<i.length;o.line++){let e=i[o.line];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){o.column=t+11,o.isFound=!0;break}if(n!==-1){o.column=n+6,o.isFound=!0,o.isFair=!0;break}}let s=/* @__PURE__ */ new Set,c=Ya(i,0,`BEGIN`,`TRANSLATION`);c===-1&&s.add(`NO_TRANSLATION_EXISTS`);let l=Ya(i,c+1,`END`,`TRANSLATION`);if(l===-1&&s.add(`NO_TRANSLATION_EXISTS`),c===-1&&l===-1)return s;if(!o.isFound)return s.add(`NO_PLUSCAL_EXISTS`),s;let u=ro(i,o.line,o.column);if(u!==void 0)return qa(t,u),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let d={ast:void 0};try{let e=Bi(i,o.line,o.column,n.length,0),r=la(t,e,o.isFair);d.ast=r.ast,Ha(r.ast,r.omitPC,r.hasDefaultInitialization,t.log)}catch(n){if(!(n instanceof e.rt))throw n;qa(t,n)}c===-1&&io(-1,i.length);let f=Wa.exec(i[c]);if(f===null)return s.add(`NO_PCAL_CHECKSUMS_EXIST`),s;let p=f.groups?.pcal,m=o.isFair&&r!==`1.7.4`?`fair`:d.ast===void 0?void 0:zi(d.ast,t.params.inputVersionNumber,r);p!==void 0&&(m===void 0||p!==Ga(m))&&s.add(`PCAL_DIVERGENCE_EXISTS`);let h=f.groups?.tla;if(h!==void 0){if(l===-1)throw new e.it(`java.lang.IllegalArgumentException: fromIndex(${c+1}) > toIndex(-1)`);let t=n.slice(c+1,l).join(``);h!==Ga(t)&&s.add(`TLA_DIVERGENCE_EXISTS`)}return s.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):s},oo=[[`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]]],so={file:`--TLA+ BUILTINS--`,beginLine:0,beginColumn:0,endLine:0,endColumn:0},G=e=>({id:e,levelChecked:0,level:0,levelParams:/* @__PURE__ */ new Set,allParams:/* @__PURE__ */ new Set,nonLeibnizParams:/* @__PURE__ */ new Set,argLevelParams:/* @__PURE__ */ new Map,levelCorrect:!0,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map}),co=e=>oo.map(([t,n,r,i,a])=>{let o=e(),s=n<0?void 0:Array.from({length:n},(t,n)=>({...G(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{...G(o),levelChecked:c?99:0,level:r,kind:`OpDef`,defKind:`BuiltIn`,name:t,arity:n,params:s,body:void 0,isLocal:!1,location:so,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}}),lo=(e,t)=>{let n=JSON.stringify(t);e.some(e=>JSON.stringify(e)===n)||e.push(t)},uo=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}`,fo=e=>e?.kind===`OpAppl`&&e.isAbsent===!0,po=e=>{let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;return t},mo=()=>({buckets:Array.from({length:11},()=>[]),count:0,threshold:8}),ho=(e,t)=>(e&2147483647)%t,go=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[ho(e.hash,t)].unshift(e));e.buckets=n,e.threshold=Math.floor(t*.75)},_o=(e,t,n=t)=>e.buckets[ho(po(n),e.buckets.length)].find(e=>e.key===t)?.value,vo=(e,t,n,r=t)=>{let i=po(r),a=e.buckets[ho(i,e.buckets.length)].find(e=>e.key===t);a?a.value=n:(e.count>=e.threshold&&go(e),e.buckets[ho(i,e.buckets.length)].unshift({hash:i,key:t,value:n}),e.count++)},yo=e=>e.buckets.toReversed().flatMap(e=>e.map(e=>e.value)),bo=`\0module `,xo=()=>({table:mo(),symbols:[]}),So=e=>e.kind===`Module`?bo+e.name:e.name,Co=(e,t)=>{vo(e.table,So(t),t,t.name),e.symbols.push(t)},wo=e=>e.kind===`ThmOrAssumpDef`?e.params.length:e.kind===`Module`?0:e.arity,To=(e,t)=>_o(e.table,t),Eo=(e,t)=>_o(e.table,bo+t,t),Do=e=>e.context.symbols.filter(e=>e.kind===`OpDef`&&e.defKind===`UserDefined`),Oo=(e,t)=>yo(e.context.table).filter(e=>e.kind===`OpDecl`&&e.declKind===t).toReversed(),ko=e=>e.context.symbols.filter(e=>e.kind===`ThmOrAssumpDef`),Ao=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),jo=e=>{let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},Mo=e=>{switch(e.kind){case`Identifier`:return jo(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=jo(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}}})}},No=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},Po=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,Fo=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,Io=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),Lo=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,Ro=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],zo=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},Bo=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):To(u.letInContext,p)),f===void 0&&(p!==void 0&&(u.name=p,u.nameLocation=zo(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: \`${Po(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=zo(u.nameLocation,l(u.index)),u.name=p,Io(f)&&t.length!==1)return e.addError(l(u.index),`Cannot take subexpression of \`${u.name}'.`);let h=wo(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 \`${Po(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
1343
- 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(Fo(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=Fo(f.op,a.length);if(o){let e=Fo(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=Fo(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=Ro(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=Fo(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(Fo(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=Fo(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
1344
- 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`?wo(f.op):u.previousMode===`FindingOpName`&&Lo(f)?wo(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:wo(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=Ao.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}.`)},Vo=/* @__PURE__ */ new Map([[`(`,`)`],[`[`,`]`],[`{`,`}`],[`<<`,`>>`]]),Ho=(e,t)=>`${e}:${t}`,Uo=(t,n)=>{let r=e.tt(n).filter(e=>e.kind!==`End`).map(e.et),i=[0,0];for(let e=0;e<n.length;e++)n[e]===`
1345
- `&&i.push(e+1);return{name:t,source:n,tokens:r,lineOffsets:i,tokenIndexes:new Map(r.map((e,t)=>[Ho(e.line,e.column),t]))}},K=(e,t,n)=>e.tokens[t]!==void 0&&e.tokens[t].text===n&&e.tokens[t].kind!==`String`,Wo=(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},Go=(e,t)=>e.tokenIndexes.get(Ho(t.line,t.column))??Math.min(Wo(e,t,!1),e.tokens.length-1),Ko=(e,t)=>Math.max(Wo(e,t,!0)-1,0),qo=(e,t)=>{let n=e.tokens[t].text,r=Vo.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},Jo=(e,t)=>({start:Go(e,t.start),end:Ko(e,t.end)}),q=(e,t)=>{let n=t.location.range;if(n)return Jo(e,n);let r=Go(e,t.location);return{start:r,end:qo(e,r)}},Yo=(e,t)=>{let n=t.start-1,r=t.end+1;return K(e,n,`(`)&&K(e,r,`)`)&&qo(e,n)===r?Yo(e,{start:n,end:r}):t},Xo=(e,t)=>{let n=t.start-1,r=t.end+1;return K(e,n,`(`)&&qo(e,n)===r&&(K(e,n-1,`(`)||K(e,n-1,`,`))?Xo(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}),Zo=(e,t)=>J(e,{start:t,end:t}),Qo=(t,n,r)=>{let i=0,a=t.lineOffsets[n];for(;a<t.source.length;){if(i=t.source[a]===` `?e.$(i):i+1,i>=r)return a;a++}return a},$o=(e,t)=>{let n=e.tokens[t],r=Qo(e,n.line,n.column);return e.source.slice(r,Qo(e,n.line,n.endColumn)+1)},es=(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},ts=t=>{let n=Uo(``,t),r=n.tokens.reduce((e,t,r)=>{if(!es(n,r))return e;let i=Qo(n,t.line,t.column);return`${e.slice(0,i)} ${e.slice(i+2)}`},t);if(r!==t&&e.D(t)!==void 0)throw new e.ft(`SANY rejects a []ASSUME or []PROVE outside an ASSUME/PROVE`);return r},ns=(e,t)=>{let n=e.tokens[t-1],r=e.tokens[t],i=n===void 0?0:Qo(e,n.line,n.endColumn)+1,a=e.source.slice(i,Qo(e,r.line,r.column)),o=[],s=0;for(;s<a.length;)if(a.startsWith(`\\*`,s)){let e=a.indexOf(`
1346
- `,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},rs=(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},is=(e,t,n,r)=>{for(let i=t;i<=n;i++)if(K(e,i,r))return i;return-1},as=new Map(e.O.flatMap(([e,...t])=>t.map(t=>[t,e]))),os=e=>e.split(`!`).map(e=>as.get(e)??(e===`~`?`\\lnot`:e)).join(`!`),ss={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}},cs=e=>/^[A-Za-z0-9_]+$/.test(e),ls=e=>e!==`!!`&&e.includes(`!`),us=e=>e.contexts[e.contexts.length-1],ds=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=To(e.contexts[n],t);if(r)return r}},fs=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,ps=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,ms=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||hs(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&hs(n.module)}return!1},hs=e=>Oo(e,2).length===0&&Oo(e,3).length===0,gs=t=>[...t.kind===`Let`?t.instances??[]:[],...e.W(t).flatMap(gs)],_s=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:_s(e)):gs(e),vs=(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},ys=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`?gs(e.definition.body):e.kind===`Theorem`&&s?_s(e.theorem.statement):e.kind===`Assumption`&&s?gs(e.assumption.expression):[]).map(e=>e.module).filter(e=>l(e)&&!vs(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}},bs=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),xs=/* @__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`]]),Ss=/* @__PURE__ */ new Set([`N_GeneralId`,`N_OpApplication`,`N_PrefixExpr`,`N_InfixExpr`,`N_PostfixExpr`,`N_FcnAppl`,`N_RecordComponent`]),Cs=/* @__PURE__ */ new Set([`'`,`^+`,`^*`,`^#`]),ws=(e,t)=>Cs.has(t)?`N_GenPostfixOp`:e.kind===`Lambda`||t===`~`||t===`-.`?`N_GenNonExpPrefixOp`:`N_GenInfixOp`,Ts=(t,n,r={})=>{let i=[],a=(e,t)=>lo(i,{location:e,text:t,isWarning:!1}),o=(e,t)=>lo(i,{location:e,text:t,isWarning:!0}),s={value:r.version===`1.7.4`?-1:0},c=()=>++s.value,l={id:0},u=(e,t)=>{let n=ds(e,t.name);if(n===t)return;if(n===void 0){Co(us(e),t);return}let i=t.kind===`FormalParam`||fs(n)!==fs(t)||wo(n)!==wo(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(i&&r.version===`1.7.4`)?a(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):i?a(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${uo(n.location)}.`):ms(t,n)||o(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${uo(n.location)}.`)};r.version!==`1.7.4`&&co(c);let d=co(c);c();let f=new Map(d.map(e=>[e.name,e])),p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=(t,n)=>{let i=n=>new e.dt(`Could not parse module ${t} from file ${t}.tla`,t,n),a=r.version===`1.7.4`?e.Q(n):void 0;if(a!==void 0)throw i(a);try{return e.T(ts(n))}catch(t){throw t instanceof e.ft?i(e.D(n)??`***Parse Error***\n${t.message}`):t}},g=(t,n,i)=>{let a=m.get(t);if(a)return a;if(n===void 0)throw new e.lt(t,i,r.version!==`1.7.4`);r.onParse?.(t);let o=h(t,n);if(o.name!==t)throw new e.dt(`File name '${t}' does not match the name '${o.name}' of the top level module it contains.`,void 0);let s={file:Uo(o.name,n),module:o};return m.set(t,s),s},_=[],v=/* @__PURE__ */ new Set,y=[],b=(t,r,i)=>{let a=y.indexOf(t);if(a!==-1)throw new e.dt(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...y.slice(a),t].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(v.has(t))return;v.add(t),y.push(t);let o=E(t,g(t,r,i).module);[...o.extendees,...o.instancees].forEach(e=>b(e,n(e),t)),y.pop(),_.push(t)},x=/* @__PURE__ */ new Set,S=(e,t)=>x.has(`${e} ${t}`),C=(e,t,n)=>{let r=m.get(e);if(!r||n.has(e))return;n.add(e);let i=E(e,r.module),a=i[t].find(t=>!S(e,t));if(a!==void 0)return{name:a,importer:e,namingModule:i.importers.get(a)??e};for(let r of[...i.extendees,...i.instancees]){let i=S(e,r)?C(r,t,n):void 0;if(i)return i}},w=e=>{g(e,t);let r=()=>C(e,`extendees`,/* @__PURE__ */ new Set)??C(e,`instancees`,/* @__PURE__ */ new Set);for(let e=r();e!==void 0;e=r())m.has(e.name)||g(e.name,n(e.name),e.namingModule),x.add(`${e.importer} ${e.name}`)},T=r.rootFileName??h(``,t).name,E=(e,t)=>{let n=ys(t);return e!==T||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};w(T),b(T,t);let ee=(t,n,i,s)=>{let d={curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSectionCount:0},m=[],h=[],g=[],_=[],v=/* @__PURE__ */ new WeakSet,y=()=>_.push({labels:/* @__PURE__ */ new Map,params:[]}),b=()=>_.pop()?.labels??/* @__PURE__ */ new Map,x={depth:0,isDeclared:[],goal:void 0,goalClause:0},S=/* @__PURE__ */ new WeakMap,C=/* @__PURE__ */ new WeakMap,w=e=>{let t=e.kind===`AssumeProve`?S.get(e):void 0;t&&(t.isInProof=!1)},T=e=>J(n,q(n,e)),E=e=>e.range?Jo(n,e.range):{start:Go(n,e),end:Go(n,e)},D={kind:`Module`,id:c(),name:t.name,location:J(n,E(t.location)),extendees:[],context:us(s),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 te=e=>{for(let t=s.contexts.length-1;t>=0;t--){let n=Eo(s.contexts[t],e);if(n?.kind===`Module`)return n}return p.get(e)},ne=t=>{let n=te(t);if(n===void 0)throw new e.ft(`Could not find module ${t}`);return n},O=(e,t)=>{s.contexts.push(e);let n=t();return s.contexts.pop(),n},k=(e,t,n,r)=>{let i={...G(c()),kind:`FormalParam`,name:e,arity:t,location:n};return r&&u(s,i),i},A=e=>({...G(c()),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=d.curLevel,d.unresolvedSum>0&&(e.recursiveSection=d.recursiveSectionCount,e.inRecursiveSection=d.unresolvedCount[d.curLevel]>0,D.opDefsInRecursiveSection.push(e))},j=(e,t,n,r={},i=c())=>({...G(i),kind:`OpAppl`,operator:e,operands:t,unbounded:r.unbounded,bounded:r.bounded,tupleOrs:r.tupleOrs,ranges:r.ranges??[],location:n}),ie=()=>({...j(M(`$Nop`),[],so,{},l.id),isNull:!0}),M=t=>{let n=f.get(t);if(!n)throw new e.pt(`SANY has no builtin operator ${t}`);return n},N=(e,t,n,r={})=>j(M(e),t,n,r),ae=(e,t)=>({...G(c()),kind:`String`,value:e,location:t}),oe=(e,t)=>({...G(c()),kind:`OpArg`,op:e,location:t}),se=(t,n)=>{let r=ds(s,os(t));if(r===void 0||r.kind===`Module`)throw new e.ft(`Unknown operator: \`${t}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},P=(e,t,n)=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`)return;let r=e.params??[];r.length===t.length?r.forEach((r,i)=>{let o=t[i];r.arity===0&&o.kind===`OpArg`&&a(n,`Operator used in argument number ${i+1} has incorrect number of arguments.`);let s=o.kind===`OpArg`&&wo(o.op)===r.arity&&!(o.op.kind===`OpDef`&&(o.op.params??[]).some(e=>e.arity>0));r.arity>0&&!s&&a(n,`Argument number ${i+1} to operator '${e.name}' \nshould be a ${r.arity}-parameter operator.`)}):a(n,`Wrong number of arguments (${t.length}) given to operator '${e.name}', \nwhich requires ${r.length} arguments.`)},F=Bo({version:r.version,resolveSymbol:e=>ds(s,e),resolveSynonym:os,generateExpression:e=>R(e),generateArgument:(e,t,n,r)=>ge(e,t,n,r),createOpAppl:(e,t,n)=>{let r=j(e,t,n);return P(e,t,n),r},createOpArg:oe,createFormalParam:(e,t,n)=>k(e,t,n,!1),createLambda:(e,t,r)=>A({name:`LAMBDA`,params:e,body:t,location:r,preComments:ns(n,Go(n,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>Be(`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:M,addError:(e,t)=>(a(e,t),ie()),isOutOfLabelScope:e=>{let t=C.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=S.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}}),I=(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=is(n,r.value,t.end,i);if(a===-1)return e;if(e.op===`Null`){let t=qo(n,a);return r.value=t+1,{...e,location:J(n,{start:a,end:t})}}r.value=a+1;let o=Zo(n,a);if(e.args===void 0||!K(n,a+1,`(`))return{...e,location:o};let s=qo(n,a+1);return r.value=s+1,{...e,location:o,argsLocation:J(n,{start:a+1,end:s})}})},ce=(t,r,i,a)=>{let o=Mo(t);if(o===void 0)throw new e.ft(`Expected a name, found ${t.kind}`);return F(I(o,q(n,t)),r,i,a,T(t))},le=t=>{let n=ce(t,0,!1,!1);if(n.kind!==`OpAppl`)throw new e.ft(`Expected an expression`);return n},ue=e=>{if(e.kind!==`OpAppl`)return;let t=m.find(t=>t.name===e.operator.name);t&&(t.node.operator=M(`$RecursiveFcnSpec`))},de=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},[]),fe=(e,t)=>ke(e,t,de(e).map(e=>R(e[0].set))),pe=(e,t)=>{let n=_.at(-1);n?.params.push(e);let r=R(t);return n?.params.pop(),r},L=e=>{let t=q(n,e),r=rs(n,t.start,t.end,e.params);return O(xo(),()=>{let i=e.params.map((e,t)=>k(e,0,Zo(n,r[t]),!0)),a=pe(i,e.body);return A({name:`LAMBDA`,params:i,body:a,location:J(n,t),preComments:ns(n,t.start)})})},me=e=>e.kind===`OperatorReference`?e.operator:e.kind===`Lambda`&&e.body.kind===`Apply`?e.body.operator:n.tokens[Go(n,e.location)].text,he=(t,n)=>{let r=T(t);if(t.kind===`Lambda`)return t.location.range===void 0?oe(se(me(t),r),r):oe(L(t),r);if(t.kind===`Identifier`||t.kind===`Subexpression`){let i=ce(t,n,!1,!1);if(i.kind!==`OpArg`)throw new e.ft(`Expected an operator argument at line ${r.beginLine}, column ${r.beginColumn}`);return i}if(t.kind===`OperatorReference`)return oe(se(t.operator,r),r);throw new e.ft(`An expression appears where an operator is required at line ${r.beginLine}`)},ge=(t,r,i,o)=>{let c=t.kind===`OpDef`&&(t.defKind===`UserDefined`||t.defKind===`ModuleInstance`)?t.params?.[r]?.arity??0:0;if(c===0)return R(i);let l=q(n,i),u=J(n,l),d=`${r+1} (counting from 1)`,f=Xo(n,l);if(f!==l||!bs.has(i.kind))return a(J(n,f),`An expression appears as argument number ${d} to operator '${t.name}', in a position an operator is required.`),ie();if(i.kind===`Identifier`||i.kind===`Subexpression`){let t=ce(i,c,!1,!1);if(t.kind===`OpArg`||t.kind===`OpAppl`)return t;throw new e.ft(`Expected an operator argument at ${uo(u)}`)}if(i.kind===`Lambda`&&i.location.range!==void 0){let e=L(i),n=wo(e);return n===c?oe(e,u):(a(o,`Lambda expression with arity ${n} used as argument ${r+1} of operator \`${t.name}', \nbut an operator of arity ${c} is required.`),ie())}let p=me(i),m=ds(s,os(p));if(m===void 0)return a(u,`Could not find declaration or definition of symbol '${p}'.`),ie();let h=wo(m);return h===c?oe(m,u):(a(o,`Operator with incorrect arity passed as argument. \nOperator '${m.name}' of arity ${h} is argument number ${d} to operator \`${uo(t.location)}', \nbut an operator of arity ${c} was expected.`),ie())},_e=e=>{let t=T(e);if(e.isBulleted)return N(e.kind===`And`?`$ConjList`:`$DisjList`,e.operands.map(R),t);let r=q(n,e),i=e.kind===`And`?`\\land`:`\\lor`,[a,...o]=e.operands;return o.reduce((e,t,a)=>{let s=Yo(n,q(n,t)),c=a===o.length-1?r.end:s.end;return N(i,[e,R(t)],J(n,{start:r.start,end:c}))},R(a))},ve=e=>{let t=q(n,e),r=e.arms.map((r,i)=>{let a=Yo(n,q(n,r.condition)),o=i===e.arms.length-1&&e.other===void 0,s=Yo(n,q(n,r.body)),c=[R(r.condition),R(r.body)];return N(`$Pair`,c,J(n,{start:a.start,end:o?t.end:s.end}))}),i=e.other;if(i){let e=Yo(n,q(n,i)),a=ye(e.start,`OTHER`);r.push(N(`$Pair`,[void 0,R(i)],J(n,{start:a,end:t.end})))}return N(`$Case`,r,J(n,t))},ye=(e,t)=>{for(let r=e;r>=0;r--)if(K(n,r,t))return r;return e},be=e=>{let t=q(n,e),r=J(n,t),i=[R(e.function)],a=N(`$Except`,i,r),o=q(n,e.function),s={value:is(n,o.end+1,t.end,`EXCEPT`)+1};return e.updates.forEach(e=>{let r=is(n,s.value,t.end,`!`),o=Yo(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=xe(l.value,e.name);return l.value=t+1,ae(e.name,Zo(n,t))}let r=is(n,l.value,t.end,`[`),i=qo(n,r);return l.value=i+1,e.args.length===1?R(e.args[0]):N(`$Tuple`,e.args.map(R),J(n,{start:r,end:i}))}),d=N(`$Seq`,u,c),f=N(`$Pair`,[d],c);g.push(f),h.push(a),f.operands.push(R(e.value)),g.pop(),h.pop(),i.push(f),s.value=o.end+1}),a},xe=(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},Se=(e,t)=>{let r=q(n,t),i={value:r.start+1},o=t.fields.map((e,r)=>{let o=xe(i.value,e.name),s=Yo(n,q(n,e.value));return i.value=s.end+1,t.fields.slice(0,r).some(t=>t.name===e.name)&&a(Zo(n,o),`Non-unique fields in constructor.`),N(`$Pair`,[ae(e.name,Zo(n,o)),R(e.value)],J(n,{start:o,end:s.end}))}),s=N(e,o,J(n,r));return D.records.push(s),s},Ce=e=>({line:n.tokens[e].line,column:n.tokens[e].column}),we=e=>{let t=[],r=e;for(;n.tokens[r]?.kind===`Identifier`;){let e=K(n,r+1,`(`)?qo(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:{...Ce(r),range:{module:n.name,start:Ce(r),end:Ce(e)}}}),!K(n,e+1,`,`))break;r=e+2}return t},Te=e=>{let t=[...e.definitions.map(e=>({unit:{kind:`Definition`,definition:e},span:Me(e)})),...(e.instances??[]).map(e=>({unit:{kind:`Instance`,instance:e},span:Me(e)}))],r=q(n,e).start,i=Yo(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:we(e+1)},span:{start:e,end:e}})}return[...t,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},Ee=e=>{let t=xo();return O(t,()=>{d.curLevel++,d.unresolvedCount[d.curLevel]=0;let n=[],r=[];Te(e).forEach(e=>{e.kind===`Recursive`?Le(e.declarations):e.kind===`Instance`?Ve(e.instance,n,r):e.definition.kind===`Function`?Fe(e.definition,n):Ne(e.definition,n)}),Re(),d.curLevel=Math.max(d.curLevel-1,0);let i=R(e.body);return{...G(c()),kind:`LetIn`,opDefs:n,instances:r,body:i,context:t,location:T(e)}})},De=e=>{let t=q(n,e),r=J(n,t);return O(xo(),()=>{let i=e.pattern,a=i.kind===`Name`?[i.name]:i.names;if(e.set===void 0){let o=rs(n,t.start,t.end,a),s=a.map((e,r)=>k(e,0,Zo(n,i.kind===`Name`?t.start:o[r]),!0)),c=pe(s,e.body);return N(`$UnboundedChoose`,[c],r,{unbounded:s})}let o=R(e.set),s=q(n,e.set),c=rs(n,t.start,s.start,a),l=a.map((e,t)=>k(e,0,Zo(n,c[t]),!0)),u=pe(l,e.body);return N(`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},Oe=e=>{if(cs(e.operator)||ls(e.operator)||e.args.length>2||ds(s,os(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=Yo(n,q(n,e.args[0])),i=e.args.length===1&&r.start!==t.start,a=i?t.start:r.end+1,o=$o(n,a);return{index:a,name:i&&o===`-`?`-.`:o,fixity:i?`prefix`:e.args.length===2?`infix`:`postfix`}},R=e=>{let t=T(e);switch(e.kind){case`Number`:return{...G(c()),kind:`Numeral`,value:Es(e.text??String(e.value)),location:t};case`Decimal`:{let[n,r]=e.text.split(`.`),i=BigInt(n+r),a=i<=9223372036854775807n;return{...G(c()),kind:`Decimal`,mantissa:i.toString(),exponent:String(a?-r.length:r.length),integralPart:n,fractionalPart:r,location:t}}case`String`:return ae(e.value,t);case`Identifier`:{let t=le(e);return ue(t),t}case`Apply`:{let r=Oe(e);if(r!==void 0)return a(Zo(n,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),a(t,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...ie(),isAbsent:!0};let i=le(e);return(ls(e.operator)||cs(e.operator))&&ue(i),i}case`Bracket`:return a(Zo(n,q(n,e).start),"Unsupported expression type `['."),{...ie(),isAbsent:!0};case`OperatorReference`:case`Lambda`:{let r=n.tokens[q(n,e).start].text;return a(t,r===`LAMBDA`?`LAMBDA expression used where an expression is required.`:`Unsupported expression type \`${ws(e,r)}'.`),{...ie(),isAbsent:!0}}case`And`:case`Or`:return _e(e);case`Prime`:return N(`'`,[R(e.expression)],t);case`Unchanged`:return N(`UNCHANGED`,[R(e.expression)],t);case`Enabled`:return N(`ENABLED`,[R(e.expression)],t);case`Always`:return N(`[]`,[R(e.expression)],t);case`Eventually`:return N(`<>`,[R(e.expression)],t);case`If`:return N(`$IfThenElse`,[R(e.condition),R(e.consequent),R(e.alternative)],t);case`Case`:return ve(e);case`Let`:return Ee(e);case`Forall`:case`Exists`:{let r=q(n,e);return O(xo(),()=>{let n=fe(e.bounds,r.start),i=pe(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=rs(n,r.start,i.start,e.names),o=e.isTemporal?e.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:e.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return O(xo(),()=>{let r=e.names.map((e,t)=>k(e,0,Zo(n,a[t]),!0)),i=pe(r,e.body);return N(o,[i],t,{unbounded:r})})}case`Choose`:return De(e);case`SetEnumeration`:return N(`$SetEnumerate`,e.elements.map(R),t);case`Tuple`:return N(`$Tuple`,e.elements.map(R),t);case`SetFilter`:{let r=R(e.bound.set),i=q(n,e);return O(xo(),()=>{let n=ke([e.bound],i.start,[r]),a=pe(n.bounded.flat(),e.predicate);return N(`$SubsetOf`,[a],t,n)})}case`SetMap`:{let r=q(n,e.expression);return O(xo(),()=>{let n=fe(e.bounds,r.end+1),i=pe(n.bounded.flat(),e.expression);return N(`$SetOfAll`,[i],t,n)})}case`FunctionConstruction`:{let r=q(n,e);return O(xo(),()=>{let n=fe(e.bounds,r.start),i=pe(n.bounded.flat(),e.body);return N(`$FcnConstructor`,[i],t,n)})}case`FunctionSet`:return N(`$SetOfFcns`,[R(e.domain),R(e.range)],t);case`Record`:return Se(`$RcdConstructor`,e);case`RecordSet`:return Se(`$SetOfRcds`,e);case`Except`:return be(e);case`ExceptAt`:{let e=h[h.length-1],n=g[g.length-1];return e===void 0||n===void 0?(a(t,`@ used where its meaning is not defined.`),ie()):{...G(c()),kind:`At`,except:e,component:n,location:n.location}}case`FunctionApplication`:{let n=R(e.function);if(fo(n))return n;ue(n);let r=e.args.length===1?R(e.args[0]):N(`$Tuple`,e.args.map(R),t);return N(`$FcnApply`,[n,r],t)}case`FieldAccess`:{let r=R(e.record),i=q(n,e);return N(`$RcdSelect`,[r,ae(e.field,Zo(n,i.end))],t)}case`Product`:return N(`$CartesianProd`,e.factors.map(R),t);case`BoxAction`:case`AngleAction`:return N(e.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[R(e.action),R(e.subscript)],t);case`WeakFairness`:case`StrongFairness`:return N(e.kind===`WeakFairness`?`$WF`:`$SF`,[R(e.subscript),R(e.action)],t);case`Label`:return Ae(e);case`Subexpression`:return le(e)}},ke=(e,t,r)=>{let i=de(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=rs(n,a.value,t.start,r);return a.value=t.end+1,r.map((e,t)=>k(e,0,Zo(n,i[t]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},Ae=e=>{let t=T(e),r=_.at(-1);if(r===void 0)return a(t,`Label not in definition or proof step.`),ie();if(x.isDeclared.slice(2,x.depth+1).some(Boolean))return a(t,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),ie();if(h.length>0&&g.length>0)return a(t,`Labels inside EXCEPT clauses are not yet implemented.`),ie();y();let i=R(e.body),o=b(),l=rs(n,q(n,e).start,q(n,e.body).start,e.params),u=e.params.map((t,r)=>{let i=ds(s,t);if(i?.kind===`FormalParam`)return i;let o=Zo(n,l[r]);return a(o,`Illegal parameter ${t} of label \`${e.name}'.`),k(t,0,o,!1)}),d={...G(c()),kind:`Label`,name:e.name,params:u,body:i,labels:o,isAssumeProve:!1,location:t},f=/* @__PURE__ */ new Set;if(u.forEach(e=>{f.has(e)&&a(t,`Repeated formal parameter ${e.name} \nin label \`${d.name}'.`),f.add(e)}),r.params.flat().forEach(e=>{f.delete(e)||a(t,`Label ${d.name} must contain formal parameter \`${e.name}'.`)}),f.size>0){let e=[...f].map(e=>`${e.name} `).join(``);a(t,`Label ${d.name} declares extra parameter(s) ${e}`)}r.labels.has(d.name)?a(t,`Duplicate label \`${d.name}'.`):r.labels.set(d.name,d);let p=x.goal;return p&&C.set(d,{scope:p,clause:x.goalClause}),d},je=(e,t,r)=>{let i={value:t.start};return e.params.map(e=>{let t=e.location?Go(n,e.location):xe(i.value,e.name),a=ut(t,e.arity);return i.value=a.end+1,k(os(e.name),e.arity,J(n,a),r)})},Me=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},Ne=(e,t)=>{let r=Me(e),i=J(n,r),o=os(e.name),c={start:e.isLocal?r.start+1:r.start,end:r.end},l=O(xo(),()=>{let t=je(e,c,!0),n=ds(s,o);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===d.curLevel?e||a(i,`Definition of ${n.name} has different arity than its RECURSIVE declaration.`):a(i,`Recursive operator ${o} defined at wrong LET/IN level.`)}else n!==void 0&&a(i,`Operator ${o} already defined or declared.`);return y(),{params:t,body:R(e.body),existing:n}}),f=b(),p=l.existing,m=l.params,h=ns(n,r.start);if(p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined&&p.letInLevel===d.curLevel){p.params=m,p.weights=m.map(()=>0),p.maxLevels=m.map(()=>3),p.isLeibnizArg=m.map(()=>!0),p.labels=f,Pe(p,l.body,i,h),D.definitions.push(p),t?.push(p);return}let g=A({name:o,params:m,body:l.body,isLocal:e.isLocal,location:i,preComments:h,labels:f});u(s,g),re(g),D.definitions.push(g),t?.push(g)},Pe=(e,t,n,r)=>{e.isDefined=!0,e.body=t,e.location=n,e.preComments=r,e.inRecursive&&(d.unresolvedCount[d.curLevel]--,d.unresolvedSum--)},Fe=(e,t)=>{let r=Me(e),i=J(n,r),o=xo(),c=e.isLocal?r.start+1:r.start,l=O(o,()=>fe(e.bounds,c+1)),f=ds(s,e.name),p=O(o,()=>k(e.name,0,i,f===void 0)),h=N(`$NonRecursiveFcnSpec`,[],i,{unbounded:[p],...l}),g=f?.kind===`OpDef`&&f.inRecursive&&!f.isDefined,_=g&&f.letInLevel===d.curLevel;_?f.arity!==0&&a(i,`Function ${f.name} has operator arguments in its RECURSIVE declaration.`):g?a(i,`Recursive function ${e.name} defined at wrong LET/IN level.`):f!==void 0&&a(i,`Function name \`${e.name}' already defined or declared.`);let v=ns(n,r.start),x=f===void 0?A({name:e.name,params:[],body:h,isLocal:e.isLocal,location:i,preComments:v}):f.kind===`OpDef`&&(_||!g)?f:void 0;_?f.arity===0&&Pe(f,h,i,v):f===void 0&&x!==void 0&&(u(s,x),re(x)),x!==void 0&&(D.definitions.push(x),t?.push(x)),m.unshift({name:e.name,node:h}),y();let S=()=>pe(l.bounded.flat(),e.body),C=x===void 0?S():O(o,S),w=b();x!==void 0&&(x.labels=w),m.shift(),h.operands=[C],h.operator.name===`$NonRecursiveFcnSpec`&&(h.unbounded=void 0)},Ie=[],Le=e=>{d.unresolvedSum===0&&d.recursiveSectionCount++,d.unresolvedCount[d.curLevel]+=e.length,d.unresolvedSum+=e.length,e.forEach(e=>{let t=dt(e);c();let r=Array.from({length:e.arity},()=>k(``,0,void 0,!1)),i=A({name:os(e.name),params:r,location:J(n,t),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:d.recursiveSectionCount,letInLevel:d.curLevel});u(s,i),Ie.push(i),D.opDefsInRecursiveSection.push(i)})},Re=()=>{d.unresolvedCount[d.curLevel]!==0&&(Ie.filter(e=>e.letInLevel===d.curLevel&&!e.isDefined).forEach(e=>a(e.location,`Symbol ${e.name} declared in RECURSIVE statement but not defined.`)),d.unresolvedSum-=d.unresolvedCount[d.curLevel])},ze=(e,t,i)=>{c();let o=yo(t.table).filter(e=>e.kind===`OpDecl`),l=o.flatMap(e=>{let t=ds(s,e.name);return t===void 0?[]:[{op:e,expr:e.declKind===3||e.declKind===2&&e.arity===0?j(t,[],i):oe(t,i),isImplicit:!0}]}),u=(e,t)=>{(t.kind===`OpArg`?wo(t.op):0)!==e.arity&&a(t.location,`An operator must be substituted for symbol '${e.name}', and it must have arity ${e.arity}.`)},d=Me(e),f={value:is(n,d.start,d.end,`WITH`)+1};return e.substitutions.forEach(e=>{let r=is(n,f.value,d.end,e.name);r!==-1&&(f.value=q(n,e.expression).end+1);let o=To(t,os(e.name));if(o?.kind!==`OpDecl`){a(r===-1?i:Zo(n,r),`Identifier '${r===-1?e.name:$o(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=o.arity===0?R(e.expression):he(e.expression,o.arity);u(o,s);let c=l.find(e=>e.op.name===o.name);c&&!c.isImplicit?a(T(e.expression),`Multiple substitutions for symbol '${o.name}' in substitution.`):c?(c.expr=s,c.isImplicit=!1):l.push({op:o,expr:s,isImplicit:!1})}),l.filter(e=>e.isImplicit&&r.version!==`1.7.4`).forEach(e=>u(e.op,e.expr)),o.filter(e=>!l.some(t=>t.op.name===e.name)).forEach(e=>a(i,`Substitution missing for symbol ${e.name} declared at ${uo(e.location)} \nand instantiated in module ${D.name}.`)),l},Be=(e,t,n,r,i,o=D)=>(fo(n)&&a(i,e===`SubstIn`?`Substitution error, probably due to error
1347
- in module being instantiated.`:`Substitution error, probably due to error in module being instantiated.`),{...G(c()),kind:e,substs:t,body:n,instantiatingModule:o,instantiatedModule:r,location:i}),Ve=(e,t,i)=>{let a=Me(e),o=J(n,a),l=ns(n,a.start),d=e.name??``,f=xo(),p=e.isLocal?a.start+1:a.start;e.params.length>0&&s.contexts.push(f);let m=je(e,{start:p,end:a.end},e.params.length>0),h=ne(e.module),g=h.context,_=ze(e,g,o);e.params.length>0&&s.contexts.pop(),yo(g.table).forEach(n=>{if(n.kind!==`OpDef`||n.isLocal||n.defKind!==`UserDefined`&&n.defKind!==`ModuleInstance`)return;let r=[...m,...n.params??[]],i=`${d}!${n.name}`,a=n.defKind===`UserDefined`?A({name:i,params:r,body:_.length>0&&n.body?Be(`SubstIn`,_,n.body,h,o):n.body,isLocal:e.isLocal,location:o,source:n.source??n,preComments:l,labels:n.labels}):A({defKind:`ModuleInstance`,name:i,params:r,isLocal:e.isLocal,location:o,module:n.module,source:n.source??n,preComments:l});u(s,a),n.defKind===`UserDefined`&&re(a),(t??D.definitions).push(a)}),yo(g.table).forEach(n=>{if(n.kind!==`ThmOrAssumpDef`||n.isLocal)return;let r=_.length>0?Be(`APSubstIn`,_,n.body,h,o):n.body,i={...G(c()),kind:`ThmOrAssumpDef`,name:`${d}!${n.name}`,isTheorem:n.isTheorem,body:r,params:[...m,...n.params],isLocal:e.isLocal,location:o,module:D,source:n.source??n,labels:n.labels,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]};u(s,i),(t??D.definitions).push(i)});let v={...G(c()),kind:`Instance`,name:d,isLocal:e.isLocal,params:m,module:h,substs:_,location:o};(i??D.topLevel).push(v);let y=A({defKind:`ModuleInstance`,name:d,params:m,isLocal:e.isLocal,location:o,preComments:l});u(s,y),r.version!==`1.7.4`&&t?.push(y)},He=(e,t=!0,r)=>{let i=Me(e),a=r??J(n,i),o=ns(n,i.start),l=ne(e.module),d=l.context,f=ze(e,d,a),p=e.isLocal,m=hs(l);yo(d.table).forEach(e=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`||e.isLocal)return;let t=(t,n)=>{let r=A({name:e.name,params:e.params,body:n,isLocal:p,location:a,module:t,source:e.source??e,preComments:o,labels:e.labels});return u(s,r),r},n=()=>(u(s,e),e),r=e.module===void 0||hs(e.module),i=m||r?p?t(e.module,e.body):n():t(D,e.body&&Be(`SubstIn`,f,e.body,l,a));D.definitions.push(i),re(i)}),yo(d.table).forEach(e=>{if(e.kind!==`ThmOrAssumpDef`||e.isLocal)return;let n=(t,n)=>{let r={...e,...G(c()),body:n,isLocal:p,location:a,module:t,source:e.source??e};return u(s,r),r},r=m?p?n(e.module,e.body):(u(s,e),e):hs(e.module)?p?n(D,e.body):e:n(D,Be(`APSubstIn`,f,e.body,l,a));t&&D.definitions.push(r)});let h={...G(c()),kind:`Instance`,name:void 0,isLocal:p,params:[],module:l,substs:f,location:a};return t&&D.topLevel.push(h),h},Ue=e=>{let t=te(e.name)??(e.name===D.name?D:void 0);return t===void 0?(a(Zo(n,Go(n,e.location)+1),`Module \`${e.name}' used without being extended or instantiated.`),[]):[t]},We=t=>t.flatMap(t=>{if(t.kind===`ModuleFact`)return Ue(t);let n=Mo(t);if(n===void 0||!No(n))return[R(t)];let r=ce(t,0,!0,!1);if(r.kind===`ThmOrAssumpDef`)throw new e.ft(`Expected a fact`);return[r]}),Ge=e=>K(n,e.start,`(`)&&qo(n,e.start)===e.end,Ke=e=>Yo(n,q(n,e)),qe=(e,t)=>Ke(e.args[0]).start===t.start?e.args.length===2?`N_InfixExpr`:`N_PostfixExpr`:n.tokens[t.start].kind===`Identifier`?`N_OpApplication`:`N_PrefixExpr`,Je=(e,t)=>Ge(t)?`N_ParenExpr`:e.kind===`String`?$o(n,t.start):e.kind===`Apply`?qe(e,t):xs.get(e.kind),Ye=(e,t)=>{if(e.kind===`String`&&!Ge(t))return!1;if(e.kind===`Identifier`&&!e.name.includes(`!`))return!0;let n=Je(e,t);return n===void 0||Ss.has(n)?void 0:!0},Xe=(e,t)=>{let r=(e,t=Ke(e))=>({last:t,lastKind:Je(e,t)});if(Ge(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:Ye(e.expression,Ke(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=Ke(t),i=r.end+1;return{hasChildlessFirstChild:Ye(t,r),last:{start:i,end:i},lastKind:n.tokens[i].text}}case`Apply`:{let n=qe(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=Ke(e.args[0]),a=i.end+1;return{hasChildlessFirstChild:Ye(e.args[0],i),last:{start:a,end:a},lastKind:n===`N_InfixExpr`?`N_GenInfixOp`:`N_GenPostfixOp`}}}},Ze=e=>{let t=Yo(n,q(n,e));if((e.kind===`Identifier`||e.kind===`Subexpression`||e.kind===`OperatorReference`)&&!Ge(t))return!1;let r=Xe(e,t);if(r?.hasChildlessFirstChild===void 0||r.lastKind===void 0)return!1;let i=J(n,r.last);return r.hasChildlessFirstChild&&a(J(n,t),`Was expecting a GeneralId.`),r.lastKind===`N_OpArgs`?a(i,"Selector `!(...)' should not have argument(s)."):(a(i,`Unexpected token found.`),a(i,`Need name or step number here, not \`${r.lastKind}'.`)),a(J(n,t),`DEF clause entry should describe a defined operator.`),!0},Qe=e=>e.flatMap(e=>{if(e.kind===`ModuleFact`)return Ue(e);if(Ze(e))return[];let t=ce(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]:(a(T(e),`DEF clause entry should describe a defined operator.`),[])}),$e=(e,t)=>{e.isOnly||e.facts.length+e.defs.length>0||a(t,`Empty BY, USE, or HIDE`)},et=e=>{let t=J(n,E(e.location));$e(e,t);let r=We(e.facts),i=Qe(e.defs);return r.length+i.length===0&&a(t,`Empty USE or HIDE statement.`),e.kind===`Hide`&&r.filter(e=>e.kind===`OpAppl`&&e.operator.kind!==`ThmOrAssumpDef`).forEach(e=>a(e.location,`The only expression allowed as a fact in a HIDE is
1348
- the name of a theorem, assumption, or step.`)),{...G(c()),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&&R(e.set),i=xe(t.start,e.name),a=ss[e.level],o={...G(c()),levelChecked:1,level:a.level,kind:`OpDecl`,name:os(e.name),arity:e.arity,declKind:a.declKind,location:J(n,ut(i,e.arity)),module:D};return u(s,o),{...G(c()),kind:`NewSymb`,declaration:o,set:r,location:J(n,t)}},nt=(e,t,r)=>{let i=E(e.location),o=es(n,i.start-1),l=q(n,e.conclusion).start,u=n.tokens.findLastIndex((e,t)=>t<l&&e.kind===`Keyword`&&e.text===`PROVE`),d=J(n,{start:o?i.start-1:i.start,end:i.start});o!==es(n,u-1)&&a(d,o?`[]ASSUME matched by PROVE instead of []PROVE`:`ASSUME matched by []PROVE instead of PROVE`);let f=c();t>1&&s.contexts.push(xo()),o&&s.contexts.some(e=>v.has(e))&&a(d,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),o||v.add(us(s));let p={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};x.depth=t,x.isDeclared[t]=!1,t===1&&(x.goal=r&&p,x.goalClause=0);let m=e.assumptions.map((e,n)=>{let r=e.kind===`NewSymbol`,i=e.kind===`AssumeProve`?nt(e,t+1):r?tt(e):R(e);return x.depth=t,r&&(x.isDeclared[t]=!0),p.isDeclaredBefore.push(p.isDeclaredBefore[n]||r),t===1&&x.goalClause++,i}),h=R(e.conclusion);t>1&&s.contexts.pop(),x.depth=t-1,t===1&&(x.goal=void 0);let g={...G(f),kind:`AssumeProve`,assumptions:m,goal:h,isSuffices:p.isSuffices,isBoxed:o,location:J(n,{start:o?i.start-1:i.start,end:i.end})};return S.set(g,p),g},rt=(e,t,n,r,i,a=!0)=>({...G(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`&&$e(e,t);let r=e.kind===`By`?We(e.facts):[],i=e.kind===`By`?Qe(e.defs):[];return e.kind===`By`&&c(),e.kind===`By`&&r.length+i.length===0&&a(t,`Empty BY`),{...G(c()),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`,[R(r.expression)],i),isPick:!1};case`Case`:return{node:N(`$Pfcase`,[R(r.expression)],i),isPick:!1};case`Witness`:return{node:N(`$Witness`,r.expressions.map(R),i),isPick:!1};case`Qed`:return{node:N(`$Qed`,[],i),isPick:!1};case`Take`:case`Pick`:{let e=r.kind===`Pick`,a=e?`$Pick`:`$Take`;e&&s.contexts.push(xo());let o=e=>r.kind===`Pick`?[pe(e,r.body)]:[];if(r.bounds.length>0){let n=fe(r.bounds,t.start),s=o(n.bounded.flat());return{node:N(a,s,i,n),isPick:e}}let c=rs(n,t.start,t.end+1,r.names),l=r.names.map((e,t)=>k(e,0,Zo(n,c[t]),!0)),u=o(l);return{node:N(a,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=Yo(n,q(n,e.args[0])),r=q(n,e).start;return t.start===r&&!K(n,t.end+1,`(`)},st=t=>{if(t.kind!==`Steps`)return it(t);let r=xo();s.contexts.push(r);let i=[],a=[],o={previousRight:void 0},l=(t,r,a)=>{if(t.kind===`Define`){let r=t.definitions.map(t=>{let n=[];t.kind===`Instance`?Ve(t,n,i):t.kind===`Function`?Fe(t,n):Ne(t,n);let r=n[t.kind===`Instance`?n.length-1:0];if(r?.kind!==`OpDef`)throw new e.ft(`A DEFINE step defines no operator`);return r});return{...G(c()),kind:`DefStep`,defs:r,location:J(n,a)}}if(t.kind===`Use`||t.kind===`Hide`)return{...et(t),location:J(n,r)};if(t.kind===`Instance`)return He(t,!1,J(n,a))},d=t.steps.map(t=>{let r=E(t.location),i=Jo(n,t.head),d={start:i.start+1,end:i.end},f=t.body;t.name!==void 0&&y();let p=t.name===void 0?void 0:c();f.kind!==`Assert`&&(o.previousRight=void 0);let m=l(f,r,d);if(m!==void 0)return t.name!==void 0&&u(s,A({defKind:`NumberedProofStep`,name:t.name,location:J(n,r),labels:b(),step:m})),m;let h=f.kind===`Assert`&&f.statement.kind===`AssumeProve`;h&&(o.previousRight=void 0);let g=f.kind===`Assert`&&f.isSuffices,_=xo(),v=f.kind===`Assert`?{node:(e=>{if(e.kind===`AssumeProve`){let n=O(_,()=>nt(e,1,t.name===void 0?void 0:{isSuffices:g}));return n.isSuffices=g,n}if(g){let t=R(e);return N(`$Suffices`,[t],J(n,d))}let r=o.previousRight,i=r!==void 0&&e.kind===`Apply`&&ot(e)&&e.args[0].kind===`ExceptAt`,a=i?R(e.args[1]):void 0,s=i?j(se(e.operator,T(e)),[N(`$Nop`,[r],T(e.args[0])),a],T(e)):R(e),c=s.kind===`OpAppl`?s.operands[1]:void 0;return o.previousRight=ot(e)?c:void 0,s})(f.statement),isPick:!1}:at(t,d);if(v===void 0)throw new e.ft(`Unexpected proof step ${f.kind}`);let x=v.isPick?s.contexts.pop():void 0,S=t.name===void 0||p===void 0?void 0:rt(p,t.name,v.node,Zo(n,Go(n,t.location)),b());S&&u(s,S);let C=h&&!g;C&&s.contexts.push(_);let ee=t.proof&&st(t.proof);return C&&s.contexts.pop(),w(v.node),h&&g&&(a.push(_),s.contexts.push(_)),x?.symbols.forEach(e=>u(s,e)),{...G(c()),kind:`Theorem`,definition:S,body:v.node,proof:ee,isSuffices:g,location:J(n,r)}});return a.forEach(()=>{s.contexts.pop()?.symbols.forEach(e=>Co(r,e))}),s.contexts.pop(),{...G(c()),kind:`NonLeafProof`,steps:d,instances:i,proofLevel:t.level,location:J(n,E(t.location))}},ct=e=>{let t=J(n,E(e.location)),r=e.statement,i=xo();e.name!==void 0&&y();let a=e.name===void 0?void 0:c();r.kind===`AssumeProve`&&s.contexts.push(i);let o=r.kind===`AssumeProve`?nt(r,1,e.name===void 0?void 0:{isSuffices:!1}):R(r),l=e.name===void 0||a===void 0?void 0:rt(a,e.name,o,t,b());l&&(r.kind===`AssumeProve`&&s.contexts.pop(),u(s,l),D.definitions.push(l),r.kind===`AssumeProve`&&s.contexts.push(i));let d=e.proof&&st(e.proof);r.kind===`AssumeProve`&&s.contexts.pop(),w(o);let f={...G(c()),kind:`Theorem`,definition:l,body:o,proof:d,isSuffices:!1,location:t};D.topLevel.push(f)},lt=e=>{let t=E(e.location),r=J(n,t);e.name!==void 0&&y();let i=R(e.expression),a=e.name===void 0?void 0:rt(c(),e.name,i,r,b(),!1);a&&(u(s,a),D.definitions.push(a));let o={...G(c()),kind:`Assume`,definition:a,body:i,location:r};D.topLevel.push(o)},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:qo(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&&a(J(n,r),`Attempted to declare '@' as a variable.`);let i={...G(c()),levelChecked:1,level:+(t===3),kind:`OpDecl`,name:os(e.name),arity:e.arity,declKind:t,location:J(n,r),module:D};return t===2&&(i.levelParams.add(i),i.allParams.add(i)),u(s,i),i};t.extends.forEach(e=>{let t=ne(e);D.extendees.push(t);let n=us(s);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?Eo(n,e.name):To(n,e.name);t===void 0?Co(n,e):t!==e&&t.kind!==e.kind?a(e.location,`The ${ps(e)} of '${e.name}' conflicts with \nits ${ps(t)} at ${uo(t.location)}.`):t!==e&&!ms(t,e)&&o(e.location,`Warning: the ${ps(t)} of '${e.name}' conflicts with \nits ${ps(t)} at ${uo(t.location)}.`)}),D.topLevel.push(...t.topLevel)});let pt=(e,t)=>{d.unresolvedSum!==0&&a(J(n,E(e)),`${t} may not appear within a recursive definition section.`)};return t.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`:Le(e.declarations);break;case`Definition`:e.definition.kind===`Function`?Fe(e.definition,void 0):Ne(e.definition,void 0);break;case`Instance`:e.instance.name===void 0?He(e.instance):Ve(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:[...s.contexts,xo()]},r=ee(e.module,n,D,t),i=te(r.name);i===void 0?Co(us(s),r):i!==r&&a(r.location,`Multiply-defined module '${r.name}': this definition or declaration conflicts \nwith the one at ${uo(i.location)}.`);break}}}),Re(),D},D=_.map(e=>{r.onAnalyze?.(e),l.id=Array.from({length:4},c)[1];let t=g(e,void 0),n=xo();d.toReversed().forEach(e=>Co(n,e));let a=ee(t.module,t.file,void 0,{contexts:[n]});return p.set(e,a),r.onModule?.(a,i),a});return{root:D[D.length-1],modules:D,messages:i}},Es=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()},Ds=(e,t,n,r)=>lo(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)},Os=(e,t,n)=>`${e.id}:${t}:${n.id}`,ks=(e,t,n,r)=>{e.set(Os(t,n,r),{op:t,index:n,param:r})},As=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},js=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},Ms=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&js(e,r,t)})},Ns=(e,t)=>`${e.id}:${t}`,Ps=(e,t,n,r)=>{let i=Ns(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},Fs=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&Ps(e,t.param,t.position,t.level)})},Is=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},Ls=(e,t)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Ms(e.levelConstraints,t.levelConstraints),Fs(e.argLevelConstraints,t.argLevelConstraints),As(e.argLevelParams,t.argLevelParams)},Rs=(e,t)=>t.includes(e.op)||t.includes(e.param),zs=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,Bs=e=>e.kind!==`Module`,Vs=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,Hs=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,Us=(e,t)=>e.kind===`OpDef`?e.weights[Hs(e,t)]??0:0,Ws=(e,t)=>e.maxLevels[Hs(e,t)]??3,Gs=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,Ks=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[Hs(e,t)]??!0:e.isLeibnizArg[t]??!0,qs=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,Js=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],Ys=(e,t)=>t.find(t=>t.op===e)?.expr,Xs=(e,t,n)=>{let r=Ys(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},Zs=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=Ys(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!zs(i.op))return;let a=i.op;Xs(e.param,t,!1).forEach(t=>ks(n,a,e.index,t))}),n},Qs=(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;Xs(r,t,!1).forEach(e=>js(a,e,i))}),e.argLevelParams.forEach(e=>{let n=Ys(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;X(n.op,r,i);let o=Ws(n.op,e.index);Xs(e.param,t,!1).forEach(e=>js(a,e,o))}),a},$s=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=Ys(e.param,t);n===void 0?Ps(i,e.param,e.position,e.level):n.kind===`OpArg`&&zs(n.op)&&Ps(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=Ys(e.param,t);if(a===void 0)return;let o=Ys(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&zs(s)&&(X(a,n,r),Ps(i,s,e.index,a.level))}),i},ec=(e,t)=>Oo(e,3).length>0||(lc(e,t),Do(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),tc=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(Ns(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(Os(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(Ns(t,n))}),As(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},nc=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>Ws(t,o)&&(n&&X(a,r,i)&&Ds(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`||!Vs(a.op)))return;let s=a.op;X(s,r,i);let c=wo(s);for(let l=0;l<c;l++){let c=Gs(t,o,l);Ws(s,l)>=c||(n&&X(a,r,i)&&Ds(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||!qs(t,o,l,u)||n.level<=Ws(s,u)||(X(a,r,i)&&X(n,r,i)&&Ds(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&&Ds(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${uo(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},rc=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);Ms(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&Ms(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>Ms(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=Ws(t,r);n?.levelParams.forEach(t=>js(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!Vs(n.op))return;let o=n.op;X(o,r,i);let s=wo(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!qs(t,a,r,i))continue;let s=Ws(o,i);n?.levelParams.forEach(t=>js(e.levelConstraints,t,s)),!o.isLeibniz&&!Ks(o,i)&&n&&Y(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&Vs(n.op)&&(X(n.op,r,i),js(e.levelConstraints,t.param,Ws(n.op,t.index)))}),Fs(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&Fs(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>Fs(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!zs(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)Ps(e.argLevelConstraints,i,n,Gs(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&qs(t,r,a,o)&&Ps(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(X(n,r,i),Ps(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&As(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>As(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=>ks(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&zs(a.op)&&ks(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!zs(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&qs(t,r,a,o)&&n.levelParams.forEach(t=>ks(e.argLevelParams,i,o,t))})})},ic=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),ac=(e,t)=>{let n=(n,r)=>{Ds(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=ic.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.`)})},oc=(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(Vs(i)){let r=X(i,t,n);nc(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&Us(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&&(Us(i,n)===1&&Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),Ks(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(Js(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),rc(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),Ms(e.levelConstraints,t.levelConstraints),Ps(e.argLevelConstraints,i,n,t.level),Fs(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>ks(e.argLevelParams,i,n,t)),As(e.argLevelParams,t.argLevelParams)});return ac(e,n),e.levelCorrect},sc=(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))}),tc(e,i,r),e.levelCorrect},cc=(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)}),tc(e,e.params,e.body)),e.levelCorrect),lc=(e,t)=>{if(e.isLevelChecked)return e.levelCorrect;e.isLevelChecked=!0;let n=e.opDefsInRecursiveSection,r=0;for(;r<n.length;){let e=n[r].recursiveSection,i=r;for(;i<n.length&&n[i].recursiveSection===e;){let e=n[i];e.inRecursive?(e.levelChecked=1,e.maxLevels=e.maxLevels.map(()=>2),e.weights=e.weights.map(()=>1)):e.levelChecked=0,i++}let a=n.slice(r,i),o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=0;a.forEach(e=>{e.inRecursive&&(e.levelChecked=0),sc(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||Ds(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),sc(e,2,t)}),r=i}e.levelCorrect=!0;let i=t=>{t||(e.levelCorrect=!1)};e.definitions.filter(e=>e.kind===`Module`).forEach(e=>i(lc(e,t)));let a=Do(e);return a.forEach(e=>i(sc(e,1,t))),ko(e).forEach(e=>i(cc(e,1,t))),e.topLevel.forEach(e=>i(X(e,1,t))),ec(e,t)||Oo(e,2).forEach(t=>js(e.levelConstraints,t,0)),a.forEach(t=>{Ms(e.levelConstraints,t.levelConstraints),Fs(e.argLevelConstraints,t.argLevelConstraints),As(e.argLevelParams,t.argLevelParams,e=>!Rs(e,t.params??[]))}),e.topLevel.forEach(t=>{Ms(e.levelConstraints,t.levelConstraints),Fs(e.argLevelConstraints,t.argLevelConstraints),As(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},uc=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{Bs(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=X(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),Ls(e,t),Y(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),dc=(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&&Ds(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&Ds(t,e.body.location,`Non-constant CASE for temporal goal.`),dc(e.proof,t)):n===`$Qed`&&dc(e.proof,t)})},fc=(e,t,n,r,i,a)=>{e.levelConstraints=Qs(t,n,r,i,a),e.argLevelConstraints=$s(t,n,i,a),e.argLevelParams=Zs(t.argLevelParams,n)},pc=(e,t,n)=>{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelParams=/* @__PURE__ */ new Set,e.levelCorrect=!0;let r=e.module;lc(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(r.expr,t,n)||(e.levelCorrect=!1)});let i=ec(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(X(a.expr,t,n)&&Ds(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||Ds(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)&&Ds(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(Ns(i.op,t))?.level;a===void 0||Ws(o,t)>=a||(s&&Ds(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=Ws(s,i.index);o.expr.level<=l||(c&&X(o.expr,t,n)&&Ds(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 Ms(e.levelConstraints,Qs(r,e.substs,i,t,n),a),e.substs.forEach(t=>Ms(e.levelConstraints,t.expr.levelConstraints,a)),Fs(e.argLevelConstraints,$s(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>Fs(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),As(e.argLevelParams,Zs(r.argLevelParams,e.substs),t=>!Rs(t,e.params)),e.substs.forEach(t=>As(e.argLevelParams,t.expr.argLevelParams,t=>!Rs(t,e.params))),e.levelCorrect},X=(e,t,n)=>{if(!Bs(e))return lc(e,n);switch(e.kind){case`OpAppl`:return oc(e,t,n);case`OpDef`:return sc(e,t,n);case`ThmOrAssumpDef`:return cc(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,Is(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),Ms(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>Ms(e.levelConstraints,t.levelConstraints)),Fs(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>Fs(e.argLevelConstraints,t.argLevelConstraints)),As(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];As(e.argLevelParams,t.argLevelParams,e=>!Rs(e,n))}),e.instances.forEach(t=>As(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,Is(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=>Ls(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,Xs(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>Y(e.allParams,Xs(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=ec(e.instantiatedModule,n);return fc(e,r,e.substs,i,t,n),e.levelCorrect}case`Instance`:return pc(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,Is(e,e.body),e.level!==0&&Ds(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=uc(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&&Ds(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&dc(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return uc(e,e.facts,t,n);case`NonLeafProof`:return uc(e,[...e.steps,...e.instances],t,n);case`DefStep`:return uc(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,Ds(n,e.location,`Level error:
1349
- Temporal formula used as set.`)),Is(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=>Ls(e,t)),e.levelCorrect&&e.levelParams.forEach(t=>{t.kind===`OpDecl`&&t.declKind===2&&js(e.levelConstraints,t,2)})),e.levelCorrect}},mc=e=>{switch(e.kind){case`OpAppl`:return[...e.ranges,...e.operands];case`OpDef`:case`ThmOrAssumpDef`:case`Label`:return[e.body];case`LetIn`:return[...e.opDefs,...e.instances,e.body];case`SubstIn`:case`APSubstIn`:return[e.body,...e.substs.map(e=>e.expr)];case`Instance`:return e.substs.map(e=>e.expr);case`AssumeProve`:return[...e.assumptions,e.goal];case`NewSymb`:return[e.set];default:return[]}},hc=/* @__PURE__ */ new Map([[`Integers`,`Int`],[`Naturals`,`Nat`],[`Reals`,`Reals`]]),gc=e=>{let t=/* @__PURE__ */ new Set,n=e=>{if(e===void 0||t.has(e))return!1;if(t.add(e),e.kind===`OpAppl`){let t=e.operator;if(t.kind===`OpDecl`||t.kind===`FormalParam`)return!0;if(t.kind===`OpDef`){if(t.name===`BOOLEAN`)return!0;let e=t.module?.name;if(e!==void 0&&hc.get(e)===t.name||n(t))return!0}}return mc(e).some(n)};return n(e)},_c=e=>e.operands.filter(e=>e?.kind===`OpAppl`),vc=e=>{let t=e.operands[0];return t?.kind===`String`?t:void 0},yc=(e,t)=>{if(e===t)return!0;if(e.operands.length!==t.operands.length)return!1;let n=new Set(_c(t).map(e=>vc(e)?.value));return _c(e).every(e=>n.has(vc(e)?.value))},bc=(e,t=/* @__PURE__ */ new Set)=>(e.extendees.forEach(e=>{t.has(e)||(t.add(e),bc(e,t))}),t),xc=e=>{let t=[...[...bc(e)].flatMap(e=>e.records),...e.records];return e.records.flatMap(n=>t.filter(e=>yc(e,n)).flatMap(_c).some(gc)?[]:_c(n).flatMap(t=>{let n=vc(t),r=n&&To(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 ${uo(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}]}))},Sc=e=>`${uo(e.location)}\n\n${e.text}`,Cc=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=>`${Sc(e)}\n\n\n`),n.length>0?`*** Warnings: ${n.length}\n\n`:``,...n.map(e=>`${Sc(e)}\n\n\n`)].join(``)},wc=/* @__PURE__ */ new Set([`FiniteSets`,`Sequences`,`Bags`,`Naturals`,`Integers`,`Reals`,`RealTime`,`Randomization`,`TLC`]),Tc=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))},Ec=t=>{try{return e.T(ts(t))}catch(t){if(t instanceof e.ft)return;throw t}},Dc=(t,n)=>n===`1.7.4`&&e.Q(t)!==void 0?void 0:Ec(t)?.name,Oc=(t,i=()=>void 0,a={})=>{let o=(0,n.basename)(t,`.tla`),s=mi(a.version),c=a.fileName??o,l=(0,r.existsSync)(t)?(0,r.readFileSync)(t,`utf8`):s.get(o),u=[],d=e=>{u.push(e),a.onPrint?.(e)},f=e=>d(`${e}\n`),p=a.version===`1.7.4`,m=p&&a.isXmlExport,h=e=>{a.isXmlExport||f(e)},g=a.describeFile,_=/* @__PURE__ */ new Map([[o,(0,r.existsSync)(t)?`file`:`standard`]]),v={value:!1},y=[],b={isReported:!1,isAborted:!1},x=ia(gi(),f),S=/* @__PURE__ */ new Map,C=[],w=()=>C.splice(0).forEach(e=>e.isError?a.onPrintError?.(`${e.text}\n`):f(e.text)),T=e=>{let t=S.get(e),n=t?.module.location.range;if(t===void 0||n===void 0)return;let r=t.text.split(/\r\n|\r|\n/),i=ao(x,r.slice(n.start.line-1,n.end.line),a.version),o=i.has(`TLA_DIVERGENCE_EXISTS`),s=i.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(p){let t=o&&s?`The PlusCal algorithm and its TLA+ translation in module ${e} filename since the last translation.`:c;t===void 0?i.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??(i.has(`ERROR_ENCOUNTERED`)?`An unexpected problem was encountered attempting to validate the specification for ${e}`:void 0);if(l===void 0)return;let u=!i.has(`ERROR_ENCOUNTERED`)||o||s;y.some(e=>e.text===l)||y.push({location:e,text:l,isWarning:u})},E=(e,t)=>{if(a.isXmlExport||S.has(e))return;let n=Ec(t);if(n===void 0||n.name!==e)return;let r=[...S.values()].filter(t=>Tc(t.module).includes(e));S.set(e,{text:t,module:n}),r.forEach(()=>T(e)),Tc(n).filter(t=>t!==e&&S.has(t)).forEach(T)},ee=()=>{if(w(),b.isReported)return;b.isReported=!0;let e=y.filter(e=>e.isWarning);e.length>0&&(h(`Warnings (${e.length}) during syntax parsing of ${c}:\n\n`),e.forEach(e=>h(`${Sc(e)}\n\n\n`))),e.length!==y.length&&(f(Cc(y)),v.value=!0,b.isAborted=!0)},D=t=>{let n=s.get(t),r=i(t),a=r===void 0&&n===void 0&&l!==void 0&&!p?e.C(l,t):void 0,o=r??a;return _.set(t,r===void 0?a===void 0?`standard`:`root file`:`file`),o!==void 0&&E(t,o),o??n},te=(()=>{try{if(l===void 0)throw new e.dt(`Cannot find source file for module ${c}`,void 0);return E(o,l),Ts(l,D,{rootFileName:o,version:a.version,rootExtendees:a.rootExtendees,onParse:e=>{g&&f(`Parsing file ${g(e,_.get(e)??`file`)}`),e===o&&T(o),w()},onAnalyze:e=>{ee(),(g||m)&&!b.isAborted&&f(`Semantic processing of module ${e}`)},onModule:(e,t)=>{if(b.isAborted||(t.every(e=>e.isWarning)&&lc(e,{messages:t,isTlc174:p}),t.length===0))return;if(t.some(e=>!e.isWarning)&&(v.value=!0),p)return f(`Semantic errors:\n\n${Cc(t)}`);let n=t.filter(e=>e.isWarning);n.length>0&&(h(`*** Warnings: ${n.length}\n`),n.forEach(e=>h(`${Sc(e)}\n\n\n`)));let r=t.filter(e=>!e.isWarning);r.length!==0&&(f(`Semantic errors:\n\n*** Errors: ${r.length}\n`),r.forEach(e=>f(`${Sc(e)}\n\n`)))}})}catch(t){if(v.value=!0,t instanceof e.it){f(`\nFatal errors while parsing TLA+ spec in file ${c}\n`),f(t.message),f(Cc(y));return}if(!(t instanceof e.dt))throw t;let n={location:t.location,text:t.message,isWarning:!1},r=p&&t.parseError?.includes(` and token "" `);if(t.parseError!==void 0&&!r&&!m&&f(t.parseError),f(`\nFatal errors while parsing TLA+ spec in file ${c}\n`),r){f(`java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null`);return}if(p){f(`tla2sany.semantic.AbortException`),d(`*** Abort messages: 1\n\n${Sc(n)}\n\n\n`);return}f(Sc(n)),f(Cc(b.isReported?[n]:[...y,n]))}})();if(te!==void 0&&ee(),te!==void 0&&!v.value&&!a.isXmlExport&&!p){let e=te.modules.filter(e=>!wc.has(e.name));g&&e.forEach(e=>f(`Linting of module ${e.name}`)),e.flatMap(xc).forEach(e=>f(`${Sc(e)}\n\n\n`))}return{text:u.join(``),isFailed:v.value,specification:b.isAborted?void 0:te}},kc={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},Ac=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:[]}),jc={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,"\r":`&#13;`},Mc=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:jc[e]),Nc=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,Pc=e=>{let t=(e.cdata??e.text)?.match(Nc)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=Pc(t);if(e)return e}},Fc=(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}>${Mc(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)Fc(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},Ic=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)]),Lc=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)`}},Rc={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)`}}},zc={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},Bc=uo(`--TLA+ BUILTINS--`),Vc=(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}]},Hc=(e,t=16)=>e>t*.75?Hc(e,t*2):t,Uc=(e,t)=>(e^e>>>16)&t-1,Wc=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},Gc=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),Kc=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,qc=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=Wc(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(Kc,``)}).join(`
1350
- `)},Jc=e=>{let t=Wc(e),n=e=>Gc(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(`
1351
- `)},Yc=(t,n,r)=>{let i=r.version===`1.7.4`,a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Map,s={isSet:!1},c=[],l=(e,t)=>{if(!i)return t();c.push(...e);let n=t();return c.length-=e.length,n},u=(t,n)=>{let r=[...c,...n].reverse(),i=[t,...r.map(e=>`\tat tla2sany.${e.at}`)].join(`
1352
- `),a=r.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${i}\n`).join(``);return e.yt(new e.ct(i,a),kc.uncaughtException)},d=e=>u(`java.lang.NullPointerException: Cannot invoke "tla2sany.semantic.${e.nullType}.export(org.w3c.dom.Document, tla2sany.xml.SymbolContext)" because ${e.nullValue} is null`,[e]),f=(e,t)=>(a.has(e.id)||(a.add(e.id),o.set(e.id,l([...t?[t]:[],...Vc(e.kind,uo(e.location))],()=>g(e)))),Z(Lc(e),[Q(`UID`,e.id)])),p=(e,t,n)=>{let r=t.levelChecked===0?[]:[Q(`level`,t.level)],i=n?[Ic(n),...r]:r;return{...e,children:[...i,...e.children]}},m=(e,t,n)=>Z(`params`,e.map((e,r)=>Z(`leibnizparam`,[f(e,n),...t?.[r]?[Z(`leibniz`)]:[]]))),h=e=>{let t=e.map(e=>e.trimEnd()).filter(e=>e.length>0).join(`
1353
- `),n=r.isUncommented?Jc(qc(t)):t;return e.length>0?[{tag:`pre-comments`,cdata:n,children:[]}]:[]},g=t=>{switch(t.kind){case`FormalParam`:return p(Z(`FormalParamNode`,[Q(`uniquename`,t.name),Q(`arity`,t.arity)]),t,t.location);case`OpDecl`:return p(Z(`OpDeclNode`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Q(`kind`,t.declKind)]),t,t.location);case`OpDef`:{if(t.defKind===`NumberedProofStep`)throw i?u(Ac(37),[zc]):e.yt(new e.pt(Ac(37)),kc.uncaughtException);if(t.defKind===`ModuleInstance`)return p(Z(`ModuleInstanceKind`,[Q(`uniquename`,t.name),...t.isLocal&&!i?[Z(`local`)]:[]]),t,t.location);let n=t.params??[];if(t.defKind===`BuiltIn`)return p(Z(`BuiltInKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),...t.params?[m(n,t.isLeibnizArg,$.builtInParam)]:[]]),t,t.location);let r=t.body,a=t.module;if(r===void 0&&i)throw d($.body);if(r===void 0||a===void 0)throw Error(`The definition of ${t.name} has no body`);return p(i?Z(`UserDefinedOpKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Z(`body`,[x(r,$.body)]),...t.params?[m(n,t.isLeibnizArg,$.param)]:[],...t.inRecursive?[Z(`recursive`)]:[]]):Z(`UserDefinedOpKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Z(`originalOperator`,[f(t.source??t)]),Z(`originallyDefinedInModule`,[f(a)]),Z(`body`,[x(r,$.body)]),m(n,t.isLeibnizArg,$.param),...h(t.preComments),...t.inRecursive?[Z(`recursive`)]:[],...t.recursiveSection>=0?[Q(`recursiveSection`,t.recursiveSection)]:[],...t.isLocal?[Z(`local`)]:[]]),t,t.location)}case`ThmOrAssumpDef`:return p(Z(t.isTheorem?`TheoremDefNode`:`AssumeDef`,[Q(`uniquename`,t.name),x(t.body,$.theoremDefinitionBody)]),t,t.location);case`Module`:return Z(`ModuleNode`,[Ic(t.location),..._(t)]);case`Theorem`:return p(Z(`TheoremNode`,[...t.definition?[Z(`definition`,[f(t.definition,$.theoremDefinition)])]:[],Z(`body`,[x(t.body,$.theorem)]),...t.proof?[x(t.proof,$.proof)]:[],...t.isSuffices?[Z(`suffices`)]:[]]),t,t.location);case`Assume`:return Z(`AssumeNode`,[Ic(t.location),...t.body.levelChecked===0?[]:[Q(`level`,t.body.level)],...t.definition?[Z(`definition`,[f(t.definition,$.assumeDefinition)])]:[],Z(`body`,[x(t.body,$.assume)])])}},_=e=>{let t=t=>!r.isRestricted||t.module===e;return[Q(`uniquename`,e.name),...i?[]:[Z(`extends`,[...new Set(e.extendees.map(e=>e.name))].toSorted().map(e=>Q(`uniquename`,e)))],...Oo(e,2).filter(t).map(e=>f(e,$.constant)),...Oo(e,3).filter(t).map(e=>f(e,$.variable)),...Do(e).filter(t).map(e=>f(e,$.definition)),...e.topLevel.map(e=>e.kind===`Instance`||e.kind===`UseOrHide`?x(e,$.topLevel):f(e,$.topLevel)),...e.definitions.filter(e=>!i&&e.kind===`Module`).map(e=>f(e))]},v=(e,t)=>l([t],()=>Z(`Subst`,[f(e.op,$.substOperator),x(e.expr,$.substExpression)])),y=e=>{if(e.isNull&&i)throw u(Ac(0),[$.operator,...Vc(`OpDef`,Bc),zc]);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=f(e.operator,$.operator),r=e.operands.map((e,t)=>e===void 0||t===0&&s.isSet&&fo(e)?i?Q(`StringNode`,`$Other`):Z(`StringNode`,[Q(`StringValue`,`$Other`)]):x(e,$.operand)),a=e.tupleOrs,o=e.unbounded===void 0&&e.bounded===void 0?[]:[Z(`boundSymbols`,[...(e.unbounded??[]).map((e,t)=>Z(`unbound`,[f(e,$.unbound),...a?.[t]?[Z(`tuple`)]:[]])),...(e.bounded??[]).map((t,n)=>Z(`bound`,[...t.map(e=>f(e,$.bound)),...a?.[n]?[Z(`tuple`)]:[],x(e.ranges[n],$.range)]))])];return Z(`OpApplNode`,[Z(`operator`,[n]),Z(`operands`,r),...o])},b=(e,t)=>e.kind===`Module`||e.kind===`OpDef`?f(e,t):x(e,t),x=(e,t)=>{if(!i)return S(e);if(e.kind===`OpAppl`&&e.isAbsent&&`nullType`in t)throw d(t);let n=[t,{at:`semantic.SemanticNode.export(SemanticNode.java:379)`,failedFor:uo(e.location)},{at:`semantic.LevelNode.getSemanticElement(LevelNode.java:333)`}];return l(n,()=>S(e))},S=e=>{switch(e.kind){case`OpAppl`:return p(y(e),e,e.location);case`Numeral`:return p(Z(`NumeralNode`,[Q(`IntValue`,e.value)]),e,e.location);case`String`:return p(Z(`StringNode`,[Q(`StringValue`,e.value)]),e,e.location);case`Decimal`:return p(Z(`DecimalNode`,[Q(`mantissa`,e.mantissa),Q(`exponent`,e.exponent),...i?[]:[Q(`integralPart`,e.integralPart),Q(`fractionalPart`,e.fractionalPart)]]),e,e.location);case`LetIn`:{let t=x(e.body,$.letBody);return p(Z(`LetInNode`,[Z(`body`,[t]),Z(`opDefs`,e.opDefs.map(e=>f(e,$.letDefinition)))]),e,e.location)}case`Label`:return p(Z(`LabelNode`,[Q(`uniquename`,e.name),Q(`arity`,e.params.length),Z(`body`,[x(e.body,$.labelBody)]),Z(`params`,e.params.map(e=>f(e,$.labelParam)))]),e,e.location);case`OpArg`:return p(Z(`OpArgNode`,[Z(`argument`,[f(e.op,$.argument)])]),e,e.location);case`At`:{let t=e.except.operands[0],n=e.component.operands[0];if(t===void 0||n===void 0)throw Error(`An @ refers to an incomplete EXCEPT`);return p(Z(`AtNode`,[x(t,$.exceptObject),x(n,$.exceptComponents)]),e,e.location)}case`SubstIn`:case`APSubstIn`:{let t=Rc[e.kind],n=e.substs.map(e=>v(e,t.subst)),r=x(e.body,t.body);return p(Z(e.kind===`SubstIn`?`SubstInNode`:`APSubstInNode`,[Z(`substs`,n),Z(`body`,[r]),Z(`instFrom`,[f(e.instantiatingModule,t.from)]),Z(`instTo`,[f(e.instantiatedModule,t.to)])]),e,e.location)}case`Instance`:{let t=e.substs.map(e=>v(e,$.instanceSubst)),n=e.params.map(e=>f(e,$.instanceParam));return Z(`InstanceNode`,[Ic(e.location),Q(`level`,0),...e.name===void 0?[]:[Q(`uniquename`,e.name)],Q(`module`,e.module.name),Z(`substs`,t),Z(`params`,n),...e.isLocal&&!i?[Z(`local`)]:[]])}case`UseOrHide`:return p(Z(`UseOrHideNode`,[Z(`facts`,e.facts.map(e=>b(e,$.useFact))),Z(`defs`,e.defs.map(e=>f(e,$.useDefinition))),...e.isOnly?[Z(`only`)]:[],...e.isHide?[Z(`hide`)]:[]]),e,e.location);case`NewSymb`:return p(Z(`NewSymbNode`,[f(e.declaration,$.newDeclaration),...e.set&&!(i&&fo(e.set))?[x(e.set,$.newSet)]:[]]),e,e.location);case`AssumeProve`:return p(Z(`AssumeProveNode`,[Z(`assumes`,e.assumptions.map(e=>x(e,$.assumption))),Z(`prove`,[x(e.goal,$.goal)]),...e.isSuffices?[Z(`suffices`)]:[],...e.isBoxed?[Z(`boxed`)]:[]]),e,e.location);case`LeafProof`:{let t=e.facts.length===0&&e.defs.length===0,n=e.isOmitted?Z(`omitted`):t?Z(`obvious`):Z(`by`,[Z(`facts`,e.facts.map(e=>b(e,$.byFact))),Z(`defs`,e.defs.map(e=>f(e,$.byDefinition))),...e.isOnly?[Z(`only`)]:[]]);return p(n,e,e.location)}case`NonLeafProof`:return p(Z(`steps`,[...i?[]:[Q(`proofLevel`,e.proofLevel)],...e.steps.map(e=>e.kind===`Theorem`?f(e,$.step):x(e,$.step))]),e,e.location);case`DefStep`:return p(Z(`DefStepNode`,e.defs.map(e=>f(e,$.defStep))),e,e.location)}},C=(r.isRestricted?[n]:t).map(e=>f(e,$.main)),w=Hc(o.size),T=Z(`context`,[...o.entries()].toSorted(([e],[t])=>Uc(e,w)-Uc(t,w)).map(([e,t])=>Z(`entry`,[Q(`UID`,e),t])));return Z(`modules`,[Q(`RootModule`,n.name),T,...C])},Xc=(t,n={version:`master`,isRestricted:!1,isUncommented:!1,isTerse:!1})=>{let r=Yc(t.modules,t.root,n),i=Pc(r);if(i){let t=i.character.codePointAt(0)??0;throw e.yt(new e.pt(`The spec contains the character U+${t.toString(16).toUpperCase().padStart(4,`0`)} in the ${i.tag} element. XML 1.0 cannot represent that character in character data, not even as a numeric character reference, so the spec cannot be exported until the character is removed from it.`),kc.unrepresentableCharacter)}let a=[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>`];return Fc(r,0,n.isTerse?0:2,a),n.isTerse?a.join(``):`${a.join(`
1354
- `)}\n`},Zc=`META-INF/MANIFEST.MF`,Qc=e=>{if(e===void 0||!(0,r.existsSync)(e))return`master`;let t=(0,l.unzipSync)((0,r.readFileSync)(e),{filter:e=>e.name===Zc})[Zc];return(t&&/^X-Git-Tag: *(\S*)/m.exec((0,l.strFromU8)(t))?.[1])===`v1.7.4`?`1.7.4`:`master`},$c={success:e.vt.success,"assumption-violation":e.vt.assumptionViolation,deadlock:e.vt.deadlock,"invariant-violation":e.vt.safetyViolation,"property-violation":e.vt.safetyViolation,"liveness-violation":e.vt.livenessViolation,"postcondition-violation":e.vt.assumptionViolation,error:e.vt.error},el=f(`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>`}]),tl=f(`tla-ts prove {options} <Module.tla|glob>...`,[{flag:`-N`,isRequired:!0},{flag:`--toolbox <start> <end>`},{flag:`--line <num>`},{flag:`--printallobs`},{flag:`--summary`},{flag:`--strict`},{flag:`-I <directory>`,isRepeatable:!0}]),nl=/* @__PURE__ */ new Set([`-o`,`-t`,`-r`,`-u`]),rl=/* @__PURE__ */ new Set([`-o`]),il=(()=>{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(`
1355
- `)})(),al=[`Usage: ${el.usage}`,` ${tl.usage}`,` tla-ts prove [<tlapm option>]... <Module.tla|glob>...`,` tla-ts [<JVM option>]... tlc2.TLC <TLC option>... <Spec>`,` tla-ts [<JVM option>]... tla2sany.xml.XMLExporter [-I <directory>]... [-o] [-t] [-r] [-u] <Module.tla>`].join(`
1356
- `),ol=/[*?[{]/,sl=e=>e.flatMap(e=>ol.test(e)?(0,r.globSync)(e).sort().map(e=>({path:e,isGlobbed:!0})):[{path:e,isGlobbed:!1}]),cl=e=>/^[+-]?\d+$/.test(e)&&BigInt.asIntN(64,BigInt(e))===BigInt(e),ll=e=>e?e[0]===`auto`?(0,o.availableParallelism)():Math.max(1,Number.parseInt(e[0],10)||1):1,ul=[`constrained`,`stuttering`,`strict`],dl=(e,t)=>e.endsWith(t)?e:`${e}${t}`,fl=e=>{if(e.length===1)return{path:dl(e[0],`.dump`)};let t=e[0].toLowerCase();return{path:dl(e[1],`.dot`),dot:!0,colorize:t.includes(`colorize`),actionLabels:t.includes(`actionlabels`),snapshot:t.includes(`snapshot`)}},pl=(t,n)=>t.print(e.I.computingInitProgress,e.L.none,`Computed ${n} initial states...`),ml=(t,n)=>t===`invariant-violation`?{code:e.I.invariantViolatedInitial,text:`Invariant ${n} is violated by the initial state:`}:{code:e.I.propertyViolatedInitial,text:`Property ${n} is violated by the initial state:`},hl=(t,n)=>n?.forEach(n=>{if(typeof n==`string`)return console.log(n);if(n.kind===`initial-states-progress`)return pl(t,n.count);let r=ml(n.status,n.name);t.print(r.code,e.L.error,`${r.text}\n${e.K(n.state)}`)}),gl=(t,n,r={code:e.I.behaviorUpToThisPoint,text:`The behavior up to this point is:`},i=!1)=>{n.length>0&&t.print(r.code,e.L.error,r.text),n.forEach((n,r)=>{(r>0||i)&&hl(t,n.output),t.print(e.I.statePrint2,e.L.state,`${r+1}: <${n.label??n.action??`Initial predicate`}>\n${e.K(n.state)}`)})},_l={code:e.I.counterExample,text:`The following behavior constitutes a counter-example:
1357
- `},vl=(e,t)=>t===`1.7.4`||e.length===0?`Temporal properties were violated.
1358
- `: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`,yl=t=>t.filter((e,n)=>e!==t[n-1]).map((t,n)=>`${n}) ${e.M(t)}\n`).toReversed().join(``),bl=e=>{if(e.length===0)return` The error call stack is empty.
1359
- `;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`},xl=(t,n)=>{let r=n.generated,i=n.distinct,a=e.V(/* @__PURE__ */ new Date);r===i?t.print(e.I.initGenerated1,e.L.none,`Finished computing initial states: ${i} distinct state${i===1?``:`s`} generated at ${a}.`):t.print(e.I.initGenerated2,e.L.none,`Finished computing initial states: ${r} state${r===1?``:`s`} generated, with ${i} of them distinct at ${a}.`)},Sl=(t,n,r)=>{let i=Math.max(Date.now()-(r??0),1)/6e4,a=e=>e.toLocaleString(`en-US`),o=(e,t)=>r===void 0?``:` (${a(Math.floor(e/i))} ${t}/min)`;t.print(e.I.progress,e.L.none,`Progress(${Math.max(n.depth,1)}) at ${e.V(/* @__PURE__ */ new Date)}: ${a(n.generatedStates)} states generated${o(n.generatedStates,`s`)}, ${a(n.distinctStates)} distinct states found${o(n.distinctStates,`ds`)}, ${a(n.queuedStates)} states left on queue.`)},Cl=(e,t)=>(0,n.join)(e,`${t}.class`),wl=(t,r,i,a)=>{let o=t.print;switch(r.kind){case`parsed`:i.isParsed=!0,t.isTool&&o(e.I.sanyFinished,e.L.none,`SANY finished.`),o(e.I.starting,e.L.none,`Starting... (${e.V(/* @__PURE__ */ new Date)})`);return;case`constant-level-invariant`:if(t.version===`1.7.4`)return;o(e.I.constantLevelInvariant,e.L.warning,`The invariant ${r.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(t.version===`1.7.4`)return;o(e.I.stateLevelProperty,e.L.warning,`The formula ${r.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 ${r.name} holds in all states of every behavior, use INVARIANT ${r.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${r.name} changes it into a temporal formula, asserting that ${r.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`);return;case`liveness-initializing`:r.isSymmetric&&o(e.I.livenessSymmetry,e.L.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.`),r.isConstrained&&t.version===`1.7.4`&&o(e.I.livenessConstraints,e.L.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`:o(e.I.temporalBranches,e.L.none,`Implied-temporal checking--satisfiability problem has ${r.branches} branches.`);return;case`java-override`:{let t=(0,s.pathToFileURL)((0,n.resolve)(Cl(a,r.module))).href;o(r.isMatched?e.I.javaOverrideLoaded:e.I.javaOverrideMismatch,r.isMatched?e.L.none:e.L.warning,`${r.isMatched?`Loading`:`Failed to match`} ${r.operator} operator override from ${t.replace(`file:///`,`file:/`)} with signature: <Java Method: ${r.signature}>.`);return}case`initial-states-started`:o(e.I.computingInit,e.L.none,`Computing initial states...`);return;case`initial-states-progress`:pl(t,r.count);return;case`initial-states-computed`:xl(t,r.initialStates);return;case`progress`:Sl(t,r.statistics,i.start);return;case`liveness-started`:{i.liveness=Date.now(),r.isComplete&&Sl(t,r.statistics);let n=r.branches>1?`${r.branches} branches of `:``,a=r.branches*r.states;o(e.I.checkingTemporal,e.L.none,`Checking ${n}temporal properties for the ${r.isComplete?`complete`:`current`} state space with ${a} total distinct states at (${e.V(/* @__PURE__ */ new Date)})`);return}case`liveness-finished`:Tl(t,i);return;case`warning`:o(r.code,e.L.warning,r.text)}},Tl=(t,n)=>{n.liveness!==void 0&&(t.print(e.I.checkingTemporalEnd,e.L.none,`Finished checking temporal properties in ${e.H(Date.now()-n.liveness)} at ${e.V(/* @__PURE__ */ new Date)}`),n.liveness=void 0)},El=(t,n,r)=>{let i=r.print,a=n.name,o=n.loopStart,s=o===void 0&&n.trace.length===1&&(t===`invariant-violation`||t===`liveness-violation`),c={code:e.I.temporalPropertyViolated,text:vl(n.properties??[a],r.version)},l={success:void 0,error:void 0,"assumption-violation":n.message?{code:e.I.assumptionEvaluationError,text:e.z(e.I.assumptionEvaluationError,`Evaluating assumption ${a} failed.\n${n.message}`,r.isTool)}:{code:e.I.assumptionFalse,text:`Assumption ${a} is false.`},deadlock:{code:e.I.deadlockReached,text:`Deadlock reached.`},"invariant-violation":s?ml(`invariant-violation`,a):{code:e.I.invariantViolatedBehavior,text:`Invariant ${a} is violated.`},"property-violation":c,"liveness-violation":o===void 0?s?ml(`liveness-violation`,a):{code:e.I.actionPropertyViolatedBehavior,text:`Action property ${a} is violated.`}:c,"postcondition-violation":{code:n.postcondition?.code??e.I.general,text:n.message??`Postcondition ${a} is false.`}}[t],u=t===`property-violation`,d=o!==void 0&&!u,f=u||d,p=f&&r.version!==`1.7.4`;if(p&&hl(r,n.trace[0]?.output),n.counts&&console.log(n.counts),l){let t=s?`${l.text}\n${e.K(n.trace[0].state)}`:l.text;i(l.code,e.L.error,t)}if(s||(f||hl(r,n.trace[0]?.output),gl(r,n.trace,f?_l:void 0,f&&!p),hl(r,n.traceOutput)),d){let t=n.loopLabel;o===n.trace.length-1?i(e.I.statePrint3,e.L.state,`${o+2}: Stuttering`):r.isTool?i(e.I.backToState,e.L.state,`${o+1}: Back to state${t?`: <${t}>\n`:``}`):console.log(`Back to state ${o+1}${t?`: <${t}>\n`:``}`)}n.warning&&r.version!==`1.7.4`&&i(n.warning.code,e.L.warning,n.warning.text);let m=n.unwitnessed??(t===`postcondition-violation`?void 0:n.postcondition);return m?.counts&&console.log(m.counts),m&&i(m.code,e.L.error,m.message),!s&&t!==`assumption-violation`},Dl=(t,n)=>t.print(e.I.nestedExpression,e.L.error,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${bl(n)}`),Ol=(t,n,r)=>{let i=n.print;if(t.failure){let r=t.failure,a=n.isTool?r.toolMessage:r.message,o=()=>{let t=r.fingerprint;if(t){let a=r.callStack?.length&&n.version!==`1.7.4`?bl(r.callStack):yl(t.sources);i(e.I.fingerprintFailed,e.L.error,`TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${a}\nReason:\n${e.B(t.reason,n.isTool)}`)}else r.callStack&&Dl(n,r.callStack)};r.isCallStackFirst&&o();let s=r.initialState&&(()=>{try{return`While working on the initial state:\n${e.K(r.initialState)}`}catch(t){throw t instanceof e.st?e.yt(new e.st(`${e.ht}${t.message}`),e.vt.error):t}})();i(s?e.I.initialState:r.code,e.L.error,s?`${a}\n${s}`:a),hl(n,r.trace[0]?.output),gl(n,r.trace);let c=r.traceFailure;c&&i(c.code,e.L.error,n.isTool?c.toolMessage:c.message),hl(n,r.traceOutput);let l=r.postcondition;l?.counts&&console.log(l.counts),l&&i(l.code,e.L.error,l.message),r.isCallStackFirst||o()}else if(t.violation){if(!El(t.status,t.violation,n))return;let e=t.additionalViolation;e&&El(`property-violation`,e,n),t.liveCallStack&&Dl(n,t.liveCallStack)}else{Tl(n,r);let a=e._(t.distinctStates,t.generatedStates),o=t.fingerprintDistance===void 0?[]:[` based on the actual fingerprints: val = ${e.m(e.h(t.fingerprintDistance))}`];i(e.I.success,e.L.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 = ${e.m(a)}`,...o].join(`
1360
- `))}if(t.failure?.isWithoutStatistics)return;t.status!==`success`&&Tl(n,r),n.isTool&&Sl(n,t,r.start),i(e.I.stats,e.L.none,`${t.generatedStates} states generated, ${t.distinctStates} distinct states found, ${t.queuedStates} states left on queue.`);let a=n.version===`1.7.4`,o=a?t.outDegrees??t.violationOutDegrees:t.outDegrees;(!a||o)&&i(e.I.searchDepth,e.L.none,`The depth of the complete state graph search is ${a?Math.max(t.depth,1):t.depth}.`);let s=o&&e.v(o);s&&i(e.I.stateGraphOutdegree,e.L.none,s)},kl=(e,t)=>e.map(e=>(0,n.join)(e,`${t}.tla`)).find(r.existsSync),Al=e=>t=>{let n=kl(e,t);return n===void 0?void 0:(0,r.readFileSync)(n,`utf8`)},jl=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),Ml=e=>`jar:file:${(0,s.pathToFileURL)((0,n.resolve)(e)).pathname}!/tla2sany/StandardModules/`,Nl=e=>(0,a.createHash)(`sha256`).update(e).digest().readBigUInt64BE().toString(),Pl=(e,t,i,a,s)=>{let c=i.temporaryDirectory??(0,o.tmpdir)(),l=(0,r.existsSync)(c)?(0,r.realpathSync)(c):(0,n.resolve)(c),u=(0,n.join)(l,`tlc-${Nl((0,n.resolve)(e))}`),d=mu(i);return(i,o)=>{let c=`${i}.tla`;if(o===`file`)return(0,r.realpathSync)(kl(t,i)??e);if(s===`1.7.4`)return(0,n.join)(l,c);if(o===`root file`){let t=a===void 0?l:(0,n.resolve)(a),o=(0,r.realpathSync)(e);return`${(0,n.join)(t,Nl(`${o} ${i}`),c)} (${o})`}let f=(0,n.join)(u,c);return d===void 0?f:`${f} (${Ml(d)}${c})`}},Fl=t=>t.print(e.I.version,e.L.none,`TLC2 Version ${u} (rev: tla-ts)`),Il=(t,n)=>(Fl(t),t.print(e.I.commandLineError,e.L.error,`${n}\nUsage: java tlc2.TLC [-help] [-option] inputfile`),1),Ll=(t,n,r)=>t.print(e.I.modelChecking,e.L.none,`Running breadth-first search Model-Checking with fp 0 and seed ${BigInt(n)} with ${r} worker${r===1?``:`s`} on ${(0,o.availableParallelism)()} cores with ${Math.floor((0,c.getHeapStatistics)().heap_size_limit/1024/1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${(0,o.type)()} ${(0,o.release)()} ${(0,o.arch)()}, Node.js ${process.versions.node} ${process.arch.endsWith(`64`)?64:32}bit, MemFPSet, MemStateQueue).`),Rl=(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`)},zl=async(i,a,o,s)=>{let c=a.has(`-seed`)?a.get(`-seed`)?.[0]:`0`;if(c===void 0)return Il(s,`Error: seed required.`);if(!cl(c))return Il(s,`Error: An integer for seed required. But encountered ${c}`);let l=a.has(`-lncheck`)?a.get(`-lncheck`)?.[0]?.toLowerCase():`default`;if(l===void 0)return Il(s,`Error: expect a strategy such as final for -lncheck option.`);let u=a.get(`-dump`);if(u?.length===0)return Il(s,`Error: A file name for dumping states required.`);let d=u?.length===2&&ul.find(e=>u[0].toLowerCase().includes(e));if(d)return console.error(`Error: tla-ts does not support the -dump format ${d}.`),1;let f=a.get(`-fp`)?.[0];if(f!==void 0&&Number(f)!==0)return console.error(`Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${f}.`),1;let p=ll(a.get(`-workers`)),m=s.version;Fl(s),Ll(s,c,p);let h=a.get(`-config`)?.[0]??(a.has(`-config`)?void 0:i.replace(/\.tla$/,`.cfg`));if(!h||!(0,r.existsSync)(h))return s.print(e.I.configFileError,e.L.error,`TLC encountered the following error when trying to read the configuration file ${h??``}:\nFile not found.`),e.vt.configParseError;let g=(0,n.basename)(i,`.tla`),_={start:Date.now(),liveness:void 0,isParsed:!1},v=()=>{let t=Date.now()-_.start;s.print(e.I.finished,e.L.none,`Finished in ${s.isTool?`${t}ms`:e.H(t)} at (${e.V(/* @__PURE__ */ new Date)})`)},y=()=>s.print(e.I.parsingFailed,e.L.error,`Parsing or semantic analysis failed.`),b=t=>(t instanceof e.ft?y():Vl(t,s),v(),e.gt(t)),x=(()=>{try{return e.Z((0,r.readFileSync)(h,`utf8`),m)}catch(t){if(!(t instanceof e.at))throw t;return t}})();if(x instanceof e.at&&m===`1.7.4`)return s.print(e.I.general,e.L.error,`${e._t(`tlc2.tool.ConfigFileException`)}${e.B(x.message,s.isTool)}`),v(),e.vt.error;if(x instanceof e.at)return b(x);a.has(`-deadlock`)&&(x.checkDeadlock=!1);let S=(0,n.dirname)(i),C=[S,...o.libraries],w=Al(C),T=Rl(a,m),E=async()=>{let o=(0,r.readFileSync)(i,`utf8`),d=e.w(o).name;if(d!==g)throw new e.dt(`File name '${g}' does not match the name '${d}' of the top level module it contains.`,void 0);let f=await t.t({workers:p,livenessCheck:[`final`,`seqfinal`,`off`].includes(l)?`final`:`default`,seed:BigInt(c),dump:u&&fl(u),isTool:s.isTool,isTraceRecorded:T,isSanyReported:!0,isWarningEnabled:!a.has(`-nowarning`),version:m,onProgress:e=>wl(s,e,_,S),source:o,config:x,onPause:()=>(0,r.readSync)(0,Buffer.alloc(1)),loadModule:w,loadClass:e=>{let t=Cl(S,e);return(0,r.existsSync)(t)?(0,r.readFileSync)(t):void 0},readFile:e=>(0,r.existsSync)(e)?(0,r.readFileSync)(e,`utf8`):void 0,writeFile:(e,t)=>{(0,r.mkdirSync)((0,n.dirname)((0,n.resolve)(e)),{recursive:!0}),(0,r.writeFileSync)(e,t)}});return Ol(f,s,_),v(),f.failure?.exitCode??$c[f.status]};s.isTool&&s.print(e.I.startingSany,e.L.none,`Starting SANY...`);let ee=(0,n.isAbsolute)(i),D=ee?g:i.replace(/\.tla$/,``),te=mu(o),ne=m===`1.7.4`&&te!==void 0?lu(i,o,te):void 0;if(ne?!(0,r.existsSync)(i)&&!pi.has(g)&&ne(`${g}.tla`):!(0,r.existsSync)(i)&&!fi.has(g)&&jl(ee?S:process.cwd(),ee?`${g}.tla`:`./${D}.tla`,[...ee||S===`.`?[]:[S],...o.libraries]),Oc(i,ne?uu(w,ne):w,{fileName:D,describeFile:Pl(i,C,o,a.get(`-metadir`)?.[0],m),version:m,rootExtendees:T?[`_TLCTrace`]:void 0,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}).isFailed)return wl(s,{kind:`parsed`},_,S),y(),v(),e.vt.specParseError;try{return await E()}catch(t){if(!(t instanceof e.ot))throw t;return t instanceof e.ft&&console.log(Bl(t,g)),_.isParsed||wl(s,{kind:`parsed`},_,S),b(t)}},Bl=(t,n)=>{let r=t instanceof e.dt;if(!r&&!t.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${t.message}\n\n`;let i=r?t.location===void 0?`Unknown location\n\n${t.message}`:`In module ${t.location}\n\n${t.message}`:`In module ${n}\n\nCould not parse module ${n} from file ${n}.tla`;return`${t.failure?`***Parse Error***\n${t.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${n}\n\n${i}\n*** Errors: 1\n\n${i}\n\n\n`},Vl=(t,n)=>{if(t instanceof e.at||t instanceof e.st){let r=e.U(t.message),i=r&&!r.isEvalException?r.code:e.I.general;return n.print(i,e.L.error,e.z(i,t.message,n.isTool))}console.error(`${t.name}: ${t.message}`)},Hl=async(t,n=e.R(!1))=>{try{return await t()}catch(t){if(!(t instanceof e.ot))throw t;return Vl(t,n),e.gt(t)}},Ul=async(t,n,r)=>{let i=[];for(let[e,a]of t.entries()){e>0&&console.log(``);let t=r();i.push(await Hl(()=>n(a,t),t))}return i.find(t=>t!==e.vt.success)??e.vt.success},Wl=()=>(process.env.PATH??``).split(n.delimiter).map(e=>(0,n.join)(e,`tlapm`)).filter(e=>(0,r.existsSync)(e)),Gl=()=>Wl().map(e=>(0,n.join)((0,n.dirname)((0,n.dirname)((0,r.realpathSync)(e))),`lib/tlapm/stdlib`)).find(e=>(0,r.existsSync)(e)),Kl=e=>e.flatMap(e=>ol.test(e)?(0,r.globSync)(e).sort():[e]),ql=e=>{let t=Wl()[0];return t===void 0?(console.error(`Error: tla-ts prove runs tlapm to prove obligations, but tlapm isn't on your PATH. Install tlapm, or pass -N to only generate the obligations.`),1):(0,i.spawnSync)(t,Kl(e),{stdio:`inherit`}).status??1},Jl=e=>(0,r.existsSync)(e)?{file:e,source:(0,r.readFileSync)(e,`utf8`)}:void 0,Yl=e=>console.error(`@!!BEGIN\n${e.map(e=>`@!!${e}\n`).join(``)}@!!END\n`),Xl=e=>/^[+,\-./0-9:=@A-Z_a-z]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`,Zl=t=>console.log(`\n\\* TLAPM version 5f5037f\n\\* launched at ${e.V(/* @__PURE__ */ new Date)} with command line:\n\\* ${[`tla-ts`,`prove`,...t].map(Xl).join(` `)}\n`),Ql={incomplete:11,emptyTarget:12},$l=(e,t,n)=>{let r=e.summary;n||(r.absent.forEach(e=>console.error(`Missing proof at ${m(e)}`)),r.omitted.forEach(e=>console.error(`Omitted proof at ${m(e)}`)));let i=r.absent.length+r.omitted.length>0;i&&console.error(`${h(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(`${h(e.location)}[ERROR]: No proof obligation found for the selected target.`),[...i?[Ql.incomplete]:[],...a?[Ql.emptyTarget]:[]]},eu=t=>{try{return t()}catch(t){if(!(t instanceof e.ut))throw t;console.error(` tlapm ending abnormally with ${t.exception}\n`);return}},tu=t=>{if(!t.includes(`-N`)&&!t.includes(`--summary`))return ql(t);let i=tl.parse(t),a=i.unknown[0];if(a!==void 0)return console.error(`Error: tla-ts prove does not support the tlapm option ${a}.`),1;if(i.incomplete)return console.error(`Error: option '${i.incomplete.name}' needs an argument.`),1;let o=i.options.find(e=>e.name!==`-I`&&e.values.some(e=>!/^-?\d+$/.test(e)));if(o)return console.error(`Error: option '${o.name}' expects an integer.`),1;let s=Kl(i.positionals),c=s.map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(c.length===0)return console.error(al),1;let l=i.has(`--toolbox`)||i.has(`--line`);l&&Zl(t);let u=i.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?Zr:{start:n,end:n}:e},Zr),d=Gl(),f=i.options.flatMap(e=>e.name===`-I`?e.values:[]),p=c.reduce((e,t)=>e.includes((0,n.dirname)(t))?e:[(0,n.dirname)(t),...e],[`.`,...d?[d]:[],...f.toReversed()]),m=eu(()=>{let t=c.findIndex(e=>!(0,r.existsSync)(e));if(t!==-1){let n=s[t];throw console.error(`File "<unknown>":\nError: File ${JSON.stringify(n)} not found`),new e.ut(`File ${n} not found`,{failure:`Module.Parser.parse_file`})}return ui(c.map(e=>({file:`./${e}`,source:(0,r.readFileSync)(e,`utf8`)})),e=>p.map(t=>Jl(`${t}/${e}.tla`)).find(Boolean),{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 Yl([`type:warning`,`msg:${e.text}`]);e.channel!==`toolboxOnly`&&console.error(e.text)}})});if(!m)return 3;let h=m.flatMap(e=>(i.has(`--summary`)&&console.log(li(e)),l&&(e.obligations.forEach(e=>Yl([`type:obligation`,`id:${e.id}`,`loc:${e.location}`,`status:to be proved`,...i.has(`--printallobs`)?[`obl:${e.text}`]:[]])),Yl([`type:obligationsnumber`,`count:${e.obligations.length}`])),i.has(`--strict`)?$l(e,u.start>0||u.end<1/0,i.has(`--summary`)):[]));return h.includes(Ql.incomplete)?Ql.incomplete:h[0]??e.vt.success},nu=async(t,i)=>{let a=el.parse(t),o=sl(a.positionals),s=a.has(`-config`),c=o.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||s||(0,r.existsSync)(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(c.length===0)return console.error(al),1;if(s&&c.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let l=[...new Set(c.map(e=>(0,r.existsSync)(e)||(0,n.isAbsolute)(e)?e:i.libraries.map(t=>(0,n.join)(t,e)).find(r.existsSync)??e))],u=Qc(mu(i));return Ul(l,(e,t)=>(l.length>1&&console.log(`Checking ${(0,n.basename)(e)} with ${(0,n.basename)(e,`.tla`)}.cfg`),zl(e,a,i,t)),()=>e.R(a.has(`-tool`),!a.has(`-nowarning`),u))},ru=e=>(process.stderr.write(`ERROR: ${e}\n${il}`),kc.argsParsingFailure),iu=(t,n)=>{try{return process.stdout.write(Xc(t,n)),e.vt.success}catch(t){if(!(t instanceof e.pt))throw t;let n=e.gt(t),r=t instanceof e.ct?t.unwound:``;return console.error(n===kc.uncaughtException?`${r}Exception in thread "main" ${t.message}`:`ERROR: ${t.message}`),n}},au=(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`}},ou=t=>{if(t.length===0)return ru(`at least one .tla file must be given`);let i=au(t,nl);if(i.error===`missing-include`)return ru(`the -I flag must be followed by a directory and at least one .tla file`);if(i.error===`several-files`)return ru(`Only one TLA file to check allowed!`);let a=t[t.length-1];if(a===`-help`)return process.stdout.write(il),e.vt.success;let o=a.endsWith(`.tla`)?a:`${a}.tla`,s=[`.`,...i.includes],c=s.map(e=>(0,n.resolve)(e,o)).find(r.existsSync);c===void 0&&!fi.has(o.slice(0,-4))&&jl(process.cwd(),`./${o}`,i.includes);let l=Oc(c??o,Al(s),{fileName:a,isXmlExport:!0});return process.stderr.write(l.text),l.isFailed||l.specification===void 0?(console.error(`ERROR: Failed to parse module.`),kc.specParsingFailure):iu(l.specification,{version:`master`,isRestricted:i.flags.has(`-r`),isUncommented:i.flags.has(`-u`),isTerse:i.flags.has(`-t`)})},su=(e,t,r)=>console.error(`File does not exist: ${(0,n.isAbsolute)(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,Ml(r)].join(`, `)}`),cu=e=>e.endsWith(`/`)?e:`${e}/`,lu=(e,t,r)=>{let i=e.slice(0,e.lastIndexOf(`/`)+1),a=(!(0,n.isAbsolute)(e)&&i!==``?[i]:t.libraries).map(cu),o=a.length>0?a[a.length-1]:(0,n.isAbsolute)(e)?i:``;return e=>su(`${o}${e}`,a,r)},uu=(e,t)=>n=>{let r=e(n);return r===void 0&&!pi.has(n)&&t(`${n}.tla`),r},du=(e,t)=>(console.error(`Exception in thread "main" ${e}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${t})`),kc.uncaughtException),fu=(t,i)=>{if(t.length===0)return du(`java.lang.IllegalArgumentException: at least one .tla file must be given`,59);let a=au(t,rl);if(a.error===`missing-include`)return du(`java.lang.IllegalArgumentException: the -I flag must be followed by a directory and at least one .tla file`,71);if(a.error===`several-files`)return du(`java.lang.IllegalArgumentException: Only one TLA file to check allowed!`,83);let o=t[t.length-1],s=`${o.replace(/\.tla$/i,``)}.tla`,c=(a.includes.length===0?[`/`]:a.includes).map(cu),l=[`.`,...c],u=e=>su(`${c[c.length-1]}${e}`,c,i),d=l.map(e=>(0,n.resolve)(e,s)).find(r.existsSync);if(d===void 0&&!pi.has((0,n.basename)(s,`.tla`)))return u(s),e.vt.success;let f=Oc(d??s,uu(Al(l),u),{fileName:o,isXmlExport:!0,version:`1.7.4`});return process.stderr.write(f.text),f.specification===void 0?du(`tla2sany.xml.XMLExportingException: spec ${(d&&Dc((0,r.readFileSync)(d,`utf8`),`1.7.4`))??`null`} is malformed - does not have a root module`,110):iu(f.specification,{version:`1.7.4`,isRestricted:!1,isUncommented:!1,isTerse:!0})},pu=[`tlc2.TLC`,`tla2sany.xml.XMLExporter`],mu=e=>e.classPath?.split(n.delimiter).find(e=>e.endsWith(`.jar`)),hu=e=>{let t={libraries:[]};for(let r=0;r<e.length;r++){let i=e[r];if(i===`-cp`||i===`-classpath`||i===`--class-path`)r++,t.classPath=e[r];else if(i===`-jar`)return t.classPath=e[r+1],{mainClass:`tlc2.TLC`,args:e.slice(r+2),java:t};else if(i.startsWith(`-DTLA-Library=`))t.libraries.push(...i.slice(14).split(n.delimiter));else if(i.startsWith(`-Djava.io.tmpdir=`))t.temporaryDirectory=i.slice(17);else if(!i.startsWith(`-D`)&&!i.startsWith(`-X`))return r>0||pu.includes(i)?{mainClass:i,args:e.slice(r+1),java:t}:void 0}},gu=e=>{if(e.mainClass===`tlc2.TLC`)return nu(e.args,e.java);if(e.mainClass===`tla2sany.xml.XMLExporter`){let t=mu(e.java);return Hl(()=>t!==void 0&&Qc(t)===`1.7.4`?fu(e.args,t):ou(e.args))}return console.error(`Error: tla-ts runs the Java classes ${pu.join(` and `)}, not ${e.mainClass}.`),1},_u=async e=>{if(e[0]===`prove`)return Hl(()=>tu(e.slice(1)));let t=hu(e);return t?gu(t):nu(e,{libraries:[]})},vu=async()=>{process.exitCode=await _u(process.argv.slice(2))};exports.runCli=vu;
34
+ `&&Ri(n),Si(a.lines)},Qi=(e,t,n)=>Zi(e,t,!0,n),$i=(e,t)=>(Zi(e,t,!1,!1),e.delimiter),ea=(e,t)=>({params:e,tokenizer:Xi(),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}),ta=()=>Si([[vi(`defaultInitValue`,0,0)]]),na=(e,t)=>[...e,...t.filter((n,r)=>!e.includes(n)&&t.indexOf(n)===r)],ra=(e,t)=>!t.some(t=>e.includes(t)),ia=(e,t)=>{t.splice(0,t.length,...e)},aa=(t,n,r)=>{let i=t.params,a=t.lookahead,o=t.lastToken,s={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:i.inputVersionNumber>=1500,omitStutteringWhenDone:i.inputVersionNumber>=1500},c=t=>{throw new e.rt(`${t}\n line ${o.line}, column ${o.column}`)},l=()=>{if(s.lookaheadSize===0)return zi(n),o.column=n.vcolumn+1,o.line=n.line+1,o.text=$i(t.tokenizer,n),o.text;o.column=a.columns[0]+1,o.line=a.lines[0]+1;let e=a.tokens[0];for(let e=1;e<s.lookaheadSize;e++)a.tokens[e-1]=a.tokens[e],a.columns[e-1]=a.columns[e],a.lines[e-1]=a.lines[e];return--s.lookaheadSize,o.text=e,e},u=r=>{for(;s.lookaheadSize<r;){let r=s.lookaheadSize;if(zi(n)===` `)throw new e.rt(`Premature end of file, perhaps because of unclosed comment, near\n line ${a.lines[r]+1}, column ${a.columns[r]+1}`);a.columns[r]=n.vcolumn,a.lines[r]=n.line,a.tokens[r]=$i(t.tokenizer,n),s.lookaheadSize+=1}return a.tokens[r-1]},d=r=>{if(r<s.lookaheadSize)throw new e.nt(`ParseAlgorithm.PeekPastAlgToken called to peek after a token
35
+ it has already peeked at`);for(;r>s.lookaheadSize;)a.tokens[s.lookaheadSize]=$i(t.tokenizer,n),s.lookaheadSize+=1;return zi(n)},f=(r=!1)=>{if(s.lookaheadSize!==0)throw new e.nt(`ParseAlgorithm: GetExpr called after lookahead`);let i=Qi(t.tokenizer,n,r);return a.tokens[0]=t.tokenizer.delimiter,a.columns[0]=t.tokenizer.delimiterCol,a.lines[0]=t.tokenizer.delimiterLine,s.lookaheadSize=1,i},p=(t,n)=>{if(t===`;`){let t=u(1);if(`end begin else elsif or do macro procedure process fair define } {`.split(` `).includes(t))return;if(`if either while with call return goto print assert skip`.split(` `).includes(t))throw new e.rt(`Missing \`;' before line ${a.lines[0]+1}, column ${a.columns[0]+1}`)}let r=l();r!==t&&r!==n&&c(`Expected "${t}" but found "${r}"`)},m=e=>{let t=l();t!==e&&c(`Expected "${e}" but found "${t}"`)},h=()=>{let e=l();return e===`=`?!0:e===`\\in`||e===`∈`?!1:c(`Expected "=" or "\\in" but found "${e}"`)},g=()=>p(u(1)===`,`?`,`:`;`),_=()=>p(s.pSyntax?`begin`:`{`),v=e=>{s.cSyntax?p(`}`):(p(`end`),p(e))},y=()=>{u(1)===`variables`?m(`variables`):p(`variable`)},b=()=>{let t={...U(),kind:`VarDecl`,var:l(),col:o.column,line:o.line,isEq:!0,val:ta()};if(![`=`,`\\in`,`∈`].includes(u(1)))return s.hasDefaultInitialization=!0,t;if(t.isEq=h(),t.val=f(),t.val.tokens.length===0)throw new e.it(`NullPointerException`);return t},x=()=>{y();let e=[],t=[`begin`,`{`,`procedure`,`process`,`fair`,`define`,`macro`];for(;!t.includes(u(1));)e.push(b()),g();return e},S=()=>{let t={...U(),kind:`PVarDecl`,var:l(),col:o.column,line:o.line,val:ta()};if(u(1)!==`=`)return s.hasDefaultInitialization=!0,t;if(p(`=`),t.val=f(),t.val.tokens.length===0)throw new e.it(`NullPointerException`);return t},C=()=>{y();let e=[];for(;u(1)!==`begin`&&u(1)!==`{`;)e.push(S()),g();return e},w=()=>{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=zi(n);return e.length>0&&e[0]===`:`&&!(e.length>1&&e[1]===`=`)},T=()=>{if(!w())return``;let e=l();t.isInMacro&&c(`A label may not appear in a macro.`),e===`Done`&&c("Cannot use `Done' as a label."),e===`Error`&&c("Cannot use `Error' as a label."),p(`:`),s.hasLabel=!0,s.allLabels.add(e);let n=u(1);return n!==`+`&&n!==`-`||(p(n),(n===`+`?s.plusLabels:s.minusLabels).push(e),s.omitPC=!1),e},E=()=>{let e=[],t=e=>s.pSyntax&&[`end`,`else`,`elsif`,`or`].includes(e)||s.cSyntax&&e===`}`;for(;!t(u(1));)e.push(...D());return s.cSyntax&&e.length===0&&c(`Empty statement list`),e},ee=t=>{m(`{`);let n=E();if(p(`}`),p(`;`),t!==``){if(n[0].lbl!==``)throw new e.rt(`Duplicate labeling of statement`,n[0]);n[0].lbl=t}return n},D=()=>{let e=T();if(s.cSyntax&&u(1)===`{`)return ee(e);let t=te();return t.lbl=e,[t]},te=()=>{let t=u(1);if(t===`if`)return O(0);if(t===`either`)return k();if(t===`with`)return re(0);if(t===`when`||t===`await`){m(t);let n=o.column,r=o.line,i=f();if(i.tokens.length===0)throw new e.it(`NullPointerException`);return p(`;`),{...U(),kind:`When`,col:n,line:r,exp:i}}if(t===`print`||t===`assert`){m(t);let e=o.column,n=o.line,r=f();return r.tokens.length===0&&c(`Empty expression in ${t} statement at `),p(`;`),{...U(),kind:t===`print`?`PrintS`:`Assert`,col:e,line:n,exp:r}}if(t===`skip`){m(`skip`);let e={...U(),kind:`Skip`,col:o.column,line:o.line};return p(`;`),e}if(t===`call`)return N();if(t===`return`){m(`return`);let e={...U(),kind:`Return`,col:o.column,line:o.line,from:s.currentProcedure};return p(`;`),e}if(t===`goto`){m(`goto`);let e=o.column,t=o.line,n=l();return s.gotoUsed=!0,(n===`Done`||n===`"Done"`)&&(s.gotoDoneUsed=!0),p(`;`),{...U(),kind:`Goto`,col:e,line:t,to:n}}return t===`while`?ne():d(1)[0]===`(`?ae():A()},ne=()=>{m(`while`);let e=o.column,t=o.line;s.cSyntax&&p(`(`);let n=f();s.cSyntax&&p(`)`),n.tokens.length===0&&c(`Empty while test at `),s.pSyntax&&p(`do`);let r=s.pSyntax?E():D();return s.pSyntax&&(p(`end`),p(`while`),p(`;`)),r.length===0&&c(`Missing body of while statement at`),{...U(),kind:`While`,col:e,line:t,test:n,unlabDo:r,labDo:[]}},O=e=>{m(e===0?`if`:`elsif`);let t={...U(),kind:`LabelIf`,col:o.column,line:o.line,test:bi(),unlabThen:[],labThen:[],unlabElse:[],labElse:[]};s.cSyntax&&p(`(`),t.test=f(),s.cSyntax&&p(`)`),t.test.tokens.length===0&&c(`Empty if test at `),s.pSyntax&&p(`then`),t.unlabThen=s.pSyntax?E():D();let n=u(1);return n===`else`&&(m(`else`),t.unlabElse=s.pSyntax?E():D()),s.pSyntax&&n===`elsif`&&(t.unlabElse=[O(e+1)]),s.pSyntax&&![`else`,`elsif`,`end`].includes(n)&&c(`Expecting "else", "elsif", or "end"`),s.pSyntax&&e===0&&(p(`end`),p(`if`),p(`;`)),t.unlabElse.length===0&&_i(t.unlabThen,t.unlabThen.length-1),t},k=()=>{m(`either`);let t={...U(),kind:`LabelEither`,col:o.column,line:o.line,clauses:[]};for(;;){let n={...U(),kind:`Clause`,unlabOr:s.pSyntax?E():D(),labOr:[]};if(n.unlabOr.length===0)throw new e.rt("`either' statement with empty `or' clause",t);if(t.clauses.push(n),u(1)!==`or`)break;m(`or`)}if(s.pSyntax&&(m(`end`),p(`either`),p(`;`)),t.clauses.length===1)throw new e.rt("`either' statement has no `or'",t);return t},re=t=>{t===0&&(p(`with`),s.cSyntax&&p(`(`));let n={...U(),kind:`With`,col:o.column,line:o.line,var:l(),isEq:!0,exp:bi(),Do:[]};n.isEq=h(),n.exp=f(),(s.pSyntax||u(1)!==`)`)&&g(),n.exp.tokens.length===0&&c(`Empty with expression at `);let r=s.pSyntax&&u(1)===`do`,i=s.cSyntax&&u(1)===`)`;if(r&&p(`do`),i&&m(`)`),n.Do=r?E():i?D():[re(t+1)],r&&(p(`end`),p(`with`),p(`;`)),n.Do.length===0)throw new e.rt(`Missing body of with statement`,n);return n},ie=()=>{let e=a.columns[0]+1,t=a.lines[0]+1,n={...U(),kind:`Lhs`,col:e,line:t,var:l(),sub:f()};p(`:=`,`≔`);let r=f();return r.tokens.length===0&&c(`Empty right-hand side of assignment at `),{...U(),kind:`SingleAssign`,col:e,line:t,lhs:n,rhs:r}},A=()=>{let t={...U(),kind:`Assign`,col:a.columns[0]+1,line:a.lines[0]+1,ass:[ie()]};for(;u(1)===`||`||u(1)===`‖`;){l();try{t.ass.push(ie())}catch(t){if(!(t instanceof e.rt))throw t;c(`Bad assignment statement at `)}}return p(`;`),t},j=()=>{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;p(`,`)}return p(`)`),p(`;`),e},M=()=>{m(`call`);let e={...U(),kind:`Call`,col:o.column,line:o.line,returnTo:``,to:l(),args:[]};return p(`(`),e.args=j(),s.proceduresCalled.includes(e.to)||s.proceduresCalled.push(e.to),e},N=()=>{let e=M();if(u(1)===`return`)return m(`return`),p(`;`),{...U(),kind:`CallReturn`,col:e.col,line:e.line,to:e.to,from:s.currentProcedure,args:e.args};if(u(1)!==`goto`)return e;m(`goto`);let t={...U(),kind:`CallGoto`,col:e.col,line:e.line,to:e.to,after:l(),args:e.args};return s.gotoUsed=!0,(t.to===`Done`||t.to===`"Done"`)&&(s.gotoDoneUsed=!0),p(`;`),t},ae=()=>{let e={...U(),kind:`MacroCall`,name:l(),col:o.column,line:o.line,args:[]};return m(`(`),e.args=j(),e},oe=e=>{t.isInMacro=!0,m(`macro`);let n={...U(),kind:`Macro`,col:o.column,line:o.line,name:l(),params:[],body:[]};for(p(`(`);u(1)!==`)`;)n.params.length>0&&p(`,`),n.params.push(l());return m(`)`),_(),n.body=E(),v(`macro`),u(1)===`;`&&l(),he(n.body,e),t.isInMacro=!1,n},se=()=>{p(`procedure`);let e={...U(),kind:`Procedure`,col:o.column,line:o.line,name:l(),minusLabels:[],plusLabels:[],proceduresCalled:[],params:[],decls:[],body:[]};for(s.currentProcedure=e.name,s.plusLabels=[],s.minusLabels=[],s.proceduresCalled=[],p(`(`);u(1)!==`)`;)e.params.length>0&&p(`,`),e.params.push(S());return m(`)`),u(1)!==`begin`&&u(1)!==`{`&&(e.decls=C()),_(),e.body=E(),v(`procedure`),u(1)===`;`&&l(),s.currentProcedure=void 0,e.plusLabels=s.plusLabels,e.minusLabels=s.minusLabels,e.proceduresCalled=s.proceduresCalled,e},P=()=>{p(`process`);let e=o.column,t=o.line;s.cSyntax&&p(`(`);let n=l(),r=h(),i=f();s.plusLabels=[],s.minusLabels=[],s.proceduresCalled=[],s.cSyntax&&p(`)`),i.tokens.length===0&&c(`Empty process id at `);let a=u(1)===`begin`||u(1)===`{`?[]:x();_();let d=E();return v(`process`),u(1)===`;`&&l(),{...U(),kind:`Process`,col:e,line:t,name:n,fairness:0,minusLabels:s.minusLabels,plusLabels:s.plusLabels,proceduresCalled:s.proceduresCalled,isEq:r,id:i,decls:a,body:d}},F=()=>{let e=`${i.labelRoot}${s.nextLabelNum}`;return s.nextLabelNum+=1,s.allLabels.has(e)?F():e},I=e=>{e.lbl===``&&(e.lbl=F(),s.addedLabels.push(e.lbl),s.addedLabelsLocs.push(hi(e)))},ce=(t,n,r,i,a)=>{ia(i,a);let o={isNextLabeled:n,hasLabel:!1},c=e=>{I(e),o.hasLabel=!0,a.length=0};return t.forEach(t=>{if(t.lbl!==``&&(o.hasLabel=!0,a.length=0,r))throw new e.rt("Label in `with' statement",t);if(o.isNextLabeled){if(r)throw new e.rt("Statement follows `call' or `return' inside a `with' statement.",t);c(t),o.isNextLabeled=!1}switch(t.kind){case`LabelIf`:{let e=[],n=[],i=ce(t.unlabThen,!1,r,a,e);o.isNextLabeled=ce(t.unlabElse,!1,r,a,n)||i,ia(na(e,n),a);return}case`LabelEither`:{let e=[];t.clauses.forEach(t=>{let n=[];o.isNextLabeled=ce(t.unlabOr,!1,r,a,n)||o.isNextLabeled,ia(na(n,e),e)}),ia(e,a);return}case`While`:if(r)throw new e.rt("`while' inside a `with' statement",t);c(t),ce(t.unlabDo,!1,!1,a,[]),o.isNextLabeled=!1;return;case`With`:{let e=[];o.isNextLabeled=ce(t.Do,!1,!0,r?[...i]:[],e),ia(e,a),!r&&!ra(i,a)&&c(t);return}}let n=t.kind===`Call`||t.kind===`CallGoto`,l=t.kind===`Return`||t.kind===`CallReturn`,u=t.kind===`Assign`?na([],t.ass.map(e=>e.lhs.var)):n||l?[`stack`,...l||t.to===s.currentProcedure?s.procedures.flatMap(e=>[...e.params,...e.decls].map(e=>e.var)):[]]:[];if(o.isNextLabeled=n||l||t.kind===`Goto`,ra(a,u))ia(na(a,u),a);else{if(r)throw new e.rt(t.kind===`Assign`?"Second assignment to same variable inside a `with' statement":"Call or return makes second assignment to a variable inside a `with' statement",t);c(t),ia(u,a)}}),o.hasLabel||o.isNextLabeled},le=e=>{let t=e=>{let t=e.findIndex(e=>e.lbl!==``),n=t===-1?e:e.slice(0,t);return le(n),{unlabeled:n,labeled:ue(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}}})},ue=t=>{let n=[];return t.forEach(t=>{if(t.lbl===``&&n.length>0)n[n.length-1].stmts.push(t);else{if(t.lbl===``)throw new e.nt(`Failure of assertion: Missing Label in MakeLabeledStmtSeq`);n.push({...U(),kind:`LabeledStmt`,col:t.col,line:t.line,macroCol:t.macroCol,macroLine:t.macroLine,label:t.lbl,stmts:[t]})}}),n.forEach(e=>le(e.stmts)),n},de=(t,n)=>{let r=t[n];switch(r.kind){case`LabelIf`:{let e=fe(r.unlabThen);r.labThen.forEach(e=>fe(e.stmts));let i=fe(r.unlabElse);return r.labElse.forEach(e=>fe(e.stmts)),r.labThen.length>0||r.labElse.length>0||e===2||i===2?2:(t[n]={...U(),kind:`If`,test:r.test,Then:r.unlabThen,Else:r.unlabElse},+(e+i>0))}case`LabelEither`:{let e=r.clauses.reduce((e,t)=>{let n=Math.max(e,fe(t.unlabOr));return t.labOr.forEach(e=>fe(e.stmts)),t.labOr.length>0?2:n},0);return e===2?2:(t[n]={...U(),kind:`Either`,ors:r.clauses.map(e=>e.unlabOr)},e)}case`With`:{let t=fe(r.Do);if(t===2)throw new e.rt(`with statement at ${hi(r)} contains a labeled statement`);return t}case`While`:if(n!==0)throw new e.nt("ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.");return fe(r.unlabDo),r.labDo.forEach(e=>fe(e.stmts)),0;case`Call`:return t[n+1]?.kind===`Return`?0:1;case`Return`:case`CallReturn`:if(s.currentProcedure===void 0)throw new e.rt(`return statement not in a procedure at ${hi(r)}`);return 1;case`Goto`:case`CallGoto`:return 1;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`MacroCall`:return 0;default:throw new e.nt(`ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${r.kind}`)}},fe=t=>{for(let n=0;n<t.length;n++){let r=de(t,n);if(r!==0){if(n===t.length-1)return r;throw new e.nt(`Translator discovered later than it should have that\n Statement at ${hi(t[n+1])} must have a label`)}}return 0},pe=e=>{ce(e,!0,!1,[],[]);let t=ue(e);return t.forEach(e=>fe(e.stmts)),t},L=(t,n,r,i,a)=>{let o=e=>Mi(e,n,r),s=e=>e.map(e=>L(e,n,r,i,a)),c=e=>e.map(e=>({...U(),kind:`LabeledStmt`,label:e.label,stmts:e.stmts.map(e=>L(e,n,r,-1,0))})),l={...U(),col:t.col,line:t.line,macroCol:i>0?a:t.macroCol,macroLine:i>0?i:t.macroLine};switch(t.kind){case`Assign`:return{...l,kind:`Assign`,ass:t.ass.map(e=>me(e,n,r,i,a))};case`If`:return{...l,kind:`If`,test:o(t.test),Then:s(t.Then),Else:s(t.Else)};case`Either`:return{...l,kind:`Either`,ors:t.ors.map(s)};case`With`:return{...l,kind:`With`,var:t.var,isEq:t.isEq,exp:o(t.exp),Do:s(t.Do)};case`When`:case`Assert`:case`PrintS`:return{...l,kind:t.kind,exp:o(t.exp)};case`Skip`:return{...l,kind:`Skip`,macroCol:i>0?a:0,macroLine:i>0?i:-1};case`While`:return{...l,kind:`While`,test:o(t.test),unlabDo:s(t.unlabDo),labDo:c(t.labDo)};case`LabelIf`:return{...l,kind:`LabelIf`,test:o(t.test),unlabThen:s(t.unlabThen),labThen:c(t.labThen),unlabElse:s(t.unlabElse),labElse:c(t.labElse)};case`LabelEither`:return{...l,kind:`LabelEither`,clauses:t.clauses.map(e=>({...U(),kind:`Clause`,labOr:c(e.labOr),unlabOr:s(e.unlabOr)}))};case`Call`:return{...l,kind:`Call`,to:t.to,returnTo:t.returnTo,args:Ni(t.args,n,r)};case`Return`:return{...l,kind:`Return`,from:t.from};case`CallReturn`:return{...l,kind:`CallReturn`,to:t.to,from:t.from,args:Ni(t.args,n,r)};case`CallGoto`:return{...l,kind:`CallGoto`,to:t.to,after:t.after,args:Ni(t.args,n,r)};case`Goto`:return{...l,kind:`Goto`,to:t.to};default:throw new e.nt(`Found unexpected statement type in macro at${hi(t)}`)}},me=(t,n,r,i,a)=>{let o=Mi(t.rhs,n,r),s={...U(),kind:`Lhs`,var:t.lhs.var,sub:t.lhs.sub.tokens.length===0?t.lhs.sub:Mi(t.lhs.sub,n,r)},c={...U(),kind:`SingleAssign`,col:t.col,line:t.line,macroCol:i>0?a:t.macroCol,macroLine:i>0?i:t.macroLine,lhs:s,rhs:o},l=r.indexOf(s.var);if(l===-1)return c;let u=n[l],d=Di(u,{line:0,item:0});if(d.type!==di.ident)throw new e.rt(`Macro expansion substitutes \`${d.string}' for assignment variable\n at ${hi(c)}`);if(s.var=d.string,Oi(u,{line:0,item:0},1)===void 0)return c;let f=wi(u);return f.tokens[0].splice(0,1),xi(f),s.sub.tokens.length===0?s.sub=f:Ti(s.sub,f,0),c},he=(e,t)=>{let n=e.flatMap(e=>{switch(e.kind){case`LabelIf`:return he(e.unlabThen,t),he(e.unlabElse,t),[e];case`LabelEither`:return e.clauses.forEach(e=>he(e.unlabOr,t)),[e];case`With`:return he(e.Do,t),[e];case`While`:return he(e.unlabDo,t),[e];case`MacroCall`:return ge(e,t);default:return[e]}});e.splice(0,e.length,...n)},ge=(t,n)=>{let r=n.findLast(e=>e.name===t.name);if(r===void 0)throw new e.rt(`Macro ${t.name} undefined,\n at ${hi(t)}`);if(r.params.length!==t.args.length)throw new e.rt(`Macro ${t.name} called with wrong number of arguments at \n ${hi(t)}`);let i=r.body.map(e=>L(e,t.args,r.params,t.line,t.col));return i.length>0&&(i[0].lbl=t.lbl),i},_e=t=>{t.forEach((n,r)=>{if(t.slice(r+1).some(e=>e.name===n.name))throw new e.rt(`Multiple definitions of macro name \`${n.name}'`)})},ve=e=>{if(e.length===0)return;let t=()=>{s.omitPC=!1,s.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`||!Ei(r.test)||r.test.tokens[0][0].string!==`TRUE`)return t();r.labDo.length>0&&(s.omitPC=!1),r.unlabDo.some(e=>[`LabelIf`,`LabelEither`,`LabeledStmt`].includes(e.kind))&&(s.omitPC=!1)},ye=()=>{let t=s.addedLabels.length>1?`Missing labels at the following locations:`:`Missing label at the following location:`;throw new e.rt([t,...s.addedLabelsLocs].join(`
36
+ `))},be=()=>{i.reportLabelsFlag?(t.log(s.addedLabels.length>1?`The following labels were added:`:`The following label was added:`),s.addedLabels.forEach((e,n)=>t.log(` ${e} at ${s.addedLabelsLocs[n]}`))):t.log(`Labels added.`)},xe=e=>s.procedures.forEach(t=>{s.currentProcedure=t.name,he(t.body,e),t.body=pe(t.body)}),Se=()=>{r&&(l()!==`algorithm`&&c("`--fair' not followed by `algorithm'"),i.fairAlgorithm=!0);let e=l();s.cSyntax=u(1)===`{`,s.pSyntax=!s.cSyntax,s.cSyntax&&m(`{`);let n=u(1)===`variable`||u(1)===`variables`?x():[],a={value:bi()};u(1)===`define`&&(m(`define`),s.cSyntax&&p(`{`),a.value=f(!0),v(`define`),p(`;`));let o=[];for(;u(1)===`macro`;)o.push(oe(o));for(;u(1)===`procedure`;)s.procedures.push(se()),s.omitPC=!1;if(u(1)===`fair`&&(u(2)===`process`||u(2)===`+`&&u(3)===`process`)||u(1)===`process`){let t=[];for(;u(1)===`fair`||u(1)===`process`;){let e=u(1)===`fair`;e&&m(`fair`);let n=e&&u(1)===`+`;n&&m(`+`);let r=n||!e&&i.fairnessOption===`sf`?2:e||i.fairnessOption===`wf`?1:0;t.push({...P(),fairness:r})}v(`algorithm`),_e(o);let r=t.map(e=>(he(e.body,o),e.body=pe(e.body),s.omitStutteringWhenDone=!0,ve(e.body),s.omitStutteringWhenDone));return s.omitStutteringWhenDone=r.includes(!0),xe(o),s.addedLabels.length>0&&(i.labelFlag||ye(),be()),s.gotoDoneUsed&&(s.omitPC=!1,s.omitStutteringWhenDone=!1),s.gotoUsed&&(s.omitPC=!1),{...U(),kind:`Multiprocess`,name:e,decls:n,defs:a.value,macros:o,prcds:s.procedures,procs:t}}i.inputVersionNumber===1500&&u(1)===`fair`&&(p(`fair`),u(1)===`+`&&p(`+`),i.fairnessOption=`wf`),r&&([``,`wf`,`wfNext`].includes(i.fairnessOption)||t.log(`Warning: Option \`${i.fairnessOption}' specified for --fair algorithm.`),i.fairnessOption=`wf`),_();let d=E();_e(o),he(d,o),xe(o),s.cSyntax&&p(`}`),v(`algorithm`);let h=pe(d);return s.addedLabels.length>0&&(s.hasLabel&&!i.labelFlag&&ye(),be()),s.gotoUsed&&(s.omitPC=!1),s.gotoDoneUsed||ve(h),s.gotoDoneUsed&&(s.omitPC=!1,s.omitStutteringWhenDone=!1),{...U(),kind:`Uniprocess`,name:e,decls:n,defs:a.value,macros:o,prcds:s.procedures,body:h}};try{return{ast:Se(),omitPC:s.omitPC,omitStutteringWhenDone:s.omitStutteringWhenDone,hasDefaultInitialization:s.hasDefaultInitialization}}catch(t){if(!(t instanceof e.it))throw t;return c(`Unknown error at or before`)}},W={global:0,label:1,procedure:2,process:3,processVar:4,procedureVar:5,parameter:6},oa=[`Global variable`,`Label`,`Procedure`,`Process`,`Process variable`,`Procedure variable`,`Parameter`],sa=/* @__PURE__ */ new Set([W.global,W.processVar,W.procedureVar,W.parameter]),ca=(e,t,n,r)=>e.symbols.find(e=>e.id===n&&e.context===r&&e.type===t),la=(e,t,n)=>e.symbols.find(e=>e.id===t&&e.context===n),ua=(e,t)=>{let n=e.procedures.findIndex(e=>e.name===t);return n===-1?e.procedures.length:n},da=(e,t)=>{let n=e.processes.findIndex(e=>e.name===t);return n===-1?e.processes.length:n},fa=(e,t,n,r,i,a,o)=>!(t===W.procedureVar||t===W.processVar||t===W.parameter?ca(e,W.global,n,``)!==void 0||la(e,n,r)!==void 0:ca(e,t,n,r)!==void 0)&&(e.symbols.push({type:t,id:n,context:r,contextType:i,line:a,col:o,useThis:n}),!0),pa=(e,t,n,r)=>ca(e,t,n,r)?.useThis??n,ma=(e,t,n)=>{let r=la(e,t,n);return r===void 0?t:sa.has(r.type)?r.useThis:t},ha=t=>{let n={symbols:[],procedures:[],processes:[],disambiguateReport:[],errorReport:``,initialPC:void 0},r=(e,t,r)=>{fa(n,W.label,e.label,t,r,e.line,e.col)||(n.errorReport+=`\nLabel ${e.label} redefined at line ${e.line}, column ${e.col}`),e.stmts.forEach(e=>i(e,t,r))},i=(t,n,a)=>{let o=e=>e.forEach(e=>i(e,n,a)),s=e=>e.forEach(e=>r(e,n,a));switch(t.kind){case`While`:o(t.unlabDo),s(t.labDo);return;case`If`:o(t.Then),o(t.Else);return;case`With`:o(t.Do);return;case`LabelIf`:o(t.unlabThen),s(t.labThen),o(t.unlabElse),s(t.labElse);return;case`Either`:t.ors.forEach(o);return;case`LabelEither`:t.clauses.forEach(e=>{o(e.unlabOr),s(e.labOr)});return;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`Call`:case`Return`:case`CallReturn`:case`CallGoto`:case`Goto`:return;default:throw new e.nt(`Unexpected AST type ${t.kind}`)}},a=(e,t,r=`process`,i=t===``?W.global:W.processVar)=>{fa(n,i,e.var,t,r,e.line,e.col)||(n.errorReport+=`\n${oa[i]} ${e.var} redefined at line ${e.line}, column ${e.col}`)};if(fa(n,W.global,`pc`,``,``,0,0),t.prcds.length>0&&fa(n,W.global,`stack`,``,``,0,0),t.decls.forEach(e=>a(e,``)),t.prcds.forEach(e=>{let t=ua(n,e.name)<n.procedures.length;t&&(n.errorReport+=`\nProcedure ${e.name} redefined at line ${e.line}, column ${e.col}`),t||n.procedures.push({name:e.name,params:e.params,decls:e.decls,initialPC:e.body.length===0?void 0:gi(e.body[0]).label}),fa(n,W.procedure,e.name,``,`procedure`,e.line,e.col),e.decls.forEach(t=>a(t,e.name,`procedure`,W.procedureVar)),e.params.forEach(t=>a(t,e.name,`procedure`,W.parameter)),e.body.forEach(t=>r(gi(t),e.name,`procedure`))}),t.kind===`Multiprocess`&&t.procs.forEach(e=>{let t=da(n,e.name)<n.processes.length;t&&(n.errorReport+=`\nProcess ${e.name} redefined at line ${e.line}, column ${e.col}`),t||n.processes.push({name:e.name,initialPC:e.body.length===0?void 0:gi(e.body[0]).label}),fa(n,W.process,e.name,``,`process`,e.line,e.col),e.decls.forEach(t=>a(t,e.name)),e.body.forEach(t=>r(gi(t),e.name,`process`))}),t.kind===`Uniprocess`&&(t.body.length>0&&(n.initialPC=gi(t.body[0]).label),t.body.forEach(e=>r(gi(e),``,``))),n.errorReport.length>0)throw new e.rt(n.errorReport);return n},ga=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(`\\* ${oa[r.type]} ${r.id}${i} at line ${r.line} col ${r.col} changed to ${r.useThis}`)})},_a=t=>{let n=t.symbols.filter(e=>e.id===`defaultInitValue`).map(e=>`${oa[e.type]} name`);if(n.length>0)throw new e.rt(`Cannot use \`defaultInitValue' as ${n.join(` or `)}`)},va=(t,n,r)=>{let i=(e,t)=>{let r=[],i=[];e.tokens.forEach(e=>e.forEach(e=>{if(e.type!==di.ident)return;let a=ma(n,e.string,t);r.includes(e.string)||a===e.string||(r.push(e.string),i.push(Si([[Sa(a)]])))})),i.length>0&&ji(e,i,r,!1)},a=(e,t)=>{e.var=ma(n,e.var,t),i(e.val,t)},o=(e,t)=>e.forEach((r,i)=>{e[i]=pa(n,W.label,r,t)}),s=(e,t)=>e===void 0?void 0:pa(n,W.procedure,e,t),c=(e,t)=>{e.label=pa(n,W.label,e.label,t),e.stmts.forEach(e=>l(e,t))},l=(t,r)=>{let a=e=>e.forEach(e=>l(e,r)),o=e=>e.forEach(e=>c(e,r)),u=e=>e.forEach(e=>i(e,r));switch(t.kind){case`LabeledStmt`:c(t,r);return;case`While`:a(t.unlabDo),o(t.labDo),i(t.test,r);return;case`Assign`:t.ass.forEach(e=>{e.lhs.var=ma(n,e.lhs.var,r),i(e.lhs.sub,r),i(e.rhs,r)});return;case`If`:a(t.Then),a(t.Else),i(t.test,r);return;case`With`:i(t.exp,r),a(t.Do);return;case`When`:case`PrintS`:case`Assert`:i(t.exp,r);return;case`Skip`:return;case`LabelIf`:i(t.test,r),a(t.unlabThen),o(t.labThen),a(t.unlabElse),o(t.labElse);return;case`Call`:t.returnTo=pa(n,W.procedure,t.returnTo,r),t.to=pa(n,W.procedure,t.to,r),u(t.args);return;case`Return`:t.from=s(t.from,r);return;case`CallReturn`:t.from=s(t.from,r),t.to=pa(n,W.procedure,t.to,r),u(t.args);return;case`CallGoto`:t.after=pa(n,W.procedure,t.after,r),t.to=pa(n,W.procedure,t.to,r),u(t.args);return;case`Goto`:if(ca(n,W.label,t.to,r)===void 0&&t.to!==`Done`)throw new e.rt(`goto to non-existent label \`${t.to}' at line ${t.line}, column ${t.col}`);t.to=pa(n,W.label,t.to,r);return;case`Either`:t.ors.forEach(a);return;case`LabelEither`:t.clauses.forEach(e=>{a(e.unlabOr),o(e.labOr)});return;default:throw new e.nt(`Unexpected AST type${t.kind}`)}},u=e=>{e.decls.forEach(t=>a(t,e.name)),e.params.forEach(t=>a(t,e.name)),e.body.forEach(t=>c(gi(t),e.name));let t=_i(n.procedures,ua(n,e.name));o(e.plusLabels,e.name),o(e.minusLabels,e.name),t.initialPC!==void 0&&(t.initialPC=pa(n,W.label,t.initialPC,e.name)),e.name=pa(n,W.procedure,e.name,``),t.name=e.name},d=e=>{e.decls.forEach(t=>a(t,e.name)),e.body.forEach(t=>c(gi(t),e.name));let t=_i(n.processes,da(n,e.name));o(e.plusLabels,e.name),o(e.minusLabels,e.name),t.initialPC!==void 0&&(t.initialPC=pa(n,W.label,t.initialPC,e.name)),e.name=pa(n,W.process,e.name,``),t.name=e.name};t.decls.forEach(e=>a(e,``)),t.kind===`Multiprocess`&&((e,t)=>{e.forEach(u);let n=e.map(e=>e.name),i=e.map(e=>n.map(t=>e.proceduresCalled.includes(t)));n.forEach((e,t)=>i.forEach(e=>e.forEach((n,r)=>{e[r]=n||e[t]&&i[t][r]}))),e.forEach((e,t)=>{e.proceduresCalled=n.filter((e,n)=>i[t][n])});for(let e of t){d(e);let t=e.proceduresCalled;for(let e=0;e<t.length;e+=1){let a=n.indexOf(t[e]);if(a===-1){r(`\nUnrecoverable error:\n -- Could not find procedure name \`${t[e]}'.\n`);return}n.forEach((e,n)=>{i[a][n]&&!t.includes(e)&&t.push(e)})}}})(t.prcds,t.procs),t.kind===`Uniprocess`&&(t.prcds.forEach(u),t.body.forEach(e=>c(gi(e),``))),n.initialPC!==void 0&&(n.initialPC=pa(n,W.label,n.initialPC,``))},ya=e=>vi(e,0,di.string),ba=e=>vi(e,0,di.added),xa=e=>vi(e,0,di.builtin),Sa=e=>vi(e,0,di.ident),Ca=(e,t)=>{let n=[];return e.forEach(e=>{let r=n.at(-1),i=r===void 0?0:r.column+yi(r)+t;n.push(vi(e.string,i,e.type))}),Si([n])},wa=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+=yi(e),e.type===di.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}})}),Ta=(e,t,n,r=0,i=0)=>({...U(),kind:`SingleAssign`,line:r,col:i,lhs:{...U(),kind:`Lhs`,var:e,sub:t},rhs:n}),Ea=(e,t=0,n=0)=>({...U(),kind:`Assign`,line:t,col:n,ass:e}),Da=(e,t,n=0,r=0)=>Ea([Ta(e,Si([]),t,n,r)],n,r),Oa=e=>{if(e.tokens.length>1)return!1;let t=_i(e.tokens,0);return t.length===1?t[0].string===`TRUE`:t.length===3&&t[0].string===`(`&&t[1].string===`TRUE`&&t[2].string===`)`},ka=e=>({...U(),kind:`When`,exp:Ca([ba(`pc`),xa(`=`),ya(e)],1)}),Aa=e=>Da(`pc`,Si([[ya(e??`null`)]])),ja=e=>[Sa(`Head`),xa(`(`),ba(`stack`),xa(`)`),xa(`.`),Sa(e)],Ma=()=>[Sa(`Tail`),xa(`(`),ba(`stack`),xa(`)`)],Na=e=>Si([ja(e)]),Pa=(e,t,n,r)=>{let i=[[xa(`<<`),xa(`[`),Sa(`procedure`),xa(`|->`),ya(e),xa(`,`)],[Sa(`pc`),xa(`|->`),...t]];n.forEach(e=>{i[i.length-1].push(xa(`,`)),i.push([Sa(e.var),xa(`|->`),Sa(e.var)])}),i[i.length-1].push(xa(`]`),xa(`>>`)),i.push(r);let a=bi(i);return wa(a),xi(a),a},Fa=(t,n,r)=>{if(n.params.length!==r.args.length)throw new e.rt(`Procedure ${r.to} called with wrong number of arguments`,r);return n.params.forEach((e,n)=>t.ass.push(Ta(e.var,Si([]),r.args[n],r.line,r.col))),[t,...n.decls.map(e=>Da(e.var,e.val,r.line,r.col)),Aa(n.initialPC)]},Ia=(t,n,r)=>{let i={procedure:void 0},a=(t,r)=>{let i=ua(n,t.to);if(i===n.procedures.length)throw new e.rt(`Call of non-existent procedure ${t.to}`,t);let a=n.procedures[i],o=Pa(t.to,[ya(r)],[...a.decls,...a.params],[xa(`\\o`),ba(`stack`)]);return Fa(Da(`stack`,o,t.line,t.col),a,t)},o=t=>{t.from??=i.procedure;let r=t.from;if(r===void 0)throw new e.rt("`return' statement not in procedure",t);let a=ua(n,r);if(a>=n.procedures.length)throw new e.rt(`Error in procedure (perhaps name used elsewhere)`,t);let o=n.procedures[a],s=(e,n)=>Ea([Ta(e,bi(),n,t.line,t.col)],t.line,t.col);return[s(`pc`,Na(`pc`)),...o.decls.map(e=>s(e.var,Na(e.var))),...o.params.map(e=>s(e.var,Na(e.var))),s(`stack`,Si([Ma()]))]},s=t=>{let r=t.from;if(r===void 0)throw new e.rt(`\`return' statement following \`call' at ${hi(t)} not in a procedure`);let i=_i(n.procedures,ua(n,r)),a=ua(n,t.to);if(a===n.procedures.length)throw new e.rt(`Call of non-existent procedure ${t.to}`,t);let o=n.procedures[a],s=Ea([],t.line,t.col);if(r!==t.to){i.decls.forEach(e=>s.ass.push(Ta(e.var,bi(),Na(e.var),t.line,t.col)));let e=Pa(t.to,ja(`pc`),[...o.decls,...o.params],[xa(`\\o`),...Ma()]);s.ass.push(Ta(`stack`,Si([]),e,t.line,t.col))}return Fa(s,o,t)},c=(e,t)=>{if(e.length===0)return{stmts:[],labeledStmts:[],needsGoto:!r};let n={stmts:e,labeledStmts:[],needsGoto:!1},i=e[e.length-1];switch(i.kind){case`LabelIf`:case`LabelEither`:{let r=i.kind===`LabelIf`?p(i,t):m(i,t);e.pop(),e.push(r.stmt),n.labeledStmts=r.labeledStmts;break}case`Goto`:e.pop(),e.push(Aa(i.to));break;case`Call`:e.pop(),e.push(...a(i,t));break;case`Return`:e.pop(),e.push(...o(i));break;case`CallReturn`:e.pop(),e.push(...s(i));break;case`CallGoto`:e.pop(),e.push(...a({...U(),kind:`Call`,returnTo:``,to:i.to,args:i.args,line:i.line,col:i.col},i.after));break;case`If`:{let e=c(i.Then,t),a=c(i.Else,t);n.labeledStmts.push(...e.labeledStmts,...a.labeledStmts),i.Then=e.stmts,i.Else=a.stmts,r||(n.needsGoto=e.needsGoto&&a.needsGoto,n.needsGoto||(e.needsGoto&&i.Then.push(Aa(t)),a.needsGoto&&i.Else.push(Aa(t))));break}case`Either`:{let e=i.ors.map((e,r)=>{let a=c(e,t);return i.ors[r]=a.stmts,n.labeledStmts.push(...a.labeledStmts),a});n.needsGoto=e.every(e=>e.needsGoto),!r&&!n.needsGoto&&e.forEach((e,n)=>{e.needsGoto&&i.ors[n].push(Aa(t))});break}case`With`:{let e=c(i.Do,t);i.Do=e.stmts,n.labeledStmts.push(...e.labeledStmts),n.needsGoto=e.needsGoto;break}default:n.needsGoto=!0}return r&&(n.needsGoto=!1),n},l=(e,t)=>{let n=c(e,t);return n.needsGoto&&n.stmts.push(Aa(t)),n},u=(e,t)=>{let n=e.stmts.at(0);if(n?.kind===`While`)return f(e,n,t);let i=l([...e.stmts],t),a=[];return r||(i.stmts.unshift(ka(e.label)),a.push({...U(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:i.stmts})),a.push(...i.labeledStmts),a},d=(e,t)=>e.flatMap((n,r)=>u(n,r<e.length-1?e[r+1].label:t)),f=(e,t,n)=>{let i=t.labDo.length===0?e.label:t.labDo[0].label,a=l([...t.unlabDo],i),o=l(e.stmts.slice(1),n),s=Oa(t.test),c=s?a.stmts:[{...U(),kind:`If`,test:t.test,Then:a.stmts,Else:o.stmts}];return[{...U(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:[...r?[]:[ka(e.label)],...c]},...d(t.labDo,e.label),...a.labeledStmts,...s?[]:o.labeledStmts]},p=(e,t)=>{let n=l(e.unlabThen,e.labThen.length===0?t:e.labThen[0].label),r=l(e.unlabElse,e.labElse.length===0?t:e.labElse[0].label),i=d(e.labThen,t);return i.push(...d(e.labElse,t)),i.push(...n.labeledStmts,...r.labeledStmts),{stmt:{...U(),kind:`If`,col:e.col,line:e.line,test:e.test,Then:n.stmts,Else:r.stmts},labeledStmts:i}},m=(e,t)=>{let n=[],r=[];return e.clauses.forEach(e=>{let i=l(e.unlabOr,e.labOr.length>0?e.labOr[0].label:t);n.push(i.stmts),r.push(...i.labeledStmts),r.push(...d(e.labOr,t))}),{stmt:{...U(),kind:`Either`,col:e.col,line:e.line,ors:n},labeledStmts:r}},h=(e,t)=>d(e.map(gi),t),g=e=>{i.procedure=e.name;let t=h(e.body,pa(n,W.label,`Error`,``));return i.procedure=void 0,{...U(),kind:`Procedure`,col:e.col,line:e.line,name:e.name,minusLabels:[],plusLabels:[],proceduresCalled:[],params:e.params,decls:e.decls,body:t}},_=e=>({...U(),kind:`Process`,col:e.col,line:e.line,name:e.name,fairness:0,minusLabels:[],plusLabels:[],proceduresCalled:[],isEq:e.isEq,id:e.id,decls:e.decls,body:h(e.body,`Done`)}),v=t.prcds.map(g);return t.kind===`Uniprocess`?{...U(),kind:`Uniprocess`,col:t.col,line:t.line,name:t.name,decls:t.decls,defs:t.defs,macros:[],prcds:v,body:h(t.body,`Done`)}:{...U(),kind:`Multiprocess`,col:t.col,line:t.line,name:t.name,decls:t.decls,defs:t.defs,macros:[],prcds:v,procs:t.procs.map(_)}},La=(t,n)=>{let r=n?[]:[`pc`];if(r.push(...t.decls.map(e=>e.var)),t.prcds.length>0&&r.push(`stack`),t.prcds.forEach(e=>{r.push(...e.params.map(e=>e.var)),r.push(...e.decls.map(e=>e.var))}),t.kind===`Multiprocess`&&t.procs.forEach(e=>r.push(...e.decls.map(e=>e.var))),r.length===0)throw new e.rt(`The algorithm has no variables.`);let i=(e,t)=>{let n=r.indexOf(t);return n===-1?0:(e[n]+=1,e[n])},a=(e,t)=>t.forEach((t,n)=>{e[n]=Math.max(e[n],t)}),o=e=>[...e].sort((e,t)=>e.lhs.var<t.lhs.var?-1:+(e.lhs.var>t.lhs.var)),s=(t,n)=>{let s=[...n];t.ass=o(t.ass),new Set(t.ass.map(e=>e.lhs.var)).forEach(n=>{let a=t.ass.filter(e=>e.lhs.var===n);if(!r.includes(n))throw new e.rt(`Assignment to undeclared variable ${n}`,a[0]);let o=a.some(e=>e.lhs.sub.tokens.length===0);if(i(s,n)>1||a.length>1&&o)throw new e.rt(`Multiple assignment to ${n}`,t)}),a(n,s)},c=(t,n)=>{switch(t.kind){case`Assign`:s(t,n);return;case`If`:{let e=[...n],r=[...n];t.Then.forEach(t=>c(t,e)),t.Else.forEach(e=>c(e,r)),a(n,e),a(n,r);return}case`Either`:{let e=[...n];t.ors.forEach(t=>{let r=[...n];t.forEach(e=>c(e,r)),a(e,r)}),a(n,e);return}case`With`:t.Do.forEach(e=>c(e,n));return;case`When`:case`PrintS`:case`Assert`:case`Skip`:return;default:throw new e.nt(`Unexpected AST type ${t.kind}`)}},l=e=>e.forEach(e=>{let t=r.map(()=>0);gi(e).stmts.forEach(e=>c(e,t))});t.prcds.forEach(e=>l(e.body)),(t.kind===`Uniprocess`?[t.body]:t.procs.map(e=>e.body)).forEach(l)},Ra=(e,t,n,r)=>{let i=ha(e);ga(i),i.disambiguateReport.length>0&&r(`Warning: symbols were renamed.`),va(e,i,r),La(Ia(e,i,t),t),n&&_a(i)},za=`[ \\t\\n\\x0B\\f\\r]`,Ba=RegExp(`\\\\\\* BEGIN TRANSLATION${za}+\\(${za}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${za}*(=${za}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${za}*STRING)${za}*\\/\\\\${za}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${za}*(=${za}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${za}*STRING)${za}*\\)`),Va=e=>process.getBuiltinModule(`node:zlib`).crc32(Buffer.from(e,`utf8`)).toString(16),Ha=(e,t)=>e.log(`\nUnrecoverable error:\n -- ${t}.\n`),Ua=(e,t)=>Ha(e,t.node===void 0||t.node.line===0?t.message:`${t.message}\n at ${hi(t.node)}`),Wa=e=>e.map(e=>`${Array.from(e).reduce((e,t)=>t===` `?e+` `.repeat(8-e.length%8):e+t,``)} `),Ga=(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},Ka=(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``},qa=(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},Ja=e=>/^[\p{L}\p{Nd}_]$/u.test(e),Ya=(e,t,n)=>{for(;t.line<e.length;){let r=Ka(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=qa(r,e,` `),!0}t.column=qa(r,t.column,` `)}return!1},Xa=(e,t)=>Ha(e,`Command-line error: ${t}`),Za=(e,t)=>{let n=e.params,r={isFirst:!0,isExplicitNof:!1},i=t=>(r.isFirst&&=(n.fairnessOption=``,!1),n.fairnessOption===``?(n.fairnessOption=t,!0):(Xa(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){Xa(e,`
37
+ Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){Xa(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){Xa(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){Xa(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){Xa(e,"Version number must follow `-version' option");return}let t=pi(s);if(t<0||t>1903){Ha(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),Xa(e,`Bad version number`);return}n.inputVersionNumber=t,a+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){Xa(e,"Integer value at least 60 must follow `-lineWidth' option");return}a+=1;continue;default:Xa(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!r.isExplicitNof&&(n.fairnessOption=`wf`)},Qa=(e,t,n)=>{if(Ka(t,n),n.column+=7,!Ka(t,n).slice(n.column).startsWith(`(`)){Ha(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=Ka(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=qa(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?Ha(e,`No closing ')' found in options statement`):Za(e,r)},$a=(t,n,r)=>{let i={depth:0,isDone:!1,isInString:!1};for(let a=n;!i.isDone&&a<t.length;a++){let o=t[a],s=a===n?r:0,c=[o.slice(0,s)];i.isInString=!1;for(let e=s;!i.isDone&&e<o.length;e++){let t=o[e],n=o.slice(e,e+2);if(n===`(*`&&!i.isInString)i.depth+=1,c.push(` `),e+=1;else if(n===`*)`&&!i.isInString&&i.depth===0)c.push(n),i.isDone=!0;else if(n===`*)`&&!i.isInString)--i.depth,c.push(` `),e+=1;else if(i.depth>0)c.push(` `);else if(i.isInString&&t===`\\`&&n.length===2)c.push(n),e+=1;else{if(!i.isInString&&n===`\\*`){c.push(` `);break}t===`"`&&(i.isInString=!i.isInString),c.push(t)}}if(i.isInString)return new e.rt(`Unterminated string in line ${a+1}`);t[a]=c.join(``)}},eo=(t,n)=>{let r=10*2**Math.max(0,Math.ceil(Math.log2(n/10)));throw new e.it(`java.lang.ArrayIndexOutOfBoundsException: Index ${t} out of bounds for length ${r}`)},to=(t,n,r)=>{if(!n.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let i=Wa(n),a={line:0,column:0};for(;Ya(i,a,`PlusCal`);){let e=Ka(i,a).slice(a.column),n=Array.from(e).findIndex(e=>!Ja(e));if(e.startsWith(`options`)&&(n===-1?e.length:n)===7){t.params.optionsInFile=!0,Qa(t,i,a);break}}let o={line:0,column:-1,isFound:!1,isFair:!1};for(;o.line<i.length;o.line++){let e=i[o.line];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){o.column=t+11,o.isFound=!0;break}if(n!==-1){o.column=n+6,o.isFound=!0,o.isFair=!0;break}}let s=/* @__PURE__ */ new Set,c=Ga(i,0,`BEGIN`,`TRANSLATION`);c===-1&&s.add(`NO_TRANSLATION_EXISTS`);let l=Ga(i,c+1,`END`,`TRANSLATION`);if(l===-1&&s.add(`NO_TRANSLATION_EXISTS`),c===-1&&l===-1)return s;if(!o.isFound)return s.add(`NO_PLUSCAL_EXISTS`),s;let u=$a(i,o.line,o.column);if(u!==void 0)return Ua(t,u),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let d={ast:void 0};try{let e=Ii(i,o.line,o.column,n.length,0),r=aa(t,e,o.isFair);d.ast=r.ast,Ra(r.ast,r.omitPC,r.hasDefaultInitialization,t.log)}catch(n){if(!(n instanceof e.rt))throw n;Ua(t,n)}c===-1&&eo(-1,i.length);let f=Ba.exec(i[c]);if(f===null)return s.add(`NO_PCAL_CHECKSUMS_EXIST`),s;let p=f.groups?.pcal,m=o.isFair&&r!==`1.7.4`?`fair`:d.ast===void 0?void 0:Fi(d.ast,t.params.inputVersionNumber,r);p!==void 0&&(m===void 0||p!==Va(m))&&s.add(`PCAL_DIVERGENCE_EXISTS`);let h=f.groups?.tla;if(h!==void 0){if(l===-1)throw new e.it(`java.lang.IllegalArgumentException: fromIndex(${c+1}) > toIndex(-1)`);let t=n.slice(c+1,l).join(``);h!==Va(t)&&s.add(`TLA_DIVERGENCE_EXISTS`)}return s.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):s},no=[[`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]]],ro={file:`--TLA+ BUILTINS--`,beginLine:0,beginColumn:0,endLine:0,endColumn:0},G=e=>({id:e,levelChecked:0,level:0,levelParams:/* @__PURE__ */ new Set,allParams:/* @__PURE__ */ new Set,nonLeibnizParams:/* @__PURE__ */ new Set,argLevelParams:/* @__PURE__ */ new Map,levelCorrect:!0,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map}),io=e=>no.map(([t,n,r,i,a])=>{let o=e(),s=n<0?void 0:Array.from({length:n},(t,n)=>({...G(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{...G(o),levelChecked:c?99:0,level:r,kind:`OpDef`,defKind:`BuiltIn`,name:t,arity:n,params:s,body:void 0,isLocal:!1,location:ro,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}}),ao=(e,t)=>{let n=JSON.stringify(t);e.some(e=>JSON.stringify(e)===n)||e.push(t)},oo=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}`,so=e=>e?.kind===`OpAppl`&&e.isAbsent===!0,co=e=>{let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;return t},lo=()=>({buckets:Array.from({length:11},()=>[]),count:0,threshold:8}),uo=(e,t)=>(e&2147483647)%t,fo=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[uo(e.hash,t)].unshift(e));e.buckets=n,e.threshold=Math.floor(t*.75)},po=(e,t,n=t)=>e.buckets[uo(co(n),e.buckets.length)].find(e=>e.key===t)?.value,mo=(e,t,n,r=t)=>{let i=co(r),a=e.buckets[uo(i,e.buckets.length)].find(e=>e.key===t);a?a.value=n:(e.count>=e.threshold&&fo(e),e.buckets[uo(i,e.buckets.length)].unshift({hash:i,key:t,value:n}),e.count++)},ho=e=>e.buckets.toReversed().flatMap(e=>e.map(e=>e.value)),go=`\0module `,_o=()=>({table:lo(),symbols:[]}),vo=e=>e.kind===`Module`?go+e.name:e.name,yo=(e,t)=>{mo(e.table,vo(t),t,t.name),e.symbols.push(t)},bo=e=>e.kind===`ThmOrAssumpDef`?e.params.length:e.kind===`Module`?0:e.arity,xo=(e,t)=>po(e.table,t),So=(e,t)=>po(e.table,go+t,t),Co=e=>e.context.symbols.filter(e=>e.kind===`OpDef`&&e.defKind===`UserDefined`),wo=(e,t)=>ho(e.context.table).filter(e=>e.kind===`OpDecl`&&e.declKind===t).toReversed(),To=e=>e.context.symbols.filter(e=>e.kind===`ThmOrAssumpDef`),Eo=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),Do=e=>{let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},Oo=e=>{switch(e.kind){case`Identifier`:return Do(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=Do(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}}})}},ko=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},Ao=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,jo=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,Mo=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),No=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,Po=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],Fo=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},Io=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):xo(u.letInContext,p)),f===void 0&&(p!==void 0&&(u.name=p,u.nameLocation=Fo(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: \`${Ao(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=Fo(u.nameLocation,l(u.index)),u.name=p,Mo(f)&&t.length!==1)return e.addError(l(u.index),`Cannot take subexpression of \`${u.name}'.`);let h=bo(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 \`${Ao(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
38
+ 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(jo(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=jo(f.op,a.length);if(o){let e=jo(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=jo(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=Po(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=jo(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(jo(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=jo(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
39
+ 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`?bo(f.op):u.previousMode===`FindingOpName`&&No(f)?bo(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:bo(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=Eo.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}.`)},Lo=/* @__PURE__ */ new Map([[`(`,`)`],[`[`,`]`],[`{`,`}`],[`<<`,`>>`]]),Ro=(e,t)=>`${e}:${t}`,zo=(t,n)=>{let r=e.tt(n).filter(e=>e.kind!==`End`).map(e.et),i=[0,0];for(let e=0;e<n.length;e++)n[e]===`
40
+ `&&i.push(e+1);return{name:t,source:n,tokens:r,lineOffsets:i,tokenIndexes:new Map(r.map((e,t)=>[Ro(e.line,e.column),t]))}},K=(e,t,n)=>e.tokens[t]!==void 0&&e.tokens[t].text===n&&e.tokens[t].kind!==`String`,Bo=(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},Vo=(e,t)=>e.tokenIndexes.get(Ro(t.line,t.column))??Math.min(Bo(e,t,!1),e.tokens.length-1),Ho=(e,t)=>Math.max(Bo(e,t,!0)-1,0),Uo=(e,t)=>{let n=e.tokens[t].text,r=Lo.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},Wo=(e,t)=>({start:Vo(e,t.start),end:Ho(e,t.end)}),q=(e,t)=>{let n=t.location.range;if(n)return Wo(e,n);let r=Vo(e,t.location);return{start:r,end:Uo(e,r)}},Go=(e,t)=>{let n=t.start-1,r=t.end+1;return K(e,n,`(`)&&K(e,r,`)`)&&Uo(e,n)===r?Go(e,{start:n,end:r}):t},Ko=(e,t)=>{let n=t.start-1,r=t.end+1;return K(e,n,`(`)&&Uo(e,n)===r&&(K(e,n-1,`(`)||K(e,n-1,`,`))?Ko(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}),qo=(e,t)=>J(e,{start:t,end:t}),Jo=(t,n,r)=>{let i=0,a=t.lineOffsets[n];for(;a<t.source.length;){if(i=t.source[a]===` `?e.$(i):i+1,i>=r)return a;a++}return a},Yo=(e,t)=>{let n=e.tokens[t],r=Jo(e,n.line,n.column);return e.source.slice(r,Jo(e,n.line,n.endColumn)+1)},Xo=(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},Zo=t=>{let n=zo(``,t),r=n.tokens.reduce((e,t,r)=>{if(!Xo(n,r))return e;let i=Jo(n,t.line,t.column);return`${e.slice(0,i)} ${e.slice(i+2)}`},t);if(r!==t&&e.A(t)!==void 0)throw new e.ft(`SANY rejects a []ASSUME or []PROVE outside an ASSUME/PROVE`);return r},Qo=(e,t)=>{let n=e.tokens[t-1],r=e.tokens[t],i=n===void 0?0:Jo(e,n.line,n.endColumn)+1,a=e.source.slice(i,Jo(e,r.line,r.column)),o=[],s=0;for(;s<a.length;)if(a.startsWith(`\\*`,s)){let e=a.indexOf(`
41
+ `,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},$o=(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},es=(e,t,n,r)=>{for(let i=t;i<=n;i++)if(K(e,i,r))return i;return-1},ts=new Map(e.j.flatMap(([e,...t])=>t.map(t=>[t,e]))),ns=e=>e.split(`!`).map(e=>ts.get(e)??(e===`~`?`\\lnot`:e)).join(`!`),rs={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}},is=e=>/^[A-Za-z0-9_]+$/.test(e),as=e=>e!==`!!`&&e.includes(`!`),os=e=>e.contexts[e.contexts.length-1],ss=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=xo(e.contexts[n],t);if(r)return r}},cs=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,ls=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,us=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||ds(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&ds(n.module)}return!1},ds=e=>wo(e,2).length===0&&wo(e,3).length===0,fs=t=>[...t.kind===`Let`?t.instances??[]:[],...e.W(t).flatMap(fs)],ps=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:ps(e)):fs(e),ms=(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},hs=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`?fs(e.definition.body):e.kind===`Theorem`&&s?ps(e.theorem.statement):e.kind===`Assumption`&&s?fs(e.assumption.expression):[]).map(e=>e.module).filter(e=>l(e)&&!ms(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}},gs=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),_s=e=>{let t=e.kind===`Apply`?Oo(e):void 0;return gs.has(e.kind)||t!==void 0&&ko(t)},vs=/* @__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`]]),ys=/* @__PURE__ */ new Set([`N_GeneralId`,`N_OpApplication`,`N_PrefixExpr`,`N_InfixExpr`,`N_PostfixExpr`,`N_FcnAppl`,`N_RecordComponent`]),bs=/* @__PURE__ */ new Set([`'`,`^+`,`^*`,`^#`]),xs=(e,t)=>bs.has(t)?`N_GenPostfixOp`:e.kind===`Lambda`||t===`~`||t===`-.`?`N_GenNonExpPrefixOp`:`N_GenInfixOp`,Ss=(t,n,r={})=>{let i=[],a=(e,t)=>ao(i,{location:e,text:t,isWarning:!1}),o=(e,t)=>ao(i,{location:e,text:t,isWarning:!0}),s={value:r.version===`1.7.4`?-1:0},c=()=>++s.value,l={id:0},u=(e,t)=>{let n=ss(e,t.name);if(n===t)return;if(n===void 0){yo(os(e),t);return}let i=t.kind===`FormalParam`||cs(n)!==cs(t)||bo(n)!==bo(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(i&&r.version===`1.7.4`)?a(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):i?a(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${oo(n.location)}.`):us(t,n)||o(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${oo(n.location)}.`)};r.version!==`1.7.4`&&io(c);let d=io(c);c();let f=new Map(d.map(e=>[e.name,e])),p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=(t,n)=>{let i=t===r.rootFileName&&r.rootFilePath||`${t}.tla`,a=n=>new e.dt(`Could not parse module ${t} from file ${i}`,t,n),o=r.version===`1.7.4`?e.Q(n):void 0;if(o!==void 0)throw a(o);try{return e.O(Zo(n))}catch(t){throw t instanceof e.ft?a(e.A(n)??`***Parse Error***\n${t.message}`):t}},g=(t,n,i)=>{let a=m.get(t);if(a)return a;if(n===void 0)throw new e.lt(t,i,r.version!==`1.7.4`);r.onParse?.(t);let o=h(t,n);if(o.name!==t)throw new e.dt(`File name '${t}' does not match the name '${o.name}' of the top level module it contains.`,void 0);let s={file:zo(o.name,n),module:o};return m.set(t,s),s},_=[],v=/* @__PURE__ */ new Set,y=[],b=(t,r,i)=>{let a=y.indexOf(t);if(a!==-1)throw new e.dt(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...y.slice(a),t].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(v.has(t))return;v.add(t),y.push(t);let o=E(t,g(t,r,i).module);[...o.extendees,...o.instancees].forEach(e=>b(e,n(e),t)),y.pop(),_.push(t)},x=/* @__PURE__ */ new Set,S=(e,t)=>x.has(`${e} ${t}`),C=(e,t,n)=>{let r=m.get(e);if(!r||n.has(e))return;n.add(e);let i=E(e,r.module),a=i[t].find(t=>!S(e,t));if(a!==void 0)return{name:a,importer:e,namingModule:i.importers.get(a)??e};for(let r of[...i.extendees,...i.instancees]){let i=S(e,r)?C(r,t,n):void 0;if(i)return i}},w=e=>{g(e,t);let r=()=>C(e,`extendees`,/* @__PURE__ */ new Set)??C(e,`instancees`,/* @__PURE__ */ new Set);for(let e=r();e!==void 0;e=r())m.has(e.name)||g(e.name,n(e.name),e.namingModule),x.add(`${e.importer} ${e.name}`)},T=r.rootFileName??h(``,t).name,E=(e,t)=>{let n=hs(t);return e!==T||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};w(T),b(T,t);let ee=(t,n,i,s)=>{let d={curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSectionCount:0},m=[],h=[],g=[],_=[],v=/* @__PURE__ */ new WeakSet,y=()=>_.push({labels:/* @__PURE__ */ new Map,params:[]}),b=()=>_.pop()?.labels??/* @__PURE__ */ new Map,x={depth:0,isDeclared:[],goal:void 0,goalClause:0},S=/* @__PURE__ */ new WeakMap,C=/* @__PURE__ */ new WeakMap,w=e=>{let t=e.kind===`AssumeProve`?S.get(e):void 0;t&&(t.isInProof=!1)},T=e=>J(n,q(n,e)),E=e=>e.range?Wo(n,e.range):{start:Vo(n,e),end:Vo(n,e)},D={kind:`Module`,id:c(),name:t.name,location:J(n,E(t.location)),extendees:[],context:os(s),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 te=e=>{for(let t=s.contexts.length-1;t>=0;t--){let n=So(s.contexts[t],e);if(n?.kind===`Module`)return n}return p.get(e)},ne=t=>{let n=te(t);if(n===void 0)throw new e.ft(`Could not find module ${t}`);return n},O=(e,t)=>{s.contexts.push(e);let n=t();return s.contexts.pop(),n},k=(e,t,n,r)=>{let i={...G(c()),kind:`FormalParam`,name:e,arity:t,location:n};return r&&u(s,i),i},re=e=>({...G(c()),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}),ie=e=>{e.letInLevel=d.curLevel,d.unresolvedSum>0&&(e.recursiveSection=d.recursiveSectionCount,e.inRecursiveSection=d.unresolvedCount[d.curLevel]>0,D.opDefsInRecursiveSection.push(e))},A=(e,t,n,r={},i=c())=>({...G(i),kind:`OpAppl`,operator:e,operands:t,unbounded:r.unbounded,bounded:r.bounded,tupleOrs:r.tupleOrs,ranges:r.ranges??[],location:n}),j=()=>({...A(M(`$Nop`),[],ro,{},l.id),isNull:!0}),M=t=>{let n=f.get(t);if(!n)throw new e.pt(`SANY has no builtin operator ${t}`);return n},N=(e,t,n,r={})=>A(M(e),t,n,r),ae=(e,t)=>({...G(c()),kind:`String`,value:e,location:t}),oe=(e,t)=>({...G(c()),kind:`OpArg`,op:e,location:t}),se=(t,n)=>{let r=ss(s,ns(t));if(r===void 0||r.kind===`Module`)throw new e.ft(`Unknown operator: \`${t}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},P=(e,t,n)=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`)return;let r=e.params??[];r.length===t.length?r.forEach((r,i)=>{let o=t[i];r.arity===0&&o.kind===`OpArg`&&a(n,`Operator used in argument number ${i+1} has incorrect number of arguments.`);let s=o.kind===`OpArg`&&bo(o.op)===r.arity&&!(o.op.kind===`OpDef`&&(o.op.params??[]).some(e=>e.arity>0));r.arity>0&&!s&&a(n,`Argument number ${i+1} to operator '${e.name}' \nshould be a ${r.arity}-parameter operator.`)}):a(n,`Wrong number of arguments (${t.length}) given to operator '${e.name}', \nwhich requires ${r.length} arguments.`)},F=Io({version:r.version,resolveSymbol:e=>ss(s,e),resolveSynonym:ns,generateExpression:e=>R(e),generateArgument:(e,t,n,r)=>ge(e,t,n,r),createOpAppl:(e,t,n)=>{let r=A(e,t,n);return P(e,t,n),r},createOpArg:oe,createFormalParam:(e,t,n)=>k(e,t,n,!1),createLambda:(e,t,r)=>re({name:`LAMBDA`,params:e,body:t,location:r,preComments:Qo(n,Vo(n,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>Be(`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:M,addError:(e,t)=>(a(e,t),j()),isOutOfLabelScope:e=>{let t=C.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=S.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}}),I=(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=es(n,r.value,t.end,i);if(a===-1)return e;if(e.op===`Null`){let t=Uo(n,a);return r.value=t+1,{...e,location:J(n,{start:a,end:t})}}r.value=a+1;let o=qo(n,a);if(e.args===void 0||!K(n,a+1,`(`))return{...e,location:o};let s=Uo(n,a+1);return r.value=s+1,{...e,location:o,argsLocation:J(n,{start:a+1,end:s})}})},ce=(t,r,i,a)=>{let o=Oo(t);if(o===void 0)throw new e.ft(`Expected a name, found ${t.kind}`);return F(I(o,q(n,t)),r,i,a,T(t))},le=t=>{let n=ce(t,0,!1,!1);if(n.kind!==`OpAppl`)throw new e.ft(`Expected an expression`);return n},ue=e=>{if(e.kind!==`OpAppl`)return;let t=m.find(t=>t.name===e.operator.name);t&&(t.node.operator=M(`$RecursiveFcnSpec`))},de=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},[]),fe=(e,t)=>ke(e,t,de(e).map(e=>R(e[0].set))),pe=(e,t)=>{let n=_.at(-1);n?.params.push(e);let r=R(t);return n?.params.pop(),r},L=e=>{let t=q(n,e),r=$o(n,t.start,t.end,e.params);return O(_o(),()=>{let i=e.params.map((e,t)=>k(e,0,qo(n,r[t]),!0)),a=pe(i,e.body);return re({name:`LAMBDA`,params:i,body:a,location:J(n,t),preComments:Qo(n,t.start)})})},me=e=>e.kind===`OperatorReference`?e.operator:e.kind===`Lambda`&&e.body.kind===`Apply`?e.body.operator:n.tokens[Vo(n,e.location)].text,he=(t,n)=>{let r=T(t);if(t.kind===`Lambda`)return t.location.range===void 0?oe(se(me(t),r),r):oe(L(t),r);if(!_s(t))return a(r,`Arity ${n.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${n.name}'.`),j();if(t.kind===`OperatorReference`)return oe(se(t.operator,r),r);let i=ce(t,n.arity,!1,!1);if(i.kind===`OpArg`||i.kind===`OpAppl`&&i.isNull===!0)return i;throw new e.ft(`Expected an operator argument at line ${r.beginLine}, column ${r.beginColumn}`)},ge=(t,r,i,o)=>{let c=t.kind===`OpDef`&&(t.defKind===`UserDefined`||t.defKind===`ModuleInstance`)?t.params?.[r]?.arity??0:0;if(c===0)return R(i);let l=q(n,i),u=J(n,l),d=`${r+1} (counting from 1)`,f=Ko(n,l);if(f!==l||!_s(i))return a(J(n,f),`An expression appears as argument number ${d} to operator '${t.name}', in a position an operator is required.`),j();if(i.kind===`Identifier`||i.kind===`Subexpression`||i.kind===`Apply`){let t=ce(i,c,!1,!1);if(t.kind===`OpArg`||t.kind===`OpAppl`)return t;throw new e.ft(`Expected an operator argument at ${oo(u)}`)}if(i.kind===`Lambda`&&i.location.range!==void 0){let e=L(i),n=bo(e);return n===c?oe(e,u):(a(o,`Lambda expression with arity ${n} used as argument ${r+1} of operator \`${t.name}', \nbut an operator of arity ${c} is required.`),j())}let p=me(i),m=ss(s,ns(p));if(m===void 0)return a(u,`Could not find declaration or definition of symbol '${p}'.`),j();let h=bo(m);return h===c?oe(m,u):(a(o,`Operator with incorrect arity passed as argument. \nOperator '${m.name}' of arity ${h} is argument number ${d} to operator \`${oo(t.location)}', \nbut an operator of arity ${c} was expected.`),j())},_e=e=>{let t=T(e);if(e.isBulleted)return N(e.kind===`And`?`$ConjList`:`$DisjList`,e.operands.map(R),t);let r=q(n,e),i=e.kind===`And`?`\\land`:`\\lor`,[a,...o]=e.operands;return o.reduce((e,t,a)=>{let s=Go(n,q(n,t)),c=a===o.length-1?r.end:s.end;return N(i,[e,R(t)],J(n,{start:r.start,end:c}))},R(a))},ve=e=>{let t=q(n,e),r=e.arms.map((r,i)=>{let a=Go(n,q(n,r.condition)),o=i===e.arms.length-1&&e.other===void 0,s=Go(n,q(n,r.body)),c=[R(r.condition),R(r.body)];return N(`$Pair`,c,J(n,{start:a.start,end:o?t.end:s.end}))}),i=e.other;if(i){let e=Go(n,q(n,i)),a=ye(e.start,`OTHER`);r.push(N(`$Pair`,[void 0,R(i)],J(n,{start:a,end:t.end})))}return N(`$Case`,r,J(n,t))},ye=(e,t)=>{for(let r=e;r>=0;r--)if(K(n,r,t))return r;return e},be=e=>{let t=q(n,e),r=J(n,t),i=[R(e.function)],a=N(`$Except`,i,r),o=q(n,e.function),s={value:es(n,o.end+1,t.end,`EXCEPT`)+1};return e.updates.forEach(e=>{let r=es(n,s.value,t.end,`!`),o=Go(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=xe(l.value,e.name);return l.value=t+1,ae(e.name,qo(n,t))}let r=es(n,l.value,t.end,`[`),i=Uo(n,r);return l.value=i+1,e.args.length===1?R(e.args[0]):N(`$Tuple`,e.args.map(R),J(n,{start:r,end:i}))}),d=N(`$Seq`,u,c),f=N(`$Pair`,[d],c);g.push(f),h.push(a),f.operands.push(R(e.value)),g.pop(),h.pop(),i.push(f),s.value=o.end+1}),a},xe=(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},Se=(e,t)=>{let r=q(n,t),i={value:r.start+1},o=t.fields.map((e,r)=>{let o=xe(i.value,e.name),s=Go(n,q(n,e.value));return i.value=s.end+1,t.fields.slice(0,r).some(t=>t.name===e.name)&&a(qo(n,o),`Non-unique fields in constructor.`),N(`$Pair`,[ae(e.name,qo(n,o)),R(e.value)],J(n,{start:o,end:s.end}))}),s=N(e,o,J(n,r));return D.records.push(s),s},Ce=e=>({line:n.tokens[e].line,column:n.tokens[e].column}),we=e=>{let t=[],r=e;for(;n.tokens[r]?.kind===`Identifier`;){let e=K(n,r+1,`(`)?Uo(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:{...Ce(r),range:{module:n.name,start:Ce(r),end:Ce(e)}}}),!K(n,e+1,`,`))break;r=e+2}return t},Te=e=>{let t=[...e.definitions.map(e=>({unit:{kind:`Definition`,definition:e},span:Me(e)})),...(e.instances??[]).map(e=>({unit:{kind:`Instance`,instance:e},span:Me(e)}))],r=q(n,e).start,i=Go(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:we(e+1)},span:{start:e,end:e}})}return[...t,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},Ee=e=>{let t=_o();return O(t,()=>{d.curLevel++,d.unresolvedCount[d.curLevel]=0;let n=[],r=[];Te(e).forEach(e=>{e.kind===`Recursive`?Le(e.declarations):e.kind===`Instance`?Ve(e.instance,n,r):e.definition.kind===`Function`?Fe(e.definition,n):Ne(e.definition,n)}),Re(),d.curLevel=Math.max(d.curLevel-1,0);let i=R(e.body);return{...G(c()),kind:`LetIn`,opDefs:n,instances:r,body:i,context:t,location:T(e)}})},De=e=>{let t=q(n,e),r=J(n,t);return O(_o(),()=>{let i=e.pattern,a=i.kind===`Name`?[i.name]:i.names;if(e.set===void 0){let o=$o(n,t.start,t.end,a),s=a.map((e,r)=>k(e,0,qo(n,i.kind===`Name`?t.start:o[r]),!0)),c=pe(s,e.body);return N(`$UnboundedChoose`,[c],r,{unbounded:s})}let o=R(e.set),s=q(n,e.set),c=$o(n,t.start,s.start,a),l=a.map((e,t)=>k(e,0,qo(n,c[t]),!0)),u=pe(l,e.body);return N(`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},Oe=e=>{if(is(e.operator)||as(e.operator)||e.args.length>2||ss(s,ns(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=Go(n,q(n,e.args[0])),i=e.args.length===1&&r.start!==t.start,a=i?t.start:r.end+1,o=Yo(n,a);return{index:a,name:i&&o===`-`?`-.`:o,fixity:i?`prefix`:e.args.length===2?`infix`:`postfix`}},R=e=>{let t=T(e);switch(e.kind){case`Number`:return{...G(c()),kind:`Numeral`,value:Cs(e.text??String(e.value)),location:t};case`Decimal`:{let[n,r]=e.text.split(`.`),i=BigInt(n+r),a=i<=9223372036854775807n;return{...G(c()),kind:`Decimal`,mantissa:i.toString(),exponent:String(a?-r.length:r.length),integralPart:n,fractionalPart:r,location:t}}case`String`:return ae(e.value,t);case`Identifier`:{let t=le(e);return ue(t),t}case`Apply`:{let r=Oe(e);if(r!==void 0)return a(qo(n,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),a(t,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...j(),isAbsent:!0};let i=le(e);return(as(e.operator)||is(e.operator))&&ue(i),i}case`Bracket`:return a(qo(n,q(n,e).start),"Unsupported expression type `['."),{...j(),isAbsent:!0};case`OperatorReference`:case`Lambda`:{let r=n.tokens[q(n,e).start].text;return a(t,r===`LAMBDA`?`LAMBDA expression used where an expression is required.`:`Unsupported expression type \`${xs(e,r)}'.`),{...j(),isAbsent:!0}}case`And`:case`Or`:return _e(e);case`Prime`:return N(`'`,[R(e.expression)],t);case`Unchanged`:return N(`UNCHANGED`,[R(e.expression)],t);case`Enabled`:return N(`ENABLED`,[R(e.expression)],t);case`Always`:return N(`[]`,[R(e.expression)],t);case`Eventually`:return N(`<>`,[R(e.expression)],t);case`If`:return N(`$IfThenElse`,[R(e.condition),R(e.consequent),R(e.alternative)],t);case`Case`:return ve(e);case`Let`:return Ee(e);case`Forall`:case`Exists`:{let r=q(n,e);return O(_o(),()=>{let n=fe(e.bounds,r.start),i=pe(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=$o(n,r.start,i.start,e.names),o=e.isTemporal?e.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:e.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return O(_o(),()=>{let r=e.names.map((e,t)=>k(e,0,qo(n,a[t]),!0)),i=pe(r,e.body);return N(o,[i],t,{unbounded:r})})}case`Choose`:return De(e);case`SetEnumeration`:return N(`$SetEnumerate`,e.elements.map(R),t);case`Tuple`:return N(`$Tuple`,e.elements.map(R),t);case`SetFilter`:{let r=R(e.bound.set),i=q(n,e);return O(_o(),()=>{let n=ke([e.bound],i.start,[r]),a=pe(n.bounded.flat(),e.predicate);return N(`$SubsetOf`,[a],t,n)})}case`SetMap`:{let r=q(n,e.expression);return O(_o(),()=>{let n=fe(e.bounds,r.end+1),i=pe(n.bounded.flat(),e.expression);return N(`$SetOfAll`,[i],t,n)})}case`FunctionConstruction`:{let r=q(n,e);return O(_o(),()=>{let n=fe(e.bounds,r.start),i=pe(n.bounded.flat(),e.body);return N(`$FcnConstructor`,[i],t,n)})}case`FunctionSet`:return N(`$SetOfFcns`,[R(e.domain),R(e.range)],t);case`Record`:return Se(`$RcdConstructor`,e);case`RecordSet`:return Se(`$SetOfRcds`,e);case`Except`:return be(e);case`ExceptAt`:{let e=h[h.length-1],n=g[g.length-1];return e===void 0||n===void 0?(a(t,`@ used where its meaning is not defined.`),j()):{...G(c()),kind:`At`,except:e,component:n,location:n.location}}case`FunctionApplication`:{let n=R(e.function);if(so(n))return n;ue(n);let r=e.args.length===1?R(e.args[0]):N(`$Tuple`,e.args.map(R),t);return N(`$FcnApply`,[n,r],t)}case`FieldAccess`:{let r=R(e.record),i=q(n,e);return N(`$RcdSelect`,[r,ae(e.field,qo(n,i.end))],t)}case`Product`:return N(`$CartesianProd`,e.factors.map(R),t);case`BoxAction`:case`AngleAction`:return N(e.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[R(e.action),R(e.subscript)],t);case`WeakFairness`:case`StrongFairness`:return N(e.kind===`WeakFairness`?`$WF`:`$SF`,[R(e.subscript),R(e.action)],t);case`Label`:return Ae(e);case`Subexpression`:return le(e)}},ke=(e,t,r)=>{let i=de(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=$o(n,a.value,t.start,r);return a.value=t.end+1,r.map((e,t)=>k(e,0,qo(n,i[t]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},Ae=e=>{let t=T(e),r=_.at(-1);if(r===void 0)return a(t,`Label not in definition or proof step.`),j();if(x.isDeclared.slice(2,x.depth+1).some(Boolean))return a(t,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),j();if(h.length>0&&g.length>0)return a(t,`Labels inside EXCEPT clauses are not yet implemented.`),j();y();let i=R(e.body),o=b(),l=$o(n,q(n,e).start,q(n,e.body).start,e.params),u=e.params.map((t,r)=>{let i=ss(s,t);if(i?.kind===`FormalParam`)return i;let o=qo(n,l[r]);return a(o,`Illegal parameter ${t} of label \`${e.name}'.`),k(t,0,o,!1)}),d={...G(c()),kind:`Label`,name:e.name,params:u,body:i,labels:o,isAssumeProve:!1,location:t},f=/* @__PURE__ */ new Set;if(u.forEach(e=>{f.has(e)&&a(t,`Repeated formal parameter ${e.name} \nin label \`${d.name}'.`),f.add(e)}),r.params.flat().forEach(e=>{f.delete(e)||a(t,`Label ${d.name} must contain formal parameter \`${e.name}'.`)}),f.size>0){let e=[...f].map(e=>`${e.name} `).join(``);a(t,`Label ${d.name} declares extra parameter(s) ${e}`)}r.labels.has(d.name)?a(t,`Duplicate label \`${d.name}'.`):r.labels.set(d.name,d);let p=x.goal;return p&&C.set(d,{scope:p,clause:x.goalClause}),d},je=(e,t,r)=>{let i={value:t.start};return e.params.map(e=>{let t=e.location?Vo(n,e.location):xe(i.value,e.name),a=ut(t,e.arity);return i.value=a.end+1,k(ns(e.name),e.arity,J(n,a),r)})},Me=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},Ne=(e,t)=>{let r=Me(e),i=J(n,r),o=ns(e.name),c={start:e.isLocal?r.start+1:r.start,end:r.end},l=O(_o(),()=>{let t=je(e,c,!0),n=ss(s,o);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===d.curLevel?e||a(i,`Definition of ${n.name} has different arity than its RECURSIVE declaration.`):a(i,`Recursive operator ${o} defined at wrong LET/IN level.`)}else n!==void 0&&a(i,`Operator ${o} already defined or declared.`);return y(),{params:t,body:R(e.body),existing:n}}),f=b(),p=l.existing,m=l.params,h=Qo(n,r.start);if(p?.kind===`OpDef`&&p.inRecursive&&!p.isDefined&&p.letInLevel===d.curLevel){p.params=m,p.weights=m.map(()=>0),p.maxLevels=m.map(()=>3),p.isLeibnizArg=m.map(()=>!0),p.labels=f,Pe(p,l.body,i,h),D.definitions.push(p),t?.push(p);return}let g=re({name:o,params:m,body:l.body,isLocal:e.isLocal,location:i,preComments:h,labels:f});u(s,g),ie(g),D.definitions.push(g),t?.push(g)},Pe=(e,t,n,r)=>{e.isDefined=!0,e.body=t,e.location=n,e.preComments=r,e.inRecursive&&(d.unresolvedCount[d.curLevel]--,d.unresolvedSum--)},Fe=(e,t)=>{let r=Me(e),i=J(n,r),o=_o(),c=e.isLocal?r.start+1:r.start,l=O(o,()=>fe(e.bounds,c+1)),f=ss(s,e.name),p=O(o,()=>k(e.name,0,i,f===void 0)),h=N(`$NonRecursiveFcnSpec`,[],i,{unbounded:[p],...l}),g=f?.kind===`OpDef`&&f.inRecursive&&!f.isDefined,_=g&&f.letInLevel===d.curLevel;_?f.arity!==0&&a(i,`Function ${f.name} has operator arguments in its RECURSIVE declaration.`):g?a(i,`Recursive function ${e.name} defined at wrong LET/IN level.`):f!==void 0&&a(i,`Function name \`${e.name}' already defined or declared.`);let v=Qo(n,r.start),x=f===void 0?re({name:e.name,params:[],body:h,isLocal:e.isLocal,location:i,preComments:v}):f.kind===`OpDef`&&(_||!g)?f:void 0;_?f.arity===0&&Pe(f,h,i,v):f===void 0&&x!==void 0&&(u(s,x),ie(x)),x!==void 0&&(D.definitions.push(x),t?.push(x)),m.unshift({name:e.name,node:h}),y();let S=()=>pe(l.bounded.flat(),e.body),C=x===void 0?S():O(o,S),w=b();x!==void 0&&(x.labels=w),m.shift(),h.operands=[C],h.operator.name===`$NonRecursiveFcnSpec`&&(h.unbounded=void 0)},Ie=[],Le=e=>{d.unresolvedSum===0&&d.recursiveSectionCount++,d.unresolvedCount[d.curLevel]+=e.length,d.unresolvedSum+=e.length,e.forEach(e=>{let t=dt(e);c();let r=Array.from({length:e.arity},()=>k(``,0,void 0,!1)),i=re({name:ns(e.name),params:r,location:J(n,t),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:d.recursiveSectionCount,letInLevel:d.curLevel});u(s,i),Ie.push(i),D.opDefsInRecursiveSection.push(i)})},Re=()=>{d.unresolvedCount[d.curLevel]!==0&&(Ie.filter(e=>e.letInLevel===d.curLevel&&!e.isDefined).forEach(e=>a(e.location,`Symbol ${e.name} declared in RECURSIVE statement but not defined.`)),d.unresolvedSum-=d.unresolvedCount[d.curLevel])},ze=(e,t,i)=>{c();let o=ho(t.table).filter(e=>e.kind===`OpDecl`),l=o.flatMap(e=>{let t=ss(s,e.name);return t===void 0?[]:[{op:e,expr:e.declKind===3||e.declKind===2&&e.arity===0?A(t,[],i):oe(t,i),isImplicit:!0}]}),u=(e,t)=>{let n=t.kind===`OpArg`?bo(t.op):0,r=e.arity>0&&t.kind===`OpAppl`&&t.isNull===!0;n!==e.arity&&!r&&a(t.location,`An operator must be substituted for symbol '${e.name}', and it must have arity ${e.arity}.`)},d=Me(e),f={value:es(n,d.start,d.end,`WITH`)+1};return e.substitutions.forEach(e=>{let r=es(n,f.value,d.end,e.name);r!==-1&&(f.value=q(n,e.expression).end+1);let o=xo(t,ns(e.name));if(o?.kind!==`OpDecl`){a(r===-1?i:qo(n,r),`Identifier '${r===-1?e.name:Yo(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=o.arity===0?R(e.expression):he(e.expression,o);u(o,s);let c=l.find(e=>e.op.name===o.name);c&&!c.isImplicit?a(T(e.expression),`Multiple substitutions for symbol '${o.name}' in substitution.`):c?(c.expr=s,c.isImplicit=!1):l.push({op:o,expr:s,isImplicit:!1})}),l.filter(e=>e.isImplicit&&r.version!==`1.7.4`).forEach(e=>u(e.op,e.expr)),o.filter(e=>!l.some(t=>t.op.name===e.name)).forEach(e=>a(i,`Substitution missing for symbol ${e.name} declared at ${oo(e.location)} \nand instantiated in module ${D.name}.`)),l},Be=(e,t,n,r,i,o=D)=>(so(n)&&a(i,e===`SubstIn`?`Substitution error, probably due to error
42
+ in module being instantiated.`:`Substitution error, probably due to error in module being instantiated.`),{...G(c()),kind:e,substs:t,body:n,instantiatingModule:o,instantiatedModule:r,location:i}),Ve=(e,t,i)=>{let a=Me(e),o=J(n,a),l=Qo(n,a.start),d=e.name??``,f=_o(),p=e.isLocal?a.start+1:a.start;e.params.length>0&&s.contexts.push(f);let m=je(e,{start:p,end:a.end},e.params.length>0),h=ne(e.module),g=h.context,_=ze(e,g,o);e.params.length>0&&s.contexts.pop(),ho(g.table).forEach(n=>{if(n.kind!==`OpDef`||n.isLocal||n.defKind!==`UserDefined`&&n.defKind!==`ModuleInstance`)return;let r=[...m,...n.params??[]],i=`${d}!${n.name}`,a=n.defKind===`UserDefined`?re({name:i,params:r,body:_.length>0&&n.body?Be(`SubstIn`,_,n.body,h,o):n.body,isLocal:e.isLocal,location:o,source:n.source??n,preComments:l,labels:n.labels}):re({defKind:`ModuleInstance`,name:i,params:r,isLocal:e.isLocal,location:o,module:n.module,source:n.source??n,preComments:l});u(s,a),n.defKind===`UserDefined`&&ie(a),(t??D.definitions).push(a)}),ho(g.table).forEach(n=>{if(n.kind!==`ThmOrAssumpDef`||n.isLocal)return;let r=_.length>0?Be(`APSubstIn`,_,n.body,h,o):n.body,i={...G(c()),kind:`ThmOrAssumpDef`,name:`${d}!${n.name}`,isTheorem:n.isTheorem,body:r,params:[...m,...n.params],isLocal:e.isLocal,location:o,module:D,source:n.source??n,labels:n.labels,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]};u(s,i),(t??D.definitions).push(i)});let v={...G(c()),kind:`Instance`,name:d,isLocal:e.isLocal,params:m,module:h,substs:_,location:o};(i??D.topLevel).push(v);let y=re({defKind:`ModuleInstance`,name:d,params:m,isLocal:e.isLocal,location:o,preComments:l});u(s,y),r.version!==`1.7.4`&&t?.push(y)},He=(e,t=!0,r)=>{let i=Me(e),a=r??J(n,i),o=Qo(n,i.start),l=ne(e.module),d=l.context,f=ze(e,d,a),p=e.isLocal,m=ds(l);ho(d.table).forEach(e=>{if(e.kind!==`OpDef`||e.defKind!==`UserDefined`||e.isLocal)return;let t=(t,n)=>{let r=re({name:e.name,params:e.params,body:n,isLocal:p,location:a,module:t,source:e.source??e,preComments:o,labels:e.labels});return u(s,r),r},n=()=>(u(s,e),e),r=e.module===void 0||ds(e.module),i=m||r?p?t(e.module,e.body):n():t(D,e.body&&Be(`SubstIn`,f,e.body,l,a));D.definitions.push(i),ie(i)}),ho(d.table).forEach(e=>{if(e.kind!==`ThmOrAssumpDef`||e.isLocal)return;let n=(t,n)=>{let r={...e,...G(c()),body:n,isLocal:p,location:a,module:t,source:e.source??e};return u(s,r),r},r=m?p?n(e.module,e.body):(u(s,e),e):ds(e.module)?p?n(D,e.body):e:n(D,Be(`APSubstIn`,f,e.body,l,a));t&&D.definitions.push(r)});let h={...G(c()),kind:`Instance`,name:void 0,isLocal:p,params:[],module:l,substs:f,location:a};return t&&D.topLevel.push(h),h},Ue=e=>{let t=te(e.name)??(e.name===D.name?D:void 0);return t===void 0?(a(qo(n,Vo(n,e.location)+1),`Module \`${e.name}' used without being extended or instantiated.`),[]):[t]},We=t=>t.flatMap(t=>{if(t.kind===`ModuleFact`)return Ue(t);let n=Oo(t);if(n===void 0||!ko(n))return[R(t)];let r=ce(t,0,!0,!1);if(r.kind===`ThmOrAssumpDef`)throw new e.ft(`Expected a fact`);return[r]}),Ge=e=>K(n,e.start,`(`)&&Uo(n,e.start)===e.end,Ke=e=>Go(n,q(n,e)),qe=(e,t)=>Ke(e.args[0]).start===t.start?e.args.length===2?`N_InfixExpr`:`N_PostfixExpr`:n.tokens[t.start].kind===`Identifier`?`N_OpApplication`:`N_PrefixExpr`,Je=(e,t)=>Ge(t)?`N_ParenExpr`:e.kind===`String`?Yo(n,t.start):e.kind===`Apply`?qe(e,t):vs.get(e.kind),Ye=(e,t)=>{if(e.kind===`String`&&!Ge(t))return!1;if(e.kind===`Identifier`&&!e.name.includes(`!`))return!0;let n=Je(e,t);return n===void 0||ys.has(n)?void 0:!0},Xe=(e,t)=>{let r=(e,t=Ke(e))=>({last:t,lastKind:Je(e,t)});if(Ge(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:Ye(e.expression,Ke(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=Ke(t),i=r.end+1;return{hasChildlessFirstChild:Ye(t,r),last:{start:i,end:i},lastKind:n.tokens[i].text}}case`Apply`:{let n=qe(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=Ke(e.args[0]),a=i.end+1;return{hasChildlessFirstChild:Ye(e.args[0],i),last:{start:a,end:a},lastKind:n===`N_InfixExpr`?`N_GenInfixOp`:`N_GenPostfixOp`}}}},Ze=e=>{let t=Go(n,q(n,e));if((e.kind===`Identifier`||e.kind===`Subexpression`||e.kind===`OperatorReference`)&&!Ge(t))return!1;let r=Xe(e,t);if(r?.hasChildlessFirstChild===void 0||r.lastKind===void 0)return!1;let i=J(n,r.last);return r.hasChildlessFirstChild&&a(J(n,t),`Was expecting a GeneralId.`),r.lastKind===`N_OpArgs`?a(i,"Selector `!(...)' should not have argument(s)."):(a(i,`Unexpected token found.`),a(i,`Need name or step number here, not \`${r.lastKind}'.`)),a(J(n,t),`DEF clause entry should describe a defined operator.`),!0},Qe=e=>e.flatMap(e=>{if(e.kind===`ModuleFact`)return Ue(e);if(Ze(e))return[];let t=ce(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]:(a(T(e),`DEF clause entry should describe a defined operator.`),[])}),$e=(e,t)=>{e.isOnly||e.facts.length+e.defs.length>0||a(t,`Empty BY, USE, or HIDE`)},et=e=>{let t=J(n,E(e.location));$e(e,t);let r=We(e.facts),i=Qe(e.defs);return r.length+i.length===0&&a(t,`Empty USE or HIDE statement.`),e.kind===`Hide`&&r.filter(e=>e.kind===`OpAppl`&&e.operator.kind!==`ThmOrAssumpDef`).forEach(e=>a(e.location,`The only expression allowed as a fact in a HIDE is
43
+ the name of a theorem, assumption, or step.`)),{...G(c()),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&&R(e.set),i=xe(t.start,e.name),a=rs[e.level],o={...G(c()),levelChecked:1,level:a.level,kind:`OpDecl`,name:ns(e.name),arity:e.arity,declKind:a.declKind,location:J(n,ut(i,e.arity)),module:D};return u(s,o),{...G(c()),kind:`NewSymb`,declaration:o,set:r,location:J(n,t)}},nt=(e,t,r)=>{let i=E(e.location),o=Xo(n,i.start-1),l=q(n,e.conclusion).start,u=n.tokens.findLastIndex((e,t)=>t<l&&e.kind===`Keyword`&&e.text===`PROVE`),d=J(n,{start:o?i.start-1:i.start,end:i.start});o!==Xo(n,u-1)&&a(d,o?`[]ASSUME matched by PROVE instead of []PROVE`:`ASSUME matched by []PROVE instead of PROVE`);let f=c();t>1&&s.contexts.push(_o()),o&&s.contexts.some(e=>v.has(e))&&a(d,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),o||v.add(os(s));let p={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};x.depth=t,x.isDeclared[t]=!1,t===1&&(x.goal=r&&p,x.goalClause=0);let m=e.assumptions.map((e,n)=>{let r=e.kind===`NewSymbol`,i=e.kind===`AssumeProve`?nt(e,t+1):r?tt(e):R(e);return x.depth=t,r&&(x.isDeclared[t]=!0),p.isDeclaredBefore.push(p.isDeclaredBefore[n]||r),t===1&&x.goalClause++,i}),h=R(e.conclusion);t>1&&s.contexts.pop(),x.depth=t-1,t===1&&(x.goal=void 0);let g={...G(f),kind:`AssumeProve`,assumptions:m,goal:h,isSuffices:p.isSuffices,isBoxed:o,location:J(n,{start:o?i.start-1:i.start,end:i.end})};return S.set(g,p),g},rt=(e,t,n,r,i,a=!0)=>({...G(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`&&$e(e,t);let r=e.kind===`By`?We(e.facts):[],i=e.kind===`By`?Qe(e.defs):[];return e.kind===`By`&&c(),e.kind===`By`&&r.length+i.length===0&&a(t,`Empty BY`),{...G(c()),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`,[R(r.expression)],i),isPick:!1};case`Case`:return{node:N(`$Pfcase`,[R(r.expression)],i),isPick:!1};case`Witness`:return{node:N(`$Witness`,r.expressions.map(R),i),isPick:!1};case`Qed`:return{node:N(`$Qed`,[],i),isPick:!1};case`Take`:case`Pick`:{let e=r.kind===`Pick`,a=e?`$Pick`:`$Take`;e&&s.contexts.push(_o());let o=e=>r.kind===`Pick`?[pe(e,r.body)]:[];if(r.bounds.length>0){let n=fe(r.bounds,t.start),s=o(n.bounded.flat());return{node:N(a,s,i,n),isPick:e}}let c=$o(n,t.start,t.end+1,r.names),l=r.names.map((e,t)=>k(e,0,qo(n,c[t]),!0)),u=o(l);return{node:N(a,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=Go(n,q(n,e.args[0])),r=q(n,e).start;return t.start===r&&!K(n,t.end+1,`(`)},st=t=>{if(t.kind!==`Steps`)return it(t);let r=_o();s.contexts.push(r);let i=[],a=[],o={previousRight:void 0},l=(t,r,a)=>{if(t.kind===`Define`){let r=t.definitions.map(t=>{let n=[];t.kind===`Instance`?Ve(t,n,i):t.kind===`Function`?Fe(t,n):Ne(t,n);let r=n[t.kind===`Instance`?n.length-1:0];if(r?.kind!==`OpDef`)throw new e.ft(`A DEFINE step defines no operator`);return r});return{...G(c()),kind:`DefStep`,defs:r,location:J(n,a)}}if(t.kind===`Use`||t.kind===`Hide`)return{...et(t),location:J(n,r)};if(t.kind===`Instance`)return He(t,!1,J(n,a))},d=t.steps.map(t=>{let r=E(t.location),i=Wo(n,t.head),d={start:i.start+1,end:i.end},f=t.body;t.name!==void 0&&y();let p=t.name===void 0?void 0:c();f.kind!==`Assert`&&(o.previousRight=void 0);let m=l(f,r,d);if(m!==void 0)return t.name!==void 0&&u(s,re({defKind:`NumberedProofStep`,name:t.name,location:J(n,r),labels:b(),step:m})),m;let h=f.kind===`Assert`&&f.statement.kind===`AssumeProve`;h&&(o.previousRight=void 0);let g=f.kind===`Assert`&&f.isSuffices,_=_o(),v=f.kind===`Assert`?{node:(e=>{if(e.kind===`AssumeProve`){let n=O(_,()=>nt(e,1,t.name===void 0?void 0:{isSuffices:g}));return n.isSuffices=g,n}if(g){let t=R(e);return N(`$Suffices`,[t],J(n,d))}let r=o.previousRight,i=r!==void 0&&e.kind===`Apply`&&ot(e)&&e.args[0].kind===`ExceptAt`,a=i?R(e.args[1]):void 0,s=i?A(se(e.operator,T(e)),[N(`$Nop`,[r],T(e.args[0])),a],T(e)):R(e),c=s.kind===`OpAppl`?s.operands[1]:void 0;return o.previousRight=ot(e)?c:void 0,s})(f.statement),isPick:!1}:at(t,d);if(v===void 0)throw new e.ft(`Unexpected proof step ${f.kind}`);let x=v.isPick?s.contexts.pop():void 0,S=t.name===void 0||p===void 0?void 0:rt(p,t.name,v.node,qo(n,Vo(n,t.location)),b());S&&u(s,S);let C=h&&!g;C&&s.contexts.push(_);let ee=t.proof&&st(t.proof);return C&&s.contexts.pop(),w(v.node),h&&g&&(a.push(_),s.contexts.push(_)),x?.symbols.forEach(e=>u(s,e)),{...G(c()),kind:`Theorem`,definition:S,body:v.node,proof:ee,isSuffices:g,location:J(n,r)}});return a.forEach(()=>{s.contexts.pop()?.symbols.forEach(e=>yo(r,e))}),s.contexts.pop(),{...G(c()),kind:`NonLeafProof`,steps:d,instances:i,proofLevel:t.level,location:J(n,E(t.location))}},ct=e=>{let t=J(n,E(e.location)),r=e.statement,i=_o();e.name!==void 0&&y();let a=e.name===void 0?void 0:c();r.kind===`AssumeProve`&&s.contexts.push(i);let o=r.kind===`AssumeProve`?nt(r,1,e.name===void 0?void 0:{isSuffices:!1}):R(r),l=e.name===void 0||a===void 0?void 0:rt(a,e.name,o,t,b());l&&(r.kind===`AssumeProve`&&s.contexts.pop(),u(s,l),D.definitions.push(l),r.kind===`AssumeProve`&&s.contexts.push(i));let d=e.proof&&st(e.proof);r.kind===`AssumeProve`&&s.contexts.pop(),w(o);let f={...G(c()),kind:`Theorem`,definition:l,body:o,proof:d,isSuffices:!1,location:t};D.topLevel.push(f)},lt=e=>{let t=E(e.location),r=J(n,t);e.name!==void 0&&y();let i=R(e.expression),a=e.name===void 0?void 0:rt(c(),e.name,i,r,b(),!1);a&&(u(s,a),D.definitions.push(a));let o={...G(c()),kind:`Assume`,definition:a,body:i,location:r};D.topLevel.push(o)},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:Uo(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&&a(J(n,r),`Attempted to declare '@' as a variable.`);let i={...G(c()),levelChecked:1,level:+(t===3),kind:`OpDecl`,name:ns(e.name),arity:e.arity,declKind:t,location:J(n,r),module:D};return t===2&&(i.levelParams.add(i),i.allParams.add(i)),u(s,i),i};t.extends.forEach(e=>{let t=ne(e);D.extendees.push(t);let n=os(s);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?So(n,e.name):xo(n,e.name);t===void 0?yo(n,e):t!==e&&t.kind!==e.kind?a(e.location,`The ${ls(e)} of '${e.name}' conflicts with \nits ${ls(t)} at ${oo(t.location)}.`):t!==e&&!us(t,e)&&o(e.location,`Warning: the ${ls(t)} of '${e.name}' conflicts with \nits ${ls(t)} at ${oo(t.location)}.`)}),D.topLevel.push(...t.topLevel)});let pt=(e,t)=>{d.unresolvedSum!==0&&a(J(n,E(e)),`${t} may not appear within a recursive definition section.`)};return t.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`:Le(e.declarations);break;case`Definition`:e.definition.kind===`Function`?Fe(e.definition,void 0):Ne(e.definition,void 0);break;case`Instance`:e.instance.name===void 0?He(e.instance):Ve(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:[...s.contexts,_o()]},r=ee(e.module,n,D,t),i=te(r.name);i===void 0?yo(os(s),r):i!==r&&a(r.location,`Multiply-defined module '${r.name}': this definition or declaration conflicts \nwith the one at ${oo(i.location)}.`);break}}}),Re(),D},D=_.map(e=>{r.onAnalyze?.(e),l.id=Array.from({length:4},c)[1];let t=g(e,void 0),n=_o();d.toReversed().forEach(e=>yo(n,e));let a=ee(t.module,t.file,void 0,{contexts:[n]});return p.set(e,a),r.onModule?.(a,i),a});return{root:D[D.length-1],modules:D,messages:i}},Cs=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()},ws=(e,t,n,r)=>ao(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)},Ts=(e,t,n)=>`${e.id}:${t}:${n.id}`,Es=(e,t,n,r)=>{e.set(Ts(t,n,r),{op:t,index:n,param:r})},Ds=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},Os=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},ks=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&Os(e,r,t)})},As=(e,t)=>`${e.id}:${t}`,js=(e,t,n,r)=>{let i=As(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},Ms=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&js(e,t.param,t.position,t.level)})},Ns=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},Ps=(e,t)=>{Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),ks(e.levelConstraints,t.levelConstraints),Ms(e.argLevelConstraints,t.argLevelConstraints),Ds(e.argLevelParams,t.argLevelParams)},Fs=(e,t)=>t.includes(e.op)||t.includes(e.param),Is=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,Ls=e=>e.kind!==`Module`,Rs=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,zs=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,Bs=(e,t)=>e.kind===`OpDef`?e.weights[zs(e,t)]??0:0,Vs=(e,t)=>e.maxLevels[zs(e,t)]??3,Hs=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,Us=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[zs(e,t)]??!0:e.isLeibnizArg[t]??!0,Ws=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,Gs=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],Ks=(e,t)=>t.find(t=>t.op===e)?.expr,qs=(e,t,n)=>{let r=Ks(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},Js=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=Ks(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!Is(i.op))return;let a=i.op;qs(e.param,t,!1).forEach(t=>Es(n,a,e.index,t))}),n},Ys=(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;qs(r,t,!1).forEach(e=>Os(a,e,i))}),e.argLevelParams.forEach(e=>{let n=Ks(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;X(n.op,r,i);let o=Vs(n.op,e.index);qs(e.param,t,!1).forEach(e=>Os(a,e,o))}),a},Xs=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=Ks(e.param,t);n===void 0?js(i,e.param,e.position,e.level):n.kind===`OpArg`&&Is(n.op)&&js(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=Ks(e.param,t);if(a===void 0)return;let o=Ks(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&Is(s)&&(X(a,n,r),js(i,s,e.index,a.level))}),i},Zs=(e,t)=>wo(e,3).length>0||(oc(e,t),Co(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),Qs=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(As(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(Ts(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(As(t,n))}),Ds(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},$s=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>Vs(t,o)&&(n&&X(a,r,i)&&ws(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`||!Rs(a.op)))return;let s=a.op;X(s,r,i);let c=bo(s);for(let l=0;l<c;l++){let c=Hs(t,o,l);Vs(s,l)>=c||(n&&X(a,r,i)&&ws(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||!Ws(t,o,l,u)||n.level<=Vs(s,u)||(X(a,r,i)&&X(n,r,i)&&ws(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&&ws(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${oo(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},ec=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);ks(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&ks(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>ks(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=Vs(t,r);n?.levelParams.forEach(t=>Os(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!Rs(n.op))return;let o=n.op;X(o,r,i);let s=bo(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!Ws(t,a,r,i))continue;let s=Vs(o,i);n?.levelParams.forEach(t=>Os(e.levelConstraints,t,s)),!o.isLeibniz&&!Us(o,i)&&n&&Y(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&Rs(n.op)&&(X(n.op,r,i),Os(e.levelConstraints,t.param,Vs(n.op,t.index)))}),Ms(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&Ms(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>Ms(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!Is(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)js(e.argLevelConstraints,i,n,Hs(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&Ws(t,r,a,o)&&js(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(X(n,r,i),js(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&Ds(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>Ds(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=>Es(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&Is(a.op)&&Es(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!Is(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&Ws(t,r,a,o)&&n.levelParams.forEach(t=>Es(e.argLevelParams,i,o,t))})})},tc=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),nc=(e,t)=>{let n=(n,r)=>{ws(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=tc.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.`)})},rc=(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(Rs(i)){let r=X(i,t,n);$s(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&Bs(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&&(Bs(i,n)===1&&Y(e.levelParams,t.levelParams),Y(e.allParams,t.allParams),Y(e.nonLeibnizParams,t.nonLeibnizParams),Us(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(Gs(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),ec(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),ks(e.levelConstraints,t.levelConstraints),js(e.argLevelConstraints,i,n,t.level),Ms(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>Es(e.argLevelParams,i,n,t)),Ds(e.argLevelParams,t.argLevelParams)});return nc(e,n),e.levelCorrect},ic=(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))}),Qs(e,i,r),e.levelCorrect},ac=(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)}),Qs(e,e.params,e.body)),e.levelCorrect),oc=(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),ic(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||ws(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),ic(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(oc(e,t)));let a=Co(e);return a.forEach(e=>i(ic(e,1,t))),To(e).forEach(e=>i(ac(e,1,t))),e.topLevel.forEach(e=>i(X(e,1,t))),Zs(e,t)||wo(e,2).forEach(t=>Os(e.levelConstraints,t,0)),a.forEach(t=>{ks(e.levelConstraints,t.levelConstraints),Ms(e.argLevelConstraints,t.argLevelConstraints),Ds(e.argLevelParams,t.argLevelParams,e=>!Fs(e,t.params??[]))}),e.topLevel.forEach(t=>{ks(e.levelConstraints,t.levelConstraints),Ms(e.argLevelConstraints,t.argLevelConstraints),Ds(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},sc=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{Ls(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=X(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),Ps(e,t),Y(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),cc=(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&&ws(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&ws(t,e.body.location,`Non-constant CASE for temporal goal.`),cc(e.proof,t)):n===`$Qed`&&cc(e.proof,t)})},lc=(e,t,n,r,i,a)=>{e.levelConstraints=Ys(t,n,r,i,a),e.argLevelConstraints=Xs(t,n,i,a),e.argLevelParams=Js(t.argLevelParams,n)},uc=(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;oc(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{X(r.expr,t,n)||(e.levelCorrect=!1)});let i=Zs(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(X(a.expr,t,n)&&ws(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||ws(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)&&ws(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(As(i.op,t))?.level;a===void 0||Vs(o,t)>=a||(s&&ws(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=Vs(s,i.index);o.expr.level<=l||(c&&X(o.expr,t,n)&&ws(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 ks(e.levelConstraints,Ys(r,e.substs,i,t,n),a),e.substs.forEach(t=>ks(e.levelConstraints,t.expr.levelConstraints,a)),Ms(e.argLevelConstraints,Xs(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>Ms(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),Ds(e.argLevelParams,Js(r.argLevelParams,e.substs),t=>!Fs(t,e.params)),e.substs.forEach(t=>Ds(e.argLevelParams,t.expr.argLevelParams,t=>!Fs(t,e.params))),e.levelCorrect},X=(e,t,n)=>{if(!Ls(e))return oc(e,n);switch(e.kind){case`OpAppl`:return rc(e,t,n);case`OpDef`:return ic(e,t,n);case`ThmOrAssumpDef`:return ac(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,Ns(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),ks(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>ks(e.levelConstraints,t.levelConstraints)),Ms(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>Ms(e.argLevelConstraints,t.argLevelConstraints)),Ds(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];Ds(e.argLevelParams,t.argLevelParams,e=>!Fs(e,n))}),e.instances.forEach(t=>Ds(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,Ns(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=>Ps(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,qs(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>Y(e.allParams,qs(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=Zs(e.instantiatedModule,n);return lc(e,r,e.substs,i,t,n),e.levelCorrect}case`Instance`:return uc(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,Ns(e,e.body),e.level!==0&&ws(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=sc(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&&ws(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&cc(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return sc(e,e.facts,t,n);case`NonLeafProof`:return sc(e,[...e.steps,...e.instances],t,n);case`DefStep`:return sc(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,ws(n,e.location,`Level error:
44
+ Temporal formula used as set.`)),Ns(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=>Ps(e,t)),e.levelCorrect&&e.levelParams.forEach(t=>{t.kind===`OpDecl`&&t.declKind===2&&Os(e.levelConstraints,t,2)})),e.levelCorrect}},dc=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[]}},fc=/* @__PURE__ */ new Map([[`Integers`,`Int`],[`Naturals`,`Nat`],[`Reals`,`Reals`]]),pc=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&&fc.get(e)===t.name||n(t))return!0}}return dc(e).some(n)};return n(e)},mc=e=>e.operands.filter(e=>e?.kind===`OpAppl`),hc=e=>{let t=e.operands[0];return t?.kind===`String`?t:void 0},gc=(e,t)=>{if(e===t)return!0;if(e.operands.length!==t.operands.length)return!1;let n=new Set(mc(t).map(e=>hc(e)?.value));return mc(e).every(e=>n.has(hc(e)?.value))},_c=(e,t=/* @__PURE__ */ new Set)=>(e.extendees.forEach(e=>{t.has(e)||(t.add(e),_c(e,t))}),t),vc=e=>{let t=[...[..._c(e)].flatMap(e=>e.records),...e.records];return e.records.flatMap(n=>t.filter(e=>gc(e,n)).flatMap(mc).some(pc)?[]:mc(n).flatMap(t=>{let n=hc(t),r=n&&xo(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 ${oo(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}]}))},yc=e=>`${oo(e.location)}\n\n${e.text}`,bc=e=>{let t=e.filter(e=>!e.isWarning),n=e.filter(e=>e.isWarning);return[t.length>0?`*** Errors: ${t.length}\n\n`:``,...t.map(e=>`${yc(e)}\n\n\n`),n.length>0?`*** Warnings: ${n.length}\n\n`:``,...n.map(e=>`${yc(e)}\n\n\n`)].join(``)},xc=/* @__PURE__ */ new Set([`FiniteSets`,`Sequences`,`Bags`,`Naturals`,`Integers`,`Reals`,`RealTime`,`Randomization`,`TLC`]),Sc=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))},Cc=t=>{try{return e.O(Zo(t))}catch(t){if(t instanceof e.ft)return;throw t}},wc=(t,n)=>n===`1.7.4`&&e.Q(t)!==void 0?void 0:Cc(t)?.name,Tc=(t,i=()=>void 0,a={})=>{let o=(0,n.basename)(t,`.tla`),s=e.T(a.version),c=a.fileName??o,l=(0,r.existsSync)(t)?(0,r.readFileSync)(t,`utf8`):s.get(o),u=[],d=e=>{u.push(e),a.onPrint?.(e)},f=e=>d(`${e}\n`),p=a.version===`1.7.4`,m=p&&a.isXmlExport,h=e=>{a.isXmlExport||f(e)},g=a.describeFile,_=/* @__PURE__ */ new Map([[o,(0,r.existsSync)(t)?`file`:`standard`]]),v={value:!1},y=[],b={isReported:!1,isAborted:!1},x=ea(fi(),f),S=/* @__PURE__ */ new Map,C=[],w=()=>C.splice(0).forEach(e=>e.isError?a.onPrintError?.(`${e.text}\n`):f(e.text)),T=e=>{let t=S.get(e),n=t?.module.location.range;if(t===void 0||n===void 0)return;let r=t.text.split(/\r\n|\r|\n/),i=to(x,r.slice(n.start.line-1,n.end.line),a.version),o=i.has(`TLA_DIVERGENCE_EXISTS`),s=i.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(p){let t=o&&s?`The PlusCal algorithm and its TLA+ translation in module ${e} filename since the last translation.`:c;t===void 0?i.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??(i.has(`ERROR_ENCOUNTERED`)?`An unexpected problem was encountered attempting to validate the specification for ${e}`:void 0);if(l===void 0)return;let u=!i.has(`ERROR_ENCOUNTERED`)||o||s;y.some(e=>e.text===l)||y.push({location:e,text:l,isWarning:u})},E=(e,t)=>{if(a.isXmlExport||S.has(e))return;let n=Cc(t);if(n===void 0||n.name!==e)return;let r=[...S.values()].filter(t=>Sc(t.module).includes(e));S.set(e,{text:t,module:n}),r.forEach(()=>T(e)),Sc(n).filter(t=>t!==e&&S.has(t)).forEach(T)},ee=()=>{if(w(),b.isReported)return;b.isReported=!0;let e=y.filter(e=>e.isWarning);e.length>0&&(h(`Warnings (${e.length}) during syntax parsing of ${c}:\n\n`),e.forEach(e=>h(`${yc(e)}\n\n\n`))),e.length!==y.length&&(f(bc(y)),v.value=!0,b.isAborted=!0)},D=t=>{let n=s.get(t),r=i(t),a=r===void 0&&n===void 0&&l!==void 0&&!p?e.E(l,t):void 0,o=r??a;return _.set(t,r===void 0?a===void 0?`standard`:`root file`:`file`),o!==void 0&&E(t,o),o??n},te=(()=>{try{if(l===void 0)throw new e.dt(`Cannot find source file for module ${c}`,void 0);return E(o,l),Ss(l,D,{rootFileName:o,rootFilePath:a.isXmlExport?`${c.replace(/\.tla$/,``)}.tla`:void 0,version:a.version,rootExtendees:a.rootExtendees,onParse:e=>{g&&f(`Parsing file ${g(e,_.get(e)??`file`)}`),e===o&&T(o),w()},onAnalyze:e=>{ee(),(g||m)&&!b.isAborted&&f(`Semantic processing of module ${e}`)},onModule:(e,t)=>{if(b.isAborted||(t.every(e=>e.isWarning)&&oc(e,{messages:t,isTlc174:p}),t.length===0))return;if(t.some(e=>!e.isWarning)&&(v.value=!0),p)return f(`Semantic errors:\n\n${bc(t)}`);let n=t.filter(e=>e.isWarning);n.length>0&&(h(`*** Warnings: ${n.length}\n`),n.forEach(e=>h(`${yc(e)}\n\n\n`)));let r=t.filter(e=>!e.isWarning);r.length!==0&&(f(`Semantic errors:\n\n*** Errors: ${r.length}\n`),r.forEach(e=>f(`${yc(e)}\n\n`)))}})}catch(t){if(v.value=!0,t instanceof e.it){f(`\nFatal errors while parsing TLA+ spec in file ${c}\n`),f(t.message),f(bc(y));return}if(!(t instanceof e.dt))throw t;let n={location:t.location,text:t.message,isWarning:!1},r=p&&t.parseError?.includes(` and token "" `);if(t.parseError!==void 0&&!r&&!m&&f(t.parseError),f(`\nFatal errors while parsing TLA+ spec in file ${c}\n`),r){f(`java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null`);return}if(p){f(`tla2sany.semantic.AbortException`),d(`*** Abort messages: 1\n\n${yc(n)}\n\n\n`);return}f(yc(n)),f(bc(b.isReported?[n]:[...y,n]))}})();if(te!==void 0&&ee(),te!==void 0&&!v.value&&!a.isXmlExport&&!p){let e=te.modules.filter(e=>!xc.has(e.name));g&&e.forEach(e=>f(`Linting of module ${e.name}`)),e.flatMap(vc).forEach(e=>f(`${yc(e)}\n\n\n`))}return{text:u.join(``),isFailed:v.value,specification:b.isAborted?void 0:te}},Ec={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},Dc=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:[]}),Oc={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,"\r":`&#13;`},kc=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:Oc[e]),Ac=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,jc=e=>{let t=(e.cdata??e.text)?.match(Ac)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=jc(t);if(e)return e}},Mc=(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}>${kc(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)Mc(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},Nc=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)]),Pc=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)`}},Fc={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)`}}},Ic={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},Lc=oo(`--TLA+ BUILTINS--`),Rc=(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}]},zc=(e,t=16)=>e>t*.75?zc(e,t*2):t,Bc=(e,t)=>(e^e>>>16)&t-1,Vc=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},Hc=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),Uc=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,Wc=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=Vc(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(Uc,``)}).join(`
45
+ `)},Gc=e=>{let t=Vc(e),n=e=>Hc(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(`
46
+ `)},Kc=(t,n,r)=>{let i=r.version===`1.7.4`,a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Map,s={isSet:!1},c=[],l=(e,t)=>{if(!i)return t();c.push(...e);let n=t();return c.length-=e.length,n},u=(t,n)=>{let r=[...c,...n].reverse(),i=[t,...r.map(e=>`\tat tla2sany.${e.at}`)].join(`
47
+ `),a=r.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${i}\n`).join(``);return e.yt(new e.ct(i,a),Ec.uncaughtException)},d=e=>u(`java.lang.NullPointerException: Cannot invoke "tla2sany.semantic.${e.nullType}.export(org.w3c.dom.Document, tla2sany.xml.SymbolContext)" because ${e.nullValue} is null`,[e]),f=(e,t)=>(a.has(e.id)||(a.add(e.id),o.set(e.id,l([...t?[t]:[],...Rc(e.kind,oo(e.location))],()=>g(e)))),Z(Pc(e),[Q(`UID`,e.id)])),p=(e,t,n)=>{let r=t.levelChecked===0?[]:[Q(`level`,t.level)],i=n?[Nc(n),...r]:r;return{...e,children:[...i,...e.children]}},m=(e,t,n)=>Z(`params`,e.map((e,r)=>Z(`leibnizparam`,[f(e,n),...t?.[r]?[Z(`leibniz`)]:[]]))),h=e=>{let t=e.map(e=>e.trimEnd()).filter(e=>e.length>0).join(`
48
+ `),n=r.isUncommented?Gc(Wc(t)):t;return e.length>0?[{tag:`pre-comments`,cdata:n,children:[]}]:[]},g=t=>{switch(t.kind){case`FormalParam`:return p(Z(`FormalParamNode`,[Q(`uniquename`,t.name),Q(`arity`,t.arity)]),t,t.location);case`OpDecl`:return p(Z(`OpDeclNode`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Q(`kind`,t.declKind)]),t,t.location);case`OpDef`:{if(t.defKind===`NumberedProofStep`)throw i?u(Dc(37),[Ic]):e.yt(new e.pt(Dc(37)),Ec.uncaughtException);if(t.defKind===`ModuleInstance`)return p(Z(`ModuleInstanceKind`,[Q(`uniquename`,t.name),...t.isLocal&&!i?[Z(`local`)]:[]]),t,t.location);let n=t.params??[];if(t.defKind===`BuiltIn`)return p(Z(`BuiltInKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),...t.params?[m(n,t.isLeibnizArg,$.builtInParam)]:[]]),t,t.location);let r=t.body,a=t.module;if(r===void 0&&i)throw d($.body);if(r===void 0||a===void 0)throw Error(`The definition of ${t.name} has no body`);return p(i?Z(`UserDefinedOpKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Z(`body`,[x(r,$.body)]),...t.params?[m(n,t.isLeibnizArg,$.param)]:[],...t.inRecursive?[Z(`recursive`)]:[]]):Z(`UserDefinedOpKind`,[Q(`uniquename`,t.name),Q(`arity`,t.arity),Z(`originalOperator`,[f(t.source??t)]),Z(`originallyDefinedInModule`,[f(a)]),Z(`body`,[x(r,$.body)]),m(n,t.isLeibnizArg,$.param),...h(t.preComments),...t.inRecursive?[Z(`recursive`)]:[],...t.recursiveSection>=0?[Q(`recursiveSection`,t.recursiveSection)]:[],...t.isLocal?[Z(`local`)]:[]]),t,t.location)}case`ThmOrAssumpDef`:return p(Z(t.isTheorem?`TheoremDefNode`:`AssumeDef`,[Q(`uniquename`,t.name),x(t.body,$.theoremDefinitionBody)]),t,t.location);case`Module`:return Z(`ModuleNode`,[Nc(t.location),..._(t)]);case`Theorem`:return p(Z(`TheoremNode`,[...t.definition?[Z(`definition`,[f(t.definition,$.theoremDefinition)])]:[],Z(`body`,[x(t.body,$.theorem)]),...t.proof?[x(t.proof,$.proof)]:[],...t.isSuffices?[Z(`suffices`)]:[]]),t,t.location);case`Assume`:return Z(`AssumeNode`,[Nc(t.location),...t.body.levelChecked===0?[]:[Q(`level`,t.body.level)],...t.definition?[Z(`definition`,[f(t.definition,$.assumeDefinition)])]:[],Z(`body`,[x(t.body,$.assume)])])}},_=e=>{let t=t=>!r.isRestricted||t.module===e;return[Q(`uniquename`,e.name),...i?[]:[Z(`extends`,[...new Set(e.extendees.map(e=>e.name))].toSorted().map(e=>Q(`uniquename`,e)))],...wo(e,2).filter(t).map(e=>f(e,$.constant)),...wo(e,3).filter(t).map(e=>f(e,$.variable)),...Co(e).filter(t).map(e=>f(e,$.definition)),...e.topLevel.map(e=>e.kind===`Instance`||e.kind===`UseOrHide`?x(e,$.topLevel):f(e,$.topLevel)),...e.definitions.filter(e=>!i&&e.kind===`Module`).map(e=>f(e))]},v=(e,t)=>l([t],()=>Z(`Subst`,[f(e.op,$.substOperator),x(e.expr,$.substExpression)])),y=e=>{if(e.isNull&&i)throw u(Dc(0),[$.operator,...Rc(`OpDef`,Lc),Ic]);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=f(e.operator,$.operator),r=e.operands.map((e,t)=>e===void 0||t===0&&s.isSet&&so(e)?i?Q(`StringNode`,`$Other`):Z(`StringNode`,[Q(`StringValue`,`$Other`)]):x(e,$.operand)),a=e.tupleOrs,o=e.unbounded===void 0&&e.bounded===void 0?[]:[Z(`boundSymbols`,[...(e.unbounded??[]).map((e,t)=>Z(`unbound`,[f(e,$.unbound),...a?.[t]?[Z(`tuple`)]:[]])),...(e.bounded??[]).map((t,n)=>Z(`bound`,[...t.map(e=>f(e,$.bound)),...a?.[n]?[Z(`tuple`)]:[],x(e.ranges[n],$.range)]))])];return Z(`OpApplNode`,[Z(`operator`,[n]),Z(`operands`,r),...o])},b=(e,t)=>e.kind===`Module`||e.kind===`OpDef`?f(e,t):x(e,t),x=(e,t)=>{if(!i)return S(e);if(e.kind===`OpAppl`&&e.isAbsent&&`nullType`in t)throw d(t);let n=[t,{at:`semantic.SemanticNode.export(SemanticNode.java:379)`,failedFor:oo(e.location)},{at:`semantic.LevelNode.getSemanticElement(LevelNode.java:333)`}];return l(n,()=>S(e))},S=e=>{switch(e.kind){case`OpAppl`:return p(y(e),e,e.location);case`Numeral`:return p(Z(`NumeralNode`,[Q(`IntValue`,e.value)]),e,e.location);case`String`:return p(Z(`StringNode`,[Q(`StringValue`,e.value)]),e,e.location);case`Decimal`:return p(Z(`DecimalNode`,[Q(`mantissa`,e.mantissa),Q(`exponent`,e.exponent),...i?[]:[Q(`integralPart`,e.integralPart),Q(`fractionalPart`,e.fractionalPart)]]),e,e.location);case`LetIn`:{let t=x(e.body,$.letBody);return p(Z(`LetInNode`,[Z(`body`,[t]),Z(`opDefs`,e.opDefs.map(e=>f(e,$.letDefinition)))]),e,e.location)}case`Label`:return p(Z(`LabelNode`,[Q(`uniquename`,e.name),Q(`arity`,e.params.length),Z(`body`,[x(e.body,$.labelBody)]),Z(`params`,e.params.map(e=>f(e,$.labelParam)))]),e,e.location);case`OpArg`:return p(Z(`OpArgNode`,[Z(`argument`,[f(e.op,$.argument)])]),e,e.location);case`At`:{let t=e.except.operands[0],n=e.component.operands[0];if(t===void 0||n===void 0)throw Error(`An @ refers to an incomplete EXCEPT`);return p(Z(`AtNode`,[x(t,$.exceptObject),x(n,$.exceptComponents)]),e,e.location)}case`SubstIn`:case`APSubstIn`:{let t=Fc[e.kind],n=e.substs.map(e=>v(e,t.subst)),r=x(e.body,t.body);return p(Z(e.kind===`SubstIn`?`SubstInNode`:`APSubstInNode`,[Z(`substs`,n),Z(`body`,[r]),Z(`instFrom`,[f(e.instantiatingModule,t.from)]),Z(`instTo`,[f(e.instantiatedModule,t.to)])]),e,e.location)}case`Instance`:{let t=e.substs.map(e=>v(e,$.instanceSubst)),n=e.params.map(e=>f(e,$.instanceParam));return Z(`InstanceNode`,[Nc(e.location),Q(`level`,0),...e.name===void 0?[]:[Q(`uniquename`,e.name)],Q(`module`,e.module.name),Z(`substs`,t),Z(`params`,n),...e.isLocal&&!i?[Z(`local`)]:[]])}case`UseOrHide`:return p(Z(`UseOrHideNode`,[Z(`facts`,e.facts.map(e=>b(e,$.useFact))),Z(`defs`,e.defs.map(e=>f(e,$.useDefinition))),...e.isOnly?[Z(`only`)]:[],...e.isHide?[Z(`hide`)]:[]]),e,e.location);case`NewSymb`:return p(Z(`NewSymbNode`,[f(e.declaration,$.newDeclaration),...e.set&&!(i&&so(e.set))?[x(e.set,$.newSet)]:[]]),e,e.location);case`AssumeProve`:return p(Z(`AssumeProveNode`,[Z(`assumes`,e.assumptions.map(e=>x(e,$.assumption))),Z(`prove`,[x(e.goal,$.goal)]),...e.isSuffices?[Z(`suffices`)]:[],...e.isBoxed?[Z(`boxed`)]:[]]),e,e.location);case`LeafProof`:{let t=e.facts.length===0&&e.defs.length===0,n=e.isOmitted?Z(`omitted`):t?Z(`obvious`):Z(`by`,[Z(`facts`,e.facts.map(e=>b(e,$.byFact))),Z(`defs`,e.defs.map(e=>f(e,$.byDefinition))),...e.isOnly?[Z(`only`)]:[]]);return p(n,e,e.location)}case`NonLeafProof`:return p(Z(`steps`,[...i?[]:[Q(`proofLevel`,e.proofLevel)],...e.steps.map(e=>e.kind===`Theorem`?f(e,$.step):x(e,$.step))]),e,e.location);case`DefStep`:return p(Z(`DefStepNode`,e.defs.map(e=>f(e,$.defStep))),e,e.location)}},C=(r.isRestricted?[n]:t).map(e=>f(e,$.main)),w=zc(o.size),T=Z(`context`,[...o.entries()].toSorted(([e],[t])=>Bc(e,w)-Bc(t,w)).map(([e,t])=>Z(`entry`,[Q(`UID`,e),t])));return Z(`modules`,[Q(`RootModule`,n.name),T,...C])},qc=(t,n={version:`master`,isRestricted:!1,isUncommented:!1,isTerse:!1})=>{let r=Kc(t.modules,t.root,n),i=jc(r);if(i){let t=i.character.codePointAt(0)??0;throw e.yt(new e.pt(`The spec contains the character U+${t.toString(16).toUpperCase().padStart(4,`0`)} in the ${i.tag} element. XML 1.0 cannot represent that character in character data, not even as a numeric character reference, so the spec cannot be exported until the character is removed from it.`),Ec.unrepresentableCharacter)}let a=[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>`];return Mc(r,0,n.isTerse?0:2,a),n.isTerse?a.join(``):`${a.join(`
49
+ `)}\n`},Jc=`META-INF/MANIFEST.MF`,Yc=e=>{if(e===void 0||!(0,r.existsSync)(e))return`master`;let t=(0,l.unzipSync)((0,r.readFileSync)(e),{filter:e=>e.name===Jc})[Jc];return(t&&/^X-Git-Tag: *(\S*)/m.exec((0,l.strFromU8)(t))?.[1])===`v1.7.4`?`1.7.4`:`master`},Xc={success:e.vt.success,"assumption-violation":e.vt.assumptionViolation,deadlock:e.vt.deadlock,"invariant-violation":e.vt.safetyViolation,"property-violation":e.vt.safetyViolation,"liveness-violation":e.vt.livenessViolation,"postcondition-violation":e.vt.assumptionViolation,error:e.vt.error},Zc=f(`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>`}]),Qc=f(`tla-ts prove {options} <Module.tla|glob>...`,[{flag:`-N`,isRequired:!0},{flag:`--toolbox <start> <end>`},{flag:`--line <num>`},{flag:`--printallobs`},{flag:`--summary`},{flag:`--strict`},{flag:`-I <directory>`,isRepeatable:!0}]),$c=/* @__PURE__ */ new Set([`-o`,`-t`,`-r`,`-u`]),el=/* @__PURE__ */ new Set([`-o`]),tl=(()=>{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(`
50
+ `)})(),nl=[`Usage: ${Zc.usage}`,` ${Qc.usage}`,` tla-ts prove [<tlapm option>]... <Module.tla|glob>...`,` 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(`
51
+ `),rl=/[*?[{]/,il=e=>e.flatMap(e=>rl.test(e)?(0,r.globSync)(e).sort().map(e=>({path:e,isGlobbed:!0})):[{path:e,isGlobbed:!1}]),al=e=>/^[+-]?\d+$/.test(e)&&BigInt.asIntN(64,BigInt(e))===BigInt(e),ol=e=>e?e[0]===`auto`?(0,o.availableParallelism)():Math.max(1,Number.parseInt(e[0],10)||1):1,sl=[`constrained`,`stuttering`,`strict`],cl=(e,t)=>e.endsWith(t)?e:`${e}${t}`,ll=e=>{if(e.length===1)return{path:cl(e[0],`.dump`)};let t=e[0].toLowerCase();return{path:cl(e[1],`.dot`),dot:!0,colorize:t.includes(`colorize`),actionLabels:t.includes(`actionlabels`),snapshot:t.includes(`snapshot`)}},ul=(t,n)=>t.print(e.I.computingInitProgress,e.L.none,`Computed ${n} initial states...`),dl=(t,n)=>t===`invariant-violation`?{code:e.I.invariantViolatedInitial,text:`Invariant ${n} is violated by the initial state:`}:{code:e.I.propertyViolatedInitial,text:`Property ${n} is violated by the initial state:`},fl=(t,n)=>n?.forEach(n=>{if(typeof n==`string`)return console.log(n);if(n.kind===`initial-states-progress`)return ul(t,n.count);let r=dl(n.status,n.name);t.print(r.code,e.L.error,`${r.text}\n${e.K(n.state)}`)}),pl=(t,n,r={code:e.I.behaviorUpToThisPoint,text:`The behavior up to this point is:`},i=!1)=>{n.length>0&&t.print(r.code,e.L.error,r.text),n.forEach((n,r)=>{(r>0||i)&&fl(t,n.output),t.print(e.I.statePrint2,e.L.state,`${r+1}: <${n.label??n.action??`Initial predicate`}>\n${e.K(n.state)}`)})},ml={code:e.I.counterExample,text:`The following behavior constitutes a counter-example:
52
+ `},hl=(e,t)=>t===`1.7.4`||e.length===0?`Temporal properties were violated.
53
+ `: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`,gl=t=>t.filter((e,n)=>e!==t[n-1]).map((t,n)=>`${n}) ${e.M(t)}\n`).toReversed().join(``),_l=e=>{if(e.length===0)return` The error call stack is empty.
54
+ `;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`},vl=(t,n)=>{let r=n.generated,i=n.distinct,a=e.V(/* @__PURE__ */ new Date);r===i?t.print(e.I.initGenerated1,e.L.none,`Finished computing initial states: ${i} distinct state${i===1?``:`s`} generated at ${a}.`):t.print(e.I.initGenerated2,e.L.none,`Finished computing initial states: ${r} state${r===1?``:`s`} generated, with ${i} of them distinct at ${a}.`)},yl=(t,n,r)=>{let i=Math.max(Date.now()-(r??0),1)/6e4,a=e=>e.toLocaleString(`en-US`),o=(e,t)=>r===void 0?``:` (${a(Math.floor(e/i))} ${t}/min)`;t.print(e.I.progress,e.L.none,`Progress(${Math.max(n.depth,1)}) at ${e.V(/* @__PURE__ */ new Date)}: ${a(n.generatedStates)} states generated${o(n.generatedStates,`s`)}, ${a(n.distinctStates)} distinct states found${o(n.distinctStates,`ds`)}, ${a(n.queuedStates)} states left on queue.`)},bl=(e,t)=>(0,n.join)(e,`${t}.class`),xl=(t,r,i,a)=>{let o=t.print;switch(r.kind){case`parsed`:i.isParsed=!0,t.isTool&&o(e.I.sanyFinished,e.L.none,`SANY finished.`),o(e.I.starting,e.L.none,`Starting... (${e.V(/* @__PURE__ */ new Date)})`);return;case`constant-level-invariant`:if(t.version===`1.7.4`)return;o(e.I.constantLevelInvariant,e.L.warning,`The invariant ${r.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(t.version===`1.7.4`)return;o(e.I.stateLevelProperty,e.L.warning,`The formula ${r.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 ${r.name} holds in all states of every behavior, use INVARIANT ${r.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${r.name} changes it into a temporal formula, asserting that ${r.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`);return;case`liveness-initializing`:r.isSymmetric&&o(e.I.livenessSymmetry,e.L.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.`),r.isConstrained&&t.version===`1.7.4`&&o(e.I.livenessConstraints,e.L.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`:o(e.I.temporalBranches,e.L.none,`Implied-temporal checking--satisfiability problem has ${r.branches} branches.`);return;case`java-override`:{let t=(0,s.pathToFileURL)((0,n.resolve)(bl(a,r.module))).href;o(r.isMatched?e.I.javaOverrideLoaded:e.I.javaOverrideMismatch,r.isMatched?e.L.none:e.L.warning,`${r.isMatched?`Loading`:`Failed to match`} ${r.operator} operator override from ${t.replace(`file:///`,`file:/`)} with signature: <Java Method: ${r.signature}>.`);return}case`initial-states-started`:o(e.I.computingInit,e.L.none,`Computing initial states...`);return;case`initial-states-progress`:ul(t,r.count);return;case`initial-states-computed`:vl(t,r.initialStates);return;case`progress`:yl(t,r.statistics,i.start);return;case`liveness-started`:{i.liveness=Date.now(),r.isComplete&&yl(t,r.statistics);let n=r.branches>1?`${r.branches} branches of `:``,a=r.branches*r.states;o(e.I.checkingTemporal,e.L.none,`Checking ${n}temporal properties for the ${r.isComplete?`complete`:`current`} state space with ${a} total distinct states at (${e.V(/* @__PURE__ */ new Date)})`);return}case`liveness-finished`:Sl(t,i);return;case`warning`:o(r.code,e.L.warning,r.text)}},Sl=(t,n)=>{n.liveness!==void 0&&(t.print(e.I.checkingTemporalEnd,e.L.none,`Finished checking temporal properties in ${e.H(Date.now()-n.liveness)} at ${e.V(/* @__PURE__ */ new Date)}`),n.liveness=void 0)},Cl=(t,n,r)=>{let i=r.print,a=n.name,o=n.loopStart,s=o===void 0&&n.trace.length===1&&(t===`invariant-violation`||t===`liveness-violation`),c={code:e.I.temporalPropertyViolated,text:hl(n.properties??[a],r.version)},l={success:void 0,error:void 0,"assumption-violation":n.message?{code:e.I.assumptionEvaluationError,text:e.z(e.I.assumptionEvaluationError,`Evaluating assumption ${a} failed.\n${n.message}`,r.isTool)}:{code:e.I.assumptionFalse,text:`Assumption ${a} is false.`},deadlock:{code:e.I.deadlockReached,text:`Deadlock reached.`},"invariant-violation":s?dl(`invariant-violation`,a):{code:e.I.invariantViolatedBehavior,text:`Invariant ${a} is violated.`},"property-violation":c,"liveness-violation":o===void 0?s?dl(`liveness-violation`,a):{code:e.I.actionPropertyViolatedBehavior,text:`Action property ${a} is violated.`}:c,"postcondition-violation":{code:n.postcondition?.code??e.I.general,text:n.message??`Postcondition ${a} is false.`}}[t],u=t===`property-violation`,d=o!==void 0&&!u,f=u||d,p=f&&r.version!==`1.7.4`;if(p&&fl(r,n.trace[0]?.output),n.counts&&console.log(n.counts),l){let t=s?`${l.text}\n${e.K(n.trace[0].state)}`:l.text;i(l.code,e.L.error,t)}if(s||(f||fl(r,n.trace[0]?.output),pl(r,n.trace,f?ml:void 0,f&&!p),fl(r,n.traceOutput)),d){let t=n.loopLabel;o===n.trace.length-1?i(e.I.statePrint3,e.L.state,`${o+2}: Stuttering`):r.isTool?i(e.I.backToState,e.L.state,`${o+1}: Back to state${t?`: <${t}>\n`:``}`):console.log(`Back to state ${o+1}${t?`: <${t}>\n`:``}`)}n.warning&&r.version!==`1.7.4`&&i(n.warning.code,e.L.warning,n.warning.text);let m=n.unwitnessed??(t===`postcondition-violation`?void 0:n.postcondition);return m?.counts&&console.log(m.counts),m&&i(m.code,e.L.error,m.message),!s&&t!==`assumption-violation`},wl=(t,n)=>t.print(e.I.nestedExpression,e.L.error,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${_l(n)}`),Tl=(t,n,r)=>{let i=n.print;if(t.failure){let r=t.failure,a=n.isTool?r.toolMessage:r.message,o=()=>{let t=r.fingerprint;if(t){let a=r.callStack?.length&&n.version!==`1.7.4`?_l(r.callStack):gl(t.sources);i(e.I.fingerprintFailed,e.L.error,`TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${a}\nReason:\n${e.B(t.reason,n.isTool)}`)}else r.callStack&&wl(n,r.callStack)};r.isCallStackFirst&&o();let s=r.initialState&&(()=>{try{return`While working on the initial state:\n${e.K(r.initialState)}`}catch(t){throw t instanceof e.st?e.yt(new e.st(`${e.ht}${t.message}`),e.vt.error):t}})();i(s?e.I.initialState:r.code,e.L.error,s?`${a}\n${s}`:a),fl(n,r.trace[0]?.output),pl(n,r.trace);let c=r.traceFailure;c&&i(c.code,e.L.error,n.isTool?c.toolMessage:c.message),fl(n,r.traceOutput);let l=r.postcondition;l?.counts&&console.log(l.counts),l&&i(l.code,e.L.error,l.message),r.isCallStackFirst||o()}else if(t.violation){if(!Cl(t.status,t.violation,n))return;let e=t.additionalViolation;e&&Cl(`property-violation`,e,n),t.liveCallStack&&wl(n,t.liveCallStack)}else{Sl(n,r);let a=e._(t.distinctStates,t.generatedStates),o=t.fingerprintDistance===void 0?[]:[` based on the actual fingerprints: val = ${e.m(e.h(t.fingerprintDistance))}`];i(e.I.success,e.L.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 = ${e.m(a)}`,...o].join(`
55
+ `))}if(t.failure?.isWithoutStatistics)return;t.status!==`success`&&Sl(n,r),n.isTool&&yl(n,t,r.start),i(e.I.stats,e.L.none,`${t.generatedStates} states generated, ${t.distinctStates} distinct states found, ${t.queuedStates} states left on queue.`);let a=n.version===`1.7.4`,o=a?t.outDegrees??t.violationOutDegrees:t.outDegrees;(!a||o)&&i(e.I.searchDepth,e.L.none,`The depth of the complete state graph search is ${a?Math.max(t.depth,1):t.depth}.`);let s=o&&e.v(o);s&&i(e.I.stateGraphOutdegree,e.L.none,s)},El=(e,t)=>e.map(e=>(0,n.join)(e,`${t}.tla`)).find(r.existsSync),Dl=e=>t=>{let n=El(e,t);return n===void 0?void 0:(0,r.readFileSync)(n,`utf8`)},Ol=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),kl=e=>`jar:file:${(0,s.pathToFileURL)((0,n.resolve)(e)).pathname}!/tla2sany/StandardModules/`,Al=e=>(0,a.createHash)(`sha256`).update(e).digest().readBigUInt64BE().toString(),jl=(e,t,i,a,s)=>{let c=i.temporaryDirectory??(0,o.tmpdir)(),l=(0,r.existsSync)(c)?(0,r.realpathSync)(c):(0,n.resolve)(c),u=(0,n.join)(l,`tlc-${Al((0,n.resolve)(e))}`),d=du(i);return(i,o)=>{let c=`${i}.tla`;if(o===`file`)return(0,r.realpathSync)(El(t,i)??e);if(s===`1.7.4`)return(0,n.join)(l,c);if(o===`root file`){let t=a===void 0?l:(0,n.resolve)(a),o=(0,r.realpathSync)(e);return`${(0,n.join)(t,Al(`${o} ${i}`),c)} (${o})`}let f=(0,n.join)(u,c);return d===void 0?f:`${f} (${kl(d)}${c})`}},Ml=t=>t.print(e.I.version,e.L.none,`TLC2 Version ${u} (rev: tla-ts)`),Nl=(t,n)=>(Ml(t),t.print(e.I.commandLineError,e.L.error,`${n}\nUsage: java tlc2.TLC [-help] [-option] inputfile`),1),Pl=(t,n,r)=>t.print(e.I.modelChecking,e.L.none,`Running breadth-first search Model-Checking with fp 0 and seed ${BigInt(n)} with ${r} worker${r===1?``:`s`} on ${(0,o.availableParallelism)()} cores with ${Math.floor((0,c.getHeapStatistics)().heap_size_limit/1024/1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${(0,o.type)()} ${(0,o.release)()} ${(0,o.arch)()}, Node.js ${process.versions.node} ${process.arch.endsWith(`64`)?64:32}bit, MemFPSet, MemStateQueue).`),Fl=(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`)},Il=async(i,a,o,s)=>{let c=a.has(`-seed`)?a.get(`-seed`)?.[0]:`0`;if(c===void 0)return Nl(s,`Error: seed required.`);if(!al(c))return Nl(s,`Error: An integer for seed required. But encountered ${c}`);let l=a.has(`-lncheck`)?a.get(`-lncheck`)?.[0]?.toLowerCase():`default`;if(l===void 0)return Nl(s,`Error: expect a strategy such as final for -lncheck option.`);let u=a.get(`-dump`);if(u?.length===0)return Nl(s,`Error: A file name for dumping states required.`);let d=u?.length===2&&sl.find(e=>u[0].toLowerCase().includes(e));if(d)return console.error(`Error: tla-ts does not support the -dump format ${d}.`),1;let f=a.get(`-fp`)?.[0];if(f!==void 0&&Number(f)!==0)return console.error(`Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${f}.`),1;let p=ol(a.get(`-workers`)),m=s.version;Ml(s),Pl(s,c,p);let h=a.get(`-config`)?.[0]??(a.has(`-config`)?void 0:i.replace(/\.tla$/,`.cfg`));if(!h||!(0,r.existsSync)(h))return s.print(e.I.configFileError,e.L.error,`TLC encountered the following error when trying to read the configuration file ${h??``}:\nFile not found.`),e.vt.configParseError;let g=(0,n.basename)(i,`.tla`),_={start:Date.now(),liveness:void 0,isParsed:!1},v=()=>{let t=Date.now()-_.start;s.print(e.I.finished,e.L.none,`Finished in ${s.isTool?`${t}ms`:e.H(t)} at (${e.V(/* @__PURE__ */ new Date)})`)},y=()=>s.print(e.I.parsingFailed,e.L.error,`Parsing or semantic analysis failed.`),b=t=>(t instanceof e.ft?y():Rl(t,s),v(),e.gt(t)),x=(()=>{try{return e.Z((0,r.readFileSync)(h,`utf8`),m)}catch(t){if(!(t instanceof e.at))throw t;return t}})();if(x instanceof e.at&&m===`1.7.4`)return s.print(e.I.general,e.L.error,`${e._t(`tlc2.tool.ConfigFileException`)}${e.B(x.message,s.isTool)}`),v(),e.vt.error;if(x instanceof e.at)return b(x);a.has(`-deadlock`)&&(x.checkDeadlock=!1);let S=(0,n.dirname)(i),C=[S,...o.libraries],w=Dl(C),T=Fl(a,m),E=async()=>{let o=(0,r.readFileSync)(i,`utf8`),d=e.D(o).name;if(d!==g)throw new e.dt(`File name '${g}' does not match the name '${d}' of the top level module it contains.`,void 0);let f=await t.t({workers:p,livenessCheck:[`final`,`seqfinal`,`off`].includes(l)?`final`:`default`,seed:BigInt(c),dump:u&&ll(u),isTool:s.isTool,isTraceRecorded:T,isSanyReported:!0,isWarningEnabled:!a.has(`-nowarning`),version:m,onProgress:e=>xl(s,e,_,S),source:o,config:x,onPause:()=>(0,r.readSync)(0,Buffer.alloc(1)),loadModule:w,loadClass:e=>{let t=bl(S,e);return(0,r.existsSync)(t)?(0,r.readFileSync)(t):void 0},readFile:e=>(0,r.existsSync)(e)?(0,r.readFileSync)(e,`utf8`):void 0,writeFile:(e,t)=>{(0,r.mkdirSync)((0,n.dirname)((0,n.resolve)(e)),{recursive:!0}),(0,r.writeFileSync)(e,t)}});return Tl(f,s,_),v(),f.failure?.exitCode??Xc[f.status]};s.isTool&&s.print(e.I.startingSany,e.L.none,`Starting SANY...`);let ee=(0,n.isAbsolute)(i),D=ee?g:i.replace(/\.tla$/,``),te=du(o),ne=m===`1.7.4`?ou(i,o,te):void 0;if(ne?!(0,r.existsSync)(i)&&!e.C.has(g)&&ne(`${g}.tla`):!(0,r.existsSync)(i)&&!e.w.has(g)&&Ol(ee?S:process.cwd(),ee?`${g}.tla`:`./${D}.tla`,[...ee||S===`.`?[]:[S],...o.libraries]),Tc(i,ne?su(w,ne):w,{fileName:D,describeFile:jl(i,C,o,a.get(`-metadir`)?.[0],m),version:m,rootExtendees:T?[`_TLCTrace`]:void 0,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}).isFailed)return xl(s,{kind:`parsed`},_,S),y(),v(),e.vt.specParseError;try{return await E()}catch(t){if(!(t instanceof e.ot))throw t;return t instanceof e.ft&&console.log(Ll(t,g)),_.isParsed||xl(s,{kind:`parsed`},_,S),b(t)}},Ll=(t,n)=>{let r=t instanceof e.dt;if(!r&&!t.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${t.message}\n\n`;let i=r?t.location===void 0?`Unknown location\n\n${t.message}`:`In module ${t.location}\n\n${t.message}`:`In module ${n}\n\nCould not parse module ${n} from file ${n}.tla`;return`${t.failure?`***Parse Error***\n${t.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${n}\n\n${i}\n*** Errors: 1\n\n${i}\n\n\n`},Rl=(t,n)=>{if(t instanceof e.at||t instanceof e.st){let r=e.U(t.message),i=r&&!r.isEvalException?r.code:e.I.general;return n.print(i,e.L.error,e.z(i,t.message,n.isTool))}console.error(`${t.name}: ${t.message}`)},zl=async(t,n=e.R(!1))=>{try{return await t()}catch(t){if(!(t instanceof e.ot))throw t;return Rl(t,n),e.gt(t)}},Bl=async(t,n,r)=>{let i=[];for(let[e,a]of t.entries()){e>0&&console.log(``);let t=r();i.push(await zl(()=>n(a,t),t))}return i.find(t=>t!==e.vt.success)??e.vt.success},Vl=()=>(process.env.PATH??``).split(n.delimiter).map(e=>(0,n.join)(e,`tlapm`)).filter(e=>(0,r.existsSync)(e)),Hl=()=>Vl().map(e=>(0,n.join)((0,n.dirname)((0,n.dirname)((0,r.realpathSync)(e))),`lib/tlapm/stdlib`)).find(e=>(0,r.existsSync)(e)),Ul=e=>e.flatMap(e=>rl.test(e)?(0,r.globSync)(e).sort():[e]),Wl=e=>{let t=Vl()[0];return t===void 0?(console.error(`Error: tla-ts prove runs tlapm to prove obligations, but tlapm isn't on your PATH. Install tlapm, or pass -N to only generate the obligations.`),1):(0,i.spawnSync)(t,Ul(e),{stdio:`inherit`}).status??1},Gl=e=>(0,r.existsSync)(e)?{file:e,source:(0,r.readFileSync)(e,`utf8`)}:void 0,Kl=e=>console.error(`@!!BEGIN\n${e.map(e=>`@!!${e}\n`).join(``)}@!!END\n`),ql=e=>/^[+,\-./0-9:=@A-Z_a-z]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`,Jl=t=>console.log(`\n\\* TLAPM version 5f5037f\n\\* launched at ${e.V(/* @__PURE__ */ new Date)} with command line:\n\\* ${[`tla-ts`,`prove`,...t].map(ql).join(` `)}\n`),Yl={incomplete:11,emptyTarget:12},Xl=(e,t,n)=>{let r=e.summary;n||(r.absent.forEach(e=>console.error(`Missing proof at ${m(e)}`)),r.omitted.forEach(e=>console.error(`Omitted proof at ${m(e)}`)));let i=r.absent.length+r.omitted.length>0;i&&console.error(`${h(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(`${h(e.location)}[ERROR]: No proof obligation found for the selected target.`),[...i?[Yl.incomplete]:[],...a?[Yl.emptyTarget]:[]]},Zl=t=>{try{return t()}catch(t){if(!(t instanceof e.ut))throw t;console.error(` tlapm ending abnormally with ${t.exception}\n`);return}},Ql=t=>{if(!t.includes(`-N`)&&!t.includes(`--summary`))return Wl(t);let i=Qc.parse(t),a=i.unknown[0];if(a!==void 0)return console.error(`Error: tla-ts prove does not support the tlapm option ${a}.`),1;if(i.incomplete)return console.error(`Error: option '${i.incomplete.name}' needs an argument.`),1;let o=i.options.find(e=>e.name!==`-I`&&e.values.some(e=>!/^-?\d+$/.test(e)));if(o)return console.error(`Error: option '${o.name}' expects an integer.`),1;let s=Ul(i.positionals),c=s.map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(c.length===0)return console.error(nl),1;let l=i.has(`--toolbox`)||i.has(`--line`);l&&Jl(t);let u=i.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?Zr:{start:n,end:n}:e},Zr),d=Hl(),f=i.options.flatMap(e=>e.name===`-I`?e.values:[]),p=c.reduce((e,t)=>e.includes((0,n.dirname)(t))?e:[(0,n.dirname)(t),...e],[`.`,...d?[d]:[],...f.toReversed()]),m=Zl(()=>{let t=c.findIndex(e=>!(0,r.existsSync)(e));if(t!==-1){let n=s[t];throw console.error(`File "<unknown>":\nError: File ${JSON.stringify(n)} not found`),new e.ut(`File ${n} not found`,{failure:`Module.Parser.parse_file`})}return ui(c.map(e=>({file:`./${e}`,source:(0,r.readFileSync)(e,`utf8`)})),e=>p.map(t=>Gl(`${t}/${e}.tla`)).find(Boolean),{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 Kl([`type:warning`,`msg:${e.text}`]);e.channel!==`toolboxOnly`&&console.error(e.text)}})});if(!m)return 3;let h=m.flatMap(e=>(i.has(`--summary`)&&console.log(li(e)),l&&(e.obligations.forEach(e=>Kl([`type:obligation`,`id:${e.id}`,`loc:${e.location}`,`status:to be proved`,...i.has(`--printallobs`)?[`obl:${e.text}`]:[]])),Kl([`type:obligationsnumber`,`count:${e.obligations.length}`])),i.has(`--strict`)?Xl(e,u.start>0||u.end<1/0,i.has(`--summary`)):[]));return h.includes(Yl.incomplete)?Yl.incomplete:h[0]??e.vt.success},$l=async(t,i)=>{let a=Zc.parse(t),o=il(a.positionals),s=a.has(`-config`),c=o.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||s||(0,r.existsSync)(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(c.length===0)return console.error(nl),1;if(s&&c.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let l=[...new Set(c.map(e=>(0,r.existsSync)(e)||(0,n.isAbsolute)(e)?e:i.libraries.map(t=>(0,n.join)(t,e)).find(r.existsSync)??e))],u=fu(i);return Bl(l,(e,t)=>(l.length>1&&console.log(`Checking ${(0,n.basename)(e)} with ${(0,n.basename)(e,`.tla`)}.cfg`),Il(e,a,i,t)),()=>e.R(a.has(`-tool`),!a.has(`-nowarning`),u))},eu=e=>(process.stderr.write(`ERROR: ${e}\n${tl}`),Ec.argsParsingFailure),tu=(t,n)=>{try{return process.stdout.write(qc(t,n)),e.vt.success}catch(t){if(!(t instanceof e.pt))throw t;let n=e.gt(t),r=t instanceof e.ct?t.unwound:``;return console.error(n===Ec.uncaughtException?`${r}Exception in thread "main" ${t.message}`:`ERROR: ${t.message}`),n}},nu=(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`}},ru=t=>{if(t.length===0)return eu(`at least one .tla file must be given`);let i=nu(t,$c);if(i.error===`missing-include`)return eu(`the -I flag must be followed by a directory and at least one .tla file`);if(i.error===`several-files`)return eu(`Only one TLA file to check allowed!`);let a=t[t.length-1];if(a===`-help`)return process.stdout.write(tl),e.vt.success;let o=a.endsWith(`.tla`)?a:`${a}.tla`,s=[`.`,...i.includes],c=s.map(e=>(0,n.resolve)(e,o)).find(r.existsSync);c===void 0&&!e.w.has(o.slice(0,-4))&&Ol(process.cwd(),`./${o}`,i.includes);let l=Tc(c??o,Dl(s),{fileName:a,isXmlExport:!0});return process.stderr.write(l.text),l.isFailed||l.specification===void 0?(console.error(`ERROR: Failed to parse module.`),Ec.specParsingFailure):tu(l.specification,{version:`master`,isRestricted:i.flags.has(`-r`),isUncommented:i.flags.has(`-u`),isTerse:i.flags.has(`-t`)})},iu=(e,t,r)=>console.error(`File does not exist: ${(0,n.isAbsolute)(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,...r===void 0?[]:[kl(r)]].join(`, `)}`),au=e=>e.endsWith(`/`)?e:`${e}/`,ou=(e,t,r)=>{let i=e.slice(0,e.lastIndexOf(`/`)+1),a=(!(0,n.isAbsolute)(e)&&i!==``?[i]:t.libraries).map(au),o=a.length>0?a[a.length-1]:(0,n.isAbsolute)(e)?i:``;return e=>iu(`${o}${e}`,a,r)},su=(t,n)=>r=>{let i=t(r);return i===void 0&&!e.C.has(r)&&n(`${r}.tla`),i},cu=(e,t)=>(console.error(`Exception in thread "main" ${e}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${t})`),Ec.uncaughtException),lu=(t,i)=>{if(t.length===0)return cu(`java.lang.IllegalArgumentException: at least one .tla file must be given`,59);let a=nu(t,el);if(a.error===`missing-include`)return cu(`java.lang.IllegalArgumentException: the -I flag must be followed by a directory and at least one .tla file`,71);if(a.error===`several-files`)return cu(`java.lang.IllegalArgumentException: Only one TLA file to check allowed!`,83);let o=t[t.length-1],s=`${o.replace(/\.tla$/i,``)}.tla`,c=(a.includes.length===0?[`/`]:a.includes).map(au),l=[`.`,...c],u=e=>iu(`${c[c.length-1]}${e}`,c,i),d=l.map(e=>(0,n.resolve)(e,s)).find(r.existsSync);if(d===void 0&&!e.C.has((0,n.basename)(s,`.tla`)))return u(s),e.vt.success;let f=Tc(d??s,su(Dl(l),u),{fileName:o,isXmlExport:!0,version:`1.7.4`});return process.stderr.write(f.text),f.specification===void 0?cu(`tla2sany.xml.XMLExportingException: spec ${(d&&wc((0,r.readFileSync)(d,`utf8`),`1.7.4`))??`null`} is malformed - does not have a root module`,110):tu(f.specification,{version:`1.7.4`,isRestricted:!1,isUncommented:!1,isTerse:!0})},uu=[`tlc2.TLC`,`tla2sany.xml.XMLExporter`],du=e=>e.classPath?.split(n.delimiter).find(e=>e.endsWith(`.jar`)),fu=e=>e.tlcVersion??Yc(du(e)),pu=e=>{let t={libraries:[]};for(let r=0;r<e.length;r++){let i=e[r];if(i===`-cp`||i===`-classpath`||i===`--class-path`)r++,t.classPath=e[r];else if(i===`-jar`)return t.classPath=e[r+1],{mainClass:`tlc2.TLC`,args:e.slice(r+2),java:t};else if(i.startsWith(`-DTLA-Library=`))t.libraries.push(...i.slice(14).split(n.delimiter));else if(i.startsWith(`-Djava.io.tmpdir=`))t.temporaryDirectory=i.slice(17);else if(i.startsWith(`-Dtla-ts.tlc=`))t.tlcVersion=i.slice(13)===`1.7.4`?`1.7.4`:`master`;else if(!i.startsWith(`-D`)&&!i.startsWith(`-X`))return r>0||uu.includes(i)?{mainClass:i,args:e.slice(r+1),java:t}:void 0}},mu=e=>e.mainClass===`tlc2.TLC`?$l(e.args,e.java):e.mainClass===`tla2sany.xml.XMLExporter`?zl(()=>fu(e.java)===`1.7.4`?lu(e.args,du(e.java)):ru(e.args)):(console.error(`Error: tla-ts runs the Java classes ${uu.join(` and `)}, not ${e.mainClass}.`),1),hu=async e=>{if(e[0]===`prove`)return zl(()=>Ql(e.slice(1)));let t=pu(e);return t?mu(t):$l(e,{libraries:[]})},gu=async()=>{process.exitCode=await hu(process.argv.slice(2))};exports.runCli=gu;