@shd101wyy/yo 0.0.33 → 0.1.1

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/out/esm/index.mjs CHANGED
@@ -3,7 +3,7 @@ var Ci=class{constructor(){this.headers="";this.declarations="";this.code=""}emi
3
3
  `,this.headers}emitDeclarationLine(t,n=""){return this.declarations+=n+t+`
4
4
  `,this.declarations}print(){return this.headers+`
5
5
  `+this.declarations+`
6
- `+this.code.trim()}};import{readFileSync as gy}from"node:fs";import hy from"path";var Sn=class{constructor({characterIndex:t,message:n,row:r}){this.characterIndex=t,this.message=n,this.row=r}toString(){return`Lexer Error at row ${this.row+1}: ${this.message}`}},yn=class{constructor(t,n,r){this.tokenAndErrorList=[];this.tokenAndErrorList=t,this.isAssertionError=n||!1,this.kind=r}toString(){return this.tokenAndErrorList.map(({token:n,errorMessage:r})=>`Error: ${r}
6
+ `+this.code.trim()}};import{readFileSync as hy}from"node:fs";import vy from"path";var Sn=class{constructor({characterIndex:t,message:n,row:r}){this.characterIndex=t,this.message=n,this.row=r}toString(){return`Lexer Error at row ${this.row+1}: ${this.message}`}},yn=class{constructor(t,n,r){this.tokenAndErrorList=[];this.tokenAndErrorList=t,this.isAssertionError=n||!1,this.kind=r}toString(){return this.tokenAndErrorList.map(({token:n,errorMessage:r})=>`Error: ${r}
7
7
  ${Yl({token:n})}`).join(`
8
8
 
9
9
  `)}};function Yl({token:e}){let{position:t,modulePath:n,inputString:r}=e,{row:i,column:o}=t,s=r.split(`
@@ -12,7 +12,7 @@ ${s}
12
12
  ${" ".repeat(o+Math.floor(e.value.length/2))}^`}function y({token:e,errorMessage:t,cause:n,isAssertionError:r,kind:i}){let o=`${t.trim()}
13
13
 
14
14
  ${Yl({token:e})}`;return new yn([{token:e,errorMessage:o+(n?.message?`
15
- `+n.message:"")}],r,i)}function lt(e,t,n){if(e.length===0)throw new Error("tokenAndErrorList must not be empty");return new yn(e,t,n)}var jt=($=>($.Operator="operator",$.Dot=".",$.LParen="(",$.RParen=")",$.LBracket="[",$.RBracket="]",$.LCurlyBracket="{",$.RCurlyBracket="}",$.Char="char",$.String="string",$.Identifier="identifier",$.Integer="integer",$.Float="float",$.Bool="bool",$.Semicolon=";",$.Comma=",",$.SingleLineComment="single_line_comment",$.MultiLineComment="multi_line_comment",$.Whitespace="whitespace",$.TemplateString="template_string",$))(jt||{}),ae={modulePath:"_",inputString:"_",type:"identifier",value:"_",position:{row:0,column:0,character:0}},Rh={modulePath:"drop",inputString:"drop",type:"identifier",value:"drop",position:{row:0,column:0,character:0}},rs=["=","+","-","*","/","<",">","@","$","~","&","%","|","!","?","^",".",":","\\","#"];function yo(e){return rs.includes(e)}function ir(e){let t=!0;for(let n=0;n<e.length;n++){let r=e[n];if(!yo(r)){t=!1;break}}return t}var is=/^[_a-zA-Z\xA0-\uFFFF][_a-zA-Z0-9\xA0-\uFFFF]*[!?]?$/;function Hl(e,t){let n=")";if(!e[t])return-1;let r=e[t].type;if(r==="{")n="}";else if(r==="(")n=")";else if(r==="[")n="]";else throw new Error("Expected '{', '(' or '['");t=t+1;let i=1,o=-1;for(;;){let a=e[t];if(!a)return-1;if(a.type===n){if(i=i-1,i===0){o=t;break}}else a.type===r&&(i=i+1);t=t+1}return o}var os;function jl(e){os=e}function S({expr:e,env:t,context:n}){if(!os)throw new Error("Internal Error: evaluateExpression function is not set.");return os({expr:e,env:t,context:n})}function Kl(e,t){let n=[],r=0,i=0;for(let o=0;o<e.length;o++){let a=e[o],s=o-i,l=o,u="",c=o;if(e[c]===".")for(;e[c]===".";)u+=e[c],c=c+1;else for(;yo(e[c])&&e[c]!==".";)u+=e[c],c=c+1;if(u&&!u.startsWith("//")&&!u.startsWith("/*")){n.push({type:u==="."?".":"operator",value:u,position:{row:r,column:s,character:l},modulePath:t,inputString:e}),o=c-1;continue}switch(a){case" ":case" ":case`
15
+ `+n.message:"")}],r,i)}function lt(e,t,n){if(e.length===0)throw new Error("tokenAndErrorList must not be empty");return new yn(e,t,n)}var jt=($=>($.Operator="operator",$.Dot=".",$.LParen="(",$.RParen=")",$.LBracket="[",$.RBracket="]",$.LCurlyBracket="{",$.RCurlyBracket="}",$.Char="char",$.String="string",$.Identifier="identifier",$.Integer="integer",$.Float="float",$.Bool="bool",$.Semicolon=";",$.Comma=",",$.SingleLineComment="single_line_comment",$.MultiLineComment="multi_line_comment",$.Whitespace="whitespace",$.TemplateString="template_string",$))(jt||{}),ae={modulePath:"_",inputString:"_",type:"identifier",value:"_",position:{row:0,column:0,character:0}},Ph={modulePath:"drop",inputString:"drop",type:"identifier",value:"drop",position:{row:0,column:0,character:0}},rs=["=","+","-","*","/","<",">","@","$","~","&","%","|","!","?","^",".",":","\\","#"];function yo(e){return rs.includes(e)}function ir(e){let t=!0;for(let n=0;n<e.length;n++){let r=e[n];if(!yo(r)){t=!1;break}}return t}var is=/^[_a-zA-Z\xA0-\uFFFF][_a-zA-Z0-9\xA0-\uFFFF]*[!?]?$/;function Hl(e,t){let n=")";if(!e[t])return-1;let r=e[t].type;if(r==="{")n="}";else if(r==="(")n=")";else if(r==="[")n="]";else throw new Error("Expected '{', '(' or '['");t=t+1;let i=1,o=-1;for(;;){let a=e[t];if(!a)return-1;if(a.type===n){if(i=i-1,i===0){o=t;break}}else a.type===r&&(i=i+1);t=t+1}return o}var os;function jl(e){os=e}function S({expr:e,env:t,context:n}){if(!os)throw new Error("Internal Error: evaluateExpression function is not set.");return os({expr:e,env:t,context:n})}function Kl(e,t){let n=[],r=0,i=0;for(let o=0;o<e.length;o++){let a=e[o],s=o-i,l=o,u="",c=o;if(e[c]===".")for(;e[c]===".";)u+=e[c],c=c+1;else for(;yo(e[c])&&e[c]!==".";)u+=e[c],c=c+1;if(u&&!u.startsWith("//")&&!u.startsWith("/*")){n.push({type:u==="."?".":"operator",value:u,position:{row:r,column:s,character:l},modulePath:t,inputString:e}),o=c-1;continue}switch(a){case" ":case" ":case`
16
16
  `:case"\r":{let _="",p=o,f=r;for(;e[p]===" "||e[p]===" "||e[p]===`
17
17
  `||e[p]==="\r";)_+=e[p],e[p]===`
18
18
  `&&(r++,i=p+1),p=p+1;n.push({type:"whitespace",value:_,position:{row:f,column:s,character:l},modulePath:t,inputString:e}),o=p-1;break}case"/":if(e[o+1]==="/"){let _="",p=o;for(;e[p]!==`
@@ -40,8 +40,8 @@ ${e}
40
40
  `,inputString:e});if(t.getParserError())throw t.getParserError();let n=t.getProgram();if(n.length!==1)throw new Error(`Expected exactly one expression from parsed code, got ${n.length}: "${e}"
41
41
  ${n.map(r=>w(r)).join(`
42
42
  `)}
43
- `);return n[0]}function go(e){return e.tag==="unit"||e.tag==="bool"||e.tag==="usize"||e.tag==="isize"||e.tag==="u8"||e.tag==="i8"||e.tag==="u16"||e.tag==="i16"||e.tag==="u32"||e.tag==="i32"||e.tag==="u64"||e.tag==="i64"||e.tag==="f32"||e.tag==="f64"||e.tag==="char"||e.tag==="short"||e.tag==="ushort"||e.tag==="int"||e.tag==="uint"||e.tag==="long"||e.tag==="ulong"||e.tag==="longlong"||e.tag==="ulonglong"||e.tag==="longdouble"}function pe(e){return e?.tag==="unit"}function vt(e){return e?.tag==="comptime_int"}function Nt(e){return e?.tag==="comptime_float"}function Et(e){return e?.tag==="comptime_string"}function Vt(e){return e?.tag==="ComptimeList"}function Zr(e){return Vt(e)&&Lt(e.childType)}function cn(e){return e?.tag==="bool"}function ho(e){return e?.tag==="usize"}function vo(e){return e?.tag==="isize"}function Hn(e){return e?.tag==="u8"}function To(e){return e?.tag==="i8"}function Eo(e){return e?.tag==="u16"}function $o(e){return e?.tag==="i16"}function Co(e){return e?.tag==="u32"}function bo(e){return e?.tag==="i32"}function ko(e){return e?.tag==="u64"}function wo(e){return e?.tag==="i64"}function Fo(e){return e?.tag==="f32"}function Lo(e){return e?.tag==="f64"}function Lt(e){return e?.tag==="Expr"}function ke(e){return e?.tag==="Array"}function Qe(e){return e?.tag==="Slice"}function we(e){return e?.tag==="Tuple"}function it(e){return e?.tag==="Union"}function ge(e){return e?.tag==="Enum"}function ce(e){return e?.tag==="Struct"}function pt(e){return e?.tag==="Struct"&&e.isReferenceSemantics}function Er(e){return e?.tag==="Struct"&&e.isNewtype}function Te(e){return e?.tag==="Module"}function De(e){return e?.tag==="Trait"}function bt(e){return De(e)&&e.isFn!==void 0}function G(e){return e?.tag==="Function"}function Ao(e){return e?.tag==="Function"&&e.return.isCompileTimeOnly}function He(e){return e?.tag==="Type"}function Xl(e){return He(e)&&e.tag==="Type"&&e.level===0}function x(e){return e?.tag==="SomeType"}function Ie(e){return e?.tag==="Ptr"}function kt(e){return e?.tag==="Iso"}function $t(e){return e?.tag==="Arc"}function be(e){return e?.tag==="Dyn"}function sn(e){if(x(e)){let t=e;if(Ce(t))return!0;if(t.resolvedConcreteType)return sn(t.resolvedConcreteType)}return pt(e)||be(e)||kt(e)||$t(e)}function or(e){return e?.tag==="u8"||e?.tag==="i8"||e?.tag==="u16"||e?.tag==="i16"||e?.tag==="u32"||e?.tag==="i32"||e?.tag==="u64"||e?.tag==="i64"||e?.tag==="usize"||e?.tag==="isize"}function ar(e){return e?.tag==="f32"||e?.tag==="f64"}function Ql(e){return e?.tag==="i8"||e?.tag==="i16"||e?.tag==="i32"||e?.tag==="i64"||e?.tag==="isize"}function ki(e){return e?.tag==="char"}function $r(e){return e?.tag==="void"}function Kt(e){return De(e)&&e.isFuture!==void 0}function oa(e){return De(e)&&e.isConcrete!==void 0}function jn(e){return!!e&&(e.tag==="char"||e.tag==="short"||e.tag==="ushort"||e.tag==="int"||e.tag==="uint"||e.tag==="long"||e.tag==="ulong"||e.tag==="longlong"||e.tag==="ulonglong"||e.tag==="longdouble")}function Pn(e){if(!e||e.return?.isCompileTimeOnly)return!1;let t=e.parameters.some(r=>r.isCompileTimeOnly)||e.forallParameters.length>0||e.implicitParameters.length>0,n=e.parameters.some(r=>!r.isCompileTimeOnly&&x(r.type)&&!Ce(r.type));return t||n}function sr(e){if(!e||e.return?.isCompileTimeOnly)return!1;let t=e.parameters.some(r=>r.isCompileTimeOnly)||e.forallParameters.length>0,n=e.parameters.some(r=>!r.isCompileTimeOnly&&x(r.type)&&!Ce(r.type));return t||n}function as(e){let t=e.type;return t?Pn(t)&&(e.specializedFunctionCaches?.length??0)>0:!1}function $n(e){return pt(e)?e.fields.length===1&&e.fields[0].label==="*"&&!!e.typeName?.startsWith("Box("):!1}function ot(e){return e?.tag==="EffectsRow"}function aa(e,t,n){let r=!1,i=0;for(let o of t){let a=o.type;if(n.includes(o))throw y({token:n[n.length-1].exprs.expr.token,errorMessage:`Recursive type has infinite size in field "${n[n.length-1].label}"
44
- Insert some indirection (e.g., a pointer '*' or reference '&') to break the cycle.`});if(pt(a))continue;let s=[...n,o],l=wt(a,s);He(l)&&(i=Math.max(i,l.level),l.tag==="Type"&&(r=!0))}return i>0?gn(i):r?tt(e):tt(e)}function wt(e,t=[]){if(be(e))return tt(e);if(go(e))return tt(e);if(He(e))return gn(e.level+1);if(vt(e)||Nt(e)||Et(e)||Vt(e))return tt(e);if(Lt(e))return tt(e);if(G(e))return tt(e);if(bt(e))return tt(e);if(ke(e))return wt(e.childType,t);if(Qe(e))return tt(e);if(we(e))return aa(e,e.fields,t);if(ce(e))return aa(e,e.fields,t);if(ge(e)){let n=[];for(let r of e.variants)r.fields&&n.push(...r.fields);return aa(e,n,t)}else{if(it(e))return aa(e,e.fields,t);if(Te(e))return gn(1,e);if(De(e))return gn(1,e);if(x(e))return e.parentType;if(Ie(e))return tt(e);if(kt(e))return tt(e);if($t(e))return tt(e);if(Kt(e))return tt(e);if($r(e))return tt(e);if(ot(e))return gn(1);throw new Error(`Unknown type tag: ${e.tag}`)}}function Zl(e){if(e.exprs.labelExpr?.token)return e.exprs.labelExpr.token;if(e.exprs.typeExpr?.token)return e.exprs.typeExpr.token;if(e.exprs.defaultValueExpr?.token)return e.exprs.defaultValueExpr.token;throw new Error("Cannot get token for function parameter")}function Me(e){if(!e)return"<runtime value>";switch(e.tag){case"Type":return A(e.value);case"ComptimeInt":case"ComptimeFloat":return e.value.toString();case"ComptimeString":return JSON.stringify(e.value);case"ComptimeList":return`comptime_list(${e.elements.map(Me).join(", ")})`;case"U8":case"I8":case"U16":case"I16":case"U32":case"I32":case"U64":case"I64":case"F32":case"F64":case"Usize":case"Isize":return typeof e.value=="bigint",e.value.toString();case"Bool":return e.value.toString();case"Array":return`[${e.elements.map(Me).join(", ")}${e.elements.length===1?",":""}]`;case"Slice":return`slice[${e.sourceArray[0].elements.slice(e.startIndex,e.endIndex).map(Me).join(", ")}]`;case"Tuple":return e.fields.length===0?"()":`(${e.fields.map(Me).join(", ")}${e.fields.length===1?",":""})`;case"Struct":return`${e.type.typeName??"_"}(${e.fields.map((t,n)=>{let r=e.type.fields[n].label;return ir(r)&&(r=`(${r})`),`${r}: ${Me(t)}`}).join(", ")})`;case"Enum":{if(e.fields.length===0)return`.${e.variantName}`;let t=e.type.variants.find(n=>n.name===e.variantName);return`.${e.variantName}(${e.fields.map((n,r)=>{let i=t?.fields[r].label??"_";return ir(i)&&(i=`(${i})`),`${i}: ${Me(n)}`}).join(", ")})`}case"Function":return e.funcName?`<fn ${e.funcName}>`:e.type.typeName?`<fn ${e.type.typeName}>`:"<fn>";case"Module":return`${e.type.typeName??"_"}(${e.fields.map((t,n)=>{let r=e.type.fields[n].label;return ir(r)&&(r=`(${r})`),`${r}: ${Me(t)}`}).join(", ")})`;case"Trait":return`${e.type.typeName??"_"}(${e.fields.map((t,n)=>{let r=e.type.fields[n].label;return ir(r)&&(r=`(${r})`),`${r}: ${Me(t)}`}).join(", ")})`;case"Unit":return"()";case"Expr":return`quote(${w(e.value)})`;case"Unknown":return e.variableName?e.variableName:`<comptime ${A(e.type)}>`;case"Ptr":{let t=e.targetValue[0];return Un(t)?`<ptr to ${Me(t.elements[e.targetIndex])}>`:`<ptr to ${Me(t)}>`}default:throw new Error("valueToString: Unsupported value")}}function O(e){return e?.tag==="Type"}function An(e){return e?.tag==="ComptimeInt"}function la(e){return e?.tag==="ComptimeFloat"}function Ve(e){return e?.tag==="ComptimeString"}function lr(e){return e?.tag==="ComptimeList"}function Jl(e){return lr(e)&&Lt(e.type.childType)}function ze(e){return e?.tag==="ComptimeInt"||e?.tag==="ComptimeFloat"||e?.tag==="U8"||e?.tag==="I8"||e?.tag==="U16"||e?.tag==="I16"||e?.tag==="U32"||e?.tag==="I32"||e?.tag==="U64"||e?.tag==="I64"||e?.tag==="F32"||e?.tag==="F64"||e?.tag==="Usize"||e?.tag==="Isize"}function Re(e){return e?.tag==="Bool"}function ne(e){return e?.tag==="Function"}function de(e){return e?.tag==="Unknown"}function hn(e){return e?.tag==="Tuple"}function Cn(e){return e?.tag==="Struct"}function Un(e){return e?.tag==="Array"}function sa(e){return e?.tag==="Slice"}function It(e){return e?.tag==="Enum"}function We(e){return e?.tag==="Module"}function Tt(e){return e?.tag==="Trait"}function wi(e){return e?.tag==="Ptr"}function ln(e){return e?.tag==="Expr"}function ee(e){return{tag:"Type",type:wt(e),value:e}}function on(e){return{tag:"ComptimeString",type:xt(),value:e}}function zn(e,t){return{tag:"ComptimeList",type:Io(e),elements:t}}function Xt(e,t){let n;if(e==="ComptimeInt")n=Or();else if(e==="ComptimeFloat")n=Li();else if(e==="U8")n=Ii();else if(e==="I8")n=Si();else if(e==="U16")n=Ni();else if(e==="I16")n=Vi();else if(e==="U32")n=xi();else if(e==="I32")n=Rr();else if(e==="U64")n=Di();else if(e==="I64")n=Mi();else if(e==="F32")n=Oi();else if(e==="F64")n=Pr();else if(e==="Usize")n=gt();else if(e==="Isize")n=Ai();else throw new Error(`createNumberValue: Unsupported tag: ${e}`);return{tag:e,type:n,value:t}}function ur(e){return Xt("ComptimeInt",e)}function ua(e){return Xt("ComptimeFloat",e)}function ft(e){return{tag:"Bool",type:Je(),value:e}}function K(e,{variableName:t,recursiveTypeRef:n,env:r,context:i}){if(He(e)&&e.level===0){if(!t)throw console.trace("!variableName bug found in createUnknownValue"),new Error(`createUnknownValue expects a variable name for type ${A(e)}`);let o=bn(e,t,{recursiveTypeRef:n,env:r,context:i});return ee(o)}return{tag:"Unknown",type:e,variableName:t}}function Bn(e,t){return{tag:"Struct",type:e,fields:t}}function ca(e,t){return{tag:"Module",type:e,fields:t}}function Fi(e,t){return{tag:"Trait",type:e,fields:t}}function _a(e,t){return{tag:"Tuple",type:e,fields:t}}function Jr(e,t,n){return{tag:"Enum",type:e,variantName:t,fields:n}}function Mr(e,t){return{tag:"Array",type:e,elements:t}}function pa(e,t,n,r){return{tag:"Slice",type:e,sourceArray:t,startIndex:n,endIndex:r}}function Gn(e){return{tag:"Expr",type:_n(),value:e}}function ss(e,t,n=0){return{tag:"Ptr",type:e,targetValue:t,targetIndex:n}}function At(e,t){let n=e.value,r=t.value;if(n===r)return!0;if(!n||!r)return!1;if(n.tag==="Type"&&r.tag==="Type")return Y({type:n.value,env:e.env},{type:r.value,env:t.env},!0);if(Ve(n)&&Ve(r))return n.value===r.value;if(lr(n)&&lr(r)){if(n.elements.length!==r.elements.length)return!1;for(let i=0;i<n.elements.length;i++)if(!At({value:n.elements[i],env:e.env},{value:r.elements[i],env:t.env}))return!1;return!0}else if(ze(n)&&ze(r)){let i=n.value,o=r.value;if(typeof i==typeof o)return i===o;let a=typeof i=="bigint"?i:BigInt(i),s=typeof o=="bigint"?o:BigInt(o);return a===s}else{if(Re(n)&&Re(r))return n.value===r.value;if(Un(n)&&Un(r)){if(n.elements.length!==r.elements.length)return!1;for(let i=0;i<n.elements.length;i++)if(!At({value:n.elements[i],env:e.env},{value:r.elements[i],env:t.env}))return!1;return!0}else if(sa(n)&&sa(r)){let i=n.endIndex-n.startIndex,o=r.endIndex-r.startIndex;if(i!==o)return!1;for(let a=0;a<i;a++){let s=n.sourceArray[0].elements[n.startIndex+a],l=r.sourceArray[0].elements[r.startIndex+a];if(!At({value:s,env:e.env},{value:l,env:t.env}))return!1}return!0}else if(hn(n)&&hn(r)){if(n.fields.length!==r.fields.length)return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(Cn(n)&&Cn(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0))return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(It(n)&&It(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0)||n.variantName!==r.variantName)return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(We(n)&&We(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0))return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(Tt(n)&&Tt(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0))return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else{if(ln(n)&&ln(r))return n.value===r.value||fa(n.value,r.value);if(de(n)&&de(r)){let i,o;if(n.variableName){let a=X(e.env,n.variableName);if(a.length>0){let s=a[a.length-1];s.value&&!de(s.value[0])&&(i=s.value[0])}}if(r.variableName){let a=X(t.env,r.variableName);if(a.length>0){let s=a[a.length-1];s.value&&!de(s.value[0])&&(o=s.value[0])}}return i&&o?At({value:i,env:e.env},{value:o,env:t.env}):i||o?!1:Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0)}else if(de(n)&&!de(r)){if(n.variableName){let i=X(e.env,n.variableName);if(i.length>0){let o=i[i.length-1];if(o.value&&!de(o.value[0]))return At({value:o.value[0],env:e.env},{value:r,env:t.env})}}return!1}else if(!de(n)&&de(r)){if(r.variableName){let i=X(t.env,r.variableName);if(i.length>0){let o=i[i.length-1];if(o.value&&!de(o.value[0]))return At({value:n,env:e.env},{value:o.value[0],env:t.env})}}return!1}else return wi(n)&&wi(r)?n.targetValue===r.targetValue&&n.targetIndex===r.targetIndex:!1}}}function _r(e,t){return e?ti(e,t):!1}function pr(e,t){return e?hm(e,t):!1}function ti(e,t){return Xn(e,t)&&!Fr(e,t)}function hm(e,t){let n=Xn(e,t),r=Fr(e,t);return!n&&r}function Le(e,t=[]){if(!e||t.includes(e)||(t.push(e),e.isExtern))return!1;if(sn(e))return!0;switch(e.tag){case"Array":return Le(e.childType,t);case"Tuple":return e.fields.some(n=>Le(n.type,t));case"Union":return e.fields.some(n=>Le(n.type,t));case"Struct":return e.fields.some(n=>Le(n.type,t));case"Enum":return e.variants.some(n=>n.fields?.some(r=>Le(r.type,t)));case"Iso":return Le(e.childType,t);case"Arc":return Le(e.childType,t);case"Module":return!1;case"Function":return!1;case"SomeType":{let n=e;return Ce(n)?!0:n.resolvedConcreteType?Le(n.resolvedConcreteType,t):!0}default:return!1}}function Fe(e,t=[]){if(!e||t.includes(e))return!1;if(t.push(e),x(e))return e.isExtern?!1:e.resolvedConcreteType?Fe(e.resolvedConcreteType,t):!(Wt(e)||Ce(e));switch(e.tag){case"Array":return Fe(e.childType,t);case"Tuple":return e.fields.some(n=>Fe(n.type,t));case"Struct":return e.fields.some(n=>!n.isEffectParam&&Fe(n.type,t));case"Enum":return e.variants.some(n=>n.fields?.some(r=>Fe(r.type,t)));case"Union":return e.fields.some(n=>Fe(n.type,t));case"Function":{let n=e;return n.forallParameters.length>0||n.parameters.some(r=>Fe(r.type,t))||Fe(n.return.type,t)}case"Module":return e.fields.some(n=>Fe(n.type,t));case"Ptr":return Fe(e.childType,t);default:return!1}}function Cr(e,t=new Set){return t.has(e.id)?!1:(t.add(e.id),ke(e)?de(e.length)?!0:Cr(e.childType,t):Ie(e)||Qe(e)?Cr(e.childType,t):we(e)?e.fields.some(n=>Cr(n.type,t)):ce(e)?e.fields.some(n=>Cr(n.type,t)):ge(e)?e.variants.some(n=>n.fields?.some(r=>Cr(r.type,t))):it(e)?e.fields.some(n=>Cr(n.type,t)):!1)}function us(e){let t=new Set,n=new Set;function r(i){if(!(i&&n.has(i))){if(i&&n.add(i),x(i)){if(t.has(i))return;i.resolvedConcreteType||t.add(i)}switch(i.tag){case"Array":r(i.childType);break;case"Tuple":i.fields.forEach(o=>r(o.type));break;case"Struct":i.fields.forEach(o=>r(o.type));break;case"Enum":i.variants.forEach(o=>{o.fields?.forEach(a=>r(a.type))});break;case"Union":i.fields.forEach(o=>r(o.type));break;case"Module":i.fields.forEach(o=>r(o.type));break;case"Ptr":r(i.childType);break;default:break}}}return r(e),t}function Pi(e){if(!e)return!1;switch(e.tag){case"Array":{let t=e;return de(t.length)||Pi(t.childType)}case"SomeType":return!0;case"Module":return!1;case"Trait":{let t=e;return t.isFn?Pi(t.isFn.callType):!1}default:return!1}}function yt({type:e,expectedType:t,expr:n,env:r}){let i;if(vt(e))i=Rr();else if(Nt(e))i=Pr();else if(Et(e))t&&(Ie(t)&&(Hn(t.childType)||ki(t.childType))||Qe(t))&&(i=t),i||(i=ru(r));else return e;return i&&n?.$&&(n.$.convertedRuntimeType=i),i??e}function ls(e,t=new Set){let n=e.label;e.isQuote?n=`quote(${n})`:e.isImplicit||e.isCompileTimeOnly&&(n=`comptime(${n})`);let r=A(e.type,t),i=e.exprs.defaultValueExpr?w(e.exprs.defaultValueExpr):"";return n===""?r:i?`(${n} : ${r}) ?= ${i}`:`${n} : ${r}`}function Ri(e,t=new Set){let n=e.label;ir(n)&&(n=`(${n})`);let r=e.defaultValue?Me(e.defaultValue):"",i=e.assignedValue?Me(e.assignedValue):"";return r?`(${n}: ${A(e.type,t)}) ?= ${r}`:i?`(${n}: ${A(e.type,t)}) = ${i}`:`${n}: ${A(e.type,t)}`}function eu(e,t=new Set){let n=e.label;ir(n)&&(n=`(${n})`);let r=e.defaultValue?Me(e.defaultValue):"",i=e.assignedValue?Me(e.assignedValue):"";return r?`(${n} : ${A(e.type,t)}) ?= ${r}`:i?`(${n} : ${A(e.type,t)}) = ${i}`:`${n} : ${A(e.type,t)}`}function tu(e,t=new Set){let n=e.parameters.map(_=>ls(_,t)).join(", "),r=e.forallParameters.length>0?`forall(${e.forallParameters.map(_=>ls(_,t)).join(", ")})`:"",i="";e.variadicParameter&&(e.variadicParameter.label==="..."?i="...":e.variadicParameter.isQuote?i=`...(quote(${e.variadicParameter.label}))`:e.variadicParameter.isCompileTimeOnly?i=`...(comptime(${e.variadicParameter.label}))`:i=`...(${e.variadicParameter.label})`);let o=A(e.return.type,t),a=o;e.return.isUnquote?e.return.label?a=`(unquote(${e.return.label}) : ${o})`:a=`unquote(${o})`:e.return.isCompileTimeOnly&&(e.return.label?a=`(comptime(${e.return.label}) : ${o})`:a=`comptime(${o})`);let s=e.implicitParameters.length>0?`using(${e.implicitParameters.map(_=>_.isEffectRowSpread?`...(${_.label})`:ls(_,t)).join(", ")})`:"",l=[r,n,s,i].filter(_=>!!_).join(", "),u=e.SelfType?.typeName;return`${u?`(${u}) `:""}fn(${l}) -> ${a}`}function A(e,t=new Set){if(e.id&&t.has(e.id))return e.typeName||`<circular:${e.tag}>`;e.id&&t.add(e.id);try{return vm(e,t)}finally{e.id&&t.delete(e.id)}}function vm(e,t){if(!e)return"unknown";switch(e.tag){case"unit":return"unit";case"bool":return"bool";case"usize":return"usize";case"isize":return"isize";case"u8":return"u8";case"i8":return"i8";case"u16":return"u16";case"i16":return"i16";case"u32":return"u32";case"i32":return"i32";case"u64":return"u64";case"i64":return"i64";case"f32":return"f32";case"f64":return"f64";case"Type":return"level"in e&&typeof e.level=="number"&&e.level>0?`Type(${e.level})`:"Type";case"Array":return`[${A(e.childType,t)}; ${Me(e.length)}]`;case"Slice":return`[${A(e.childType,t)}]`;case"Tuple":return e.fields.length===0?"()":`(${e.fields.map(n=>Ri(n,t)).join(", ")}${e.fields.length===1?",":""})`;case"Struct":{let n=e;return n.typeName?n.typeName:`${n.typeName?`(${n.typeName}) `:""}${n.isReferenceSemantics?"object":n.isNewtype?"newtype":"struct"}(${n.fields.map(r=>Ri(r,t)).join(", ")})`}case"Enum":{let n=e;if(n.typeName){let r=n.typeName;return n.requiredVariantNames??n.selectedVariantName?`${r} (${n.requiredVariantNames?`${n.requiredVariantNames.map(i=>`.${i}`).join(" | ")} required`:`.${n.selectedVariantName} selected`})`:r}return`${n.typeName?`(${n.typeName}) `:""}enum(${n.variants.map(r=>`${r.name}${r.fields?`(${r.fields.map(i=>Ri(i,t)).join(", ")})`:""}`).join(", ")})`}case"Union":{let n=e;if(n.typeName)return n.typeName;let r=n.fields;return`${n.typeName?`(${n.typeName}) `:""}${n.typeName?"union":n.id}(${r.map(i=>Ri(i,t)).join(", ")})`}case"Module":{let n=e,r;return n.typeName?r=n.typeName:r=`${n.typeName?`(${n.typeName}) `:""}module(${n.fields.map(i=>eu(i,t)).join(", ")})`,r}case"Trait":{let n=e;if(bt(n))return`Fn${tu(n.isFn.callType,t).slice(2)}`;if(Kt(n)){let i=[A(n.isFuture.outputType,t)];for(let o of n.isFuture.effects)o.isEffectRowSpread?i.push(`...(${o.label})`):i.push(A(o.type,t));return`Future(${i.join(", ")})`}let r;return n.typeName?r=n.typeName:r=`${n.typeName?`(${n.typeName}) `:""}trait(${n.fields.map(i=>eu(i,t)).join(", ")})`,n.receiverType&&(r=`(${A(n.receiverType,t)} <: ${r})`),r}case"Function":{let n=e;return n.typeName?n.typeName:tu(n,t)}case"SomeType":{let n=e;if(n.typeName)return n.typeName;if(n.functionApplication)return w(n.functionApplication);let r=[];if(n.requiredTraits&&n.requiredTraits.length>0)for(let i of n.requiredTraits)r.push(A(i.traitType,t));if(n.negativeTraits&&n.negativeTraits.length>0)for(let i of n.negativeTraits)r.push(`!(${A(i.traitType,t)})`);return r.length>0?`${n.name||"Impl"}(${r.join(", ")})`:n.name||"Impl()"}case"Ptr":return`*(${A(e.childType,t)})`;case"Iso":return`Iso(${A(e.childType,t)})`;case"Arc":return`Arc(${A(e.childType,t)})`;case"Expr":return"Expr";case"ComptimeList":return`ComptimeList(${A(e.childType)})`;case"EffectsRow":{let n=e;return n.implicitParameters.length===0?"EffectsRow()":`EffectsRow(${n.implicitParameters.map(r=>`${r.label} : ${A(r.type,t)}`).join(", ")})`}case"Dyn":{let n=e;if(n.typeName)return n.typeName;let r=[];for(let{traitType:i}of n.requiredTraits)r.push(A(i,t));if(n.negativeTraits&&n.negativeTraits.length>0)for(let{traitType:i}of n.negativeTraits)r.push(`!(${A(i,t)})`);return`Dyn(${r.join(", ")})`}default:return`${e.tag}`}}var nu=64;function br(){return nu}function da(){return nu/8}function Tm(e){let t=Ur(e.childType);if(t===null)return null;if(t===-1)return-1;let n=e.length;if(ze(n)){let r=BigInt(n.value);if(r<0)throw new Error("Array length cannot be negative");return Number(r)*t}return null}function Em(e){let t=0,n=1;for(let r of e.fields){let i=Ur(r.type);if(i===null)return null;if(i===-1)return-1;let o=Kn(r.type);if(o===null)return null;let a=Math.ceil(i/8);t=Math.ceil(t/o)*o,t+=a,n=Math.max(n,o)}return t=Math.ceil(t/n)*n,t*8}function $m(e){let t=0,n=1;for(let r of e.fields){let i=Ur(r.type);if(i===null)return null;if(i===-1)return-1;let o=Kn(r.type);if(o===null)return null;let a=Math.ceil(i/8);t=Math.ceil(t/o)*o,t+=a,n=Math.max(n,o)}return t=Math.ceil(t/n)*n,t*8}function Cm(e){let t=0,n=0;for(let m of e.variants){let g=0,h=1;if(m.fields)for(let v of m.fields){let T=Ur(v.type);if(T===null)return null;if(T===-1)return-1;let $=Kn(v.type);if($===null)return null;let C=Math.ceil(T/8);g=Math.ceil(g/$)*$,g+=C,h=Math.max(h,$),n=Math.max(n,$*8)}g=Math.ceil(g/h)*h;let d=g*8;t=Math.max(t,d)}let r=Math.ceil(Math.ceil(Math.log2(e.variants.length))/8)*8,i=32,o=Math.max(n,8),a=Math.max(i,o),s=r/8,l=o/8,u=(l-s%l)%l*8,c=r+u+t,_=c/8,p=a/8,f=(p-_%p)%p*8;return c+f}function bm(e){let t=0;for(let n of e.fields){let r=Ur(n.type);if(r===null)return null;if(r===-1)return-1;t=Math.max(t,r)}return t}function Kn(e){if(x(e))return null;if(pe(e)||He(e)||vt(e)||Nt(e)||Et(e)||Vt(e)||Te(e)||De(e)||Lt(e))return 1;if(cn(e))return 1;if(ho(e)||vo(e))return da();if(Hn(e)||To(e))return 1;if(Eo(e)||$o(e))return 2;if(Co(e)||bo(e))return 4;if(ko(e)||wo(e))return 8;if(Fo(e))return 4;if(Lo(e))return 8;if(ke(e))return Kn(e.childType);if(we(e)){let t=1;for(let n of e.fields){let r=Kn(n.type);if(r===null)return null;t=Math.max(t,r)}return t}else if(ce(e)){if(e.isReferenceSemantics)return da();if(e.isNewtype)return Kn(e.fields[0].type);let t=1;for(let n of e.fields){let r=Kn(n.type);if(r===null)return null;t=Math.max(t,r)}return t}else if(ge(e)){let t=1;for(let n of e.variants)if(n.fields)for(let r of n.fields){let i=Kn(r.type);if(i===null)return null;t=Math.max(t,i)}return t}else if(it(e)){let t=1;for(let n of e.fields){let r=Kn(n.type);if(r===null)return null;t=Math.max(t,r)}return t}else{if(G(e))return da();if(Ie(e))return da()}return null}function Ur(e){return x(e)?null:pe(e)||He(e)||vt(e)||Nt(e)||Et(e)||Vt(e)||Te(e)||De(e)||Lt(e)?0:cn(e)?8:ho(e)||vo(e)?br():Hn(e)||To(e)?8:Eo(e)||$o(e)?16:Co(e)||bo(e)?32:ko(e)||wo(e)?64:Fo(e)?32:Lo(e)?64:ke(e)?Tm(e):we(e)?Em(e):ce(e)?e.isReferenceSemantics?br():e.isNewtype?Ur(e.fields[0].type):$m(e):ge(e)?Cm(e):it(e)?bm(e):G(e)||Ie(e)?br():null}function kr(e,t){if($r(e))throw lt([{token:t,errorMessage:`Cannot use 'void' type here.
43
+ `);return n[0]}function go(e){return e.tag==="unit"||e.tag==="bool"||e.tag==="usize"||e.tag==="isize"||e.tag==="u8"||e.tag==="i8"||e.tag==="u16"||e.tag==="i16"||e.tag==="u32"||e.tag==="i32"||e.tag==="u64"||e.tag==="i64"||e.tag==="f32"||e.tag==="f64"||e.tag==="char"||e.tag==="short"||e.tag==="ushort"||e.tag==="int"||e.tag==="uint"||e.tag==="long"||e.tag==="ulong"||e.tag==="longlong"||e.tag==="ulonglong"||e.tag==="longdouble"}function pe(e){return e?.tag==="unit"}function vt(e){return e?.tag==="comptime_int"}function Nt(e){return e?.tag==="comptime_float"}function Et(e){return e?.tag==="comptime_string"}function Vt(e){return e?.tag==="ComptimeList"}function Zr(e){return Vt(e)&&Lt(e.childType)}function cn(e){return e?.tag==="bool"}function ho(e){return e?.tag==="usize"}function vo(e){return e?.tag==="isize"}function Hn(e){return e?.tag==="u8"}function To(e){return e?.tag==="i8"}function Eo(e){return e?.tag==="u16"}function $o(e){return e?.tag==="i16"}function Co(e){return e?.tag==="u32"}function bo(e){return e?.tag==="i32"}function ko(e){return e?.tag==="u64"}function wo(e){return e?.tag==="i64"}function Fo(e){return e?.tag==="f32"}function Lo(e){return e?.tag==="f64"}function Lt(e){return e?.tag==="Expr"}function ke(e){return e?.tag==="Array"}function Qe(e){return e?.tag==="Slice"}function we(e){return e?.tag==="Tuple"}function it(e){return e?.tag==="Union"}function ge(e){return e?.tag==="Enum"}function ce(e){return e?.tag==="Struct"}function pt(e){return e?.tag==="Struct"&&e.isReferenceSemantics}function Er(e){return e?.tag==="Struct"&&e.isNewtype}function Te(e){return e?.tag==="Module"}function De(e){return e?.tag==="Trait"}function kt(e){return De(e)&&e.isFn!==void 0}function G(e){return e?.tag==="Function"}function Ao(e){return e?.tag==="Function"&&e.return.isCompileTimeOnly}function He(e){return e?.tag==="Type"}function Xl(e){return He(e)&&e.tag==="Type"&&e.level===0}function x(e){return e?.tag==="SomeType"}function Ie(e){return e?.tag==="Ptr"}function wt(e){return e?.tag==="Iso"}function Ct(e){return e?.tag==="Arc"}function be(e){return e?.tag==="Dyn"}function sn(e){if(x(e)){let t=e;if(Ce(t))return!0;if(t.resolvedConcreteType)return sn(t.resolvedConcreteType)}return pt(e)||be(e)||wt(e)||Ct(e)}function or(e){return e?.tag==="u8"||e?.tag==="i8"||e?.tag==="u16"||e?.tag==="i16"||e?.tag==="u32"||e?.tag==="i32"||e?.tag==="u64"||e?.tag==="i64"||e?.tag==="usize"||e?.tag==="isize"}function ar(e){return e?.tag==="f32"||e?.tag==="f64"}function Ql(e){return e?.tag==="i8"||e?.tag==="i16"||e?.tag==="i32"||e?.tag==="i64"||e?.tag==="isize"}function ki(e){return e?.tag==="char"}function $r(e){return e?.tag==="void"}function Kt(e){return De(e)&&e.isFuture!==void 0}function oa(e){return De(e)&&e.isConcrete!==void 0}function jn(e){return!!e&&(e.tag==="char"||e.tag==="short"||e.tag==="ushort"||e.tag==="int"||e.tag==="uint"||e.tag==="long"||e.tag==="ulong"||e.tag==="longlong"||e.tag==="ulonglong"||e.tag==="longdouble")}function Pn(e){if(!e||e.return?.isCompileTimeOnly)return!1;let t=e.parameters.some(r=>r.isCompileTimeOnly)||e.forallParameters.length>0||e.implicitParameters.length>0,n=e.parameters.some(r=>!r.isCompileTimeOnly&&x(r.type)&&!Ce(r.type));return t||n}function sr(e){if(!e||e.return?.isCompileTimeOnly)return!1;let t=e.parameters.some(r=>r.isCompileTimeOnly)||e.forallParameters.length>0,n=e.parameters.some(r=>!r.isCompileTimeOnly&&x(r.type)&&!Ce(r.type));return t||n}function as(e){let t=e.type;return t?Pn(t)&&(e.specializedFunctionCaches?.length??0)>0:!1}function $n(e){return pt(e)?e.fields.length===1&&e.fields[0].label==="*"&&!!e.typeName?.startsWith("Box("):!1}function ot(e){return e?.tag==="EffectsRow"}function aa(e,t,n){let r=!1,i=0;for(let o of t){let a=o.type;if(n.includes(o))throw y({token:n[n.length-1].exprs.expr.token,errorMessage:`Recursive type has infinite size in field "${n[n.length-1].label}"
44
+ Insert some indirection (e.g., a pointer '*' or reference '&') to break the cycle.`});if(pt(a))continue;let s=[...n,o],l=Ft(a,s);He(l)&&(i=Math.max(i,l.level),l.tag==="Type"&&(r=!0))}return i>0?gn(i):r?tt(e):tt(e)}function Ft(e,t=[]){if(be(e))return tt(e);if(go(e))return tt(e);if(He(e))return gn(e.level+1);if(vt(e)||Nt(e)||Et(e)||Vt(e))return tt(e);if(Lt(e))return tt(e);if(G(e))return tt(e);if(kt(e))return tt(e);if(ke(e))return Ft(e.childType,t);if(Qe(e))return tt(e);if(we(e))return aa(e,e.fields,t);if(ce(e))return aa(e,e.fields,t);if(ge(e)){let n=[];for(let r of e.variants)r.fields&&n.push(...r.fields);return aa(e,n,t)}else{if(it(e))return aa(e,e.fields,t);if(Te(e))return gn(1,e);if(De(e))return gn(1,e);if(x(e))return e.parentType;if(Ie(e))return tt(e);if(wt(e))return tt(e);if(Ct(e))return tt(e);if(Kt(e))return tt(e);if($r(e))return tt(e);if(ot(e))return gn(1);throw new Error(`Unknown type tag: ${e.tag}`)}}function Zl(e){if(e.exprs.labelExpr?.token)return e.exprs.labelExpr.token;if(e.exprs.typeExpr?.token)return e.exprs.typeExpr.token;if(e.exprs.defaultValueExpr?.token)return e.exprs.defaultValueExpr.token;throw new Error("Cannot get token for function parameter")}function Me(e){if(!e)return"<runtime value>";switch(e.tag){case"Type":return A(e.value);case"ComptimeInt":case"ComptimeFloat":return e.value.toString();case"ComptimeString":return JSON.stringify(e.value);case"ComptimeList":return`comptime_list(${e.elements.map(Me).join(", ")})`;case"U8":case"I8":case"U16":case"I16":case"U32":case"I32":case"U64":case"I64":case"F32":case"F64":case"Usize":case"Isize":return typeof e.value=="bigint",e.value.toString();case"Bool":return e.value.toString();case"Array":return`[${e.elements.map(Me).join(", ")}${e.elements.length===1?",":""}]`;case"Slice":return`slice[${e.sourceArray[0].elements.slice(e.startIndex,e.endIndex).map(Me).join(", ")}]`;case"Tuple":return e.fields.length===0?"()":`(${e.fields.map(Me).join(", ")}${e.fields.length===1?",":""})`;case"Struct":return`${e.type.typeName??"_"}(${e.fields.map((t,n)=>{let r=e.type.fields[n].label;return ir(r)&&(r=`(${r})`),`${r}: ${Me(t)}`}).join(", ")})`;case"Enum":{if(e.fields.length===0)return`.${e.variantName}`;let t=e.type.variants.find(n=>n.name===e.variantName);return`.${e.variantName}(${e.fields.map((n,r)=>{let i=t?.fields[r].label??"_";return ir(i)&&(i=`(${i})`),`${i}: ${Me(n)}`}).join(", ")})`}case"Function":return e.funcName?`<fn ${e.funcName}>`:e.type.typeName?`<fn ${e.type.typeName}>`:"<fn>";case"Module":return`${e.type.typeName??"_"}(${e.fields.map((t,n)=>{let r=e.type.fields[n].label;return ir(r)&&(r=`(${r})`),`${r}: ${Me(t)}`}).join(", ")})`;case"Trait":return`${e.type.typeName??"_"}(${e.fields.map((t,n)=>{let r=e.type.fields[n].label;return ir(r)&&(r=`(${r})`),`${r}: ${Me(t)}`}).join(", ")})`;case"Unit":return"()";case"Expr":return`quote(${w(e.value)})`;case"Unknown":return e.variableName?e.variableName:`<comptime ${A(e.type)}>`;case"Ptr":{let t=e.targetValue[0];return Un(t)?`<ptr to ${Me(t.elements[e.targetIndex])}>`:`<ptr to ${Me(t)}>`}default:throw new Error("valueToString: Unsupported value")}}function O(e){return e?.tag==="Type"}function An(e){return e?.tag==="ComptimeInt"}function la(e){return e?.tag==="ComptimeFloat"}function Ve(e){return e?.tag==="ComptimeString"}function lr(e){return e?.tag==="ComptimeList"}function Jl(e){return lr(e)&&Lt(e.type.childType)}function ze(e){return e?.tag==="ComptimeInt"||e?.tag==="ComptimeFloat"||e?.tag==="U8"||e?.tag==="I8"||e?.tag==="U16"||e?.tag==="I16"||e?.tag==="U32"||e?.tag==="I32"||e?.tag==="U64"||e?.tag==="I64"||e?.tag==="F32"||e?.tag==="F64"||e?.tag==="Usize"||e?.tag==="Isize"}function Re(e){return e?.tag==="Bool"}function ne(e){return e?.tag==="Function"}function de(e){return e?.tag==="Unknown"}function hn(e){return e?.tag==="Tuple"}function Cn(e){return e?.tag==="Struct"}function Un(e){return e?.tag==="Array"}function sa(e){return e?.tag==="Slice"}function It(e){return e?.tag==="Enum"}function We(e){return e?.tag==="Module"}function Tt(e){return e?.tag==="Trait"}function wi(e){return e?.tag==="Ptr"}function ln(e){return e?.tag==="Expr"}function ee(e){return{tag:"Type",type:Ft(e),value:e}}function on(e){return{tag:"ComptimeString",type:xt(),value:e}}function zn(e,t){return{tag:"ComptimeList",type:Io(e),elements:t}}function Xt(e,t){let n;if(e==="ComptimeInt")n=Or();else if(e==="ComptimeFloat")n=Li();else if(e==="U8")n=Ii();else if(e==="I8")n=Si();else if(e==="U16")n=Ni();else if(e==="I16")n=Vi();else if(e==="U32")n=xi();else if(e==="I32")n=Rr();else if(e==="U64")n=Di();else if(e==="I64")n=Mi();else if(e==="F32")n=Oi();else if(e==="F64")n=Pr();else if(e==="Usize")n=gt();else if(e==="Isize")n=Ai();else throw new Error(`createNumberValue: Unsupported tag: ${e}`);return{tag:e,type:n,value:t}}function ur(e){return Xt("ComptimeInt",e)}function ua(e){return Xt("ComptimeFloat",e)}function ft(e){return{tag:"Bool",type:Je(),value:e}}function K(e,{variableName:t,recursiveTypeRef:n,env:r,context:i}){if(He(e)&&e.level===0){if(!t)throw console.trace("!variableName bug found in createUnknownValue"),new Error(`createUnknownValue expects a variable name for type ${A(e)}`);let o=bn(e,t,{recursiveTypeRef:n,env:r,context:i});return ee(o)}return{tag:"Unknown",type:e,variableName:t}}function Bn(e,t){return{tag:"Struct",type:e,fields:t}}function ca(e,t){return{tag:"Module",type:e,fields:t}}function Fi(e,t){return{tag:"Trait",type:e,fields:t}}function _a(e,t){return{tag:"Tuple",type:e,fields:t}}function Jr(e,t,n){return{tag:"Enum",type:e,variantName:t,fields:n}}function Mr(e,t){return{tag:"Array",type:e,elements:t}}function pa(e,t,n,r){return{tag:"Slice",type:e,sourceArray:t,startIndex:n,endIndex:r}}function Gn(e){return{tag:"Expr",type:_n(),value:e}}function ss(e,t,n=0){return{tag:"Ptr",type:e,targetValue:t,targetIndex:n}}function At(e,t){let n=e.value,r=t.value;if(n===r)return!0;if(!n||!r)return!1;if(n.tag==="Type"&&r.tag==="Type")return Y({type:n.value,env:e.env},{type:r.value,env:t.env},!0);if(Ve(n)&&Ve(r))return n.value===r.value;if(lr(n)&&lr(r)){if(n.elements.length!==r.elements.length)return!1;for(let i=0;i<n.elements.length;i++)if(!At({value:n.elements[i],env:e.env},{value:r.elements[i],env:t.env}))return!1;return!0}else if(ze(n)&&ze(r)){let i=n.value,o=r.value;if(typeof i==typeof o)return i===o;let a=typeof i=="bigint"?i:BigInt(i),s=typeof o=="bigint"?o:BigInt(o);return a===s}else{if(Re(n)&&Re(r))return n.value===r.value;if(Un(n)&&Un(r)){if(n.elements.length!==r.elements.length)return!1;for(let i=0;i<n.elements.length;i++)if(!At({value:n.elements[i],env:e.env},{value:r.elements[i],env:t.env}))return!1;return!0}else if(sa(n)&&sa(r)){let i=n.endIndex-n.startIndex,o=r.endIndex-r.startIndex;if(i!==o)return!1;for(let a=0;a<i;a++){let s=n.sourceArray[0].elements[n.startIndex+a],l=r.sourceArray[0].elements[r.startIndex+a];if(!At({value:s,env:e.env},{value:l,env:t.env}))return!1}return!0}else if(hn(n)&&hn(r)){if(n.fields.length!==r.fields.length)return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(Cn(n)&&Cn(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0))return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(It(n)&&It(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0)||n.variantName!==r.variantName)return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(We(n)&&We(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0))return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else if(Tt(n)&&Tt(r)){if(n.fields.length!==r.fields.length||!Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0))return!1;for(let i=0;i<n.fields.length;i++)if(!At({value:n.fields[i],env:e.env},{value:r.fields[i],env:t.env}))return!1;return!0}else{if(ln(n)&&ln(r))return n.value===r.value||fa(n.value,r.value);if(de(n)&&de(r)){let i,o;if(n.variableName){let a=X(e.env,n.variableName);if(a.length>0){let s=a[a.length-1];s.value&&!de(s.value[0])&&(i=s.value[0])}}if(r.variableName){let a=X(t.env,r.variableName);if(a.length>0){let s=a[a.length-1];s.value&&!de(s.value[0])&&(o=s.value[0])}}return i&&o?At({value:i,env:e.env},{value:o,env:t.env}):i||o?!1:Y({type:n.type,env:e.env},{type:r.type,env:t.env},!0)}else if(de(n)&&!de(r)){if(n.variableName){let i=X(e.env,n.variableName);if(i.length>0){let o=i[i.length-1];if(o.value&&!de(o.value[0]))return At({value:o.value[0],env:e.env},{value:r,env:t.env})}}return!1}else if(!de(n)&&de(r)){if(r.variableName){let i=X(t.env,r.variableName);if(i.length>0){let o=i[i.length-1];if(o.value&&!de(o.value[0]))return At({value:n,env:e.env},{value:o.value[0],env:t.env})}}return!1}else return wi(n)&&wi(r)?n.targetValue===r.targetValue&&n.targetIndex===r.targetIndex:!1}}}function _r(e,t){return e?ti(e,t):!1}function pr(e,t){return e?vm(e,t):!1}function ti(e,t){return Xn(e,t)&&!Fr(e,t)}function vm(e,t){let n=Xn(e,t),r=Fr(e,t);return!n&&r}function Le(e,t=[]){if(!e||t.includes(e)||(t.push(e),e.isExtern))return!1;if(sn(e))return!0;switch(e.tag){case"Array":return Le(e.childType,t);case"Tuple":return e.fields.some(n=>Le(n.type,t));case"Union":return e.fields.some(n=>Le(n.type,t));case"Struct":return e.fields.some(n=>Le(n.type,t));case"Enum":return e.variants.some(n=>n.fields?.some(r=>Le(r.type,t)));case"Iso":return Le(e.childType,t);case"Arc":return Le(e.childType,t);case"Module":return!1;case"Function":return!1;case"SomeType":{let n=e;return Ce(n)?!0:n.resolvedConcreteType?Le(n.resolvedConcreteType,t):!0}default:return!1}}function Fe(e,t=[]){if(!e||t.includes(e))return!1;if(t.push(e),x(e))return e.isExtern?!1:e.resolvedConcreteType?Fe(e.resolvedConcreteType,t):!(Wt(e)||Ce(e));switch(e.tag){case"Array":return Fe(e.childType,t);case"Tuple":return e.fields.some(n=>Fe(n.type,t));case"Struct":return e.fields.some(n=>!n.isEffectParam&&Fe(n.type,t));case"Enum":return e.variants.some(n=>n.fields?.some(r=>Fe(r.type,t)));case"Union":return e.fields.some(n=>Fe(n.type,t));case"Function":{let n=e;return n.forallParameters.length>0||n.parameters.some(r=>Fe(r.type,t))||Fe(n.return.type,t)}case"Module":return e.fields.some(n=>Fe(n.type,t));case"Ptr":return Fe(e.childType,t);default:return!1}}function Cr(e,t=new Set){return t.has(e.id)?!1:(t.add(e.id),ke(e)?de(e.length)?!0:Cr(e.childType,t):Ie(e)||Qe(e)?Cr(e.childType,t):we(e)?e.fields.some(n=>Cr(n.type,t)):ce(e)?e.fields.some(n=>Cr(n.type,t)):ge(e)?e.variants.some(n=>n.fields?.some(r=>Cr(r.type,t))):it(e)?e.fields.some(n=>Cr(n.type,t)):!1)}function us(e){let t=new Set,n=new Set;function r(i){if(!(i&&n.has(i))){if(i&&n.add(i),x(i)){if(t.has(i))return;i.resolvedConcreteType||t.add(i)}switch(i.tag){case"Array":r(i.childType);break;case"Tuple":i.fields.forEach(o=>r(o.type));break;case"Struct":i.fields.forEach(o=>r(o.type));break;case"Enum":i.variants.forEach(o=>{o.fields?.forEach(a=>r(a.type))});break;case"Union":i.fields.forEach(o=>r(o.type));break;case"Module":i.fields.forEach(o=>r(o.type));break;case"Ptr":r(i.childType);break;default:break}}}return r(e),t}function Pi(e){if(!e)return!1;switch(e.tag){case"Array":{let t=e;return de(t.length)||Pi(t.childType)}case"SomeType":return!0;case"Module":return!1;case"Trait":{let t=e;return t.isFn?Pi(t.isFn.callType):!1}default:return!1}}function yt({type:e,expectedType:t,expr:n,env:r}){let i;if(vt(e))i=Rr();else if(Nt(e))i=Pr();else if(Et(e))t&&(Ie(t)&&(Hn(t.childType)||ki(t.childType))||Qe(t))&&(i=t),i||(i=ru(r));else return e;return i&&n?.$&&(n.$.convertedRuntimeType=i),i??e}function ls(e,t=new Set){let n=e.label;e.isQuote?n=`quote(${n})`:e.isImplicit||e.isCompileTimeOnly&&(n=`comptime(${n})`);let r=A(e.type,t),i=e.exprs.defaultValueExpr?w(e.exprs.defaultValueExpr):"";return n===""?r:i?`(${n} : ${r}) ?= ${i}`:`${n} : ${r}`}function Ri(e,t=new Set){let n=e.label;ir(n)&&(n=`(${n})`);let r=e.defaultValue?Me(e.defaultValue):"",i=e.assignedValue?Me(e.assignedValue):"";return r?`(${n}: ${A(e.type,t)}) ?= ${r}`:i?`(${n}: ${A(e.type,t)}) = ${i}`:`${n}: ${A(e.type,t)}`}function eu(e,t=new Set){let n=e.label;ir(n)&&(n=`(${n})`);let r=e.defaultValue?Me(e.defaultValue):"",i=e.assignedValue?Me(e.assignedValue):"";return r?`(${n} : ${A(e.type,t)}) ?= ${r}`:i?`(${n} : ${A(e.type,t)}) = ${i}`:`${n} : ${A(e.type,t)}`}function tu(e,t=new Set){let n=e.parameters.map(_=>ls(_,t)).join(", "),r=e.forallParameters.length>0?`forall(${e.forallParameters.map(_=>ls(_,t)).join(", ")})`:"",i="";e.variadicParameter&&(e.variadicParameter.label==="..."?i="...":e.variadicParameter.isQuote?i=`...(quote(${e.variadicParameter.label}))`:e.variadicParameter.isCompileTimeOnly?i=`...(comptime(${e.variadicParameter.label}))`:i=`...(${e.variadicParameter.label})`);let o=A(e.return.type,t),a=o;e.return.isUnquote?e.return.label?a=`(unquote(${e.return.label}) : ${o})`:a=`unquote(${o})`:e.return.isCompileTimeOnly&&(e.return.label?a=`(comptime(${e.return.label}) : ${o})`:a=`comptime(${o})`);let s=e.implicitParameters.length>0?`using(${e.implicitParameters.map(_=>_.isEffectRowSpread?`...(${_.label})`:ls(_,t)).join(", ")})`:"",l=[r,n,s,i].filter(_=>!!_).join(", "),u=e.SelfType?.typeName;return`${u?`(${u}) `:""}fn(${l}) -> ${a}`}function A(e,t=new Set){if(e.id&&t.has(e.id))return e.typeName||`<circular:${e.tag}>`;e.id&&t.add(e.id);try{return Tm(e,t)}finally{e.id&&t.delete(e.id)}}function Tm(e,t){if(!e)return"unknown";switch(e.tag){case"unit":return"unit";case"bool":return"bool";case"usize":return"usize";case"isize":return"isize";case"u8":return"u8";case"i8":return"i8";case"u16":return"u16";case"i16":return"i16";case"u32":return"u32";case"i32":return"i32";case"u64":return"u64";case"i64":return"i64";case"f32":return"f32";case"f64":return"f64";case"Type":return"level"in e&&typeof e.level=="number"&&e.level>0?`Type(${e.level})`:"Type";case"Array":return`[${A(e.childType,t)}; ${Me(e.length)}]`;case"Slice":return`[${A(e.childType,t)}]`;case"Tuple":return e.fields.length===0?"()":`(${e.fields.map(n=>Ri(n,t)).join(", ")}${e.fields.length===1?",":""})`;case"Struct":{let n=e;return n.typeName?n.typeName:`${n.typeName?`(${n.typeName}) `:""}${n.isReferenceSemantics?"object":n.isNewtype?"newtype":"struct"}(${n.fields.map(r=>Ri(r,t)).join(", ")})`}case"Enum":{let n=e;if(n.typeName){let r=n.typeName;return n.requiredVariantNames??n.selectedVariantName?`${r} (${n.requiredVariantNames?`${n.requiredVariantNames.map(i=>`.${i}`).join(" | ")} required`:`.${n.selectedVariantName} selected`})`:r}return`${n.typeName?`(${n.typeName}) `:""}enum(${n.variants.map(r=>`${r.name}${r.fields?`(${r.fields.map(i=>Ri(i,t)).join(", ")})`:""}`).join(", ")})`}case"Union":{let n=e;if(n.typeName)return n.typeName;let r=n.fields;return`${n.typeName?`(${n.typeName}) `:""}${n.typeName?"union":n.id}(${r.map(i=>Ri(i,t)).join(", ")})`}case"Module":{let n=e,r;return n.typeName?r=n.typeName:r=`${n.typeName?`(${n.typeName}) `:""}module(${n.fields.map(i=>eu(i,t)).join(", ")})`,r}case"Trait":{let n=e;if(kt(n))return`Fn${tu(n.isFn.callType,t).slice(2)}`;if(Kt(n)){let i=[A(n.isFuture.outputType,t)];for(let o of n.isFuture.effects)o.isEffectRowSpread?i.push(`...(${o.label})`):i.push(A(o.type,t));return`Future(${i.join(", ")})`}let r;return n.typeName?r=n.typeName:r=`${n.typeName?`(${n.typeName}) `:""}trait(${n.fields.map(i=>eu(i,t)).join(", ")})`,n.receiverType&&(r=`(${A(n.receiverType,t)} <: ${r})`),r}case"Function":{let n=e;return n.typeName?n.typeName:tu(n,t)}case"SomeType":{let n=e;if(n.typeName)return n.typeName;if(n.functionApplication)return w(n.functionApplication);let r=[];if(n.requiredTraits&&n.requiredTraits.length>0)for(let i of n.requiredTraits)r.push(A(i.traitType,t));if(n.negativeTraits&&n.negativeTraits.length>0)for(let i of n.negativeTraits)r.push(`!(${A(i.traitType,t)})`);return r.length>0?`${n.name||"Impl"}(${r.join(", ")})`:n.name||"Impl()"}case"Ptr":return`*(${A(e.childType,t)})`;case"Iso":return`Iso(${A(e.childType,t)})`;case"Arc":return`Arc(${A(e.childType,t)})`;case"Expr":return"Expr";case"ComptimeList":return`ComptimeList(${A(e.childType)})`;case"EffectsRow":{let n=e;return n.implicitParameters.length===0?"EffectsRow()":`EffectsRow(${n.implicitParameters.map(r=>`${r.label} : ${A(r.type,t)}`).join(", ")})`}case"Dyn":{let n=e;if(n.typeName)return n.typeName;let r=[];for(let{traitType:i}of n.requiredTraits)r.push(A(i,t));if(n.negativeTraits&&n.negativeTraits.length>0)for(let{traitType:i}of n.negativeTraits)r.push(`!(${A(i,t)})`);return`Dyn(${r.join(", ")})`}default:return`${e.tag}`}}var nu=64;function br(){return nu}function da(){return nu/8}function Em(e){let t=Ur(e.childType);if(t===null)return null;if(t===-1)return-1;let n=e.length;if(ze(n)){let r=BigInt(n.value);if(r<0)throw new Error("Array length cannot be negative");return Number(r)*t}return null}function $m(e){let t=0,n=1;for(let r of e.fields){let i=Ur(r.type);if(i===null)return null;if(i===-1)return-1;let o=Kn(r.type);if(o===null)return null;let a=Math.ceil(i/8);t=Math.ceil(t/o)*o,t+=a,n=Math.max(n,o)}return t=Math.ceil(t/n)*n,t*8}function Cm(e){let t=0,n=1;for(let r of e.fields){let i=Ur(r.type);if(i===null)return null;if(i===-1)return-1;let o=Kn(r.type);if(o===null)return null;let a=Math.ceil(i/8);t=Math.ceil(t/o)*o,t+=a,n=Math.max(n,o)}return t=Math.ceil(t/n)*n,t*8}function bm(e){let t=0,n=0;for(let m of e.variants){let g=0,h=1;if(m.fields)for(let v of m.fields){let T=Ur(v.type);if(T===null)return null;if(T===-1)return-1;let $=Kn(v.type);if($===null)return null;let C=Math.ceil(T/8);g=Math.ceil(g/$)*$,g+=C,h=Math.max(h,$),n=Math.max(n,$*8)}g=Math.ceil(g/h)*h;let d=g*8;t=Math.max(t,d)}let r=Math.ceil(Math.ceil(Math.log2(e.variants.length))/8)*8,i=32,o=Math.max(n,8),a=Math.max(i,o),s=r/8,l=o/8,u=(l-s%l)%l*8,c=r+u+t,_=c/8,p=a/8,f=(p-_%p)%p*8;return c+f}function km(e){let t=0;for(let n of e.fields){let r=Ur(n.type);if(r===null)return null;if(r===-1)return-1;t=Math.max(t,r)}return t}function Kn(e){if(x(e))return null;if(pe(e)||He(e)||vt(e)||Nt(e)||Et(e)||Vt(e)||Te(e)||De(e)||Lt(e))return 1;if(cn(e))return 1;if(ho(e)||vo(e))return da();if(Hn(e)||To(e))return 1;if(Eo(e)||$o(e))return 2;if(Co(e)||bo(e))return 4;if(ko(e)||wo(e))return 8;if(Fo(e))return 4;if(Lo(e))return 8;if(ke(e))return Kn(e.childType);if(we(e)){let t=1;for(let n of e.fields){let r=Kn(n.type);if(r===null)return null;t=Math.max(t,r)}return t}else if(ce(e)){if(e.isReferenceSemantics)return da();if(e.isNewtype)return Kn(e.fields[0].type);let t=1;for(let n of e.fields){let r=Kn(n.type);if(r===null)return null;t=Math.max(t,r)}return t}else if(ge(e)){let t=1;for(let n of e.variants)if(n.fields)for(let r of n.fields){let i=Kn(r.type);if(i===null)return null;t=Math.max(t,i)}return t}else if(it(e)){let t=1;for(let n of e.fields){let r=Kn(n.type);if(r===null)return null;t=Math.max(t,r)}return t}else{if(G(e))return da();if(Ie(e))return da()}return null}function Ur(e){return x(e)?null:pe(e)||He(e)||vt(e)||Nt(e)||Et(e)||Vt(e)||Te(e)||De(e)||Lt(e)?0:cn(e)?8:ho(e)||vo(e)?br():Hn(e)||To(e)?8:Eo(e)||$o(e)?16:Co(e)||bo(e)?32:ko(e)||wo(e)?64:Fo(e)?32:Lo(e)?64:ke(e)?Em(e):we(e)?$m(e):ce(e)?e.isReferenceSemantics?br():e.isNewtype?Ur(e.fields[0].type):Cm(e):ge(e)?bm(e):it(e)?km(e):G(e)||Ie(e)?br():null}function kr(e,t){if($r(e))throw lt([{token:t,errorMessage:`Cannot use 'void' type here.
45
45
  Please consider use 'unit' type instead.
46
46
  `}])}function wr(e,t,n){if(!pt(e)||ni(e,n))return!1;if(t.has(e.id))return!0;t.add(e.id);try{for(let r of e.fields)if(ei(r.type,e,t,n))return!0;return!1}finally{t.delete(e.id)}}function ei(e,t,n,r){if(ce(e)&&e.id===t.id)return!0;if(ce(e)&&e.isReferenceSemantics)return wr(e,new Set(n),r);if(ge(e)){for(let i of e.variants)if(i.fields){for(let o of i.fields)if(ei(o.type,t,n,r))return!0}}if(x(e))return ni(e,r)?!1:e.resolvedConcreteType?ei(e.resolvedConcreteType,t,n,r):!0;if(ke(e)||Qe(e))return ei(e.childType,t,n,r);if(we(e)){for(let i of e.fields)if(ei(i.type,t,n,r))return!0}if(it(e)){for(let i of e.fields)if(ei(i.type,t,n,r))return!0}return be(e)?!0:(Ie(e),!1)}function cr(e,t){return t?e.id===t.id?!0:ke(e)||Qe(e)||Ie(e)?cr(e.childType,t):we(e)?e.fields.some(n=>cr(n.type,t)):ce(e)?e.fields.some(n=>cr(n.type,t)):it(e)?e.fields.some(n=>cr(n.type,t)):ge(e)?e.variants.some(n=>n.fields?.some(r=>cr(r.type,t))):G(e)?cr(e.return.type,t):!1:!1}import{createHash as iu}from"crypto";function Ui(e){return"yo"+iu("sha1").update(e).digest("hex").slice(0,8)}var ma=new Map;function qe(e){let t=ma.get(e);return t===void 0&&(t=0),ma.set(e,t+1),`${Ui(e)}_id_${t}`}function ya(e){ma.delete(e)}var ou=1;function au(e){return`_${Ui(e)}_temp_`}function su(e){return`${au(e)}${ou++}`}function ut(e,t){return t.startsWith(au(e))}var cs=new Map;function ri(e,t){let n="";for(let o=0;o<t.length;o++)if(yo(t[o])){let a=rs.indexOf(t[o]);n+=`${a}`}else n+=t[o];let r=Ui(e)+"_"+n,i=cs.get(r);return i===void 0?i=0:i++,cs.set(r,i),r+(i==0?"":`_${i}`)}function _s(e){return iu("sha1").update(e).digest("hex").slice(0,10)}function lu(){ma.clear(),cs.clear(),ou=1}function zr(e){return{[e]:!0}}function et(e,t){return e?.[t]===!0}function nt(e){return e!==void 0&&(e.return===!0||e.escape===!0||e.break===!0||e.continue===!0)}function So(e){let t={};for(let n of e)n.return&&(t.return=!0),n.escape&&(t.escape=!0),n.break&&(t.break=!0),n.continue&&(t.continue=!0);return t}function uu(e){let t=[];return e.return&&t.push("return"),e.escape&&t.push("escape"),e.break&&t.push("break"),e.continue&&t.push("continue"),t.join("+")}function Ae(e){switch(e.tag){case"Atom":return{...e,$:void 0};case"FnCall":return{...e,func:Ae(e.func),args:e.args.map(Ae),$:void 0}}}function F(e){return e?.tag==="FnCall"}function z(e){return e?.tag==="Atom"}function dt(e,t){return e.tag==="Atom"&&(typeof t=="string"?e.token.value===t:t.includes(e.token.value))}function zi(e){return e.tag==="Atom"&&e.token.type==="operator"}function E(e,t,n){if(e.tag!=="FnCall"||e.func.tag!=="Atom")return!1;let r=e.func.token.value;return e.tag==="FnCall"&&e.func.tag==="Atom"&&(typeof t=="string"?r===t:t.includes(r))&&(n===void 0||e.args.length===n)}function he(e,t,n){if(!F(e))throw y({token:e.token,errorMessage:`Expected function call, got atom:
47
47
  ${w(e)}`});if(!E(e,t))throw y({token:e.token,errorMessage:`Expected function call of ${Array.isArray(t)?t.map(r=>`"${r}"`).join(" or "):`"${t}"`}, got:
@@ -69,14 +69,14 @@ Consider using Dyn(...) for dynamic dispatch if different concrete types are nee
69
69
  `:"")+(b?"Might be initialized here:":"Not initialized here:"),token:b??t[R].token})))}if(g.length===1){if(g[0]&&!s[_].consumedAtToken){let C={...s[_],consumedAtToken:g[0]};e=Be(e,s[_],C),s[_]=C}}else if(!s[_].consumedAtToken&&g.every(C=>C)){let C={...s[_],consumedAtToken:g[0]};e=Be(e,s[_],C),s[_]=C}else{let C=g.filter(b=>!!b),L=g.filter(b=>!b);if(C.length>0&&L.length>0)throw lt(g.map((b,R)=>({errorMessage:(R===0?`Variable "${p}" is consumed in some cases but not in other cases:
70
70
  `:"")+(b?"Consumed here:":"Not consumed here:"),token:b??t[R].token})))}if(!s[_].isOwningTheRcValue&&m.every(C=>C)){let C={...s[_],isOwningTheRcValue:!0,isOwningTheSameRcValueAs:void 0};e=Be(e,s[_],C),s[_]=C}else{let C=m.filter(b=>!!b),L=m.filter(b=>!b);if(C.length>0&&L.length>0)throw lt(m.map((b,R)=>({errorMessage:(R===0?`Variable "${p}" might be holding the Rc value in some cases but not holding the Rc value in other cases:
71
71
  `:"")+(b?"Might be owning the Rc value here:":"Might be not owning the Rc value here:"),token:b??t[R].token})))}let v=s[_].id,T=[];for(let C=1;C<u;C++){let R=r[C-1].frames[o].variables[_];T.push(R.id)}if(T.some(C=>C!==v)){let C=ri(e.modulePath,p),L={...s[_],id:C,isOwningTheSameRcValueAs:void 0};e=Be(e,s[_],L),s[_]=L}}}return e}function dr(e,t){e.$=t.$,e.args=t.args,e.func=t.func,e.isInfix=t.isInfix,e.tag=t.tag,e.token=t.token}function ga(e,t){F(e)||(e.tag=t.tag),dr(e,t)}function Tn(e,t,n=!1){if(e.$?.value&&O(e.$?.value))return t;let r=e.$?.variableName;if(!r)return t;let i=X(t,r);if(i.length===0)throw lt([{token:e.token,errorMessage:`Variable "${r}" is not defined.`}]);let o=i[i.length-1];if(o.consumedAtToken&&!n){let a=`use of moved value: \`${r}\``;throw lt([{token:e.token,errorMessage:a},{token:o.consumedAtToken,errorMessage:"value moved here"}])}else t=Be(t,o,{...o,consumedAtToken:e.token});return t}function qt(e,t){if(!e.$||!e.$.variableName)return;if(e.$.value){let r=e.$.variableName;if(r&&ut(e.$.env.modulePath,r)&&Le(e.$.type)){let i=X(e.$.env,r);if(i.length>0){let o=i[i.length-1];o.isOwningTheRcValue&&!o.consumedAtToken&&(e.$.env=Be(e.$.env,o,{...o,consumedAtToken:e.token}))}}return}let n=e.$.variableName;if(!n)throw y({token:e.token,errorMessage:`Expression does not have a variable name to call ${k.___dup} on:
72
- ${w(e)}`});if(Le(e.$.type)){if(ut(e.$.env.modulePath,n)&&!(z(e)&&e.token.value!==n)){let o=X(e.$.env,n);if(o.length>0){let a=o[o.length-1];if(a.isOwningTheRcValue){a.consumedAtToken||(e.$.env=Be(e.$.env,a,{...a,consumedAtToken:e.token}));return}}}let r=Jt(`${k.___dup[0]}(${n})`),i=S({expr:r,env:e.$.env,context:{...t,expectedType:void 0}});if(i.$?.variableName){let o=X(i.$.env,i.$.variableName);if(o.length>0){let a=o[o.length-1];a.consumedAtToken||(i.$.env=Be(i.$.env,a,{...a,consumedAtToken:i.token}))}}e.$.deferredDupExpressions=[i],e.$.env=i.$.env}}function ii(e,t){let n=e.$?.variableName;if(!n)return;let r=X(t,n);if(r.length===0)throw lt([{token:e.token,errorMessage:`Variable "${n}" is not defined.`}]);let i=r[r.length-1];if(i.consumedAtToken){let o=`use of moved value: \`${n}\``;throw lt([{token:e.token,errorMessage:o},{token:i.consumedAtToken,errorMessage:"value moved here"}])}}var mt="__yo_self";function oi(e,t,n){if(ce(e)){if(e.isReferenceSemantics)return!1;if(n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>oi(i.type,t,n));return n.delete(e.id),r}if(we(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>oi(i.type,t,n));return n.delete(e.id),r}if(ge(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.variants.every(i=>(i.fields??[]).every(o=>oi(o.type,t,n)));return n.delete(e.id),r}return ke(e)||Qe(e)||Ie(e)?oi(e.childType,t,n):Xn(e,t)}function ai(e,t,n){if(ce(e)){if(e.isReferenceSemantics||n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>ai(i.type,t,n));return n.delete(e.id),r}if(we(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>ai(i.type,t,n));return n.delete(e.id),r}if(ge(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.variants.every(i=>(i.fields??[]).every(o=>ai(o.type,t,n)));return n.delete(e.id),r}return ke(e)||Qe(e)||Ie(e)?ai(e.childType,t,n):Fr(e,t)}function cu(e,t,n,r){let i=Jt(e),o=S({expr:i,env:n,context:{...r,SelfType:t,forceCompileTimeBindings:!1}});if(!o.$)throw new Error(`Failed to evaluate auto-generated expression: ${w(i)}`);return{expr:o,env:o.$.env}}function Wi({label:e,functionSignature:t,SelfType:n,env:r,context:i}){let{expr:o,env:a}=cu(t,n,r,i);if(F(o)&&o.$&&o.$.value&&O(o.$.value)&&G(o.$.value.value)){let s=o.$.value.value,l={label:e,type:s,assignedValue:void 0,exprs:{expr:o,labelExpr:o.args[0],typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:void 0}};if(n.trait){let u=n.trait.fields.findIndex(c=>c.label===e);u>=0?n.trait.fields[u]=l:n.trait.fields.push(l)}}return a}function wn({label:e,functionCode:t,SelfType:n,env:r,context:i}){let{expr:o,env:a}=cu(t,n,r,i);if(F(o)&&o.$&&o.$.value&&ne(o.$.value)){o.$.value.funcId+=e,o.$.value.funcName=e;let s={label:e,type:o.$.type,assignedValue:o.$.value,exprs:{expr:o,labelExpr:o.args[0],typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:o}};if(n.trait){let l=n.trait.fields.findIndex(u=>u.label===e);l>=0?n.trait.fields[l]=s:n.trait.fields.push(s)}}return a}var ps=`(fn(${mt} : Self) -> unit)`,ha=`(fn(${mt} : Self) -> unit)`,va=`(fn(${mt} : Self) -> Self)`;function km(e){return e.replace(/[^a-zA-Z0-9_]/g,t=>`_u${t.charCodeAt(0)}_`)}function wm(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function fs(e,t){if(e.length===0)return{destructuringExpr:"",callsExpr:""};let n=[],r=[];for(let i of e)if(wm(i)){let o=qe("field_"+i);n.push(`${i} : ${o}`),r.push(`(${t})(${o});`)}else{let o=qe("field_"+km(i));n.push(`(${i}) : ${o}`),r.push(`(${t})(${o});`)}return{destructuringExpr:`{ ${n.join(", ")} } := ${mt};`,callsExpr:r.join(`
73
- `)}}function Fm(e){let t=ps;if(!sn(e))return{signature:t,code:`(${t} ())`};let n=e.fields.filter(a=>Le(a.type)).map(a=>a.label);if(!n.length)return{signature:t,code:`(${t} ())`};let{destructuringExpr:r,callsExpr:i}=fs(n,k.___drop[0]),o=`
72
+ ${w(e)}`});if(Le(e.$.type)){if(ut(e.$.env.modulePath,n)&&!(z(e)&&e.token.value!==n)){let o=X(e.$.env,n);if(o.length>0){let a=o[o.length-1];if(a.isOwningTheRcValue){a.consumedAtToken||(e.$.env=Be(e.$.env,a,{...a,consumedAtToken:e.token}));return}}}let r=Jt(`${k.___dup[0]}(${n})`),i=S({expr:r,env:e.$.env,context:{...t,expectedType:void 0}});if(i.$?.variableName){let o=X(i.$.env,i.$.variableName);if(o.length>0){let a=o[o.length-1];a.consumedAtToken||(i.$.env=Be(i.$.env,a,{...a,consumedAtToken:i.token}))}}e.$.deferredDupExpressions=[i],e.$.env=i.$.env}}function ii(e,t){let n=e.$?.variableName;if(!n)return;let r=X(t,n);if(r.length===0)throw lt([{token:e.token,errorMessage:`Variable "${n}" is not defined.`}]);let i=r[r.length-1];if(i.consumedAtToken){let o=`use of moved value: \`${n}\``;throw lt([{token:e.token,errorMessage:o},{token:i.consumedAtToken,errorMessage:"value moved here"}])}}var mt="__yo_self";function oi(e,t,n){if(ce(e)){if(e.isReferenceSemantics)return!1;if(n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>oi(i.type,t,n));return n.delete(e.id),r}if(we(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>oi(i.type,t,n));return n.delete(e.id),r}if(ge(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.variants.every(i=>(i.fields??[]).every(o=>oi(o.type,t,n)));return n.delete(e.id),r}return ke(e)||Qe(e)||Ie(e)?oi(e.childType,t,n):Xn(e,t)}function ai(e,t,n){if(ce(e)){if(e.isReferenceSemantics||n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>ai(i.type,t,n));return n.delete(e.id),r}if(we(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.fields.every(i=>ai(i.type,t,n));return n.delete(e.id),r}if(ge(e)){if(n.has(e.id))return!0;n.add(e.id);let r=e.variants.every(i=>(i.fields??[]).every(o=>ai(o.type,t,n)));return n.delete(e.id),r}return ke(e)||Qe(e)||Ie(e)?ai(e.childType,t,n):Fr(e,t)}function cu(e,t,n,r){let i=Jt(e),o=S({expr:i,env:n,context:{...r,SelfType:t,forceCompileTimeBindings:!1}});if(!o.$)throw new Error(`Failed to evaluate auto-generated expression: ${w(i)}`);return{expr:o,env:o.$.env}}function Wi({label:e,functionSignature:t,SelfType:n,env:r,context:i}){let{expr:o,env:a}=cu(t,n,r,i);if(F(o)&&o.$&&o.$.value&&O(o.$.value)&&G(o.$.value.value)){let s=o.$.value.value,l={label:e,type:s,assignedValue:void 0,exprs:{expr:o,labelExpr:o.args[0],typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:void 0}};if(n.trait){let u=n.trait.fields.findIndex(c=>c.label===e);u>=0?n.trait.fields[u]=l:n.trait.fields.push(l)}}return a}function wn({label:e,functionCode:t,SelfType:n,env:r,context:i}){let{expr:o,env:a}=cu(t,n,r,i);if(F(o)&&o.$&&o.$.value&&ne(o.$.value)){o.$.value.funcId+=e,o.$.value.funcName=e;let s={label:e,type:o.$.type,assignedValue:o.$.value,exprs:{expr:o,labelExpr:o.args[0],typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:o}};if(n.trait){let l=n.trait.fields.findIndex(u=>u.label===e);l>=0?n.trait.fields[l]=s:n.trait.fields.push(s)}}return a}var ps=`(fn(${mt} : Self) -> unit)`,ha=`(fn(${mt} : Self) -> unit)`,va=`(fn(${mt} : Self) -> Self)`;function wm(e){return e.replace(/[^a-zA-Z0-9_]/g,t=>`_u${t.charCodeAt(0)}_`)}function Fm(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function fs(e,t){if(e.length===0)return{destructuringExpr:"",callsExpr:""};let n=[],r=[];for(let i of e)if(Fm(i)){let o=qe("field_"+i);n.push(`${i} : ${o}`),r.push(`(${t})(${o});`)}else{let o=qe("field_"+wm(i));n.push(`(${i}) : ${o}`),r.push(`(${t})(${o});`)}return{destructuringExpr:`{ ${n.join(", ")} } := ${mt};`,callsExpr:r.join(`
73
+ `)}}function Lm(e){let t=ps;if(!sn(e))return{signature:t,code:`(${t} ())`};let n=e.fields.filter(a=>Le(a.type)).map(a=>a.label);if(!n.length)return{signature:t,code:`(${t} ())`};let{destructuringExpr:r,callsExpr:i}=fs(n,k.___drop[0]),o=`
74
74
  ${r}
75
75
  ${i}
76
76
  `;return{signature:t,code:`(${t} { // ___dispose
77
77
  ${o}
78
78
  return ();
79
- })`}}function Lm(e){let t=ha,n=e.fields.filter(a=>Le(a.type)).map(a=>a.label),r=sn(e)?`
79
+ })`}}function Am(e){let t=ha,n=e.fields.filter(a=>Le(a.type)).map(a=>a.label),r=sn(e)?`
80
80
  ${k.__yo_decr_rc[0]}(${mt});`:"",i="";if(!sn(e)&&n.length){let{destructuringExpr:a,callsExpr:s}=fs(n,k.___drop[0]);i=`
81
81
  ${a}
82
82
  ${s}
@@ -84,7 +84,7 @@ ${w(e)}`});if(Le(e.$.type)){if(ut(e.$.env.modulePath,n)&&!(z(e)&&e.token.value!=
84
84
  ${i}
85
85
  ${r}
86
86
  return ();
87
- })`;return{signature:t,code:o}}function Am(e){let t=va,n=e.fields.filter(o=>Le(o.type)).map(o=>o.label),r=sn(e)?`
87
+ })`;return{signature:t,code:o}}function Im(e){let t=va,n=e.fields.filter(o=>Le(o.type)).map(o=>o.label),r=sn(e)?`
88
88
  ${k.__yo_incr_rc[0]}(${mt});`:"",i="";if(!sn(e)&&n.length){let{destructuringExpr:o,callsExpr:a}=fs(n,k.___dup[0]);i=`
89
89
  ${o}
90
90
  ${a}
@@ -92,7 +92,7 @@ ${w(e)}`});if(Le(e.$.type)){if(ut(e.$.env.modulePath,n)&&!(z(e)&&e.token.value!=
92
92
  ${i}
93
93
  ${r}
94
94
  return ${k.__yo_rc_own[0]}(${mt});
95
- })`}}function Im({structType:e,env:t,context:n}){if(li(e,t))return t;wt(e);let r=Fe(e),{code:i}=Fm(e),{code:o}=Lm(e),{code:a}=Am(e);return ds({structType:e,env:t,context:n}),r||(t=wn({label:k.___dispose[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___drop[0],functionCode:o,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:a,SelfType:e,env:t,context:n})),t}function ds({structType:e,env:t,context:n}){li(e,t)||(Wi({label:k.___dispose[0],functionSignature:ps,SelfType:e,env:t,context:n}),Wi({label:k.___drop[0],functionSignature:ha,SelfType:e,env:t,context:n}),Wi({label:k.___dup[0],functionSignature:va,SelfType:e,env:t,context:n}))}function Sm(e){let t=ha,n=e.variants.filter(o=>o.fields&&o.fields.some(a=>Le(a.type))),r=sn(e)?`
95
+ })`}}function Sm({structType:e,env:t,context:n}){if(li(e,t))return t;Ft(e);let r=Fe(e),{code:i}=Lm(e),{code:o}=Am(e),{code:a}=Im(e);return ds({structType:e,env:t,context:n}),r||(t=wn({label:k.___dispose[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___drop[0],functionCode:o,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:a,SelfType:e,env:t,context:n})),t}function ds({structType:e,env:t,context:n}){li(e,t)||(Wi({label:k.___dispose[0],functionSignature:ps,SelfType:e,env:t,context:n}),Wi({label:k.___drop[0],functionSignature:ha,SelfType:e,env:t,context:n}),Wi({label:k.___dup[0],functionSignature:va,SelfType:e,env:t,context:n}))}function Nm(e){let t=ha,n=e.variants.filter(o=>o.fields&&o.fields.some(a=>Le(a.type))),r=sn(e)?`
96
96
  ${k.__yo_decr_rc[0]}(${mt});`:"",i=sn(e)?"":n.length?`
97
97
  match(${mt},
98
98
  ${n.map(o=>{let a=o.fields.filter(u=>Le(u.type)).map(u=>u.label),s=o.fields.map(u=>u.label).join(", "),l=a.map(u=>` (${k.___drop[0]})(${u});`).join(`
@@ -105,7 +105,7 @@ ${l}
105
105
  ${i}
106
106
  ${r}
107
107
  return ();
108
- })`}}function Nm(e){let t=va,n=e.variants.filter(o=>o.fields&&o.fields.some(a=>Le(a.type))),r=sn(e)?`
108
+ })`}}function Vm(e){let t=va,n=e.variants.filter(o=>o.fields&&o.fields.some(a=>Le(a.type))),r=sn(e)?`
109
109
  ${k.__yo_incr_rc[0]}(${mt});`:"",i=sn(e)?"":n.length?`
110
110
  match(${mt},
111
111
  ${n.map(o=>{let a=o.fields.filter(u=>Le(u.type)).map(u=>u.label),s=o.fields.map(u=>u.label).join(", "),l=a.map(u=>` (${k.___dup[0]})(${u});`).join(`
@@ -118,37 +118,37 @@ ${l}
118
118
  ${i}
119
119
  ${r}
120
120
  return ${k.__yo_rc_own[0]}(${mt});
121
- })`}}function Vm({enumType:e,env:t,context:n}){if(li(e,t))return t;wt(e);let r=Fe(e),{code:i}=Sm(e),{code:o}=Nm(e);return ms({enumType:e,env:t,context:n}),r||(t=wn({label:k.___drop[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:o,SelfType:e,env:t,context:n})),t}function ms({enumType:e,env:t,context:n}){if(li(e,t))return t;Wi({label:k.___dispose[0],functionSignature:ps,SelfType:e,env:t,context:n}),Wi({label:k.___drop[0],functionSignature:ha,SelfType:e,env:t,context:n}),Wi({label:k.___dup[0],functionSignature:va,SelfType:e,env:t,context:n})}function No({dynType:e,env:t,context:n}){let r=xm(e),i=Dm(e);return i&&(t=wn({label:k.___dup[0],functionCode:i,SelfType:e,env:t,context:n})),r&&(t=wn({label:k.___drop[0],functionCode:r,SelfType:e,env:t,context:n})),t}function xm(e){return`((fn(${mt} : Self) -> unit) { // ___drop for ${A(e)}
121
+ })`}}function xm({enumType:e,env:t,context:n}){if(li(e,t))return t;Ft(e);let r=Fe(e),{code:i}=Nm(e),{code:o}=Vm(e);return ms({enumType:e,env:t,context:n}),r||(t=wn({label:k.___drop[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:o,SelfType:e,env:t,context:n})),t}function ms({enumType:e,env:t,context:n}){if(li(e,t))return t;Wi({label:k.___dispose[0],functionSignature:ps,SelfType:e,env:t,context:n}),Wi({label:k.___drop[0],functionSignature:ha,SelfType:e,env:t,context:n}),Wi({label:k.___dup[0],functionSignature:va,SelfType:e,env:t,context:n})}function No({dynType:e,env:t,context:n}){let r=Dm(e),i=Mm(e);return i&&(t=wn({label:k.___dup[0],functionCode:i,SelfType:e,env:t,context:n})),r&&(t=wn({label:k.___drop[0],functionCode:r,SelfType:e,env:t,context:n})),t}function Dm(e){return`((fn(${mt} : Self) -> unit) { // ___drop for ${A(e)}
122
122
  ${k.__yo_dyn_drop[0]}(${mt});
123
- })`}function Dm(e){return`((fn(${mt} : Self) -> Self) { // ___dup for ${A(e)}
123
+ })`}function Mm(e){return`((fn(${mt} : Self) -> Self) { // ___dup for ${A(e)}
124
124
  ${k.__yo_dyn_dup[0]}(${mt});
125
125
  return ${k.__yo_rc_own[0]}(${mt});
126
- })`}function Mm(e){return`((fn(${mt} : Self) -> unit) { // ___drop for ${A(e)}
126
+ })`}function Om(e){return`((fn(${mt} : Self) -> unit) { // ___drop for ${A(e)}
127
127
  ${k.__yo_sometype_drop[0]}(${mt});
128
- })`}function Om(e){return`((fn(${mt} : Self) -> Self) { // ___dup for ${A(e)}
128
+ })`}function Rm(e){return`((fn(${mt} : Self) -> Self) { // ___dup for ${A(e)}
129
129
  ${k.__yo_sometype_dup[0]}(${mt});
130
130
  return ${k.__yo_rc_own[0]}(${mt});
131
- })`}function _u({someType:e,env:t,context:n}){let r=Mm(e),i=Om(e);return t=wn({label:k.___drop[0],functionCode:r,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:i,SelfType:e,env:t,context:n}),t}function Rm(e){return`((fn(${mt} : Self) -> unit) { // ___dispose for Iso
131
+ })`}function _u({someType:e,env:t,context:n}){let r=Om(e),i=Rm(e);return t=wn({label:k.___drop[0],functionCode:r,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:i,SelfType:e,env:t,context:n}),t}function Pm(e){return`((fn(${mt} : Self) -> unit) { // ___dispose for Iso
132
132
  ${k.__yo_iso_dispose[0]}(${mt});
133
133
  return ();
134
- })`}function Pm(e){return`((fn(${mt} : Self) -> unit) { // ___drop for Iso
134
+ })`}function Um(e){return`((fn(${mt} : Self) -> unit) { // ___drop for Iso
135
135
  ${k.__yo_decr_rc_atomic[0]}(${mt});
136
136
  return ();
137
- })`}function Um(e){return`((fn(${mt} : Self) -> Self) { // ___dup for Iso
137
+ })`}function zm(e){return`((fn(${mt} : Self) -> Self) { // ___dup for Iso
138
138
  ${k.__yo_incr_rc_atomic[0]}(${mt});
139
139
  return ${k.__yo_rc_own[0]}(${mt});
140
- })`}function pu({isoType:e,env:t,context:n}){let r=Rm(e),i=Pm(e),o=Um(e);return t=wn({label:k.___dispose[0],functionCode:r,SelfType:e,env:t,context:n}),t=wn({label:k.___drop[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:o,SelfType:e,env:t,context:n}),t}function zm(e){return`((fn(${mt} : Self) -> unit) { // ___dispose for Arc
140
+ })`}function pu({isoType:e,env:t,context:n}){let r=Pm(e),i=Um(e),o=zm(e);return t=wn({label:k.___dispose[0],functionCode:r,SelfType:e,env:t,context:n}),t=wn({label:k.___drop[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:o,SelfType:e,env:t,context:n}),t}function Bm(e){return`((fn(${mt} : Self) -> unit) { // ___dispose for Arc
141
141
  ${k.__yo_arc_dispose[0]}(${mt});
142
142
  return ();
143
- })`}function Bm(e){return`((fn(${mt} : Self) -> unit) { // ___drop for Arc
143
+ })`}function Gm(e){return`((fn(${mt} : Self) -> unit) { // ___drop for Arc
144
144
  ${k.__yo_decr_rc_atomic[0]}(${mt});
145
145
  return ();
146
- })`}function Gm(e){return`((fn(${mt} : Self) -> Self) { // ___dup for Arc
146
+ })`}function Wm(e){return`((fn(${mt} : Self) -> Self) { // ___dup for Arc
147
147
  ${k.__yo_incr_rc_atomic[0]}(${mt});
148
148
  return ${k.__yo_rc_own[0]}(${mt});
149
- })`}function fu({arcType:e,env:t,context:n}){let r=zm(e),i=Bm(e),o=Gm(e);return t=wn({label:k.___dispose[0],functionCode:r,SelfType:e,env:t,context:n}),t=wn({label:k.___drop[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:o,SelfType:e,env:t,context:n}),t}function tn(e,t,n,r){let i=`${e}()`,o=Jt(i),a=S({expr:o,env:n,context:{...r,expectedType:void 0,ReceiverType:t}});if(!a.$||!Tt(a.$.value))return n;n=a.$.env;let s=a.$.value;s.type.receiverType=t;let l={label:"",type:gn(1),assignedValue:s,sourceModulePath:r.currentModulePath,exprs:{expr:o}};return t.trait.fields.push(l),n}function Wm({structType:e,env:t,context:n}){return e.isReferenceSemantics||e.fields.every(i=>Vo(i.type,t))&&(t=tn("Send",e,t,n)),t}function qm({structType:e,env:t,context:n}){return e.isReferenceSemantics&&(t=tn("Rc",e,t,n)),t}function Ym({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>Vo(o.type,t)))&&(t=tn("Send",e,t,n)),t}function du({unionType:e,env:t,context:n}){return e.fields.every(i=>Vo(i.type,t))&&(t=tn("Send",e,t,n)),t}function Hm({structType:e,env:t,context:n}){return e.isReferenceSemantics?wr(e,new Set,t)||(t=tn("Acyclic",e,t,n)):e.fields.every(i=>ni(i.type,t))&&(t=tn("Acyclic",e,t,n)),t}function jm({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>ni(o.type,t)))&&(t=tn("Acyclic",e,t,n)),t}function mu({unionType:e,env:t,context:n}){return e.fields.every(i=>ni(i.type,t))&&(t=tn("Acyclic",e,t,n)),t}function Km({structType:e,env:t,context:n}){return e.isReferenceSemantics||e.fields.every(i=>oi(i.type,t,new Set([e.id])))&&(t=tn("Comptime",e,t,n)),t}function Xm({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>oi(o.type,t,new Set([e.id]))))&&(t=tn("Comptime",e,t,n)),t}function Qm({structType:e,env:t,context:n}){return e.isReferenceSemantics?(t=tn("Runtime",e,t,n),t):(e.fields.every(i=>ai(i.type,t,new Set([e.id])))&&(t=tn("Runtime",e,t,n)),t)}function Zm({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>ai(o.type,t,new Set([e.id]))))&&(t=tn("Runtime",e,t,n)),t}function yu({unionType:e,env:t,context:n}){return t=tn("Runtime",e,t,n),t}function Jm({tupleType:e,env:t,context:n}){return e.fields.every(i=>Vo(i.type,t))&&(t=tn("Send",e,t,n)),t}function ey({tupleType:e,env:t,context:n}){return e.fields.every(i=>oi(i.type,t,new Set([e.id])))&&(t=tn("Comptime",e,t,n)),t}function ty({tupleType:e,env:t,context:n}){return e.fields.every(i=>ai(i.type,t,new Set([e.id])))&&(t=tn("Runtime",e,t,n)),t}function si({structType:e,env:t,context:n,errorToken:r}){return t=Wm({structType:e,env:t,context:n}),t=qm({structType:e,env:t,context:n}),t=Hm({structType:e,env:t,context:n}),t=Km({structType:e,env:t,context:n}),t=Qm({structType:e,env:t,context:n}),t=Im({structType:e,env:t,context:n}),Ta(e,t,r,n),t}function gu({enumType:e,env:t,context:n,errorToken:r}){return t=Ym({enumType:e,env:t,context:n}),t=jm({enumType:e,env:t,context:n}),t=Xm({enumType:e,env:t,context:n}),t=Zm({enumType:e,env:t,context:n}),t=Vm({enumType:e,env:t,context:n}),Ta(e,t,r,n),t}function hu({tupleType:e,env:t,context:n,errorToken:r}){return t=Jm({tupleType:e,env:t,context:n}),t=ey({tupleType:e,env:t,context:n}),t=ty({tupleType:e,env:t,context:n}),Ta(e,t,r,n),t}function Vn(e,t){let n=X(e,t);if(n.length===0)return;let r=n[n.length-1];if(r.value&&O(r.value[0])){let i=r.value[0];if(De(i.value))return i.value}}function Ot(e,t){let n=t.definitionFrameLevel;if(n!==void 0&&n>=0){let o=e.frames[n];if(o){let a=o.variables.find(s=>s.name===t.name&&s.value?.[0]?.tag==="Type");if(a&&a.value){let s=a.value[0];if(s.value===t||x(s.value)&&s.value.id===t.id)return t;x(s.value)&&(s.value.id,t.id)}}}let r,i=new Set;do{if(i.has(t))return t;i.add(t);let o=X(e,t.name,a=>a.value?.[0]?.tag==="Type");if(!o.length||(r=o[o.length-1].value[0],r.value===t))return t;if(x(r.value)){if(r.value.name===t.name&&r.value.id!==t.id){let a=!1;for(let s=e.frames.length-1;s>=0;s--){let l=e.frames[s];if(l){for(let u of l.variables)if(u.name===t.name&&u.value){let c=u.value[0];if(c?.tag==="Type"&&c.value===t){a=!0;break}}if(a)break}}if(!a)return t}t=r.value}else{let a=!1;for(let s=e.frames.length-1;s>=0;s--){let l=e.frames[s];if(l){for(let u of l.variables)if(u.name===t.name&&u.value){let c=u.value[0];if(c?.tag==="Type"){let _=c;if(_.value===t){a=!0;break}if(x(_.value)&&_.value.id!==t.id)return t}}if(a)break}}if(!a)return t;break}}while(x(t));return r.value}var ys=null;function Or(){if(ys)return ys;let e=at(),t=Oe(e),n={id:"comptime_int",tag:"comptime_int",trait:t};return t.receiverType=n,ys=n,n}var gs=null;function Li(){if(gs)return gs;let e=at(),t=Oe(e),n={id:"comptime_float",tag:"comptime_float",trait:t};return t.receiverType=n,gs=n,n}var hs=null;function xt(){if(hs)return hs;let e=at(),t=Oe(e),n={id:"comptime_string",tag:"comptime_string",trait:t};return t.receiverType=n,hs=n,n}var vs=null;function _n(){if(vs)return vs;let e=at(),t=Oe(e),n={id:"Expr",tag:"Expr",trait:t};return t.receiverType=n,vs=n,n}var Ts=new Map;function Io(e){if(Ts.has(e))return Ts.get(e);let t=at(),n=Oe(t),i={id:`comptime_list_${e.id}`,tag:"ComptimeList",childType:e,trait:n};return n.receiverType=i,Ts.set(e,i),i}function xo(){return Io(_n())}var Es=null;function Je(){if(Es)return Es;let e=at(),t=Oe(e),n={id:"bool",tag:"bool",trait:t};return t.receiverType=n,Es=n,n}var $s=null;function gt(){if($s)return $s;let e=at(),t=Oe(e),n={id:"usize",tag:"usize",trait:t};return t.receiverType=n,$s=n,n}var Cs=null;function Ai(){if(Cs)return Cs;let e=at(),t=Oe(e),n={id:"isize",tag:"isize",trait:t};return t.receiverType=n,Cs=n,n}var bs=null;function Ii(){if(bs)return bs;let e=at(),t=Oe(e),n={id:"u8",tag:"u8",trait:t};return t.receiverType=n,bs=n,n}var ks=null;function Si(){if(ks)return ks;let e=at(),t=Oe(e),n={id:"i8",tag:"i8",trait:t};return t.receiverType=n,ks=n,n}var ws=null;function Ni(){if(ws)return ws;let e=at(),t=Oe(e),n={id:"u16",tag:"u16",trait:t};return t.receiverType=n,ws=n,n}var Fs=null;function Vi(){if(Fs)return Fs;let e=at(),t=Oe(e),n={id:"i16",tag:"i16",trait:t};return t.receiverType=n,Fs=n,n}var Ls=null;function xi(){if(Ls)return Ls;let e=at(),t=Oe(e),n={id:"u32",tag:"u32",trait:t};return t.receiverType=n,Ls=n,n}var As=null;function Rr(){if(As)return As;let e=at(),t=Oe(e),n={id:"i32",tag:"i32",trait:t};return t.receiverType=n,As=n,n}var Is=null;function Di(){if(Is)return Is;let e=at(),t=Oe(e),n={id:"u64",tag:"u64",trait:t};return t.receiverType=n,Is=n,n}var Ss=null;function Mi(){if(Ss)return Ss;let e=at(),t=Oe(e),n={id:"i64",tag:"i64",trait:t};return t.receiverType=n,Ss=n,n}var Ns=null;function Oi(){if(Ns)return Ns;let e=at(),t=Oe(e),n={id:"f32",tag:"f32",trait:t};return t.receiverType=n,Ns=n,n}var Vs=null;function Pr(){if(Vs)return Vs;let e=at(),t=Oe(e),n={id:"f64",tag:"f64",trait:t};return t.receiverType=n,Vs=n,n}var xs=null;function xn(){if(xs)return xs;let e=at(),t=Oe(e),n={id:"unit",tag:"unit",trait:t};return t.receiverType=n,xs=n,n}var Ds=null;function Tu(){if(Ds)return Ds;let e=at(),t=Oe(e),n={id:"char",tag:"char",trait:t};return t.receiverType=n,Ds=n,n}var Ms=null;function Eu(){if(Ms)return Ms;let e=at(),t=Oe(e),n={id:"short",tag:"short",trait:t};return t.receiverType=n,Ms=n,n}var Os=null;function $u(){if(Os)return Os;let e=at(),t=Oe(e),n={id:"ushort",tag:"ushort",trait:t};return t.receiverType=n,Os=n,n}var Rs=null;function Cu(){if(Rs)return Rs;let e=at(),t=Oe(e),n={id:"int",tag:"int",trait:t};return t.receiverType=n,Rs=n,n}var Ps=null;function bu(){if(Ps)return Ps;let e=at(),t=Oe(e),n={id:"uint",tag:"uint",trait:t};return t.receiverType=n,Ps=n,n}var Us=null;function ku(){if(Us)return Us;let e=at(),t=Oe(e),n={id:"long",tag:"long",trait:t};return t.receiverType=n,Us=n,n}var zs=null;function wu(){if(zs)return zs;let e=at(),t=Oe(e),n={id:"ulong",tag:"ulong",trait:t};return t.receiverType=n,zs=n,n}var Bs=null;function Fu(){if(Bs)return Bs;let e=at(),t=Oe(e),n={id:"longlong",tag:"longlong",trait:t};return t.receiverType=n,Bs=n,n}var Gs=null;function Lu(){if(Gs)return Gs;let e=at(),t=Oe(e),n={id:"ulonglong",tag:"ulonglong",trait:t};return t.receiverType=n,Gs=n,n}var Ws=null;function Au(){if(Ws)return Ws;let e=at(),t=Oe(e),n={id:"longdouble",tag:"longdouble",trait:t};return t.receiverType=n,Ws=n,n}function tt(e){return gn(0,e)}function mr(e,t){let n=at(),r=Oe(n),i={id:`array_${e.id+"_"+_s(Me(t))}`,tag:"Array",childType:e,length:t,trait:r};return r.receiverType=i,i}var qs=new Map;function $a(e){if(qs.has(e))return qs.get(e);let t=at(),n=Oe(t),r={id:`slice_${e.id}`,tag:"Slice",childType:e,trait:n};return n.receiverType=r,qs.set(e,r),r}function ru(e){let n=X(e,"str").find(r=>O(r.value?.[0])&&r.value[0].type);if(!n||!O(n.value?.[0]))throw new Error("'str' type not found in environment. Make sure prelude is loaded.");return n.value[0].value}var Ys;function Iu(){if(Ys)return Ys;let e=at(),t=Oe(e),n={id:"void",tag:"void",trait:t};return t.receiverType=n,Ys=n,n}function qi(e){let t=at(),n=Oe(t),r={id:`tuple_${e.map(i=>i.type.id).join("_")}`,tag:"Tuple",fields:e,trait:n};return n.receiverType=r,r}function ui(e,t=!1,n=!1){let r=Oe(e),i={id:`struct_${qe(e.modulePath)}`,tag:"Struct",isReferenceSemantics:t,isNewtype:n,fields:[],trait:r,env:e};return r.receiverType=i,i}function Ca(e){return{id:`module_${qe(e.modulePath)}`,tag:"Module",fields:[],env:e,trait:void 0}}function Oe(e){return{id:`trait_${qe(e.modulePath)}`,tag:"Trait",fields:[],env:e,trait:void 0}}function Su(e){let t=Oe(e),n={id:`enum_${qe(e.modulePath)}`,tag:"Enum",variants:[],trait:t,env:e};return t.receiverType=n,n}function Nu(e){let t=Oe(e),n={id:`union_${qe(e.modulePath)}`,tag:"Union",fields:[],trait:t,env:e};return t.receiverType=n,n}function ci({parameters:e,forallParameters:t,implicitParameters:n,variadicParameter:r,whereClauseExprs:i,return_:o,env:a,parametersFrame:s,SelfType:l,SelfTraitType:u,SelfModuleType:c,isClosure:_}){let p=at(),f=Oe(p),m={id:`fn_${qe(a.modulePath)}`,tag:"Function",parameters:e,forallParameters:t,implicitParameters:n??[],variadicParameter:r,whereClauseExprs:i,return:o,env:a,parametersFrame:s,SelfType:l,SelfTraitType:u,SelfModuleType:c,trait:f,isClosure:_};return f.receiverType=m,m}var Hs=new Map;function _i(e){if(Hs.has(e))return Hs.get(e);let t=at(),n=Oe(t),r={id:`ptr_${e.id}`,tag:"Ptr",childType:e,trait:n};return n.receiverType=r,Hs.set(e,r),r}var js=new Map;function Vu(e,t){if(js.has(e))return js.get(e);let n=Oe(t),r={id:`iso_${e.id}`,tag:"Iso",childType:e,trait:n,env:t};return n.receiverType=r,js.set(e,r),r}var Ks=new Map;function xu(e,t){if(Ks.has(e))return Ks.get(e);let n=Oe(t),r={id:`arc_${e.id}`,tag:"Arc",childType:e,trait:n,env:t};return n.receiverType=r,Ks.set(e,r),r}function bn(e,t,{id:n,requiredTraits:r,negativeTraits:i,recursiveTypeRef:o,env:a,context:s}){if(e.level!==0)throw console.trace(),new Error(`createSomeType expects a type with level 0, got level ${e.level}`);let l=Oe(a),u=r?.map(p=>({traitType:p,frameLevel:-1}))??[],c=i?.map(p=>({traitType:p,frameLevel:-1}))??[],_={id:n??`sometype_${qe(a.modulePath)}`,tag:"SomeType",name:t,definitionFrameLevel:a.frames.length>0?a.frames.length-1:void 0,parentType:e,size:void 0,requiredTraits:u,negativeTraits:c,trait:l,isExtern:e.isExtern,externName:e.externName,recursiveTypeRef:o};return l.receiverType=_,Vn(a,"Runtime")&&tn("Runtime",_,a,s),_u({someType:_,env:a,context:{SelfType:_,stdPath:""}}),_}var Ea=new Map;function pi(e,t){let n=Oe(t),r=gn(1),i={id:`effects_row_sometype_${qe(t.modulePath)}`,tag:"SomeType",name:e,definitionFrameLevel:t.frames.length>0?t.frames.length-1:void 0,parentType:r,size:void 0,requiredTraits:[],negativeTraits:[],trait:n,isEffectsRow:!0};return n.receiverType=i,i}function Lr(e){let t=at(),n=Oe(t),r={id:`EffectsRow_${qe(t.modulePath)}`,tag:"EffectsRow",implicitParameters:e,trait:n};return n.receiverType=r,r}function gn(e,t){if(Ea.has(e)){let i=Ea.get(e);if(i.has(t))return i.get(t)}else Ea.set(e,new Map);let n=Oe(at()),r={id:`Type(${e})`,tag:"Type",level:e,baseType:t,trait:n};return n.receiverType=r,Ea.get(e).set(t,r),r}function fi({expr:e,labelExpr:t,typeExpr:n,defaultValueExpr:r,assignedValueExpr:i}){return{expr:e,labelExpr:t,typeExpr:n,defaultValueExpr:r,assignedValueExpr:i}}function Du(e,t){let n=`fn_trait_${e.id}`,r=Oe(t);return r.isFn={callType:e},r.id=n,r.receiverType=void 0,r}function vu(e){return e.fields.map(n=>{if(n.type.tag==="Function"){let r=n.type,i=r.parameters.map(a=>`${a.label}:${A(a.type)}`).join(","),o=A(r.return.type);return`${n.label}:(${i})->${o}`}return`${n.label}:${A(n.type)}`}).join(";")}function Do({requiredTraits:e,env:t,negativeTraits:n}){let r=Oe(t),i=e.map(c=>vu(c)).join("__"),o=n?n.map(c=>vu(c)).join("__"):"",a=`dyn_${_s(i+(o?`_neg_${o}`:""))}`,s=e.map(c=>({traitType:c,frameLevel:-1}))??[],l=n?.map(c=>({traitType:c,frameLevel:-1}))??[],u={id:a,tag:"Dyn",requiredTraits:s,negativeTraits:l,trait:r,env:t};return r.receiverType=u,u}function Mu(e,t){return!He(e)||!He(t)?!1:t.level===e.level&&(t.tag===e.tag||e.tag==="Type")}function Dn(e,t,n=new Set){if(n.has(t.id))return!1;if(n.add(t.id),x(t))return e===t.id;if(ce(t))return t.fields.some(r=>Dn(e,r.type,n));if(ge(t))return t.variants.some(r=>r.fields?r.fields.some(i=>Dn(e,i.type,n)):!1);if(we(t))return t.fields.some(r=>Dn(e,r.type,n));if(ke(t)||Qe(t)||Vt(t))return Dn(e,t.childType,n);if(Ie(t))return!1;if(kt(t)||$t(t))return Dn(e,t.childType,n);if(G(t))return t.parameters.some(r=>Dn(e,r.type,n))||Dn(e,t.return.type,n);if(Kt(t)){if(Dn(e,t.isFuture.outputType,n))return!0;for(let r of t.isFuture.effects)if(Dn(e,r.type,n))return!0;return!1}return bt(t)?Dn(e,t.isFn.callType,n):!1}function Ze(e,t,n=[]){if(n.find(r=>r.expected===e.type&&r.given===t.type))return{expectedEnv:e.env,givenEnv:t.env};if(n.push({expected:e.type,given:t.type}),x(e.type)&&x(t.type)){let r=Ot(e.env,e.type),i=Ot(t.env,t.type);if(x(r))if(x(i)){if(r!==i){let o=ee(t.type);{let a=X(e.env,e.type.name),s=a[a.length-1];if(s)e.env=Be(e.env,s,{...s,value:[o]});else{let{env:l}=me({env:e.env,variable:{name:e.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=l}}{let a=X(t.env,t.type.name),s=a[a.length-1];if(s)t.env=Be(t.env,s,{...s,value:[o]});else{let{env:l}=me({env:t.env,variable:{name:t.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});t.env=l}}}}else{let o=ee(i),a=X(e.env,e.type.name),s=a[a.length-1];if(s)e.env=Be(e.env,s,{...s,value:[o]});else{let{env:l}=me({env:e.env,variable:{name:e.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=l}}else{let o=ee(r),a=X(t.env,t.type.name),s=a[a.length-1];if(s)t.env=Be(t.env,s,{...s,value:[o]});else{let{env:l}=me({env:t.env,variable:{name:t.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});t.env=l}}if(e.type.id!==t.type.id&&e.type.requiredTraits&&t.type.requiredTraits){let o=e.type.requiredTraits,a=t.type.requiredTraits;for(let s=0;s<o.length;s++){let l=o[s].traitType;if(bt(l)){let u=a.find(c=>bt(c.traitType));if(u&&bt(u.traitType)){let{expectedEnv:c,givenEnv:_}=Ze({type:l.isFn.callType,env:e.env},{type:u.traitType.isFn.callType,env:t.env},n);e.env=c,t.env=_}}else if(Kt(l)){let u=a.find(c=>Kt(c.traitType));if(u&&Kt(u.traitType)){let{expectedEnv:c,givenEnv:_}=Ze({type:l.isFuture.outputType,env:e.env},{type:u.traitType.isFuture.outputType,env:t.env},n);e.env=c,t.env=_,Xs(l.isFuture.effects,u.traitType.isFuture.effects,e,t,n)}}}}}else if(x(e.type)){let r=Ot(e.env,e.type);if(x(r)&&(r.id===e.type.id||r.name===e.type.name)){if(Dn(e.type.id,t.type))throw new Error(`Cannot unify type variable "${e.type.name}" with type "${A(t.type)}" because it would create an infinite type.`);let i=ee(t.type),o=X(e.env,e.type.name),a=o[o.length-1];if(a)a&&(e.env=Be(e.env,a,{...a,value:[i]}));else{let{env:s}=me({env:e.env,variable:{name:e.type.name,value:[i],type:i.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=s}if(e.type.requiredTraits){for(let{traitType:s}of e.type.requiredTraits)if(bt(s)&&G(t.type)){let l=s.isFn.callType,{expectedEnv:u,givenEnv:c}=Ze({type:l,env:e.env},{type:t.type,env:t.env},n);e.env=u,t.env=c}else if(Kt(s)&&Kt(t.type)){let{expectedEnv:l,givenEnv:u}=Ze({type:s.isFuture.outputType,env:e.env},{type:t.type.isFuture.outputType,env:t.env},n);e.env=l,t.env=u,Xs(s.isFuture.effects,t.type.isFuture.effects,e,t,n)}}}else if(!x(r)){let{expectedEnv:i,givenEnv:o}=Ze({type:r,env:e.env},{type:t.type,env:t.env},n);e.env=i,t.env=o}}else if(x(t.type)){let r=Ot(t.env,t.type);if(x(r)){if(Dn(t.type.id,e.type))throw new Error(`Cannot unify type variable "${t.type.name}" with type "${A(e.type)}" because it would create an infinite type.`);let i=ee(e.type),o=X(t.env,t.type.name),a=o[o.length-1];if(a)a&&(t.env=Be(t.env,a,{...a,value:[i]}));else{let{env:s}=me({env:t.env,variable:{name:t.type.name,value:[i],type:i.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});t.env=s}}else{let{expectedEnv:i,givenEnv:o}=Ze({type:e.type,env:e.env},{type:r,env:t.env},n);e.env=i,t.env=o}}else if(we(e.type)&&we(t.type)&&e.type.fields.length===t.type.fields.length)for(let r=0;r<e.type.fields.length;r++){let{expectedEnv:i,givenEnv:o}=Ze({type:e.type.fields[r].type,env:e.env},{type:t.type.fields[r].type,env:t.env},n);e.env=i,t.env=o}else{if(we(e.type)&&we(t.type))throw new Error(`Cannot unify incompatible tuple types: "${A(e.type)}" and "${A(t.type)}"`);if(ce(e.type)&&ce(t.type)){if(!(e.type.id===t.type.id||e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue)){if(!(e.type.functionValue&&t.type.functionValue&&e.type.functionValue.funcId===t.type.functionValue.funcId))throw new Error(`Cannot unify incompatible struct types: "${A(e.type)}" and "${A(t.type)}"`)}for(let r=0;r<e.type.fields.length;r++){let i=e.type.fields[r],o=t.type.fields[r],{expectedEnv:a,givenEnv:s}=Ze({type:i.type,env:e.env},{type:o.type,env:t.env},n);if(e.env=a,t.env=s,i.assignedValue&&o.assignedValue&&O(i.assignedValue)&&O(o.assignedValue)){let{expectedEnv:l,givenEnv:u}=Ze({type:i.assignedValue.value,env:e.env},{type:o.assignedValue.value,env:t.env},n);e.env=l,t.env=u}}}else if(ge(e.type)&&ge(t.type)&&(e.type.id===t.type.id||e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue))for(let r=0;r<e.type.variants.length;r++){let i=e.type.variants[r],o=t.type.variants[r],a=i.fields??[],s=o.fields??[];for(let l=0;l<a.length;l++){let{expectedEnv:u,givenEnv:c}=Ze({type:a[l].type,env:e.env},{type:s[l].type,env:t.env},n);e.env=u,t.env=c}}else{if(ge(e.type)&&ge(t.type))throw new Error(`Cannot unify incompatible enum types: "${A(e.type)}" and "${A(t.type)}"`);if(Te(e.type)&&Te(t.type)&&e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue)for(let r=0;r<e.type.fields.length;r++){let i=e.type.fields[r],o=t.type.fields[r],{expectedEnv:a,givenEnv:s}=Ze({type:i.type,env:e.env},{type:o.type,env:t.env},n);if(e.env=a,t.env=s,i.assignedValue&&o.assignedValue&&O(i.assignedValue)&&O(o.assignedValue)){let{expectedEnv:l,givenEnv:u}=Ze({type:i.assignedValue.value,env:e.env},{type:o.assignedValue.value,env:t.env},n);e.env=l,t.env=u}}else if(De(e.type)&&De(t.type)&&e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue)for(let r=0;r<e.type.fields.length;r++){let i=e.type.fields[r],o=t.type.fields[r],{expectedEnv:a,givenEnv:s}=Ze({type:i.type,env:e.env},{type:o.type,env:t.env},n);if(e.env=a,t.env=s,i.assignedValue&&o.assignedValue&&O(i.assignedValue)&&O(o.assignedValue)){let{expectedEnv:l,givenEnv:u}=Ze({type:i.assignedValue.value,env:e.env},{type:o.assignedValue.value,env:t.env},n);e.env=l,t.env=u}}else if(Ie(e.type)&&Ie(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(kt(e.type)&&kt(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if($t(e.type)&&$t(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(ke(e.type)&&ke(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);if(e.env=r,t.env=i,de(e.type.length)&&e.type.length.variableName&&!de(t.type.length)){let o=e.type.length.variableName,a=t.type.length,s=X(e.env,o),l=s[s.length-1];if(l)l&&(e.env=Be(e.env,l,{...l,value:[a]}));else{let{env:u}=me({env:e.env,variable:{name:o,value:[a],type:t.type.length.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=u}}}else if(Qe(e.type)&&Qe(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(Vt(e.type)&&Vt(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(Kt(e.type)&&Kt(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.isFuture.outputType,env:e.env},{type:t.type.isFuture.outputType,env:t.env},n);e.env=r,t.env=i,Xs(e.type.isFuture.effects,t.type.isFuture.effects,e,t,n)}else if(bt(e.type)&&bt(t.type)){let r=e.type,i=t.type,{expectedEnv:o,givenEnv:a}=Ze({type:r.isFn.callType,env:e.env},{type:i.isFn.callType,env:t.env},n);e.env=o,t.env=a}else if(G(e.type)&&G(t.type)&&e.type.forallParameters.length===t.type.forallParameters.length&&e.type.parameters.length===t.type.parameters.length){let r=e.type,i=t.type;for(let s=0;s<r.forallParameters.length;s++){let l=r.forallParameters[s],u=i.forallParameters[s],{expectedEnv:c,givenEnv:_}=Ze({type:l.type,env:e.env},{type:u.type,env:t.env},n);e.env=c,t.env=_}for(let s=0;s<r.parameters.length;s++){let{expectedEnv:l,givenEnv:u}=Ze({type:r.parameters[s].type,env:e.env},{type:i.parameters[s].type,env:t.env},n);e.env=l,t.env=u}{let s=r.implicitParameters,l=[];for(let f of i.implicitParameters)f.isEffectRowSpread?ot(f.type)&&l.push(...f.type.implicitParameters):l.push(f);let u=[],c=[],_=[];for(let f of s)f.isEffectRowSpread?ot(f.type)?c.push(f):x(f.type)&&f.type.isEffectsRow&&_.push(f):u.push(f);if(_.length>1)throw new Error(`Ambiguous effect row unification: multiple unsolved effect row variables (${_.map(f=>f.label).join(", ")}). At most one effect row spread can be unsolved during type unification.`);let p=new Set;for(let f of u)for(let m=0;m<l.length;m++)if(!p.has(m)&&f.type.id===l[m].type.id){let{expectedEnv:g,givenEnv:h}=Ze({type:f.type,env:e.env},{type:l[m].type,env:t.env},n);e.env=g,t.env=h,p.add(m);break}for(let f of c){let m=f.type.implicitParameters;for(let g of m)for(let h=0;h<l.length;h++)if(!p.has(h)&&g.type.id===l[h].type.id){let{expectedEnv:d,givenEnv:v}=Ze({type:g.type,env:e.env},{type:l[h].type,env:t.env},n);e.env=d,t.env=v,p.add(h);break}}if(_.length===1){let f=_[0],m=[];for(let g=0;g<l.length;g++)p.has(g)||m.push(l[g]);if(x(f.type)&&f.type.isEffectsRow){let g=Lr(m),h=ee(g),d=X(e.env,f.type.name),v=d[d.length-1];if(v)e.env=Be(e.env,v,{...v,value:[h]});else{let{env:T}=me({env:e.env,variable:{name:f.type.name,value:[h],type:h.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=T}}}}let{expectedEnv:o,givenEnv:a}=Ze({type:r.return.type,env:e.env},{type:i.return.type,env:t.env},n);e.env=o,t.env=a}else if(!(He(e.type)&&!He(t.type))){if(e.type.tag!==t.type.tag)throw new Error(`Cannot unify incompatible types:
149
+ })`}function fu({arcType:e,env:t,context:n}){let r=Bm(e),i=Gm(e),o=Wm(e);return t=wn({label:k.___dispose[0],functionCode:r,SelfType:e,env:t,context:n}),t=wn({label:k.___drop[0],functionCode:i,SelfType:e,env:t,context:n}),t=wn({label:k.___dup[0],functionCode:o,SelfType:e,env:t,context:n}),t}function tn(e,t,n,r){let i=`${e}()`,o=Jt(i),a=S({expr:o,env:n,context:{...r,expectedType:void 0,ReceiverType:t}});if(!a.$||!Tt(a.$.value))return n;n=a.$.env;let s=a.$.value;s.type.receiverType=t;let l={label:"",type:gn(1),assignedValue:s,sourceModulePath:r.currentModulePath,exprs:{expr:o}};return t.trait.fields.push(l),n}function qm({structType:e,env:t,context:n}){return e.isReferenceSemantics||e.fields.every(i=>Vo(i.type,t))&&(t=tn("Send",e,t,n)),t}function Ym({structType:e,env:t,context:n}){return e.isReferenceSemantics&&(t=tn("Rc",e,t,n)),t}function Hm({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>Vo(o.type,t)))&&(t=tn("Send",e,t,n)),t}function du({unionType:e,env:t,context:n}){return e.fields.every(i=>Vo(i.type,t))&&(t=tn("Send",e,t,n)),t}function jm({structType:e,env:t,context:n}){return e.isReferenceSemantics?wr(e,new Set,t)||(t=tn("Acyclic",e,t,n)):e.fields.every(i=>ni(i.type,t))&&(t=tn("Acyclic",e,t,n)),t}function Km({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>ni(o.type,t)))&&(t=tn("Acyclic",e,t,n)),t}function mu({unionType:e,env:t,context:n}){return e.fields.every(i=>ni(i.type,t))&&(t=tn("Acyclic",e,t,n)),t}function Xm({structType:e,env:t,context:n}){return e.isReferenceSemantics||e.fields.every(i=>oi(i.type,t,new Set([e.id])))&&(t=tn("Comptime",e,t,n)),t}function Qm({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>oi(o.type,t,new Set([e.id]))))&&(t=tn("Comptime",e,t,n)),t}function Zm({structType:e,env:t,context:n}){return e.isReferenceSemantics?(t=tn("Runtime",e,t,n),t):(e.fields.every(i=>ai(i.type,t,new Set([e.id])))&&(t=tn("Runtime",e,t,n)),t)}function Jm({enumType:e,env:t,context:n}){return e.variants.every(i=>!i.fields||i.fields.length===0?!0:i.fields.every(o=>ai(o.type,t,new Set([e.id]))))&&(t=tn("Runtime",e,t,n)),t}function yu({unionType:e,env:t,context:n}){return t=tn("Runtime",e,t,n),t}function ey({tupleType:e,env:t,context:n}){return e.fields.every(i=>Vo(i.type,t))&&(t=tn("Send",e,t,n)),t}function ty({tupleType:e,env:t,context:n}){return e.fields.every(i=>oi(i.type,t,new Set([e.id])))&&(t=tn("Comptime",e,t,n)),t}function ny({tupleType:e,env:t,context:n}){return e.fields.every(i=>ai(i.type,t,new Set([e.id])))&&(t=tn("Runtime",e,t,n)),t}function si({structType:e,env:t,context:n,errorToken:r}){return t=qm({structType:e,env:t,context:n}),t=Ym({structType:e,env:t,context:n}),t=jm({structType:e,env:t,context:n}),t=Xm({structType:e,env:t,context:n}),t=Zm({structType:e,env:t,context:n}),t=Sm({structType:e,env:t,context:n}),Ta(e,t,r,n),t}function gu({enumType:e,env:t,context:n,errorToken:r}){return t=Hm({enumType:e,env:t,context:n}),t=Km({enumType:e,env:t,context:n}),t=Qm({enumType:e,env:t,context:n}),t=Jm({enumType:e,env:t,context:n}),t=xm({enumType:e,env:t,context:n}),Ta(e,t,r,n),t}function hu({tupleType:e,env:t,context:n,errorToken:r}){return t=ey({tupleType:e,env:t,context:n}),t=ty({tupleType:e,env:t,context:n}),t=ny({tupleType:e,env:t,context:n}),Ta(e,t,r,n),t}function Vn(e,t){let n=X(e,t);if(n.length===0)return;let r=n[n.length-1];if(r.value&&O(r.value[0])){let i=r.value[0];if(De(i.value))return i.value}}function Ot(e,t){let n=t.definitionFrameLevel;if(n!==void 0&&n>=0){let o=e.frames[n];if(o){let a=o.variables.find(s=>s.name===t.name&&s.value?.[0]?.tag==="Type");if(a&&a.value){let s=a.value[0];if(s.value===t||x(s.value)&&s.value.id===t.id)return t;x(s.value)&&(s.value.id,t.id)}}}let r,i=new Set;do{if(i.has(t))return t;i.add(t);let o=X(e,t.name,a=>a.value?.[0]?.tag==="Type");if(!o.length||(r=o[o.length-1].value[0],r.value===t))return t;if(x(r.value)){if(r.value.name===t.name&&r.value.id!==t.id){let a=!1;for(let s=e.frames.length-1;s>=0;s--){let l=e.frames[s];if(l){for(let u of l.variables)if(u.name===t.name&&u.value){let c=u.value[0];if(c?.tag==="Type"&&c.value===t){a=!0;break}}if(a)break}}if(!a)return t}t=r.value}else{let a=!1;for(let s=e.frames.length-1;s>=0;s--){let l=e.frames[s];if(l){for(let u of l.variables)if(u.name===t.name&&u.value){let c=u.value[0];if(c?.tag==="Type"){let _=c;if(_.value===t){a=!0;break}if(x(_.value)&&_.value.id!==t.id)return t}}if(a)break}}if(!a)return t;break}}while(x(t));return r.value}var ys=null;function Or(){if(ys)return ys;let e=at(),t=Oe(e),n={id:"comptime_int",tag:"comptime_int",trait:t};return t.receiverType=n,ys=n,n}var gs=null;function Li(){if(gs)return gs;let e=at(),t=Oe(e),n={id:"comptime_float",tag:"comptime_float",trait:t};return t.receiverType=n,gs=n,n}var hs=null;function xt(){if(hs)return hs;let e=at(),t=Oe(e),n={id:"comptime_string",tag:"comptime_string",trait:t};return t.receiverType=n,hs=n,n}var vs=null;function _n(){if(vs)return vs;let e=at(),t=Oe(e),n={id:"Expr",tag:"Expr",trait:t};return t.receiverType=n,vs=n,n}var Ts=new Map;function Io(e){if(Ts.has(e))return Ts.get(e);let t=at(),n=Oe(t),i={id:`comptime_list_${e.id}`,tag:"ComptimeList",childType:e,trait:n};return n.receiverType=i,Ts.set(e,i),i}function xo(){return Io(_n())}var Es=null;function Je(){if(Es)return Es;let e=at(),t=Oe(e),n={id:"bool",tag:"bool",trait:t};return t.receiverType=n,Es=n,n}var $s=null;function gt(){if($s)return $s;let e=at(),t=Oe(e),n={id:"usize",tag:"usize",trait:t};return t.receiverType=n,$s=n,n}var Cs=null;function Ai(){if(Cs)return Cs;let e=at(),t=Oe(e),n={id:"isize",tag:"isize",trait:t};return t.receiverType=n,Cs=n,n}var bs=null;function Ii(){if(bs)return bs;let e=at(),t=Oe(e),n={id:"u8",tag:"u8",trait:t};return t.receiverType=n,bs=n,n}var ks=null;function Si(){if(ks)return ks;let e=at(),t=Oe(e),n={id:"i8",tag:"i8",trait:t};return t.receiverType=n,ks=n,n}var ws=null;function Ni(){if(ws)return ws;let e=at(),t=Oe(e),n={id:"u16",tag:"u16",trait:t};return t.receiverType=n,ws=n,n}var Fs=null;function Vi(){if(Fs)return Fs;let e=at(),t=Oe(e),n={id:"i16",tag:"i16",trait:t};return t.receiverType=n,Fs=n,n}var Ls=null;function xi(){if(Ls)return Ls;let e=at(),t=Oe(e),n={id:"u32",tag:"u32",trait:t};return t.receiverType=n,Ls=n,n}var As=null;function Rr(){if(As)return As;let e=at(),t=Oe(e),n={id:"i32",tag:"i32",trait:t};return t.receiverType=n,As=n,n}var Is=null;function Di(){if(Is)return Is;let e=at(),t=Oe(e),n={id:"u64",tag:"u64",trait:t};return t.receiverType=n,Is=n,n}var Ss=null;function Mi(){if(Ss)return Ss;let e=at(),t=Oe(e),n={id:"i64",tag:"i64",trait:t};return t.receiverType=n,Ss=n,n}var Ns=null;function Oi(){if(Ns)return Ns;let e=at(),t=Oe(e),n={id:"f32",tag:"f32",trait:t};return t.receiverType=n,Ns=n,n}var Vs=null;function Pr(){if(Vs)return Vs;let e=at(),t=Oe(e),n={id:"f64",tag:"f64",trait:t};return t.receiverType=n,Vs=n,n}var xs=null;function xn(){if(xs)return xs;let e=at(),t=Oe(e),n={id:"unit",tag:"unit",trait:t};return t.receiverType=n,xs=n,n}var Ds=null;function Tu(){if(Ds)return Ds;let e=at(),t=Oe(e),n={id:"char",tag:"char",trait:t};return t.receiverType=n,Ds=n,n}var Ms=null;function Eu(){if(Ms)return Ms;let e=at(),t=Oe(e),n={id:"short",tag:"short",trait:t};return t.receiverType=n,Ms=n,n}var Os=null;function $u(){if(Os)return Os;let e=at(),t=Oe(e),n={id:"ushort",tag:"ushort",trait:t};return t.receiverType=n,Os=n,n}var Rs=null;function Cu(){if(Rs)return Rs;let e=at(),t=Oe(e),n={id:"int",tag:"int",trait:t};return t.receiverType=n,Rs=n,n}var Ps=null;function bu(){if(Ps)return Ps;let e=at(),t=Oe(e),n={id:"uint",tag:"uint",trait:t};return t.receiverType=n,Ps=n,n}var Us=null;function ku(){if(Us)return Us;let e=at(),t=Oe(e),n={id:"long",tag:"long",trait:t};return t.receiverType=n,Us=n,n}var zs=null;function wu(){if(zs)return zs;let e=at(),t=Oe(e),n={id:"ulong",tag:"ulong",trait:t};return t.receiverType=n,zs=n,n}var Bs=null;function Fu(){if(Bs)return Bs;let e=at(),t=Oe(e),n={id:"longlong",tag:"longlong",trait:t};return t.receiverType=n,Bs=n,n}var Gs=null;function Lu(){if(Gs)return Gs;let e=at(),t=Oe(e),n={id:"ulonglong",tag:"ulonglong",trait:t};return t.receiverType=n,Gs=n,n}var Ws=null;function Au(){if(Ws)return Ws;let e=at(),t=Oe(e),n={id:"longdouble",tag:"longdouble",trait:t};return t.receiverType=n,Ws=n,n}function tt(e){return gn(0,e)}function mr(e,t){let n=at(),r=Oe(n),i={id:`array_${e.id+"_"+_s(Me(t))}`,tag:"Array",childType:e,length:t,trait:r};return r.receiverType=i,i}var qs=new Map;function $a(e){if(qs.has(e))return qs.get(e);let t=at(),n=Oe(t),r={id:`slice_${e.id}`,tag:"Slice",childType:e,trait:n};return n.receiverType=r,qs.set(e,r),r}function ru(e){let n=X(e,"str").find(r=>O(r.value?.[0])&&r.value[0].type);if(!n||!O(n.value?.[0]))throw new Error("'str' type not found in environment. Make sure prelude is loaded.");return n.value[0].value}var Ys;function Iu(){if(Ys)return Ys;let e=at(),t=Oe(e),n={id:"void",tag:"void",trait:t};return t.receiverType=n,Ys=n,n}function qi(e){let t=at(),n=Oe(t),r={id:`tuple_${e.map(i=>i.type.id).join("_")}`,tag:"Tuple",fields:e,trait:n};return n.receiverType=r,r}function ui(e,t=!1,n=!1){let r=Oe(e),i={id:`struct_${qe(e.modulePath)}`,tag:"Struct",isReferenceSemantics:t,isNewtype:n,fields:[],trait:r,env:e};return r.receiverType=i,i}function Ca(e){return{id:`module_${qe(e.modulePath)}`,tag:"Module",fields:[],env:e,trait:void 0}}function Oe(e){return{id:`trait_${qe(e.modulePath)}`,tag:"Trait",fields:[],env:e,trait:void 0}}function Su(e){let t=Oe(e),n={id:`enum_${qe(e.modulePath)}`,tag:"Enum",variants:[],trait:t,env:e};return t.receiverType=n,n}function Nu(e){let t=Oe(e),n={id:`union_${qe(e.modulePath)}`,tag:"Union",fields:[],trait:t,env:e};return t.receiverType=n,n}function ci({parameters:e,forallParameters:t,implicitParameters:n,variadicParameter:r,whereClauseExprs:i,return_:o,env:a,parametersFrame:s,SelfType:l,SelfTraitType:u,SelfModuleType:c,isClosure:_}){let p=at(),f=Oe(p),m={id:`fn_${qe(a.modulePath)}`,tag:"Function",parameters:e,forallParameters:t,implicitParameters:n??[],variadicParameter:r,whereClauseExprs:i,return:o,env:a,parametersFrame:s,SelfType:l,SelfTraitType:u,SelfModuleType:c,trait:f,isClosure:_};return f.receiverType=m,m}var Hs=new Map;function _i(e){if(Hs.has(e))return Hs.get(e);let t=at(),n=Oe(t),r={id:`ptr_${e.id}`,tag:"Ptr",childType:e,trait:n};return n.receiverType=r,Hs.set(e,r),r}var js=new Map;function Vu(e,t){if(js.has(e))return js.get(e);let n=Oe(t),r={id:`iso_${e.id}`,tag:"Iso",childType:e,trait:n,env:t};return n.receiverType=r,js.set(e,r),r}var Ks=new Map;function xu(e,t){if(Ks.has(e))return Ks.get(e);let n=Oe(t),r={id:`arc_${e.id}`,tag:"Arc",childType:e,trait:n,env:t};return n.receiverType=r,Ks.set(e,r),r}function bn(e,t,{id:n,requiredTraits:r,negativeTraits:i,recursiveTypeRef:o,env:a,context:s}){if(e.level!==0)throw console.trace(),new Error(`createSomeType expects a type with level 0, got level ${e.level}`);let l=Oe(a),u=r?.map(p=>({traitType:p,frameLevel:-1}))??[],c=i?.map(p=>({traitType:p,frameLevel:-1}))??[],_={id:n??`sometype_${qe(a.modulePath)}`,tag:"SomeType",name:t,definitionFrameLevel:a.frames.length>0?a.frames.length-1:void 0,parentType:e,size:void 0,requiredTraits:u,negativeTraits:c,trait:l,isExtern:e.isExtern,externName:e.externName,recursiveTypeRef:o};return l.receiverType=_,Vn(a,"Runtime")&&tn("Runtime",_,a,s),_u({someType:_,env:a,context:{SelfType:_,stdPath:""}}),_}var Ea=new Map;function pi(e,t){let n=Oe(t),r=gn(1),i={id:`effects_row_sometype_${qe(t.modulePath)}`,tag:"SomeType",name:e,definitionFrameLevel:t.frames.length>0?t.frames.length-1:void 0,parentType:r,size:void 0,requiredTraits:[],negativeTraits:[],trait:n,isEffectsRow:!0};return n.receiverType=i,i}function Lr(e){let t=at(),n=Oe(t),r={id:`EffectsRow_${qe(t.modulePath)}`,tag:"EffectsRow",implicitParameters:e,trait:n};return n.receiverType=r,r}function gn(e,t){if(Ea.has(e)){let i=Ea.get(e);if(i.has(t))return i.get(t)}else Ea.set(e,new Map);let n=Oe(at()),r={id:`Type(${e})`,tag:"Type",level:e,baseType:t,trait:n};return n.receiverType=r,Ea.get(e).set(t,r),r}function fi({expr:e,labelExpr:t,typeExpr:n,defaultValueExpr:r,assignedValueExpr:i}){return{expr:e,labelExpr:t,typeExpr:n,defaultValueExpr:r,assignedValueExpr:i}}function Du(e,t){let n=`fn_trait_${e.id}`,r=Oe(t);return r.isFn={callType:e},r.id=n,r.receiverType=void 0,r}function vu(e){return e.fields.map(n=>{if(n.type.tag==="Function"){let r=n.type,i=r.parameters.map(a=>`${a.label}:${A(a.type)}`).join(","),o=A(r.return.type);return`${n.label}:(${i})->${o}`}return`${n.label}:${A(n.type)}`}).join(";")}function Do({requiredTraits:e,env:t,negativeTraits:n}){let r=Oe(t),i=e.map(c=>vu(c)).join("__"),o=n?n.map(c=>vu(c)).join("__"):"",a=`dyn_${_s(i+(o?`_neg_${o}`:""))}`,s=e.map(c=>({traitType:c,frameLevel:-1}))??[],l=n?.map(c=>({traitType:c,frameLevel:-1}))??[],u={id:a,tag:"Dyn",requiredTraits:s,negativeTraits:l,trait:r,env:t};return r.receiverType=u,u}function Mu(e,t){return!He(e)||!He(t)?!1:t.level===e.level&&(t.tag===e.tag||e.tag==="Type")}function Dn(e,t,n=new Set){if(n.has(t.id))return!1;if(n.add(t.id),x(t))return e===t.id;if(ce(t))return t.fields.some(r=>Dn(e,r.type,n));if(ge(t))return t.variants.some(r=>r.fields?r.fields.some(i=>Dn(e,i.type,n)):!1);if(we(t))return t.fields.some(r=>Dn(e,r.type,n));if(ke(t)||Qe(t)||Vt(t))return Dn(e,t.childType,n);if(Ie(t))return!1;if(wt(t)||Ct(t))return Dn(e,t.childType,n);if(G(t))return t.parameters.some(r=>Dn(e,r.type,n))||Dn(e,t.return.type,n);if(Kt(t)){if(Dn(e,t.isFuture.outputType,n))return!0;for(let r of t.isFuture.effects)if(Dn(e,r.type,n))return!0;return!1}return kt(t)?Dn(e,t.isFn.callType,n):!1}function Ze(e,t,n=[]){if(n.find(r=>r.expected===e.type&&r.given===t.type))return{expectedEnv:e.env,givenEnv:t.env};if(n.push({expected:e.type,given:t.type}),x(e.type)&&x(t.type)){let r=Ot(e.env,e.type),i=Ot(t.env,t.type);if(x(r))if(x(i)){if(r!==i){let o=ee(t.type);{let a=X(e.env,e.type.name),s=a[a.length-1];if(s)e.env=Be(e.env,s,{...s,value:[o]});else{let{env:l}=me({env:e.env,variable:{name:e.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=l}}{let a=X(t.env,t.type.name),s=a[a.length-1];if(s)t.env=Be(t.env,s,{...s,value:[o]});else{let{env:l}=me({env:t.env,variable:{name:t.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});t.env=l}}}}else{let o=ee(i),a=X(e.env,e.type.name),s=a[a.length-1];if(s)e.env=Be(e.env,s,{...s,value:[o]});else{let{env:l}=me({env:e.env,variable:{name:e.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=l}}else{let o=ee(r),a=X(t.env,t.type.name),s=a[a.length-1];if(s)t.env=Be(t.env,s,{...s,value:[o]});else{let{env:l}=me({env:t.env,variable:{name:t.type.name,value:[o],type:o.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});t.env=l}}if(e.type.id!==t.type.id&&e.type.requiredTraits&&t.type.requiredTraits){let o=e.type.requiredTraits,a=t.type.requiredTraits;for(let s=0;s<o.length;s++){let l=o[s].traitType;if(kt(l)){let u=a.find(c=>kt(c.traitType));if(u&&kt(u.traitType)){let{expectedEnv:c,givenEnv:_}=Ze({type:l.isFn.callType,env:e.env},{type:u.traitType.isFn.callType,env:t.env},n);e.env=c,t.env=_}}else if(Kt(l)){let u=a.find(c=>Kt(c.traitType));if(u&&Kt(u.traitType)){let{expectedEnv:c,givenEnv:_}=Ze({type:l.isFuture.outputType,env:e.env},{type:u.traitType.isFuture.outputType,env:t.env},n);e.env=c,t.env=_,Xs(l.isFuture.effects,u.traitType.isFuture.effects,e,t,n)}}}}}else if(x(e.type)){let r=Ot(e.env,e.type);if(x(r)&&(r.id===e.type.id||r.name===e.type.name)){if(Dn(e.type.id,t.type))throw new Error(`Cannot unify type variable "${e.type.name}" with type "${A(t.type)}" because it would create an infinite type.`);let i=ee(t.type),o=X(e.env,e.type.name),a=o[o.length-1];if(a)a&&(e.env=Be(e.env,a,{...a,value:[i]}));else{let{env:s}=me({env:e.env,variable:{name:e.type.name,value:[i],type:i.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=s}if(e.type.requiredTraits){for(let{traitType:s}of e.type.requiredTraits)if(kt(s)&&G(t.type)){let l=s.isFn.callType,{expectedEnv:u,givenEnv:c}=Ze({type:l,env:e.env},{type:t.type,env:t.env},n);e.env=u,t.env=c}else if(Kt(s)&&Kt(t.type)){let{expectedEnv:l,givenEnv:u}=Ze({type:s.isFuture.outputType,env:e.env},{type:t.type.isFuture.outputType,env:t.env},n);e.env=l,t.env=u,Xs(s.isFuture.effects,t.type.isFuture.effects,e,t,n)}}}else if(!x(r)){let{expectedEnv:i,givenEnv:o}=Ze({type:r,env:e.env},{type:t.type,env:t.env},n);e.env=i,t.env=o}}else if(x(t.type)){let r=Ot(t.env,t.type);if(x(r)){if(Dn(t.type.id,e.type))throw new Error(`Cannot unify type variable "${t.type.name}" with type "${A(e.type)}" because it would create an infinite type.`);let i=ee(e.type),o=X(t.env,t.type.name),a=o[o.length-1];if(a)a&&(t.env=Be(t.env,a,{...a,value:[i]}));else{let{env:s}=me({env:t.env,variable:{name:t.type.name,value:[i],type:i.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});t.env=s}}else{let{expectedEnv:i,givenEnv:o}=Ze({type:e.type,env:e.env},{type:r,env:t.env},n);e.env=i,t.env=o}}else if(we(e.type)&&we(t.type)&&e.type.fields.length===t.type.fields.length)for(let r=0;r<e.type.fields.length;r++){let{expectedEnv:i,givenEnv:o}=Ze({type:e.type.fields[r].type,env:e.env},{type:t.type.fields[r].type,env:t.env},n);e.env=i,t.env=o}else{if(we(e.type)&&we(t.type))throw new Error(`Cannot unify incompatible tuple types: "${A(e.type)}" and "${A(t.type)}"`);if(ce(e.type)&&ce(t.type)){if(!(e.type.id===t.type.id||e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue)){if(!(e.type.functionValue&&t.type.functionValue&&e.type.functionValue.funcId===t.type.functionValue.funcId))throw new Error(`Cannot unify incompatible struct types: "${A(e.type)}" and "${A(t.type)}"`)}for(let r=0;r<e.type.fields.length;r++){let i=e.type.fields[r],o=t.type.fields[r],{expectedEnv:a,givenEnv:s}=Ze({type:i.type,env:e.env},{type:o.type,env:t.env},n);if(e.env=a,t.env=s,i.assignedValue&&o.assignedValue&&O(i.assignedValue)&&O(o.assignedValue)){let{expectedEnv:l,givenEnv:u}=Ze({type:i.assignedValue.value,env:e.env},{type:o.assignedValue.value,env:t.env},n);e.env=l,t.env=u}}}else if(ge(e.type)&&ge(t.type)&&(e.type.id===t.type.id||e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue))for(let r=0;r<e.type.variants.length;r++){let i=e.type.variants[r],o=t.type.variants[r],a=i.fields??[],s=o.fields??[];for(let l=0;l<a.length;l++){let{expectedEnv:u,givenEnv:c}=Ze({type:a[l].type,env:e.env},{type:s[l].type,env:t.env},n);e.env=u,t.env=c}}else{if(ge(e.type)&&ge(t.type))throw new Error(`Cannot unify incompatible enum types: "${A(e.type)}" and "${A(t.type)}"`);if(Te(e.type)&&Te(t.type)&&e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue)for(let r=0;r<e.type.fields.length;r++){let i=e.type.fields[r],o=t.type.fields[r],{expectedEnv:a,givenEnv:s}=Ze({type:i.type,env:e.env},{type:o.type,env:t.env},n);if(e.env=a,t.env=s,i.assignedValue&&o.assignedValue&&O(i.assignedValue)&&O(o.assignedValue)){let{expectedEnv:l,givenEnv:u}=Ze({type:i.assignedValue.value,env:e.env},{type:o.assignedValue.value,env:t.env},n);e.env=l,t.env=u}}else if(De(e.type)&&De(t.type)&&e.type.functionValue&&t.type.functionValue&&e.type.functionValue===t.type.functionValue)for(let r=0;r<e.type.fields.length;r++){let i=e.type.fields[r],o=t.type.fields[r],{expectedEnv:a,givenEnv:s}=Ze({type:i.type,env:e.env},{type:o.type,env:t.env},n);if(e.env=a,t.env=s,i.assignedValue&&o.assignedValue&&O(i.assignedValue)&&O(o.assignedValue)){let{expectedEnv:l,givenEnv:u}=Ze({type:i.assignedValue.value,env:e.env},{type:o.assignedValue.value,env:t.env},n);e.env=l,t.env=u}}else if(Ie(e.type)&&Ie(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(wt(e.type)&&wt(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(Ct(e.type)&&Ct(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(ke(e.type)&&ke(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);if(e.env=r,t.env=i,de(e.type.length)&&e.type.length.variableName&&!de(t.type.length)){let o=e.type.length.variableName,a=t.type.length,s=X(e.env,o),l=s[s.length-1];if(l)l&&(e.env=Be(e.env,l,{...l,value:[a]}));else{let{env:u}=me({env:e.env,variable:{name:o,value:[a],type:t.type.length.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=u}}}else if(Qe(e.type)&&Qe(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(Vt(e.type)&&Vt(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n);e.env=r,t.env=i}else if(Kt(e.type)&&Kt(t.type)){let{expectedEnv:r,givenEnv:i}=Ze({type:e.type.isFuture.outputType,env:e.env},{type:t.type.isFuture.outputType,env:t.env},n);e.env=r,t.env=i,Xs(e.type.isFuture.effects,t.type.isFuture.effects,e,t,n)}else if(kt(e.type)&&kt(t.type)){let r=e.type,i=t.type,{expectedEnv:o,givenEnv:a}=Ze({type:r.isFn.callType,env:e.env},{type:i.isFn.callType,env:t.env},n);e.env=o,t.env=a}else if(G(e.type)&&G(t.type)&&e.type.forallParameters.length===t.type.forallParameters.length&&e.type.parameters.length===t.type.parameters.length){let r=e.type,i=t.type;for(let s=0;s<r.forallParameters.length;s++){let l=r.forallParameters[s],u=i.forallParameters[s],{expectedEnv:c,givenEnv:_}=Ze({type:l.type,env:e.env},{type:u.type,env:t.env},n);e.env=c,t.env=_}for(let s=0;s<r.parameters.length;s++){let{expectedEnv:l,givenEnv:u}=Ze({type:r.parameters[s].type,env:e.env},{type:i.parameters[s].type,env:t.env},n);e.env=l,t.env=u}{let s=r.implicitParameters,l=[];for(let f of i.implicitParameters)f.isEffectRowSpread?ot(f.type)&&l.push(...f.type.implicitParameters):l.push(f);let u=[],c=[],_=[];for(let f of s)f.isEffectRowSpread?ot(f.type)?c.push(f):x(f.type)&&f.type.isEffectsRow&&_.push(f):u.push(f);if(_.length>1)throw new Error(`Ambiguous effect row unification: multiple unsolved effect row variables (${_.map(f=>f.label).join(", ")}). At most one effect row spread can be unsolved during type unification.`);let p=new Set;for(let f of u)for(let m=0;m<l.length;m++)if(!p.has(m)&&f.type.id===l[m].type.id){let{expectedEnv:g,givenEnv:h}=Ze({type:f.type,env:e.env},{type:l[m].type,env:t.env},n);e.env=g,t.env=h,p.add(m);break}for(let f of c){let m=f.type.implicitParameters;for(let g of m)for(let h=0;h<l.length;h++)if(!p.has(h)&&g.type.id===l[h].type.id){let{expectedEnv:d,givenEnv:v}=Ze({type:g.type,env:e.env},{type:l[h].type,env:t.env},n);e.env=d,t.env=v,p.add(h);break}}if(_.length===1){let f=_[0],m=[];for(let g=0;g<l.length;g++)p.has(g)||m.push(l[g]);if(x(f.type)&&f.type.isEffectsRow){let g=Lr(m),h=ee(g),d=X(e.env,f.type.name),v=d[d.length-1];if(v)e.env=Be(e.env,v,{...v,value:[h]});else{let{env:T}=me({env:e.env,variable:{name:f.type.name,value:[h],type:h.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});e.env=T}}}}let{expectedEnv:o,givenEnv:a}=Ze({type:r.return.type,env:e.env},{type:i.return.type,env:t.env},n);e.env=o,t.env=a}else if(!(He(e.type)&&!He(t.type))){if(e.type.tag!==t.type.tag)throw new Error(`Cannot unify incompatible types:
150
150
  Expected: "${A(e.type)}"
151
- Given: "${A(t.type)}"`)}}}return{expectedEnv:e.env,givenEnv:t.env}}function Xs(e,t,n,r,i){if(e.length===0&&t.length===0)return;let o=[],a=[],s=[];for(let c of e)c.isEffectRowSpread?ot(c.type)?a.push(c):x(c.type)&&c.type.isEffectsRow&&s.push(c):o.push(c);if(s.length>1)throw new Error(`Ambiguous effect row unification: multiple unsolved effect row variables (${s.map(c=>c.label).join(", ")}). At most one effect row spread can be unsolved during type unification.`);let l=[];for(let c of t)c.isEffectRowSpread?ot(c.type)&&l.push(...c.type.implicitParameters):l.push(c);let u=new Set;for(let c of o)for(let _=0;_<l.length;_++)if(!u.has(_)&&c.type.id===l[_].type.id){let{expectedEnv:p,givenEnv:f}=Ze({type:c.type,env:n.env},{type:l[_].type,env:r.env},i);n.env=p,r.env=f,u.add(_);break}for(let c of a){let _=c.type.implicitParameters;for(let p of _)for(let f=0;f<l.length;f++)if(!u.has(f)&&p.type.id===l[f].type.id){let{expectedEnv:m,givenEnv:g}=Ze({type:p.type,env:n.env},{type:l[f].type,env:r.env},i);n.env=m,r.env=g,u.add(f);break}}if(s.length===1){let c=s[0],_=[];for(let p=0;p<l.length;p++)u.has(p)||_.push(l[p]);if(x(c.type)&&c.type.isEffectsRow){let p=Lr(_),f=ee(p),m=X(n.env,c.type.name),g=m[m.length-1];if(g)n.env=Be(n.env,g,{...g,value:[f]});else{let{env:h}=me({env:n.env,variable:{name:c.type.name,value:[f],type:f.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});n.env=h}}}}function Qs(e,t){let n=new Map;for(let i of t.requiredTraits??[])n.set(i.traitType.id,i.traitType);let r=Wn(e,t);if(r)for(let i of r.requiredTraits)n.set(i.id,i);return[...n.values()]}function Ou(e,t){let n=new Map;for(let i of t.negativeTraits??[])n.set(i.traitType.id,i.traitType);let r=Wn(e,t);if(r)for(let i of r.negativeTraits)n.set(i.id,i);return[...n.values()]}function Zs(e){let t=[];for(let n of e)n.isEffectRowSpread&&ot(n.type)?t.push(...Zs(n.type.implicitParameters)):(n.isEffectRowSpread&&x(n.type)&&n.type.isEffectsRow,t.push(n));return t}function Y(e,t,n=!1,r=new Set){let i=e.type.id,o=t.type.id;if(i&&o&&(ce(e.type)||ge(e.type)||it(e.type))&&(ce(t.type)||ge(t.type)||it(t.type))){let a=`${i}:${o}`;if(r.has(a))return!0;r.add(a)}if(go(e.type)&&go(t.type))return e.type.tag===t.type.tag;if((vt(e.type)||e.type.tag==="u8"||e.type.tag==="i8"||e.type.tag==="u16"||e.type.tag==="i16"||e.type.tag==="u32"||e.type.tag==="i32"||e.type.tag==="u64"||e.type.tag==="i64"||e.type.tag==="usize"||e.type.tag==="isize"||jn(e.type))&&vt(t.type))return!(n&&!vt(e.type));if((Nt(e.type)||e.type.tag==="f32"||e.type.tag==="f64")&&Nt(t.type))return!(n&&!Nt(e.type));if((Et(e.type)||Qe(e.type)&&Hn(e.type.childType)||Ie(e.type)&&(Hn(e.type.childType)||ki(e.type.childType))||Er(e.type)&&e.type.typeName==="str")&&Et(t.type))return!0;if(jn(e.type)&&jn(t.type))return e.type.tag===t.type.tag;if(Lt(e.type)&&Lt(t.type))return!0;if(Vt(e.type)&&Vt(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(ke(e.type)&&ke(t.type))return At({value:e.type.length,env:e.env},{value:t.type.length,env:t.env})&&Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(Qe(e.type)&&Qe(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(we(e.type)&&we(t.type)){if(e.type.fields.length!==t.type.fields.length)return!1;for(let a=0;a<e.type.fields.length;a++){let s=e.type.fields[a],l=t.type.fields[a];if(!Y({type:s.type,env:e.env},{type:l.type,env:t.env},n,r))return!1}return!0}if(ce(e.type)&&ce(t.type)){if(e.type.fields.length!==t.type.fields.length||e.type.id!==t.type.id&&!Fe(e.type)&&!Fe(t.type)&&!(e.type.functionValue&&t.type.functionValue&&e.type.functionValue.funcId===t.type.functionValue.funcId))return!1;if(e.type.id===t.type.id)return!0;for(let a=0;a<e.type.fields.length;a++){let s=e.type.fields[a],l=t.type.fields[a];if(s.label!==l.label||!Y({type:s.type,env:e.env},{type:l.type,env:t.env},n,r))return!1}return!0}if(ge(e.type)&&ge(t.type)){if(e.type.id===t.type.id)return!0;if(e.type.variants.length!==t.type.variants.length)return!1;for(let a=0;a<e.type.variants.length;a++){let s=e.type.variants[a],l=t.type.variants[a];if(s.name!==l.name||s.fields?.length!==l.fields?.length)return!1;if(s.fields)for(let u=0;u<s.fields.length;u++){let c=s.fields[u],_=l.fields[u];if(c.label!==_.label||!Y({type:c.type,env:e.env},{type:_.type,env:t.env},n,r))return!1}}return e.type.requiredVariantNames&&(t.type.selectedVariantName&&!e.type.requiredVariantNames.includes(t.type.selectedVariantName)||!t.type.selectedVariantName)?!1:!e.type.selectedVariantName}if(it(e.type)&&it(t.type)){if(e.type.fields.length!==t.type.fields.length||e.type.id!==t.type.id&&!Fe(e.type)&&!Fe(t.type))return!1;if(e.type.id===t.type.id)return!0;for(let a=0;a<e.type.fields.length;a++){let s=e.type.fields[a],l=t.type.fields[a];if(s.label!==l.label||!Y({type:s.type,env:e.env},{type:l.type,env:t.env},n,r))return!1}return!0}if(Te(e.type)&&Te(t.type)){for(let a of e.type.fields){let s=t.type.fields.find(l=>l.label===a.label);if(!s||!Y({type:a.type,env:e.env},{type:s.type,env:t.env},n,r))return!1}return!0}if(De(e.type)){if(De(t.type)){if(bt(e.type))return!(!bt(t.type)||!Ru({type:e.type.isFn.callType,env:e.env},{type:t.type.isFn.callType,env:t.env},n));if(Kt(e.type)){if(!Kt(t.type)||!Y({type:e.type.isFuture.outputType,env:e.env},{type:t.type.isFuture.outputType,env:t.env},n,r))return!1;let a=Zs(e.type.isFuture.effects),s=Zs(t.type.isFuture.effects);if(a.length>0&&s.length>0){if(a.length!==s.length)return!1;let l=new Set;for(let u of a){let c=!1;for(let _=0;_<s.length;_++)if(!l.has(_)&&Y({type:u.type,env:e.env},{type:s[_].type,env:t.env},n,r)){l.add(_),c=!0;break}if(!c)return!1}}return!0}return e.type.id===t.type.id}return He(t.type)&&t.type.baseType&&t.type.baseType.trait&&De(e.type)?Y({type:e.type,env:e.env},{type:t.type.baseType.trait,env:t.env},n,r):!1}if(G(e.type)&&G(t.type))return Ru({type:e.type,env:e.env},{type:t.type,env:t.env},n);if(He(e.type)&&He(t.type))return Mu(e.type,t.type);if(Ie(e.type)&&Ie(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},!0,r);if(kt(e.type)&&kt(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if($t(e.type)&&$t(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(e.type.tag==="void"&&t.type.tag==="void")return!0;if(be(e.type)&&be(t.type)){for(let{traitType:a}of e.type.requiredTraits)if(!t.type.requiredTraits.find(({traitType:l})=>Y({type:a,env:e.env},{type:l,env:t.env},n,r)))return!1;if(e.type.negativeTraits&&e.type.negativeTraits.length>0){for(let{traitType:a}of e.type.negativeTraits)if(t.type.requiredTraits.find(({traitType:l})=>Y({type:a,env:e.env},{type:l,env:t.env},n,r)))return!1}return!0}if(x(e.type)){if(be(t.type))return!0;if(x(t.type)){if(e.type===t.type)return!0;if(e.type.id===t.type.id)return e.type.resolvedConcreteType?t.type.resolvedConcreteType?Y({type:e.type.resolvedConcreteType,env:e.env},{type:t.type.resolvedConcreteType,env:t.env},n,r):!1:!0;let a=Qs(e.env,e.type),s=Qs(t.env,t.type);if(n&&a.length!==s.length)return!1;for(let u of a)if(!s.find(_=>Y({type:u,env:e.env},{type:_,env:t.env},n,r)))return!1;let l=Ou(e.env,e.type);if(l.length>0){for(let u of l)if(s.find(_=>Y({type:u,env:e.env},{type:_,env:t.env},n,r)))return!1}if(e.type.resolvedConcreteType&&t.type.resolvedConcreteType){if(!Y({type:e.type.resolvedConcreteType,env:e.env},{type:t.type.resolvedConcreteType,env:t.env},n,r))return!1}else if(n&&(e.type.resolvedConcreteType||t.type.resolvedConcreteType))return!1;return!0}else{if(e.type.resolvedConcreteType)return Y({type:e.type.resolvedConcreteType,env:e.env},t,n,r);let a=Qs(e.env,e.type);if(a.length===0)return!n;if(a.length>0){for(let c of a)if(!St({targetType:t.type,traitType:c,env:e.env}))break;let l=Ou(e.env,e.type);if(l.length>0){for(let c of l)if(St({targetType:t.type,traitType:c,env:e.env}))return!1}let u=!0;for(let c of a)if(!St({targetType:t.type,traitType:c,env:e.env})){u=!1;break}if(u)return!0}let s=Ot(e.env,e.type);return e.type===s?!1:Y({type:s,env:e.env},t,n,r)}}else if(x(t.type)){if(t.type.resolvedConcreteType&&Y(e,{type:t.type.resolvedConcreteType,env:t.env},n,r))return!0;let a=Ot(t.env,t.type);return t.type===a?!1:Y(e,{type:a,env:t.env},n,r)}return!1}function Ru(e,t,n=!1){if(e.type===t.type)return!0;if(e.type.parameters.length!==t.type.parameters.length||e.type.forallParameters.length!==t.type.forallParameters.length)return!1;try{let{expectedEnv:i,givenEnv:o}=Ze({type:e.type,env:e.env},{type:t.type,env:t.env});e.env=i,t.env=o}catch{return!1}for(let i=0;i<e.type.forallParameters.length;i++){let o=e.type.forallParameters[i],a=t.type.forallParameters[i];if(!Y({type:o.type,env:e.env},{type:a.type,env:t.env},n))return!1}for(let i=0;i<e.type.parameters.length;i++){let o=e.type.parameters[i],a=t.type.parameters[i];if(o.isCompileTimeOnly!==a.isCompileTimeOnly||!Y({type:o.type,env:e.env},{type:a.type,env:t.env},n))return!1}return Y({type:e.type.return.type,env:e.env},{type:t.type.return.type,env:t.env},n)}function ba(e){return E(e,["->","=>"])?!!(e.$?.isAnonymousFunctionDefinition===!0||F(e)&&F(e.func)&&(E(e.func,I.fn)||E(e.func,I.unsafe_fn)||E(e.func,I.Fn))||!e.$):!1}function ka(e,t){if(!F(e))return!1;if(t(e.func))return!0;for(let n of e.args)if(F(n)&&E(n,"=>")){for(let r of n.args)if(t(r))return!0}else if(t(n))return!0;return!1}function Qn(e){if(z(e))return dt(e,I.escape);if(F(e)){if(e.$?.macroExpansion)return Qn(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,Qn);if(ba(e)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(Qn(e.func))return!0;for(let t of e.args)if(Qn(t))return!0}return!1}function Yi(e){if(z(e))return dt(e,I.return)||dt(e,I.escape);if(F(e)){if(E(e,I.return)||E(e,I.escape))return!0;if(e.$?.macroExpansion)return Yi(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,Yi);if(ba(e)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(Yi(e.func))return!0;for(let t of e.args)if(Yi(t))return!0}return!1}function un(e){if(F(e)){if(e.func.$?.type?.ioBuiltin==="io_await")return!0;if(e.$?.macroExpansion)return un(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,un);if(e.func.$?.type?.ioBuiltin==="io_async"||ba(e)||O(e.func.$?.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(un(e.func))return!0;for(let t of e.args)if(un(t))return!0}return!1}function Hi(e){if(z(e))return dt(e,I.break)||dt(e,I.return)||dt(e,I.escape);if(F(e)){if(E(e,I.return)||E(e,I.escape))return!0;if(e.$?.macroExpansion)return Hi(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,Hi);if(ba(e)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(Hi(e.func))return!0;for(let t of e.args)if(Hi(t))return!0}return!1}var H={tag:"Unit",type:xn()};function Mo(e){if(e&&e.tag==="FnCall"&&E(e,":=")){let t=e.args[0];if(t&&t.tag==="Atom"&&t.token.type==="identifier"&&t.$){let n=t.token.value,r=X(t.$.env,n);if(r.length>0)return r[r.length-1].id}}}function wa(e,t){let n=[],r=new Map,i=new Map,o=new Map;if(yr(e,n,r,i,o,t),e.$?.deferredDropExpressions)for(let a of e.$.deferredDropExpressions)yr(a,n,r,i,o,t);return n.length===0&&r.clear(),{suspensionPoints:n,capturedVariables:Array.from(r.values()),hasSuspensions:n.length>0,variableIdRemapping:o}}function yr(e,t,n,r,i,o,a){switch(e.tag){case"Atom":if(e.$&&e.token.type==="identifier"){let s=e.token.value,l=e.$.type,u=X(e.$.env,s);if(u.length>0){let c=u[u.length-1];if(c&&!n.has(c.id)&&!c.isCompileTimeOnly){let _=`${c.name}:${c.frameLevel}`,p=r.get(_);if(p&&p!==c.id)i.set(c.id,p);else if(c.isOwningTheSameRcValueAs){let f=c.isOwningTheSameRcValueAs;if(!n.has(f.id)){let m={id:f.id,name:f.name,type:f.type,isOwningTheSameRcValueAs:void 0};n.set(f.id,m);let g=`${f.name}:${f.frameLevel}`;r.has(g)||r.set(g,f.id)}}else n.set(c.id,{id:c.id,name:s,type:l,isOwningTheSameRcValueAs:void 0}),r.has(_)||r.set(_,c.id)}}}break;case"FnCall":{if(E(e,I.while)){let s=t.length;yr(e.func,t,n,r,i,o,e);for(let u of e.args)yr(u,t,n,r,i,o,e);let l=t.length;if(l>s)for(let u=s;u<l;u++)t[u].isInsideWhile=!0,t[u].whileNestingDepth=(t[u].whileNestingDepth??0)+1,t[u].enclosingWhileExpr||(t[u].enclosingWhileExpr=e);break}if(E(e,I.cond)){Pu(e,t,n,r,i,o);break}if(E(e,I.match)){Pu(e,t,n,r,i,o);break}if(o.detect(e,a,t),o.shouldSkipBody(e)){if(e.$?.deferredDupExpressions)for(let s of e.$.deferredDupExpressions)yr(s,t,n,r,i,o,e);break}yr(e.func,t,n,r,i,o,e);for(let s of e.args)yr(s,t,n,r,i,o,e);if(e.$?.deferredDropExpressions)for(let s of e.$.deferredDropExpressions)yr(s,t,n,r,i,o,e);break}}}function Pu(e,t,n,r,i,o){if(e.tag!=="FnCall")return;let a=t.length;yr(e.func,t,n,r,i,o,e);let s=new Map(r),l=[];for(let c of e.args){let _=t.length;yr(c,t,n,r,i,o,e),l.push(t.slice(_))}r.clear();for(let[c,_]of s)r.set(c,_);let u=Math.max(...l.map(c=>c.length),0);if(u>0){t.splice(a);let c=a;for(let _=0;_<u;_++){let p;for(let f of l)if(_<f.length){p=f[_];break}p&&(p.index=t.length,p.isInsideCond=!0,_===0&&(p.needsOwnCondBranchField=!0),_>0&&(p.condBranchSourceIndex=c),t.push(p))}}}function Uu(e){let n=wa(e,{detect(i,o,a){if(i.tag==="FnCall"&&pn(i)){let s=i.args[0];if(!s)return;let l=s.$?.type;if(l&&Ce(l)){let u=Dt(l);if(!u)return;let c=u.isFuture.outputType,_;if(s.tag==="Atom"&&s.token.type==="identifier"&&s.$){let f=s.token.value,m=X(s.$.env,f);if(m.length>0){let g=m[m.length-1];g.isOwningTheSameRcValueAs?_=g.isOwningTheSameRcValueAs.id:_=g.id}}let p=Mo(o);a.push({index:a.length,expr:i,resultType:c,futureType:u,targetVariableId:p,futureVariableId:_})}}},shouldSkipBody(i){return Rt(i)}}),r=n.capturedVariables.map(i=>({id:i.id,name:i.name,type:i.type,kind:"local",isOwningTheSameRcValueAs:void 0}));return{awaitPoints:n.suspensionPoints,capturedVariables:r,hasAwaits:n.hasSuspensions,variableIdRemapping:n.variableIdRemapping}}function Rt(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_async"}function pn(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_await"}function zu(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_state"}function Fa(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_spawn"}function Bu(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="join_handle_await"}function je(e){return z(e)&&e.token.type==="identifier"||e.token.type==="operator"}function Oo(e,t,n){if(!e.$?.variableName)return;let r=X(t,e.$.variableName);if(!r.length)return;let i=r[r.length-1],o=new Set;for(;i&&i.isOwningTheSameRcValueAs;){if(o.has(i.id))return;o.add(i.id),i=i.isOwningTheSameRcValueAs}if(i&&i.isOwningTheRcValue)return i}function Br(e){let t=e.$?.env;if(!t)return;let n;if(e.$?.pathCollection)for(let r of e.$.pathCollection)r.length>0&&typeof r[0]=="string"&&(n=r[0]);else z(e)&&(n=e.token.value);if(n){let r=X(t,n),i=r[r.length-1];if(i?.isImplicit)throw y({token:e.token,errorMessage:`Cannot use implicit variable "${i.name}" in assignment. Implicit variables must be passed via using() parameters.`})}}var La=!0;function Gu({variablesToDrop:e,env:t,context:n}){let r=[],i=t;for(let o of e){let a=Jt(`${k.___drop[0]}(${o.name})`),s=S({expr:a,env:i,context:{...n,expectedType:{env:i,type:H.type}}});r.push(s),s.$&&s.$.env&&(i=s.$.env)}return{deferredDropExpressions:r.length>0?r:void 0,env:i}}function Ro(e,t,n){if(F(e)&&Rt(e))return;if(e.$?.deferredDupExpressions)for(let s of e.$.deferredDupExpressions)Ro(s,t,n);if(F(e)&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[0])&&z(e.func.args[1])&&e.func.args[1].token.value===k.___dup[0]&&e.args.length===0&&e.$?.env){let s=e.func.args[0].token.value,l=X(e.$.env,s);if(l.length>0){let u=l[l.length-1];t.has(u.id)||t.set(u.id,[]),t.get(u.id).push(e)}return}if(F(e)&&E(e,I.while))return;function i(s){if(nt(s.$?.controlFlow))return!0;if(F(s)&&E(s,I.begin)){let l=s.args[s.args.length-1];if(nt(l?.$?.controlFlow)||F(l)&&E(l,I.return))return!0}return!!(F(s)&&E(s,I.return))}function o(s){if(F(s)&&E(s,I.tuple,0))return!0;if(F(s)&&E(s,I.begin)){if(s.args.length===0)return!0;if(s.args.length===1){let l=s.args[0];if(F(l)&&E(l,I.tuple,0))return!0}}return!1}function a(s,l){let u=[],c=[],_=[];for(let f=l;f<s.args.length;f++){let m=s.args[f];if(F(m)&&E(m,"=>",2)){let g=m.args[1],h=Wu(g);u.push(h),c.push(i(g)),_.push(o(g))}}let p=new Set;for(let f of u){for(let m of f.dupCalls.keys())p.add(m);for(let m of f.varsWithPartialBranchDups)n.add(m)}if(u.length>0)for(let f of p){let m=[],g=[];for(let h=0;h<u.length;h++){let d=u[h],v=d.dupCalls.has(f),T=c[h];if(v){let $=d.dupCalls.get(f);T?m.push(...$):g.push(...$)}}for(let h of m)t.has(f)||t.set(f,[]),h.__isEarlyReturnDup=!0,t.get(f).push(h);if(g.length>0){let h=0,d=0;for(let v=0;v<u.length;v++)c[v]||(h++,u[v].dupCalls.has(f)&&d++);if(d===h){t.has(f)||t.set(f,[]);for(let v of g)t.get(f).push(v)}else n.add(f)}}}if(F(e)&&E(e,I.cond)){a(e,0);return}if(F(e)&&E(e,I.match)){e.args[0]&&Ro(e.args[0],t,n),a(e,1);return}if(F(e)){Ro(e.func,t,n);for(let s of e.args)Ro(s,t,n)}}function Wu(e){let t=new Map,n=new Set;return Ro(e,t,n),{dupCalls:t,varsWithPartialBranchDups:n}}function Aa(e){return F(e)&&E(e,I.tuple,0)}function Js(e,t){if(e.$?.deferredDupExpressions&&(e.$.deferredDupExpressions=e.$.deferredDupExpressions.filter(n=>!t.has(n)),e.$.deferredDupExpressions.length===0&&(e.$.deferredDupExpressions=void 0)),F(e)){Js(e.func,t);for(let n of e.args)Js(n,t)}}function ht({expr:e,env:t,context:n,variablesToAdd:r=[],isEvaluatingFunctionBodyBeginBlock:i=!1}){if(F(e)&&E(e,"_")&&!E(e,I.begin)){let $=e;$.args.some(L=>F(L)&&E(L,":"))||($.func={...$.func,token:{...$.func.token,value:I.begin[0]}})}if(!F(e)||!E(e,I.begin)){let $={tag:"FnCall",func:{tag:"Atom",token:{...e.token,value:I.begin[0]}},args:[Ae(e)],token:{...e.token,value:I.begin[0]}};dr(e,$),e=e}let o=e.args,a=n.expectedType;if(o.length===0)return e.$={env:t,type:H.type,value:H,pathCollection:[]},e;t=Pe(t,void 0,!0);for(let $=0;$<r.length;$++){let C=r[$],{env:L}=me({env:t,variable:C});t=L}let s=o[o.length-1],l,u=!1;for(let $=0;$<o.length;$++){let C=o[$];if(z(C)&&dt(C,I.return)||F(C)&&E(C,I.return)){if($!==o.length-1&&!($===o.length-2&&Aa(o[o.length-1])))throw y({token:C.token,errorMessage:'The "return" keyword can only be used as the last expression.'});if(F(C)&&he(C,I.return,1),!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:C.token,errorMessage:'The "return" keyword can only be used inside a function body or async block.'});if(l=C,z(C)){C.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:zr("return")},s=C;break}else{he(C,I.return,1);let L=C.args[0],b=S({expr:L,env:t,context:{...n,expectedType:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?{type:n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type,env:t}:n.expectedType}});if(!b.$)throw y({token:L.token,errorMessage:`Return expression is not evaluated correctly:
151
+ Given: "${A(t.type)}"`)}}}return{expectedEnv:e.env,givenEnv:t.env}}function Xs(e,t,n,r,i){if(e.length===0&&t.length===0)return;let o=[],a=[],s=[];for(let c of e)c.isEffectRowSpread?ot(c.type)?a.push(c):x(c.type)&&c.type.isEffectsRow&&s.push(c):o.push(c);if(s.length>1)throw new Error(`Ambiguous effect row unification: multiple unsolved effect row variables (${s.map(c=>c.label).join(", ")}). At most one effect row spread can be unsolved during type unification.`);let l=[];for(let c of t)c.isEffectRowSpread?ot(c.type)&&l.push(...c.type.implicitParameters):l.push(c);let u=new Set;for(let c of o)for(let _=0;_<l.length;_++)if(!u.has(_)&&c.type.id===l[_].type.id){let{expectedEnv:p,givenEnv:f}=Ze({type:c.type,env:n.env},{type:l[_].type,env:r.env},i);n.env=p,r.env=f,u.add(_);break}for(let c of a){let _=c.type.implicitParameters;for(let p of _)for(let f=0;f<l.length;f++)if(!u.has(f)&&p.type.id===l[f].type.id){let{expectedEnv:m,givenEnv:g}=Ze({type:p.type,env:n.env},{type:l[f].type,env:r.env},i);n.env=m,r.env=g,u.add(f);break}}if(s.length===1){let c=s[0],_=[];for(let p=0;p<l.length;p++)u.has(p)||_.push(l[p]);if(x(c.type)&&c.type.isEffectsRow){let p=Lr(_),f=ee(p),m=X(n.env,c.type.name),g=m[m.length-1];if(g)n.env=Be(n.env,g,{...g,value:[f]});else{let{env:h}=me({env:n.env,variable:{name:c.type.name,value:[f],type:f.type,isCompileTimeOnly:!0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});n.env=h}}}}function Qs(e,t){let n=new Map;for(let i of t.requiredTraits??[])n.set(i.traitType.id,i.traitType);let r=Wn(e,t);if(r)for(let i of r.requiredTraits)n.set(i.id,i);return[...n.values()]}function Ou(e,t){let n=new Map;for(let i of t.negativeTraits??[])n.set(i.traitType.id,i.traitType);let r=Wn(e,t);if(r)for(let i of r.negativeTraits)n.set(i.id,i);return[...n.values()]}function Zs(e){let t=[];for(let n of e)n.isEffectRowSpread&&ot(n.type)?t.push(...Zs(n.type.implicitParameters)):(n.isEffectRowSpread&&x(n.type)&&n.type.isEffectsRow,t.push(n));return t}function Y(e,t,n=!1,r=new Set){let i=e.type.id,o=t.type.id;if(i&&o&&(ce(e.type)||ge(e.type)||it(e.type))&&(ce(t.type)||ge(t.type)||it(t.type))){let a=`${i}:${o}`;if(r.has(a))return!0;r.add(a)}if(go(e.type)&&go(t.type))return e.type.tag===t.type.tag;if((vt(e.type)||e.type.tag==="u8"||e.type.tag==="i8"||e.type.tag==="u16"||e.type.tag==="i16"||e.type.tag==="u32"||e.type.tag==="i32"||e.type.tag==="u64"||e.type.tag==="i64"||e.type.tag==="usize"||e.type.tag==="isize"||jn(e.type))&&vt(t.type))return!(n&&!vt(e.type));if((Nt(e.type)||e.type.tag==="f32"||e.type.tag==="f64")&&Nt(t.type))return!(n&&!Nt(e.type));if((Et(e.type)||Qe(e.type)&&Hn(e.type.childType)||Ie(e.type)&&(Hn(e.type.childType)||ki(e.type.childType))||Er(e.type)&&e.type.typeName==="str")&&Et(t.type))return!0;if(jn(e.type)&&jn(t.type))return e.type.tag===t.type.tag;if(Lt(e.type)&&Lt(t.type))return!0;if(Vt(e.type)&&Vt(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(ke(e.type)&&ke(t.type))return At({value:e.type.length,env:e.env},{value:t.type.length,env:t.env})&&Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(Qe(e.type)&&Qe(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(we(e.type)&&we(t.type)){if(e.type.fields.length!==t.type.fields.length)return!1;for(let a=0;a<e.type.fields.length;a++){let s=e.type.fields[a],l=t.type.fields[a];if(!Y({type:s.type,env:e.env},{type:l.type,env:t.env},n,r))return!1}return!0}if(ce(e.type)&&ce(t.type)){if(e.type.fields.length!==t.type.fields.length||e.type.id!==t.type.id&&!Fe(e.type)&&!Fe(t.type)&&!(e.type.functionValue&&t.type.functionValue&&e.type.functionValue.funcId===t.type.functionValue.funcId))return!1;if(e.type.id===t.type.id)return!0;for(let a=0;a<e.type.fields.length;a++){let s=e.type.fields[a],l=t.type.fields[a];if(s.label!==l.label||!Y({type:s.type,env:e.env},{type:l.type,env:t.env},n,r))return!1}return!0}if(ge(e.type)&&ge(t.type)){if(e.type.id===t.type.id)return!0;if(e.type.variants.length!==t.type.variants.length)return!1;for(let a=0;a<e.type.variants.length;a++){let s=e.type.variants[a],l=t.type.variants[a];if(s.name!==l.name||s.fields?.length!==l.fields?.length)return!1;if(s.fields)for(let u=0;u<s.fields.length;u++){let c=s.fields[u],_=l.fields[u];if(c.label!==_.label||!Y({type:c.type,env:e.env},{type:_.type,env:t.env},n,r))return!1}}return e.type.requiredVariantNames&&(t.type.selectedVariantName&&!e.type.requiredVariantNames.includes(t.type.selectedVariantName)||!t.type.selectedVariantName)?!1:!e.type.selectedVariantName}if(it(e.type)&&it(t.type)){if(e.type.fields.length!==t.type.fields.length||e.type.id!==t.type.id&&!Fe(e.type)&&!Fe(t.type))return!1;if(e.type.id===t.type.id)return!0;for(let a=0;a<e.type.fields.length;a++){let s=e.type.fields[a],l=t.type.fields[a];if(s.label!==l.label||!Y({type:s.type,env:e.env},{type:l.type,env:t.env},n,r))return!1}return!0}if(Te(e.type)&&Te(t.type)){for(let a of e.type.fields){let s=t.type.fields.find(l=>l.label===a.label);if(!s||!Y({type:a.type,env:e.env},{type:s.type,env:t.env},n,r))return!1}return!0}if(De(e.type)){if(De(t.type)){if(kt(e.type))return!(!kt(t.type)||!Ru({type:e.type.isFn.callType,env:e.env},{type:t.type.isFn.callType,env:t.env},n));if(Kt(e.type)){if(!Kt(t.type)||!Y({type:e.type.isFuture.outputType,env:e.env},{type:t.type.isFuture.outputType,env:t.env},n,r))return!1;let a=Zs(e.type.isFuture.effects),s=Zs(t.type.isFuture.effects);if(a.length>0&&s.length>0){if(a.length!==s.length)return!1;let l=new Set;for(let u of a){let c=!1;for(let _=0;_<s.length;_++)if(!l.has(_)&&Y({type:u.type,env:e.env},{type:s[_].type,env:t.env},n,r)){l.add(_),c=!0;break}if(!c)return!1}}return!0}return e.type.id===t.type.id}return He(t.type)&&t.type.baseType&&t.type.baseType.trait&&De(e.type)?Y({type:e.type,env:e.env},{type:t.type.baseType.trait,env:t.env},n,r):!1}if(G(e.type)&&G(t.type))return Ru({type:e.type,env:e.env},{type:t.type,env:t.env},n);if(He(e.type)&&He(t.type))return Mu(e.type,t.type);if(Ie(e.type)&&Ie(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},!0,r);if(wt(e.type)&&wt(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(Ct(e.type)&&Ct(t.type))return Y({type:e.type.childType,env:e.env},{type:t.type.childType,env:t.env},n,r);if(e.type.tag==="void"&&t.type.tag==="void")return!0;if(be(e.type)&&be(t.type)){for(let{traitType:a}of e.type.requiredTraits)if(!t.type.requiredTraits.find(({traitType:l})=>Y({type:a,env:e.env},{type:l,env:t.env},n,r)))return!1;if(e.type.negativeTraits&&e.type.negativeTraits.length>0){for(let{traitType:a}of e.type.negativeTraits)if(t.type.requiredTraits.find(({traitType:l})=>Y({type:a,env:e.env},{type:l,env:t.env},n,r)))return!1}return!0}if(x(e.type)){if(be(t.type))return!0;if(x(t.type)){if(e.type===t.type)return!0;if(e.type.id===t.type.id)return e.type.resolvedConcreteType?t.type.resolvedConcreteType?Y({type:e.type.resolvedConcreteType,env:e.env},{type:t.type.resolvedConcreteType,env:t.env},n,r):!1:!0;let a=Qs(e.env,e.type),s=Qs(t.env,t.type);if(n&&a.length!==s.length)return!1;for(let u of a)if(!s.find(_=>Y({type:u,env:e.env},{type:_,env:t.env},n,r)))return!1;let l=Ou(e.env,e.type);if(l.length>0){for(let u of l)if(s.find(_=>Y({type:u,env:e.env},{type:_,env:t.env},n,r)))return!1}if(e.type.resolvedConcreteType&&t.type.resolvedConcreteType){if(!Y({type:e.type.resolvedConcreteType,env:e.env},{type:t.type.resolvedConcreteType,env:t.env},n,r))return!1}else if(n&&(e.type.resolvedConcreteType||t.type.resolvedConcreteType))return!1;return!0}else{if(e.type.resolvedConcreteType)return Y({type:e.type.resolvedConcreteType,env:e.env},t,n,r);let a=Qs(e.env,e.type);if(a.length===0)return!n;if(a.length>0){for(let c of a)if(!St({targetType:t.type,traitType:c,env:e.env}))break;let l=Ou(e.env,e.type);if(l.length>0){for(let c of l)if(St({targetType:t.type,traitType:c,env:e.env}))return!1}let u=!0;for(let c of a)if(!St({targetType:t.type,traitType:c,env:e.env})){u=!1;break}if(u)return!0}let s=Ot(e.env,e.type);return e.type===s?!1:Y({type:s,env:e.env},t,n,r)}}else if(x(t.type)){if(t.type.resolvedConcreteType&&Y(e,{type:t.type.resolvedConcreteType,env:t.env},n,r))return!0;let a=Ot(t.env,t.type);return t.type===a?!1:Y(e,{type:a,env:t.env},n,r)}return!1}function Ru(e,t,n=!1){if(e.type===t.type)return!0;if(e.type.parameters.length!==t.type.parameters.length||e.type.forallParameters.length!==t.type.forallParameters.length)return!1;try{let{expectedEnv:i,givenEnv:o}=Ze({type:e.type,env:e.env},{type:t.type,env:t.env});e.env=i,t.env=o}catch{return!1}for(let i=0;i<e.type.forallParameters.length;i++){let o=e.type.forallParameters[i],a=t.type.forallParameters[i];if(!Y({type:o.type,env:e.env},{type:a.type,env:t.env},n))return!1}for(let i=0;i<e.type.parameters.length;i++){let o=e.type.parameters[i],a=t.type.parameters[i];if(o.isCompileTimeOnly!==a.isCompileTimeOnly||!Y({type:o.type,env:e.env},{type:a.type,env:t.env},n))return!1}return Y({type:e.type.return.type,env:e.env},{type:t.type.return.type,env:t.env},n)}function ba(e){return E(e,["->","=>"])?!!(e.$?.isAnonymousFunctionDefinition===!0||F(e)&&F(e.func)&&(E(e.func,I.fn)||E(e.func,I.unsafe_fn)||E(e.func,I.Fn))||!e.$):!1}function ka(e,t){if(!F(e))return!1;if(t(e.func))return!0;for(let n of e.args)if(F(n)&&E(n,"=>")){for(let r of n.args)if(t(r))return!0}else if(t(n))return!0;return!1}function Qn(e){if(z(e))return dt(e,I.escape);if(F(e)){if(e.$?.macroExpansion)return Qn(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,Qn);if(ba(e)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(Qn(e.func))return!0;for(let t of e.args)if(Qn(t))return!0}return!1}function Yi(e){if(z(e))return dt(e,I.return)||dt(e,I.escape);if(F(e)){if(E(e,I.return)||E(e,I.escape))return!0;if(e.$?.macroExpansion)return Yi(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,Yi);if(ba(e)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(Yi(e.func))return!0;for(let t of e.args)if(Yi(t))return!0}return!1}function un(e){if(F(e)){if(e.func.$?.type?.ioBuiltin==="io_await")return!0;if(e.$?.macroExpansion)return un(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,un);if(e.func.$?.type?.ioBuiltin==="io_async"||ba(e)||O(e.func.$?.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(un(e.func))return!0;for(let t of e.args)if(un(t))return!0}return!1}function Hi(e){if(z(e))return dt(e,I.break)||dt(e,I.return)||dt(e,I.escape);if(F(e)){if(E(e,I.return)||E(e,I.escape))return!0;if(e.$?.macroExpansion)return Hi(e.$.macroExpansion);if(E(e,I.cond)||E(e,I.match))return ka(e,Hi);if(ba(e)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&G(e.func.$.value.value)||F(e.func)&&e.func.$?.value!==void 0&&O(e.func.$.value)&&Wt(e.func.$.value.value))return!1;if(Hi(e.func))return!0;for(let t of e.args)if(Hi(t))return!0}return!1}var H={tag:"Unit",type:xn()};function Mo(e){if(e&&e.tag==="FnCall"&&E(e,":=")){let t=e.args[0];if(t&&t.tag==="Atom"&&t.token.type==="identifier"&&t.$){let n=t.token.value,r=X(t.$.env,n);if(r.length>0)return r[r.length-1].id}}}function wa(e,t){let n=[],r=new Map,i=new Map,o=new Map;if(yr(e,n,r,i,o,t),e.$?.deferredDropExpressions)for(let a of e.$.deferredDropExpressions)yr(a,n,r,i,o,t);return n.length===0&&r.clear(),{suspensionPoints:n,capturedVariables:Array.from(r.values()),hasSuspensions:n.length>0,variableIdRemapping:o}}function yr(e,t,n,r,i,o,a){switch(e.tag){case"Atom":if(e.$&&e.token.type==="identifier"){let s=e.token.value,l=e.$.type,u=X(e.$.env,s);if(u.length>0){let c=u[u.length-1];if(c&&!n.has(c.id)&&!c.isCompileTimeOnly){let _=`${c.name}:${c.frameLevel}`,p=r.get(_);if(p&&p!==c.id)i.set(c.id,p);else if(c.isOwningTheSameRcValueAs){let f=c.isOwningTheSameRcValueAs;if(!n.has(f.id)){let m={id:f.id,name:f.name,type:f.type,isOwningTheSameRcValueAs:void 0};n.set(f.id,m);let g=`${f.name}:${f.frameLevel}`;r.has(g)||r.set(g,f.id)}}else n.set(c.id,{id:c.id,name:s,type:l,isOwningTheSameRcValueAs:void 0}),r.has(_)||r.set(_,c.id)}}}break;case"FnCall":{if(E(e,I.while)){let s=t.length;yr(e.func,t,n,r,i,o,e);for(let u of e.args)yr(u,t,n,r,i,o,e);let l=t.length;if(l>s)for(let u=s;u<l;u++)t[u].isInsideWhile=!0,t[u].whileNestingDepth=(t[u].whileNestingDepth??0)+1,t[u].enclosingWhileExpr||(t[u].enclosingWhileExpr=e);break}if(E(e,I.cond)){Pu(e,t,n,r,i,o);break}if(E(e,I.match)){Pu(e,t,n,r,i,o);break}if(o.detect(e,a,t),o.shouldSkipBody(e)){if(e.$?.deferredDupExpressions)for(let s of e.$.deferredDupExpressions)yr(s,t,n,r,i,o,e);break}yr(e.func,t,n,r,i,o,e);for(let s of e.args)yr(s,t,n,r,i,o,e);if(e.$?.deferredDropExpressions)for(let s of e.$.deferredDropExpressions)yr(s,t,n,r,i,o,e);break}}}function Pu(e,t,n,r,i,o){if(e.tag!=="FnCall")return;let a=t.length;yr(e.func,t,n,r,i,o,e);let s=new Map(r),l=[];for(let c of e.args){let _=t.length;yr(c,t,n,r,i,o,e),l.push(t.slice(_))}r.clear();for(let[c,_]of s)r.set(c,_);let u=Math.max(...l.map(c=>c.length),0);if(u>0){t.splice(a);let c=a;for(let _=0;_<u;_++){let p;for(let f of l)if(_<f.length){p=f[_];break}p&&(p.index=t.length,p.isInsideCond=!0,_===0&&(p.needsOwnCondBranchField=!0),_>0&&(p.condBranchSourceIndex=c),t.push(p))}}}function Uu(e){let n=wa(e,{detect(i,o,a){if(i.tag==="FnCall"&&pn(i)){let s=i.args[0];if(!s)return;let l=s.$?.type;if(l&&Ce(l)){let u=Dt(l);if(!u)return;let c=u.isFuture.outputType,_;if(s.tag==="Atom"&&s.token.type==="identifier"&&s.$){let f=s.token.value,m=X(s.$.env,f);if(m.length>0){let g=m[m.length-1];g.isOwningTheSameRcValueAs?_=g.isOwningTheSameRcValueAs.id:_=g.id}}let p=Mo(o);a.push({index:a.length,expr:i,resultType:c,futureType:u,targetVariableId:p,futureVariableId:_})}}},shouldSkipBody(i){return Rt(i)}}),r=n.capturedVariables.map(i=>({id:i.id,name:i.name,type:i.type,kind:"local",isOwningTheSameRcValueAs:void 0}));return{awaitPoints:n.suspensionPoints,capturedVariables:r,hasAwaits:n.hasSuspensions,variableIdRemapping:n.variableIdRemapping}}function Rt(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_async"}function pn(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_await"}function zu(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_state"}function Fa(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="io_spawn"}function Bu(e){return e.tag!=="FnCall"?!1:e.func.$?.type?.ioBuiltin==="join_handle_await"}function je(e){return z(e)&&e.token.type==="identifier"||e.token.type==="operator"}function Oo(e,t,n){if(!e.$?.variableName)return;let r=X(t,e.$.variableName);if(!r.length)return;let i=r[r.length-1],o=new Set;for(;i&&i.isOwningTheSameRcValueAs;){if(o.has(i.id))return;o.add(i.id),i=i.isOwningTheSameRcValueAs}if(i&&i.isOwningTheRcValue)return i}function Br(e){let t=e.$?.env;if(!t)return;let n;if(e.$?.pathCollection)for(let r of e.$.pathCollection)r.length>0&&typeof r[0]=="string"&&(n=r[0]);else z(e)&&(n=e.token.value);if(n){let r=X(t,n),i=r[r.length-1];if(i?.isImplicit)throw y({token:e.token,errorMessage:`Cannot use implicit variable "${i.name}" in assignment. Implicit variables must be passed via using() parameters.`})}}var La=!0;function Gu({variablesToDrop:e,env:t,context:n}){let r=[],i=t;for(let o of e){let a=Jt(`${k.___drop[0]}(${o.name})`),s=S({expr:a,env:i,context:{...n,expectedType:{env:i,type:H.type}}});r.push(s),s.$&&s.$.env&&(i=s.$.env)}return{deferredDropExpressions:r.length>0?r:void 0,env:i}}function Ro(e,t,n){if(F(e)&&Rt(e))return;if(e.$?.deferredDupExpressions)for(let s of e.$.deferredDupExpressions)Ro(s,t,n);if(F(e)&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[0])&&z(e.func.args[1])&&e.func.args[1].token.value===k.___dup[0]&&e.args.length===0&&e.$?.env){let s=e.func.args[0].token.value,l=X(e.$.env,s);if(l.length>0){let u=l[l.length-1];t.has(u.id)||t.set(u.id,[]),t.get(u.id).push(e)}return}if(F(e)&&E(e,I.while))return;function i(s){if(nt(s.$?.controlFlow))return!0;if(F(s)&&E(s,I.begin)){let l=s.args[s.args.length-1];if(nt(l?.$?.controlFlow)||F(l)&&E(l,I.return))return!0}return!!(F(s)&&E(s,I.return))}function o(s){if(F(s)&&E(s,I.tuple,0))return!0;if(F(s)&&E(s,I.begin)){if(s.args.length===0)return!0;if(s.args.length===1){let l=s.args[0];if(F(l)&&E(l,I.tuple,0))return!0}}return!1}function a(s,l){let u=[],c=[],_=[];for(let f=l;f<s.args.length;f++){let m=s.args[f];if(F(m)&&E(m,"=>",2)){let g=m.args[1],h=Wu(g);u.push(h),c.push(i(g)),_.push(o(g))}}let p=new Set;for(let f of u){for(let m of f.dupCalls.keys())p.add(m);for(let m of f.varsWithPartialBranchDups)n.add(m)}if(u.length>0)for(let f of p){let m=[],g=[];for(let h=0;h<u.length;h++){let d=u[h],v=d.dupCalls.has(f),T=c[h];if(v){let $=d.dupCalls.get(f);T?m.push(...$):g.push(...$)}}for(let h of m)t.has(f)||t.set(f,[]),h.__isEarlyReturnDup=!0,t.get(f).push(h);if(g.length>0){let h=0,d=0;for(let v=0;v<u.length;v++)c[v]||(h++,u[v].dupCalls.has(f)&&d++);if(d===h){t.has(f)||t.set(f,[]);for(let v of g)t.get(f).push(v)}else n.add(f)}}}if(F(e)&&E(e,I.cond)){a(e,0);return}if(F(e)&&E(e,I.match)){e.args[0]&&Ro(e.args[0],t,n),a(e,1);return}if(F(e)){Ro(e.func,t,n);for(let s of e.args)Ro(s,t,n)}}function Wu(e){let t=new Map,n=new Set;return Ro(e,t,n),{dupCalls:t,varsWithPartialBranchDups:n}}function Aa(e){return F(e)&&E(e,I.tuple,0)}function Js(e,t){if(e.$?.deferredDupExpressions&&(e.$.deferredDupExpressions=e.$.deferredDupExpressions.filter(n=>!t.has(n)),e.$.deferredDupExpressions.length===0&&(e.$.deferredDupExpressions=void 0)),F(e)){Js(e.func,t);for(let n of e.args)Js(n,t)}}function ht({expr:e,env:t,context:n,variablesToAdd:r=[],isEvaluatingFunctionBodyBeginBlock:i=!1}){if(F(e)&&E(e,"_")&&!E(e,I.begin)){let $=e;$.args.some(L=>F(L)&&E(L,":"))||($.func={...$.func,token:{...$.func.token,value:I.begin[0]}})}if(!F(e)||!E(e,I.begin)){let $={tag:"FnCall",func:{tag:"Atom",token:{...e.token,value:I.begin[0]}},args:[Ae(e)],token:{...e.token,value:I.begin[0]}};dr(e,$),e=e}let o=e.args,a=n.expectedType;if(o.length===0)return e.$={env:t,type:H.type,value:H,pathCollection:[]},e;t=Pe(t,void 0,!0);for(let $=0;$<r.length;$++){let C=r[$],{env:L}=me({env:t,variable:C});t=L}let s=o[o.length-1],l,u=!1;for(let $=0;$<o.length;$++){let C=o[$];if(z(C)&&dt(C,I.return)||F(C)&&E(C,I.return)){if($!==o.length-1&&!($===o.length-2&&Aa(o[o.length-1])))throw y({token:C.token,errorMessage:'The "return" keyword can only be used as the last expression.'});if(F(C)&&he(C,I.return,1),!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:C.token,errorMessage:'The "return" keyword can only be used inside a function body or async block.'});if(l=C,z(C)){C.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:zr("return")},s=C;break}else{he(C,I.return,1);let L=C.args[0],b=S({expr:L,env:t,context:{...n,expectedType:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?{type:n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type,env:t}:n.expectedType}});if(!b.$)throw y({token:L.token,errorMessage:`Return expression is not evaluated correctly:
152
152
  ${w(L)}`});if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&x(n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type)&&n.functionReturnImplConcreteType){let R=b.$.type;if(n.functionReturnImplConcreteType.length>0){let N=n.functionReturnImplConcreteType[0];if(!Y({type:N.concreteType,env:N.env},{type:R,env:t}))throw lt([{token:C.token,errorMessage:`All return statements must return the same concrete type for Impl(...).
153
153
  Impl(...) uses static dispatch and requires the same concrete type across all returns.
154
154
  Consider using Dyn(...) for dynamic dispatch if different concrete types are needed.`},{token:N.token,errorMessage:`First return has concrete type: ${A(N.concreteType)}`},{token:C.token,errorMessage:`Conflicting return has concrete type: ${A(R)}`}])}else n.functionReturnImplConcreteType.push({concreteType:R,env:t,token:C.token})}Ge(b,!0),t=b.$.env,C.$={env:t,type:b.$.type,value:b.$.value,pathCollection:b.$.pathCollection,variableName:b.$.variableName,controlFlow:zr("return")},s=C;break}}else if(z(C)&&dt(C,I.break)){if($!==o.length-1&&!($===o.length-2&&Aa(o[o.length-1])))throw y({token:C.token,errorMessage:'The "break" keyword can only be used as the last expression.'});if(!n.isEvaluatingLoopBody)throw y({token:C.token,errorMessage:'The "break" keyword can only be used inside a loop.'});C.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:zr("break")},s=C;break}else if(z(C)&&dt(C,I.continue)){if($!==o.length-1&&!($===o.length-2&&Aa(o[o.length-1])))throw y({token:C.token,errorMessage:'The "continue" keyword can only be used as the last expression.'});if(!n.isEvaluatingLoopBody)throw y({token:C.token,errorMessage:'The "continue" keyword can only be used inside a loop.'});C.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:zr("continue")},s=C;break}else if(F(C)&&E(C,I.escape)){if($!==o.length-1&&!($===o.length-2&&Aa(o[o.length-1])))throw y({token:C.token,errorMessage:'The "escape" keyword can only be used as the last expression.'});if(!n.enclosingFunctionReturnType)throw y({token:C.token,errorMessage:'The "escape" keyword can only be used inside a function that has an enclosing function.'});l=C,he(C,I.escape,1);let L=C.args[0],b=S({expr:L,env:t,context:{...n,expectedType:{type:n.enclosingFunctionReturnType,env:t}}});if(!b.$)throw y({token:L.token,errorMessage:`Escape expression is not evaluated correctly:
@@ -164,39 +164,40 @@ ${w(p)}`});f=p.token.value,m=f}else if(F(p)&&E(p,":",2)){let v=p.args[0],T=p.arg
164
164
  ${w(v)}`});if(!je(v))throw y({token:v.token,errorMessage:`Expected identifier for export, got:
165
165
  ${w(v)}`});if(f=v.token.value,!z(T))throw y({token:T.token,errorMessage:`Expected identifier for export, got:
166
166
  ${w(T)}`});if(!je(T))throw y({token:T.token,errorMessage:`Expected identifier for export, got:
167
- ${w(T)}`});m=T.token.value}let g=X(t,m);if(g.length===0)throw y({token:p.token,errorMessage:`Variable "${m}" is not defined in the module.`});let h=g[g.length-1];if(i.fields.findIndex(v=>v.label===m)>=0)throw y({token:p.token,errorMessage:`Variable "${m}" is already exported in the module.`});if(!h.isCompileTimeOnly)throw y({token:p.token,errorMessage:`Variable "${m}" is not a compile-time variable and cannot be exported.`});i.fields.push({label:f,type:h.type,assignedValue:h.isCompileTimeOnly?h.value?.[0]:void 0,defaultValue:void 0,exprs:{expr:p,labelExpr:void 0,typeExpr:void 0,assignedValueExpr:void 0,defaultValueExpr:void 0}}),o.push(h.value?.[0]),p.$={env:t,type:h.type,value:h.value?.[0],pathCollection:[]}}}}else{let c=S({expr:u,env:t,context:{...n,expectedType:void 0}});c.$?.env&&(t=c.$?.env)}}catch(c){if(r){a=c;break}else throw c}}try{a||(t=ct(t))}catch(l){if(r)a=l;else throw l}return{moduleValue:ca({...i},o),moduleType:i,env:t,partialModuleError:a}}function Sa({functionType:e,specializedEnv:t,SelfType:n}){let r=e.parameters.map(u=>{if(!u.exprs.typeExpr)return u;let c=Ae(u.exprs.typeExpr),_=S({expr:c,env:t,context:{isEvaluatingGenericImplSpecialization:!0,stdPath:"",isEvaluatingFunctionType:!0,SelfType:n}});return O(_.$?.value)?{...u,type:_.$.value.value,exprs:{...u.exprs}}:u}),i=e.return.type,o=Ae(e.return.typeExpr),a=S({expr:o,env:t,context:{isEvaluatingGenericImplSpecialization:!0,stdPath:"",isEvaluatingFunctionType:!0,SelfType:n}});O(a.$?.value)&&(i=a.$.value.value);let s=e.SelfType;n&&(s=n);let l={...e.parametersFrame,variables:e.parametersFrame.variables.map(u=>{let c=r.find(p=>p.label===u.name),_=c?c.type:u.type;return _!==u.type?{...u,type:_}:u})};return{...e,env:t,forallParameters:[],parameters:r,parametersFrame:l,return:{...e.return,type:i},SelfType:s}}var Po=new Map;function ny({traitExpr:e,traitType:t}){if(!e||!F(e))return{};let n=e.func;if(F(n)){let r=n.args.map(o=>Ae(o)),i;if(t.functionValue&&G(t.functionValue.type)){let o=t.functionValue.type;o.parameters.length>0?i=o.parameters.map(a=>a.label):o.forallParameters.length>0&&(i=o.forallParameters.map(a=>a.label))}return{traitTypeArgExprs:r,traitFunctionParamNames:i}}if(!t.functionValue){let r=[],i=[];for(let o of e.args)if(F(o)&&E(o,":",2)){let a=o.args[0],s=o.args[1];if(z(a)){let l=a.token.value,u=t.fields.find(c=>c.label===l);u&&!G(u.type)&&(r.push(Ae(s)),i.push(l))}}if(r.length>0)return{traitTypeArgExprs:r,traitFunctionParamNames:i}}return{}}function qu({fieldExprs:e,env:t,context:n,receiverType:r}){let i=[],o=Oe(t),a=[],s=!1,l=r?.trait;r?.trait&&(r.trait={...r.trait,fields:[...r.trait.fields]}),t=Pe(t);for(let u of e){if(F(u)&&E(u,I.begin))throw y({token:u.token,errorMessage:'impl receiverType, ... no longer accepts begin blocks. Use "impl { ... }" for anonymous modules.'});if(F(u)&&(E(u,"::",2)||E(u,":=",2)))throw y({token:u.token,errorMessage:'impl fields must use ":". "::" and ":=" are not allowed here.'});if(F(u)&&E(u,":",2)){let _=u.args[0],p=u.args[1];if(!z(_)||!je(_))throw y({token:_.token,errorMessage:`Expected identifier for impl field name, got:
167
+ ${w(T)}`});m=T.token.value}let g=X(t,m);if(g.length===0)throw y({token:p.token,errorMessage:`Variable "${m}" is not defined in the module.`});let h=g[g.length-1];if(i.fields.findIndex(v=>v.label===m)>=0)throw y({token:p.token,errorMessage:`Variable "${m}" is already exported in the module.`});if(!h.isCompileTimeOnly)throw y({token:p.token,errorMessage:`Variable "${m}" is not a compile-time variable and cannot be exported.`});i.fields.push({label:f,type:h.type,assignedValue:h.isCompileTimeOnly?h.value?.[0]:void 0,defaultValue:void 0,exprs:{expr:p,labelExpr:void 0,typeExpr:void 0,assignedValueExpr:void 0,defaultValueExpr:void 0}}),o.push(h.value?.[0]),p.$={env:t,type:h.type,value:h.value?.[0],pathCollection:[]}}}}else{let c=S({expr:u,env:t,context:{...n,expectedType:void 0}});c.$?.env&&(t=c.$?.env)}}catch(c){if(r){a=c;break}else throw c}}try{a||(t=ct(t))}catch(l){if(r)a=l;else throw l}return{moduleValue:ca({...i},o),moduleType:i,env:t,partialModuleError:a}}function Sa({functionType:e,specializedEnv:t,SelfType:n}){let r=e.parameters.map(u=>{if(!u.exprs.typeExpr)return u;let c=Ae(u.exprs.typeExpr),_=S({expr:c,env:t,context:{isEvaluatingGenericImplSpecialization:!0,stdPath:"",isEvaluatingFunctionType:!0,SelfType:n}});return O(_.$?.value)?{...u,type:_.$.value.value,exprs:{...u.exprs}}:u}),i=e.return.type,o=Ae(e.return.typeExpr),a=S({expr:o,env:t,context:{isEvaluatingGenericImplSpecialization:!0,stdPath:"",isEvaluatingFunctionType:!0,SelfType:n}});O(a.$?.value)&&(i=a.$.value.value);let s=e.SelfType;n&&(s=n);let l={...e.parametersFrame,variables:e.parametersFrame.variables.map(u=>{let c=r.find(p=>p.label===u.name),_=c?c.type:u.type;return _!==u.type?{...u,type:_}:u})};return{...e,env:t,forallParameters:[],parameters:r,parametersFrame:l,return:{...e.return,type:i},SelfType:s}}var Po=new Map;function ry({traitExpr:e,traitType:t}){if(!e||!F(e))return{};let n=e.func;if(F(n)){let r=n.args.map(o=>Ae(o)),i;if(t.functionValue&&G(t.functionValue.type)){let o=t.functionValue.type;o.parameters.length>0?i=o.parameters.map(a=>a.label):o.forallParameters.length>0&&(i=o.forallParameters.map(a=>a.label))}return{traitTypeArgExprs:r,traitFunctionParamNames:i}}if(!t.functionValue){let r=[],i=[];for(let o of e.args)if(F(o)&&E(o,":",2)){let a=o.args[0],s=o.args[1];if(z(a)){let l=a.token.value,u=t.fields.find(c=>c.label===l);u&&!G(u.type)&&(r.push(Ae(s)),i.push(l))}}if(r.length>0)return{traitTypeArgExprs:r,traitFunctionParamNames:i}}return{}}function qu({fieldExprs:e,env:t,context:n,receiverType:r}){let i=[],o=Oe(t),a=[],s=!1,l=r?.trait;r?.trait&&(r.trait={...r.trait,fields:[...r.trait.fields]}),t=Pe(t);for(let u of e){if(F(u)&&E(u,I.begin))throw y({token:u.token,errorMessage:'impl receiverType, ... no longer accepts begin blocks. Use "impl { ... }" for anonymous modules.'});if(F(u)&&(E(u,"::",2)||E(u,":=",2)))throw y({token:u.token,errorMessage:'impl fields must use ":". "::" and ":=" are not allowed here.'});if(F(u)&&E(u,":",2)){let _=u.args[0],p=u.args[1];if(!z(_)||!je(_))throw y({token:_.token,errorMessage:`Expected identifier for impl field name, got:
168
168
  ${w(_)}`});let f=_.token.value,m=S({expr:p,env:t,context:{...n,expectedType:void 0,SelfType:r}});if(!m.$?.type)throw y({token:p.token,errorMessage:`Failed to evaluate impl field value for "${f}".`});t=m.$.env;let g=m.$.type,h=m.$.value;if(!h)throw y({token:p.token,errorMessage:`impl field "${f}" must be a compile-time value.`});ne(h)&&!h.funcName&&(h.funcName=f,h.funcId+=`_${f}`);let{env:d}=me({env:t,variable:{name:f,type:g,isCompileTimeOnly:!0,value:[h],token:_.token,initializedAtToken:_.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});t=d,o.fields.push({label:f,type:g,assignedValue:h,defaultValue:void 0,exprs:{expr:u}}),a.push(h),s=!0,r?.trait&&r.trait.fields.push({label:f,type:g,assignedValue:h,defaultValue:void 0,exprs:{expr:u}});continue}let c=S({expr:u,env:t,context:{...n,expectedType:void 0,ReceiverType:r}});if(!c.$||!Tt(c.$.value))throw y({token:u.token,errorMessage:`Expected trait value in impl field list, got:
169
- ${w(u)}`});t=c.$.env,i.push({traitValue:c.$.value,sourceExpr:u,isAnonymousTrait:!1})}if(t=ct(t),r&&(r.trait=l),s){let u=Fi({...o,receiverType:r},a);i.unshift({traitValue:u,sourceExpr:void 0,isAnonymousTrait:!0})}return{env:t,traitEntries:i}}var Zn=new Map,di=new Map;function Uo(e){for(let[t,n]of Zn.entries()){let r=n.filter(i=>i.sourceModulePath!==e);r.length===0?Zn.delete(t):Zn.set(t,r)}}function ry(e){for(let[t,n]of di.entries()){let r=n.filter(i=>i.modulePath!==e);r.length===0?di.delete(t):di.set(t,r)}}function el(){Po.clear(),Zn.clear(),di.clear()}function Na(e){return e.functionValue?e.functionValue.funcId:e.typeName||e.id}function Yu(e){if("functionValue"in e){let t=e.functionValue;if(t)return t.funcId}return e.id}function Hu(e,t){if(!t.traitType.typeName){let r=t.traitType.fields.filter(i=>i.label&&G(i.type)).map(i=>i.label);if(r.length>0){let i=Yu(t.receiverTypePattern);if(i){for(let[o,a]of Zn.entries())for(let s of a)if(!(s.traitType.typeName||Yu(s.receiverTypePattern)!==i)){for(let u of s.traitType.fields)if(u.label&&G(u.type)&&r.includes(u.label))throw y({token:t.expr.token,errorMessage:`Method "${u.label}" is already defined for type "${A(t.receiverTypePattern)}".
170
- Cannot define duplicate method names across impl blocks. Use a different name (e.g., "comptime_${u.label}") for the comptime variant.`})}}}}let n=Zn.get(e);n||(n=[],Zn.set(e,n)),n.push(t)}function iy({receiverType:e,traitType:t,currentModulePath:n,expr:r}){let i=e.id,a=(di.get(i)||[]).find(s=>s.traitTypeId===t.id);if(a)throw y({token:r.token,errorMessage:`Trait "${t.typeName??t.id}" is already implemented for type "${A(e)}".
171
- First implementation was in: ${a.modulePath||"unknown"}`})}function oy({receiverType:e,traitType:t,currentModulePath:n,expr:r}){let i=e.id,o=di.get(i);o||(o=[],di.set(i,o)),o.push({traitTypeId:t.id,traitTypeName:t.typeName,modulePath:n||"unknown",expr:r})}function ay({receiverType:e,traitType:t,currentModulePath:n,expr:r}){if(!n)return;let i=t.definedInModulePath===n,o=e.definedInModulePath===n;if(!(n.includes("prelude.yo")||n.includes("std/"))&&!i&&!o)throw y({token:r.token,errorMessage:`Orphan impl: Cannot implement foreign trait "${t.typeName??t.id}" for foreign type "${A(e)}".
169
+ ${w(u)}`});t=c.$.env,i.push({traitValue:c.$.value,sourceExpr:u,isAnonymousTrait:!1})}if(t=ct(t),r&&(r.trait=l),s){let u=Fi({...o,receiverType:r},a);i.unshift({traitValue:u,sourceExpr:void 0,isAnonymousTrait:!0})}return{env:t,traitEntries:i}}var Zn=new Map,di=new Map;function Uo(e){for(let[t,n]of Zn.entries()){let r=n.filter(i=>i.sourceModulePath!==e);r.length===0?Zn.delete(t):Zn.set(t,r)}}function iy(e){for(let[t,n]of di.entries()){let r=n.filter(i=>i.modulePath!==e);r.length===0?di.delete(t):di.set(t,r)}}function el(){Po.clear(),Zn.clear(),di.clear()}function Na(e){return e.functionValue?e.functionValue.funcId:e.typeName||e.id}function Yu(e){if("functionValue"in e){let t=e.functionValue;if(t)return t.funcId}return e.id}function Hu(e,t){if(!t.traitType.typeName){let r=t.traitType.fields.filter(i=>i.label&&G(i.type)).map(i=>i.label);if(r.length>0){let i=Yu(t.receiverTypePattern);if(i){for(let[o,a]of Zn.entries())for(let s of a)if(!(s.traitType.typeName||Yu(s.receiverTypePattern)!==i)){for(let u of s.traitType.fields)if(u.label&&G(u.type)&&r.includes(u.label))throw y({token:t.expr.token,errorMessage:`Method "${u.label}" is already defined for type "${A(t.receiverTypePattern)}".
170
+ Cannot define duplicate method names across impl blocks. Use a different name (e.g., "comptime_${u.label}") for the comptime variant.`})}}}}let n=Zn.get(e);n||(n=[],Zn.set(e,n)),n.push(t)}function oy({receiverType:e,traitType:t,currentModulePath:n,expr:r}){let i=e.id,a=(di.get(i)||[]).find(s=>s.traitTypeId===t.id);if(a)throw y({token:r.token,errorMessage:`Trait "${t.typeName??t.id}" is already implemented for type "${A(e)}".
171
+ First implementation was in: ${a.modulePath||"unknown"}`})}function ay({receiverType:e,traitType:t,currentModulePath:n,expr:r}){let i=e.id,o=di.get(i);o||(o=[],di.set(i,o)),o.push({traitTypeId:t.id,traitTypeName:t.typeName,modulePath:n||"unknown",expr:r})}function sy({receiverType:e,traitType:t,currentModulePath:n,expr:r}){if(!n)return;let i=t.definedInModulePath===n,o=e.definedInModulePath===n;if(!(n.includes("prelude.yo")||n.includes("std/"))&&!i&&!o)throw y({token:r.token,errorMessage:`Orphan impl: Cannot implement foreign trait "${t.typeName??t.id}" for foreign type "${A(e)}".
172
172
  At least one of the trait or the type must be defined in this module.
173
173
  Trait defined in: ${t.definedInModulePath||"unknown"}
174
174
  Type defined in: ${e.definedInModulePath||"unknown"}
175
- Current module: ${n}`})}function Va({concreteType:e,traitType:t,env:n}){let r=Na(t),i=Zn.get(r);if(!(!i||i.length===0)){for(let o of i)if(Da({concreteType:e,impl:o,env:n}).matched)return o}}function Jn({concreteType:e,methodName:t,env:n}){if(x(e)){let i=Ot(n,e);x(i)||(e=i)}let r=[];for(let[i,o]of Zn.entries())for(let a of o){let s=Da({concreteType:e,impl:a,env:n});if(!s.matched)continue;let l=a.traitType,u=a.traitValue,c=l.fields.findIndex(_=>_.label===t&&G(_.type));if(c>=0){let _=l.fields[c];if(G(_.type)){let p=u.fields[c],f=Cr(e);if(ne(p)&&(s.valueSubstitutions.size>0||s.substitutions.size>0)&&!f){let g=a.definitionEnv,h=Pe(g);for(let[C,L]of s.substitutions){let{env:b}=me({env:h,variable:{name:C,type:tt(),isCompileTimeOnly:!0,value:[ee(L)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=b}for(let[C,L]of s.valueSubstitutions){let{env:b}=me({env:h,variable:{name:C,type:L.type,isCompileTimeOnly:!0,value:[L],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=b}if(a.traitTypeArgExprs&&a.traitFunctionParamNames&&a.traitTypeArgExprs.length===a.traitFunctionParamNames.length)for(let C=0;C<a.traitTypeArgExprs.length;C++){let L=a.traitTypeArgExprs[C],b=a.traitFunctionParamNames[C],R=S({expr:Ae(L),env:h,context:{isEvaluatingGenericImplSpecialization:!0,stdPath:""}});if(R.$&&O(R.$.value)){let{env:N}=me({env:h,variable:{name:b,type:tt(),isCompileTimeOnly:!0,value:[R.$.value],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});h=N}}let d=Sa({functionType:_.type,specializedEnv:h,SelfType:s.substitutions.get("Self")});h=Pe(h,d.parametersFrame);let v=Ae(p.body),T=ht({expr:v,env:h,context:{isEvaluatingGenericImplSpecialization:!0,expectedType:{type:d.return.type,env:h},stdPath:"",isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:d,value:p,evaluationEnv:h},functionReturnImplConcreteType:[],SelfType:s.substitutions.get("Self")},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),$={...p,specializedType:d,body:T,funcId:`${p.funcId}_specialized_${[...s.substitutions.entries()].map(([C,L])=>`${C}_${A(L)}`).join("_")}_${[...s.valueSubstitutions.entries()].map(([C,L])=>`${C}_${Me(L)}`).join("_")}`,funcName:p.funcName?`${p.funcName}_specialized`:void 0};r.push({type:d,value:$})}else if(f){let g=a.definitionEnv,h=Pe(g);for(let[v,T]of s.substitutions){let{env:$}=me({env:h,variable:{name:v,type:tt(),isCompileTimeOnly:!0,value:[ee(T)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}for(let[v,T]of s.valueSubstitutions){let{env:$}=me({env:h,variable:{name:v,type:T.type,isCompileTimeOnly:!0,value:[T],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}let d=Sa({functionType:_.type,specializedEnv:h,SelfType:s.substitutions.get("Self")});r.push({type:d,value:void 0})}else if(ne(p)){let g={...p,specializedType:_.type};r.push({type:_.type,value:g})}else if(!ne(p)&&(s.substitutions.size>0||s.valueSubstitutions.size>0)){let g=a.definitionEnv,h=Pe(g);for(let[v,T]of s.substitutions){let{env:$}=me({env:h,variable:{name:v,type:tt(),isCompileTimeOnly:!0,value:[ee(T)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}for(let[v,T]of s.valueSubstitutions){let{env:$}=me({env:h,variable:{name:v,type:T.type,isCompileTimeOnly:!0,value:[T],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}let d=Sa({functionType:_.type,specializedEnv:h,SelfType:s.substitutions.get("Self")});r.push({type:d,value:p})}else r.push({type:_.type,value:p})}}}return r}function xa({concreteType:e,propertyName:t,env:n}){if(x(e)){let r=Ot(n,e);x(r)||(e=r)}for(let[r,i]of Zn.entries())for(let o of i){let a;try{a=Da({concreteType:e,impl:o,env:n})}catch{continue}if(!a.matched)continue;let s=o.traitType,l=s.fields.findIndex(_=>_.label===t&&!G(_.type));if(l<0)continue;if(o.traitTypeArgExprs&&o.traitFunctionParamNames&&o.traitTypeArgExprs.length===o.traitFunctionParamNames.length){let _=o.definitionEnv,p=Pe(_);for(let[f,m]of a.substitutions){let{env:g}=me({env:p,variable:{name:f,type:tt(),isCompileTimeOnly:!0,value:[ee(m)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});p=g}for(let f=0;f<o.traitTypeArgExprs.length;f++){let m=o.traitTypeArgExprs[f];if(o.traitFunctionParamNames[f]===t)try{let h=Ae(m),d=S({expr:h,env:p,context:{stdPath:"",isEvaluatingGenericImplSpecialization:!0}});if(d.$&&O(d.$.value))return{type:d.$.value.type,value:d.$.value}}catch{}}}let u=s.fields[l],c=o.traitValue.fields[l]??u.assignedValue;if(!(!c||!O(c))){if(!x(c.value))return{type:c.type,value:c};for(let _ of o.forallParameters)if(_.kind==="type"&&_.someType===c.value){let p=a.substitutions.get(_.name);if(p){let f=ee(p);return{type:f.type,value:f}}}}}}function Ku({concreteType:e,traitType:t,methodName:n,env:r}){let i=Na(t),o=Zn.get(i);if(!(!o||o.length===0))for(let a of o){let s=Da({concreteType:e,impl:a,env:r});if(!s.matched)continue;let l=a.traitType,u=a.traitValue,c=l.fields.findIndex(_=>_.label===n&&G(_.type));if(c>=0){let _=l.fields[c];if(G(_.type)){let p=u.fields[c];if(ne(p)&&(s.valueSubstitutions.size>0||s.substitutions.size>0)){let f=a.definitionEnv,m=Pe(f);for(let[T,$]of s.substitutions){let{env:C}=me({env:m,variable:{name:T,type:tt(),isCompileTimeOnly:!0,value:[ee($)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});m=C}for(let[T,$]of s.valueSubstitutions){let{env:C}=me({env:m,variable:{name:T,type:$.type,isCompileTimeOnly:!0,value:[$],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});m=C}let g=Sa({functionType:_.type,specializedEnv:m,SelfType:s.substitutions.get("Self")});m=Pe(m,g.parametersFrame);let h=Ae(p.body),d=ht({expr:h,env:m,context:{isEvaluatingGenericImplSpecialization:!0,expectedType:{type:g.return.type,env:m},stdPath:"",isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:g,value:p,evaluationEnv:m},functionReturnImplConcreteType:[],SelfType:s.substitutions.get("Self")},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),v={...p,specializedType:g,body:d,funcId:`${p.funcId}_specialized_${[...s.substitutions.entries()].map(([T,$])=>`${T}_${A($)}`).join("_")}_${[...s.valueSubstitutions.entries()].map(([T,$])=>`${T}_${Me($)}`).join("_")}`,funcName:p.funcName?`${p.funcName}_specialized`:void 0};return{type:g,value:v}}else if(ne(p)){let f={...p,specializedType:_.type};return{type:_.type,value:f}}else return{type:_.type,value:p}}}}}function Da({concreteType:e,impl:t,env:n}){let r={matched:!1,substitutions:new Map,valueSubstitutions:new Map};if(x(e)){let o=Ot(n,e);if(x(o))return r;e=o}let i=Pe(n);for(let o of t.forallParameters)if(o.kind==="type"){let{env:a}=me({env:i,variable:{name:o.name,type:tt(),isCompileTimeOnly:!0,value:[ee(o.someType)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});i=a}else{let{env:a}=me({env:i,variable:{name:o.name,type:o.type,isCompileTimeOnly:!0,value:[o.unknownValue],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});i=a}try{let{expectedEnv:o}=Ze({type:t.receiverTypePattern,env:i},{type:e,env:n});for(let{someType:l,traitType:u,traitExpr:c}of t.whereConstraints){let _=ju(o,l);if(!_)return r;let p=u;if(c)try{let f=Ae(c),m=S({expr:f,env:o,context:{stdPath:"",isEvaluatingGenericImplSpecialization:!0}});m.$&&O(m.$.value)&&De(m.$.value.value)&&(p=m.$.value.value)}catch{}if(p.isNegatedConstraint){if(x(_)){if(!ly(_,p,n))return r;continue}if(St({targetType:_,traitType:p,env:n}))return r;continue}if(x(_)){if(!sy(_,p,n))return r;continue}if(!St({targetType:_,traitType:p,env:o}))return r}let a=new Map,s=new Map;for(let l of t.forallParameters)if(l.kind==="type"){let u=ju(o,l.someType);u&&!x(u)&&a.set(l.name,u)}else{let u=X(o,l.name),c=u[u.length-1];if(c&&c.value&&!de(c.value[0])){let _={...c.value[0],type:l.type};s.set(l.name,_)}}return a.set("Self",e),{matched:!0,substitutions:a,valueSubstitutions:s}}catch{return r}}function sy(e,t,n){if(!t.typeName)return!1;for(let o of e.requiredTraits)if(o.traitType.id===t.id)return!0;let i=Wn(n,e);if(i){for(let o of i.requiredTraits)if(o.id===t.id)return!0}for(let o of e.trait.fields)if(Tt(o.assignedValue)&&o.assignedValue.type.id===t.id)return!0;return!1}function ly(e,t,n){if(!t.typeName)return!1;if(e.negativeTraits){for(let o of e.negativeTraits)if(o.traitType.id===t.id)return!0}let i=Wn(n,e);if(i){for(let o of i.negativeTraits)if(o.id===t.id)return!0}return!1}function uy({receiverTypePattern:e,traitType:t,whereConstraints:n,env:r,errorToken:i}){if(t.selfConstraints&&t.selfConstraints.length>0)for(let o of t.selfConstraints){if(St({targetType:e,traitType:o,env:r}))continue;let a=new Set;for(let s of n)s.traitType.typeName===o.typeName&&!s.traitType.isNegatedConstraint&&a.add(s.someType.name);throw y({token:i,errorMessage:`Generic impl receiver type "${A(e)}" does not satisfy constraint "${o.typeName??A(o)}" required by trait "${t.typeName??A(t)}".
175
+ Current module: ${n}`})}function Va({concreteType:e,traitType:t,env:n}){let r=Na(t),i=Zn.get(r);if(!(!i||i.length===0)){for(let o of i)if(Da({concreteType:e,impl:o,env:n}).matched)return o}}function Jn({concreteType:e,methodName:t,env:n}){if(x(e)){let i=Ot(n,e);x(i)||(e=i)}let r=[];for(let[i,o]of Zn.entries())for(let a of o){let s=Da({concreteType:e,impl:a,env:n});if(!s.matched)continue;let l=a.traitType,u=a.traitValue,c=l.fields.findIndex(_=>_.label===t&&G(_.type));if(c>=0){let _=l.fields[c];if(G(_.type)){let p=u.fields[c],f=Cr(e);if(ne(p)&&(s.valueSubstitutions.size>0||s.substitutions.size>0)&&!f){let g=a.definitionEnv,h=Pe(g);for(let[C,L]of s.substitutions){let{env:b}=me({env:h,variable:{name:C,type:tt(),isCompileTimeOnly:!0,value:[ee(L)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=b}for(let[C,L]of s.valueSubstitutions){let{env:b}=me({env:h,variable:{name:C,type:L.type,isCompileTimeOnly:!0,value:[L],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=b}if(a.traitTypeArgExprs&&a.traitFunctionParamNames&&a.traitTypeArgExprs.length===a.traitFunctionParamNames.length)for(let C=0;C<a.traitTypeArgExprs.length;C++){let L=a.traitTypeArgExprs[C],b=a.traitFunctionParamNames[C],R=S({expr:Ae(L),env:h,context:{isEvaluatingGenericImplSpecialization:!0,stdPath:""}});if(R.$&&O(R.$.value)){let{env:N}=me({env:h,variable:{name:b,type:tt(),isCompileTimeOnly:!0,value:[R.$.value],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});h=N}}let d=Sa({functionType:_.type,specializedEnv:h,SelfType:s.substitutions.get("Self")});h=Pe(h,d.parametersFrame);let v=Ae(p.body),T=ht({expr:v,env:h,context:{isEvaluatingGenericImplSpecialization:!0,expectedType:{type:d.return.type,env:h},stdPath:"",isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:d,value:p,evaluationEnv:h},functionReturnImplConcreteType:[],SelfType:s.substitutions.get("Self")},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),$={...p,specializedType:d,body:T,funcId:`${p.funcId}_specialized_${[...s.substitutions.entries()].map(([C,L])=>`${C}_${A(L)}`).join("_")}_${[...s.valueSubstitutions.entries()].map(([C,L])=>`${C}_${Me(L)}`).join("_")}`,funcName:p.funcName?`${p.funcName}_specialized`:void 0};r.push({type:d,value:$})}else if(f){let g=a.definitionEnv,h=Pe(g);for(let[v,T]of s.substitutions){let{env:$}=me({env:h,variable:{name:v,type:tt(),isCompileTimeOnly:!0,value:[ee(T)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}for(let[v,T]of s.valueSubstitutions){let{env:$}=me({env:h,variable:{name:v,type:T.type,isCompileTimeOnly:!0,value:[T],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}let d=Sa({functionType:_.type,specializedEnv:h,SelfType:s.substitutions.get("Self")});r.push({type:d,value:void 0})}else if(ne(p)){let g={...p,specializedType:_.type};r.push({type:_.type,value:g})}else if(!ne(p)&&(s.substitutions.size>0||s.valueSubstitutions.size>0)){let g=a.definitionEnv,h=Pe(g);for(let[v,T]of s.substitutions){let{env:$}=me({env:h,variable:{name:v,type:tt(),isCompileTimeOnly:!0,value:[ee(T)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}for(let[v,T]of s.valueSubstitutions){let{env:$}=me({env:h,variable:{name:v,type:T.type,isCompileTimeOnly:!0,value:[T],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});h=$}let d=Sa({functionType:_.type,specializedEnv:h,SelfType:s.substitutions.get("Self")});r.push({type:d,value:p})}else r.push({type:_.type,value:p})}}}return r}function xa({concreteType:e,propertyName:t,env:n}){if(x(e)){let r=Ot(n,e);x(r)||(e=r)}for(let[r,i]of Zn.entries())for(let o of i){let a;try{a=Da({concreteType:e,impl:o,env:n})}catch{continue}if(!a.matched)continue;let s=o.traitType,l=s.fields.findIndex(_=>_.label===t&&!G(_.type));if(l<0)continue;if(o.traitTypeArgExprs&&o.traitFunctionParamNames&&o.traitTypeArgExprs.length===o.traitFunctionParamNames.length){let _=o.definitionEnv,p=Pe(_);for(let[f,m]of a.substitutions){let{env:g}=me({env:p,variable:{name:f,type:tt(),isCompileTimeOnly:!0,value:[ee(m)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});p=g}for(let f=0;f<o.traitTypeArgExprs.length;f++){let m=o.traitTypeArgExprs[f];if(o.traitFunctionParamNames[f]===t)try{let h=Ae(m),d=S({expr:h,env:p,context:{stdPath:"",isEvaluatingGenericImplSpecialization:!0}});if(d.$&&O(d.$.value))return{type:d.$.value.type,value:d.$.value}}catch{}}}let u=s.fields[l],c=o.traitValue.fields[l]??u.assignedValue;if(!(!c||!O(c))){if(!x(c.value))return{type:c.type,value:c};for(let _ of o.forallParameters)if(_.kind==="type"&&_.someType===c.value){let p=a.substitutions.get(_.name);if(p){let f=ee(p);return{type:f.type,value:f}}}}}}function Ku({concreteType:e,traitType:t,methodName:n,env:r}){let i=Na(t),o=Zn.get(i);if(!(!o||o.length===0))for(let a of o){let s=Da({concreteType:e,impl:a,env:r});if(!s.matched)continue;let l=a.traitType,u=a.traitValue,c=l.fields.findIndex(_=>_.label===n&&G(_.type));if(c>=0){let _=l.fields[c];if(G(_.type)){let p=u.fields[c];if(ne(p)&&(s.valueSubstitutions.size>0||s.substitutions.size>0)){let f=a.definitionEnv,m=Pe(f);for(let[T,$]of s.substitutions){let{env:C}=me({env:m,variable:{name:T,type:tt(),isCompileTimeOnly:!0,value:[ee($)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});m=C}for(let[T,$]of s.valueSubstitutions){let{env:C}=me({env:m,variable:{name:T,type:$.type,isCompileTimeOnly:!0,value:[$],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});m=C}let g=Sa({functionType:_.type,specializedEnv:m,SelfType:s.substitutions.get("Self")});m=Pe(m,g.parametersFrame);let h=Ae(p.body),d=ht({expr:h,env:m,context:{isEvaluatingGenericImplSpecialization:!0,expectedType:{type:g.return.type,env:m},stdPath:"",isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:g,value:p,evaluationEnv:m},functionReturnImplConcreteType:[],SelfType:s.substitutions.get("Self")},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),v={...p,specializedType:g,body:d,funcId:`${p.funcId}_specialized_${[...s.substitutions.entries()].map(([T,$])=>`${T}_${A($)}`).join("_")}_${[...s.valueSubstitutions.entries()].map(([T,$])=>`${T}_${Me($)}`).join("_")}`,funcName:p.funcName?`${p.funcName}_specialized`:void 0};return{type:g,value:v}}else if(ne(p)){let f={...p,specializedType:_.type};return{type:_.type,value:f}}else return{type:_.type,value:p}}}}}function Da({concreteType:e,impl:t,env:n}){let r={matched:!1,substitutions:new Map,valueSubstitutions:new Map};if(x(e)){let o=Ot(n,e);if(x(o))return r;e=o}let i=Pe(n);for(let o of t.forallParameters)if(o.kind==="type"){let{env:a}=me({env:i,variable:{name:o.name,type:tt(),isCompileTimeOnly:!0,value:[ee(o.someType)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});i=a}else{let{env:a}=me({env:i,variable:{name:o.name,type:o.type,isCompileTimeOnly:!0,value:[o.unknownValue],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});i=a}try{let{expectedEnv:o}=Ze({type:t.receiverTypePattern,env:i},{type:e,env:n});for(let{someType:l,traitType:u,traitExpr:c}of t.whereConstraints){let _=ju(o,l);if(!_)return r;let p=u;if(c)try{let f=Ae(c),m=S({expr:f,env:o,context:{stdPath:"",isEvaluatingGenericImplSpecialization:!0}});m.$&&O(m.$.value)&&De(m.$.value.value)&&(p=m.$.value.value)}catch{}if(p.isNegatedConstraint){if(x(_)){if(!uy(_,p,n))return r;continue}if(St({targetType:_,traitType:p,env:n}))return r;continue}if(x(_)){if(!ly(_,p,n))return r;continue}if(!St({targetType:_,traitType:p,env:o}))return r}let a=new Map,s=new Map;for(let l of t.forallParameters)if(l.kind==="type"){let u=ju(o,l.someType);u&&!x(u)&&a.set(l.name,u)}else{let u=X(o,l.name),c=u[u.length-1];if(c&&c.value&&!de(c.value[0])){let _={...c.value[0],type:l.type};s.set(l.name,_)}}return a.set("Self",e),{matched:!0,substitutions:a,valueSubstitutions:s}}catch{return r}}function ly(e,t,n){if(!t.typeName)return!1;for(let o of e.requiredTraits)if(o.traitType.id===t.id)return!0;let i=Wn(n,e);if(i){for(let o of i.requiredTraits)if(o.id===t.id)return!0}for(let o of e.trait.fields)if(Tt(o.assignedValue)&&o.assignedValue.type.id===t.id)return!0;return!1}function uy(e,t,n){if(!t.typeName)return!1;if(e.negativeTraits){for(let o of e.negativeTraits)if(o.traitType.id===t.id)return!0}let i=Wn(n,e);if(i){for(let o of i.negativeTraits)if(o.id===t.id)return!0}return!1}function cy({receiverTypePattern:e,traitType:t,whereConstraints:n,env:r,errorToken:i}){if(t.selfConstraints&&t.selfConstraints.length>0)for(let o of t.selfConstraints){if(St({targetType:e,traitType:o,env:r}))continue;let a=new Set;for(let s of n)s.traitType.typeName===o.typeName&&!s.traitType.isNegatedConstraint&&a.add(s.someType.name);throw y({token:i,errorMessage:`Generic impl receiver type "${A(e)}" does not satisfy constraint "${o.typeName??A(o)}" required by trait "${t.typeName??A(t)}".
176
176
  Consider adding "where(T <: ${o.typeName??A(o)})" to the impl.`})}if(t.negativeSelfConstraints&&t.negativeSelfConstraints.length>0){for(let o of t.negativeSelfConstraints)if(St({targetType:e,traitType:o,env:r}))throw y({token:i,errorMessage:`Generic impl receiver type "${A(e)}" implements "${o.typeName??A(o)}" but trait "${t.typeName??A(t)}" requires it to NOT implement this trait.
177
- Consider adding "where(T <: !(${o.typeName??A(o)}))" to the impl.`})}}function ju(e,t){for(let n=e.frames.length-1;n>=0;n--){let r=e.frames[n];for(let i of r.variables)if(i.name===t.name&&i.value&&O(i.value[0]))return i.value[0].value}return t}function zo(e){let t=Po.get(e);if(t){for(let n of t)n.fields=n.fields.filter(r=>r.sourceModulePath!==e);Po.delete(e),ry(e)}}function cy(e,t){let n=Po.get(e);n||(n=new Set,Po.set(e,n)),n.add(t)}function _y(e,t,n){let r=e.type.receiverType;if(!(!r||!r.trait))if(e.type.typeName&&(ay({receiverType:r,traitType:e.type,currentModulePath:n,expr:t}),iy({receiverType:r,traitType:e.type,currentModulePath:n,expr:t}),oy({receiverType:r,traitType:e.type,currentModulePath:n,expr:t})),n&&cy(n,r.trait),e.type.typeName){let i={label:"",type:gn(1),assignedValue:e,sourceModulePath:n,exprs:{expr:t}};r.trait.fields.push(i)}else for(let i=0;i<e.type.fields.length;i++){let o=e.type.fields[i],a=e.fields[i];if(o.label&&G(o.type)&&r.trait.fields.find(u=>u.label===o.label&&G(u.type)))throw y({token:t.token,errorMessage:`Method "${o.label}" is already defined for type "${A(r)}".
177
+ Consider adding "where(T <: !(${o.typeName??A(o)}))" to the impl.`})}}function ju(e,t){for(let n=e.frames.length-1;n>=0;n--){let r=e.frames[n];for(let i of r.variables)if(i.name===t.name&&i.value&&O(i.value[0]))return i.value[0].value}return t}function zo(e){let t=Po.get(e);if(t){for(let n of t)n.fields=n.fields.filter(r=>r.sourceModulePath!==e);Po.delete(e),iy(e)}}function _y(e,t){let n=Po.get(e);n||(n=new Set,Po.set(e,n)),n.add(t)}function py(e,t,n){let r=e.type.receiverType;if(!(!r||!r.trait))if(e.type.typeName&&(sy({receiverType:r,traitType:e.type,currentModulePath:n,expr:t}),oy({receiverType:r,traitType:e.type,currentModulePath:n,expr:t}),ay({receiverType:r,traitType:e.type,currentModulePath:n,expr:t})),n&&_y(n,r.trait),e.type.typeName){let i={label:"",type:gn(1),assignedValue:e,sourceModulePath:n,exprs:{expr:t}};r.trait.fields.push(i)}else for(let i=0;i<e.type.fields.length;i++){let o=e.type.fields[i],a=e.fields[i];if(o.label&&G(o.type)&&r.trait.fields.find(u=>u.label===o.label&&G(u.type)))throw y({token:t.token,errorMessage:`Method "${o.label}" is already defined for type "${A(r)}".
178
178
  Cannot define duplicate method names across impl blocks. Use a different name (e.g., "comptime_${o.label}") for the comptime variant.`});let s={label:o.label,type:o.type,assignedValue:a,sourceModulePath:n,exprs:{expr:t}};r.trait.fields.push(s)}}function Xu({expr:e,env:t,context:n}){if(!E(e,I.impl))throw y({token:e.token,errorMessage:`Expected "impl", got:
179
- ${w(e)}`});if(e.args.length===1&&F(e.args[0])&&E(e.args[0],I.begin)){let $=e.args[0].args,{moduleType:C,moduleValue:L,env:b}=Ia({beginExprs:$,env:t,context:{...n,expectedType:void 0,SelfType:n.SelfType}});return t=b,e.$={env:t,type:C,value:L,pathCollection:[]},e}let r=e.args,i=0,o,a;if(r[i]&&F(r[i])&&E(r[i],I.forall)&&(o=r[i],i++),r[i]&&F(r[i])&&E(r[i],I.where)){if(!o)throw y({token:r[i].token,errorMessage:"impl where(...) requires forall(...) and may appear before or after the receiver type."});a=r[i],i++}if(!r[i])throw y({token:e.token,errorMessage:"impl requires a receiver type and at least one field."});let s=r[i];if(i++,r[i]&&F(r[i])&&E(r[i],I.where)){if(!o)throw y({token:r[i].token,errorMessage:"impl where(...) requires forall(...) and may appear before or after the receiver type."});if(a)throw y({token:r[i].token,errorMessage:"impl supports only a single where(...) clause."});a=r[i],i++}let l=r.slice(i);if(l.length===0)throw y({token:e.token,errorMessage:"impl requires at least one field after the receiver type."});if(!o){let $=S({expr:s,env:t,context:{...n}});if(!$.$||!$.$.value||!O($.$.value))throw y({token:s.token,errorMessage:"Expected type for receiver type argument."});t=$.$.env;let C=$.$.value.value,L=Qe(C)||ke(C),{env:b,traitEntries:R}=qu({fieldExprs:l,env:t,context:{...n},receiverType:C});if(t=b,R.length===0)throw y({token:e.token,errorMessage:"impl requires at least one trait or member field."});for(let B of R){let D=B.traitValue,V=D.type;if(B.isAnonymousTrait||Qu({targetType:C,traitType:V,env:t,errorToken:e.token}),L){let U=Na(V),re={forallParameters:[],whereConstraints:[],receiverTypePattern:C,traitType:V,traitValue:D,expr:e,sourceModulePath:n.currentModulePath,definitionEnv:t};Hu(U,re)}else _y(D,e,n.currentModulePath)}let N=R[0].traitValue;return e.$={env:t,type:N.type,value:N,pathCollection:[]},e}let c=o.args,_=[];t=Pe(t);for(let $ of c){let C,L;if(F($)&&E($,":",2)){let V=$.args[0];if(!z(V))throw y({token:V.token,errorMessage:`Expected identifier for forall parameter name, got: ${w(V)}`});C=V.token.value,L=$.args[1]}else if(z($))C=$.token.value;else throw y({token:$.token,errorMessage:`Expected parameter name or "name : Type" for forall parameter, got: ${w($)}`});let b;if(L){let V=S({expr:L,env:t,context:{...n}});if(V.$?.env&&(t=V.$.env),!V.$||!V.$.value||!O(V.$.value))throw y({token:L.token,errorMessage:`Expected type for forall parameter type, got: ${w(L)}`});b=V.$.value.value}let R=!b||Xl(b),N=b||tt(),B=K(N,{variableName:C,env:t,context:n}),{env:D}=me({env:t,variable:{name:C,type:N,isCompileTimeOnly:!0,value:[B],token:$.token,initializedAtToken:$.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});if(t=D,R){let V=B.value;_.push({kind:"type",name:C,someType:V})}else _.push({kind:"value",name:C,type:N,unknownValue:B})}let p=new Map;if(a)for(let $ of a.args){if(!F($)||!E($,"<:",2))throw y({token:$.token,errorMessage:`Expected constraint in the form "T <: Module", got: ${w($)}`});let C=S({expr:$,env:t,context:{...n,isInsideWhereClause:!0}});C.$?.env&&(t=C.$.env);let L=$.args[0],b=$.args[1],R=S({expr:L,env:t,context:{...n}});if(!R.$||!R.$.value||!O(R.$.value)||!x(R.$.value.value))throw y({token:L.token,errorMessage:`In a where clause, the left-hand side of <: must be a type parameter (SomeType), got: ${w(L)}`});t=R.$.env;let N=[];if(F(b)&&E(b,I.tuple))for(let B of b.args)F(B)&&E(B,"!")&&B.args.length===1?N.push({expr:B.args[0],isNegated:!0}):N.push({expr:B,isNegated:!1});else F(b)&&E(b,"!")&&b.args.length===1?N.push({expr:b.args[0],isNegated:!0}):N.push({expr:b,isNegated:!1});for(let{expr:B}of N){let D=S({expr:B,env:t,context:{...n}});if(!D.$||!D.$.value||!O(D.$.value)||!De(D.$.value.value))throw y({token:B.token,errorMessage:"Expected trait type for right-hand side expression."});t=D.$.env;let V=D.$.value.value;p.set(V.id,Ae(B))}}let f=[];for(let $ of _){if($.kind!=="type")continue;let{someType:C}=$,L=Wn(t,C);if(L){for(let b of L.requiredTraits)f.push({someType:C,traitType:b,traitExpr:p.get(b.id)});for(let b of L.negativeTraits){let R={...b,isNegatedConstraint:!0};f.push({someType:C,traitType:R,traitExpr:p.get(b.id)})}}}let m=S({expr:s,env:t,context:{...n}});if(!m.$||!m.$.value||!O(m.$.value))throw y({token:s.token,errorMessage:"Expected type for receiver type pattern."});t=m.$.env;let g=m.$.value.value,{env:h,traitEntries:d}=qu({fieldExprs:l,env:t,context:{...n},receiverType:g});if(t=h,d.length===0)throw y({token:e.token,errorMessage:"impl requires at least one trait or member field."});let v=[];for(let $ of d){let C=$.traitValue,L=C.type;uy({receiverTypePattern:g,traitType:L,whereConstraints:f,env:t,errorToken:e.token});let{traitTypeArgExprs:b,traitFunctionParamNames:R}=$.isAnonymousTrait?{}:ny({traitExpr:$.sourceExpr,traitType:L});v.push({traitType:L,traitValue:C,traitTypeArgExprs:b,traitFunctionParamNames:R})}t=ct(t);for(let $ of v){let C=Na($.traitType),L={forallParameters:_,whereConstraints:f,receiverTypePattern:g,traitType:$.traitType,traitValue:$.traitValue,expr:e,sourceModulePath:n.currentModulePath,definitionEnv:t,traitTypeArgExprs:$.traitTypeArgExprs,traitFunctionParamNames:$.traitFunctionParamNames};Hu(C,L)}let T=v[0].traitValue;return e.$={env:t,type:T.type,value:T,pathCollection:[]},e}var tl=new Set;function Ju(e){if(!e||ce(e)&&e.isReferenceSemantics)return!1;switch(e.tag){case"comptime_int":case"comptime_float":case"comptime_string":case"Type":case"Module":case"Trait":case"Expr":case"ComptimeList":return!0;case"Iso":case"Arc":case"Dyn":case"void":case"Union":case"char":case"short":case"ushort":case"int":case"uint":case"long":case"ulong":case"longlong":case"ulonglong":case"longdouble":return!1;case"unit":case"bool":case"usize":case"isize":case"u8":case"i8":case"u16":case"i16":case"u32":case"i32":case"u64":case"i64":case"f32":case"f64":case"Function":return!0}if(He(e))return!0}function ec(e){if(!e)return!1;if(ce(e)&&e.isReferenceSemantics)return!0;switch(e.tag){case"comptime_int":case"comptime_float":case"comptime_string":case"Type":case"Module":case"Trait":case"Expr":case"ComptimeList":return!1;case"Iso":case"Arc":case"Dyn":case"void":case"char":case"short":case"ushort":case"int":case"uint":case"long":case"ulong":case"longlong":case"ulonglong":case"longdouble":return!0;case"unit":case"bool":case"usize":case"isize":case"u8":case"i8":case"u16":case"i16":case"u32":case"i32":case"u64":case"i64":case"f32":case"f64":case"Function":case"Union":return!0}}function Zu(e,t,n){if(!t.associatedTypeConstraints||t.associatedTypeConstraints.length===0)return!0;for(let r of t.associatedTypeConstraints){let i;if(e.trait)for(let o of e.trait.fields){if(o.label===r.label&&o.assignedValue&&O(o.assignedValue)){i=o.assignedValue.value;break}if(o.assignedValue&&Tt(o.assignedValue)){let a=o.assignedValue;if(a.type.id===t.id){for(let s=0;s<a.type.fields.length;s++)if(a.type.fields[s].label===r.label){let u=a.fields[s];u&&O(u)&&(i=u.value);break}}if(i)break}}if(!i){let o=xa({concreteType:e,propertyName:r.label,env:n});o&&O(o.value)&&(i=o.value.value)}if(!i||!Y({type:r.constraintType,env:n},{type:i,env:n}))return!1}return!0}function St({targetType:e,traitType:t,env:n}){let r=Vn(n,"Comptime");if(r&&t.id===r.id){let l=Ju(e);if(l!==void 0)return l}let i=Vn(n,"Runtime");if(i&&t.id===i.id){let l=ec(e);if(l!==void 0)return l}let o={...t,receiverType:e},a=e.trait;if(a)for(let l of a.fields){if(!l.assignedValue||!Tt(l.assignedValue))continue;let c=l.assignedValue.type;if(Y({type:o,env:n},{type:c,env:n})&&Zu(e,t,n))return!0}if(be(e)){for(let{traitType:l}of e.requiredTraits){if(l.id===t.id)return!0;if(l.selfConstraints){for(let u of l.selfConstraints)if(u.id===t.id)return!0}}for(let{traitType:l}of e.negativeTraits)if(l.id===t.id)return!1}if(x(e)){let l=!1,u=!1;for(let _ of e.requiredTraits)_.traitType.id===t.id&&(l=!0);let c=Wn(n,e);if(c){for(let _ of c.requiredTraits)_.id===t.id&&(l=!0);for(let _ of c.negativeTraits)_.id===t.id&&(u=!0)}if(e.negativeTraits)for(let _ of e.negativeTraits)_.traitType.id===t.id&&(u=!0);if(l)return!u;if(u)return!1}if(x(e)){let l=Ot(n,e);if(x(l))return!1;e=l}let s=`${e.id}:${t.id}`;if(tl.has(s))return!1;tl.add(s);try{return Va({concreteType:e,traitType:t,env:n})===void 0?!1:Zu(e,t,n)}finally{tl.delete(s)}}function Qu({targetType:e,traitType:t,env:n,errorToken:r}){if(t.selfConstraints&&t.selfConstraints.length>0){for(let i of t.selfConstraints)if(!St({targetType:e,traitType:i,env:n}))throw y({token:r,errorMessage:`Type "${A(e)}" does not implement required constraint "${i.typeName??A(i)}" from trait "${t.typeName??A(t)}"'s where clause.`})}if(t.negativeSelfConstraints&&t.negativeSelfConstraints.length>0){for(let i of t.negativeSelfConstraints)if(St({targetType:e,traitType:i,env:n}))throw y({token:r,errorMessage:`Type "${A(e)}" implements "${i.typeName??A(i)}" but the trait "${t.typeName??A(t)}"'s where clause requires it to NOT implement this trait.`})}}function Xn(e,t){let n=Ju(e);if(n!==void 0)return n;let r=Vn(t,"Comptime");return r?St({targetType:e,traitType:r,env:t}):!1}function Fr(e,t){let n=ec(e);if(n!==void 0)return n;let r=Vn(t,"Runtime");return r?St({targetType:e,traitType:r,env:t}):!1}function Vo(e,t){if(!e)return!1;let n=Vn(t,"Send");return n?St({targetType:e,traitType:n,env:t}):!1}function ni(e,t){if(!e)return!1;let n=Vn(t,"Acyclic");return n?St({targetType:e,traitType:n,env:t}):!1}function li(e,t){return Xn(e,t)&&!Fr(e,t)}function Wt(e){if(!e)return!1;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(bt(t))return!0}return!1}function nn(e){if(bt(e))return e;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(bt(t))return t}}function Ce(e){if(!e)return!1;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(Kt(t))return!0}return!1}function Dt(e){if(Kt(e))return e;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(Kt(t))return t}}function Ta(e,t,n,r){if(!Fe(e)&&!Xn(e,t)&&!Fr(e,t))throw y({token:n,errorMessage:`Type ${A(e)} has incompatible field contexts and cannot be used in any evaluation context.
179
+ ${w(e)}`});if(e.args.length===1&&F(e.args[0])&&E(e.args[0],I.begin)){let $=e.args[0].args,{moduleType:C,moduleValue:L,env:b}=Ia({beginExprs:$,env:t,context:{...n,expectedType:void 0,SelfType:n.SelfType}});return t=b,e.$={env:t,type:C,value:L,pathCollection:[]},e}let r=e.args,i=0,o,a;if(r[i]&&F(r[i])&&E(r[i],I.forall)&&(o=r[i],i++),r[i]&&F(r[i])&&E(r[i],I.where)){if(!o)throw y({token:r[i].token,errorMessage:"impl where(...) requires forall(...) and may appear before or after the receiver type."});a=r[i],i++}if(!r[i])throw y({token:e.token,errorMessage:"impl requires a receiver type and at least one field."});let s=r[i];if(i++,r[i]&&F(r[i])&&E(r[i],I.where)){if(!o)throw y({token:r[i].token,errorMessage:"impl where(...) requires forall(...) and may appear before or after the receiver type."});if(a)throw y({token:r[i].token,errorMessage:"impl supports only a single where(...) clause."});a=r[i],i++}let l=r.slice(i);if(l.length===0)throw y({token:e.token,errorMessage:"impl requires at least one field after the receiver type."});if(!o){let $=S({expr:s,env:t,context:{...n}});if(!$.$||!$.$.value||!O($.$.value))throw y({token:s.token,errorMessage:"Expected type for receiver type argument."});t=$.$.env;let C=$.$.value.value,L=Qe(C)||ke(C),{env:b,traitEntries:R}=qu({fieldExprs:l,env:t,context:{...n},receiverType:C});if(t=b,R.length===0)throw y({token:e.token,errorMessage:"impl requires at least one trait or member field."});for(let B of R){let D=B.traitValue,V=D.type;if(B.isAnonymousTrait||Qu({targetType:C,traitType:V,env:t,errorToken:e.token}),L){let U=Na(V),re={forallParameters:[],whereConstraints:[],receiverTypePattern:C,traitType:V,traitValue:D,expr:e,sourceModulePath:n.currentModulePath,definitionEnv:t};Hu(U,re)}else py(D,e,n.currentModulePath)}let N=R[0].traitValue;return e.$={env:t,type:N.type,value:N,pathCollection:[]},e}let c=o.args,_=[];t=Pe(t);for(let $ of c){let C,L;if(F($)&&E($,":",2)){let V=$.args[0];if(!z(V))throw y({token:V.token,errorMessage:`Expected identifier for forall parameter name, got: ${w(V)}`});C=V.token.value,L=$.args[1]}else if(z($))C=$.token.value;else throw y({token:$.token,errorMessage:`Expected parameter name or "name : Type" for forall parameter, got: ${w($)}`});let b;if(L){let V=S({expr:L,env:t,context:{...n}});if(V.$?.env&&(t=V.$.env),!V.$||!V.$.value||!O(V.$.value))throw y({token:L.token,errorMessage:`Expected type for forall parameter type, got: ${w(L)}`});b=V.$.value.value}let R=!b||Xl(b),N=b||tt(),B=K(N,{variableName:C,env:t,context:n}),{env:D}=me({env:t,variable:{name:C,type:N,isCompileTimeOnly:!0,value:[B],token:$.token,initializedAtToken:$.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});if(t=D,R){let V=B.value;_.push({kind:"type",name:C,someType:V})}else _.push({kind:"value",name:C,type:N,unknownValue:B})}let p=new Map;if(a)for(let $ of a.args){if(!F($)||!E($,"<:",2))throw y({token:$.token,errorMessage:`Expected constraint in the form "T <: Module", got: ${w($)}`});let C=S({expr:$,env:t,context:{...n,isInsideWhereClause:!0}});C.$?.env&&(t=C.$.env);let L=$.args[0],b=$.args[1],R=S({expr:L,env:t,context:{...n}});if(!R.$||!R.$.value||!O(R.$.value)||!x(R.$.value.value))throw y({token:L.token,errorMessage:`In a where clause, the left-hand side of <: must be a type parameter (SomeType), got: ${w(L)}`});t=R.$.env;let N=[];if(F(b)&&E(b,I.tuple))for(let B of b.args)F(B)&&E(B,"!")&&B.args.length===1?N.push({expr:B.args[0],isNegated:!0}):N.push({expr:B,isNegated:!1});else F(b)&&E(b,"!")&&b.args.length===1?N.push({expr:b.args[0],isNegated:!0}):N.push({expr:b,isNegated:!1});for(let{expr:B}of N){let D=S({expr:B,env:t,context:{...n}});if(!D.$||!D.$.value||!O(D.$.value)||!De(D.$.value.value))throw y({token:B.token,errorMessage:"Expected trait type for right-hand side expression."});t=D.$.env;let V=D.$.value.value;p.set(V.id,Ae(B))}}let f=[];for(let $ of _){if($.kind!=="type")continue;let{someType:C}=$,L=Wn(t,C);if(L){for(let b of L.requiredTraits)f.push({someType:C,traitType:b,traitExpr:p.get(b.id)});for(let b of L.negativeTraits){let R={...b,isNegatedConstraint:!0};f.push({someType:C,traitType:R,traitExpr:p.get(b.id)})}}}let m=S({expr:s,env:t,context:{...n}});if(!m.$||!m.$.value||!O(m.$.value))throw y({token:s.token,errorMessage:"Expected type for receiver type pattern."});t=m.$.env;let g=m.$.value.value,{env:h,traitEntries:d}=qu({fieldExprs:l,env:t,context:{...n},receiverType:g});if(t=h,d.length===0)throw y({token:e.token,errorMessage:"impl requires at least one trait or member field."});let v=[];for(let $ of d){let C=$.traitValue,L=C.type;cy({receiverTypePattern:g,traitType:L,whereConstraints:f,env:t,errorToken:e.token});let{traitTypeArgExprs:b,traitFunctionParamNames:R}=$.isAnonymousTrait?{}:ry({traitExpr:$.sourceExpr,traitType:L});v.push({traitType:L,traitValue:C,traitTypeArgExprs:b,traitFunctionParamNames:R})}t=ct(t);for(let $ of v){let C=Na($.traitType),L={forallParameters:_,whereConstraints:f,receiverTypePattern:g,traitType:$.traitType,traitValue:$.traitValue,expr:e,sourceModulePath:n.currentModulePath,definitionEnv:t,traitTypeArgExprs:$.traitTypeArgExprs,traitFunctionParamNames:$.traitFunctionParamNames};Hu(C,L)}let T=v[0].traitValue;return e.$={env:t,type:T.type,value:T,pathCollection:[]},e}var tl=new Set;function Ju(e){if(!e||ce(e)&&e.isReferenceSemantics)return!1;switch(e.tag){case"comptime_int":case"comptime_float":case"comptime_string":case"Type":case"Module":case"Trait":case"Expr":case"ComptimeList":return!0;case"Iso":case"Arc":case"Dyn":case"void":case"Union":case"char":case"short":case"ushort":case"int":case"uint":case"long":case"ulong":case"longlong":case"ulonglong":case"longdouble":return!1;case"unit":case"bool":case"usize":case"isize":case"u8":case"i8":case"u16":case"i16":case"u32":case"i32":case"u64":case"i64":case"f32":case"f64":case"Function":return!0}if(He(e))return!0}function ec(e){if(!e)return!1;if(ce(e)&&e.isReferenceSemantics)return!0;switch(e.tag){case"comptime_int":case"comptime_float":case"comptime_string":case"Type":case"Module":case"Trait":case"Expr":case"ComptimeList":return!1;case"Iso":case"Arc":case"Dyn":case"void":case"char":case"short":case"ushort":case"int":case"uint":case"long":case"ulong":case"longlong":case"ulonglong":case"longdouble":return!0;case"unit":case"bool":case"usize":case"isize":case"u8":case"i8":case"u16":case"i16":case"u32":case"i32":case"u64":case"i64":case"f32":case"f64":case"Function":case"Union":return!0}}function Zu(e,t,n){if(!t.associatedTypeConstraints||t.associatedTypeConstraints.length===0)return!0;for(let r of t.associatedTypeConstraints){let i;if(e.trait)for(let o of e.trait.fields){if(o.label===r.label&&o.assignedValue&&O(o.assignedValue)){i=o.assignedValue.value;break}if(o.assignedValue&&Tt(o.assignedValue)){let a=o.assignedValue;if(a.type.id===t.id){for(let s=0;s<a.type.fields.length;s++)if(a.type.fields[s].label===r.label){let u=a.fields[s];u&&O(u)&&(i=u.value);break}}if(i)break}}if(!i){let o=xa({concreteType:e,propertyName:r.label,env:n});o&&O(o.value)&&(i=o.value.value)}if(!i||!Y({type:r.constraintType,env:n},{type:i,env:n}))return!1}return!0}function St({targetType:e,traitType:t,env:n}){let r=Vn(n,"Comptime");if(r&&t.id===r.id){let l=Ju(e);if(l!==void 0)return l}let i=Vn(n,"Runtime");if(i&&t.id===i.id){let l=ec(e);if(l!==void 0)return l}let o={...t,receiverType:e},a=e.trait;if(a)for(let l of a.fields){if(!l.assignedValue||!Tt(l.assignedValue))continue;let c=l.assignedValue.type;if(Y({type:o,env:n},{type:c,env:n})&&Zu(e,t,n))return!0}if(be(e)){for(let{traitType:l}of e.requiredTraits){if(l.id===t.id)return!0;if(l.selfConstraints){for(let u of l.selfConstraints)if(u.id===t.id)return!0}}for(let{traitType:l}of e.negativeTraits)if(l.id===t.id)return!1}if(x(e)){let l=!1,u=!1;for(let _ of e.requiredTraits)_.traitType.id===t.id&&(l=!0);let c=Wn(n,e);if(c){for(let _ of c.requiredTraits)_.id===t.id&&(l=!0);for(let _ of c.negativeTraits)_.id===t.id&&(u=!0)}if(e.negativeTraits)for(let _ of e.negativeTraits)_.traitType.id===t.id&&(u=!0);if(l)return!u;if(u)return!1}if(x(e)){let l=Ot(n,e);if(x(l))return!1;e=l}let s=`${e.id}:${t.id}`;if(tl.has(s))return!1;tl.add(s);try{return Va({concreteType:e,traitType:t,env:n})===void 0?!1:Zu(e,t,n)}finally{tl.delete(s)}}function Qu({targetType:e,traitType:t,env:n,errorToken:r}){if(t.selfConstraints&&t.selfConstraints.length>0){for(let i of t.selfConstraints)if(!St({targetType:e,traitType:i,env:n}))throw y({token:r,errorMessage:`Type "${A(e)}" does not implement required constraint "${i.typeName??A(i)}" from trait "${t.typeName??A(t)}"'s where clause.`})}if(t.negativeSelfConstraints&&t.negativeSelfConstraints.length>0){for(let i of t.negativeSelfConstraints)if(St({targetType:e,traitType:i,env:n}))throw y({token:r,errorMessage:`Type "${A(e)}" implements "${i.typeName??A(i)}" but the trait "${t.typeName??A(t)}"'s where clause requires it to NOT implement this trait.`})}}function Xn(e,t){let n=Ju(e);if(n!==void 0)return n;let r=Vn(t,"Comptime");return r?St({targetType:e,traitType:r,env:t}):!1}function Fr(e,t){let n=ec(e);if(n!==void 0)return n;let r=Vn(t,"Runtime");return r?St({targetType:e,traitType:r,env:t}):!1}function Vo(e,t){if(!e)return!1;let n=Vn(t,"Send");return n?St({targetType:e,traitType:n,env:t}):!1}function ni(e,t){if(!e)return!1;let n=Vn(t,"Acyclic");return n?St({targetType:e,traitType:n,env:t}):!1}function li(e,t){return Xn(e,t)&&!Fr(e,t)}function Wt(e){if(!e)return!1;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(kt(t))return!0}return!1}function nn(e){if(kt(e))return e;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(kt(t))return t}}function Ce(e){if(!e)return!1;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(Kt(t))return!0}return!1}function Dt(e){if(Kt(e))return e;if(x(e)||be(e)){for(let{traitType:t}of e.requiredTraits)if(Kt(t))return t}}function Ta(e,t,n,r){if(!Fe(e)&&!Xn(e,t)&&!Fr(e,t))throw y({token:n,errorMessage:`Type ${A(e)} has incompatible field contexts and cannot be used in any evaluation context.
180
180
 
181
181
  This typically happens when a struct/enum/array/tuple contains fields with conflicting availability:
182
182
  - Compile-time only fields (e.g., comptime_int, Type, Module)
183
183
  - Runtime only fields (e.g., *(T), [T], void, C-compatible types)
184
184
 
185
- Consider restructuring the type to avoid mixing incompatible field types.`})}function an(e,t=!0,n){switch(e.tag){case"ComptimeInt":case"ComptimeFloat":case"U8":case"I8":case"U16":case"I16":case"U32":case"I32":case"U64":case"I64":case"F32":case"F64":case"Usize":case"Isize":return e;case"Bool":return e;case"Unit":return e;case"ComptimeString":return e;case"Type":return e;case"Function":return e;case"Expr":return e;case"Unknown":return e;case"Ptr":{if(t)return e;let r=e;if(n){let a=n.get(r.targetValue);if(a)return{...r,targetValue:a,targetIndex:r.targetIndex}}let o=[an(r.targetValue[0],t,n)];return n&&n.set(r.targetValue,o),{...r,targetValue:o,targetIndex:r.targetIndex}}case"Tuple":{let r=e;return{...r,fields:r.fields.map(i=>an(i,t,n))}}case"Struct":{let r=e;return{...r,fields:r.fields.map(i=>an(i,t,n))}}case"Enum":{let r=e;return{...r,fields:r.fields.map(i=>an(i,t,n))}}case"Array":{let r=e;return{...r,elements:r.elements.map(i=>an(i,t,n))}}case"Slice":{if(t)return e;let r=e;if(n){let a=n.get(r.sourceArray);if(a)return{...r,sourceArray:a}}let o=[an(r.sourceArray[0],t,n)];return n&&n.set(r.sourceArray,o),{...r,sourceArray:o}}case"ComptimeList":{let r=e;return{...r,elements:r.elements.map(i=>an(i,t,n))}}case"Module":{let r=e;return{...r,fields:r.fields.map(i=>i?an(i,t,n):void 0)}}case"Trait":{let r=e;return{...r,fields:r.fields.map(i=>i?an(i,t,n):void 0)}}default:return e}}function nl({modulePath:e,inputString:t}){return{functionDeclarationFrameLevel:-1,frames:[],modulePath:e,inputString:t}}function at(){let e=nl({modulePath:"",inputString:""});return Pe(e)}function rl(e){let t=new Map,n=[...e.frames.flatMap(o=>o.variables)];for(let o of n)if(o.value&&!t.has(o.value)){let a=an(o.value[0],!1,t);t.has(o.value)||t.set(o.value,[a])}let r=o=>{if(!o.value)return{...o};let a=t.get(o.value);if(a)return{...o,value:a};let s=an(o.value[0],!1,t);return{...o,value:[s]}},i=o=>({...o,variables:o.variables.map(r),whereClauseConstraints:py(o.whereClauseConstraints)});return{...e,frames:e.frames.map(i)}}function py(e){let t=new Map;for(let[n,r]of e)t.set(n,{someType:r.someType,requiredTraits:[...r.requiredTraits],negativeTraits:[...r.negativeTraits]});return t}function er({env:e,someType:t,traitType:n,isNegated:r}){let i=e.frames.length-1,o=e.frames[i];if(!o)return e;let a=t.id,s=o.whereClauseConstraints.get(a);s||(s={someType:t,requiredTraits:[],negativeTraits:[]},o.whereClauseConstraints.set(a,s));let l=r?s.negativeTraits:s.requiredTraits;return l.some(u=>u.id===n.id)||l.push(n),e}function Wn(e,t){let n=[],r=[],i=new Set,o=new Set,a=!1,s=new Set;for(let l of e.frames)for(let u of l.variables){let c=u.value?.[0];O(c)&&x(c.value)&&c.value.id===t.id&&s.add(u.name)}for(let l of e.frames)for(let u of l.whereClauseConstraints.values())if(!(u.someType.id!==t.id&&!s.has(u.someType.name))){a=!0;for(let c of u.requiredTraits)i.has(c.id)||(i.add(c.id),n.push(c));for(let c of u.negativeTraits)o.has(c.id)||(o.add(c.id),r.push(c))}if(a)return{requiredTraits:n,negativeTraits:r}}var tc=null;function nc(e){tc=e}function rc(){tc=null}var fy="__yo_self";function me({env:e,variable:t,deltaFrame:n,variableId:r,addToBeginBlockFrame:i,allowVariableShadowing:o}){let a=e.frames.length-1+(n??0);if(i){let f=yy(e);f>=0&&(a=f)}if(t.name!==fy){let f=X(e,t.name);if(f.length>0&&!o){let m=f[f.length-1];throw lt([{token:t.token,errorMessage:`Failed to define variable "${t.name}":`},{token:m.token,errorMessage:`Variable "${t.name}" is already defined here (variable shadowing is not allowed):`}])}}let s=e.frames[a];if(!s)throw console.trace(`Frame at level ${a} does not exist in the environment.`),new Error(`Frame at level ${a} does not exist in the environment.`);let l=ut(e.modulePath,t.name)?t.name:r??ri(e.modulePath,t.name),u={...t,frameLevel:a,id:l},c=dy({frame:s,variable:u}),_=e.frames.slice();return _[a]=c,{env:{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:_,modulePath:e.modulePath,inputString:e.inputString},variable:u}}function dy({frame:e,variable:t}){if(t.name==="_")return e;if(e.variables.some(r=>r.name===t.name))throw lt([{token:t.token,errorMessage:`Failed to define variable "${t.name}":`},{token:e.variables.find(r=>r.name===t.name).token,errorMessage:`Variable "${t.name}" is already defined here in the same scope:`}]);let n=e.variables.findIndex(r=>r.name===t.name&&!r.initializedAtToken);if(n>-1){let r=e.variables.slice();return r[n]=t,{id:e.id,variables:r,isBeginBlockFrame:e.isBeginBlockFrame,whereClauseConstraints:new Map(e.whereClauseConstraints)}}return{id:e.id,variables:[...e.variables,t],isBeginBlockFrame:e.isBeginBlockFrame,whereClauseConstraints:new Map(e.whereClauseConstraints)}}function my(e,t,n){let r=e.variables.filter(i=>i.name===t);return n?r.filter(n):r}function X(e,t,n){let r=[];for(let i=0;i<e.frames.length;i++){let o=e.frames[i],a=my(o,t,n);r.push(...a)}return n?r.filter(n):r}function fn(e,t){let n=[];for(let r=0;r<e.frames.length;r++){let o=e.frames[r].variables.filter(t);n.push(...o)}return n}function Bo(e,t){for(let n=e.frames.length-1;n>=0;n--)if(e.frames[n].variables.some(t))return n;return-1}function Pe(e,t={id:ri(e.modulePath,"frame"),variables:[],isBeginBlockFrame:!1,whereClauseConstraints:new Map},n){let r=n?{...t,isBeginBlockFrame:!0}:t;return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:[...e.frames,r],modulePath:e.modulePath,inputString:e.inputString}}function ct(e,t=!1){let n=e.frames.length-1,r=e.frames[n];if(!t){let i=ji(e),o=r.variables.filter(a=>!a.initializedAtToken);if(i.length>0)throw lt(i.map(a=>({token:a.token,errorMessage:`Variable "${a.name}" was not consumed. It is supposed to be consumed before going out of scope.
186
- Typeof "${a.name}": ${A(a.type)}`})));if(o.length>0)throw lt(o.map(a=>({token:a.token,errorMessage:`Variable "${a.name}" is undefined.`})))}return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:e.frames.slice(0,-1),modulePath:e.modulePath,inputString:e.inputString}}function Be(e,t,n){let r=e.frames.map(i=>{let o=i.variables.map(a=>a.id===t.id?n:a);return{...i,variables:o}});return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:r,modulePath:e.modulePath,inputString:e.inputString}}function ic(e){return{id:e.id,name:e.name,type:A(e.type),typeId:e.type.id,value:Me(e.value?.[0]),isCompileTimeOnly:e.isCompileTimeOnly,isUndefined:!e.initializedAtToken,isOwningTheRcValue:!!e.isOwningTheRcValue,isOwningTheSameRcValueAs:e.isOwningTheSameRcValueAs?.name,isReassignable:!!e.isReassignable,isConsumed:!!e.consumedAtToken}}function oc({env:e,context:t,methodName:n,type:r}){let i=[];if(!r.trait)return i;let o=r.trait.fields.find(a=>a.label===n&&G(a.type));if(o&&G(o.type)){let a=o.assignedValue;de(a)&&(a=K(o.type,{variableName:o.label,env:e,context:t})),i.push({type:o.type,value:a})}for(let a of r.trait.fields)if(a.label===""&&a.assignedValue&&Tt(a.assignedValue)){let s=a.assignedValue,l=s.type,u=l.fields.findIndex(c=>c.label===n&&G(c.type));if(u>=0){let c=l.fields[u];if(G(c.type)){let _=s.fields[u],p=c.type;ne(_)&&_.specializedType&&(p=_.specializedType),i.push({type:p,value:_})}}}if(i.length===0){let a=Jn({concreteType:r,methodName:n,env:e});i.push(...a)}return i}function il({env:e,context:t,methodName:n,receiverType:r,isInfixOperatorCall:i}){let o=[],a=r;for(;Ie(a);)a=a.childType;function s(p,f){let m=p.fields.find(g=>g.label===n&&(G(g.type)||De(g.type)));if(m){let g;if(G(m.type)){if(de(f))g=K(m.type,{variableName:m.label,env:e,context:t});else if(Tt(f)){let h=p.fields.findIndex(d=>d.label===m.label);g=f.fields[h]}o.push({type:m.type,value:g})}else if(Te(m.type)){let h=m.assignedValue;We(h)&&l(h)}}if(!m)for(let g of p.fields)De(g.type)&&g.assignedValue&&s(g.type,g.assignedValue)}function l(p){let f=p.type.fields.findIndex(m=>m.label==="Call");if(f>=0){let m=p.type.fields[f];if(m.assignedValue){let g=m.assignedValue;hn(g)?g.fields.forEach(h=>{o.push({type:h.type,value:h})}):o.push({type:g.type,value:g})}}}function u(p){return p.filter(m=>{if(G(m.type)){if(m.type.parameters.length===0)return!1;let h=m.type.parameters[0].type;if(!i&&Ie(h)){let v=h.childType,T=r;if((vt(r)||Nt(r)||Et(r))&&(T=yt({type:r,expectedType:void 0,expr:void 0,env:e})),Y({type:v,env:m.type.env},{type:T,env:e},!0))return m.needsPointerConversion=!0,!0}if(Fe(h)||Fe(h)&&!Fe(r)||x(r)&&r.resolvedConcreteType&&!Ce(r)&&!Fe(h)&&Y({type:h,env:m.type.env},{type:r.resolvedConcreteType,env:e},!0))return!0;if(!Fe(h)&&Fe(r))return!1;if(vt(r)||Nt(r)||Et(r)){let v=yt({type:r,expectedType:void 0,expr:void 0,env:e});if(Y({type:h,env:m.type.env},{type:v,env:e},!0))return!0}if(be(r)&&m.value===void 0){if(m.type.parameters.length>0&&m.type.SelfType){let T=m.type.parameters[0];if(T){let $=T.type;if(!pt($)&&!be($)&&!Ie($))return!1}}let v=m.type.return.type;if(cr(v,m.type.SelfType))return!1}return Y({type:h,env:m.type.env},{type:r,env:e},!0)}return!0})}function c(p,f,m=new Set){if(m.has(p.id))return;m.add(p.id);let g=p.fields.find(h=>h.label===f&&G(h.type));if(g&&G(g.type)){let h=g.assignedValue;de(h)&&(h=K(g.type,{variableName:g.label,env:e,context:t})),o.push({type:g.type,value:h});return}for(let h of p.fields)De(h.type)&&h.assignedValue&&s(h.type,h.assignedValue)}if(r!==a&&r.trait){let p=r.trait.fields.find(f=>f.label===n&&G(f.type));if(p&&G(p.type)){let f=p.assignedValue;de(f)&&(f=K(p.type,{variableName:p.label,env:e,context:t})),o.push({type:p.type,value:f})}else c(r.trait,n);for(let f of r.trait.fields)if(f.label===""&&f.assignedValue&&Tt(f.assignedValue)){let m=f.assignedValue,g=m.type,h=g.fields.findIndex(d=>d.label===n&&G(d.type));if(h>=0){let d=g.fields[h];if(G(d.type)){let v=m.fields[h],T=d.type;ne(v)&&v.specializedType&&(T=v.specializedType),o.push({type:T,value:v})}}}}if(o.length===0&&r!==a){let p=Jn({concreteType:r,methodName:n,env:e});o.push(...p)}let _=x(a)&&a.resolvedConcreteType&&!Ce(a);if(a.trait&&!be(a)&&!_){let p=a.trait.fields.find(f=>f.label===n&&(G(f.type)||Te(f.type)));if(p&&G(p.type)){let f=p.assignedValue;de(f)&&(f=K(p.type,{variableName:p.label,env:e,context:t})),o.push({type:p.type,value:f})}else if(p&&Te(p.type)){let f=p.assignedValue;We(f)&&l(f)}else c(a.trait,n);for(let f of a.trait.fields)if(f.label===""&&f.assignedValue&&Tt(f.assignedValue)){let m=f.assignedValue,g=m.type,h=g.fields.findIndex(d=>d.label===n&&G(d.type));if(h>=0){let d=g.fields[h];if(G(d.type)){let v=m.fields[h],T=d.type;ne(v)&&v.specializedType&&(T=v.specializedType),o.push({type:T,value:v})}}}if(o.length===0){let f=Jn({concreteType:a,methodName:n,env:e});o.push(...f)}}if(vt(a)||Nt(a)||Et(a)){let p=yt({type:a,expectedType:void 0,expr:void 0,env:e});if(p.trait){let f=p.trait.fields.find(m=>m.label===n&&G(m.type));if(f&&G(f.type)){let m=f.assignedValue;de(m)&&(m=K(f.type,{variableName:f.label,env:e,context:t})),o.push({type:f.type,value:m})}else c(p.trait,n);for(let m of p.trait.fields)if(m.label===""&&m.assignedValue&&Tt(m.assignedValue)){let g=m.assignedValue,h=g.type,d=h.fields.findIndex(v=>v.label===n&&G(v.type));if(d>=0){let v=h.fields[d];if(G(v.type)){let T=g.fields[d],$=v.type;ne(T)&&T.specializedType&&($=T.specializedType),o.push({type:$,value:T})}}}if(o.length===0){let m=Jn({concreteType:p,methodName:n,env:e});o.push(...m)}}}if(x(a)){if(a.resolvedConcreteType?.trait&&!Ce(a)){let p=a.resolvedConcreteType,f=p.trait,m=f?.fields.find(g=>g.label===n&&G(g.type));if(m&&G(m.type)){let g=m.assignedValue||K(m.type,{variableName:m.label,env:e,context:t});o.push({type:m.type,value:g})}if(o.length===0){for(let g of f?.fields??[])if(g.label===""&&g.assignedValue&&Tt(g.assignedValue)){let h=g.assignedValue,d=h.type,v=d.fields.findIndex(T=>T.label===n&&G(T.type));if(v>=0){let T=d.fields[v];if(G(T.type)){let $=h.fields[v],C=T.type;ne($)&&$.specializedType&&(C=$.specializedType),o.push({type:C,value:$});break}}}}if(o.length===0){let g=Jn({concreteType:p,methodName:n,env:e});o.push(...g)}}if(!(o.length>0)){let p=[],f=new Set;for(let g of a.requiredTraits??[])f.has(g.traitType.id)||(f.add(g.traitType.id),p.push(g.traitType));let m=Wn(e,a);if(m)for(let g of m.requiredTraits)f.has(g.id)||(f.add(g.id),p.push(g));if(x(a))for(let g=e.frames.length-1;g>=0;g--){let h=e.frames[g];for(let d of h.whereClauseConstraints.values())if(Y({type:d.someType,env:e},{type:a,env:e},!1))for(let v of d.requiredTraits)f.has(v.id)||(f.add(v.id),p.push(v))}for(let g of p){let h=g.fields.find(d=>d.label===n&&G(d.type));if(h&&G(h.type)){let d={...h.type,SelfType:a},v=!1;if(d.parameters.length>0&&Ie(d.parameters[0].type)){let $=d.parameters[0].type.childType;(x($)&&$.name==="Self"||Y({type:$,env:d.env},{type:r,env:e},!0))&&(v=!0)}let T=K(d,{variableName:h.label,env:e,context:t});o.push({type:d,value:T,needsPointerConversion:v})}}if(o.length===0){for(let g of a.trait.fields)if(g.label===""&&g.assignedValue&&O(g.assignedValue)&&De(g.assignedValue.value)){let d=g.assignedValue.value.fields.find(v=>v.label===n&&G(v.type));if(d&&G(d.type)){let v=K(d.type,{variableName:d.label,env:e,context:t});o.push({type:d.type,value:v})}}}}}if(be(a)){let p=a.trait.fields.find(m=>m.label===n&&(G(m.type)||De(m.type)));if(p&&G(p.type)){let m=p.assignedValue||K(p.type,{variableName:p.label,env:e,context:t});o.push({type:p.type,value:m})}let f=a.requiredTraits;for(let{traitType:m}of f){let g=m.fields.find(h=>h.label===n&&(G(h.type)||De(h.type)));g&&G(g.type)&&g.type.parameters.length>0&&(Fe(g.type.parameters[0].type)||Fe(r)||Y({type:g.type.parameters[0].type,env:g.type.env},{type:r,env:e},!0))&&o.push({type:g.type,value:void 0})}}return o.length>0,u(o)}function ac(e){let t=e.frames.map(n=>({...n,variables:n.variables.filter(r=>!r.isImplicit)}));return{...e,frames:t}}function Ma(e){let t=e.frames.map((n,r)=>{if(r===0)return n;let i=n.variables.filter(o=>!(!o.isCompileTimeOnly||o.isImplicit));return{...n,variables:i}});return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:t,modulePath:e.modulePath,inputString:e.inputString}}function ji(e){return e.frames.length===0?[]:e.frames[e.frames.length-1].variables.filter(r=>{if(r.consumedAtToken||!r.isOwningTheRcValue||!Le(r.type))return!1;let i=r.type;return!(x(i)&&!i.resolvedConcreteType&&i.requiredTraits.length===0)}).reverse()}function yy(e){for(let t=e.frames.length-1;t>=0;t--)if(e.frames[t]?.isBeginBlockFrame)return t;return-1}var vy=process.env.YO_SKIP_PRELUDE==="1"||process.env.YO_SKIP_PRELUDE==="true";function Ty(e,t){return e.some(n=>(n.type==="single_line_comment"||n.type==="multi_line_comment")&&n.value.includes(t))}var Go=class{constructor({modulePath:t,stdPath:n,loadModule:r,inputString:i,allowPartialModule:o=!1}){if(this.modulePath=t,this.allowPartialModule=o,!this.modulePath.match(/^file:\/\//))throw new Error(`Invalid file protocol: ${this.modulePath}. Only file:// is supported for now. `);try{if(this.inputString=i??gy(t.replace(/^file:\/\//,""),"utf-8"),this.parser=new bi({modulePath:t,inputString:this.inputString}),this.program=this.parser.getProgram(),this.tokens=this.parser.getTokens(),!this.allowPartialModule&&this.parser.getParserError())throw this.parser.getParserError();this.evaluateProgram(n,r)}catch(a){throw new Error(`Failed to import module "${t}":
187
- ${a instanceof yn||a instanceof Sn?a.toString():a instanceof Error?a.message:String(a)}`)}}getProgram(){return this.program}getTokens(){return this.tokens}evaluateProgram(t,n){let r=nl({modulePath:this.modulePath,inputString:this.inputString});if(!Ty(this.tokens,"@skip_prelude")&&!vy){let l="file://"+hy.join(t,"prelude.yo"),{moduleValue:u,moduleError:c}=n(l);if(c)throw c;if(u&&Te(u.type)){r=Pe(r);for(let _=0;_<u.type.fields.length;_++){let p=u.type.fields[_],f=u.fields[_],{env:m}=me({env:r,variable:{name:p.label,type:p.type,value:f?[f]:void 0,isCompileTimeOnly:!0,initializedAtToken:p.exprs.labelExpr?.token??p.exprs.expr.token,consumedAtToken:void 0,token:p.exprs.labelExpr?.token??p.exprs.expr.token,isOwningTheRcValue:!1}});r=m}}nc(r)}let{moduleValue:o,env:a,partialModuleError:s}=Ia({beginExprs:this.program,env:r,context:{isExecuting:!0,expectedType:void 0,SelfType:void 0,loadModule:n.bind(this),stdPath:t,currentModulePath:this.modulePath},allowPartialModule:this.allowPartialModule});r=a,this.moduleValue=o,this.moduleError=s}getModuleValue(){if(!this.moduleValue)throw new Error("Module value is not set");return this.moduleValue}getModuleError(){return this.parser.getParserError()??this.moduleError}};function f$(...e){process.env.NODE_ENV!=="production"&&process.env.DEBUG&&console.log(...e)}import{existsSync as xh}from"fs";import*as ia from"path";function Ey(e){switch(e){case"x86_64":case"aarch64":return 64;case"x86":case"arm":case"wasm32":return 32}}var sc={darwin:"macos",linux:"linux",win32:"windows",freebsd:"freebsd"},lc={x64:"x86_64",arm64:"aarch64",ia32:"x86",arm:"arm"},Oa;function $y(){if(Oa)return Oa;let e=sc[process.platform];if(!e)throw new Error(`Unsupported host platform: ${process.platform}. Supported: ${Object.keys(sc).join(", ")}`);let t=lc[process.arch];if(!t)throw new Error(`Unsupported host architecture: ${process.arch}. Supported: ${Object.keys(lc).join(", ")}`);return Oa={platform:e,arch:t},Oa}function pc(e){switch(e){case"linux":return"gnu";case"windows":return"msvc";case"wasi":return"wasm";case"macos":case"freebsd":return}}function Cy(e,t,n){return n?`${e}-${t}-${n}`:`${e}-${t}`}function fc(e,t,n){return{arch:e,os:t,abi:n,pointerSizeBits:Ey(e),triple:Cy(e,t,n)}}function Gr(){let e=$y(),t=pc(e.platform);return fc(e.arch,e.platform,t)}var uc=new Set(["x86_64","aarch64","x86","arm","wasm32"]),cc=new Set(["linux","macos","windows","freebsd","wasi"]),_c=new Set(["gnu","musl","msvc","none","wasm"]);function dc(e){let t=e.split("-");if(t.length<2||t.length>3)throw new Error(`Invalid target triple "${e}". Expected format: <arch>-<os> or <arch>-<os>-<abi>. Example: x86_64-linux-gnu`);let n=t[0],r=t[1],i=t[2];if(!uc.has(n))throw new Error(`Unknown architecture "${n}" in target triple "${e}". Supported: ${[...uc].join(", ")}`);if(!cc.has(r))throw new Error(`Unknown OS "${r}" in target triple "${e}". Supported: ${[...cc].join(", ")}`);let o=n,a=r,s;if(i!==void 0)if(i==="none")s=void 0;else if(_c.has(i))s=i;else throw new Error(`Unknown ABI "${i}" in target triple "${e}". Supported: ${[..._c].join(", ")}`);else s=pc(a);return fc(o,a,s)}var ol;function Wo(){return ol||(ol=Gr()),ol}function zt(e){return e.os==="windows"}function mi(e){return e.os==="linux"}function qn(e){return e.os==="macos"}function yi(e){return e.arch==="wasm32"||e.os==="wasi"}function mc(e){for(let t in e.types){let{type:n}=e.types[t];n.cInclude&&e.cIncludes.add(n.cInclude)}for(let t in e.externFunctions){let{type:n}=e.externFunctions[t];n.cInclude&&e.cIncludes.add(n.cInclude)}}function yc(e){let t=zt(e.targetInfo);t?(e.emitter.emitHeaderLine("#ifndef WIN32_LEAN_AND_MEAN"),e.emitter.emitHeaderLine("#define WIN32_LEAN_AND_MEAN"),e.emitter.emitHeaderLine("#endif"),e.emitter.emitHeaderLine("#ifndef _WINSOCKAPI_"),e.emitter.emitHeaderLine("#define _WINSOCKAPI_"),e.emitter.emitHeaderLine("#endif")):(e.emitter.emitHeaderLine("#define _DEFAULT_SOURCE"),e.emitter.emitHeaderLine("#define _GNU_SOURCE // Needed for sched_getcpu() on Linux")),e.emitter.emitHeaderLine("");for(let n of e.cIncludes)e.emitter.emitHeaderLine(`#include ${n}`);t?(e.emitter.emitHeaderLine("#include <windows.h>"),e.emitter.emitHeaderLine("#include <bcrypt.h>"),e.emitter.emitHeaderLine("#include <io.h>"),e.emitter.emitHeaderLine("#include <sys/stat.h>")):(e.emitter.emitHeaderLine("#include <unistd.h>"),e.emitter.emitHeaderLine("#include <sys/stat.h>"),e.emitter.emitHeaderLine("#include <sys/random.h>")),e.emitter.emitHeaderLine(""),e.allocator==="mimalloc"?(e.emitter.emitHeaderLine("// Mimalloc compatibility layer - try mimalloc first, fallback to stdlib"),e.emitter.emitHeaderLine("#ifdef __has_include"),e.emitter.emitHeaderLine(" #if __has_include(<mimalloc.h>)"),e.emitter.emitHeaderLine(" #include <mimalloc.h>"),e.emitter.emitHeaderLine(" #define __yo_malloc mi_malloc"),e.emitter.emitHeaderLine(" #define __yo_calloc mi_calloc"),e.emitter.emitHeaderLine(" #define __yo_realloc mi_realloc"),e.emitter.emitHeaderLine(" #define __yo_free mi_free"),e.emitter.emitHeaderLine(" #define __yo_aligned_alloc mi_aligned_alloc"),e.emitter.emitHeaderLine(" #define __yo_aligned_free mi_free"),e.emitter.emitHeaderLine(" #else"),e.emitter.emitHeaderLine(" #define __yo_malloc malloc"),e.emitter.emitHeaderLine(" #define __yo_calloc calloc"),e.emitter.emitHeaderLine(" #define __yo_realloc realloc"),e.emitter.emitHeaderLine(" #define __yo_free free"),t?(e.emitter.emitHeaderLine(" static inline void* __yo_aligned_alloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); }"),e.emitter.emitHeaderLine(" #define __yo_aligned_free _aligned_free")):(e.emitter.emitHeaderLine(" #define __yo_aligned_alloc aligned_alloc"),e.emitter.emitHeaderLine(" #define __yo_aligned_free free")),e.emitter.emitHeaderLine(" #endif"),e.emitter.emitHeaderLine("#else"),e.emitter.emitHeaderLine(" // Fallback for older compilers without __has_include"),e.emitter.emitHeaderLine(" #define __yo_malloc malloc"),e.emitter.emitHeaderLine(" #define __yo_calloc calloc"),e.emitter.emitHeaderLine(" #define __yo_realloc realloc"),e.emitter.emitHeaderLine(" #define __yo_free free"),t?(e.emitter.emitHeaderLine(" static inline void* __yo_aligned_alloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); }"),e.emitter.emitHeaderLine(" #define __yo_aligned_free _aligned_free")):(e.emitter.emitHeaderLine(" #define __yo_aligned_alloc aligned_alloc"),e.emitter.emitHeaderLine(" #define __yo_aligned_free free")),e.emitter.emitHeaderLine("#endif")):(e.emitter.emitHeaderLine("// Using libc allocator"),e.emitter.emitHeaderLine("#define __yo_malloc malloc"),e.emitter.emitHeaderLine("#define __yo_calloc calloc"),e.emitter.emitHeaderLine("#define __yo_realloc realloc"),e.emitter.emitHeaderLine("#define __yo_free free"),t?(e.emitter.emitHeaderLine("static inline void* __yo_aligned_alloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); }"),e.emitter.emitHeaderLine("#define __yo_aligned_free _aligned_free")):(e.emitter.emitHeaderLine("#define __yo_aligned_alloc aligned_alloc"),e.emitter.emitHeaderLine("#define __yo_aligned_free free"))),e.emitter.emitHeaderLine("")}function Ar(e){let{emitter:t,indent:n,resultCode:r,debugLabel:i}=e;r!==void 0&&t.emitLine(`${n}sm->result = ${r};`),i&&t.emitLine(`${n}ASYNC_DEBUG("${i}: Setting state to COMPLETED\\n");`),t.emitLine(`${n}sm->state = -1; // -1 = completed`),t.emitLine(""),t.emitLine(`${n}void (*continuation_fn)(void*) = (void (*)(void*))sm->continuation_fn;`),t.emitLine(`${n}void* continuation_sm = sm->continuation_sm;`),t.emitLine(""),t.emitLine(`${n}if (continuation_fn != NULL) {`),i&&t.emitLine(`${n} ASYNC_DEBUG("${i}: Spawning continuation: resume_fn=%p, sm=%p\\n", (void*)continuation_fn, continuation_sm);`),t.emitLine(""),t.emitLine(`${n} sm->continuation_fn = NULL;`),t.emitLine(`${n} sm->continuation_sm = NULL;`),t.emitLine(""),t.emitLine(`${n} __yo_async_spawn_task(continuation_fn, continuation_sm);`),t.emitLine(`${n}}`),t.emitLine(""),t.emitLine(`${n}__yo_decr_rc((void*)sm);`),t.emitLine(""),t.emitLine(`${n}return;`)}function Mn(e){let{emitter:t,indent:n,resultCode:r,debugLabel:i}=e;r!==void 0&&t.emitLine(`${n}sm->result = ${r};`),i&&t.emitLine(`${n}ASYNC_DEBUG("${i}: Setting state to ESCAPED (effect handler escape)\\n");`),t.emitLine(`${n}sm->state = -2; // -2 = escaped`),t.emitLine(""),t.emitLine(`${n}void (*continuation_fn)(void*) = (void (*)(void*))sm->continuation_fn;`),t.emitLine(`${n}void* continuation_sm = sm->continuation_sm;`),t.emitLine(""),t.emitLine(`${n}if (continuation_fn != NULL) {`),i&&t.emitLine(`${n} ASYNC_DEBUG("${i}: Spawning continuation for escaped future: resume_fn=%p, sm=%p\\n", (void*)continuation_fn, continuation_sm);`),t.emitLine(""),t.emitLine(`${n} sm->continuation_fn = NULL;`),t.emitLine(`${n} sm->continuation_sm = NULL;`),t.emitLine(""),t.emitLine(`${n} __yo_async_spawn_task(continuation_fn, continuation_sm);`),t.emitLine(`${n}}`),t.emitLine(""),t.emitLine(`${n}__yo_decr_rc((void*)sm);`),t.emitLine(""),t.emitLine(`${n}return;`)}var gi=[...k.__yo_op_add,...k.__yo_op_sub,...k.__yo_op_mul,...k.__yo_op_div,...k.__yo_op_mod,...k.__yo_op_neg,...k.__yo_op_eq,...k.__yo_op_neq,...k.__yo_op_lt,...k.__yo_op_lte,...k.__yo_op_gt,...k.__yo_op_gte,...k.__yo_op_not,...k.__yo_op_bit_and,...k.__yo_op_bit_or,...k.__yo_op_bit_xor,...k.__yo_op_bit_complement,...k.__yo_op_bit_left_shift,...k.__yo_op_bit_right_shift,...k.__yo_ptr_add,...k.__yo_ptr_sub,...k.__yo_ptr_diff,...k.__yo_ptr_eq,...k.__yo_ptr_neq,...k.__yo_ptr_lt,...k.__yo_ptr_lte,...k.__yo_ptr_gt,...k.__yo_ptr_gte,...k.__yo_slice_len,...k.__yo_slice_new,...k.__yo_as,...k.__yo_getrandom,...k.__yo_arc4random_buf,...k.__yo_bcrypt_gen_random,...k.__yo_maybe_uninit_new,...k.__yo_maybe_uninit_as_ptr,...k.__yo_maybe_uninit_assume_init,...k.__yo_noop,...k.__yo_return_self,...k.__yo_ms_sleep],gc=new Set(["bool","usize","isize","u8","i8","u16","i16","u32","i32","u64","i64","f32","f64","char","short","ushort","int","uint","long","ulong","longlong","ulonglong","longdouble"]);function te(e,t=!1){let n=new Set(["auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","inline","int","long","register","restrict","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while","_Alignas","_Alignof","_Atomic","_Bool","_Complex","_Generic","_Imaginary","_Noreturn","_Static_assert","_Thread_local","errno","stdin","stdout","stderr","NULL","true","false"]),r=e.replace(/[^a-zA-Z0-9_]/g,i=>`_u${i.charCodeAt(0)}_`);return!t&&n.has(r)&&(r="__yo_c_reserved_"+r),r}function P(e,t){if(!e)return"int32_t";if(e.isExtern&&e.externName)return e.externName;switch(e.tag){case"unit":return"void";case"void":return"void";case"bool":return"bool";case"usize":return"size_t";case"isize":return"intptr_t";case"u8":return"uint8_t";case"i8":return"int8_t";case"u16":return"uint16_t";case"i16":return"int16_t";case"u32":return"uint32_t";case"i32":return"int32_t";case"u64":return"uint64_t";case"i64":return"int64_t";case"f32":return"float";case"f64":return"double";case"comptime_int":return"int32_t";case"comptime_float":return"double";case"comptime_string":return"uint8_t*";case"char":return"char";case"short":return"short";case"ushort":return"unsigned short";case"int":return"int";case"uint":return"unsigned int";case"long":return"long";case"ulong":return"unsigned long";case"longlong":return"long long";case"ulonglong":return"unsigned long long";case"longdouble":return"long double";case"Tuple":case"Struct":case"Union":case"Enum":{if(e.tag==="Enum"){let i=Yt(e);if(i)return P(i,t)}let n;switch(e.tag){case"Tuple":n="tuple";break;case"Struct":n="struct";break;case"Union":n="union";break;case"Enum":n="enum";break;default:throw new Error("Unreachable")}let r=t.types[e.id]?.cName;if(!r)throw new Error(`No C type name found for ${n} ${A(e)}`);return(e.tag==="Struct"||e.tag==="Enum")&&ce(e)&&e.isReferenceSemantics?`${r}*`:r}case"Function":return"void*";case"Dyn":{let n=t.types[e.id]?.cName;if(!n)throw new Error(`No C type name found for dynamic dispatch type ${A(e)}`);return n}case"Array":{let n=e,r=n.childType,i=n.length;if(ze(i)){let o=P(r,t),a=`Array_${te(o)}_${i.value}`;return t.arrayStructTypes.has(a)||t.arrayStructTypes.set(a,{childType:o,length:typeof i.value=="bigint"?Number(i.value):i.value}),a}break}case"Slice":{let n=e,i=`Slice_${te(P(n.childType,t))}`;return t.sliceStructTypes.has(i)||t.sliceStructTypes.set(i,{childType:P(n.childType,t)}),i}case"SomeType":{let n=e;if(Ce(n)){if(n.resolvedConcreteType?.isExtern)return`${P(n.resolvedConcreteType,t)}*`;let r=t.types[n.id]?.cName;if(r)return`${r}*`;if(n.resolvedConcreteType&&x(n.resolvedConcreteType)&&Ce(n.resolvedConcreteType)){let o=n.resolvedConcreteType,a=t.types[o.id]?.cName;if(a)return`${a}*`}if(n.resolvedConcreteType&&ce(n.resolvedConcreteType)){let o=n.resolvedConcreteType.id;for(let[a,s]of Object.entries(t.types))if(x(s.type)&&Ce(s.type)&&s.type.resolvedConcreteType&&ce(s.type.resolvedConcreteType)&&s.type.resolvedConcreteType.id===o)return`${s.cName}*`}let i=Dt(n);if(i){let o=t.types[i.id]?.cName;if(o)return`${o}*`}throw new Error(`Impl(Future) type has no registered concrete type. SomeType ID: ${n.id}, FutureModule: ${i?.id??"none"}. Ensure async blocks are properly analyzed and their state machine types are registered.
185
+ Consider restructuring the type to avoid mixing incompatible field types.`})}function an(e,t=!0,n){switch(e.tag){case"ComptimeInt":case"ComptimeFloat":case"U8":case"I8":case"U16":case"I16":case"U32":case"I32":case"U64":case"I64":case"F32":case"F64":case"Usize":case"Isize":return e;case"Bool":return e;case"Unit":return e;case"ComptimeString":return e;case"Type":return e;case"Function":return e;case"Expr":return e;case"Unknown":return e;case"Ptr":{if(t)return e;let r=e;if(n){let a=n.get(r.targetValue);if(a)return{...r,targetValue:a,targetIndex:r.targetIndex}}let o=[an(r.targetValue[0],t,n)];return n&&n.set(r.targetValue,o),{...r,targetValue:o,targetIndex:r.targetIndex}}case"Tuple":{let r=e;return{...r,fields:r.fields.map(i=>an(i,t,n))}}case"Struct":{let r=e;return{...r,fields:r.fields.map(i=>an(i,t,n))}}case"Enum":{let r=e;return{...r,fields:r.fields.map(i=>an(i,t,n))}}case"Array":{let r=e;return{...r,elements:r.elements.map(i=>an(i,t,n))}}case"Slice":{if(t)return e;let r=e;if(n){let a=n.get(r.sourceArray);if(a)return{...r,sourceArray:a}}let o=[an(r.sourceArray[0],t,n)];return n&&n.set(r.sourceArray,o),{...r,sourceArray:o}}case"ComptimeList":{let r=e;return{...r,elements:r.elements.map(i=>an(i,t,n))}}case"Module":{let r=e;return{...r,fields:r.fields.map(i=>i?an(i,t,n):void 0)}}case"Trait":{let r=e;return{...r,fields:r.fields.map(i=>i?an(i,t,n):void 0)}}default:return e}}function nl({modulePath:e,inputString:t}){return{functionDeclarationFrameLevel:-1,frames:[],modulePath:e,inputString:t}}function at(){let e=nl({modulePath:"",inputString:""});return Pe(e)}function rl(e){let t=new Map,n=[...e.frames.flatMap(o=>o.variables)];for(let o of n)if(o.value&&!t.has(o.value)){let a=an(o.value[0],!1,t);t.has(o.value)||t.set(o.value,[a])}let r=o=>{if(!o.value)return{...o};let a=t.get(o.value);if(a)return{...o,value:a};let s=an(o.value[0],!1,t);return{...o,value:[s]}},i=o=>({...o,variables:o.variables.map(r),whereClauseConstraints:fy(o.whereClauseConstraints)});return{...e,frames:e.frames.map(i)}}function fy(e){let t=new Map;for(let[n,r]of e)t.set(n,{someType:r.someType,requiredTraits:[...r.requiredTraits],negativeTraits:[...r.negativeTraits]});return t}function er({env:e,someType:t,traitType:n,isNegated:r}){let i=e.frames.length-1,o=e.frames[i];if(!o)return e;let a=t.id,s=o.whereClauseConstraints.get(a);s||(s={someType:t,requiredTraits:[],negativeTraits:[]},o.whereClauseConstraints.set(a,s));let l=r?s.negativeTraits:s.requiredTraits;return l.some(u=>u.id===n.id)||l.push(n),e}function Wn(e,t){let n=[],r=[],i=new Set,o=new Set,a=!1,s=new Set;for(let l of e.frames)for(let u of l.variables){let c=u.value?.[0];O(c)&&x(c.value)&&c.value.id===t.id&&s.add(u.name)}for(let l of e.frames)for(let u of l.whereClauseConstraints.values())if(!(u.someType.id!==t.id&&!s.has(u.someType.name))){a=!0;for(let c of u.requiredTraits)i.has(c.id)||(i.add(c.id),n.push(c));for(let c of u.negativeTraits)o.has(c.id)||(o.add(c.id),r.push(c))}if(a)return{requiredTraits:n,negativeTraits:r}}var tc=null;function nc(e){tc=e}function rc(){tc=null}var dy="__yo_self";function me({env:e,variable:t,deltaFrame:n,variableId:r,addToBeginBlockFrame:i,allowVariableShadowing:o}){let a=e.frames.length-1+(n??0);if(i){let f=gy(e);f>=0&&(a=f)}if(t.name!==dy){let f=X(e,t.name);if(f.length>0&&!o){let m=f[f.length-1];throw lt([{token:t.token,errorMessage:`Failed to define variable "${t.name}":`},{token:m.token,errorMessage:`Variable "${t.name}" is already defined here (variable shadowing is not allowed):`}])}}let s=e.frames[a];if(!s)throw console.trace(`Frame at level ${a} does not exist in the environment.`),new Error(`Frame at level ${a} does not exist in the environment.`);let l=ut(e.modulePath,t.name)?t.name:r??ri(e.modulePath,t.name),u={...t,frameLevel:a,id:l},c=my({frame:s,variable:u}),_=e.frames.slice();return _[a]=c,{env:{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:_,modulePath:e.modulePath,inputString:e.inputString},variable:u}}function my({frame:e,variable:t}){if(t.name==="_")return e;if(e.variables.some(r=>r.name===t.name))throw lt([{token:t.token,errorMessage:`Failed to define variable "${t.name}":`},{token:e.variables.find(r=>r.name===t.name).token,errorMessage:`Variable "${t.name}" is already defined here in the same scope:`}]);let n=e.variables.findIndex(r=>r.name===t.name&&!r.initializedAtToken);if(n>-1){let r=e.variables.slice();return r[n]=t,{id:e.id,variables:r,isBeginBlockFrame:e.isBeginBlockFrame,whereClauseConstraints:new Map(e.whereClauseConstraints)}}return{id:e.id,variables:[...e.variables,t],isBeginBlockFrame:e.isBeginBlockFrame,whereClauseConstraints:new Map(e.whereClauseConstraints)}}function yy(e,t,n){let r=e.variables.filter(i=>i.name===t);return n?r.filter(n):r}function X(e,t,n){let r=[];for(let i=0;i<e.frames.length;i++){let o=e.frames[i],a=yy(o,t,n);r.push(...a)}return n?r.filter(n):r}function fn(e,t){let n=[];for(let r=0;r<e.frames.length;r++){let o=e.frames[r].variables.filter(t);n.push(...o)}return n}function Bo(e,t){for(let n=e.frames.length-1;n>=0;n--)if(e.frames[n].variables.some(t))return n;return-1}function Pe(e,t={id:ri(e.modulePath,"frame"),variables:[],isBeginBlockFrame:!1,whereClauseConstraints:new Map},n){let r=n?{...t,isBeginBlockFrame:!0}:t;return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:[...e.frames,r],modulePath:e.modulePath,inputString:e.inputString}}function ct(e,t=!1){let n=e.frames.length-1,r=e.frames[n];if(!t){let i=ji(e),o=r.variables.filter(a=>!a.initializedAtToken);if(i.length>0)throw lt(i.map(a=>({token:a.token,errorMessage:`Variable "${a.name}" was not consumed. It is supposed to be consumed before going out of scope.
186
+ Typeof "${a.name}": ${A(a.type)}`})));if(o.length>0)throw lt(o.map(a=>({token:a.token,errorMessage:`Variable "${a.name}" is undefined.`})))}return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:e.frames.slice(0,-1),modulePath:e.modulePath,inputString:e.inputString}}function Be(e,t,n){let r=e.frames.map(i=>{let o=i.variables.map(a=>a.id===t.id?n:a);return{...i,variables:o}});return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:r,modulePath:e.modulePath,inputString:e.inputString}}function ic(e){return{id:e.id,name:e.name,type:A(e.type),typeId:e.type.id,value:Me(e.value?.[0]),isCompileTimeOnly:e.isCompileTimeOnly,isUndefined:!e.initializedAtToken,isOwningTheRcValue:!!e.isOwningTheRcValue,isOwningTheSameRcValueAs:e.isOwningTheSameRcValueAs?.name,isReassignable:!!e.isReassignable,isConsumed:!!e.consumedAtToken}}function oc({env:e,context:t,methodName:n,type:r}){let i=[];if(!r.trait)return i;let o=r.trait.fields.find(a=>a.label===n&&G(a.type));if(o&&G(o.type)){let a=o.assignedValue;de(a)&&(a=K(o.type,{variableName:o.label,env:e,context:t})),i.push({type:o.type,value:a})}for(let a of r.trait.fields)if(a.label===""&&a.assignedValue&&Tt(a.assignedValue)){let s=a.assignedValue,l=s.type,u=l.fields.findIndex(c=>c.label===n&&G(c.type));if(u>=0){let c=l.fields[u];if(G(c.type)){let _=s.fields[u],p=c.type;ne(_)&&_.specializedType&&(p=_.specializedType),i.push({type:p,value:_})}}}if(i.length===0){let a=Jn({concreteType:r,methodName:n,env:e});i.push(...a)}return i}function il({env:e,context:t,methodName:n,receiverType:r,isInfixOperatorCall:i}){let o=[],a=r;for(;Ie(a);)a=a.childType;function s(p,f){let m=p.fields.find(g=>g.label===n&&(G(g.type)||De(g.type)));if(m){let g;if(G(m.type)){if(de(f))g=K(m.type,{variableName:m.label,env:e,context:t});else if(Tt(f)){let h=p.fields.findIndex(d=>d.label===m.label);g=f.fields[h]}o.push({type:m.type,value:g})}else if(Te(m.type)){let h=m.assignedValue;We(h)&&l(h)}}if(!m)for(let g of p.fields)De(g.type)&&g.assignedValue&&s(g.type,g.assignedValue)}function l(p){let f=p.type.fields.findIndex(m=>m.label==="Call");if(f>=0){let m=p.type.fields[f];if(m.assignedValue){let g=m.assignedValue;hn(g)?g.fields.forEach(h=>{o.push({type:h.type,value:h})}):o.push({type:g.type,value:g})}}}function u(p){return p.filter(m=>{if(G(m.type)){if(m.type.parameters.length===0)return!1;let h=m.type.parameters[0].type;if(!i&&Ie(h)){let v=h.childType,T=r;if((vt(r)||Nt(r)||Et(r))&&(T=yt({type:r,expectedType:void 0,expr:void 0,env:e})),Y({type:v,env:m.type.env},{type:T,env:e},!0))return m.needsPointerConversion=!0,!0}if(Fe(h)||Fe(h)&&!Fe(r)||x(r)&&r.resolvedConcreteType&&!Ce(r)&&!Fe(h)&&Y({type:h,env:m.type.env},{type:r.resolvedConcreteType,env:e},!0))return!0;if(!Fe(h)&&Fe(r))return!1;if(vt(r)||Nt(r)||Et(r)){let v=yt({type:r,expectedType:void 0,expr:void 0,env:e});if(Y({type:h,env:m.type.env},{type:v,env:e},!0))return!0}if(be(r)&&m.value===void 0){if(m.type.parameters.length>0&&m.type.SelfType){let T=m.type.parameters[0];if(T){let $=T.type;if(!pt($)&&!be($)&&!Ie($))return!1}}let v=m.type.return.type;if(cr(v,m.type.SelfType))return!1}return Y({type:h,env:m.type.env},{type:r,env:e},!0)}return!0})}function c(p,f,m=new Set){if(m.has(p.id))return;m.add(p.id);let g=p.fields.find(h=>h.label===f&&G(h.type));if(g&&G(g.type)){let h=g.assignedValue;de(h)&&(h=K(g.type,{variableName:g.label,env:e,context:t})),o.push({type:g.type,value:h});return}for(let h of p.fields)De(h.type)&&h.assignedValue&&s(h.type,h.assignedValue)}if(r!==a&&r.trait){let p=r.trait.fields.find(f=>f.label===n&&G(f.type));if(p&&G(p.type)){let f=p.assignedValue;de(f)&&(f=K(p.type,{variableName:p.label,env:e,context:t})),o.push({type:p.type,value:f})}else c(r.trait,n);for(let f of r.trait.fields)if(f.label===""&&f.assignedValue&&Tt(f.assignedValue)){let m=f.assignedValue,g=m.type,h=g.fields.findIndex(d=>d.label===n&&G(d.type));if(h>=0){let d=g.fields[h];if(G(d.type)){let v=m.fields[h],T=d.type;ne(v)&&v.specializedType&&(T=v.specializedType),o.push({type:T,value:v})}}}}if(o.length===0&&r!==a){let p=Jn({concreteType:r,methodName:n,env:e});o.push(...p)}let _=x(a)&&a.resolvedConcreteType&&!Ce(a);if(a.trait&&!be(a)&&!_){let p=a.trait.fields.find(f=>f.label===n&&(G(f.type)||Te(f.type)));if(p&&G(p.type)){let f=p.assignedValue;de(f)&&(f=K(p.type,{variableName:p.label,env:e,context:t})),o.push({type:p.type,value:f})}else if(p&&Te(p.type)){let f=p.assignedValue;We(f)&&l(f)}else c(a.trait,n);for(let f of a.trait.fields)if(f.label===""&&f.assignedValue&&Tt(f.assignedValue)){let m=f.assignedValue,g=m.type,h=g.fields.findIndex(d=>d.label===n&&G(d.type));if(h>=0){let d=g.fields[h];if(G(d.type)){let v=m.fields[h],T=d.type;ne(v)&&v.specializedType&&(T=v.specializedType),o.push({type:T,value:v})}}}if(o.length===0){let f=Jn({concreteType:a,methodName:n,env:e});o.push(...f)}}if(vt(a)||Nt(a)||Et(a)){let p=yt({type:a,expectedType:void 0,expr:void 0,env:e});if(p.trait){let f=p.trait.fields.find(m=>m.label===n&&G(m.type));if(f&&G(f.type)){let m=f.assignedValue;de(m)&&(m=K(f.type,{variableName:f.label,env:e,context:t})),o.push({type:f.type,value:m})}else c(p.trait,n);for(let m of p.trait.fields)if(m.label===""&&m.assignedValue&&Tt(m.assignedValue)){let g=m.assignedValue,h=g.type,d=h.fields.findIndex(v=>v.label===n&&G(v.type));if(d>=0){let v=h.fields[d];if(G(v.type)){let T=g.fields[d],$=v.type;ne(T)&&T.specializedType&&($=T.specializedType),o.push({type:$,value:T})}}}if(o.length===0){let m=Jn({concreteType:p,methodName:n,env:e});o.push(...m)}}}if(x(a)){if(a.resolvedConcreteType?.trait&&!Ce(a)){let p=a.resolvedConcreteType,f=p.trait,m=f?.fields.find(g=>g.label===n&&G(g.type));if(m&&G(m.type)){let g=m.assignedValue||K(m.type,{variableName:m.label,env:e,context:t});o.push({type:m.type,value:g})}if(o.length===0){for(let g of f?.fields??[])if(g.label===""&&g.assignedValue&&Tt(g.assignedValue)){let h=g.assignedValue,d=h.type,v=d.fields.findIndex(T=>T.label===n&&G(T.type));if(v>=0){let T=d.fields[v];if(G(T.type)){let $=h.fields[v],C=T.type;ne($)&&$.specializedType&&(C=$.specializedType),o.push({type:C,value:$});break}}}}if(o.length===0){let g=Jn({concreteType:p,methodName:n,env:e});o.push(...g)}}if(!(o.length>0)){let p=[],f=new Set;for(let g of a.requiredTraits??[])f.has(g.traitType.id)||(f.add(g.traitType.id),p.push(g.traitType));let m=Wn(e,a);if(m)for(let g of m.requiredTraits)f.has(g.id)||(f.add(g.id),p.push(g));if(x(a))for(let g=e.frames.length-1;g>=0;g--){let h=e.frames[g];for(let d of h.whereClauseConstraints.values())if(Y({type:d.someType,env:e},{type:a,env:e},!1))for(let v of d.requiredTraits)f.has(v.id)||(f.add(v.id),p.push(v))}for(let g of p){let h=g.fields.find(d=>d.label===n&&G(d.type));if(h&&G(h.type)){let d={...h.type,SelfType:a},v=!1;if(d.parameters.length>0&&Ie(d.parameters[0].type)){let $=d.parameters[0].type.childType;(x($)&&$.name==="Self"||Y({type:$,env:d.env},{type:r,env:e},!0))&&(v=!0)}let T=K(d,{variableName:h.label,env:e,context:t});o.push({type:d,value:T,needsPointerConversion:v})}}if(o.length===0){for(let g of a.trait.fields)if(g.label===""&&g.assignedValue&&O(g.assignedValue)&&De(g.assignedValue.value)){let d=g.assignedValue.value.fields.find(v=>v.label===n&&G(v.type));if(d&&G(d.type)){let v=K(d.type,{variableName:d.label,env:e,context:t});o.push({type:d.type,value:v})}}}}}if(be(a)){let p=a.trait.fields.find(m=>m.label===n&&(G(m.type)||De(m.type)));if(p&&G(p.type)){let m=p.assignedValue||K(p.type,{variableName:p.label,env:e,context:t});o.push({type:p.type,value:m})}let f=a.requiredTraits;for(let{traitType:m}of f){let g=m.fields.find(h=>h.label===n&&(G(h.type)||De(h.type)));g&&G(g.type)&&g.type.parameters.length>0&&(Fe(g.type.parameters[0].type)||Fe(r)||Y({type:g.type.parameters[0].type,env:g.type.env},{type:r,env:e},!0))&&o.push({type:g.type,value:void 0})}}return o.length>0,u(o)}function ac(e){let t=e.frames.map(n=>({...n,variables:n.variables.filter(r=>!r.isImplicit)}));return{...e,frames:t}}function Ma(e){let t=e.frames.map((n,r)=>{if(r===0)return n;let i=n.variables.filter(o=>!(!o.isCompileTimeOnly||o.isImplicit));return{...n,variables:i}});return{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:t,modulePath:e.modulePath,inputString:e.inputString}}function ji(e){return e.frames.length===0?[]:e.frames[e.frames.length-1].variables.filter(r=>{if(r.consumedAtToken||!r.isOwningTheRcValue||!Le(r.type))return!1;let i=r.type;return!(x(i)&&!i.resolvedConcreteType&&i.requiredTraits.length===0)}).reverse()}function gy(e){for(let t=e.frames.length-1;t>=0;t--)if(e.frames[t]?.isBeginBlockFrame)return t;return-1}var Ty=process.env.YO_SKIP_PRELUDE==="1"||process.env.YO_SKIP_PRELUDE==="true";function Ey(e,t){return e.some(n=>(n.type==="single_line_comment"||n.type==="multi_line_comment")&&n.value.includes(t))}var Go=class{constructor({modulePath:t,stdPath:n,loadModule:r,inputString:i,allowPartialModule:o=!1}){if(this.modulePath=t,this.allowPartialModule=o,!this.modulePath.match(/^file:\/\//))throw new Error(`Invalid file protocol: ${this.modulePath}. Only file:// is supported for now. `);try{if(this.inputString=i??hy(t.replace(/^file:\/\//,""),"utf-8"),this.parser=new bi({modulePath:t,inputString:this.inputString}),this.program=this.parser.getProgram(),this.tokens=this.parser.getTokens(),!this.allowPartialModule&&this.parser.getParserError())throw this.parser.getParserError();this.evaluateProgram(n,r)}catch(a){throw new Error(`Failed to import module "${t}":
187
+ ${a instanceof yn||a instanceof Sn?a.toString():a instanceof Error?a.message:String(a)}`)}}getProgram(){return this.program}getTokens(){return this.tokens}evaluateProgram(t,n){let r=nl({modulePath:this.modulePath,inputString:this.inputString});if(!Ey(this.tokens,"@skip_prelude")&&!Ty){let l="file://"+vy.join(t,"prelude.yo"),{moduleValue:u,moduleError:c}=n(l);if(c)throw c;if(u&&Te(u.type)){r=Pe(r);for(let _=0;_<u.type.fields.length;_++){let p=u.type.fields[_],f=u.fields[_],{env:m}=me({env:r,variable:{name:p.label,type:p.type,value:f?[f]:void 0,isCompileTimeOnly:!0,initializedAtToken:p.exprs.labelExpr?.token??p.exprs.expr.token,consumedAtToken:void 0,token:p.exprs.labelExpr?.token??p.exprs.expr.token,isOwningTheRcValue:!1}});r=m}}nc(r)}let{moduleValue:o,env:a,partialModuleError:s}=Ia({beginExprs:this.program,env:r,context:{isExecuting:!0,expectedType:void 0,SelfType:void 0,loadModule:n.bind(this),stdPath:t,currentModulePath:this.modulePath},allowPartialModule:this.allowPartialModule});r=a,this.moduleValue=o,this.moduleError=s}getModuleValue(){if(!this.moduleValue)throw new Error("Module value is not set");return this.moduleValue}getModuleError(){return this.parser.getParserError()??this.moduleError}};function d$(...e){process.env.NODE_ENV!=="production"&&process.env.DEBUG&&console.log(...e)}import{existsSync as Dh}from"fs";import*as ia from"path";function $y(e){switch(e){case"x86_64":case"aarch64":return 64;case"x86":case"arm":case"wasm32":return 32}}var sc={darwin:"macos",linux:"linux",win32:"windows",freebsd:"freebsd"},lc={x64:"x86_64",arm64:"aarch64",ia32:"x86",arm:"arm"},Oa;function Cy(){if(Oa)return Oa;let e=sc[process.platform];if(!e)throw new Error(`Unsupported host platform: ${process.platform}. Supported: ${Object.keys(sc).join(", ")}`);let t=lc[process.arch];if(!t)throw new Error(`Unsupported host architecture: ${process.arch}. Supported: ${Object.keys(lc).join(", ")}`);return Oa={platform:e,arch:t},Oa}function pc(e){switch(e){case"linux":return"gnu";case"windows":return"msvc";case"wasi":return"wasm";case"macos":case"freebsd":return}}function by(e,t,n){return n?`${e}-${t}-${n}`:`${e}-${t}`}function fc(e,t,n){return{arch:e,os:t,abi:n,pointerSizeBits:$y(e),triple:by(e,t,n)}}function Gr(){let e=Cy(),t=pc(e.platform);return fc(e.arch,e.platform,t)}var uc=new Set(["x86_64","aarch64","x86","arm","wasm32"]),cc=new Set(["linux","macos","windows","freebsd","wasi"]),_c=new Set(["gnu","musl","msvc","none","wasm"]);function dc(e){let t=e.split("-");if(t.length<2||t.length>3)throw new Error(`Invalid target triple "${e}". Expected format: <arch>-<os> or <arch>-<os>-<abi>. Example: x86_64-linux-gnu`);let n=t[0],r=t[1],i=t[2];if(!uc.has(n))throw new Error(`Unknown architecture "${n}" in target triple "${e}". Supported: ${[...uc].join(", ")}`);if(!cc.has(r))throw new Error(`Unknown OS "${r}" in target triple "${e}". Supported: ${[...cc].join(", ")}`);let o=n,a=r,s;if(i!==void 0)if(i==="none")s=void 0;else if(_c.has(i))s=i;else throw new Error(`Unknown ABI "${i}" in target triple "${e}". Supported: ${[..._c].join(", ")}`);else s=pc(a);return fc(o,a,s)}var ol;function Wo(){return ol||(ol=Gr()),ol}function Pt(e){return e.os==="windows"}function mi(e){return e.os==="linux"}function qn(e){return e.os==="macos"}function yi(e){return e.arch==="wasm32"||e.os==="wasi"}function mc(e){for(let t in e.types){let{type:n}=e.types[t];n.cInclude&&e.cIncludes.add(n.cInclude)}for(let t in e.externFunctions){let{type:n}=e.externFunctions[t];n.cInclude&&e.cIncludes.add(n.cInclude)}}function yc(e){let t=Pt(e.targetInfo);t?(e.emitter.emitHeaderLine("#ifndef WIN32_LEAN_AND_MEAN"),e.emitter.emitHeaderLine("#define WIN32_LEAN_AND_MEAN"),e.emitter.emitHeaderLine("#endif"),e.emitter.emitHeaderLine("#ifndef _WINSOCKAPI_"),e.emitter.emitHeaderLine("#define _WINSOCKAPI_"),e.emitter.emitHeaderLine("#endif")):(e.emitter.emitHeaderLine("#define _DEFAULT_SOURCE"),e.emitter.emitHeaderLine("#define _GNU_SOURCE // Needed for sched_getcpu() on Linux")),e.emitter.emitHeaderLine("");for(let n of e.cIncludes)e.emitter.emitHeaderLine(`#include ${n}`);t?(e.emitter.emitHeaderLine("#include <windows.h>"),e.emitter.emitHeaderLine("#include <bcrypt.h>"),e.emitter.emitHeaderLine("#include <io.h>"),e.emitter.emitHeaderLine("#include <sys/stat.h>")):(e.emitter.emitHeaderLine("#include <unistd.h>"),e.emitter.emitHeaderLine("#include <sys/stat.h>"),e.emitter.emitHeaderLine("#include <sys/random.h>")),e.emitter.emitHeaderLine(""),e.allocator==="mimalloc"?(e.emitter.emitHeaderLine("// Mimalloc compatibility layer - try mimalloc first, fallback to stdlib"),e.emitter.emitHeaderLine("#ifdef __has_include"),e.emitter.emitHeaderLine(" #if __has_include(<mimalloc.h>)"),e.emitter.emitHeaderLine(" #include <mimalloc.h>"),e.emitter.emitHeaderLine(" #define __yo_malloc mi_malloc"),e.emitter.emitHeaderLine(" #define __yo_calloc mi_calloc"),e.emitter.emitHeaderLine(" #define __yo_realloc mi_realloc"),e.emitter.emitHeaderLine(" #define __yo_free mi_free"),e.emitter.emitHeaderLine(" #define __yo_aligned_alloc mi_aligned_alloc"),e.emitter.emitHeaderLine(" #define __yo_aligned_free mi_free"),e.emitter.emitHeaderLine(" #else"),e.emitter.emitHeaderLine(" #define __yo_malloc malloc"),e.emitter.emitHeaderLine(" #define __yo_calloc calloc"),e.emitter.emitHeaderLine(" #define __yo_realloc realloc"),e.emitter.emitHeaderLine(" #define __yo_free free"),t?(e.emitter.emitHeaderLine(" static inline void* __yo_aligned_alloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); }"),e.emitter.emitHeaderLine(" #define __yo_aligned_free _aligned_free")):(e.emitter.emitHeaderLine(" #define __yo_aligned_alloc aligned_alloc"),e.emitter.emitHeaderLine(" #define __yo_aligned_free free")),e.emitter.emitHeaderLine(" #endif"),e.emitter.emitHeaderLine("#else"),e.emitter.emitHeaderLine(" // Fallback for older compilers without __has_include"),e.emitter.emitHeaderLine(" #define __yo_malloc malloc"),e.emitter.emitHeaderLine(" #define __yo_calloc calloc"),e.emitter.emitHeaderLine(" #define __yo_realloc realloc"),e.emitter.emitHeaderLine(" #define __yo_free free"),t?(e.emitter.emitHeaderLine(" static inline void* __yo_aligned_alloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); }"),e.emitter.emitHeaderLine(" #define __yo_aligned_free _aligned_free")):(e.emitter.emitHeaderLine(" #define __yo_aligned_alloc aligned_alloc"),e.emitter.emitHeaderLine(" #define __yo_aligned_free free")),e.emitter.emitHeaderLine("#endif")):(e.emitter.emitHeaderLine("// Using libc allocator"),e.emitter.emitHeaderLine("#define __yo_malloc malloc"),e.emitter.emitHeaderLine("#define __yo_calloc calloc"),e.emitter.emitHeaderLine("#define __yo_realloc realloc"),e.emitter.emitHeaderLine("#define __yo_free free"),t?(e.emitter.emitHeaderLine("static inline void* __yo_aligned_alloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); }"),e.emitter.emitHeaderLine("#define __yo_aligned_free _aligned_free")):(e.emitter.emitHeaderLine("#define __yo_aligned_alloc aligned_alloc"),e.emitter.emitHeaderLine("#define __yo_aligned_free free"))),e.emitter.emitHeaderLine("")}function Ar(e){let{emitter:t,indent:n,resultCode:r,debugLabel:i}=e;r!==void 0&&t.emitLine(`${n}sm->result = ${r};`),i&&t.emitLine(`${n}ASYNC_DEBUG("${i}: Setting state to COMPLETED\\n");`),t.emitLine(`${n}sm->state = -1; // -1 = completed`),t.emitLine(""),t.emitLine(`${n}void (*continuation_fn)(void*) = (void (*)(void*))sm->continuation_fn;`),t.emitLine(`${n}void* continuation_sm = sm->continuation_sm;`),t.emitLine(""),t.emitLine(`${n}if (continuation_fn != NULL) {`),i&&t.emitLine(`${n} ASYNC_DEBUG("${i}: Spawning continuation: resume_fn=%p, sm=%p\\n", (void*)continuation_fn, continuation_sm);`),t.emitLine(""),t.emitLine(`${n} sm->continuation_fn = NULL;`),t.emitLine(`${n} sm->continuation_sm = NULL;`),t.emitLine(""),t.emitLine(`${n} __yo_async_spawn_task(continuation_fn, continuation_sm);`),t.emitLine(`${n}}`),t.emitLine(""),t.emitLine(`${n}__yo_decr_rc((void*)sm);`),t.emitLine(""),t.emitLine(`${n}return;`)}function Mn(e){let{emitter:t,indent:n,resultCode:r,debugLabel:i}=e;r!==void 0&&t.emitLine(`${n}sm->result = ${r};`),i&&t.emitLine(`${n}ASYNC_DEBUG("${i}: Setting state to ESCAPED (effect handler escape)\\n");`),t.emitLine(`${n}sm->state = -2; // -2 = escaped`),t.emitLine(""),t.emitLine(`${n}void (*continuation_fn)(void*) = (void (*)(void*))sm->continuation_fn;`),t.emitLine(`${n}void* continuation_sm = sm->continuation_sm;`),t.emitLine(""),t.emitLine(`${n}if (continuation_fn != NULL) {`),i&&t.emitLine(`${n} ASYNC_DEBUG("${i}: Spawning continuation for escaped future: resume_fn=%p, sm=%p\\n", (void*)continuation_fn, continuation_sm);`),t.emitLine(""),t.emitLine(`${n} sm->continuation_fn = NULL;`),t.emitLine(`${n} sm->continuation_sm = NULL;`),t.emitLine(""),t.emitLine(`${n} __yo_async_spawn_task(continuation_fn, continuation_sm);`),t.emitLine(`${n}}`),t.emitLine(""),t.emitLine(`${n}__yo_decr_rc((void*)sm);`),t.emitLine(""),t.emitLine(`${n}return;`)}var gi=[...k.__yo_op_add,...k.__yo_op_sub,...k.__yo_op_mul,...k.__yo_op_div,...k.__yo_op_mod,...k.__yo_op_neg,...k.__yo_op_eq,...k.__yo_op_neq,...k.__yo_op_lt,...k.__yo_op_lte,...k.__yo_op_gt,...k.__yo_op_gte,...k.__yo_op_not,...k.__yo_op_bit_and,...k.__yo_op_bit_or,...k.__yo_op_bit_xor,...k.__yo_op_bit_complement,...k.__yo_op_bit_left_shift,...k.__yo_op_bit_right_shift,...k.__yo_ptr_add,...k.__yo_ptr_sub,...k.__yo_ptr_diff,...k.__yo_ptr_eq,...k.__yo_ptr_neq,...k.__yo_ptr_lt,...k.__yo_ptr_lte,...k.__yo_ptr_gt,...k.__yo_ptr_gte,...k.__yo_slice_len,...k.__yo_slice_new,...k.__yo_as,...k.__yo_getrandom,...k.__yo_arc4random_buf,...k.__yo_bcrypt_gen_random,...k.__yo_maybe_uninit_new,...k.__yo_maybe_uninit_as_ptr,...k.__yo_maybe_uninit_assume_init,...k.__yo_noop,...k.__yo_return_self,...k.__yo_ms_sleep],gc=new Set(["bool","usize","isize","u8","i8","u16","i16","u32","i32","u64","i64","f32","f64","char","short","ushort","int","uint","long","ulong","longlong","ulonglong","longdouble"]);function te(e,t=!1){let n=new Set(["auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","inline","int","long","register","restrict","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while","_Alignas","_Alignof","_Atomic","_Bool","_Complex","_Generic","_Imaginary","_Noreturn","_Static_assert","_Thread_local","errno","stdin","stdout","stderr","NULL","true","false"]),r=e.replace(/[^a-zA-Z0-9_]/g,i=>`_u${i.charCodeAt(0)}_`);return!t&&n.has(r)&&(r="__yo_c_reserved_"+r),r}function P(e,t){if(!e)return"int32_t";if(e.isExtern&&e.externName)return e.externName;switch(e.tag){case"unit":return"void";case"void":return"void";case"bool":return"bool";case"usize":return"size_t";case"isize":return"intptr_t";case"u8":return"uint8_t";case"i8":return"int8_t";case"u16":return"uint16_t";case"i16":return"int16_t";case"u32":return"uint32_t";case"i32":return"int32_t";case"u64":return"uint64_t";case"i64":return"int64_t";case"f32":return"float";case"f64":return"double";case"comptime_int":return"int32_t";case"comptime_float":return"double";case"comptime_string":return"uint8_t*";case"char":return"char";case"short":return"short";case"ushort":return"unsigned short";case"int":return"int";case"uint":return"unsigned int";case"long":return"long";case"ulong":return"unsigned long";case"longlong":return"long long";case"ulonglong":return"unsigned long long";case"longdouble":return"long double";case"Tuple":case"Struct":case"Union":case"Enum":{if(e.tag==="Enum"){let i=Yt(e);if(i)return P(i,t)}let n;switch(e.tag){case"Tuple":n="tuple";break;case"Struct":n="struct";break;case"Union":n="union";break;case"Enum":n="enum";break;default:throw new Error("Unreachable")}let r=t.types[e.id]?.cName;if(!r)throw new Error(`No C type name found for ${n} ${A(e)}`);return(e.tag==="Struct"||e.tag==="Enum")&&ce(e)&&e.isReferenceSemantics?`${r}*`:r}case"Function":return"void*";case"Dyn":{let n=t.types[e.id]?.cName;if(!n)throw new Error(`No C type name found for dynamic dispatch type ${A(e)}`);return n}case"Array":{let n=e,r=n.childType,i=n.length;if(ze(i)){let o=P(r,t),a=`Array_${te(o)}_${i.value}`;return t.arrayStructTypes.has(a)||t.arrayStructTypes.set(a,{childType:o,length:typeof i.value=="bigint"?Number(i.value):i.value}),a}break}case"Slice":{let n=e,i=`Slice_${te(P(n.childType,t))}`;return t.sliceStructTypes.has(i)||t.sliceStructTypes.set(i,{childType:P(n.childType,t)}),i}case"SomeType":{let n=e;if(Ce(n)){if(n.resolvedConcreteType?.isExtern)return`${P(n.resolvedConcreteType,t)}*`;let r=t.types[n.id]?.cName;if(r)return`${r}*`;if(n.resolvedConcreteType&&x(n.resolvedConcreteType)&&Ce(n.resolvedConcreteType)){let o=n.resolvedConcreteType,a=t.types[o.id]?.cName;if(a)return`${a}*`}if(n.resolvedConcreteType&&ce(n.resolvedConcreteType)){let o=n.resolvedConcreteType.id;for(let[a,s]of Object.entries(t.types))if(x(s.type)&&Ce(s.type)&&s.type.resolvedConcreteType&&ce(s.type.resolvedConcreteType)&&s.type.resolvedConcreteType.id===o)return`${s.cName}*`}let i=Dt(n);if(i){let o=t.types[i.id]?.cName;if(o)return`${o}*`}throw new Error(`Impl(Future) type has no registered concrete type. SomeType ID: ${n.id}, FutureModule: ${i?.id??"none"}. Ensure async blocks are properly analyzed and their state machine types are registered.
188
188
  resolvedConcreteType: ${n.resolvedConcreteType?.id??"none"}
189
- registered type IDs: ${Object.keys(t.types).filter(o=>o.startsWith("sometype")).join(", ")}`)}return Wt(n)&&n.resolvedConcreteType||n.resolvedConcreteType?P(n.resolvedConcreteType,t):"void*"}case"Ptr":{let r=e.childType;if(Qe(r)){let a=P(r.childType,t),s=`Slice_${te(a)}`;return t.sliceStructTypes.has(s)||t.sliceStructTypes.set(s,{childType:a}),`${s}*`}let i=P(r,t);return pt(r)?`${i}*`:ge(r)&&Yt(r)?`${i}*`:`${i}*`}case"Iso":{let n=e,r=n.childType,i=P(r,t),o=i.replace(/\*/g,"").trim(),a=`Iso_${te(o)}`;return t.isoTypes||(t.isoTypes=new Map),t.isoTypes.has(a)||t.isoTypes.set(a,{childTypeCName:i,isoType:n}),a}case"Arc":{let n=e,r=n.childType,i=P(r,t),o=i.replace(/\*/g,"").trim(),a=`Arc_${te(o)}`;return t.arcTypes||(t.arcTypes=new Map),t.arcTypes.has(a)||t.arcTypes.set(a,{childTypeCName:i,arcType:n}),a}}return`// Unknown type: ${A(e)}`}function st(e,t,n){let r=te(t);return`${P(e,n)} ${r}`}function Bt(e,t,n){let r=n.types[e.id]?.cName;if(!r)throw new Error(`No C type name found for enum ${e.typeName} (${A(e)})`);return`${r.toUpperCase()}_${t.toUpperCase()}`}function Wr(e){return e.type.return.isCompileTimeOnly}function Ki(e){let t=e.body,n=null;return F(t)&&E(t,"begin")&&t.args.length===1&&F(t.args[0])&&E(t.args[0],gi)?n=t.args[0].func.token.value:F(t)&&E(t,gi)&&(n=t.func.token.value),n&&k.__yo_as.includes(n)?null:n}function Yt(e){if(e.variants.length!==2)return null;let t=null,n=null;for(let r of e.variants)if(!r.fields||r.fields.length===0){if(t)return null;t=r}else if(r.fields.length===1){let i=r.fields[0].type;if(Ie(i)){if(n)return null;n=r}else return null}else return null;return t&&n&&n.fields?n.fields[0].type:null}function Fn(e){for(let t of e.variants)if(t.fields&&t.fields.length>0)return!1;return e.variants.length>0}function Ee(e,t){if(!t)return te(e);let n=X(t,e);if(n.length>0){let r=n[n.length-1];return te(r.name,r.type.isExtern==="c")}return te(e)}function Ra(e){if(F(e)&&e.args.length>=1){let t=e.args[0];if(t&&z(t))return t.token.value}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[0])&&z(e.func.args[1])&&e.func.args[1].token.value===k.___dup[0])return e.func.args[0].token.value}function In(e){if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&z(e.func.args[0]))return e.func.args[0].token.value;if(!F(e)||!E(e,k.___drop)||e.args.length<1)return;let t=e.args[0];if(!(!t||!z(t)))return t.token.value}function qo(e){if(e){if(Rt(e))return e;if(F(e)){let t=e;for(let n of t.args){let r=qo(n);if(r)return r}}}}var al;function hc(e){al=e}function M(e,t,n){if(!al)throw new Error("Internal Error: generateExpr function is not set.");return al(e,t,n)}function Ir(e,t,n){let r=x(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(!Le(r))return"";if(ke(r)){let i=r.length;if(!ze(i))return"/* Error: array has non-constant length */";let o=n.emitter;o.emitLine(`for (size_t i = 0; i < ${i.value}; i++) {`);let a=Ir(`(${e}).data[i]`,r.childType,n);return a&&o.emitLine(` ${a};`),o.emitLine("}"),""}if(we(r)){let i=n.emitter;for(let o=0;o<r.fields.length;o++){let a=r.fields[o].type,s=x(a)&&a.resolvedConcreteType?a.resolvedConcreteType:a;if(Le(s)){let l=Ir(`(${e})._${o}`,a,n);l&&i.emitLine(`${l};`)}}return""}if(be(r))return`__yo_decr_rc((void*)(${e}).data)`;if(pt(r))return`__yo_decr_rc((void*)(${e}))`;if(kt(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if($t(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if(ce(r)||ge(r)){let i=gr(r,n);if(i)return`${i}(${e})`}return""}function Xi(e,t,n){let r=x(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(ke(r)){let i=r.length;if(!ze(i))return"/* Error: array has non-constant length */";let o=`temp_dup_${qe("")}`,a=`i_${qe("")}`,s=P(r,n),l=n.emitter;l.emitLine(`${s} ${o} = ${e};`),l.emitLine(`for (size_t ${a} = 0; ${a} < ${i.value}; ${a}++) {`);let u=Xi(`${o}.data[${a}]`,r.childType,n);return l.emitLine(` ${o}.data[${a}] = ${u};`),l.emitLine("}"),o}if(we(r)){let i=n.emitter,o=`temp_dup_tuple_${qe("")}`,a=P(r,n);i.emitLine(`${a} ${o} = ${e};`);for(let s=0;s<r.fields.length;s++){let l=r.fields[s].type,u=x(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(Le(u)){let c=Xi(`${o}._${s}`,l,n);i.emitLine(`${o}._${s} = ${c};`)}}return o}if(be(r))return`((${P(r,n)}){ .data = __yo_incr_rc((void*)(${e}).data), .vtable = (${e}).vtable })`;if(pt(r))return`((${P(r,n)})__yo_incr_rc((void*)(${e})))`;if(kt(r))return`((${P(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if($t(r))return`((${P(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if(ce(r)||ge(r)){let i=On(r,n);if(i)return`${i}(${e})`}return e}function gr(e,t){if(ce(e)||ge(e)||be(e)||x(e)||kt(e)||$t(e)){let n=e.trait.fields.find(r=>r.label===k.___drop[0]);if(n&&n.assignedValue&&ne(n.assignedValue))return t.functions[n.assignedValue.funcId]?.cName}}function On(e,t){if(ce(e)||ge(e)||be(e)||x(e)||kt(e)||$t(e)){let n=e.trait.fields.find(r=>r.label===k.___dup[0]);if(n&&n.assignedValue&&ne(n.assignedValue))return t.functions[n.assignedValue.funcId]?.cName}}function Ct(e,t,n){let r=n.emitter;if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions){let o=M(i,t,n);o&&r.emitLine(`${t}${o};`)}}function rt(e,t,n){let r=n.emitter;if(e.$?.deferredDupExpressions){for(let i of e.$.deferredDupExpressions)if(F(i)){let o=M(i,t,n);o&&r.emitLine(`${t}${o};`)}}}function Qt(e,t,n){if(ze(e)){let r=(typeof e.value=="bigint",e.value.toString());return e.tag==="F32"?(r.includes(".")?r:r+".0")+"f":e.tag==="F64"||e.tag==="ComptimeFloat"?r.includes(".")?r:r+".0":e.tag==="U64"||e.tag==="Usize"?r+"ULL":e.tag==="I64"||e.tag==="Isize"?r+"LL":e.tag==="U32"?r+"U":r}else{if(Re(e))return e.value?"true":"false";if(Ve(e)){let r=n?.$?.convertedRuntimeType||n?.$?.type;if(r&&Er(r)&&r.fields.length===1){let i=r.fields[0].type;if(Qe(i)){let o=P(r,t),a=JSON.stringify(e.value),s=Buffer.byteLength(e.value,"utf8");return`(${o}){ .data = (uint8_t*)${a}, .length = ${s} }`}}if(r&&Qe(r)){let i=P(r,t),o=JSON.stringify(e.value),a=Buffer.byteLength(e.value,"utf8");return`(${i}){ .data = (uint8_t*)${o}, .length = ${a} }`}return JSON.stringify(e.value)}else if(It(e)){let r=e.type;if(Yt(r)){let l=r.variants.find(u=>u.name===e.variantName);if(!l)return`// Error: Variant ${e.variantName} not found in enum`;if(!l.fields||l.fields.length===0)return"NULL";if(l.fields.length===1&&e.fields.length===1)return Qt(e.fields[0],t)}if(Fn(r))return Bt(r,e.variantName,t);let a=t.types[r.id]?.cName;if(!a)return`// Error: No C type name found for enum ${A(r)}`;let s=Bt(r,e.variantName,t);if(!e.fields||e.fields.length===0)return`(${a}){ .tag = ${s} }`;{let l=r.variants.find(c=>c.name===e.variantName);if(!l||!l.fields)return`// Error: Variant ${e.variantName} not found or has no fields`;let u=e.fields.map((c,_)=>{let p=l.fields[_];if(p&&!pe(p.type)){let f=te(p.label),m=Qt(c,t);return`.${f} = ${m}`}return null}).filter(c=>c!==null);return u.length===0?`(${a}){ .tag = ${s} }`:`(${a}){ .tag = ${s}, .data = { .${e.variantName} = { ${u.join(", ")} } } }`}}else if(hn(e)){let r=e.type,i=t.types[r.id]?.cName;if(!i)return`// Error: No C type name found for tuple ${A(r)}
189
+ registered type IDs: ${Object.keys(t.types).filter(o=>o.startsWith("sometype")).join(", ")}`)}return Wt(n)&&n.resolvedConcreteType||n.resolvedConcreteType?P(n.resolvedConcreteType,t):"void*"}case"Ptr":{let r=e.childType;if(Qe(r)){let a=P(r.childType,t),s=`Slice_${te(a)}`;return t.sliceStructTypes.has(s)||t.sliceStructTypes.set(s,{childType:a}),`${s}*`}let i=P(r,t);return pt(r)?`${i}*`:ge(r)&&Yt(r)?`${i}*`:`${i}*`}case"Iso":{let n=e,r=n.childType,i=P(r,t),o=i.replace(/\*/g,"").trim(),a=`Iso_${te(o)}`;return t.isoTypes||(t.isoTypes=new Map),t.isoTypes.has(a)||t.isoTypes.set(a,{childTypeCName:i,isoType:n}),a}case"Arc":{let n=e,r=n.childType,i=P(r,t),o=i.replace(/\*/g,"").trim(),a=`Arc_${te(o)}`;return t.arcTypes||(t.arcTypes=new Map),t.arcTypes.has(a)||t.arcTypes.set(a,{childTypeCName:i,arcType:n}),a}}return`// Unknown type: ${A(e)}`}function st(e,t,n){let r=te(t);return`${P(e,n)} ${r}`}function Bt(e,t,n){let r=n.types[e.id]?.cName;if(!r)throw new Error(`No C type name found for enum ${e.typeName} (${A(e)})`);return`${r.toUpperCase()}_${t.toUpperCase()}`}function Wr(e){return e.type.return.isCompileTimeOnly}function Ki(e){let t=e.body,n=null;return F(t)&&E(t,"begin")&&t.args.length===1&&F(t.args[0])&&E(t.args[0],gi)?n=t.args[0].func.token.value:F(t)&&E(t,gi)&&(n=t.func.token.value),n&&k.__yo_as.includes(n)?null:n}function Yt(e){if(e.variants.length!==2)return null;let t=null,n=null;for(let r of e.variants)if(!r.fields||r.fields.length===0){if(t)return null;t=r}else if(r.fields.length===1){let i=r.fields[0].type;if(Ie(i)){if(n)return null;n=r}else return null}else return null;return t&&n&&n.fields?n.fields[0].type:null}function Fn(e){for(let t of e.variants)if(t.fields&&t.fields.length>0)return!1;return e.variants.length>0}function Ee(e,t){if(!t)return te(e);let n=X(t,e);if(n.length>0){let r=n[n.length-1];return te(r.name,r.type.isExtern==="c")}return te(e)}function Ra(e){if(F(e)&&e.args.length>=1){let t=e.args[0];if(t&&z(t))return t.token.value}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[0])&&z(e.func.args[1])&&e.func.args[1].token.value===k.___dup[0])return e.func.args[0].token.value}function In(e){if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&z(e.func.args[0]))return e.func.args[0].token.value;if(!F(e)||!E(e,k.___drop)||e.args.length<1)return;let t=e.args[0];if(!(!t||!z(t)))return t.token.value}function qo(e){if(e){if(Rt(e))return e;if(F(e)){let t=e;for(let n of t.args){let r=qo(n);if(r)return r}}}}var al;function hc(e){al=e}function M(e,t,n){if(!al)throw new Error("Internal Error: generateExpr function is not set.");return al(e,t,n)}function Ir(e,t,n){let r=x(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(!Le(r))return"";if(ke(r)){let i=r.length;if(!ze(i))return"/* Error: array has non-constant length */";let o=n.emitter;o.emitLine(`for (size_t i = 0; i < ${i.value}; i++) {`);let a=Ir(`(${e}).data[i]`,r.childType,n);return a&&o.emitLine(` ${a};`),o.emitLine("}"),""}if(we(r)){let i=n.emitter;for(let o=0;o<r.fields.length;o++){let a=r.fields[o].type,s=x(a)&&a.resolvedConcreteType?a.resolvedConcreteType:a;if(Le(s)){let l=Ir(`(${e})._${o}`,a,n);l&&i.emitLine(`${l};`)}}return""}if(be(r))return`__yo_decr_rc((void*)(${e}).data)`;if(pt(r))return`__yo_decr_rc((void*)(${e}))`;if(wt(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if(Ct(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if(ce(r)||ge(r)){let i=gr(r,n);if(i)return`${i}(${e})`}return""}function Xi(e,t,n){let r=x(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(ke(r)){let i=r.length;if(!ze(i))return"/* Error: array has non-constant length */";let o=`temp_dup_${qe("")}`,a=`i_${qe("")}`,s=P(r,n),l=n.emitter;l.emitLine(`${s} ${o} = ${e};`),l.emitLine(`for (size_t ${a} = 0; ${a} < ${i.value}; ${a}++) {`);let u=Xi(`${o}.data[${a}]`,r.childType,n);return l.emitLine(` ${o}.data[${a}] = ${u};`),l.emitLine("}"),o}if(we(r)){let i=n.emitter,o=`temp_dup_tuple_${qe("")}`,a=P(r,n);i.emitLine(`${a} ${o} = ${e};`);for(let s=0;s<r.fields.length;s++){let l=r.fields[s].type,u=x(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(Le(u)){let c=Xi(`${o}._${s}`,l,n);i.emitLine(`${o}._${s} = ${c};`)}}return o}if(be(r))return`((${P(r,n)}){ .data = __yo_incr_rc((void*)(${e}).data), .vtable = (${e}).vtable })`;if(pt(r))return`((${P(r,n)})__yo_incr_rc((void*)(${e})))`;if(wt(r))return`((${P(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if(Ct(r))return`((${P(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if(ce(r)||ge(r)){let i=On(r,n);if(i)return`${i}(${e})`}return e}function gr(e,t){if(ce(e)||ge(e)||be(e)||x(e)||wt(e)||Ct(e)){let n=e.trait.fields.find(r=>r.label===k.___drop[0]);if(n&&n.assignedValue&&ne(n.assignedValue))return t.functions[n.assignedValue.funcId]?.cName}}function On(e,t){if(ce(e)||ge(e)||be(e)||x(e)||wt(e)||Ct(e)){let n=e.trait.fields.find(r=>r.label===k.___dup[0]);if(n&&n.assignedValue&&ne(n.assignedValue))return t.functions[n.assignedValue.funcId]?.cName}}function bt(e,t,n){let r=n.emitter;if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions){let o=M(i,t,n);o&&r.emitLine(`${t}${o};`)}}function rt(e,t,n){let r=n.emitter;if(e.$?.deferredDupExpressions){for(let i of e.$.deferredDupExpressions)if(F(i)){let o=M(i,t,n);o&&r.emitLine(`${t}${o};`)}}}function Qt(e,t,n){if(ze(e)){let r=(typeof e.value=="bigint",e.value.toString());return e.tag==="F32"?(r.includes(".")?r:r+".0")+"f":e.tag==="F64"||e.tag==="ComptimeFloat"?r.includes(".")?r:r+".0":e.tag==="U64"||e.tag==="Usize"?r+"ULL":e.tag==="I64"||e.tag==="Isize"?r+"LL":e.tag==="U32"?r+"U":r}else{if(Re(e))return e.value?"true":"false";if(Ve(e)){let r=n?.$?.convertedRuntimeType||n?.$?.type;if(r&&Er(r)&&r.fields.length===1){let i=r.fields[0].type;if(Qe(i)){let o=P(r,t),a=JSON.stringify(e.value),s=Buffer.byteLength(e.value,"utf8");return`(${o}){ .data = (uint8_t*)${a}, .length = ${s} }`}}if(r&&Qe(r)){let i=P(r,t),o=JSON.stringify(e.value),a=Buffer.byteLength(e.value,"utf8");return`(${i}){ .data = (uint8_t*)${o}, .length = ${a} }`}return JSON.stringify(e.value)}else if(It(e)){let r=e.type;if(Yt(r)){let l=r.variants.find(u=>u.name===e.variantName);if(!l)return`// Error: Variant ${e.variantName} not found in enum`;if(!l.fields||l.fields.length===0)return"NULL";if(l.fields.length===1&&e.fields.length===1)return Qt(e.fields[0],t)}if(Fn(r))return Bt(r,e.variantName,t);let a=t.types[r.id]?.cName;if(!a)return`// Error: No C type name found for enum ${A(r)}`;let s=Bt(r,e.variantName,t);if(!e.fields||e.fields.length===0)return`(${a}){ .tag = ${s} }`;{let l=r.variants.find(c=>c.name===e.variantName);if(!l||!l.fields)return`// Error: Variant ${e.variantName} not found or has no fields`;let u=e.fields.map((c,_)=>{let p=l.fields[_];if(p&&!pe(p.type)){let f=te(p.label),m=Qt(c,t);return`.${f} = ${m}`}return null}).filter(c=>c!==null);return u.length===0?`(${a}){ .tag = ${s} }`:`(${a}){ .tag = ${s}, .data = { .${e.variantName} = { ${u.join(", ")} } } }`}}else if(hn(e)){let r=e.type,i=t.types[r.id]?.cName;if(!i)return`// Error: No C type name found for tuple ${A(r)}
190
190
  `;let o=e.fields.map((a,s)=>{let l=Qt(a,t);return`._${s} = ${l}`});return`(${i}){ ${o.join(", ")} }`}else if(Cn(e)){let r=e.type;if(r&&ce(r)){let i=t.types[r.id]?.cName;if(!i)return`// Error: No C type name found for struct ${A(r)}
191
191
  `;if(r.isNewtype&&r.fields.length===1&&e.fields.length===1){let o=Qt(e.fields[0],t);return`((${i})(${o}))`}if(r.isReferenceSemantics){let o=e.fields.map(s=>Qt(s,t));return`${`__yo_new_${i}`}(${o.join(", ")})`}else{let o=e.fields.map((a,s)=>{let l=a,u=we(r)?`_${s}`:te(r.fields[s].label),c=Qt(l,t);return`.${u} = ${c}`});return`(${i}){ ${o.join(", ")} }`}}}else if(Un(e)){let r=e.type,i=P(r,t),o=e.elements.map(a=>Qt(a,t));return`(${i}){ .data = { ${o.join(", ")} } }`}else if(ne(e)){let r=t.functions[e.funcId]?.cName;return r||`// Error: No C function name found for function value with ID ${e.funcId}
192
- `}else if(O(e)){let r=e.value;if(r)return t.types[r.id]?t.types[r.id].cName:`/* Error: No C type name found for type ${A(r)} */`}else if(wi(e)){let r=e.targetValue[0];if(r){let i=n?.$?.convertedRuntimeType||n?.$?.type;if(i&&Ie(i)){let o=i.childType,a=Qt(r,t,{$:{type:o,convertedRuntimeType:o}});if(a&&!a.startsWith("/*")&&!a.startsWith("//"))return`(&${a})`}}return`/* Error: Cannot generate pointer value ${Me(e)} */`}}return`/* skip generating: ${Me(e)} */`}function Qi(e,t,n){if(e===t)return!0;if(e.tag==="FnCall"){if(n&&n(e))return!1;if(Qi(e.func,t,n))return!0;for(let r of e.args)if(Qi(r,t,n))return!0}return!1}function by(e,t,n){for(let r=0;r<t.length;r++)if(Qi(e,t[r].expr,n))return r;return-1}function vc(e,t,n){let r=[],i=n?.shouldSkipBody;if(e.tag!=="FnCall"||!E(e,"begin"))return t.length===0?[{stateNumber:0,expressions:[e],suspensionPoint:null}]:[{stateNumber:0,expressions:[e],suspensionPoint:t[0]??null}];let o=e.args,a=[],s=[];for(let l of o){let u=by(l,t,i),c=n?.handleReturnStatements&&(dt(l,"return")||E(l,"return"));if(u!==-1){if(s.push(l),a.push(s),s=[],n?.handleSequentialSuspensions)for(let _=u+1;_<t.length&&Qi(l,t[_].expr,i);_++)a.push([])}else if(c){s.push(l),a.push(s),s=[];break}else s.push(l)}s.length>0&&a.push(s);for(let l=0;l<a.length;l++){let u=a[l],c=l<t.length?t[l]:null;r.push({stateNumber:l,expressions:u,suspensionPoint:c})}return r}function ll(e,t){let r=vc(e,t,{shouldSkipBody:Rt,handleReturnStatements:!0,handleSequentialSuspensions:!0}).map(i=>({stateNumber:i.stateNumber,expressions:i.expressions,awaitPoint:i.suspensionPoint}));return r.length>0&&r[r.length-1].awaitPoint!==null&&r.push({stateNumber:r.length,expressions:[],awaitPoint:null}),r}function ky(e,t){return Qi(e,t,Rt)}function Tc(e,t,n,r=!1){let i=n.emitter;for(let o=0;o<e.expressions.length;o++){let a=e.expressions[o],s=o===e.expressions.length-1,l=e.awaitPoint&&ky(a,e.awaitPoint.expr),u=e.awaitPoint&&a.tag==="FnCall"&&(E(a,I.while)||E(a,I.cond)||E(a,I.match))&&un(a);if((l||u)&&e.awaitPoint)to(a,e.awaitPoint,e.stateNumber,t,n);else if(s&&r){let c=M(a,t,n);c&&(i.emitLine(`${t}// Store final expression result`),i.emitLine(`${t}sm->result = ${c};`))}else{let c=M(a,t,n);!c||!a.$||ut(a.$.env.modulePath,c)||i.emitLine(`${t}${c};`)}}}function to(e,t,n,r,i){let o=i.emitter;if(e.tag==="FnCall"&&pn(e)){let a=e.args[0];if(!a){o.emitLine(`${r}// Error: await without argument`);return}if(t.futureVariableId===void 0){let s=M(a,r,i);o.emitLine(`${r}// Store pattern-matched Future for await ${t.index}`),o.emitLine(`${r}sm->await_future_${t.index} = ${s};`)}else o.emitLine(`${r}// Prepare for await (future already stored in state machine variable)`);return}if(e.tag==="FnCall"&&E(e,":=")){let a=e.args[0],s=e.args[1];if(!a||!s){o.emitLine(`${r}// Error: Invalid assignment expression`);return}if(s.tag==="FnCall"&&pn(s)){let l=s.args[0];if(!l){o.emitLine(`${r}// Error: await without argument`);return}let u=a.token?.value;if(!u||!a.$){o.emitLine(`${r}// Error: Invalid variable name`);return}if(t.futureVariableId===void 0){let c=M(l,r,i);o.emitLine(`${r}// Store Future for await (variable: ${u})`),o.emitLine(`${r}sm->await_future_${t.index} = ${c};`)}else o.emitLine(`${r}// Store Future for await (variable: ${u}) - future already in state machine`);return}if(s.tag==="FnCall"&&E(s,I.cond)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,c=X(a.$.env,u);c.length>0&&(l=c[c.length-1].id)}Yo(s,t,r,i,l);return}if(s.tag==="FnCall"&&E(s,I.match)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,c=X(a.$.env,u);c.length>0&&(l=c[c.length-1].id)}Ho(s,t,r,i,l);return}}if(e.tag==="FnCall"&&E(e,"=")){let a=e.args[0],s=e.args[1];if(a&&s){if(s.tag==="FnCall"&&E(s,I.cond)){let l=M(a,r,i);Yo(s,t,r,i,void 0,l||void 0);return}if(s.tag==="FnCall"&&E(s,I.match)){let l=M(a,r,i);Ho(s,t,r,i,void 0,l||void 0);return}}}if(e.tag==="FnCall"&&E(e,I.cond)){Yo(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,I.match)){Ho(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,I.while)){ul(e,t,r,i);return}o.emitLine(`${r}// ERROR: Unsupported pattern for await expression`),o.emitLine(`${r}// Expression type: ${e.tag}, function: ${e.tag==="FnCall"?e.func.tag==="Atom"?e.func.token?.value:e.func.tag:"N/A"}`)}function Yo(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,I.cond)){a.emitLine(`${n}// Error: Expected cond expression`);return}let s=e.args;if(s.length===0){a.emitLine(`${n}// Error: cond must have at least one branch`);return}let l=[],u=-1;for(let h=0;h<s.length;h++){let d=s[h];if(d.tag==="FnCall"&&E(d,"=>")){let v=d.args[0];if(v&&!(Re(v.$?.value)&&v.$.value.value===!1)){u=h;break}}}let c=!1;if(u>=0){let h=s[u];if(h.tag==="FnCall"&&E(h,"=>")){let d=h.args[0];d&&Re(d.$?.value)&&d.$.value.value===!0&&(c=!0)}}if(c&&u>=0){let h=s[u],d=F(h)?h.args[1]:void 0;if(d)if(qr(d)){let C=eo(d,t,n,r),L=r.asyncWhileLoopInfo?.get(t.index);if(L&&C.length>0){let R=r.asyncCondBranchInfo?.get(t.index)?.branches.some(N=>N.hasAwait&&N.remainingExprs&&N.remainingExprs.length>0)??!1;L.condBranchPostWhileExprs={branchIndex:u,condBranchFieldIndex:t.index,exprs:C,deferredDropExpressions:d.$?.deferredDropExpressions,skipCondBranchCheck:R},l.push({index:u,value:d,hasAwait:!0,remainingExprs:[],deferredDropExpressions:d.$?.deferredDropExpressions})}else l.push({index:u,value:d,hasAwait:!0,remainingExprs:C,deferredDropExpressions:d.$?.deferredDropExpressions})}else{if(Zi(e,d,r,i,o))Ji(d,n,r);else if(F(d)&&E(d,I.begin)){let C=d.args;for(let L=0;L<C.length;L++){let b=C[L],R=M(b,n,r);if(R==="break"&&t.isInsideWhile)a.emitLine(`${n}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${n}goto while_loop_${t.index}_end;`);else{let N=R==="break"||R==="continue"||R?.includes("return");R&&(N||b.$&&!ut(b.$.env.modulePath,R))&&a.emitLine(`${n}${R};`)}}if(d.$?.deferredDropExpressions)for(let L of d.$.deferredDropExpressions){let b=M(L,n,r);b&&a.emitLine(`${n}${b};`)}}else{let C=M(d,n,r);if(C==="break"&&t.isInsideWhile)a.emitLine(`${n}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${n}goto while_loop_${t.index}_end;`);else{let L=C==="break"||C==="continue"||C?.includes("return");C&&(L||d.$&&!ut(d.$.env.modulePath,C))&&a.emitLine(`${n}${C};`)}}l.push({index:u,value:d,hasAwait:!1})}r.asyncCondBranchInfo||(r.asyncCondBranchInfo=new Map),(r.asyncCondBranchInfo.get(t.index)?.branches.some($=>$.hasAwait&&$.remainingExprs&&$.remainingExprs.length>0)??!1)||r.asyncCondBranchInfo.set(t.index,{branches:l,targetVariableId:i,targetAssignmentCode:o});return}let _=!1,p=0,f=n;for(let h=0;h<s.length;h++){let d=s[h];if(d.tag!=="FnCall"||!E(d,"=>")){a.emitLine(`${f}// Error: Expected => pair in cond`);continue}let v=d.args[0],T=d.args[1];if(!v||!T){a.emitLine(`${f}// Error: Invalid pair in cond`);continue}if(Re(v.$?.value)&&v.$.value.value===!1)continue;_&&(a.emitLine(`${f}else {`),p++,f+=" ");let $=h===s.length-1&&v.tag==="Atom"&&v.token?.value==="true"?null:M(v,f,r);$?a.emitLine(`${f}if (${$}) {`):a.emitLine(`${f}{`),_=!0;let C=`${f} `;if(qr(T)){a.emitLine(`${C}sm->cond_branch_${t.index} = ${h};`);let b=eo(T,t,C,r),R=r.asyncWhileLoopInfo?.get(t.index);if(R&&b.length>0){let B=r.asyncCondBranchInfo?.get(t.index)?.branches.some(D=>D.hasAwait&&D.remainingExprs&&D.remainingExprs.length>0)??!1;R.condBranchPostWhileExprs={branchIndex:h,condBranchFieldIndex:t.index,exprs:b,deferredDropExpressions:T.$?.deferredDropExpressions,skipCondBranchCheck:B},l.push({index:h,value:T,hasAwait:!0,remainingExprs:[],deferredDropExpressions:T.$?.deferredDropExpressions})}else l.push({index:h,value:T,hasAwait:!0,remainingExprs:b,deferredDropExpressions:T.$?.deferredDropExpressions})}else{if(Zi(e,T,r,i,o))Ji(T,C,r);else if(F(T)&&E(T,I.begin)){let b=T.args;for(let R=0;R<b.length;R++){let N=b[R],B=M(N,C,r);if(B==="break"&&t.isInsideWhile)a.emitLine(`${C}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${C}goto while_loop_${t.index}_end;`);else{let D=B==="break"||B==="continue"||B?.includes("return");B&&(D||N.$&&!ut(N.$.env.modulePath,B))&&a.emitLine(`${C}${B};`)}}if(T.$?.deferredDropExpressions)for(let R of T.$.deferredDropExpressions){let N=M(R,C,r);N&&a.emitLine(`${C}${N};`)}}else{let b=M(T,C,r);if(b==="break"&&t.isInsideWhile)a.emitLine(`${C}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${C}goto while_loop_${t.index}_end;`);else{let R=b==="break"||b==="continue"||b?.includes("return");b&&(R||T.$&&!ut(T.$.env.modulePath,b))&&a.emitLine(`${C}${b};`)}}l.push({index:h,value:T,hasAwait:!1})}a.emitLine(`${f}}`)}for(let h=0;h<p;h++)f=f.slice(0,-2),a.emitLine(`${f}}`);r.asyncCondBranchInfo||(r.asyncCondBranchInfo=new Map),(r.asyncCondBranchInfo.get(t.index)?.branches.some(h=>h.hasAwait&&h.remainingExprs&&h.remainingExprs.length>0)??!1)||r.asyncCondBranchInfo.set(t.index,{branches:l,targetVariableId:i,targetAssignmentCode:o})}function Zi(e,t,n,r,i){return!r&&!i&&n.asyncBodyReturnExpr!==void 0&&e===n.asyncBodyReturnExpr&&!!n.inAsyncStateMachine&&!Ec(t)}function Ji(e,t,n){let r=n.emitter,i=pe(e.$?.type);if(F(e)&&E(e,I.begin)){let o=e.args;for(let s=0;s<o.length-1;s++){let l=o[s],u=M(l,t,n);u&&l.$&&!ut(l.$.env.modulePath,u)&&r.emitLine(`${t}${u};`)}let a=o[o.length-1];if(a&&!i){let s=M(a,t,n);s&&r.emitLine(`${t}sm->result = ${s};`)}if(e.$?.deferredDropExpressions)for(let s of e.$.deferredDropExpressions){let l=M(s,t,n);l&&r.emitLine(`${t}${l};`)}}else if(!i){let o=M(e,t,n);o&&r.emitLine(`${t}sm->result = ${o};`)}if(r.emitLine(`${t}// Drop local variables before early completion`),n.pendingDeferredDrops)for(let o of n.pendingDeferredDrops){let a=M(o,t,n);a&&a.includes("sm->")&&r.emitLine(`${t}${a};`)}Ar({emitter:r,indent:t,resultCode:void 0,debugLabel:n.currentFunctionName}),r.emitLine(`${t}return;`)}function qr(e){if(e.tag==="FnCall"&&pn(e))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(qr(t))return!0}return!1}function Ec(e){if(dt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(Ec(t))return!0}return!1}function Ho(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,I.match)){a.emitLine(`${n}// Error: Expected match expression`);return}let s=e.args[0],l=e.args.slice(1);if(!s||l.length===0){a.emitLine(`${n}// Error: match must have a value and at least one case`);return}let u=M(s,n,r),c=s.$?.type;if(!c){a.emitLine(`${n}// Error: match value has no type`);return}if(e.$?.isPrimitiveMatch){Fy(e,l,u,t,n,r,i,o);return}if(!ge(c)){a.emitLine(`${n}// Error: match requires an enum type or primitive type`);return}let _=c,p=r.types[_.id]?.cName;if(!p){a.emitLine(`${n}// Error: enum type has no C name`);return}let f=Yt(_);if(f){let m=-1,g=-1,h;for(let d=0;d<l.length;d++){let v=l[d];if(F(v)&&E(v,"=>",2)){let T=v.args[0];if(T&&F(T)&&E(T,"."))m=d;else if(T&&F(T)){let $=T.func;$&&F($)&&E($,".")&&(g=d,T.args.length>0&&z(T.args[0])&&(h=T.args[0].token.value))}}}if(a.emitLine(`${n}if (${u} != NULL) {`),g>=0){let d=l[g];if(!F(d))a.emitLine(`${n} // Error: Expected => in case`);else{let v=d.args[1];if(h){let T=r,$=!1,C;if(T.stateMachineVariables){for(let[L,b]of T.stateMachineVariables)if(b.name===h){$=!0,C=L;break}}if($&&C){let L=rn(C,"local",T.stateMachineFieldAliases);a.emitLine(`${n} sm->${L} = ${u};`)}else a.emitLine(`${n} ${P(f,r)} ${h} = ${u};`)}if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${g};`),qr(v)){let T=eo(v,t,n+" ",r);if(T.length>0){let $=r;$.asyncCondBranchInfo||($.asyncCondBranchInfo=new Map);let C=$.asyncCondBranchInfo.get(t.index)||{branches:[]};C.branches.push({index:g,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(Zi(e,v,r,i,o))Ji(v,n+" ",r);else{let T=M(v,n+" ",r);if(i){let $=te(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!ut(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}if(a.emitLine(`${n}} else {`),m>=0){let d=l[m];if(!F(d))a.emitLine(`${n} // Error: Expected => in case`);else{let v=d.args[1];if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${m};`),qr(v)){let T=eo(v,t,n+" ",r);if(T.length>0){let $=r;$.asyncCondBranchInfo||($.asyncCondBranchInfo=new Map);let C=$.asyncCondBranchInfo.get(t.index)||{branches:[]};C.branches.push({index:m,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(Zi(e,v,r,i,o))Ji(v,n+" ",r);else{let T=M(v,n+" ",r);if(i){let $=te(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!ut(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}a.emitLine(`${n}}`)}else{a.emitLine(`${n}switch (${u}.tag) {`);let m=!1;for(let g=0;g<l.length;g++){let h=l[g];if(!F(h)||!E(h,"=>",2))continue;let d=h.args[0],v=h.args[1],T=z(d)&&d.token.value==="_",$;if(!T){if(F(d)&&E(d,".",1))$=d.args[0].token.value;else if(F(d)){let C=d.func;C&&F(C)&&E(C,".",1)&&($=C.args[0].token.value)}}if(!T&&!$){a.emitLine(`${n} // Error: Could not extract variant name`);continue}if(T)m=!0,a.emitLine(`${n} default: {`);else{let C=`${p.toUpperCase()}_${$.toUpperCase()}`;a.emitLine(`${n} case ${C}: {`)}if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${g};`),F(d)&&d.args.length>=1){let C=d.func;if(C&&F(C)&&E(C,".")){let L=_.variants.find(b=>b.name===$);if(L&&L.fields)for(let b=0;b<Math.min(d.args.length,L.fields.length);b++){let R=d.args[b],N=L.fields[b];if(z(R)&&N){let B=R.token.value,D=te(B),V=r,U=!1,re;if(V.stateMachineVariables){for(let[le,_e]of V.stateMachineVariables)if(_e.name===B){U=!0,re=le;break}}let j=te(N.label,N.type.isExtern==="c"),W=`${u}.data.${$}.${j}`;if(U&&re){let le=rn(re,"local",V.stateMachineFieldAliases);a.emitLine(`${n} sm->${le} = ${W};`)}else{let le=P(N.type,r);a.emitLine(`${n} ${le} ${D} = ${W};`)}}}}}if(qr(v)){let C=eo(v,t,n+" ",r);if(C.length>0){let L=r;L.asyncCondBranchInfo||(L.asyncCondBranchInfo=new Map);let b=L.asyncCondBranchInfo.get(t.index)||{branches:[]};b.branches.push({index:g,value:v,hasAwait:!0,remainingExprs:C,deferredDropExpressions:v.$?.deferredDropExpressions}),L.asyncCondBranchInfo.set(t.index,b)}}else if(Zi(e,v,r,i,o))Ji(v,n+" ",r);else{let C=M(v,n+" ",r);if(i){let L=te(`var_${i}`);C&&a.emitLine(`${n} sm->${L} = ${C};`)}else o?C&&a.emitLine(`${n} ${o} = ${C};`):C&&v.$&&!ut(v.$.env.modulePath,C)&&a.emitLine(`${n} ${C};`)}a.emitLine(`${n} break;`),a.emitLine(`${n} }`)}m||a.emitLine(`${n} default: break;`),a.emitLine(`${n}}`)}}function wy(e){return F(e)?E(e,"|",2):!1}function sl(e){if(!wy(e))return[e];if(e.tag!=="FnCall")return[e];let t=e.args[0],n=e.args[1];return[...sl(t),...sl(n)]}function Fy(e,t,n,r,i,o,a,s){let l=o.emitter,u=[];l.emitLine(`${i}switch (${n}) {`);for(let c=0;c<t.length;c++){let _=t[c];if(!F(_)||!E(_,"=>",2))continue;let p=_.args[0],f=_.args[1];if(dt(p,"_"))l.emitLine(`${i} default:`);else{let m=p.$?.primitivePatternValues;if(m&&m.length>0){for(let g of m)if(g!==void 0){let h=Qt(g,o);l.emitLine(`${i} case ${h}:`)}}else{let g=sl(p);for(let h of g){let d=h.$?.value;if(d!==void 0){let v=Qt(d,o);l.emitLine(`${i} case ${v}:`)}}}}if(l.emitLine(`${i} sm->cond_branch_${r.index} = ${c};`),qr(f)){let m=eo(f,r,i+" ",o);u.push({index:c,value:f,hasAwait:!0,remainingExprs:m,deferredDropExpressions:f.$?.deferredDropExpressions})}else{if(Zi(e,f,o,a,s))Ji(f,i+" ",o);else{let m=M(f,i+" ",o);if(a){let g=te(`var_${a}`);m&&l.emitLine(`${i} sm->${g} = ${m};`)}else s?m&&l.emitLine(`${i} ${s} = ${m};`):m&&f.$&&!ut(f.$.env.modulePath,m)&&l.emitLine(`${i} ${m};`)}u.push({index:c,value:f,hasAwait:!1})}l.emitLine(`${i} break;`)}l.emitLine(`${i}}`),o.asyncCondBranchInfo||(o.asyncCondBranchInfo=new Map),o.asyncCondBranchInfo.set(r.index,{branches:u,targetVariableId:a,targetAssignmentCode:s})}function eo(e,t,n,r){let i=r.emitter,o=[];if(e.tag!=="FnCall"||!E(e,"begin"))return i.emitLine(`${n}// Error: Expected begin block in cond branch with await`),o;let a=e.args,s=!1;for(let l of a){if(s){o.push(l);continue}if(qr(l))if(s=!0,l.tag==="FnCall"&&E(l,":=")){let u=l.args[1];if(u&&u.tag==="FnCall"&&pn(u)){let c=u.args[0];if(c){let _=M(c,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${_};`)}}}else if(l.tag==="FnCall"&&pn(l)){let u=l.args[0];if(u)if(t.futureVariableId===void 0){let c=M(u,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${c};`)}else i.emitLine(`${n}// Await will use Future from sm->var_${t.futureVariableId}`)}else if(l.tag==="FnCall"&&E(l,I.cond)){let u=l===a[a.length-1],c=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),Yo(l,t,n,r),r.asyncBodyReturnExpr=c}else if(l.tag==="FnCall"&&E(l,I.match)){let u=l===a[a.length-1],c=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),Ho(l,t,n,r),r.asyncBodyReturnExpr=c}else l.tag==="FnCall"&&E(l,I.while)&&ul(l,t,n,r);else{let u=M(l,n,r);u&&l.$&&!ut(l.$.env.modulePath,u)&&i.emitLine(`${n}${u};`)}}return o}function ul(e,t,n,r){let i=r.emitter;if(e.tag!=="FnCall"||!E(e,"while")){i.emitLine(`${n}// Error: Expected while expression`);return}let o=e.args;if(o.length<2||o.length>3){i.emitLine(`${n}// Error: while must have 2 or 3 arguments (condition, [step,] body)`);return}let a=o[0],s=o.length===3?o[1]:void 0,l=o.length===3?o[2]:o[1],u=Ay(l),c;u?(c=r.asyncNextWhileLoopIndex??t.index+1,r.asyncNextWhileLoopIndex=c+1):c=t.index,i.emitLine(`${n}sm->while_loop_${c}_active = true;`),i.emitLine(`${n}while_loop_${c}_start:`);let _=M(a,n,r);i.emitLine(`${n}if (!(${_})) {`),i.emitLine(`${n} sm->while_loop_${c}_active = false;`),i.emitLine(`${n} goto while_loop_${c}_end;`),i.emitLine(`${n}}`);let p=Ly(l,t,n,r,c);if(i.emitLine(`${n}while_loop_${c}_end:`),r.asyncWhileLoopInfo||(r.asyncWhileLoopInfo=new Map),u){let f=r.asyncWhileLoopInfo.get(t.index);f&&(f.outerWhileLoop={whileLoopIndex:c,conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}else r.asyncWhileLoopInfo.set(t.index,{conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}function Ly(e,t,n,r,i){let o=r.emitter,a=[],s=[];e.tag==="FnCall"&&E(e,"begin")?s=e.args:s=[e];let l=-1;for(let f=0;f<s.length;f++){let m=s[f];if(un(m)){l=f;break}}if(l===-1)return o.emitLine(`${n}// Error: Expected await in while loop body but none found`),a;let u=r.smWhileBreakInfo,c=r.smWhileContinueInfo,_=r.smWhileBodyDrops;r.smWhileBreakInfo={label:`while_loop_${i}_end`,activeIndex:i},r.smWhileContinueInfo={label:`while_loop_${i}_start`,emitDropsBeforeGoto:!0},r.smWhileBodyDrops=[...e.$?.deferredDropExpressions??[]];for(let f=0;f<l;f++){let m=s[f],g=M(m,n,r);g&&m.$&&!ut(m.$.env.modulePath,g)&&o.emitLine(`${n}${g};`)}r.smWhileBreakInfo=u,r.smWhileContinueInfo=c,r.smWhileBodyDrops=_;let p=s[l];if(F(p)&&E(p,I.while)&&un(p)){ul(p,t,n,r);for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}if(F(p)&&E(p,":=")){let f=p.args[1];if(f&&f.tag==="FnCall"&&pn(f)){let m=f.args[0];if(m){let g=M(m,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${g};`)}}}else if(p.tag==="FnCall"&&pn(p)){let f=p.args[0];if(f&&t.futureVariableId===void 0){let m=M(f,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${m};`)}}else if(F(p)&&E(p,I.cond)){Yo(p,t,n,r,void 0);for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}else if(F(p)&&E(p,I.match)){Ho(p,t,n,r);for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}function Ay(e){let t=e.tag==="FnCall"&&E(e,"begin")?e.args:[e];for(let n of t)if(n.tag==="FnCall"&&E(n,I.while)&&un(n))return!0;return!1}function hi(e,t,n){if(e)switch(e.tag){case"Atom":if(e.$&&e.token.type==="identifier"){let r=e.token.value,i=X(e.$.env,r);if(i.length>0){let o=i[i.length-1];if(o&&!o.isCompileTimeOnly){let a=n.get(o.id)??o.id,s=o.isOwningTheSameRcValueAs?o.isOwningTheSameRcValueAs.id:a;t.add(s)}}}break;case"FnCall":if(Rt(e)){if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)hi(r,t,n);break}hi(e.func,t,n);for(let r of e.args)hi(r,t,n);if(e.$?.deferredDropExpressions)for(let r of e.$.deferredDropExpressions)hi(r,t,n);if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)hi(r,t,n);break}}function Pa(e,t){let{awaitPoints:n,capturedVariables:r,variableIdRemapping:i}=t;if(n.length===0)return{crossBoundaryIds:new Set,awaitFutureTempVarAliases:new Map,variableSegments:new Map};let o=new Set,a=ll(e,n);for(let _ of a)(_.awaitPoint?.isInsideCond||_.awaitPoint?.isInsideWhile)&&o.add(_.stateNumber);let s=new Map;for(let _ of a){let p=new Set;for(let f of _.expressions)hi(f,p,i);for(let f of p){let m=s.get(f);m||(m=new Set,s.set(f,m)),m.add(_.stateNumber)}}let l=-1;if(e.$?.deferredDropExpressions){let _=new Set;for(let p of e.$.deferredDropExpressions)hi(p,_,i);for(let p of _){let f=s.get(p);f||(f=new Set,s.set(p,f)),f.add(l)}}let u=new Set;for(let _ of r){if(_.kind==="outer")continue;let p=s.get(_.id);if(!p)u.add(_.id);else if(p.size>1)u.add(_.id);else if(p.has(l))u.add(_.id);else{let f=p.values().next().value;o.has(f)&&u.add(_.id)}}let c=new Map;for(let _ of n){if(_.futureVariableId!==void 0)continue;let p=_.expr;if(!F(p))continue;let f=p.args[0];if(!f)continue;let m=f.$?.variableName;if(!m)continue;let g=r.find(h=>h.kind==="local"&&(h.name===m||h.id===m));g&&(c.set(g.id,`await_future_${_.index}`),u.delete(g.id))}return{crossBoundaryIds:u,awaitFutureTempVarAliases:c,variableSegments:s}}function Ua(e,t,n,r,i){let o={slotAliases:new Map,slots:[]},a=n.filter(p=>p.kind==="local"&&e.has(p.id)&&!r.has(p.id)&&!Le(p.type));if(a.length<2)return o;let s=new Map;for(let p of a){let f=t.get(p.id);if(!f||f.size===0)continue;let m=[...f].filter(d=>d>=0);if(m.length===0)continue;let g=Math.min(...m),h=Math.max(...m);s.set(p.id,[g,h])}if(s.size<2)return o;let l=new Map;for(let[p]of s){let f=a.find(h=>h.id===p);if(!f)continue;let m=P(f.type,i),g=l.get(m);g||(g=[],l.set(m,g)),g.push(p)}let u=new Map,c=[],_=0;for(let[p,f]of l){if(f.length<2)continue;let m=new Map;for(let d of f)m.set(d,new Set);for(let d=0;d<f.length;d++)for(let v=d+1;v<f.length;v++){let[T,$]=s.get(f[d]),[C,L]=s.get(f[v]);T<=L&&C<=$&&(m.get(f[d]).add(f[v]),m.get(f[v]).add(f[d]))}let g=new Map;for(let d of f){let v=new Set;for(let $ of m.get(d))g.has($)&&v.add(g.get($));let T=0;for(;v.has(T);)T++;g.set(d,T)}let h=new Map;for(let[d,v]of g){let T=h.get(v);T||(T=[],h.set(v,T)),T.push(d)}for(let[,d]of h){if(d.length<2)continue;let v=`slot_${_}`,T=d.map($=>a.find(C=>C.id===$)?.name??$);for(let $ of d)u.set($,v);c.push({fieldName:v,cType:p,variableNames:T}),_++}}return{slotAliases:u,slots:c}}function _l(e,t){if(e.futureVariableId){let n=t.capturedVariables.find(r=>r.id===e.futureVariableId);if(n)return n.kind==="outer"?n.name:`var_${n.id}`}return`await_future_${e.index}`}function jo(e){return!e||!x(e)?!1:e.resolvedConcreteType&&x(e.resolvedConcreteType)&&e.resolvedConcreteType.isExtern?!0:e.requiredTraits.some(t=>oa(t.traitType))}function rn(e,t,n){if(t==="outer")return`__capture.${te(e)}`;let r=n?.get(e);return r||te(`var_${e}`)}function Cc(e,t,n,r,i,o,a,s){let l=s.emitter,c=Dt(o).isFuture.outputType,_=pe(c);s.asyncCondBranchInfo=new Map,s.asyncWhileLoopInfo=new Map,s.asyncNextWhileLoopIndex=i.awaitPoints.length;let p=ll(e,i.awaitPoints),f=e.tag==="FnCall"&&E(e,"begin")?e.args:[e],m=f.length>0?f[f.length-1]:void 0;l.emitLine(`// Resume function for async block ${t}`),l.emitLine(`void ${r}(${n}* sm) {`),l.emitLine(` ASYNC_DEBUG("${t}_resume: state=%d\\n", sm->state);`),l.emitLine(" switch (sm->state) {");let g=[];for(let h=0;h<p.length;h++){let d=p[h];if(!d)continue;let v=d.stateNumber,T=h===p.length-1;if(l.emitLine(`
193
- state_${v}:`),l.emitLine(` case ${v}: { // State ${v}`),l.emitLine(` ASYNC_DEBUG("${t}: Entering state ${v}\\n");`),v>0&&i.awaitPoints[v-1]){let V=i.awaitPoints[v-1],U=_l(V,i);V.isInsideCond&&l.emitLine(` if (sm->${U} != NULL) {`);let re=pe(V.resultType)||x(V.resultType)&&!V.resultType.resolvedConcreteType;if(l.emitLine(" // Check if the awaited Future was aborted"),l.emitLine(` if (sm->${U}->state == -2) {`),l.emitLine(` __yo_decr_rc((void*)sm->${U});`),l.emitLine(` sm->${U} = NULL;`),Mn({emitter:l,indent:" ",debugLabel:t}),l.emitLine(" }"),V&&!re){l.emitLine(` // Extract result from await ${v-1}`),l.emitLine(` int state_before_read = sm->${U}->state;`),l.emitLine(` ASYNC_DEBUG("${t}: Reading result from await ${v-1}, state=%d\\n", state_before_read);`);let W=!!V.isInsideCond,le;if(W?le=`sm->await_result_${v-1}`:V.targetVariableId&&(le=`sm->${rn(V.targetVariableId,"local",s.stateMachineFieldAliases)}`),le)if(Le(V.resultType)){let _e=On(V.resultType,s);_e?l.emitLine(` ${le} = ${_e}(sm->${U}->result);`):(l.emitLine(" /* Warning: No ___dup function found for result type, shallow copy may cause use-after-free */"),l.emitLine(` ${le} = sm->${U}->result;`))}else l.emitLine(` ${le} = sm->${U}->result;`);if(W&&V.targetVariableId){let _e=rn(V.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(` sm->${_e} = sm->await_result_${v-1};`)}l.emitLine("")}if(!V.futureVariableId){let W=V.expr;if(W.tag==="FnCall"){let _e=W.args[0]?.$?.type;_e&&(x(_e)||be(_e))&&(l.emitLine(` if (sm->${U} != NULL) { __yo_decr_rc((void*)sm->${U}); sm->${U} = NULL; }`),l.emitLine(""))}}let j=s;if(V){let W=j.asyncCondBranchInfo?.get(V.index);if(W&&W.branches.some(_e=>_e.hasAwait)){let _e=W.condBranchFieldIndex??V.index,ve=_e===-1;l.emitLine(" // Execute remaining code from chosen cond branch"),ve||l.emitLine(` switch (sm->cond_branch_${_e}) {`);let q=d.awaitPoint?.isInsideCond??!1;for(let Z of W.branches)if(Z.hasAwait){if(ve||l.emitLine(` case ${Z.index}: {`),l.emitLine(` ASYNC_DEBUG("${t}: Executing remaining code from branch ${Z.index}\\n");`),Z.remainingExprs&&Z.remainingExprs.length>0){let se=s.inAsyncStateMachine,Se=s.stateMachineVariables,fe=s.variableIdRemapping,xe=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Ke=j.asyncWhileLoopInfo?.get(V.index);s.pendingDeferredDrops=[...Z.deferredDropExpressions??[],...Ke?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let J=new Map;for(let ye of i.capturedVariables)J.set(ye.id,ye);if(a)for(let ye of a.fields)J.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=J;let Q=!1,oe=[],ue=W.targetAssignmentCode;for(let ye=0;ye<Z.remainingExprs.length;ye++){let ie=Z.remainingExprs[ye],Ne=ye===Z.remainingExprs.length-1;if(Q){oe.push(ie);continue}if(q&&un(ie)){Q=!0,cl(ie,d.awaitPoint,i," ",s);continue}let $e=M(ie," ",s);!$e||!ie.$||ut(ie.$.env.modulePath,$e)||(Ne&&ue?l.emitLine(` ${ue} = ${$e};`):l.emitLine(` ${$e};`))}if(Z.remainingExprs.length===0&&ue&&l.emitLine(` ${ue} = sm->await_result_${V.index};`),Q&&d.awaitPoint){let ye=d.awaitPoint.index;j.asyncCondBranchInfo||(j.asyncCondBranchInfo=new Map);let ie=j.asyncCondBranchInfo.get(ye);if(ie)ie.chainedBranches||(ie.chainedBranches=[]),ie.chainedBranches.push({branches:[{index:Z.index,value:Z.value,hasAwait:oe.length>0||oe.some(Ne=>un(Ne)),remainingExprs:oe,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:_e});else{let Ne={branches:[{index:Z.index,value:Z.value,hasAwait:oe.length>0||oe.some($e=>un($e)),remainingExprs:oe,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:_e};j.asyncCondBranchInfo.set(ye,Ne)}}else if(Z.deferredDropExpressions)for(let ye of Z.deferredDropExpressions){let ie=M(ye," ",s);ie&&ie.includes("sm->")&&l.emitLine(` ${ie};`)}s.inAsyncStateMachine=se,s.stateMachineVariables=Se,s.variableIdRemapping=fe,s.pendingDeferredDrops=xe}ve||(l.emitLine(" break;"),l.emitLine(" }"))}if(ve||l.emitLine(" }"),W.chainedBranches){for(let Z of W.chainedBranches)for(let se of Z.branches)if(se.hasAwait&&se.remainingExprs&&se.remainingExprs.length>0){let Se=s.inAsyncStateMachine,fe=s.stateMachineVariables,xe=s.variableIdRemapping,Ke=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let J=j.asyncWhileLoopInfo?.get(V.index);s.pendingDeferredDrops=[...se.deferredDropExpressions??[],...J?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let Q=new Map;for(let ie of i.capturedVariables)Q.set(ie.id,ie);if(a)for(let ie of a.fields)Q.set(ie.label,{id:ie.label,name:ie.label,type:ie.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Q;let oe=d.awaitPoint?.isInsideCond??!1,ue=!1,ye=[];for(let ie of se.remainingExprs){if(ue){ye.push(ie);continue}if(oe&&un(ie)){ue=!0,cl(ie,d.awaitPoint,i," ",s);continue}let Ne=M(ie," ",s);!Ne||!ie.$||ut(ie.$.env.modulePath,Ne)||l.emitLine(` ${Ne};`)}if(ue&&d.awaitPoint){let ie=d.awaitPoint.index;j.asyncCondBranchInfo||(j.asyncCondBranchInfo=new Map);let Ne=j.asyncCondBranchInfo.get(ie);Ne?(Ne.chainedBranches||(Ne.chainedBranches=[]),Ne.chainedBranches.push({branches:[{index:se.index,value:se.value,hasAwait:ye.length>0||ye.some($e=>un($e)),remainingExprs:ye,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})):j.asyncCondBranchInfo.set(ie,{branches:[{index:se.index,value:se.value,hasAwait:ye.length>0||ye.some($e=>un($e)),remainingExprs:ye,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})}else if(se.deferredDropExpressions)for(let ie of se.deferredDropExpressions){let Ne=M(ie," ",s);Ne&&Ne.includes("sm->")&&l.emitLine(` ${Ne};`)}s.inAsyncStateMachine=Se,s.stateMachineVariables=fe,s.variableIdRemapping=xe,s.pendingDeferredDrops=Ke}}if(W.targetVariableId){let Z=rn(W.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(" // Assign cond result to target variable"),l.emitLine(` sm->${Z} = sm->await_result_${V.index};`)}l.emitLine("")}V.isInsideCond&&l.emitLine(" }");let le=j.asyncWhileLoopInfo?.get(V.index);if(le){if(l.emitLine(" // Execute remaining code from while loop body and continue loop"),l.emitLine(` if (sm->while_loop_${V.index}_active) {`),le.bodyExprsAfterAwait&&le.bodyExprsAfterAwait.length>0){let fe=s.inAsyncStateMachine,xe=s.stateMachineVariables,Ke=s.variableIdRemapping,J=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...le.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let Q=new Map;for(let ie of i.capturedVariables)Q.set(ie.id,ie);if(a)for(let ie of a.fields)Q.set(ie.label,{id:ie.label,name:ie.label,type:ie.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Q;let oe=s.smWhileBreakInfo,ue=s.smWhileContinueInfo,ye=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${V.index}`,activeIndex:V.index},s.smWhileContinueInfo={label:`while_loop_${V.index}_continue`},s.smWhileBodyDrops=[...le.bodyExpr.$?.deferredDropExpressions??[]];for(let ie of le.bodyExprsAfterAwait){let Ne=M(ie," ",s);!Ne||!ie.$||ut(ie.$.env.modulePath,Ne)||l.emitLine(` ${Ne};`)}s.smWhileBreakInfo=oe,s.smWhileContinueInfo=ue,s.smWhileBodyDrops=ye,s.inAsyncStateMachine=fe,s.stateMachineVariables=xe,s.variableIdRemapping=Ke,s.pendingDeferredDrops=J}l.emitLine(` while_loop_${V.index}_continue:`);{let fe=le.bodyExpr.$?.deferredDropExpressions??[];if(fe.length>0){let xe=s.inAsyncStateMachine,Ke=s.stateMachineVariables,J=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Q=new Map;for(let oe of i.capturedVariables)Q.set(oe.id,oe);if(a)for(let oe of a.fields)Q.set(oe.label,{id:oe.label,name:oe.label,type:oe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Q;for(let oe of fe){let ue=M(oe," ",s);ue&&ue.includes("sm->")&&l.emitLine(` ${ue};`)}s.inAsyncStateMachine=xe,s.stateMachineVariables=Ke,s.variableIdRemapping=J}}if(l.emitLine(` ASYNC_DEBUG("${t}: Re-evaluating while loop condition\\n");`),le.stepExpr){let fe=s.inAsyncStateMachine,xe=s.stateMachineVariables,Ke=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let J=new Map;for(let oe of i.capturedVariables)J.set(oe.id,oe);if(a)for(let oe of a.fields)J.set(oe.label,{id:oe.label,name:oe.label,type:oe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=J;let Q=M(le.stepExpr," ",s);Q&&l.emitLine(` ${Q};`),s.inAsyncStateMachine=fe,s.stateMachineVariables=xe,s.variableIdRemapping=Ke}let _e=s.inAsyncStateMachine,ve=s.stateMachineVariables,q=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Z=new Map;for(let fe of i.capturedVariables)Z.set(fe.id,fe);if(a)for(let fe of a.fields)Z.set(fe.label,{id:fe.label,name:fe.label,type:fe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Z;let se=M(le.conditionExpr," ",s);s.inAsyncStateMachine=_e,s.stateMachineVariables=ve,s.variableIdRemapping=q,l.emitLine(` if (!(${se})) {`),l.emitLine(` sm->while_loop_${V.index}_active = false;`),l.emitLine(` ASYNC_DEBUG("${t}: While loop condition false, exiting loop\\n");`),l.emitLine(" } else {"),l.emitLine(` ASYNC_DEBUG("${t}: While loop condition true, continuing iteration\\n");`);let Se=V.index;if(l.emitLine(" // Loop back by transitioning to while loop state"),l.emitLine(` sm->state = ${Se};`),l.emitLine(` goto while_loop_${Se}_start;`),l.emitLine(" }"),l.emitLine(" }"),l.emitLine(""),l.emitLine(` after_while_loop_${V.index}:`),le.condBranchPostWhileExprs){let fe=le.condBranchPostWhileExprs,xe=fe.condBranchFieldIndex,Ke=fe.branchIndex;fe.skipCondBranchCheck?(l.emitLine(" // Execute post-while-loop code from cond branch (unconditional)"),l.emitLine(" {")):(l.emitLine(" // Execute post-while-loop code from cond branch"),l.emitLine(` if (sm->cond_branch_${xe} == ${Ke}) {`));let J=s.inAsyncStateMachine,Q=s.stateMachineVariables,oe=s.variableIdRemapping,ue=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let ye=new Map;for(let Xe of i.capturedVariables)ye.set(Xe.id,Xe);if(a)for(let Xe of a.fields)ye.set(Xe.label,{id:Xe.label,name:Xe.label,type:Xe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ye;let ie=d.awaitPoint!=null,Ne=!1,$e=[];for(let Xe=0;Xe<fe.exprs.length;Xe++){let _t=fe.exprs[Xe];if(Ne){$e.push(_t);continue}if(ie&&un(_t)){Ne=!0,cl(_t,d.awaitPoint,i," ",s);continue}let Ye=M(_t," ",s);!Ye||!_t.$||ut(_t.$.env.modulePath,Ye)||l.emitLine(` ${Ye};`)}if(Ne&&d.awaitPoint){let Xe=d.awaitPoint.index;j.asyncCondBranchInfo||(j.asyncCondBranchInfo=new Map);let _t=fe.skipCondBranchCheck?-1:fe.condBranchFieldIndex,Ye=j.asyncCondBranchInfo.get(Xe);Ye?(Ye.chainedBranches||(Ye.chainedBranches=[]),Ye.chainedBranches.push({branches:[{index:fe.branchIndex,value:fe.exprs[0],hasAwait:$e.length>0||$e.some(Gt=>un(Gt)),remainingExprs:$e,deferredDropExpressions:fe.deferredDropExpressions}],condBranchFieldIndex:_t})):j.asyncCondBranchInfo.set(Xe,{branches:[{index:fe.branchIndex,value:fe.exprs[0],hasAwait:$e.length>0||$e.some(Gt=>un(Gt)),remainingExprs:$e,deferredDropExpressions:fe.deferredDropExpressions}],condBranchFieldIndex:_t})}if(!Ne&&fe.deferredDropExpressions)for(let Xe of fe.deferredDropExpressions){let _t=M(Xe," ",s);_t&&_t.includes("sm->")&&l.emitLine(` ${_t};`)}l.emitLine(" }"),s.inAsyncStateMachine=J,s.stateMachineVariables=Q,s.variableIdRemapping=oe,s.pendingDeferredDrops=ue}if(le.outerWhileLoop){let fe=le.outerWhileLoop,xe=fe.whileLoopIndex;if(l.emitLine(" // Execute remaining code from outer while loop body"),l.emitLine(` if (sm->while_loop_${xe}_active) {`),fe.bodyExprsAfterAwait.length>0){let Ke=s.inAsyncStateMachine,J=s.stateMachineVariables,Q=s.variableIdRemapping,oe=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...fe.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let ue=new Map;for(let $e of i.capturedVariables)ue.set($e.id,$e);if(a)for(let $e of a.fields)ue.set($e.label,{id:$e.label,name:$e.label,type:$e.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ue;let ye=s.smWhileBreakInfo,ie=s.smWhileContinueInfo,Ne=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${xe}`,activeIndex:xe},s.smWhileContinueInfo={label:`while_loop_${xe}_continue`},s.smWhileBodyDrops=[...fe.bodyExpr.$?.deferredDropExpressions??[]];for(let $e of fe.bodyExprsAfterAwait){let Xe=M($e," ",s);!Xe||!$e.$||ut($e.$.env.modulePath,Xe)||l.emitLine(` ${Xe};`)}s.smWhileBreakInfo=ye,s.smWhileContinueInfo=ie,s.smWhileBodyDrops=Ne,s.inAsyncStateMachine=Ke,s.stateMachineVariables=J,s.variableIdRemapping=Q,s.pendingDeferredDrops=oe}l.emitLine(` while_loop_${xe}_continue:`);{let Ke=fe.bodyExpr.$?.deferredDropExpressions??[];if(Ke.length>0){let J=s.inAsyncStateMachine,Q=s.stateMachineVariables,oe=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let ue=new Map;for(let ye of i.capturedVariables)ue.set(ye.id,ye);if(a)for(let ye of a.fields)ue.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ue;for(let ye of Ke){let ie=M(ye," ",s);ie&&ie.includes("sm->")&&l.emitLine(` ${ie};`)}s.inAsyncStateMachine=J,s.stateMachineVariables=Q,s.variableIdRemapping=oe}}if(fe.stepExpr){let Ke=s.inAsyncStateMachine,J=s.stateMachineVariables,Q=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let oe=new Map;for(let ye of i.capturedVariables)oe.set(ye.id,ye);if(a)for(let ye of a.fields)oe.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=oe;let ue=M(fe.stepExpr," ",s);ue&&l.emitLine(` ${ue};`),s.inAsyncStateMachine=Ke,s.stateMachineVariables=J,s.variableIdRemapping=Q}{let Ke=s.inAsyncStateMachine,J=s.stateMachineVariables,Q=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let oe=new Map;for(let ye of i.capturedVariables)oe.set(ye.id,ye);if(a)for(let ye of a.fields)oe.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=oe;let ue=M(fe.conditionExpr," ",s);s.inAsyncStateMachine=Ke,s.stateMachineVariables=J,s.variableIdRemapping=Q,l.emitLine(` if (!(${ue})) {`),l.emitLine(` sm->while_loop_${xe}_active = false;`),l.emitLine(" } else {"),l.emitLine(` sm->state = ${V.index};`),l.emitLine(` goto while_loop_${xe}_start;`),l.emitLine(" }")}l.emitLine(" }"),l.emitLine(""),l.emitLine(` after_while_loop_${xe}:`)}}}}let $=s.inAsyncStateMachine,C=s.stateMachineVariables,L=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let b=new Map;for(let V of i.capturedVariables)b.set(V.id,V);if(a)for(let V of a.fields)b.set(V.label,{id:V.label,name:V.label,type:V.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=b;let R=s.pendingDeferredDrops;s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let N=T&&!_&&d.expressions.length>0,B=d.expressions.length>0?d.expressions[d.expressions.length-1]:void 0,D=s.asyncBodyReturnExpr;if(!_&&B&&m&&B===m&&d.awaitPoint?s.asyncBodyReturnExpr=B:s.asyncBodyReturnExpr=void 0,Tc(d," ",s,N),s.asyncBodyReturnExpr=D,s.pendingDeferredDrops=R,l.emitLine(""),d.awaitPoint){s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L;let V=v+1;{let U=_l(d.awaitPoint,i),j=d.awaitPoint.expr.args?.[0],W=jo(j?.$?.type),le=d.awaitPoint?.isInsideCond;le&&(l.emitLine(" // Only await if the cond branch with await was taken"),l.emitLine(` if (sm->${U} != NULL) {`));let _e=d.awaitPoint?.isInsideWhile,ve=_e?s.asyncWhileLoopInfo?.get(d.awaitPoint.index):void 0;if(_e&&ve){let q=d.awaitPoint.index;l.emitLine(" // Only await if while loop is still active (not broken)"),l.emitLine(` if (sm->while_loop_${q}_active) {`)}if(l.emitLine(" // Transition to next state after await"),l.emitLine(` sm->state = ${V};`),l.emitLine(""),l.emitLine(" // Check if future is ready"),l.emitLine(` int future_state = sm->${U}->state;`),l.emitLine(" if (future_state == -1 || future_state == -2) { // -1 = completed, -2 = aborted"),l.emitLine(" // Already complete or aborted \u2014 yield once for fairness"),l.emitLine(" // Yield once to event loop for fairness (microtask yield)"),l.emitLine(` __yo_async_spawn_task((void (*)(void*))${r}, (void*)sm);`),l.emitLine(" return;"),l.emitLine(" }"),l.emitLine(""),W?l.emitLine(" // IO future: no extra ref needed (completion handler does not decr_rc)"):(l.emitLine(" // Future not complete \u2014 take event loop reference and start if cold"),l.emitLine(` __yo_incr_rc((void*)sm->${U}); // event loop reference`)),W||(l.emitLine(" if (future_state == 0) { // 0 = cold (not started)"),Sy(d.awaitPoint.expr,`sm->${U}`," ",s),l.emitLine(" // Cold future \u2014 start it via stored resume function pointer"),l.emitLine(` sm->${U}->__yo_resume_fn((void*)sm->${U});`),l.emitLine(""),l.emitLine(" // Re-check: may have completed synchronously"),l.emitLine(` future_state = sm->${U}->state;`),l.emitLine(" if (future_state == -1 || future_state == -2) {"),l.emitLine(" // Completed or aborted synchronously \u2014 yield for fairness"),l.emitLine(` __yo_async_spawn_task((void (*)(void*))${r}, (void*)sm);`),l.emitLine(" return;"),l.emitLine(" }"),l.emitLine(" }")),l.emitLine(""),l.emitLine(" // Still pending \u2014 register continuation and suspend"),l.emitLine(` sm->${U}->continuation_fn = (void (*)(void*))${r};`),l.emitLine(` sm->${U}->continuation_sm = (void*)sm;`),l.emitLine(" return;"),_e&&ve){let q=d.awaitPoint.index;l.emitLine(" } else {"),l.emitLine(" // While loop was broken, jump to code after loop"),l.emitLine(` goto after_while_loop_${q};`),l.emitLine(" }")}le&&(l.emitLine(" } else {"),l.emitLine(" // Non-await cond branch was taken, skip directly to next state"),l.emitLine(` sm->state = ${V};`),l.emitLine(` goto state_${V};`),l.emitLine(" }"))}}else if(T){if(!d.expressions.some(U=>bc(U))){if(e.$?.deferredDropExpressions){let U=new Ci,re=s.emitter;s.emitter=U;for(let W of e.$.deferredDropExpressions){let le=M(W,"",s);le&&U.emitLine(`${le};`)}s.emitter=re;let j=U.print().trim();if(j){l.emitLine(" // Drop local variables before completion");for(let W of j.split(`
194
- `)){let le=W.trim();le&&(l.emitLine(` ${le}`),g.push(le))}l.emitLine("")}}l.emitLine(" // Final state - complete the Future"),Ar({emitter:l,indent:" ",debugLabel:"Future %p completed"})}s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L}else s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L;l.emitLine(" }")}return l.emitLine(" }"),l.emitLine("}"),l.emitLine(""),g}function cl(e,t,n,r,i){let o=i.emitter,a=_l(t,n);if(e.tag==="FnCall"&&E(e,":=")){let s=e.args[1];if(s&&s.tag==="FnCall"&&pn(s)){let l=s.args[0];if(l){let u=M(l,r,i);o.emitLine(`${r}// Store Future for additional await in cond branch`),o.emitLine(`${r}sm->${a} = ${u};`)}}return}if(e.tag==="FnCall"&&pn(e)){let s=e.args[0];if(s){let l=M(s,r,i);o.emitLine(`${r}// Store Future for additional await in cond branch`),o.emitLine(`${r}sm->${a} = ${l};`)}return}if(e.tag==="FnCall"&&E(e,I.cond)){to(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,I.match)){to(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,I.while)){to(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,I.begin)){to(e,t,0,r,i);return}o.emitLine(`${r}// Warning: unhandled await pattern in remaining expressions`)}function bc(e){if(dt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(bc(t))return!0}return!1}function Iy(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function Sy(e,t,n,r){let i=e.args?.[0];if(!i?.$?.type)return;let o=Dt(i.$.type);if(!o?.isFuture.effects?.length)return;let a=Iy(o.isFuture.effects),s=r.emitter,l=e.args?.find(u=>F(u)&&E(u,I.using));if(l){let u=l.args;for(let c=0;c<a.length&&c<u.length;c++){let _=a[c],p=u[c];if(G(_.type)){if(_.type.forallParameters.length>0)continue;let f=M(p,n,r),m=_.label;s.emitLine(`${n}${t}->__capture.${m} = (void*)${f};`)}else Te(_.type)&&$c(_.type,t,n,p.$?.value,r,e)}}else for(let u of a)if(G(u.type)){if(u.type.forallParameters.length>0)continue;let c=Ny(u.label,r,e);c&&s.emitLine(`${n}${t}->__capture.${u.label} = (void*)${c};`)}else Te(u.type)&&$c(u.type,t,n,void 0,r,e)}function $c(e,t,n,r,i,o){let a=i.emitter;for(let s of e.fields){if(!G(s.type))continue;let l;if(i.stateMachineVariables){for(let[,u]of i.stateMachineVariables)if(u.name===s.label&&u.kind==="outer"){l=`sm->__capture.${s.label}`;break}}if(!l&&r&&We(r)){let u=e.fields.indexOf(s),c=r.fields[u];if(c&&ne(c)){let _=i.functions[c.funcId];_&&(l=_.cName)}}if(!l&&i.currentEvidenceParams){for(let u of i.currentEvidenceParams.values())if(u.fieldLabel===s.label){l=u.cParamName;break}}if(!l){let u=o.$?.env??o.func.$?.env;if(u){let c=fn(u,_=>_.isImplicit===!0);for(let _=c.length-1;_>=0;_--){let p=c[_],f=p.value?.[p.value.length-1];if(f&&We(f)){let m=f.type.fields.findIndex(g=>g.label===s.label);if(m>=0){let g=f.fields[m];if(g&&ne(g)){let h=i.functions[g.funcId]?.cName;if(h){l=h;break}}}}}}}l&&a.emitLine(`${n}${t}->__capture.${s.label} = (void*)${l};`)}}function Ny(e,t,n){if(t.currentEvidenceParams){for(let r of t.currentEvidenceParams.values())if(r.fieldLabel===e)return r.cParamName}if(t.stateMachineVariables){for(let[,r]of t.stateMachineVariables)if(r.name===e&&r.kind==="outer")return`sm->__capture.${e}`}}var Vy=new Set(["__yo_mutex_init","__yo_mutex_destroy","__yo_mutex_lock","__yo_mutex_unlock","__yo_cond_init","__yo_cond_destroy","__yo_cond_wait","__yo_cond_signal","__yo_cond_broadcast","__yo_thread_join","__yo_thread_self"]);function kc(e){let t=e.emitter;t.emitDeclarationLine("// Function declarations"),t.emitDeclarationLine("/// Extern functions");for(let n in e.externFunctions){let{cName:r,type:i}=e.externFunctions[n];if(i.isExtern==="yo"){if(Vy.has(r))continue;pl(i,r,!0,e);continue}i.isExtern==="c"&&i.cInclude||r.startsWith("__atomic_")||r.startsWith("__sync_")||pl(i,r,!0,e)}t.emitDeclarationLine(""),e.usesAsync&&(t.emitDeclarationLine("/// Async runtime functions"),t.emitDeclarationLine("static void __yo_async_spawn_task(void (*resume_fn)(void*), void* state_machine);"),t.emitDeclarationLine("")),t.emitDeclarationLine("/// Object constructors"),Dy(e),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Closure constructors"),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Capture dispose functions"),My(e),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Dyn type constructors"),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Regular functions");for(let n in e.functions){let{cName:r,value:i}=e.functions[n],o=r==="__yo_user_main",a=i.body?.$?.effectAnalysis,s=a&&a.hasEffects;if(!o&&!i.type.isClosure&&i.specializedFunctionCaches?.length>0||!o&&!s&&!i.isModuleEffectMember&&!i.type.isClosure&&!i.specializedType&&(i.specializedFunctionCaches?.length??0)===0&&Ft(i.specializedType??i.type).length===0&&[...i.type.implicitParameters,...i.type.parameters.filter(g=>g.isImplicit)].some(g=>G(g.type)))continue;let u=i.specializedType??i.type,c=Ft(u).length>0;if(!o&&i.isIoAsyncStateMachineClosure||!o&&!s&&!c&&!i.isModuleEffectMember&&(sr(i.type)&&!i.type.isClosure||i.specializedFunctionCaches?.length>0&&!i.type.isClosure||Wr(i)||Ki(i)||i.isIoAsyncStateMachineClosure))continue;let _=i.specializedType??i.type,p=!s&&!i.isModuleEffectMember&&(_.parameters.some(g=>Fe(g.type))||_.forallParameters.length>0),f=Fe(_.return.type),m=x(_.return.type)&&_.return.type.requiredTraits.length>0;p||f&&!m&&!i.isModuleEffectMember||pl(_,r,!1,e,i.isModuleEffectMember?void 0:i.body,i.specializedType&&Ft(_).length===0&&Ft(i.type).some(g=>g.fieldFunctionType.forallParameters&&g.fieldFunctionType.forallParameters.length>0)?i.type:void 0)}t.emitDeclarationLine("/// Closure vtable instances"),t.emitDeclarationLine("")}function Ft(e){let t=[],n=xy(e.implicitParameters);for(let r of n)Te(r.type)?wc(r.label,r.type,[],t):G(r.type)&&t.push({implicitLabel:r.label,fieldLabel:r.label,fieldPath:[r.label],fieldFunctionType:r.type,cParamName:te(r.label)});return t}function wc(e,t,n,r){for(let i of t.fields)if(G(i.type)){let o=[...n,i.label],a=o.join("__");r.push({implicitLabel:e,fieldLabel:a,fieldPath:o,fieldFunctionType:i.type,cParamName:te(`${e}__${a}`)})}else Te(i.type)&&wc(e,i.type,[...n,i.label],r)}function xy(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function hr(e,t,n,r,i){let o=r||P(e.return.type,n),a=e.parameters.filter(_=>!_.isCompileTimeOnly),s=[];e.isClosure&&s.push("void* closure_context");let l=a.map((_,p)=>{let f=te(_.label||`param${p}`);if(G(_.type))return hr(_.type,"(*)",n).replace(" (*)(",` (*${f})(`);{let m;return x(_.type)&&Ce(_.type)?_.type.resolvedConcreteType?m=P(_.type.resolvedConcreteType,n)+"*":m=P(_.type,n):m=P(_.type,n),`${m} ${f}`}});s.push(...l);let u=Ft(i??e);for(let _ of u)if(_.fieldFunctionType.forallParameters&&_.fieldFunctionType.forallParameters.length>0)s.push(`void* ${_.cParamName}`);else{let p=hr(_.fieldFunctionType,"(*)",n).replace(" (*)(",` (*${_.cParamName})(`);s.push(p)}let c=s.join(", ");return`${o} ${t}(${c})`}function pl(e,t,n,r,i,o){let a;if(i&&Ce(e.return.type)){let c=qo(i);c?.$?.asyncStateMachineStructName?a=`${c.$.asyncStateMachineStructName}*`:i.$?.type&&x(i.$.type)&&Ce(i.$.type)&&(a=P(i.$.type,r))}if(i&&x(e.return.type)&&!Ce(e.return.type)&&i.$?.type&&(a=P(i.$.type,r)),!a&&i&&i.$?.type&&!Ce(e.return.type)){let c=P(e.return.type,r),_=P(i.$.type,r);c!==_&&(a=_)}let s=a?hr(e,t,r,a,o):hr(e,t,r,void 0,o),l=A(e),u=n?"extern ":"static ";r.emitter.emitDeclarationLine(`${u}${s}; // ${l}`)}function Dy(e){let t=e.emitter;t.emitDeclarationLine("static void __yo_decr_rc(void* ptr); // Decrement reference count"),t.emitDeclarationLine("static void* __yo_incr_rc(void* ptr); // Increment reference count"),t.emitDeclarationLine("static void __yo_gc_register(void* ptr); // Register object for cycle detection"),t.emitDeclarationLine("static void __yo_gc_unregister(void* ptr); // Unregister object from cycle detection"),t.emitDeclarationLine("static void __yo_gc_collect(); // Trigger garbage collection"),t.emitDeclarationLine("static void __yo_gc_init_thread(); // Initialize thread-local GC state (for worker threads)"),t.emitDeclarationLine("static void __yo_cleanup_thread_gc(); // Clean up thread-local GC state"),t.emitDeclarationLine("static void __yo_init_process_cleanup(void); // Initialize process cleanup");for(let n in e.types){let{type:r,cName:i}=e.types[n];if(ce(r)&&r.isReferenceSemantics){if(r.fields.some(l=>Fe(l.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(l=>{let u=P(l.type,e),c=te(l.label);return`${u} ${c}`}).join(", ");t.emitDeclarationLine(`static ${i}* ${a}(${s}); // Constructor`)}}}function My(e){let t=e.emitter;if(e.closureCaptureMap&&e.closureCaptureMap.size>0)for(let[n]of e.closureCaptureMap){let r=`__yo_dispose_closure_${n}`;t.emitDeclarationLine(`static void ${r}(void* closure_ptr);`)}}function Fc(e){let t=new Set;for(let n in e.functions){let{value:r,cName:i}=e.functions[n],o=r.specializedType;if(Wr(r)||!o||!Pn(r.type)||Pn(o))continue;let a=o.parameters.some(u=>Fe(u.type)),s=Fe(o.return.type);a||s||Ft(r.type).some(u=>u.fieldFunctionType.forallParameters&&u.fieldFunctionType.forallParameters.length>0)||t.has(n)||(t.add(n),e.emitter.emitDeclarationLine(`static ${hr(o,i,e)}; // specialized function: ${A(r.type)}`))}}function vr(e,t,n){let r=X(t,e);return r.length===0?!1:r[r.length-1].frameLevel<=n}function Lc(e){return!!(e.$?.closureFunctionValue&&e.$?.type&&Wt(e.$.type))}function Oy(e,t,n,r,i,o=!1){let a=Object.values(i.types).find(f=>f.type===e);if(!a)return i.emitter.emitLine(`${r}/* Error: Capture type not found for closure */`),null;let s=a.cName,l=new Map;if(n.$?.deferredDupExpressions)for(let f of n.$.deferredDupExpressions){let m=Ra(f);m&&l.set(m,f)}let u=e.fields.map(f=>{if(f.isEffectParam)return"NULL";let m,g=f.exprs.expr;if(g.$?.deferredDupExpressions?.length&&(m=g.$.deferredDupExpressions[0]),!m){let d=[f.label];z(g)&&d.push(g.token.value);for(let v of d){let T=l.get(v);if(T){m=T;break}}}if(m)return M(m,r,i);let h={tag:"Atom",token:g.token,$:g.$};return M(h,r,i)}),c=`(${s}){ ${u.map((f,m)=>{let g=e.fields[m];return g?`.${g.label} = ${f}`:`/* Error: missing field at index ${m} */`}).join(", ")} }`,_=n.token.position.row!==void 0?`${Date.now()}_${n.token.position.row}`:`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=`__capture_${t}_${_}`;return o?i.emitter.emitLine(`${r}${s} ${p} = ${c};`):(i.emitter.emitLine(`${r}${s}* ${p} = (${s}*)__yo_malloc(sizeof(${s}));`),i.emitter.emitLine(`${r}*${p} = ${c};`)),{captureTempVar:p,captureCName:s}}function Ac(e,t,n){if(!e.$||!e.$.type||!e.$.closureFunctionValue)return"// Error: Missing closure metadata";let r=nn(e.$.type),i=r.isFn.callType,o=e.$.closureFunctionValue,a=e.$.captureType,s=n.functions[o.funcId]?.cName;if(!s)return"// Error: Closure implementation function not found in context";let l=be(e.$.type),u;if(l){let m=n.types[e.$.type.id];if(!m)return"// Error: Dyn closure type not found in context";u=m.cName}let c=a&&ce(a)&&a.fields.length>0,_=P(i.return.type,n),p=i.parameters.map(m=>P(m.type,n)).join(", "),f=`(${_} (*)(void*${p?", "+p:""}))${s}`;if(c&&a&&ce(a)){let m=!l,g=Oy(a,i.id,e,t,n,m);if(!g)return"// Error: Failed to allocate closure capture";let{captureTempVar:h}=g;if(l){let d=`__yo_create_${u}`,v=`__yo_dispose_${u}`;return`${d}(${h}, ${v}, ${f})`}else return n.implClosureCallMap.set(a.id,{functionCName:s,callTypeId:r.isFn.callType.id}),h}else if(l){let m=`__yo_create_${u}`,g=`__yo_dispose_${u}`;return`${m}(NULL, ${g}, ${f})`}else{if(e.$.type.tag==="SomeType"){let m=e.$.type;if(m.resolvedConcreteType)return n.implClosureCallMap.set(m.resolvedConcreteType.id,{functionCName:s,callTypeId:r.isFn.callType.id}),`(${P(m.resolvedConcreteType,n)}){}`}return"// Error: Impl(Fn(...)) without captures missing resolvedConcreteType"}}function fl(e,t,n){if(e.pendingDeferredDrops&&e.loopBodyDropsBaselineCount!==void 0){let r=e.loopBodyDropsBaselineCount,i=e.pendingDeferredDrops.length,o=e.pendingDeferredDrops.slice(0,i-r);for(let a of o){let s=M(a,t,n);s&&n.emitter.emitLine(`${t}${s};`)}}}function no(e,t,n=""){let r=t;if(e.token.value==="continue"){if(r.currentContinueLabel)return fl(r,n,t),`goto ${r.currentContinueLabel}`;if(r.currentLoopLabel)return fl(r,n,t),"continue";if(r.smWhileContinueInfo){if(r.smWhileContinueInfo.emitDropsBeforeGoto&&r.smWhileBodyDrops&&r.smWhileBodyDrops.length>0){let a=t.emitter;for(let s of r.smWhileBodyDrops){let l=M(s,n,t);l&&l.includes("sm->")&&a.emitLine(`${n}${l};`)}}if(r.smWhileContinueInfo.stepExpr){let a=t.emitter,s=M(r.smWhileContinueInfo.stepExpr,n,t);s&&a.emitLine(`${n}${s};`)}return`goto ${r.smWhileContinueInfo.label}`}return"continue"}if(e.token.value==="break"){if(r.currentLoopLabel)return fl(r,n,t),r.insideMatch?`goto ${r.currentLoopLabel}`:"break";if(r.smWhileBreakInfo){let{label:a,activeIndex:s}=r.smWhileBreakInfo;if(r.smWhileBodyDrops&&r.smWhileBodyDrops.length>0){let l=t.emitter;for(let u of r.smWhileBodyDrops){let c=M(u,n,t);c&&c.includes("sm->")&&l.emitLine(`${n}${c};`)}}return s!==void 0?(t.emitter.emitLine(`${n}sm->while_loop_${s}_active = false;`),`goto ${a}`):`goto ${a}`}return"break"}if(e.token.value==="return"){if(r.inAsyncStateMachine){let a=t.emitter,s=r.inAsyncStateMachine.futureType,u=Dt(s).isFuture.outputType,c=pe(u);if(e.$?.deferredDropExpressions)for(let p of e.$.deferredDropExpressions){let f=M(p,n,t);f&&f.includes("sm->")&&a.emitLine(`${n}${f};`)}if(r.pendingDeferredDrops&&r.pendingDeferredDrops.length>0){a.emitLine(`${n}// Drop local variables before early completion`);for(let p of r.pendingDeferredDrops){let f=M(p,n,t);f&&f.includes("sm->")&&a.emitLine(`${n}${f};`)}}a.emitLine(`${n}// Early return - complete the result Future`);let _=c?void 0:`(${P(u,t)}){0}`;return Ar({emitter:a,indent:n,resultCode:_,debugLabel:t.currentFunctionName}),""}return"return"}if(e.$?.type&&pe(e.$.type))return"";if((r.inAsyncStateMachine||r.inEffectStateMachine)&&r.stateMachineVariables){let a=e.token.value;if(r.localShadowedVariables?.has(a))return te(a);let s=!1;if(e.$?.env){let l=X(e.$.env,a);if(l.length>0){let u=l[l.length-1],c=u.isOwningTheSameRcValueAs?u.isOwningTheSameRcValueAs.id:u.id;r.variableIdRemapping?.has(c)&&(c=r.variableIdRemapping.get(c));let _=r.stateMachineVariables.get(c);if(_){let p=r.stateMachineFieldAliases?.get(c);if(p)return s=!0,`sm->${p}`;let f=_.kind==="outer"?`__capture.${a}`:`var_${_.id}`;return s=!0,`sm->${f}`}}}if(!s){for(let[l,u]of r.stateMachineVariables)if(u.name===a){let c=r.stateMachineFieldAliases?.get(l);if(c)return s=!0,`sm->${c}`;let _=u.kind==="outer"?`__capture.${a}`:`var_${l}`;return s=!0,`sm->${_}`}}if(e.$?.env){let l=X(e.$.env,a);if(l.length>0){let u=l[l.length-1];if(u.isOwningTheSameRcValueAs){let c=u.isOwningTheSameRcValueAs.name,_=u.isOwningTheSameRcValueAs.id;for(let[p,f]of r.stateMachineVariables)if(f.name===c||p===_)return`sm->${f.kind==="outer"?`__capture.${c}`:`var_${p}`}`}}}if(r.currentClosureCaptures&&r.currentClosureCaptures.includes(a)&&r.currentClosureCaptureFrameLevel!==void 0){let l=r.currentClosureCaptureTypeCName;return l?`((${l}*)closure_context)->${Ee(a,e.$?.env)}`:`closure_context->${Ee(a,e.$?.env)}`}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!de(e.$.value)){let l=X(e.$.env,e.$.variableName);if(l.length>0&&l[l.length-1].isCompileTimeOnly)return Qt(e.$.value,t,e)}return Ee(e.$.variableName,e.$.env)}}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!de(e.$.value)){let a=X(e.$.env,e.$.variableName);if(a.length>0&&a[a.length-1].isCompileTimeOnly)return Qt(e.$.value,t,e)}if(!(r.currentClosureCaptures&&r.currentClosureCaptures.includes(e.token.value)&&e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0&&vr(e.token.value,e.$.env,r.currentClosureCaptureFrameLevel)))return Ee(e.$.variableName,e.$?.env)}if(e.$?.value&&!de(e.$.value))return Qt(e.$.value,t,e);let i=e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0?vr(e.token.value,e.$.env,r.currentClosureCaptureFrameLevel):!1;if(r.currentClosureCaptures&&r.currentClosureCaptures.includes(e.token.value)&&r.currentClosureCaptureFrameLevel!==void 0&&(!e.$?.env||i)){let a=r.currentClosureCaptureTypeCName;return a?`((${a}*)closure_context)->${Ee(e.token.value,e.$?.env)}`:`closure_context->${Ee(e.token.value,e.$?.env)}`}if(r.currentFunctionName&&!r.currentClosureCaptures){let a=Object.values(r.functions).find(s=>s.cName===r.currentFunctionName);if(a&&a.value.type.isClosure){let s=Object.values(r.types).find(l=>G(l.type)&&l.type.isClosure&&l.type===a.value.type);if(s)return`((${`${s.cName}_capture`}*)closure_context->data)->${Ee(e.token.value,e.$?.env)}`}}if(e.$?.env){let a=X(e.$.env,e.token.value);if(a.length>0){let s=a[a.length-1];if(s.value?.[0]&&ne(s.value[0])){let l=t.functions[s.value[0].funcId]?.cName;if(l)return l}else if(G(s.type)&&(de(s.value?.[0])||s.value===void 0)){let l=Object.entries(t.functions).find(([u,c])=>c.value.funcName===e.token.value);if(l)return l[1].cName}}}return Ee(e.token.value,e.$?.env)}function Ic(e,t,n){let r;if(Rt(e)){let d=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;d&&ne(d)&&(r=d.body)}else r=e.args[0];if(!r)return"/* Error: async requires exactly 1 argument */";let i=e.$?.type;if(!i||!Ce(i))return"/* Error: async block must have Future type */";let o=Dt(i);if(!o)return"/* Error: Could not extract Future module type */";let a=e.$?.variableName||`async_block_${Date.now()}`,s=`${a}_state_t`,l=`${a}_resume`,u=`__yo_new_${a}`,c=`${a}_state_dispose`;n.types[i.id]={type:i,cName:s};let _=e.$?.awaitAnalysis;if(!_)throw new Error("Missing await analysis for async block. This should have been computed during evaluation.");let p=o.isFuture.outputType;if(x(p))if(p.resolvedConcreteType)p=p.resolvedConcreteType;else{let d=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(d&&ne(d)){let v=d.type?.return?.type;if(v&&x(v)&&v.resolvedConcreteType)p=v.resolvedConcreteType;else if(d.body?.$?.type){let T=d.body.$.type;x(T)&&T.resolvedConcreteType?p=T.resolvedConcreteType:x(T)||(p=T)}}}let f=P(p,n),m=n.emitter;if(m.emitDeclarationLine(`void ${c}(void* sm_ptr); // Dispose function for state machine`),m.emitDeclarationLine(""),m.emitDeclarationLine(`void ${l}(${s}* sm);`),m.emitDeclarationLine(""),e.$?.captureType){let h=e.$.captureType,d=Object.values(n.types).find(T=>T.type===h),v=d?d.cName:`async_capture_${h.id}`;m.emitDeclarationLine(`${s}* ${u}(${v} __capture);`)}else m.emitDeclarationLine(`${s}* ${u}();`);m.emitDeclarationLine(""),n.deferredAsyncBlocks||(n.deferredAsyncBlocks=[]),n.deferredAsyncBlocks.push({bodyExpr:r,asyncBlockId:a,structName:s,resumeFunctionName:l,constructorName:u,disposeFunctionName:c,futureType:i,futureModuleType:o,resultType:p,resultTypeCName:f,captureType:e.$?.captureType,analysis:_});let g=e.$?.captureType;if(g){let h=Object.values(n.types).find(N=>N.type===g),d=h?h.cName:`async_capture_${g.id}`,v=n,T=v.currentClosureCaptures!==void 0||v.inAsyncStateMachine!==void 0||v.inEffectStateMachine!==void 0,$=!1,C=g.fields.map(N=>{if(N.isEffectParam)return`.${N.label} = NULL`;let B;if(!T&&e.$?.deferredDupExpressions)for(let V of e.$.deferredDupExpressions){let U;if(F(V)&&(V.args.length>0&&z(V.args[0])?U=V.args[0].token.value:V.args.length===0&&F(V.func)&&E(V.func,".")&&V.func.args.length>=2&&z(V.func.args[0])&&(U=V.func.args[0].token.value)),U===N.label){B=V;break}}if(B)return $=!0,B.$?.variableName?(M(B,t,n),`.${N.label} = ${B.$.variableName}`):`.${N.label} = ${M(B,t,n)}`;let D={tag:"Atom",token:N.exprs.expr.token,$:N.exprs.expr.$};return`.${N.label} = ${no(D,n)}`}).join(", "),L=`(${d}){${C}}`;if(!$){let N=On(g,n);N&&(L=`${N}(${L})`)}let b=e.$?.variableName||"async_result",R=`${u}(${L})`;if(b&&e.$?.type){let N=st(e.$.type,b,n);return n.emitter.emitLine(`${t}${N} = ${R};`),b}else return R}else{let h=e.$?.variableName||"async_result",d=`${u}()`;if(h&&e.$?.type){let v=st(e.$.type,h,n);return n.emitter.emitLine(`${t}${v} = ${d};`),h}else return d}}function Sc(e,t){let n=t.emitter,{asyncBlockId:r,structName:i,resultType:o,resultTypeCName:a,captureType:s,analysis:l,crossBoundaryIds:u,awaitFutureTempVarAliases:c,overlappingSlotAliases:_,overlappingSlots:p}=e;if(n.emitDeclarationLine(`// State machine for async block ${r} - implements Future(${A(o)})`),n.emitDeclarationLine(`struct ${i}_struct {`),n.emitDeclarationLine(" __yo_ref_header_t header; // Reference counting header (must be first)"),n.emitDeclarationLine(" int state; // Current state (0 = cold, 1..N = intermediate, -1 = completed, -2 = aborted)"),pe(o)?n.emitDeclarationLine(" uint8_t result; // Dummy result for unit type"):n.emitDeclarationLine(` ${a} result; // The result value of type ${A(o)}`),n.emitDeclarationLine(" void (*continuation_fn)(void*); // Resume function of awaiting task"),n.emitDeclarationLine(" void* continuation_sm; // State machine of awaiting task"),n.emitDeclarationLine(""),n.emitDeclarationLine(" void (*__yo_resume_fn)(void*); // Resume function pointer (for lazy start at await/spawn)"),n.emitDeclarationLine(""),s){let h=Object.values(t.types).find(v=>v.type===s),d=h?h.cName:`async_capture_${s.id}`;n.emitDeclarationLine(" // Captured variables from outer scope"),n.emitDeclarationLine(` ${d} __capture;`),n.emitDeclarationLine("")}let f=l.capturedVariables.filter(h=>h.kind!=="outer");if(u&&(f=f.filter(h=>u.has(h.id)&&!c?.has(h.id)&&!_?.has(h.id))),f.length>0){n.emitDeclarationLine(" // Local variables");for(let h of f){let d=P(h.type,t),v=rn(h.id,"local");n.emitDeclarationLine(` ${d} ${v}; // ${h.name}`)}n.emitDeclarationLine("")}if(p&&p.length>0){n.emitDeclarationLine(" // Overlapping storage slots (Phase 2)");for(let h of p)n.emitDeclarationLine(` ${h.cType} ${h.fieldName}; // shared: ${h.variableNames.join(", ")}`);n.emitDeclarationLine("")}if(l.awaitPoints.length>0){let h=[];for(let d of l.awaitPoints)if(!(pe(d.resultType)||x(d.resultType)&&!d.resultType.resolvedConcreteType)&&d.isInsideCond){let $=d.resultType;if(d.futureType){let L=Dt(d.futureType);L&&($=L.isFuture.outputType)}let C=P($,t);h.push(` ${C} await_result_${d.index};`)}if(h.length>0){n.emitDeclarationLine(" // Await result temporaries");for(let d of h)n.emitDeclarationLine(d);n.emitDeclarationLine("")}}if(l.awaitPoints.length>0){let h=l.awaitPoints.filter(d=>d.futureVariableId===void 0);if(h.length>0){n.emitDeclarationLine(" // Future references for awaits");for(let d of h){let v=d.expr;if(v.tag!=="FnCall")continue;let $=v.args[0]?.$?.type;if(!$)throw new Error(`Internal error: await expression missing type info for future argument in async block ${r}`);let C=P($,t);n.emitDeclarationLine(` ${C} await_future_${d.index};`)}n.emitDeclarationLine("")}}let m=l.awaitPoints.filter(h=>h.needsOwnCondBranchField);if(m.length>0){n.emitDeclarationLine(" // Branch tracking for cond expressions with await");for(let h of m)n.emitDeclarationLine(` int cond_branch_${h.index}; // Which branch was taken in cond with await ${h.index}`);n.emitDeclarationLine("")}let g=l.awaitPoints.filter(h=>h.isInsideWhile);if(g.length>0){n.emitDeclarationLine(" // Loop state tracking for while loops with await");let h=l.awaitPoints.length;for(let d of g){n.emitDeclarationLine(` _Bool while_loop_${d.index}_active; // Whether while loop ${d.index} should continue`);let v=(d.whileNestingDepth??1)-1;for(let T=0;T<v;T++)n.emitDeclarationLine(` _Bool while_loop_${h}_active; // Whether outer while loop ${h} should continue`),h++}n.emitDeclarationLine("")}n.emitDeclarationLine("};"),n.emitDeclarationLine("")}function Ry(e){if(!e.deferredAsyncBlocks||e.deferredAsyncBlocks.length===0)return;let t=e.deferredAsyncBlocks,n=new Map;for(let l of t)n.set(l.structName,l);let r=new Map,i=new Map;for(let l of t)r.set(l.structName,new Set),i.set(l.structName,0);for(let l of t){let u=c=>{let _=r.get(c);_.has(l.structName)||(_.add(l.structName),i.set(l.structName,(i.get(l.structName)??0)+1))};for(let c of l.analysis.capturedVariables){let _;try{_=P(c.type,e)}catch{continue}let p=n.get(_);p&&p.structName!==l.structName&&u(p.structName)}for(let c of l.analysis.awaitPoints){if(c.futureVariableId!==void 0)continue;let _=c.expr;if(_.tag!=="FnCall")continue;let f=_.args[0]?.$?.type;if(!f)continue;let m;try{m=P(f,e)}catch{continue}let g=n.get(m);g&&g.structName!==l.structName&&u(g.structName)}}let o=[];for(let[l,u]of i.entries())u===0&&o.push(l);let a=[];for(;o.length>0;){let l=o.shift();a.push(l);let u=r.get(l);if(u)for(let c of u){let _=(i.get(c)??0)-1;i.set(c,_),_===0&&o.push(c)}}let s=a.length===t.length?a.map(l=>n.get(l)).filter(Boolean):t;for(let l of s){let{crossBoundaryIds:u,awaitFutureTempVarAliases:c,variableSegments:_}=Pa(l.bodyExpr,l.analysis),{slotAliases:p,slots:f}=Ua(u,_,l.analysis.capturedVariables,c,e);Sc({asyncBlockId:l.asyncBlockId,structName:l.structName,resultType:l.resultType,resultTypeCName:l.resultTypeCName,captureType:l.captureType,analysis:l.analysis,crossBoundaryIds:u,awaitFutureTempVarAliases:c,overlappingSlotAliases:p,overlappingSlots:f},e)}}function Py(e,t,n,r,i,o,a,s,l,u){let c=u.emitter;if(c.emitLine(`// Dispose function for async block ${e} state machine`),c.emitLine("// Called by __yo_decr_rc when refcount hits 0 - do NOT call __yo_free here"),c.emitLine(`void ${n}(void* sm_ptr) {`),c.emitLine(` ${t}* sm = (${t}*)sm_ptr;`),c.emitLine(` ASYNC_DEBUG("${n}: Disposing state machine\\n");`),c.emitLine(""),i&&Le(i)){let _=Object.values(u.types).find(p=>p.type===i);if(!_)c.emitLine(" /* Error: capture struct type not found in context */");else{let p=_.cName,f=i.trait.fields.find(m=>m.label===k.___drop[0]);if(f&&f.assignedValue&&ne(f.assignedValue)){let m=u.functions[f.assignedValue.funcId]?.cName;m&&(c.emitLine(' ASYNC_DEBUG(" Dropping capture struct\\n");'),c.emitLine(` ${m}(sm->__capture);`))}else c.emitLine(` /* Warning: ___drop function not found for capture struct ${p} */`)}}if(c.emitLine(""),!pe(r)&&Le(r)){let _=P(r,u);c.emitLine(" // Drop result field if it was set (state == -1 means completed)"),c.emitLine(" int final_state = sm->state;"),c.emitLine(" if (final_state == -1) {"),c.emitLine(' ASYNC_DEBUG(" Dropping result field\\n");');let p=gr(r,u);p?c.emitLine(` ${p}(sm->result);`):c.emitLine(` /* Warning: No ___drop function found for result type ${_} */`),c.emitLine(" }")}c.emitLine("");{let _=[];for(let p of o.capturedVariables){if(p.kind!=="local"||!s.has(p.id)||l.has(p.id)||p.isOwningTheSameRcValueAs!==void 0)continue;let m=`sm->${rn(p.id,"local")}`;if(be(p.type))_.push(` if ((${m}).data != NULL) { __yo_decr_rc((void*)(${m}).data); }`);else if(kt(p.type)||$t(p.type))_.push(` if (${m} != NULL) { __yo_decr_rc_atomic((void*)${m}); }`);else if(pt(p.type)||x(p.type)&&sn(p.type)){let g=gr(p.type,u);g?_.push(` if (${m} != NULL) { ${g}(${m}); }`):_.push(` if (${m} != NULL) { __yo_decr_rc((void*)${m}); }`)}else if(Le(p.type)){let g=gr(p.type,u);g&&_.push(` ${g}(${m});`)}}if(_.length>0){c.emitLine(" // Drop local variables on escape (state == -2)"),c.emitLine(" if (sm->state == -2) {");for(let p of _)c.emitLine(p);c.emitLine(" }")}}c.emitLine(" // Memory freed by __yo_decr_rc after this function returns"),c.emitLine("}")}function Uy(e,t,n,r,i,o,a,s,l,u){let c=u.emitter;if(l){let _=Object.values(u.types).find(f=>f.type===l),p=_?_.cName:`async_capture_${l.id}`;c.emitLine(`${t}* ${r}(${p} __capture) {`)}else c.emitLine(`${t}* ${r}() {`);c.emitLine(" // Allocate async block state machine (heap-backed, ref-counted)"),c.emitLine(` ${t}* sm = (${t}*)__yo_malloc(sizeof(${t}));`),c.emitLine(` memset(sm, 0, sizeof(${t}));`),c.emitLine(""),c.emitLine(" // Initialize reference counting header"),c.emitLine(" sm->header.ref_count = 1; // Caller owns initial reference"),c.emitLine(` GC_DEBUG("AsyncBlock ${t}: Created ptr=%p RC=1\\n", (void*)sm);`),c.emitLine(" sm->header.gc_flags = 0;"),c.emitLine(" sm->header.gc_mark = __YO_GC_UNMARKED;"),c.emitLine(" sm->header.gc_next = NULL;"),c.emitLine(" sm->header.gc_prev = NULL;"),c.emitLine(` sm->header.dispose_fn = (void(*)(void*))${i};`),c.emitLine(" sm->header.traverse_fn = NULL; // TODO: Add traverse for cycle detection if needed"),c.emitLine(""),c.emitLine(" sm->state = 0;"),c.emitLine(" sm->continuation_fn = NULL;"),c.emitLine(" sm->continuation_sm = NULL;"),c.emitLine(""),l&&(c.emitLine(" // Initialize captured variables"),c.emitLine(" sm->__capture = __capture;"),c.emitLine("")),c.emitLine(" // Initialize result (will be set when async block completes)"),pe(a)?c.emitLine(" // Result is unit type, no initialization needed"):c.emitLine(` memset(&sm->result, 0, sizeof(${s}));`),c.emitLine(""),c.emitLine(` sm->__yo_resume_fn = (void(*)(void*))${n};`),c.emitLine(""),c.emitLine(" return sm;"),c.emitLine("}"),c.emitLine("")}function Nc(e){if(!e.deferredAsyncBlocks||e.deferredAsyncBlocks.length===0)return;let t=e.emitter;Ry(e),t.emitLine("// Deferred async block implementations");let n=0;for(;n<e.deferredAsyncBlocks.length;){let r=e.deferredAsyncBlocks[n],i=e.deferredAsyncBlocks.length,{bodyExpr:o,asyncBlockId:a,structName:s,resumeFunctionName:l,constructorName:u,disposeFunctionName:c,futureType:_,resultType:p,resultTypeCName:f,captureType:m,analysis:g}=r,h=e.stateMachineVariables,d=e.currentEvidenceParams,v=new Map,{crossBoundaryIds:T,awaitFutureTempVarAliases:$,variableSegments:C}=Pa(o,g),{slotAliases:L}=Ua(T,C,g.capturedVariables,$,e),b=g.capturedVariables.filter(V=>V.kind==="outer"||T.has(V.id)||$.has(V.id)||L.has(V.id)),R={...g,capturedVariables:b};for(let V of b)v.set(V.id,V);if(m)for(let V of m.fields)v.set(V.label,{id:V.label,name:V.label,type:V.type,kind:"outer",isOwningTheSameRcValueAs:void 0});e.stateMachineVariables=v;let N=e.stateMachineFieldAliases,B=new Map($);for(let[V,U]of L)B.set(V,U);e.stateMachineFieldAliases=B;let D=Cc(o,a,s,l,R,_,m,e);if(e.stateMachineVariables=h,e.currentEvidenceParams=d,e.stateMachineFieldAliases=N,t.emitLine(""),Py(a,s,c,p,m,R,D,T,$,e),t.emitLine(""),Uy(a,s,l,u,c,_,p,f,m,e),t.emitLine(""),e.deferredAsyncBlocks.length>i){let V=e.deferredAsyncBlocks.slice(i);for(let U of V){let{crossBoundaryIds:re,awaitFutureTempVarAliases:j,variableSegments:W}=Pa(U.bodyExpr,U.analysis),{slotAliases:le,slots:_e}=Ua(re,W,U.analysis.capturedVariables,j,e);Sc({asyncBlockId:U.asyncBlockId,structName:U.structName,resultType:U.resultType,resultTypeCName:U.resultTypeCName,captureType:U.captureType,analysis:U.analysis,crossBoundaryIds:re,awaitFutureTempVarAliases:j,overlappingSlotAliases:le,overlappingSlots:_e},e)}}n++}}function Vc(e){for(let t in e.functions){let{value:n}=e.functions[t];n.body&&xc(n.body,e)}}var zy=["__yo_poll_","__yo_fs_event_","__yo_async_"];function By(e){return zy.some(t=>e.startsWith(t))}function xc(e,t){if(e&&F(e)){let n=e;if(Rt(e)){t.usesAsync=!0;let r=e.$?.type;if(r&&Ce(r)&&Dt(r)){let a=`${e.$?.variableName||`async_block_${Date.now()}`}_state_t`;e.$&&(e.$.asyncStateMachineStructName=a),t.types[r.id]={type:r,cName:a},t.emitter.emitDeclarationLine(`typedef struct ${a}_struct ${a}; // Forward declaration for async state machine`)}}if(Rt(e)){let r=e.$?.type;if(r&&Ce(r)&&Dt(r)){let o=e.$?.variableName||`io_async_block_${Date.now()}`,a=!!e.$?.awaitAnalysis,s=a?`${o}_state_t`:`${o}_sync_fut_t`;e.$&&(e.$.asyncStateMachineStructName=s),t.types[r.id]={type:r,cName:s},t.emitter.emitDeclarationLine(`typedef struct ${s}_struct ${s}; // Forward declaration for io.async ${a?"state machine":"sync future"}`)}}(pn(e)||Fa(e))&&(t.usesAsync=!0);{let r=n.func.$?.type;r&&"isExtern"in r&&r.isExtern==="yo"&&"externName"in r&&typeof r.externName=="string"&&By(r.externName)&&(t.usesAsync=!0)}{let r=n.func.$?.type;r&&"isExtern"in r&&r.isExtern==="yo"&&"externName"in r&&typeof r.externName=="string"&&(r.externName==="__yo_thread_spawn"||r.externName==="__yo_worker_spawn")&&(t.usesParallelism=!0)}for(let r of n.args)xc(r,t)}}function Dc(e,t,n){let r=e.$?.type;if(!r||!Ce(r))return"/* Error: io.async must return a Future type */";let i=Dt(r);if(!i)return"/* Error: Could not extract Future module type */";let o=i.isFuture.outputType;if(x(o))if(o.resolvedConcreteType)o=o.resolvedConcreteType;else{let R=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(R&&ne(R)){let N=R.type?.return?.type;if(N&&x(N)&&N.resolvedConcreteType)o=N.resolvedConcreteType;else if(R.body?.$?.type){let B=R.body.$.type;x(B)&&B.resolvedConcreteType?o=B.resolvedConcreteType:x(B)||(o=B)}}}let a=P(o,n),s=e.$?.asyncStateMachineStructName;if(!s)return"/* Error: Missing sync future struct name */";let l=`${s}_dispose`,u=`${s}_resume`,c=n.emitter,_=e.$?.runtimeArgExprsInOrder?.[0];if(!_?.$)return"/* Error: Missing closure argument for io.async */";let p=M(_,t,n),f=_.$.type,m,g;if(x(f)&&f.resolvedConcreteType){let b=f.resolvedConcreteType,R=n.implClosureCallMap.get(b.id);R&&(m=R.functionCName);let N=n.types[b.id];N&&(g=N.cName)}if(!m||!g)return"/* Error: no closure function or capture type for io.async sync path */";c.emitDeclarationLine(`struct ${s}_struct {`),c.emitDeclarationLine(" __yo_ref_header_t header;"),c.emitDeclarationLine(" int state;"),pe(o)?c.emitDeclarationLine(" uint8_t result;"):c.emitDeclarationLine(` ${a} result;`),c.emitDeclarationLine(" void (*continuation_fn)(void*);"),c.emitDeclarationLine(" void* continuation_sm;"),c.emitDeclarationLine(" void (*__yo_resume_fn)(void*);"),c.emitDeclarationLine(` ${g} __capture;`),c.emitDeclarationLine("};"),c.emitDeclarationLine("");let h="";for(let b in n.functions){let R=n.functions[b];if(R.cName===m){let N=Ft(R.value.type);N.length>0&&(h=", "+N.map(B=>`(void*)sm->__capture.${B.fieldPath.join(".")}`).join(", "));break}}c.emitDeclarationLine(`void ${u}(void* ptr) {`),c.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),pe(o)?c.emitDeclarationLine(` ${m}(&sm->__capture${h});`):c.emitDeclarationLine(` sm->result = ${m}(&sm->__capture${h});`),h&&(c.emitDeclarationLine(" if (__yo_effect_escaped) {"),c.emitDeclarationLine(" __yo_effect_escaped = 0;"),c.emitDeclarationLine(" sm->state = -2;"),c.emitDeclarationLine(" __yo_decr_rc(ptr);"),c.emitDeclarationLine(" return;"),c.emitDeclarationLine(" }")),c.emitDeclarationLine(" sm->state = -1;"),c.emitDeclarationLine(" void (*continuation)(void*) = sm->continuation_fn;"),c.emitDeclarationLine(" if (continuation) {"),c.emitDeclarationLine(" void* cont_sm = sm->continuation_sm;"),c.emitDeclarationLine(" continuation(cont_sm);"),c.emitDeclarationLine(" }"),c.emitDeclarationLine(" __yo_decr_rc(ptr);"),c.emitDeclarationLine("}"),c.emitDeclarationLine("");let d=_.$.captureType,v=d&&Le(d)?gr(d,n):void 0,T=d&&Le(d)?On(d,n):void 0,$=gr(o,n);c.emitDeclarationLine(`void ${l}(void* ptr) {`),(v||$)&&(c.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),v&&(c.emitDeclarationLine(" // Drop captured variables (future owns its references)"),c.emitDeclarationLine(` ${v}(sm->__capture);`)),$&&(c.emitDeclarationLine(" if (sm->state == -1) {"),c.emitDeclarationLine(` ${$}(sm->result);`),c.emitDeclarationLine(" }"))),c.emitDeclarationLine("}"),c.emitDeclarationLine("");let C=e.$?.variableName||"__io_async_result",L=st(r,C,n);return c.emitLine(`${t}${L} = (${s}*)__yo_malloc(sizeof(${s}));`),c.emitLine(`${t}memset(${C}, 0, sizeof(${s}));`),c.emitLine(`${t}${C}->header.ref_count = 1;`),c.emitLine(`${t}${C}->header.gc_flags = 0;`),c.emitLine(`${t}${C}->header.gc_mark = __YO_GC_UNMARKED;`),c.emitLine(`${t}${C}->header.gc_next = NULL;`),c.emitLine(`${t}${C}->header.gc_prev = NULL;`),c.emitLine(`${t}${C}->header.dispose_fn = (void(*)(void*))${l};`),c.emitLine(`${t}${C}->header.traverse_fn = NULL;`),c.emitLine(`${t}${C}->__capture = ${p};`),T&&c.emitLine(`${t}${C}->__capture = ${T}(${C}->__capture);`),c.emitLine(`${t}${C}->state = 0;`),c.emitLine(`${t}${C}->__yo_resume_fn = ${u};`),c.emitLine(`${t}${C}->continuation_fn = NULL;`),c.emitLine(`${t}${C}->continuation_sm = NULL;`),C}function Mc(e,t){for(let i=0;i<e.fields.length;i++){let o=e.fields[i];ne(o)&&(Sr(o.type,t),vi(o.body,t))}let n=new Set,r=!0;for(;r;){r=!1;for(let i in t.functions){if(n.has(i))continue;n.add(i),r=!0;let o=t.functions[i];if(Sr(o.value.type,t),o.value.specializedType&&Sr(o.value.specializedType,t),vi(o.value.body,t),o.value.calledComptimeFunctionCaches)for(let a of o.value.calledComptimeFunctionCaches)a.value&&a.value.type&&Mt(a.value.type,t),vi(a.body,t)}}}function Sr(e,t){for(let n of e.parameters)Mt(n.type,t);for(let n of e.forallParameters)Mt(n.type,t);Mt(e.return.type,t)}function vi(e,t){if(e.$&&e.$.type&&Mt(e.$.type,t),e.$&&e.$.value&&ne(e.$.value)){let n=e.$.value;n.isControlFunction?(Sr(n.type,t),Ht(n.body,t)):t.functions[n.funcId]||n.type.parameters.map(o=>o.type).some(o=>x(o)&&Ce(o)&&!o.resolvedConcreteType)||(t.functions[n.funcId]={value:n,cName:te(n.funcId)},Sr(n.type,t),Ht(n.body,t))}if(e.$&&e.$.deferredDropExpressions&&e.$.deferredDropExpressions.length>0)for(let n of e.$.deferredDropExpressions)vi(n,t);if(e.$&&e.$.macroExpansion&&vi(e.$.macroExpansion,t),e.$&&e.$.runtimeDestructurings)for(let{type:n}of e.$.runtimeDestructurings)Mt(n,t);if(e.$&&e.$.captureType&&ce(e.$.captureType)){let n=e.$.captureType;if(!t.types[n.id]){t.types[n.id]={type:n,cName:`__yo_${n.id}`};for(let r of n.fields)Mt(r.type,t);for(let r of n.trait.fields)if(r.assignedValue&&ne(r.assignedValue)){let i=r.assignedValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:i.funcId},Sr(i.type,t),Ht(i.body,t))}}}switch(e.tag){case"FnCall":if(E(e,I.test))break;vi(e.func,t);for(let n of e.args)vi(n,t);break;case"Atom":e.$?.value&&O(e.$.value)&&Mt(e.$.value.value,t);break}}function Mt(e,t){if(!t.types[e.id]){if(x(e)&&Wt(e)){if(e.resolvedConcreteType){Mt(e.resolvedConcreteType,t);return}let n=nn(e);n&&Mt(n,t);return}if(x(e)&&Ce(e)){let n=Dt(e);n&&Mt(n.isFuture.outputType,t);return}if(x(e)&&e.resolvedConcreteType){Mt(e.resolvedConcreteType,t);return}if(!Fe(e)){if(ce(e)||it(e)||ge(e)||we(e)||be(e)||Te(e)||De(e)||Qe(e)||kt(e)||$t(e)){let n=Qe(e)?P(e,t):e.isExtern==="c"&&e.externName?e.externName:`__yo_${e.id}`;if(t.types[e.id]={type:e,cName:n},ce(e))for(let r of e.fields)Mt(r.type,t);if(ge(e)){for(let r of e.variants)if(r.fields)for(let i of r.fields)Mt(i.type,t)}if(it(e))for(let r of e.fields)Mt(r.type,t);if(be(e)){let r=e;for(let i of r.requiredTraits)Mt(i.traitType,t)}if(kt(e)){let r=e;Mt(r.childType,t),P(r,t)}if($t(e)){let r=e;Mt(r.childType,t),P(r,t)}if(Qe(e)&&Mt(e.childType,t),Te(e)||De(e)){for(let r of e.fields)Mt(r.type,t);for(let r of e.fields)if(r.assignedValue&&ne(r.assignedValue)){let i=r.assignedValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:te(i.funcId)},Sr(i.type,t),Ht(i.body,t))}else if(r.assignedValue&&(We(r.assignedValue)||Tt(r.assignedValue))){let i=r.assignedValue;Ko(i,t)}}}else if(ke(e)){let n=e,r=n.childType,i=n.length;if(ze(i)){Mt(r,t);let o=P(r,t),a=`Array_${te(o)}_${i.value}`;t.arrayStructTypes.has(a)||t.arrayStructTypes.set(a,{childType:o,length:typeof i.value=="bigint"?Number(i.value):i.value}),t.types[e.id]={type:e,cName:a}}}else if(Ie(e)){if(Mt(e.childType,t),Qe(e.childType)){let r=e.childType.childType;Mt(r,t);let i=P(r,t),o=`Slice_${te(i)}`;t.sliceStructTypes.has(o)||t.sliceStructTypes.set(o,{childType:i})}t.types[e.id]={type:e,cName:P(e,t)}}else gc.has(e.tag)&&(t.types[e.id]={type:e,cName:P(e,t)});e.trait&&Mt(e.trait,t)}}}function Ti(e){if(e.$&&e.$.value&&de(e.$.value)&&!(G(e.$.type)&&e.$.type.isExtern)){if(!pe(e.$.type))return!0}if(F(e)){if(Ti(e.func))return!0;for(let t of e.args)if(!(t.$?.type&&pe(t.$.type))&&Ti(t))return!0}if(e.$&&e.$.macroExpansion){if(e.$.type&&pe(e.$.type))return!1;if(Ti(e.$.macroExpansion))return!0}if(e.$?.deferredDupExpressions){for(let t of e.$.deferredDupExpressions)if(Ti(t))return!0}if(e.$?.deferredDropExpressions){for(let t of e.$.deferredDropExpressions)if(Ti(t))return!0}return!1}function Ko(e,t){for(let n=0;n<e.fields.length;n++){let r=e.fields[n],i=e.type.fields[n];if(ne(r)){let o=i.label;if(o==="main")t.functions[r.funcId]={value:r,cName:"__yo_user_main"};else if(t.isLibrary)if(t.currentModuleId&&r.funcId.startsWith(`fn_${t.currentModuleId}_`)){let s=te(o);t.functions[r.funcId]={value:r,cName:s},t.exportedFunctionLabels||(t.exportedFunctionLabels=new Map),t.exportedFunctionLabels.set(r.funcId,o)}else t.functions[r.funcId]={value:r,cName:te(r.funcId)};else t.functions[r.funcId]={value:r,cName:te(r.funcId)};Ht(r.body,t)}}}function Oc(e,t){for(let n=0;n<e.fields.length;n++){let r=e.fields[n];r&&ne(r)?t.functions[r.funcId]||(r.isModuleEffectMember=!0,t.functions[r.funcId]={value:r,cName:te(r.funcId)},Ht(r.body,t)):r&&We(r)&&Oc(r,t)}}function Ht(e,t){if(e.$?.value&&We(e.$.value)){let i=e.$.value;Oc(i,t)}if(F(e)&&E(e,I.test)||F(e)&&E(e,k.comptime_expect_error))return;if(e.$&&e.$.macroExpansion&&Ht(e.$.macroExpansion,t),e.$?.effectAnalysis){let i=e.$.effectAnalysis.handlerValue;i&&ne(i)&&Ht(i.body,t)}if(e.$&&e.$.closureFunctionValue){let i=e.$.closureFunctionValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:te(i.funcId)},Ht(i.body,t))}if(F(e)&&e.$&&e.$.dynCallTraitValues&&e.$.dynCallTraitValues.length>0){let i=e.$.type,o=e.args[0];if(be(i)&&o&&o.$?.type){let a=o.$.type,s=e.$.dynCallTraitValues;if(s.length>0&&(pt(a)||$n(a))){let l=$n(a)?a.fields[0].type:a,u=`${l.id}_${i.id}`;t.dynImpls.set(u,{dynType:i,concreteType:l,dataType:a,traitValues:s})}}}if(F(e)){let i=e.func.$?.type,o=e.func.$?.value;if(e.func.token.value==="?=")return;if(G(i)){if(ne(o)&&o.isControlFunction){Ht(o.body,t);for(let a of e.args)Ht(a,t);return}if(ne(o)){if(o.type.return.isCompileTimeOnly||as(o)&&!o.specializedType)return;if(o.specializedType&&sr(o.specializedType)&&Ft(o.specializedType).length===0){Ht(e.func,t);for(let s of e.args)Ht(s,t);return}if(!t.functions[o.funcId]){let a=!1;if(Ti(o.body)){let s=o.specializedType??o.type;if(a=s.implicitParameters.length>0&&(Ft(s).length>0||!sr(o.type)&&o.type.implicitParameters.length>0),!a)return}if(!a&&!(Ft(o.specializedType??o.type).length>0)&&(o.specializedType??o.type).parameters.map(c=>c.type).some(c=>x(c)&&Ce(c)&&!c.resolvedConcreteType))return;t.functions[o.funcId]={value:o,cName:te(o.funcId)},Ht(o.body,t)}}else if(i.isExtern==="c"){let a=i.externName?i.externName:z(e.func)?e.func.token.value:i.id;t.externFunctions[i.id]={type:i,cName:a}}else if(i.isExtern==="yo"){let a=i.externName;if(!(a&&a.startsWith("__yo_"))){let s=a?te(a):z(e.func)?te(e.func.token.value):te(i.id);t.externFunctions[i.id]={type:i,cName:s}}}}Ht(e.func,t);for(let a of e.args)Ht(a,t)}let n=e.$?.type,r=e.$?.value;if(G(n)){if(ne(r)&&r.isControlFunction){if(r.isModuleEffectMember=!0,t.functions[r.funcId]||(t.functions[r.funcId]={value:r,cName:te(r.funcId)}),r.specializedFunctionCaches)for(let i of r.specializedFunctionCaches){let o=i.specializedFunction;o&&!t.functions[o.funcId]&&(o.isModuleEffectMember=!0,t.functions[o.funcId]={value:o,cName:te(o.funcId)},Ht(o.body,t))}Ht(r.body,t);return}if(ne(r)){if(as(r)&&!r.specializedFunctionCaches||t.functions[r.funcId])return;if(Ti(r.body))return;t.functions[r.funcId]={value:r,cName:te(r.funcId)},Ht(r.body,t)}}if(O(e.$?.value)&&Mt(e.$.value.value,t),e.$?.deferredDupExpressions)for(let i of e.$.deferredDupExpressions)Ht(i,t);if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions)Ht(i,t);if(e.$?.dynCallTraitValues)for(let i of e.$.dynCallTraitValues)Ko(i,t)}function Rc(e){let t=k.dispose[0];for(let n in e.types){let{type:r}=e.types[n];if(!ce(r)||!r.isReferenceSemantics)continue;let i=Jn({concreteType:r,methodName:t,env:r.env});for(let o of i)if(o.value&&ne(o.value)){let a=o.value;if(e.functions[a.funcId])continue;a.funcName||(a.funcName=t),e.functions[a.funcId]={value:a,cName:te(a.funcId)},Sr(a.type,e),Ht(a.body,e)}}}function Pc(e){let t=e.emitter,n=new Set;for(let[,r]of e.dynImpls){let i=e.types[r.dynType.id]?.cName||`__yo_dyn_${r.dynType.id}`;n.has(i)||(n.add(i),t.emitLine(`${i} __yo_dup_${i}(${i} dyn) {`),t.emitLine(" if (dyn.data) {"),t.emitLine(" __yo_incr_rc(dyn.data);"),t.emitLine(" }"),t.emitLine(" return dyn;"),t.emitLine("}"),t.emitLine(""),t.emitLine(`void __yo_drop_${i}(${i} dyn) {`),t.emitLine(" if (dyn.data) {"),t.emitLine(" __yo_decr_rc(dyn.data);"),t.emitLine(" }"),t.emitLine("}"),t.emitLine(""))}}function Uc(e){let t=e.emitter;if(e.dynImpls.size===0)return;t.emitLine(""),t.emitLine("// === Dyn Box Functions ==="),t.emitLine("// Constructor and dispose functions for dyn boxes"),t.emitLine("");let n=new Set;for(let[,r]of e.dynImpls){let i=x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType,a=`__yo_dyn_box_${e.types[i.id]?.cName||`unknown_${i.id}`}`;if(n.has(a))continue;n.add(a);let s=P(i,e);t.emitLine(`static ${a}* __yo_new_${a}(${s} value) {`),t.emitLine(` ${a}* box = (${a}*)__yo_malloc(sizeof(${a}));`),t.emitLine(" box->header.ref_count = 1;"),t.emitLine(" box->header.gc_flags = 0;"),t.emitLine(" box->header.gc_mark = __YO_GC_UNMARKED;"),t.emitLine(" box->header.gc_next = NULL;"),t.emitLine(" box->header.gc_prev = NULL;"),t.emitLine(` box->header.dispose_fn = __yo_dispose_${a};`),t.emitLine(" box->header.traverse_fn = NULL; // TODO: Set if value contains GC types"),t.emitLine(" box->value = value;"),t.emitLine(" return box;"),t.emitLine("}"),t.emitLine(""),t.emitLine(`static void __yo_dispose_${a}(void* ptr) {`),t.emitLine(` ${a}* box = (${a}*)ptr;`);let u=(x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType).trait?.fields.find(c=>c.label===k.___drop[0]);if(u&&u.assignedValue&&ne(u.assignedValue)){let c=e.functions[u.assignedValue.funcId]?.cName;c&&t.emitLine(` ${c}(box->value);`)}t.emitLine("}"),t.emitLine("")}}function zc(e){let t=e.emitter;if(e.dynImpls.size!==0){t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Wrapper Functions ==="),t.emitDeclarationLine("// Wrappers that unwrap boxed values and call impl methods"),t.emitDeclarationLine("");for(let[n,r]of e.dynImpls){let i=r.dataType,o=new Set([k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]]);for(let{traitType:a}of r.dynType.requiredTraits){if(!bt(a))continue;let s=a.isFn.callType,l=P(s.return.type,e),u=`__yo_wrap_${n}_call`,c=["void* self_ptr"];for(let _=0;_<s.parameters.length;_++){let p=s.parameters[_],f=P(p.type,e);c.push(`${f} arg${_+1}`)}if(t.emitDeclarationLine(`static ${l} ${u}(${c.join(", ")}) {`),$n(i)){let _=e.types[i.id]?.cName||`unknown_${i.id}`,p=te(i.fields[0].label);t.emitDeclarationLine(` ${_}* box = (${_}*)self_ptr;`);let f=i.fields[0].type,m=x(f)&&f.resolvedConcreteType?f.resolvedConcreteType:f,g=e.implClosureCallMap.get(m.id),h=(()=>{if(g)return g.functionCName;for(let[,v]of Object.entries(e.functions))if(v.value.closureInfo?.captureType?.id===m.id)return v.cName})(),d=[];if(h){d.push(`(void*)&box->${p}`);for(let v=0;v<s.parameters.length;v++)d.push(`arg${v+1}`);$r(s.return.type)?t.emitDeclarationLine(` ${h}(${d.join(", ")});`):t.emitDeclarationLine(` return ${h}(${d.join(", ")});`)}else{d.push(`box->${p}.data`);for(let v=0;v<s.parameters.length;v++)d.push(`arg${v+1}`);$r(s.return.type)?t.emitDeclarationLine(` box->${p}.call(${d.join(", ")});`):t.emitDeclarationLine(` return box->${p}.call(${d.join(", ")});`)}}else{t.emitDeclarationLine(" (void)self_ptr; /* Dyn(Fn): expected Box(...) data */");for(let _=0;_<s.parameters.length;_++)t.emitDeclarationLine(` (void)arg${_+1};`);$r(s.return.type)?t.emitDeclarationLine(" return;"):(t.emitDeclarationLine(` ${l} zero = (${l})0;`),t.emitDeclarationLine(" return zero;"))}t.emitDeclarationLine("}"),t.emitDeclarationLine("")}for(let a=0;a<r.dynType.requiredTraits.length;a++){let{traitType:s}=r.dynType.requiredTraits[a];if(bt(s))continue;let l=r.traitValues[a];if(!l){t.emitDeclarationLine(`/* Warning: Module value missing for module ${a} */`);continue}let c=l.type.fields;for(let _=0;_<c.length;_++){let p=c[_];if(p.label==="Self"||o.has(p.label))continue;let f=l.fields[_];if(!f||!ne(f)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function value */`);continue}let m=p.type;if(!G(m)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function type */`);continue}let g=f.funcId,h=e.functions[g]?.cName;if(!h){t.emitDeclarationLine(`/* Warning: Impl function for ${p.label} not found */`);continue}let d=`__yo_wrap_${n}_${p.label}`,v=P(m.return.type,e),T=["void* self_ptr"];for(let b=1;b<m.parameters.length;b++){let R=m.parameters[b],N=P(R.type,e);T.push(`${N} arg${b}`)}t.emitDeclarationLine(`static ${v} ${d}(${T.join(", ")}) {`);let $=m.parameters[0]?.type,C;if($n(i)){let b=e.types[i.id]?.cName||`unknown_${i.id}`,R=te(i.fields[0].label);t.emitDeclarationLine(` ${b}* box = (${b}*)self_ptr;`),$&&Ie($)?C=`&box->${R}`:C=`box->${R}`}else{let b=P(r.concreteType,e);t.emitDeclarationLine(` ${b} concrete_value = (${b})self_ptr;`),$&&Ie($)?C="&concrete_value":C="concrete_value"}let L=[C];for(let b=1;b<m.parameters.length;b++)L.push(`arg${b}`);$r(m.return.type)?t.emitDeclarationLine(` ${h}(${L.join(", ")});`):t.emitDeclarationLine(` return ${h}(${L.join(", ")});`),t.emitDeclarationLine("}"),t.emitDeclarationLine("")}}}}}function Bc(e){let t=e.emitter;if(e.dynImpls.size===0)return;t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn TypeId Statics ==="),t.emitDeclarationLine("// Unique static per concrete type \u2014 address is the runtime TypeId"),t.emitDeclarationLine("");let n=new Set;e.typeIdStatics||(e.typeIdStatics=new Map);for(let[,r]of e.dynImpls){let i=x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType,o=e.types[i.id]?.cName||`unknown_${i.id}`,a=`__yo_typeid_${o}`;!n.has(a)&&!e.typeIdStatics.has(i.id)&&(n.add(a),e.typeIdStatics.set(i.id,a),t.emitDeclarationLine(`static const char ${a} = 0; // TypeId for ${o}`))}t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Static Vtables ==="),t.emitDeclarationLine("// Static vtables for dynamic dispatch"),t.emitDeclarationLine("");for(let[r,i]of e.dynImpls){let o=e.types[i.dynType.id]?.cName||`__yo_dyn_${i.dynType.id}`,a=x(i.concreteType)&&i.concreteType.resolvedConcreteType?i.concreteType.resolvedConcreteType:i.concreteType,s=e.types[a.id]?.cName||`unknown_${a.id}`,l=`__yo_vtable_${r}`,u=`${o}_vtable`,c=`__yo_typeid_${s}`;t.emitDeclarationLine(`// Vtable for impl(${s}, ${i.dynType.requiredTraits.map(({traitType:f})=>f.typeName||"?").join(" + ")})`),t.emitDeclarationLine(`static const ${u} ${l} = {`),t.emitDeclarationLine(` .__yo_type_id = (uintptr_t)&${c},`);let _=new Set,p=new Set([k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]]);for(let{traitType:f}of i.dynType.requiredTraits){if(bt(f)){let m=`__yo_wrap_${r}_call`;t.emitDeclarationLine(` .call = ${m},`),_.add("call");continue}for(let m of f.fields)if(m.label!=="Self"&&!p.has(m.label)&&!_.has(m.label)&&(_.add(m.label),G(m.type))){let g=m.type;if(g.parameters.length>0){let h=g.parameters[0];if(h&&h.label==="self"){let d=`__yo_wrap_${r}_${m.label}`;t.emitDeclarationLine(` .${te(m.label)} = ${d},`)}}}}t.emitDeclarationLine("};"),t.emitDeclarationLine("")}}function Gc(e,t){let n=!yi(t);e.emitLine(`
192
+ `}else if(O(e)){let r=e.value;if(r)return t.types[r.id]?t.types[r.id].cName:`/* Error: No C type name found for type ${A(r)} */`}else if(wi(e)){let r=e.targetValue[0];if(r){let i=n?.$?.convertedRuntimeType||n?.$?.type;if(i&&Ie(i)){let o=i.childType,a=Qt(r,t,{$:{type:o,convertedRuntimeType:o}});if(a&&!a.startsWith("/*")&&!a.startsWith("//"))return`(&${a})`}}return`/* Error: Cannot generate pointer value ${Me(e)} */`}}return`/* skip generating: ${Me(e)} */`}function Qi(e,t,n){if(e===t)return!0;if(e.tag==="FnCall"){if(n&&n(e))return!1;if(Qi(e.func,t,n))return!0;for(let r of e.args)if(Qi(r,t,n))return!0}return!1}function ky(e,t,n){for(let r=0;r<t.length;r++)if(Qi(e,t[r].expr,n))return r;return-1}function vc(e,t,n){let r=[],i=n?.shouldSkipBody;if(e.tag!=="FnCall"||!E(e,"begin"))return t.length===0?[{stateNumber:0,expressions:[e],suspensionPoint:null}]:[{stateNumber:0,expressions:[e],suspensionPoint:t[0]??null}];let o=e.args,a=[],s=[];for(let l of o){let u=ky(l,t,i),c=n?.handleReturnStatements&&(dt(l,"return")||E(l,"return"));if(u!==-1){if(s.push(l),a.push(s),s=[],n?.handleSequentialSuspensions)for(let _=u+1;_<t.length&&Qi(l,t[_].expr,i);_++)a.push([])}else if(c){s.push(l),a.push(s),s=[];break}else s.push(l)}s.length>0&&a.push(s);for(let l=0;l<a.length;l++){let u=a[l],c=l<t.length?t[l]:null;r.push({stateNumber:l,expressions:u,suspensionPoint:c})}return r}function ll(e,t){let r=vc(e,t,{shouldSkipBody:Rt,handleReturnStatements:!0,handleSequentialSuspensions:!0}).map(i=>({stateNumber:i.stateNumber,expressions:i.expressions,awaitPoint:i.suspensionPoint}));return r.length>0&&r[r.length-1].awaitPoint!==null&&r.push({stateNumber:r.length,expressions:[],awaitPoint:null}),r}function wy(e,t){return Qi(e,t,Rt)}function Tc(e,t,n,r=!1){let i=n.emitter;for(let o=0;o<e.expressions.length;o++){let a=e.expressions[o],s=o===e.expressions.length-1,l=e.awaitPoint&&wy(a,e.awaitPoint.expr),u=e.awaitPoint&&a.tag==="FnCall"&&(E(a,I.while)||E(a,I.cond)||E(a,I.match))&&un(a);if((l||u)&&e.awaitPoint)to(a,e.awaitPoint,e.stateNumber,t,n);else if(s&&r){let c=M(a,t,n);c&&(i.emitLine(`${t}// Store final expression result`),i.emitLine(`${t}sm->result = ${c};`))}else{let c=M(a,t,n);!c||!a.$||ut(a.$.env.modulePath,c)||i.emitLine(`${t}${c};`)}}}function to(e,t,n,r,i){let o=i.emitter;if(e.tag==="FnCall"&&pn(e)){let a=e.args[0];if(!a){o.emitLine(`${r}// Error: await without argument`);return}if(t.futureVariableId===void 0){let s=M(a,r,i);o.emitLine(`${r}// Store pattern-matched Future for await ${t.index}`),o.emitLine(`${r}sm->await_future_${t.index} = ${s};`)}else o.emitLine(`${r}// Prepare for await (future already stored in state machine variable)`);return}if(e.tag==="FnCall"&&E(e,":=")){let a=e.args[0],s=e.args[1];if(!a||!s){o.emitLine(`${r}// Error: Invalid assignment expression`);return}if(s.tag==="FnCall"&&pn(s)){let l=s.args[0];if(!l){o.emitLine(`${r}// Error: await without argument`);return}let u=a.token?.value;if(!u||!a.$){o.emitLine(`${r}// Error: Invalid variable name`);return}if(t.futureVariableId===void 0){let c=M(l,r,i);o.emitLine(`${r}// Store Future for await (variable: ${u})`),o.emitLine(`${r}sm->await_future_${t.index} = ${c};`)}else o.emitLine(`${r}// Store Future for await (variable: ${u}) - future already in state machine`);return}if(s.tag==="FnCall"&&E(s,I.cond)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,c=X(a.$.env,u);c.length>0&&(l=c[c.length-1].id)}Yo(s,t,r,i,l);return}if(s.tag==="FnCall"&&E(s,I.match)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,c=X(a.$.env,u);c.length>0&&(l=c[c.length-1].id)}Ho(s,t,r,i,l);return}}if(e.tag==="FnCall"&&E(e,"=")){let a=e.args[0],s=e.args[1];if(a&&s){if(s.tag==="FnCall"&&E(s,I.cond)){let l=M(a,r,i);Yo(s,t,r,i,void 0,l||void 0);return}if(s.tag==="FnCall"&&E(s,I.match)){let l=M(a,r,i);Ho(s,t,r,i,void 0,l||void 0);return}}}if(e.tag==="FnCall"&&E(e,I.cond)){Yo(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,I.match)){Ho(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,I.while)){ul(e,t,r,i);return}o.emitLine(`${r}// ERROR: Unsupported pattern for await expression`),o.emitLine(`${r}// Expression type: ${e.tag}, function: ${e.tag==="FnCall"?e.func.tag==="Atom"?e.func.token?.value:e.func.tag:"N/A"}`)}function Yo(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,I.cond)){a.emitLine(`${n}// Error: Expected cond expression`);return}let s=e.args;if(s.length===0){a.emitLine(`${n}// Error: cond must have at least one branch`);return}let l=[],u=-1;for(let h=0;h<s.length;h++){let d=s[h];if(d.tag==="FnCall"&&E(d,"=>")){let v=d.args[0];if(v&&!(Re(v.$?.value)&&v.$.value.value===!1)){u=h;break}}}let c=!1;if(u>=0){let h=s[u];if(h.tag==="FnCall"&&E(h,"=>")){let d=h.args[0];d&&Re(d.$?.value)&&d.$.value.value===!0&&(c=!0)}}if(c&&u>=0){let h=s[u],d=F(h)?h.args[1]:void 0;if(d)if(qr(d)){let C=eo(d,t,n,r),L=r.asyncWhileLoopInfo?.get(t.index);if(L&&C.length>0){let R=r.asyncCondBranchInfo?.get(t.index)?.branches.some(N=>N.hasAwait&&N.remainingExprs&&N.remainingExprs.length>0)??!1;L.condBranchPostWhileExprs={branchIndex:u,condBranchFieldIndex:t.index,exprs:C,deferredDropExpressions:d.$?.deferredDropExpressions,skipCondBranchCheck:R},l.push({index:u,value:d,hasAwait:!0,remainingExprs:[],deferredDropExpressions:d.$?.deferredDropExpressions})}else l.push({index:u,value:d,hasAwait:!0,remainingExprs:C,deferredDropExpressions:d.$?.deferredDropExpressions})}else{if(Zi(e,d,r,i,o))Ji(d,n,r);else if(F(d)&&E(d,I.begin)){let C=d.args;for(let L=0;L<C.length;L++){let b=C[L],R=M(b,n,r);if(R==="break"&&t.isInsideWhile)a.emitLine(`${n}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${n}goto while_loop_${t.index}_end;`);else{let N=R==="break"||R==="continue"||R?.includes("return");R&&(N||b.$&&!ut(b.$.env.modulePath,R))&&a.emitLine(`${n}${R};`)}}if(d.$?.deferredDropExpressions)for(let L of d.$.deferredDropExpressions){let b=M(L,n,r);b&&a.emitLine(`${n}${b};`)}}else{let C=M(d,n,r);if(C==="break"&&t.isInsideWhile)a.emitLine(`${n}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${n}goto while_loop_${t.index}_end;`);else{let L=C==="break"||C==="continue"||C?.includes("return");C&&(L||d.$&&!ut(d.$.env.modulePath,C))&&a.emitLine(`${n}${C};`)}}l.push({index:u,value:d,hasAwait:!1})}r.asyncCondBranchInfo||(r.asyncCondBranchInfo=new Map),(r.asyncCondBranchInfo.get(t.index)?.branches.some($=>$.hasAwait&&$.remainingExprs&&$.remainingExprs.length>0)??!1)||r.asyncCondBranchInfo.set(t.index,{branches:l,targetVariableId:i,targetAssignmentCode:o});return}let _=!1,p=0,f=n;for(let h=0;h<s.length;h++){let d=s[h];if(d.tag!=="FnCall"||!E(d,"=>")){a.emitLine(`${f}// Error: Expected => pair in cond`);continue}let v=d.args[0],T=d.args[1];if(!v||!T){a.emitLine(`${f}// Error: Invalid pair in cond`);continue}if(Re(v.$?.value)&&v.$.value.value===!1)continue;_&&(a.emitLine(`${f}else {`),p++,f+=" ");let $=h===s.length-1&&v.tag==="Atom"&&v.token?.value==="true"?null:M(v,f,r);$?a.emitLine(`${f}if (${$}) {`):a.emitLine(`${f}{`),_=!0;let C=`${f} `;if(qr(T)){a.emitLine(`${C}sm->cond_branch_${t.index} = ${h};`);let b=eo(T,t,C,r),R=r.asyncWhileLoopInfo?.get(t.index);if(R&&b.length>0){let B=r.asyncCondBranchInfo?.get(t.index)?.branches.some(D=>D.hasAwait&&D.remainingExprs&&D.remainingExprs.length>0)??!1;R.condBranchPostWhileExprs={branchIndex:h,condBranchFieldIndex:t.index,exprs:b,deferredDropExpressions:T.$?.deferredDropExpressions,skipCondBranchCheck:B},l.push({index:h,value:T,hasAwait:!0,remainingExprs:[],deferredDropExpressions:T.$?.deferredDropExpressions})}else l.push({index:h,value:T,hasAwait:!0,remainingExprs:b,deferredDropExpressions:T.$?.deferredDropExpressions})}else{if(Zi(e,T,r,i,o))Ji(T,C,r);else if(F(T)&&E(T,I.begin)){let b=T.args;for(let R=0;R<b.length;R++){let N=b[R],B=M(N,C,r);if(B==="break"&&t.isInsideWhile)a.emitLine(`${C}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${C}goto while_loop_${t.index}_end;`);else{let D=B==="break"||B==="continue"||B?.includes("return");B&&(D||N.$&&!ut(N.$.env.modulePath,B))&&a.emitLine(`${C}${B};`)}}if(T.$?.deferredDropExpressions)for(let R of T.$.deferredDropExpressions){let N=M(R,C,r);N&&a.emitLine(`${C}${N};`)}}else{let b=M(T,C,r);if(b==="break"&&t.isInsideWhile)a.emitLine(`${C}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${C}goto while_loop_${t.index}_end;`);else{let R=b==="break"||b==="continue"||b?.includes("return");b&&(R||T.$&&!ut(T.$.env.modulePath,b))&&a.emitLine(`${C}${b};`)}}l.push({index:h,value:T,hasAwait:!1})}a.emitLine(`${f}}`)}for(let h=0;h<p;h++)f=f.slice(0,-2),a.emitLine(`${f}}`);r.asyncCondBranchInfo||(r.asyncCondBranchInfo=new Map),(r.asyncCondBranchInfo.get(t.index)?.branches.some(h=>h.hasAwait&&h.remainingExprs&&h.remainingExprs.length>0)??!1)||r.asyncCondBranchInfo.set(t.index,{branches:l,targetVariableId:i,targetAssignmentCode:o})}function Zi(e,t,n,r,i){return!r&&!i&&n.asyncBodyReturnExpr!==void 0&&e===n.asyncBodyReturnExpr&&!!n.inAsyncStateMachine&&!Ec(t)}function Ji(e,t,n){let r=n.emitter,i=pe(e.$?.type);if(F(e)&&E(e,I.begin)){let o=e.args;for(let s=0;s<o.length-1;s++){let l=o[s],u=M(l,t,n);u&&l.$&&!ut(l.$.env.modulePath,u)&&r.emitLine(`${t}${u};`)}let a=o[o.length-1];if(a&&!i){let s=M(a,t,n);s&&r.emitLine(`${t}sm->result = ${s};`)}if(e.$?.deferredDropExpressions)for(let s of e.$.deferredDropExpressions){let l=M(s,t,n);l&&r.emitLine(`${t}${l};`)}}else if(!i){let o=M(e,t,n);o&&r.emitLine(`${t}sm->result = ${o};`)}if(r.emitLine(`${t}// Drop local variables before early completion`),n.pendingDeferredDrops)for(let o of n.pendingDeferredDrops){let a=M(o,t,n);a&&a.includes("sm->")&&r.emitLine(`${t}${a};`)}Ar({emitter:r,indent:t,resultCode:void 0,debugLabel:n.currentFunctionName}),r.emitLine(`${t}return;`)}function qr(e){if(e.tag==="FnCall"&&pn(e))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(qr(t))return!0}return!1}function Ec(e){if(dt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(Ec(t))return!0}return!1}function Ho(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,I.match)){a.emitLine(`${n}// Error: Expected match expression`);return}let s=e.args[0],l=e.args.slice(1);if(!s||l.length===0){a.emitLine(`${n}// Error: match must have a value and at least one case`);return}let u=M(s,n,r),c=s.$?.type;if(!c){a.emitLine(`${n}// Error: match value has no type`);return}if(e.$?.isPrimitiveMatch){Ly(e,l,u,t,n,r,i,o);return}if(!ge(c)){a.emitLine(`${n}// Error: match requires an enum type or primitive type`);return}let _=c,p=r.types[_.id]?.cName;if(!p){a.emitLine(`${n}// Error: enum type has no C name`);return}let f=Yt(_);if(f){let m=-1,g=-1,h;for(let d=0;d<l.length;d++){let v=l[d];if(F(v)&&E(v,"=>",2)){let T=v.args[0];if(T&&F(T)&&E(T,"."))m=d;else if(T&&F(T)){let $=T.func;$&&F($)&&E($,".")&&(g=d,T.args.length>0&&z(T.args[0])&&(h=T.args[0].token.value))}}}if(a.emitLine(`${n}if (${u} != NULL) {`),g>=0){let d=l[g];if(!F(d))a.emitLine(`${n} // Error: Expected => in case`);else{let v=d.args[1];if(h){let T=r,$=!1,C;if(T.stateMachineVariables){for(let[L,b]of T.stateMachineVariables)if(b.name===h){$=!0,C=L;break}}if($&&C){let L=rn(C,"local",T.stateMachineFieldAliases);a.emitLine(`${n} sm->${L} = ${u};`)}else a.emitLine(`${n} ${P(f,r)} ${h} = ${u};`)}if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${g};`),qr(v)){let T=eo(v,t,n+" ",r);if(T.length>0){let $=r;$.asyncCondBranchInfo||($.asyncCondBranchInfo=new Map);let C=$.asyncCondBranchInfo.get(t.index)||{branches:[]};C.branches.push({index:g,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(Zi(e,v,r,i,o))Ji(v,n+" ",r);else{let T=M(v,n+" ",r);if(i){let $=te(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!ut(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}if(a.emitLine(`${n}} else {`),m>=0){let d=l[m];if(!F(d))a.emitLine(`${n} // Error: Expected => in case`);else{let v=d.args[1];if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${m};`),qr(v)){let T=eo(v,t,n+" ",r);if(T.length>0){let $=r;$.asyncCondBranchInfo||($.asyncCondBranchInfo=new Map);let C=$.asyncCondBranchInfo.get(t.index)||{branches:[]};C.branches.push({index:m,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(Zi(e,v,r,i,o))Ji(v,n+" ",r);else{let T=M(v,n+" ",r);if(i){let $=te(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!ut(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}a.emitLine(`${n}}`)}else{a.emitLine(`${n}switch (${u}.tag) {`);let m=!1;for(let g=0;g<l.length;g++){let h=l[g];if(!F(h)||!E(h,"=>",2))continue;let d=h.args[0],v=h.args[1],T=z(d)&&d.token.value==="_",$;if(!T){if(F(d)&&E(d,".",1))$=d.args[0].token.value;else if(F(d)){let C=d.func;C&&F(C)&&E(C,".",1)&&($=C.args[0].token.value)}}if(!T&&!$){a.emitLine(`${n} // Error: Could not extract variant name`);continue}if(T)m=!0,a.emitLine(`${n} default: {`);else{let C=`${p.toUpperCase()}_${$.toUpperCase()}`;a.emitLine(`${n} case ${C}: {`)}if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${g};`),F(d)&&d.args.length>=1){let C=d.func;if(C&&F(C)&&E(C,".")){let L=_.variants.find(b=>b.name===$);if(L&&L.fields)for(let b=0;b<Math.min(d.args.length,L.fields.length);b++){let R=d.args[b],N=L.fields[b];if(z(R)&&N){let B=R.token.value,D=te(B),V=r,U=!1,re;if(V.stateMachineVariables){for(let[le,_e]of V.stateMachineVariables)if(_e.name===B){U=!0,re=le;break}}let j=te(N.label,N.type.isExtern==="c"),W=`${u}.data.${$}.${j}`;if(U&&re){let le=rn(re,"local",V.stateMachineFieldAliases);a.emitLine(`${n} sm->${le} = ${W};`)}else{let le=P(N.type,r);a.emitLine(`${n} ${le} ${D} = ${W};`)}}}}}if(qr(v)){let C=eo(v,t,n+" ",r);if(C.length>0){let L=r;L.asyncCondBranchInfo||(L.asyncCondBranchInfo=new Map);let b=L.asyncCondBranchInfo.get(t.index)||{branches:[]};b.branches.push({index:g,value:v,hasAwait:!0,remainingExprs:C,deferredDropExpressions:v.$?.deferredDropExpressions}),L.asyncCondBranchInfo.set(t.index,b)}}else if(Zi(e,v,r,i,o))Ji(v,n+" ",r);else{let C=M(v,n+" ",r);if(i){let L=te(`var_${i}`);C&&a.emitLine(`${n} sm->${L} = ${C};`)}else o?C&&a.emitLine(`${n} ${o} = ${C};`):C&&v.$&&!ut(v.$.env.modulePath,C)&&a.emitLine(`${n} ${C};`)}a.emitLine(`${n} break;`),a.emitLine(`${n} }`)}m||a.emitLine(`${n} default: break;`),a.emitLine(`${n}}`)}}function Fy(e){return F(e)?E(e,"|",2):!1}function sl(e){if(!Fy(e))return[e];if(e.tag!=="FnCall")return[e];let t=e.args[0],n=e.args[1];return[...sl(t),...sl(n)]}function Ly(e,t,n,r,i,o,a,s){let l=o.emitter,u=[];l.emitLine(`${i}switch (${n}) {`);for(let c=0;c<t.length;c++){let _=t[c];if(!F(_)||!E(_,"=>",2))continue;let p=_.args[0],f=_.args[1];if(dt(p,"_"))l.emitLine(`${i} default:`);else{let m=p.$?.primitivePatternValues;if(m&&m.length>0){for(let g of m)if(g!==void 0){let h=Qt(g,o);l.emitLine(`${i} case ${h}:`)}}else{let g=sl(p);for(let h of g){let d=h.$?.value;if(d!==void 0){let v=Qt(d,o);l.emitLine(`${i} case ${v}:`)}}}}if(l.emitLine(`${i} sm->cond_branch_${r.index} = ${c};`),qr(f)){let m=eo(f,r,i+" ",o);u.push({index:c,value:f,hasAwait:!0,remainingExprs:m,deferredDropExpressions:f.$?.deferredDropExpressions})}else{if(Zi(e,f,o,a,s))Ji(f,i+" ",o);else{let m=M(f,i+" ",o);if(a){let g=te(`var_${a}`);m&&l.emitLine(`${i} sm->${g} = ${m};`)}else s?m&&l.emitLine(`${i} ${s} = ${m};`):m&&f.$&&!ut(f.$.env.modulePath,m)&&l.emitLine(`${i} ${m};`)}u.push({index:c,value:f,hasAwait:!1})}l.emitLine(`${i} break;`)}l.emitLine(`${i}}`),o.asyncCondBranchInfo||(o.asyncCondBranchInfo=new Map),o.asyncCondBranchInfo.set(r.index,{branches:u,targetVariableId:a,targetAssignmentCode:s})}function eo(e,t,n,r){let i=r.emitter,o=[];if(e.tag!=="FnCall"||!E(e,"begin"))return i.emitLine(`${n}// Error: Expected begin block in cond branch with await`),o;let a=e.args,s=!1;for(let l of a){if(s){o.push(l);continue}if(qr(l))if(s=!0,l.tag==="FnCall"&&E(l,":=")){let u=l.args[1];if(u&&u.tag==="FnCall"&&pn(u)){let c=u.args[0];if(c){let _=M(c,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${_};`)}}}else if(l.tag==="FnCall"&&pn(l)){let u=l.args[0];if(u)if(t.futureVariableId===void 0){let c=M(u,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${c};`)}else i.emitLine(`${n}// Await will use Future from sm->var_${t.futureVariableId}`)}else if(l.tag==="FnCall"&&E(l,I.cond)){let u=l===a[a.length-1],c=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),Yo(l,t,n,r),r.asyncBodyReturnExpr=c}else if(l.tag==="FnCall"&&E(l,I.match)){let u=l===a[a.length-1],c=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),Ho(l,t,n,r),r.asyncBodyReturnExpr=c}else l.tag==="FnCall"&&E(l,I.while)&&ul(l,t,n,r);else{let u=M(l,n,r);u&&l.$&&!ut(l.$.env.modulePath,u)&&i.emitLine(`${n}${u};`)}}return o}function ul(e,t,n,r){let i=r.emitter;if(e.tag!=="FnCall"||!E(e,"while")){i.emitLine(`${n}// Error: Expected while expression`);return}let o=e.args;if(o.length<2||o.length>3){i.emitLine(`${n}// Error: while must have 2 or 3 arguments (condition, [step,] body)`);return}let a=o[0],s=o.length===3?o[1]:void 0,l=o.length===3?o[2]:o[1],u=Iy(l),c;u?(c=r.asyncNextWhileLoopIndex??t.index+1,r.asyncNextWhileLoopIndex=c+1):c=t.index,i.emitLine(`${n}sm->while_loop_${c}_active = true;`),i.emitLine(`${n}while_loop_${c}_start:`);let _=M(a,n,r);i.emitLine(`${n}if (!(${_})) {`),i.emitLine(`${n} sm->while_loop_${c}_active = false;`),i.emitLine(`${n} goto while_loop_${c}_end;`),i.emitLine(`${n}}`);let p=Ay(l,t,n,r,c);if(i.emitLine(`${n}while_loop_${c}_end:`),r.asyncWhileLoopInfo||(r.asyncWhileLoopInfo=new Map),u){let f=r.asyncWhileLoopInfo.get(t.index);f&&(f.outerWhileLoop={whileLoopIndex:c,conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}else r.asyncWhileLoopInfo.set(t.index,{conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}function Ay(e,t,n,r,i){let o=r.emitter,a=[],s=[];e.tag==="FnCall"&&E(e,"begin")?s=e.args:s=[e];let l=-1;for(let f=0;f<s.length;f++){let m=s[f];if(un(m)){l=f;break}}if(l===-1)return o.emitLine(`${n}// Error: Expected await in while loop body but none found`),a;let u=r.smWhileBreakInfo,c=r.smWhileContinueInfo,_=r.smWhileBodyDrops;r.smWhileBreakInfo={label:`while_loop_${i}_end`,activeIndex:i},r.smWhileContinueInfo={label:`while_loop_${i}_start`,emitDropsBeforeGoto:!0},r.smWhileBodyDrops=[...e.$?.deferredDropExpressions??[]];for(let f=0;f<l;f++){let m=s[f],g=M(m,n,r);g&&m.$&&!ut(m.$.env.modulePath,g)&&o.emitLine(`${n}${g};`)}r.smWhileBreakInfo=u,r.smWhileContinueInfo=c,r.smWhileBodyDrops=_;let p=s[l];if(F(p)&&E(p,I.while)&&un(p)){ul(p,t,n,r);for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}if(F(p)&&E(p,":=")){let f=p.args[1];if(f&&f.tag==="FnCall"&&pn(f)){let m=f.args[0];if(m){let g=M(m,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${g};`)}}}else if(p.tag==="FnCall"&&pn(p)){let f=p.args[0];if(f&&t.futureVariableId===void 0){let m=M(f,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${m};`)}}else if(F(p)&&E(p,I.cond)){Yo(p,t,n,r,void 0);for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}else if(F(p)&&E(p,I.match)){Ho(p,t,n,r);for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}for(let f=l+1;f<s.length;f++)a.push(s[f]);return a}function Iy(e){let t=e.tag==="FnCall"&&E(e,"begin")?e.args:[e];for(let n of t)if(n.tag==="FnCall"&&E(n,I.while)&&un(n))return!0;return!1}function hi(e,t,n){if(e)switch(e.tag){case"Atom":if(e.$&&e.token.type==="identifier"){let r=e.token.value,i=X(e.$.env,r);if(i.length>0){let o=i[i.length-1];if(o&&!o.isCompileTimeOnly){let a=n.get(o.id)??o.id,s=o.isOwningTheSameRcValueAs?o.isOwningTheSameRcValueAs.id:a;t.add(s)}}}break;case"FnCall":if(Rt(e)){if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)hi(r,t,n);break}hi(e.func,t,n);for(let r of e.args)hi(r,t,n);if(e.$?.deferredDropExpressions)for(let r of e.$.deferredDropExpressions)hi(r,t,n);if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)hi(r,t,n);break}}function Pa(e,t){let{awaitPoints:n,capturedVariables:r,variableIdRemapping:i}=t;if(n.length===0)return{crossBoundaryIds:new Set,awaitFutureTempVarAliases:new Map,variableSegments:new Map};let o=new Set,a=ll(e,n);for(let _ of a)(_.awaitPoint?.isInsideCond||_.awaitPoint?.isInsideWhile)&&o.add(_.stateNumber);let s=new Map;for(let _ of a){let p=new Set;for(let f of _.expressions)hi(f,p,i);for(let f of p){let m=s.get(f);m||(m=new Set,s.set(f,m)),m.add(_.stateNumber)}}let l=-1;if(e.$?.deferredDropExpressions){let _=new Set;for(let p of e.$.deferredDropExpressions)hi(p,_,i);for(let p of _){let f=s.get(p);f||(f=new Set,s.set(p,f)),f.add(l)}}let u=new Set;for(let _ of r){if(_.kind==="outer")continue;let p=s.get(_.id);if(!p)u.add(_.id);else if(p.size>1)u.add(_.id);else if(p.has(l))u.add(_.id);else{let f=p.values().next().value;o.has(f)&&u.add(_.id)}}let c=new Map;for(let _ of n){if(_.futureVariableId!==void 0)continue;let p=_.expr;if(!F(p))continue;let f=p.args[0];if(!f)continue;let m=f.$?.variableName;if(!m)continue;let g=r.find(h=>h.kind==="local"&&(h.name===m||h.id===m));g&&(c.set(g.id,`await_future_${_.index}`),u.delete(g.id))}return{crossBoundaryIds:u,awaitFutureTempVarAliases:c,variableSegments:s}}function Ua(e,t,n,r,i){let o={slotAliases:new Map,slots:[]},a=n.filter(p=>p.kind==="local"&&e.has(p.id)&&!r.has(p.id)&&!Le(p.type));if(a.length<2)return o;let s=new Map;for(let p of a){let f=t.get(p.id);if(!f||f.size===0)continue;let m=[...f].filter(d=>d>=0);if(m.length===0)continue;let g=Math.min(...m),h=Math.max(...m);s.set(p.id,[g,h])}if(s.size<2)return o;let l=new Map;for(let[p]of s){let f=a.find(h=>h.id===p);if(!f)continue;let m=P(f.type,i),g=l.get(m);g||(g=[],l.set(m,g)),g.push(p)}let u=new Map,c=[],_=0;for(let[p,f]of l){if(f.length<2)continue;let m=new Map;for(let d of f)m.set(d,new Set);for(let d=0;d<f.length;d++)for(let v=d+1;v<f.length;v++){let[T,$]=s.get(f[d]),[C,L]=s.get(f[v]);T<=L&&C<=$&&(m.get(f[d]).add(f[v]),m.get(f[v]).add(f[d]))}let g=new Map;for(let d of f){let v=new Set;for(let $ of m.get(d))g.has($)&&v.add(g.get($));let T=0;for(;v.has(T);)T++;g.set(d,T)}let h=new Map;for(let[d,v]of g){let T=h.get(v);T||(T=[],h.set(v,T)),T.push(d)}for(let[,d]of h){if(d.length<2)continue;let v=`slot_${_}`,T=d.map($=>a.find(C=>C.id===$)?.name??$);for(let $ of d)u.set($,v);c.push({fieldName:v,cType:p,variableNames:T}),_++}}return{slotAliases:u,slots:c}}function _l(e,t){if(e.futureVariableId){let n=t.capturedVariables.find(r=>r.id===e.futureVariableId);if(n)return n.kind==="outer"?n.name:`var_${n.id}`}return`await_future_${e.index}`}function jo(e){return!e||!x(e)?!1:e.resolvedConcreteType&&x(e.resolvedConcreteType)&&e.resolvedConcreteType.isExtern?!0:e.requiredTraits.some(t=>oa(t.traitType))}function rn(e,t,n){if(t==="outer")return`__capture.${te(e)}`;let r=n?.get(e);return r||te(`var_${e}`)}function Cc(e,t,n,r,i,o,a,s){let l=s.emitter,c=Dt(o).isFuture.outputType,_=pe(c);s.asyncCondBranchInfo=new Map,s.asyncWhileLoopInfo=new Map,s.asyncNextWhileLoopIndex=i.awaitPoints.length;let p=ll(e,i.awaitPoints),f=e.tag==="FnCall"&&E(e,"begin")?e.args:[e],m=f.length>0?f[f.length-1]:void 0;l.emitLine(`// Resume function for async block ${t}`),l.emitLine(`void ${r}(${n}* sm) {`),l.emitLine(` ASYNC_DEBUG("${t}_resume: state=%d\\n", sm->state);`),l.emitLine(" switch (sm->state) {");let g=[];for(let h=0;h<p.length;h++){let d=p[h];if(!d)continue;let v=d.stateNumber,T=h===p.length-1;if(l.emitLine(`
193
+ state_${v}:`),l.emitLine(` case ${v}: { // State ${v}`),l.emitLine(` ASYNC_DEBUG("${t}: Entering state ${v}\\n");`),v>0&&i.awaitPoints[v-1]){let V=i.awaitPoints[v-1],U=_l(V,i);V.isInsideCond&&l.emitLine(` if (sm->${U} != NULL) {`);let re=pe(V.resultType)||x(V.resultType)&&!V.resultType.resolvedConcreteType;if(l.emitLine(" // Check if the awaited Future was aborted"),l.emitLine(` if (sm->${U}->state == -2) {`),l.emitLine(` __yo_decr_rc((void*)sm->${U});`),l.emitLine(` sm->${U} = NULL;`),Mn({emitter:l,indent:" ",debugLabel:t}),l.emitLine(" }"),V&&!re){l.emitLine(` // Extract result from await ${v-1}`),l.emitLine(` int state_before_read = sm->${U}->state;`),l.emitLine(` ASYNC_DEBUG("${t}: Reading result from await ${v-1}, state=%d\\n", state_before_read);`);let W=!!V.isInsideCond,le;if(W?le=`sm->await_result_${v-1}`:V.targetVariableId&&(le=`sm->${rn(V.targetVariableId,"local",s.stateMachineFieldAliases)}`),le)if(Le(V.resultType)){let _e=On(V.resultType,s);_e?l.emitLine(` ${le} = ${_e}(sm->${U}->result);`):(l.emitLine(" /* Warning: No ___dup function found for result type, shallow copy may cause use-after-free */"),l.emitLine(` ${le} = sm->${U}->result;`))}else l.emitLine(` ${le} = sm->${U}->result;`);if(W&&V.targetVariableId){let _e=rn(V.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(` sm->${_e} = sm->await_result_${v-1};`)}l.emitLine("")}if(!V.futureVariableId){let W=V.expr;if(W.tag==="FnCall"){let _e=W.args[0]?.$?.type;_e&&(x(_e)||be(_e))&&(l.emitLine(` if (sm->${U} != NULL) { __yo_decr_rc((void*)sm->${U}); sm->${U} = NULL; }`),l.emitLine(""))}}let j=s;if(V){let W=j.asyncCondBranchInfo?.get(V.index);if(W&&W.branches.some(_e=>_e.hasAwait)){let _e=W.condBranchFieldIndex??V.index,ve=_e===-1;l.emitLine(" // Execute remaining code from chosen cond branch"),ve||l.emitLine(` switch (sm->cond_branch_${_e}) {`);let q=d.awaitPoint?.isInsideCond??!1;for(let Z of W.branches)if(Z.hasAwait){if(ve||l.emitLine(` case ${Z.index}: {`),l.emitLine(` ASYNC_DEBUG("${t}: Executing remaining code from branch ${Z.index}\\n");`),Z.remainingExprs&&Z.remainingExprs.length>0){let se=s.inAsyncStateMachine,Se=s.stateMachineVariables,fe=s.variableIdRemapping,xe=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Ke=j.asyncWhileLoopInfo?.get(V.index);s.pendingDeferredDrops=[...Z.deferredDropExpressions??[],...Ke?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let J=new Map;for(let ye of i.capturedVariables)J.set(ye.id,ye);if(a)for(let ye of a.fields)J.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=J;let Q=!1,oe=[],ue=W.targetAssignmentCode;for(let ye=0;ye<Z.remainingExprs.length;ye++){let ie=Z.remainingExprs[ye],Ne=ye===Z.remainingExprs.length-1;if(Q){oe.push(ie);continue}if(q&&un(ie)){Q=!0,cl(ie,d.awaitPoint,i," ",s);continue}let $e=M(ie," ",s);!$e||!ie.$||ut(ie.$.env.modulePath,$e)||(Ne&&ue?l.emitLine(` ${ue} = ${$e};`):l.emitLine(` ${$e};`))}if(Z.remainingExprs.length===0&&ue&&l.emitLine(` ${ue} = sm->await_result_${V.index};`),Q&&d.awaitPoint){let ye=d.awaitPoint.index;j.asyncCondBranchInfo||(j.asyncCondBranchInfo=new Map);let ie=j.asyncCondBranchInfo.get(ye);if(ie)ie.chainedBranches||(ie.chainedBranches=[]),ie.chainedBranches.push({branches:[{index:Z.index,value:Z.value,hasAwait:oe.length>0||oe.some(Ne=>un(Ne)),remainingExprs:oe,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:_e});else{let Ne={branches:[{index:Z.index,value:Z.value,hasAwait:oe.length>0||oe.some($e=>un($e)),remainingExprs:oe,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:_e};j.asyncCondBranchInfo.set(ye,Ne)}}else if(Z.deferredDropExpressions)for(let ye of Z.deferredDropExpressions){let ie=M(ye," ",s);ie&&ie.includes("sm->")&&l.emitLine(` ${ie};`)}s.inAsyncStateMachine=se,s.stateMachineVariables=Se,s.variableIdRemapping=fe,s.pendingDeferredDrops=xe}ve||(l.emitLine(" break;"),l.emitLine(" }"))}if(ve||l.emitLine(" }"),W.chainedBranches){for(let Z of W.chainedBranches)for(let se of Z.branches)if(se.hasAwait&&se.remainingExprs&&se.remainingExprs.length>0){let Se=s.inAsyncStateMachine,fe=s.stateMachineVariables,xe=s.variableIdRemapping,Ke=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let J=j.asyncWhileLoopInfo?.get(V.index);s.pendingDeferredDrops=[...se.deferredDropExpressions??[],...J?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let Q=new Map;for(let ie of i.capturedVariables)Q.set(ie.id,ie);if(a)for(let ie of a.fields)Q.set(ie.label,{id:ie.label,name:ie.label,type:ie.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Q;let oe=d.awaitPoint?.isInsideCond??!1,ue=!1,ye=[];for(let ie of se.remainingExprs){if(ue){ye.push(ie);continue}if(oe&&un(ie)){ue=!0,cl(ie,d.awaitPoint,i," ",s);continue}let Ne=M(ie," ",s);!Ne||!ie.$||ut(ie.$.env.modulePath,Ne)||l.emitLine(` ${Ne};`)}if(ue&&d.awaitPoint){let ie=d.awaitPoint.index;j.asyncCondBranchInfo||(j.asyncCondBranchInfo=new Map);let Ne=j.asyncCondBranchInfo.get(ie);Ne?(Ne.chainedBranches||(Ne.chainedBranches=[]),Ne.chainedBranches.push({branches:[{index:se.index,value:se.value,hasAwait:ye.length>0||ye.some($e=>un($e)),remainingExprs:ye,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})):j.asyncCondBranchInfo.set(ie,{branches:[{index:se.index,value:se.value,hasAwait:ye.length>0||ye.some($e=>un($e)),remainingExprs:ye,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})}else if(se.deferredDropExpressions)for(let ie of se.deferredDropExpressions){let Ne=M(ie," ",s);Ne&&Ne.includes("sm->")&&l.emitLine(` ${Ne};`)}s.inAsyncStateMachine=Se,s.stateMachineVariables=fe,s.variableIdRemapping=xe,s.pendingDeferredDrops=Ke}}if(W.targetVariableId){let Z=rn(W.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(" // Assign cond result to target variable"),l.emitLine(` sm->${Z} = sm->await_result_${V.index};`)}l.emitLine("")}V.isInsideCond&&l.emitLine(" }");let le=j.asyncWhileLoopInfo?.get(V.index);if(le){if(l.emitLine(" // Execute remaining code from while loop body and continue loop"),l.emitLine(` if (sm->while_loop_${V.index}_active) {`),le.bodyExprsAfterAwait&&le.bodyExprsAfterAwait.length>0){let fe=s.inAsyncStateMachine,xe=s.stateMachineVariables,Ke=s.variableIdRemapping,J=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...le.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let Q=new Map;for(let ie of i.capturedVariables)Q.set(ie.id,ie);if(a)for(let ie of a.fields)Q.set(ie.label,{id:ie.label,name:ie.label,type:ie.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Q;let oe=s.smWhileBreakInfo,ue=s.smWhileContinueInfo,ye=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${V.index}`,activeIndex:V.index},s.smWhileContinueInfo={label:`while_loop_${V.index}_continue`},s.smWhileBodyDrops=[...le.bodyExpr.$?.deferredDropExpressions??[]];for(let ie of le.bodyExprsAfterAwait){let Ne=M(ie," ",s);!Ne||!ie.$||ut(ie.$.env.modulePath,Ne)||l.emitLine(` ${Ne};`)}s.smWhileBreakInfo=oe,s.smWhileContinueInfo=ue,s.smWhileBodyDrops=ye,s.inAsyncStateMachine=fe,s.stateMachineVariables=xe,s.variableIdRemapping=Ke,s.pendingDeferredDrops=J}l.emitLine(` while_loop_${V.index}_continue:`);{let fe=le.bodyExpr.$?.deferredDropExpressions??[];if(fe.length>0){let xe=s.inAsyncStateMachine,Ke=s.stateMachineVariables,J=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Q=new Map;for(let oe of i.capturedVariables)Q.set(oe.id,oe);if(a)for(let oe of a.fields)Q.set(oe.label,{id:oe.label,name:oe.label,type:oe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Q;for(let oe of fe){let ue=M(oe," ",s);ue&&ue.includes("sm->")&&l.emitLine(` ${ue};`)}s.inAsyncStateMachine=xe,s.stateMachineVariables=Ke,s.variableIdRemapping=J}}if(l.emitLine(` ASYNC_DEBUG("${t}: Re-evaluating while loop condition\\n");`),le.stepExpr){let fe=s.inAsyncStateMachine,xe=s.stateMachineVariables,Ke=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let J=new Map;for(let oe of i.capturedVariables)J.set(oe.id,oe);if(a)for(let oe of a.fields)J.set(oe.label,{id:oe.label,name:oe.label,type:oe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=J;let Q=M(le.stepExpr," ",s);Q&&l.emitLine(` ${Q};`),s.inAsyncStateMachine=fe,s.stateMachineVariables=xe,s.variableIdRemapping=Ke}let _e=s.inAsyncStateMachine,ve=s.stateMachineVariables,q=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Z=new Map;for(let fe of i.capturedVariables)Z.set(fe.id,fe);if(a)for(let fe of a.fields)Z.set(fe.label,{id:fe.label,name:fe.label,type:fe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=Z;let se=M(le.conditionExpr," ",s);s.inAsyncStateMachine=_e,s.stateMachineVariables=ve,s.variableIdRemapping=q,l.emitLine(` if (!(${se})) {`),l.emitLine(` sm->while_loop_${V.index}_active = false;`),l.emitLine(` ASYNC_DEBUG("${t}: While loop condition false, exiting loop\\n");`),l.emitLine(" } else {"),l.emitLine(` ASYNC_DEBUG("${t}: While loop condition true, continuing iteration\\n");`);let Se=V.index;if(l.emitLine(" // Loop back by transitioning to while loop state"),l.emitLine(` sm->state = ${Se};`),l.emitLine(` goto while_loop_${Se}_start;`),l.emitLine(" }"),l.emitLine(" }"),l.emitLine(""),l.emitLine(` after_while_loop_${V.index}:`),le.condBranchPostWhileExprs){let fe=le.condBranchPostWhileExprs,xe=fe.condBranchFieldIndex,Ke=fe.branchIndex;fe.skipCondBranchCheck?(l.emitLine(" // Execute post-while-loop code from cond branch (unconditional)"),l.emitLine(" {")):(l.emitLine(" // Execute post-while-loop code from cond branch"),l.emitLine(` if (sm->cond_branch_${xe} == ${Ke}) {`));let J=s.inAsyncStateMachine,Q=s.stateMachineVariables,oe=s.variableIdRemapping,ue=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let ye=new Map;for(let Xe of i.capturedVariables)ye.set(Xe.id,Xe);if(a)for(let Xe of a.fields)ye.set(Xe.label,{id:Xe.label,name:Xe.label,type:Xe.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ye;let ie=d.awaitPoint!=null,Ne=!1,$e=[];for(let Xe=0;Xe<fe.exprs.length;Xe++){let _t=fe.exprs[Xe];if(Ne){$e.push(_t);continue}if(ie&&un(_t)){Ne=!0,cl(_t,d.awaitPoint,i," ",s);continue}let Ye=M(_t," ",s);!Ye||!_t.$||ut(_t.$.env.modulePath,Ye)||l.emitLine(` ${Ye};`)}if(Ne&&d.awaitPoint){let Xe=d.awaitPoint.index;j.asyncCondBranchInfo||(j.asyncCondBranchInfo=new Map);let _t=fe.skipCondBranchCheck?-1:fe.condBranchFieldIndex,Ye=j.asyncCondBranchInfo.get(Xe);Ye?(Ye.chainedBranches||(Ye.chainedBranches=[]),Ye.chainedBranches.push({branches:[{index:fe.branchIndex,value:fe.exprs[0],hasAwait:$e.length>0||$e.some(Gt=>un(Gt)),remainingExprs:$e,deferredDropExpressions:fe.deferredDropExpressions}],condBranchFieldIndex:_t})):j.asyncCondBranchInfo.set(Xe,{branches:[{index:fe.branchIndex,value:fe.exprs[0],hasAwait:$e.length>0||$e.some(Gt=>un(Gt)),remainingExprs:$e,deferredDropExpressions:fe.deferredDropExpressions}],condBranchFieldIndex:_t})}if(!Ne&&fe.deferredDropExpressions)for(let Xe of fe.deferredDropExpressions){let _t=M(Xe," ",s);_t&&_t.includes("sm->")&&l.emitLine(` ${_t};`)}l.emitLine(" }"),s.inAsyncStateMachine=J,s.stateMachineVariables=Q,s.variableIdRemapping=oe,s.pendingDeferredDrops=ue}if(le.outerWhileLoop){let fe=le.outerWhileLoop,xe=fe.whileLoopIndex;if(l.emitLine(" // Execute remaining code from outer while loop body"),l.emitLine(` if (sm->while_loop_${xe}_active) {`),fe.bodyExprsAfterAwait.length>0){let Ke=s.inAsyncStateMachine,J=s.stateMachineVariables,Q=s.variableIdRemapping,oe=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...fe.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let ue=new Map;for(let $e of i.capturedVariables)ue.set($e.id,$e);if(a)for(let $e of a.fields)ue.set($e.label,{id:$e.label,name:$e.label,type:$e.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ue;let ye=s.smWhileBreakInfo,ie=s.smWhileContinueInfo,Ne=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${xe}`,activeIndex:xe},s.smWhileContinueInfo={label:`while_loop_${xe}_continue`},s.smWhileBodyDrops=[...fe.bodyExpr.$?.deferredDropExpressions??[]];for(let $e of fe.bodyExprsAfterAwait){let Xe=M($e," ",s);!Xe||!$e.$||ut($e.$.env.modulePath,Xe)||l.emitLine(` ${Xe};`)}s.smWhileBreakInfo=ye,s.smWhileContinueInfo=ie,s.smWhileBodyDrops=Ne,s.inAsyncStateMachine=Ke,s.stateMachineVariables=J,s.variableIdRemapping=Q,s.pendingDeferredDrops=oe}l.emitLine(` while_loop_${xe}_continue:`);{let Ke=fe.bodyExpr.$?.deferredDropExpressions??[];if(Ke.length>0){let J=s.inAsyncStateMachine,Q=s.stateMachineVariables,oe=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let ue=new Map;for(let ye of i.capturedVariables)ue.set(ye.id,ye);if(a)for(let ye of a.fields)ue.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ue;for(let ye of Ke){let ie=M(ye," ",s);ie&&ie.includes("sm->")&&l.emitLine(` ${ie};`)}s.inAsyncStateMachine=J,s.stateMachineVariables=Q,s.variableIdRemapping=oe}}if(fe.stepExpr){let Ke=s.inAsyncStateMachine,J=s.stateMachineVariables,Q=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let oe=new Map;for(let ye of i.capturedVariables)oe.set(ye.id,ye);if(a)for(let ye of a.fields)oe.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=oe;let ue=M(fe.stepExpr," ",s);ue&&l.emitLine(` ${ue};`),s.inAsyncStateMachine=Ke,s.stateMachineVariables=J,s.variableIdRemapping=Q}{let Ke=s.inAsyncStateMachine,J=s.stateMachineVariables,Q=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let oe=new Map;for(let ye of i.capturedVariables)oe.set(ye.id,ye);if(a)for(let ye of a.fields)oe.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=oe;let ue=M(fe.conditionExpr," ",s);s.inAsyncStateMachine=Ke,s.stateMachineVariables=J,s.variableIdRemapping=Q,l.emitLine(` if (!(${ue})) {`),l.emitLine(` sm->while_loop_${xe}_active = false;`),l.emitLine(" } else {"),l.emitLine(` sm->state = ${V.index};`),l.emitLine(` goto while_loop_${xe}_start;`),l.emitLine(" }")}l.emitLine(" }"),l.emitLine(""),l.emitLine(` after_while_loop_${xe}:`)}}}}let $=s.inAsyncStateMachine,C=s.stateMachineVariables,L=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let b=new Map;for(let V of i.capturedVariables)b.set(V.id,V);if(a)for(let V of a.fields)b.set(V.label,{id:V.label,name:V.label,type:V.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=b;let R=s.pendingDeferredDrops;s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let N=T&&!_&&d.expressions.length>0,B=d.expressions.length>0?d.expressions[d.expressions.length-1]:void 0,D=s.asyncBodyReturnExpr;if(!_&&B&&m&&B===m&&d.awaitPoint?s.asyncBodyReturnExpr=B:s.asyncBodyReturnExpr=void 0,Tc(d," ",s,N),s.asyncBodyReturnExpr=D,s.pendingDeferredDrops=R,l.emitLine(""),d.awaitPoint){s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L;let V=v+1;{let U=_l(d.awaitPoint,i),j=d.awaitPoint.expr.args?.[0],W=jo(j?.$?.type),le=d.awaitPoint?.isInsideCond;le&&(l.emitLine(" // Only await if the cond branch with await was taken"),l.emitLine(` if (sm->${U} != NULL) {`));let _e=d.awaitPoint?.isInsideWhile,ve=_e?s.asyncWhileLoopInfo?.get(d.awaitPoint.index):void 0;if(_e&&ve){let q=d.awaitPoint.index;l.emitLine(" // Only await if while loop is still active (not broken)"),l.emitLine(` if (sm->while_loop_${q}_active) {`)}if(l.emitLine(" // Transition to next state after await"),l.emitLine(` sm->state = ${V};`),l.emitLine(""),l.emitLine(" // Check if future is ready"),l.emitLine(` int future_state = sm->${U}->state;`),l.emitLine(" if (future_state == -1 || future_state == -2) { // -1 = completed, -2 = aborted"),l.emitLine(" // Already complete or aborted \u2014 yield once for fairness"),l.emitLine(" // Yield once to event loop for fairness (microtask yield)"),l.emitLine(` __yo_async_spawn_task((void (*)(void*))${r}, (void*)sm);`),l.emitLine(" return;"),l.emitLine(" }"),l.emitLine(""),W?l.emitLine(" // IO future: no extra ref needed (completion handler does not decr_rc)"):(l.emitLine(" // Future not complete \u2014 take event loop reference and start if cold"),l.emitLine(` __yo_incr_rc((void*)sm->${U}); // event loop reference`)),W||(l.emitLine(" if (future_state == 0) { // 0 = cold (not started)"),Ny(d.awaitPoint.expr,`sm->${U}`," ",s),l.emitLine(" // Cold future \u2014 start it via stored resume function pointer"),l.emitLine(` sm->${U}->__yo_resume_fn((void*)sm->${U});`),l.emitLine(""),l.emitLine(" // Re-check: may have completed synchronously"),l.emitLine(` future_state = sm->${U}->state;`),l.emitLine(" if (future_state == -1 || future_state == -2) {"),l.emitLine(" // Completed or aborted synchronously \u2014 yield for fairness"),l.emitLine(` __yo_async_spawn_task((void (*)(void*))${r}, (void*)sm);`),l.emitLine(" return;"),l.emitLine(" }"),l.emitLine(" }")),l.emitLine(""),l.emitLine(" // Still pending \u2014 register continuation and suspend"),l.emitLine(` sm->${U}->continuation_fn = (void (*)(void*))${r};`),l.emitLine(` sm->${U}->continuation_sm = (void*)sm;`),l.emitLine(" return;"),_e&&ve){let q=d.awaitPoint.index;l.emitLine(" } else {"),l.emitLine(" // While loop was broken, jump to code after loop"),l.emitLine(` goto after_while_loop_${q};`),l.emitLine(" }")}le&&(l.emitLine(" } else {"),l.emitLine(" // Non-await cond branch was taken, skip directly to next state"),l.emitLine(` sm->state = ${V};`),l.emitLine(` goto state_${V};`),l.emitLine(" }"))}}else if(T){if(!d.expressions.some(U=>bc(U))){if(e.$?.deferredDropExpressions){let U=new Ci,re=s.emitter;s.emitter=U;for(let W of e.$.deferredDropExpressions){let le=M(W,"",s);le&&U.emitLine(`${le};`)}s.emitter=re;let j=U.print().trim();if(j){l.emitLine(" // Drop local variables before completion");for(let W of j.split(`
194
+ `)){let le=W.trim();le&&(l.emitLine(` ${le}`),g.push(le))}l.emitLine("")}}l.emitLine(" // Final state - complete the Future"),Ar({emitter:l,indent:" ",debugLabel:"Future %p completed"})}s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L}else s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L;l.emitLine(" }")}return l.emitLine(" }"),l.emitLine("}"),l.emitLine(""),g}function cl(e,t,n,r,i){let o=i.emitter,a=_l(t,n);if(e.tag==="FnCall"&&E(e,":=")){let s=e.args[1];if(s&&s.tag==="FnCall"&&pn(s)){let l=s.args[0];if(l){let u=M(l,r,i);o.emitLine(`${r}// Store Future for additional await in cond branch`),o.emitLine(`${r}sm->${a} = ${u};`)}}return}if(e.tag==="FnCall"&&pn(e)){let s=e.args[0];if(s){let l=M(s,r,i);o.emitLine(`${r}// Store Future for additional await in cond branch`),o.emitLine(`${r}sm->${a} = ${l};`)}return}if(e.tag==="FnCall"&&E(e,I.cond)){to(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,I.match)){to(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,I.while)){to(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,I.begin)){to(e,t,0,r,i);return}o.emitLine(`${r}// Warning: unhandled await pattern in remaining expressions`)}function bc(e){if(dt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(bc(t))return!0}return!1}function Sy(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function Ny(e,t,n,r){let i=e.args?.[0];if(!i?.$?.type)return;let o=Dt(i.$.type);if(!o?.isFuture.effects?.length)return;let a=Sy(o.isFuture.effects),s=r.emitter,l=e.args?.find(u=>F(u)&&E(u,I.using));if(l){let u=l.args;for(let c=0;c<a.length&&c<u.length;c++){let _=a[c],p=u[c];if(G(_.type)){if(_.type.forallParameters.length>0)continue;let f=M(p,n,r),m=_.label;s.emitLine(`${n}${t}->__capture.${m} = (void*)${f};`)}else Te(_.type)&&$c(_.type,t,n,p.$?.value,r,e)}}else for(let u of a)if(G(u.type)){if(u.type.forallParameters.length>0)continue;let c=Vy(u.label,r,e);c&&s.emitLine(`${n}${t}->__capture.${u.label} = (void*)${c};`)}else Te(u.type)&&$c(u.type,t,n,void 0,r,e)}function $c(e,t,n,r,i,o){let a=i.emitter;for(let s of e.fields){if(!G(s.type))continue;let l;if(i.stateMachineVariables){for(let[,u]of i.stateMachineVariables)if(u.name===s.label&&u.kind==="outer"){l=`sm->__capture.${s.label}`;break}}if(!l&&r&&We(r)){let u=e.fields.indexOf(s),c=r.fields[u];if(c&&ne(c)){let _=i.functions[c.funcId];_&&(l=_.cName)}}if(!l&&i.currentEvidenceParams){for(let u of i.currentEvidenceParams.values())if(u.fieldLabel===s.label){l=u.cParamName;break}}if(!l){let u=o.$?.env??o.func.$?.env;if(u){let c=fn(u,_=>_.isImplicit===!0);for(let _=c.length-1;_>=0;_--){let p=c[_],f=p.value?.[p.value.length-1];if(f&&We(f)){let m=f.type.fields.findIndex(g=>g.label===s.label);if(m>=0){let g=f.fields[m];if(g&&ne(g)){let h=i.functions[g.funcId]?.cName;if(h){l=h;break}}}}}}}l&&a.emitLine(`${n}${t}->__capture.${s.label} = (void*)${l};`)}}function Vy(e,t,n){if(t.currentEvidenceParams){for(let r of t.currentEvidenceParams.values())if(r.fieldLabel===e)return r.cParamName}if(t.stateMachineVariables){for(let[,r]of t.stateMachineVariables)if(r.name===e&&r.kind==="outer")return`sm->__capture.${e}`}}var xy=new Set(["__yo_mutex_init","__yo_mutex_destroy","__yo_mutex_lock","__yo_mutex_unlock","__yo_cond_init","__yo_cond_destroy","__yo_cond_wait","__yo_cond_signal","__yo_cond_broadcast","__yo_thread_join","__yo_thread_self"]);function kc(e){let t=e.emitter;t.emitDeclarationLine("// Function declarations"),t.emitDeclarationLine("/// Extern functions");for(let n in e.externFunctions){let{cName:r,type:i}=e.externFunctions[n];if(i.isExtern==="yo"){if(xy.has(r))continue;pl(i,r,!0,e);continue}i.isExtern==="c"&&i.cInclude||r.startsWith("__atomic_")||r.startsWith("__sync_")||pl(i,r,!0,e)}t.emitDeclarationLine(""),e.usesAsync&&(t.emitDeclarationLine("/// Async runtime functions"),t.emitDeclarationLine("static void __yo_async_spawn_task(void (*resume_fn)(void*), void* state_machine);"),t.emitDeclarationLine("")),t.emitDeclarationLine("/// Object constructors"),My(e),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Closure constructors"),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Capture dispose functions"),Oy(e),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Dyn type constructors"),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Regular functions");for(let n in e.functions){let{cName:r,value:i}=e.functions[n],o=r==="__yo_user_main",a=i.body?.$?.effectAnalysis,s=a&&a.hasEffects;if(!o&&!i.type.isClosure&&i.specializedFunctionCaches?.length>0||!o&&!s&&!i.isModuleEffectMember&&!i.type.isClosure&&!i.specializedType&&(i.specializedFunctionCaches?.length??0)===0&&$t(i.specializedType??i.type).length===0&&[...i.type.implicitParameters,...i.type.parameters.filter(g=>g.isImplicit)].some(g=>G(g.type)))continue;let u=i.specializedType??i.type,c=$t(u).length>0;if(!o&&i.isIoAsyncStateMachineClosure||!o&&!s&&!c&&!i.isModuleEffectMember&&(sr(i.type)&&!i.type.isClosure||i.specializedFunctionCaches?.length>0&&!i.type.isClosure||Wr(i)||Ki(i)||i.isIoAsyncStateMachineClosure))continue;let _=i.specializedType??i.type,p=!s&&!i.isModuleEffectMember&&(_.parameters.some(g=>Fe(g.type))||_.forallParameters.length>0),f=Fe(_.return.type),m=x(_.return.type)&&_.return.type.requiredTraits.length>0;p||f&&!m&&!i.isModuleEffectMember||pl(_,r,!1,e,i.isModuleEffectMember?void 0:i.body,i.specializedType&&$t(_).length===0&&$t(i.type).some(g=>g.fieldFunctionType.forallParameters&&g.fieldFunctionType.forallParameters.length>0)?i.type:void 0)}t.emitDeclarationLine("/// Closure vtable instances"),t.emitDeclarationLine("")}function $t(e){let t=[],n=Dy(e.implicitParameters);for(let r of n)Te(r.type)?wc(r.label,r.type,[],t):G(r.type)&&t.push({implicitLabel:r.label,fieldLabel:r.label,fieldPath:[r.label],fieldFunctionType:r.type,cParamName:te(r.label)});return t}function wc(e,t,n,r){for(let i of t.fields)if(G(i.type)){let o=[...n,i.label],a=o.join("__");r.push({implicitLabel:e,fieldLabel:a,fieldPath:o,fieldFunctionType:i.type,cParamName:te(`${e}__${a}`)})}else Te(i.type)&&wc(e,i.type,[...n,i.label],r)}function Dy(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function hr(e,t,n,r,i){let o=r||P(e.return.type,n),a=e.parameters.filter(_=>!_.isCompileTimeOnly),s=[];e.isClosure&&s.push("void* closure_context");let l=a.map((_,p)=>{let f=te(_.label||`param${p}`);if(G(_.type))return hr(_.type,"(*)",n).replace(" (*)(",` (*${f})(`);{let m;return x(_.type)&&Ce(_.type)?_.type.resolvedConcreteType?m=P(_.type.resolvedConcreteType,n)+"*":m=P(_.type,n):m=P(_.type,n),`${m} ${f}`}});s.push(...l);let u=$t(i??e);for(let _ of u)if(_.fieldFunctionType.forallParameters&&_.fieldFunctionType.forallParameters.length>0)s.push(`void* ${_.cParamName}`);else{let p=hr(_.fieldFunctionType,"(*)",n).replace(" (*)(",` (*${_.cParamName})(`);s.push(p)}let c=s.join(", ");return`${o} ${t}(${c})`}function pl(e,t,n,r,i,o){let a;if(i&&Ce(e.return.type)){let c=qo(i);c?.$?.asyncStateMachineStructName?a=`${c.$.asyncStateMachineStructName}*`:i.$?.type&&x(i.$.type)&&Ce(i.$.type)&&(a=P(i.$.type,r))}if(i&&x(e.return.type)&&!Ce(e.return.type)&&i.$?.type&&(a=P(i.$.type,r)),!a&&i&&i.$?.type&&!Ce(e.return.type)){let c=P(e.return.type,r),_=P(i.$.type,r);c!==_&&(a=_)}let s=a?hr(e,t,r,a,o):hr(e,t,r,void 0,o),l=A(e),u=n?"extern ":"static ";r.emitter.emitDeclarationLine(`${u}${s}; // ${l}`)}function My(e){let t=e.emitter;t.emitDeclarationLine("static void __yo_decr_rc(void* ptr); // Decrement reference count"),t.emitDeclarationLine("static void* __yo_incr_rc(void* ptr); // Increment reference count"),t.emitDeclarationLine("static void __yo_gc_register(void* ptr); // Register object for cycle detection"),t.emitDeclarationLine("static void __yo_gc_unregister(void* ptr); // Unregister object from cycle detection"),t.emitDeclarationLine("static void __yo_gc_collect(); // Trigger garbage collection"),t.emitDeclarationLine("static void __yo_gc_init_thread(); // Initialize thread-local GC state (for worker threads)"),t.emitDeclarationLine("static void __yo_cleanup_thread_gc(); // Clean up thread-local GC state"),t.emitDeclarationLine("static void __yo_init_process_cleanup(void); // Initialize process cleanup");for(let n in e.types){let{type:r,cName:i}=e.types[n];if(ce(r)&&r.isReferenceSemantics){if(r.fields.some(l=>Fe(l.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(l=>{let u=P(l.type,e),c=te(l.label);return`${u} ${c}`}).join(", ");t.emitDeclarationLine(`static ${i}* ${a}(${s}); // Constructor`)}}}function Oy(e){let t=e.emitter;if(e.closureCaptureMap&&e.closureCaptureMap.size>0)for(let[n]of e.closureCaptureMap){let r=`__yo_dispose_closure_${n}`;t.emitDeclarationLine(`static void ${r}(void* closure_ptr);`)}}function Fc(e){let t=new Set;for(let n in e.functions){let{value:r,cName:i}=e.functions[n],o=r.specializedType;if(Wr(r)||!o||!Pn(r.type)||Pn(o))continue;let a=o.parameters.some(u=>Fe(u.type)),s=Fe(o.return.type);a||s||$t(r.type).some(u=>u.fieldFunctionType.forallParameters&&u.fieldFunctionType.forallParameters.length>0)||t.has(n)||(t.add(n),e.emitter.emitDeclarationLine(`static ${hr(o,i,e)}; // specialized function: ${A(r.type)}`))}}function vr(e,t,n){let r=X(t,e);return r.length===0?!1:r[r.length-1].frameLevel<=n}function Lc(e){return!!(e.$?.closureFunctionValue&&e.$?.type&&Wt(e.$.type))}function Ry(e,t,n,r,i,o=!1){let a=Object.values(i.types).find(f=>f.type===e);if(!a)return i.emitter.emitLine(`${r}/* Error: Capture type not found for closure */`),null;let s=a.cName,l=new Map;if(n.$?.deferredDupExpressions)for(let f of n.$.deferredDupExpressions){let m=Ra(f);m&&l.set(m,f)}let u=e.fields.map(f=>{if(f.isEffectParam)return"NULL";let m,g=f.exprs.expr;if(g.$?.deferredDupExpressions?.length&&(m=g.$.deferredDupExpressions[0]),!m){let d=[f.label];z(g)&&d.push(g.token.value);for(let v of d){let T=l.get(v);if(T){m=T;break}}}if(m)return M(m,r,i);let h={tag:"Atom",token:g.token,$:g.$};return M(h,r,i)}),c=`(${s}){ ${u.map((f,m)=>{let g=e.fields[m];return g?`.${g.label} = ${f}`:`/* Error: missing field at index ${m} */`}).join(", ")} }`,_=n.token.position.row!==void 0?`${Date.now()}_${n.token.position.row}`:`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=`__capture_${t}_${_}`;return o?i.emitter.emitLine(`${r}${s} ${p} = ${c};`):(i.emitter.emitLine(`${r}${s}* ${p} = (${s}*)__yo_malloc(sizeof(${s}));`),i.emitter.emitLine(`${r}*${p} = ${c};`)),{captureTempVar:p,captureCName:s}}function Ac(e,t,n){if(!e.$||!e.$.type||!e.$.closureFunctionValue)return"// Error: Missing closure metadata";let r=nn(e.$.type),i=r.isFn.callType,o=e.$.closureFunctionValue,a=e.$.captureType,s=n.functions[o.funcId]?.cName;if(!s)return"// Error: Closure implementation function not found in context";let l=be(e.$.type),u;if(l){let m=n.types[e.$.type.id];if(!m)return"// Error: Dyn closure type not found in context";u=m.cName}let c=a&&ce(a)&&a.fields.length>0,_=P(i.return.type,n),p=i.parameters.map(m=>P(m.type,n)).join(", "),f=`(${_} (*)(void*${p?", "+p:""}))${s}`;if(c&&a&&ce(a)){let m=!l,g=Ry(a,i.id,e,t,n,m);if(!g)return"// Error: Failed to allocate closure capture";let{captureTempVar:h}=g;if(l){let d=`__yo_create_${u}`,v=`__yo_dispose_${u}`;return`${d}(${h}, ${v}, ${f})`}else return n.implClosureCallMap.set(a.id,{functionCName:s,callTypeId:r.isFn.callType.id,callType:r.isFn.callType}),h}else if(l){let m=`__yo_create_${u}`,g=`__yo_dispose_${u}`;return`${m}(NULL, ${g}, ${f})`}else{if(e.$.type.tag==="SomeType"){let m=e.$.type;if(m.resolvedConcreteType)return n.implClosureCallMap.set(m.resolvedConcreteType.id,{functionCName:s,callTypeId:r.isFn.callType.id,callType:r.isFn.callType}),`(${P(m.resolvedConcreteType,n)}){}`}return"// Error: Impl(Fn(...)) without captures missing resolvedConcreteType"}}function fl(e,t,n){if(e.pendingDeferredDrops&&e.loopBodyDropsBaselineCount!==void 0){let r=e.loopBodyDropsBaselineCount,i=e.pendingDeferredDrops.length,o=e.pendingDeferredDrops.slice(0,i-r);for(let a of o){let s=M(a,t,n);s&&n.emitter.emitLine(`${t}${s};`)}}}function no(e,t,n=""){let r=t;if(e.token.value==="continue"){if(r.currentContinueLabel)return fl(r,n,t),`goto ${r.currentContinueLabel}`;if(r.currentLoopLabel)return fl(r,n,t),"continue";if(r.smWhileContinueInfo){if(r.smWhileContinueInfo.emitDropsBeforeGoto&&r.smWhileBodyDrops&&r.smWhileBodyDrops.length>0){let a=t.emitter;for(let s of r.smWhileBodyDrops){let l=M(s,n,t);l&&l.includes("sm->")&&a.emitLine(`${n}${l};`)}}if(r.smWhileContinueInfo.stepExpr){let a=t.emitter,s=M(r.smWhileContinueInfo.stepExpr,n,t);s&&a.emitLine(`${n}${s};`)}return`goto ${r.smWhileContinueInfo.label}`}return"continue"}if(e.token.value==="break"){if(r.currentLoopLabel)return fl(r,n,t),r.insideMatch?`goto ${r.currentLoopLabel}`:"break";if(r.smWhileBreakInfo){let{label:a,activeIndex:s}=r.smWhileBreakInfo;if(r.smWhileBodyDrops&&r.smWhileBodyDrops.length>0){let l=t.emitter;for(let u of r.smWhileBodyDrops){let c=M(u,n,t);c&&c.includes("sm->")&&l.emitLine(`${n}${c};`)}}return s!==void 0?(t.emitter.emitLine(`${n}sm->while_loop_${s}_active = false;`),`goto ${a}`):`goto ${a}`}return"break"}if(e.token.value==="return"){if(r.inAsyncStateMachine){let a=t.emitter,s=r.inAsyncStateMachine.futureType,u=Dt(s).isFuture.outputType,c=pe(u);if(e.$?.deferredDropExpressions)for(let p of e.$.deferredDropExpressions){let f=M(p,n,t);f&&f.includes("sm->")&&a.emitLine(`${n}${f};`)}if(r.pendingDeferredDrops&&r.pendingDeferredDrops.length>0){a.emitLine(`${n}// Drop local variables before early completion`);for(let p of r.pendingDeferredDrops){let f=M(p,n,t);f&&f.includes("sm->")&&a.emitLine(`${n}${f};`)}}a.emitLine(`${n}// Early return - complete the result Future`);let _=c?void 0:`(${P(u,t)}){0}`;return Ar({emitter:a,indent:n,resultCode:_,debugLabel:t.currentFunctionName}),""}return"return"}if(e.$?.type&&pe(e.$.type))return"";if((r.inAsyncStateMachine||r.inEffectStateMachine)&&r.stateMachineVariables){let a=e.token.value;if(r.localShadowedVariables?.has(a))return te(a);let s=!1;if(e.$?.env){let l=X(e.$.env,a);if(l.length>0){let u=l[l.length-1],c=u.isOwningTheSameRcValueAs?u.isOwningTheSameRcValueAs.id:u.id;r.variableIdRemapping?.has(c)&&(c=r.variableIdRemapping.get(c));let _=r.stateMachineVariables.get(c);if(_){let p=r.stateMachineFieldAliases?.get(c);if(p)return s=!0,`sm->${p}`;let f=_.kind==="outer"?`__capture.${a}`:`var_${_.id}`;return s=!0,`sm->${f}`}}}if(!s){for(let[l,u]of r.stateMachineVariables)if(u.name===a){let c=r.stateMachineFieldAliases?.get(l);if(c)return s=!0,`sm->${c}`;let _=u.kind==="outer"?`__capture.${a}`:`var_${l}`;return s=!0,`sm->${_}`}}if(e.$?.env){let l=X(e.$.env,a);if(l.length>0){let u=l[l.length-1];if(u.isOwningTheSameRcValueAs){let c=u.isOwningTheSameRcValueAs.name,_=u.isOwningTheSameRcValueAs.id;for(let[p,f]of r.stateMachineVariables)if(f.name===c||p===_)return`sm->${f.kind==="outer"?`__capture.${c}`:`var_${p}`}`}}}if(r.currentClosureCaptures&&r.currentClosureCaptures.includes(a)&&r.currentClosureCaptureFrameLevel!==void 0){let l=r.currentClosureCaptureTypeCName;return l?`((${l}*)closure_context)->${Ee(a,e.$?.env)}`:`closure_context->${Ee(a,e.$?.env)}`}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!de(e.$.value)){let l=X(e.$.env,e.$.variableName);if(l.length>0&&l[l.length-1].isCompileTimeOnly)return Qt(e.$.value,t,e)}return Ee(e.$.variableName,e.$.env)}}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!de(e.$.value)){let a=X(e.$.env,e.$.variableName);if(a.length>0&&a[a.length-1].isCompileTimeOnly)return Qt(e.$.value,t,e)}if(!(r.currentClosureCaptures&&r.currentClosureCaptures.includes(e.token.value)&&e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0&&vr(e.token.value,e.$.env,r.currentClosureCaptureFrameLevel)))return Ee(e.$.variableName,e.$?.env)}if(e.$?.value&&!de(e.$.value))return Qt(e.$.value,t,e);let i=e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0?vr(e.token.value,e.$.env,r.currentClosureCaptureFrameLevel):!1;if(r.currentClosureCaptures&&r.currentClosureCaptures.includes(e.token.value)&&r.currentClosureCaptureFrameLevel!==void 0&&(!e.$?.env||i)){let a=r.currentClosureCaptureTypeCName;return a?`((${a}*)closure_context)->${Ee(e.token.value,e.$?.env)}`:`closure_context->${Ee(e.token.value,e.$?.env)}`}if(r.currentFunctionName&&!r.currentClosureCaptures){let a=Object.values(r.functions).find(s=>s.cName===r.currentFunctionName);if(a&&a.value.type.isClosure){let s=Object.values(r.types).find(l=>G(l.type)&&l.type.isClosure&&l.type===a.value.type);if(s)return`((${`${s.cName}_capture`}*)closure_context->data)->${Ee(e.token.value,e.$?.env)}`}}if(e.$?.env){let a=X(e.$.env,e.token.value);if(a.length>0){let s=a[a.length-1];if(s.value?.[0]&&ne(s.value[0])){let l=t.functions[s.value[0].funcId]?.cName;if(l)return l}else if(G(s.type)&&(de(s.value?.[0])||s.value===void 0)){let l=Object.entries(t.functions).find(([u,c])=>c.value.funcName===e.token.value);if(l)return l[1].cName}}}return Ee(e.token.value,e.$?.env)}function Ic(e,t,n){let r;if(Rt(e)){let d=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;d&&ne(d)&&(r=d.body)}else r=e.args[0];if(!r)return"/* Error: async requires exactly 1 argument */";let i=e.$?.type;if(!i||!Ce(i))return"/* Error: async block must have Future type */";let o=Dt(i);if(!o)return"/* Error: Could not extract Future module type */";let a=e.$?.variableName||`async_block_${Date.now()}`,s=`${a}_state_t`,l=`${a}_resume`,u=`__yo_new_${a}`,c=`${a}_state_dispose`;n.types[i.id]={type:i,cName:s};let _=e.$?.awaitAnalysis;if(!_)throw new Error("Missing await analysis for async block. This should have been computed during evaluation.");let p=o.isFuture.outputType;if(x(p))if(p.resolvedConcreteType)p=p.resolvedConcreteType;else{let d=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(d&&ne(d)){let v=d.type?.return?.type;if(v&&x(v)&&v.resolvedConcreteType)p=v.resolvedConcreteType;else if(d.body?.$?.type){let T=d.body.$.type;x(T)&&T.resolvedConcreteType?p=T.resolvedConcreteType:x(T)||(p=T)}}}let f=P(p,n),m=n.emitter;if(m.emitDeclarationLine(`void ${c}(void* sm_ptr); // Dispose function for state machine`),m.emitDeclarationLine(""),m.emitDeclarationLine(`void ${l}(${s}* sm);`),m.emitDeclarationLine(""),e.$?.captureType){let h=e.$.captureType,d=Object.values(n.types).find(T=>T.type===h),v=d?d.cName:`async_capture_${h.id}`;m.emitDeclarationLine(`${s}* ${u}(${v} __capture);`)}else m.emitDeclarationLine(`${s}* ${u}();`);m.emitDeclarationLine(""),n.deferredAsyncBlocks||(n.deferredAsyncBlocks=[]),n.deferredAsyncBlocks.push({bodyExpr:r,asyncBlockId:a,structName:s,resumeFunctionName:l,constructorName:u,disposeFunctionName:c,futureType:i,futureModuleType:o,resultType:p,resultTypeCName:f,captureType:e.$?.captureType,analysis:_});let g=e.$?.captureType;if(g){let h=Object.values(n.types).find(N=>N.type===g),d=h?h.cName:`async_capture_${g.id}`,v=n,T=v.currentClosureCaptures!==void 0||v.inAsyncStateMachine!==void 0||v.inEffectStateMachine!==void 0,$=!1,C=g.fields.map(N=>{if(N.isEffectParam)return`.${N.label} = NULL`;let B;if(!T&&e.$?.deferredDupExpressions)for(let V of e.$.deferredDupExpressions){let U;if(F(V)&&(V.args.length>0&&z(V.args[0])?U=V.args[0].token.value:V.args.length===0&&F(V.func)&&E(V.func,".")&&V.func.args.length>=2&&z(V.func.args[0])&&(U=V.func.args[0].token.value)),U===N.label){B=V;break}}if(B)return $=!0,B.$?.variableName?(M(B,t,n),`.${N.label} = ${B.$.variableName}`):`.${N.label} = ${M(B,t,n)}`;let D={tag:"Atom",token:N.exprs.expr.token,$:N.exprs.expr.$};return`.${N.label} = ${no(D,n)}`}).join(", "),L=`(${d}){${C}}`;if(!$){let N=On(g,n);N&&(L=`${N}(${L})`)}let b=e.$?.variableName||"async_result",R=`${u}(${L})`;if(b&&e.$?.type){let N=st(e.$.type,b,n);return n.emitter.emitLine(`${t}${N} = ${R};`),b}else return R}else{let h=e.$?.variableName||"async_result",d=`${u}()`;if(h&&e.$?.type){let v=st(e.$.type,h,n);return n.emitter.emitLine(`${t}${v} = ${d};`),h}else return d}}function Sc(e,t){let n=t.emitter,{asyncBlockId:r,structName:i,resultType:o,resultTypeCName:a,captureType:s,analysis:l,crossBoundaryIds:u,awaitFutureTempVarAliases:c,overlappingSlotAliases:_,overlappingSlots:p}=e;if(n.emitDeclarationLine(`// State machine for async block ${r} - implements Future(${A(o)})`),n.emitDeclarationLine(`struct ${i}_struct {`),n.emitDeclarationLine(" __yo_ref_header_t header; // Reference counting header (must be first)"),n.emitDeclarationLine(" int state; // Current state (0 = cold, 1..N = intermediate, -1 = completed, -2 = aborted)"),pe(o)?n.emitDeclarationLine(" uint8_t result; // Dummy result for unit type"):n.emitDeclarationLine(` ${a} result; // The result value of type ${A(o)}`),n.emitDeclarationLine(" void (*continuation_fn)(void*); // Resume function of awaiting task"),n.emitDeclarationLine(" void* continuation_sm; // State machine of awaiting task"),n.emitDeclarationLine(""),n.emitDeclarationLine(" void (*__yo_resume_fn)(void*); // Resume function pointer (for lazy start at await/spawn)"),n.emitDeclarationLine(""),s){let h=Object.values(t.types).find(v=>v.type===s),d=h?h.cName:`async_capture_${s.id}`;n.emitDeclarationLine(" // Captured variables from outer scope"),n.emitDeclarationLine(` ${d} __capture;`),n.emitDeclarationLine("")}let f=l.capturedVariables.filter(h=>h.kind!=="outer");if(u&&(f=f.filter(h=>u.has(h.id)&&!c?.has(h.id)&&!_?.has(h.id))),f.length>0){n.emitDeclarationLine(" // Local variables");for(let h of f){let d=P(h.type,t),v=rn(h.id,"local");n.emitDeclarationLine(` ${d} ${v}; // ${h.name}`)}n.emitDeclarationLine("")}if(p&&p.length>0){n.emitDeclarationLine(" // Overlapping storage slots (Phase 2)");for(let h of p)n.emitDeclarationLine(` ${h.cType} ${h.fieldName}; // shared: ${h.variableNames.join(", ")}`);n.emitDeclarationLine("")}if(l.awaitPoints.length>0){let h=[];for(let d of l.awaitPoints)if(!(pe(d.resultType)||x(d.resultType)&&!d.resultType.resolvedConcreteType)&&d.isInsideCond){let $=d.resultType;if(d.futureType){let L=Dt(d.futureType);L&&($=L.isFuture.outputType)}let C=P($,t);h.push(` ${C} await_result_${d.index};`)}if(h.length>0){n.emitDeclarationLine(" // Await result temporaries");for(let d of h)n.emitDeclarationLine(d);n.emitDeclarationLine("")}}if(l.awaitPoints.length>0){let h=l.awaitPoints.filter(d=>d.futureVariableId===void 0);if(h.length>0){n.emitDeclarationLine(" // Future references for awaits");for(let d of h){let v=d.expr;if(v.tag!=="FnCall")continue;let $=v.args[0]?.$?.type;if(!$)throw new Error(`Internal error: await expression missing type info for future argument in async block ${r}`);let C=P($,t);n.emitDeclarationLine(` ${C} await_future_${d.index};`)}n.emitDeclarationLine("")}}let m=l.awaitPoints.filter(h=>h.needsOwnCondBranchField);if(m.length>0){n.emitDeclarationLine(" // Branch tracking for cond expressions with await");for(let h of m)n.emitDeclarationLine(` int cond_branch_${h.index}; // Which branch was taken in cond with await ${h.index}`);n.emitDeclarationLine("")}let g=l.awaitPoints.filter(h=>h.isInsideWhile);if(g.length>0){n.emitDeclarationLine(" // Loop state tracking for while loops with await");let h=l.awaitPoints.length;for(let d of g){n.emitDeclarationLine(` _Bool while_loop_${d.index}_active; // Whether while loop ${d.index} should continue`);let v=(d.whileNestingDepth??1)-1;for(let T=0;T<v;T++)n.emitDeclarationLine(` _Bool while_loop_${h}_active; // Whether outer while loop ${h} should continue`),h++}n.emitDeclarationLine("")}n.emitDeclarationLine("};"),n.emitDeclarationLine("")}function Py(e){if(!e.deferredAsyncBlocks||e.deferredAsyncBlocks.length===0)return;let t=e.deferredAsyncBlocks,n=new Map;for(let l of t)n.set(l.structName,l);let r=new Map,i=new Map;for(let l of t)r.set(l.structName,new Set),i.set(l.structName,0);for(let l of t){let u=c=>{let _=r.get(c);_.has(l.structName)||(_.add(l.structName),i.set(l.structName,(i.get(l.structName)??0)+1))};for(let c of l.analysis.capturedVariables){let _;try{_=P(c.type,e)}catch{continue}let p=n.get(_);p&&p.structName!==l.structName&&u(p.structName)}for(let c of l.analysis.awaitPoints){if(c.futureVariableId!==void 0)continue;let _=c.expr;if(_.tag!=="FnCall")continue;let f=_.args[0]?.$?.type;if(!f)continue;let m;try{m=P(f,e)}catch{continue}let g=n.get(m);g&&g.structName!==l.structName&&u(g.structName)}}let o=[];for(let[l,u]of i.entries())u===0&&o.push(l);let a=[];for(;o.length>0;){let l=o.shift();a.push(l);let u=r.get(l);if(u)for(let c of u){let _=(i.get(c)??0)-1;i.set(c,_),_===0&&o.push(c)}}let s=a.length===t.length?a.map(l=>n.get(l)).filter(Boolean):t;for(let l of s){let{crossBoundaryIds:u,awaitFutureTempVarAliases:c,variableSegments:_}=Pa(l.bodyExpr,l.analysis),{slotAliases:p,slots:f}=Ua(u,_,l.analysis.capturedVariables,c,e);Sc({asyncBlockId:l.asyncBlockId,structName:l.structName,resultType:l.resultType,resultTypeCName:l.resultTypeCName,captureType:l.captureType,analysis:l.analysis,crossBoundaryIds:u,awaitFutureTempVarAliases:c,overlappingSlotAliases:p,overlappingSlots:f},e)}}function Uy(e,t,n,r,i,o,a,s,l,u){let c=u.emitter;if(c.emitLine(`// Dispose function for async block ${e} state machine`),c.emitLine("// Called by __yo_decr_rc when refcount hits 0 - do NOT call __yo_free here"),c.emitLine(`void ${n}(void* sm_ptr) {`),c.emitLine(` ${t}* sm = (${t}*)sm_ptr;`),c.emitLine(` ASYNC_DEBUG("${n}: Disposing state machine\\n");`),c.emitLine(""),i&&Le(i)){let _=Object.values(u.types).find(p=>p.type===i);if(!_)c.emitLine(" /* Error: capture struct type not found in context */");else{let p=_.cName,f=i.trait.fields.find(m=>m.label===k.___drop[0]);if(f&&f.assignedValue&&ne(f.assignedValue)){let m=u.functions[f.assignedValue.funcId]?.cName;m&&(c.emitLine(' ASYNC_DEBUG(" Dropping capture struct\\n");'),c.emitLine(` ${m}(sm->__capture);`))}else c.emitLine(` /* Warning: ___drop function not found for capture struct ${p} */`)}}if(c.emitLine(""),!pe(r)&&Le(r)){let _=P(r,u);c.emitLine(" // Drop result field if it was set (state == -1 means completed)"),c.emitLine(" int final_state = sm->state;"),c.emitLine(" if (final_state == -1) {"),c.emitLine(' ASYNC_DEBUG(" Dropping result field\\n");');let p=gr(r,u);p?c.emitLine(` ${p}(sm->result);`):c.emitLine(` /* Warning: No ___drop function found for result type ${_} */`),c.emitLine(" }")}c.emitLine("");{let _=[];for(let p of o.capturedVariables){if(p.kind!=="local"||!s.has(p.id)||l.has(p.id)||p.isOwningTheSameRcValueAs!==void 0)continue;let m=`sm->${rn(p.id,"local")}`;if(be(p.type))_.push(` if ((${m}).data != NULL) { __yo_decr_rc((void*)(${m}).data); }`);else if(wt(p.type)||Ct(p.type))_.push(` if (${m} != NULL) { __yo_decr_rc_atomic((void*)${m}); }`);else if(pt(p.type)||x(p.type)&&sn(p.type)){let g=gr(p.type,u);g?_.push(` if (${m} != NULL) { ${g}(${m}); }`):_.push(` if (${m} != NULL) { __yo_decr_rc((void*)${m}); }`)}else if(Le(p.type)){let g=gr(p.type,u);g&&_.push(` ${g}(${m});`)}}if(_.length>0){c.emitLine(" // Drop local variables on escape (state == -2)"),c.emitLine(" if (sm->state == -2) {");for(let p of _)c.emitLine(p);c.emitLine(" }")}}c.emitLine(" // Memory freed by __yo_decr_rc after this function returns"),c.emitLine("}")}function zy(e,t,n,r,i,o,a,s,l,u){let c=u.emitter;if(l){let _=Object.values(u.types).find(f=>f.type===l),p=_?_.cName:`async_capture_${l.id}`;c.emitLine(`${t}* ${r}(${p} __capture) {`)}else c.emitLine(`${t}* ${r}() {`);c.emitLine(" // Allocate async block state machine (heap-backed, ref-counted)"),c.emitLine(` ${t}* sm = (${t}*)__yo_malloc(sizeof(${t}));`),c.emitLine(` memset(sm, 0, sizeof(${t}));`),c.emitLine(""),c.emitLine(" // Initialize reference counting header"),c.emitLine(" sm->header.ref_count = 1; // Caller owns initial reference"),c.emitLine(` GC_DEBUG("AsyncBlock ${t}: Created ptr=%p RC=1\\n", (void*)sm);`),c.emitLine(" sm->header.gc_flags = 0;"),c.emitLine(" sm->header.gc_mark = __YO_GC_UNMARKED;"),c.emitLine(" sm->header.gc_next = NULL;"),c.emitLine(" sm->header.gc_prev = NULL;"),c.emitLine(` sm->header.dispose_fn = (void(*)(void*))${i};`),c.emitLine(" sm->header.traverse_fn = NULL; // TODO: Add traverse for cycle detection if needed"),c.emitLine(""),c.emitLine(" sm->state = 0;"),c.emitLine(" sm->continuation_fn = NULL;"),c.emitLine(" sm->continuation_sm = NULL;"),c.emitLine(""),l&&(c.emitLine(" // Initialize captured variables"),c.emitLine(" sm->__capture = __capture;"),c.emitLine("")),c.emitLine(" // Initialize result (will be set when async block completes)"),pe(a)?c.emitLine(" // Result is unit type, no initialization needed"):c.emitLine(` memset(&sm->result, 0, sizeof(${s}));`),c.emitLine(""),c.emitLine(` sm->__yo_resume_fn = (void(*)(void*))${n};`),c.emitLine(""),c.emitLine(" return sm;"),c.emitLine("}"),c.emitLine("")}function Nc(e){if(!e.deferredAsyncBlocks||e.deferredAsyncBlocks.length===0)return;let t=e.emitter;Py(e),t.emitLine("// Deferred async block implementations");let n=0;for(;n<e.deferredAsyncBlocks.length;){let r=e.deferredAsyncBlocks[n],i=e.deferredAsyncBlocks.length,{bodyExpr:o,asyncBlockId:a,structName:s,resumeFunctionName:l,constructorName:u,disposeFunctionName:c,futureType:_,resultType:p,resultTypeCName:f,captureType:m,analysis:g}=r,h=e.stateMachineVariables,d=e.currentEvidenceParams,v=new Map,{crossBoundaryIds:T,awaitFutureTempVarAliases:$,variableSegments:C}=Pa(o,g),{slotAliases:L}=Ua(T,C,g.capturedVariables,$,e),b=g.capturedVariables.filter(V=>V.kind==="outer"||T.has(V.id)||$.has(V.id)||L.has(V.id)),R={...g,capturedVariables:b};for(let V of b)v.set(V.id,V);if(m)for(let V of m.fields)v.set(V.label,{id:V.label,name:V.label,type:V.type,kind:"outer",isOwningTheSameRcValueAs:void 0});e.stateMachineVariables=v;let N=e.stateMachineFieldAliases,B=new Map($);for(let[V,U]of L)B.set(V,U);e.stateMachineFieldAliases=B;let D=Cc(o,a,s,l,R,_,m,e);if(e.stateMachineVariables=h,e.currentEvidenceParams=d,e.stateMachineFieldAliases=N,t.emitLine(""),Uy(a,s,c,p,m,R,D,T,$,e),t.emitLine(""),zy(a,s,l,u,c,_,p,f,m,e),t.emitLine(""),e.deferredAsyncBlocks.length>i){let V=e.deferredAsyncBlocks.slice(i);for(let U of V){let{crossBoundaryIds:re,awaitFutureTempVarAliases:j,variableSegments:W}=Pa(U.bodyExpr,U.analysis),{slotAliases:le,slots:_e}=Ua(re,W,U.analysis.capturedVariables,j,e);Sc({asyncBlockId:U.asyncBlockId,structName:U.structName,resultType:U.resultType,resultTypeCName:U.resultTypeCName,captureType:U.captureType,analysis:U.analysis,crossBoundaryIds:re,awaitFutureTempVarAliases:j,overlappingSlotAliases:le,overlappingSlots:_e},e)}}n++}}function Vc(e){for(let t in e.functions){let{value:n}=e.functions[t];n.body&&xc(n.body,e)}}var By=["__yo_poll_","__yo_fs_event_","__yo_async_"];function Gy(e){return By.some(t=>e.startsWith(t))}function xc(e,t){if(e&&F(e)){let n=e;if(Rt(e)){t.usesAsync=!0;let r=e.$?.type;if(r&&Ce(r)&&Dt(r)){let a=`${e.$?.variableName||`async_block_${Date.now()}`}_state_t`;e.$&&(e.$.asyncStateMachineStructName=a),t.types[r.id]={type:r,cName:a},t.emitter.emitDeclarationLine(`typedef struct ${a}_struct ${a}; // Forward declaration for async state machine`)}}if(Rt(e)){let r=e.$?.type;if(r&&Ce(r)&&Dt(r)){let o=e.$?.variableName||`io_async_block_${Date.now()}`,a=!!e.$?.awaitAnalysis,s=a?`${o}_state_t`:`${o}_sync_fut_t`;e.$&&(e.$.asyncStateMachineStructName=s),t.types[r.id]={type:r,cName:s},t.emitter.emitDeclarationLine(`typedef struct ${s}_struct ${s}; // Forward declaration for io.async ${a?"state machine":"sync future"}`)}}(pn(e)||Fa(e))&&(t.usesAsync=!0);{let r=n.func.$?.type;r&&"isExtern"in r&&r.isExtern==="yo"&&"externName"in r&&typeof r.externName=="string"&&Gy(r.externName)&&(t.usesAsync=!0)}{let r=n.func.$?.type;r&&"isExtern"in r&&r.isExtern==="yo"&&"externName"in r&&typeof r.externName=="string"&&(r.externName==="__yo_thread_spawn"||r.externName==="__yo_worker_spawn")&&(t.usesParallelism=!0)}for(let r of n.args)xc(r,t)}}function Dc(e,t,n){let r=e.$?.type;if(!r||!Ce(r))return"/* Error: io.async must return a Future type */";let i=Dt(r);if(!i)return"/* Error: Could not extract Future module type */";let o=i.isFuture.outputType;if(x(o))if(o.resolvedConcreteType)o=o.resolvedConcreteType;else{let R=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(R&&ne(R)){let N=R.type?.return?.type;if(N&&x(N)&&N.resolvedConcreteType)o=N.resolvedConcreteType;else if(R.body?.$?.type){let B=R.body.$.type;x(B)&&B.resolvedConcreteType?o=B.resolvedConcreteType:x(B)||(o=B)}}}let a=P(o,n),s=e.$?.asyncStateMachineStructName;if(!s)return"/* Error: Missing sync future struct name */";let l=`${s}_dispose`,u=`${s}_resume`,c=n.emitter,_=e.$?.runtimeArgExprsInOrder?.[0];if(!_?.$)return"/* Error: Missing closure argument for io.async */";let p=M(_,t,n),f=_.$.type,m,g;if(x(f)&&f.resolvedConcreteType){let b=f.resolvedConcreteType,R=n.implClosureCallMap.get(b.id);R&&(m=R.functionCName);let N=n.types[b.id];N&&(g=N.cName)}if(!m||!g)return"/* Error: no closure function or capture type for io.async sync path */";c.emitDeclarationLine(`struct ${s}_struct {`),c.emitDeclarationLine(" __yo_ref_header_t header;"),c.emitDeclarationLine(" int state;"),pe(o)?c.emitDeclarationLine(" uint8_t result;"):c.emitDeclarationLine(` ${a} result;`),c.emitDeclarationLine(" void (*continuation_fn)(void*);"),c.emitDeclarationLine(" void* continuation_sm;"),c.emitDeclarationLine(" void (*__yo_resume_fn)(void*);"),c.emitDeclarationLine(` ${g} __capture;`),c.emitDeclarationLine("};"),c.emitDeclarationLine("");let h="";for(let b in n.functions){let R=n.functions[b];if(R.cName===m){let N=$t(R.value.type);N.length>0&&(h=", "+N.map(B=>`(void*)sm->__capture.${B.fieldPath.join(".")}`).join(", "));break}}c.emitDeclarationLine(`void ${u}(void* ptr) {`),c.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),pe(o)?c.emitDeclarationLine(` ${m}(&sm->__capture${h});`):c.emitDeclarationLine(` sm->result = ${m}(&sm->__capture${h});`),h&&(c.emitDeclarationLine(" if (__yo_effect_escaped) {"),c.emitDeclarationLine(" __yo_effect_escaped = 0;"),c.emitDeclarationLine(" sm->state = -2;"),c.emitDeclarationLine(" __yo_decr_rc(ptr);"),c.emitDeclarationLine(" return;"),c.emitDeclarationLine(" }")),c.emitDeclarationLine(" sm->state = -1;"),c.emitDeclarationLine(" void (*continuation)(void*) = sm->continuation_fn;"),c.emitDeclarationLine(" if (continuation) {"),c.emitDeclarationLine(" void* cont_sm = sm->continuation_sm;"),c.emitDeclarationLine(" continuation(cont_sm);"),c.emitDeclarationLine(" }"),c.emitDeclarationLine(" __yo_decr_rc(ptr);"),c.emitDeclarationLine("}"),c.emitDeclarationLine("");let d=_.$.captureType,v=d&&Le(d)?gr(d,n):void 0,T=d&&Le(d)?On(d,n):void 0,$=gr(o,n);c.emitDeclarationLine(`void ${l}(void* ptr) {`),(v||$)&&(c.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),v&&(c.emitDeclarationLine(" // Drop captured variables (future owns its references)"),c.emitDeclarationLine(` ${v}(sm->__capture);`)),$&&(c.emitDeclarationLine(" if (sm->state == -1) {"),c.emitDeclarationLine(` ${$}(sm->result);`),c.emitDeclarationLine(" }"))),c.emitDeclarationLine("}"),c.emitDeclarationLine("");let C=e.$?.variableName||"__io_async_result",L=st(r,C,n);return c.emitLine(`${t}${L} = (${s}*)__yo_malloc(sizeof(${s}));`),c.emitLine(`${t}memset(${C}, 0, sizeof(${s}));`),c.emitLine(`${t}${C}->header.ref_count = 1;`),c.emitLine(`${t}${C}->header.gc_flags = 0;`),c.emitLine(`${t}${C}->header.gc_mark = __YO_GC_UNMARKED;`),c.emitLine(`${t}${C}->header.gc_next = NULL;`),c.emitLine(`${t}${C}->header.gc_prev = NULL;`),c.emitLine(`${t}${C}->header.dispose_fn = (void(*)(void*))${l};`),c.emitLine(`${t}${C}->header.traverse_fn = NULL;`),c.emitLine(`${t}${C}->__capture = ${p};`),T&&c.emitLine(`${t}${C}->__capture = ${T}(${C}->__capture);`),c.emitLine(`${t}${C}->state = 0;`),c.emitLine(`${t}${C}->__yo_resume_fn = ${u};`),c.emitLine(`${t}${C}->continuation_fn = NULL;`),c.emitLine(`${t}${C}->continuation_sm = NULL;`),C}function Mc(e,t){for(let i=0;i<e.fields.length;i++){let o=e.fields[i];ne(o)&&(Sr(o.type,t),vi(o.body,t))}let n=new Set,r=!0;for(;r;){r=!1;for(let i in t.functions){if(n.has(i))continue;n.add(i),r=!0;let o=t.functions[i];if(Sr(o.value.type,t),o.value.specializedType&&Sr(o.value.specializedType,t),vi(o.value.body,t),o.value.calledComptimeFunctionCaches)for(let a of o.value.calledComptimeFunctionCaches)a.value&&a.value.type&&Mt(a.value.type,t),vi(a.body,t)}}}function Sr(e,t){for(let n of e.parameters)Mt(n.type,t);for(let n of e.forallParameters)Mt(n.type,t);Mt(e.return.type,t)}function vi(e,t){if(e.$&&e.$.type&&Mt(e.$.type,t),e.$&&e.$.value&&ne(e.$.value)){let n=e.$.value;n.isControlFunction?(Sr(n.type,t),Ht(n.body,t)):t.functions[n.funcId]||n.type.parameters.map(o=>o.type).some(o=>x(o)&&Ce(o)&&!o.resolvedConcreteType)||(t.functions[n.funcId]={value:n,cName:te(n.funcId)},Sr(n.type,t),Ht(n.body,t))}if(e.$&&e.$.deferredDropExpressions&&e.$.deferredDropExpressions.length>0)for(let n of e.$.deferredDropExpressions)vi(n,t);if(e.$&&e.$.macroExpansion&&vi(e.$.macroExpansion,t),e.$&&e.$.runtimeDestructurings)for(let{type:n}of e.$.runtimeDestructurings)Mt(n,t);if(e.$&&e.$.captureType&&ce(e.$.captureType)){let n=e.$.captureType;if(!t.types[n.id]){t.types[n.id]={type:n,cName:`__yo_${n.id}`};for(let r of n.fields)Mt(r.type,t);for(let r of n.trait.fields)if(r.assignedValue&&ne(r.assignedValue)){let i=r.assignedValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:i.funcId},Sr(i.type,t),Ht(i.body,t))}}}switch(e.tag){case"FnCall":if(E(e,I.test))break;vi(e.func,t);for(let n of e.args)vi(n,t);break;case"Atom":e.$?.value&&O(e.$.value)&&Mt(e.$.value.value,t);break}}function Mt(e,t){if(!t.types[e.id]){if(x(e)&&Wt(e)){if(e.resolvedConcreteType){Mt(e.resolvedConcreteType,t);return}let n=nn(e);n&&Mt(n,t);return}if(x(e)&&Ce(e)){let n=Dt(e);n&&Mt(n.isFuture.outputType,t);return}if(x(e)&&e.resolvedConcreteType){Mt(e.resolvedConcreteType,t);return}if(!Fe(e)){if(ce(e)||it(e)||ge(e)||we(e)||be(e)||Te(e)||De(e)||Qe(e)||wt(e)||Ct(e)){let n=Qe(e)?P(e,t):e.isExtern==="c"&&e.externName?e.externName:`__yo_${e.id}`;if(t.types[e.id]={type:e,cName:n},ce(e))for(let r of e.fields)Mt(r.type,t);if(ge(e)){for(let r of e.variants)if(r.fields)for(let i of r.fields)Mt(i.type,t)}if(it(e))for(let r of e.fields)Mt(r.type,t);if(be(e)){let r=e;for(let i of r.requiredTraits)Mt(i.traitType,t)}if(wt(e)){let r=e;Mt(r.childType,t),P(r,t)}if(Ct(e)){let r=e;Mt(r.childType,t),P(r,t)}if(Qe(e)&&Mt(e.childType,t),Te(e)||De(e)){for(let r of e.fields)Mt(r.type,t);for(let r of e.fields)if(r.assignedValue&&ne(r.assignedValue)){let i=r.assignedValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:te(i.funcId)},Sr(i.type,t),Ht(i.body,t))}else if(r.assignedValue&&(We(r.assignedValue)||Tt(r.assignedValue))){let i=r.assignedValue;Ko(i,t)}}}else if(ke(e)){let n=e,r=n.childType,i=n.length;if(ze(i)){Mt(r,t);let o=P(r,t),a=`Array_${te(o)}_${i.value}`;t.arrayStructTypes.has(a)||t.arrayStructTypes.set(a,{childType:o,length:typeof i.value=="bigint"?Number(i.value):i.value}),t.types[e.id]={type:e,cName:a}}}else if(Ie(e)){if(Mt(e.childType,t),Qe(e.childType)){let r=e.childType.childType;Mt(r,t);let i=P(r,t),o=`Slice_${te(i)}`;t.sliceStructTypes.has(o)||t.sliceStructTypes.set(o,{childType:i})}t.types[e.id]={type:e,cName:P(e,t)}}else gc.has(e.tag)&&(t.types[e.id]={type:e,cName:P(e,t)});e.trait&&Mt(e.trait,t)}}}function Ti(e){if(e.$&&e.$.value&&de(e.$.value)&&!(G(e.$.type)&&e.$.type.isExtern)){if(!pe(e.$.type))return!0}if(F(e)){if(Ti(e.func))return!0;for(let t of e.args)if(!(t.$?.type&&pe(t.$.type))&&Ti(t))return!0}if(e.$&&e.$.macroExpansion){if(e.$.type&&pe(e.$.type))return!1;if(Ti(e.$.macroExpansion))return!0}if(e.$?.deferredDupExpressions){for(let t of e.$.deferredDupExpressions)if(Ti(t))return!0}if(e.$?.deferredDropExpressions){for(let t of e.$.deferredDropExpressions)if(Ti(t))return!0}return!1}function Ko(e,t){for(let n=0;n<e.fields.length;n++){let r=e.fields[n],i=e.type.fields[n];if(ne(r)){let o=i.label;if(o==="main")t.functions[r.funcId]={value:r,cName:"__yo_user_main"};else if(t.isLibrary)if(t.currentModuleId&&r.funcId.startsWith(`fn_${t.currentModuleId}_`)){let s=te(o);t.functions[r.funcId]={value:r,cName:s},t.exportedFunctionLabels||(t.exportedFunctionLabels=new Map),t.exportedFunctionLabels.set(r.funcId,o)}else t.functions[r.funcId]={value:r,cName:te(r.funcId)};else t.functions[r.funcId]={value:r,cName:te(r.funcId)};Ht(r.body,t)}}}function Oc(e,t){for(let n=0;n<e.fields.length;n++){let r=e.fields[n];r&&ne(r)?t.functions[r.funcId]||(r.isModuleEffectMember=!0,t.functions[r.funcId]={value:r,cName:te(r.funcId)},Ht(r.body,t)):r&&We(r)&&Oc(r,t)}}function Ht(e,t){if(e.$?.value&&We(e.$.value)){let i=e.$.value;Oc(i,t)}if(F(e)&&E(e,I.test)||F(e)&&E(e,k.comptime_expect_error))return;if(e.$&&e.$.macroExpansion&&Ht(e.$.macroExpansion,t),e.$?.effectAnalysis){let i=e.$.effectAnalysis.handlerValue;i&&ne(i)&&Ht(i.body,t)}if(e.$&&e.$.closureFunctionValue){let i=e.$.closureFunctionValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:te(i.funcId)},Ht(i.body,t))}if(F(e)&&e.$&&e.$.dynCallTraitValues&&e.$.dynCallTraitValues.length>0){let i=e.$.type,o=e.args[0];if(be(i)&&o&&o.$?.type){let a=o.$.type,s=e.$.dynCallTraitValues;if(s.length>0&&(pt(a)||$n(a))){let l=$n(a)?a.fields[0].type:a,u=`${l.id}_${i.id}`;t.dynImpls.set(u,{dynType:i,concreteType:l,dataType:a,traitValues:s})}}}if(F(e)){let i=e.func.$?.type,o=e.func.$?.value;if(e.func.token.value==="?=")return;if(G(i)){if(ne(o)&&o.isControlFunction){Ht(o.body,t);for(let a of e.args)Ht(a,t);return}if(ne(o)){if(o.type.return.isCompileTimeOnly||as(o)&&!o.specializedType)return;if(o.specializedType&&sr(o.specializedType)&&$t(o.specializedType).length===0){Ht(e.func,t);for(let s of e.args)Ht(s,t);return}if(!t.functions[o.funcId]){let a=!1;if(Ti(o.body)){let s=o.specializedType??o.type;if(a=s.implicitParameters.length>0&&($t(s).length>0||!sr(o.type)&&o.type.implicitParameters.length>0),!a)return}if(!a&&!($t(o.specializedType??o.type).length>0)&&(o.specializedType??o.type).parameters.map(c=>c.type).some(c=>x(c)&&Ce(c)&&!c.resolvedConcreteType))return;t.functions[o.funcId]={value:o,cName:te(o.funcId)},Ht(o.body,t)}}else if(i.isExtern==="c"){let a=i.externName?i.externName:z(e.func)?e.func.token.value:i.id;t.externFunctions[i.id]={type:i,cName:a}}else if(i.isExtern==="yo"){let a=i.externName;if(!(a&&a.startsWith("__yo_"))){let s=a?te(a):z(e.func)?te(e.func.token.value):te(i.id);t.externFunctions[i.id]={type:i,cName:s}}}}Ht(e.func,t);for(let a of e.args)Ht(a,t)}let n=e.$?.type,r=e.$?.value;if(G(n)){if(ne(r)&&r.isControlFunction){if(r.isModuleEffectMember=!0,t.functions[r.funcId]||(t.functions[r.funcId]={value:r,cName:te(r.funcId)}),r.specializedFunctionCaches)for(let i of r.specializedFunctionCaches){let o=i.specializedFunction;o&&!t.functions[o.funcId]&&(o.isModuleEffectMember=!0,t.functions[o.funcId]={value:o,cName:te(o.funcId)},Ht(o.body,t))}Ht(r.body,t);return}if(ne(r)){if(as(r)&&!r.specializedFunctionCaches||t.functions[r.funcId])return;if(Ti(r.body))return;t.functions[r.funcId]={value:r,cName:te(r.funcId)},Ht(r.body,t)}}if(O(e.$?.value)&&Mt(e.$.value.value,t),e.$?.deferredDupExpressions)for(let i of e.$.deferredDupExpressions)Ht(i,t);if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions)Ht(i,t);if(e.$?.dynCallTraitValues)for(let i of e.$.dynCallTraitValues)Ko(i,t)}function Rc(e){let t=k.dispose[0];for(let n in e.types){let{type:r}=e.types[n];if(!ce(r)||!r.isReferenceSemantics)continue;let i=Jn({concreteType:r,methodName:t,env:r.env});for(let o of i)if(o.value&&ne(o.value)){let a=o.value;if(e.functions[a.funcId])continue;a.funcName||(a.funcName=t),e.functions[a.funcId]={value:a,cName:te(a.funcId)},Sr(a.type,e),Ht(a.body,e)}}}function Pc(e){let t=e.emitter,n=new Set;for(let[,r]of e.dynImpls){let i=e.types[r.dynType.id]?.cName||`__yo_dyn_${r.dynType.id}`;n.has(i)||(n.add(i),t.emitLine(`${i} __yo_dup_${i}(${i} dyn) {`),t.emitLine(" if (dyn.data) {"),t.emitLine(" __yo_incr_rc(dyn.data);"),t.emitLine(" }"),t.emitLine(" return dyn;"),t.emitLine("}"),t.emitLine(""),t.emitLine(`void __yo_drop_${i}(${i} dyn) {`),t.emitLine(" if (dyn.data) {"),t.emitLine(" __yo_decr_rc(dyn.data);"),t.emitLine(" }"),t.emitLine("}"),t.emitLine(""))}}function Uc(e){let t=e.emitter;if(e.dynImpls.size===0)return;t.emitLine(""),t.emitLine("// === Dyn Box Functions ==="),t.emitLine("// Constructor and dispose functions for dyn boxes"),t.emitLine("");let n=new Set;for(let[,r]of e.dynImpls){let i=x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType,a=`__yo_dyn_box_${e.types[i.id]?.cName||`unknown_${i.id}`}`;if(n.has(a))continue;n.add(a);let s=P(i,e);t.emitLine(`static ${a}* __yo_new_${a}(${s} value) {`),t.emitLine(` ${a}* box = (${a}*)__yo_malloc(sizeof(${a}));`),t.emitLine(" box->header.ref_count = 1;"),t.emitLine(" box->header.gc_flags = 0;"),t.emitLine(" box->header.gc_mark = __YO_GC_UNMARKED;"),t.emitLine(" box->header.gc_next = NULL;"),t.emitLine(" box->header.gc_prev = NULL;"),t.emitLine(` box->header.dispose_fn = __yo_dispose_${a};`),t.emitLine(" box->header.traverse_fn = NULL; // TODO: Set if value contains GC types"),t.emitLine(" box->value = value;"),t.emitLine(" return box;"),t.emitLine("}"),t.emitLine(""),t.emitLine(`static void __yo_dispose_${a}(void* ptr) {`),t.emitLine(` ${a}* box = (${a}*)ptr;`);let u=(x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType).trait?.fields.find(c=>c.label===k.___drop[0]);if(u&&u.assignedValue&&ne(u.assignedValue)){let c=e.functions[u.assignedValue.funcId]?.cName;c&&t.emitLine(` ${c}(box->value);`)}t.emitLine("}"),t.emitLine("")}}function zc(e){let t=e.emitter;if(e.dynImpls.size!==0){t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Wrapper Functions ==="),t.emitDeclarationLine("// Wrappers that unwrap boxed values and call impl methods"),t.emitDeclarationLine("");for(let[n,r]of e.dynImpls){let i=r.dataType,o=new Set([k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]]);for(let{traitType:a}of r.dynType.requiredTraits){if(!kt(a))continue;let s=a.isFn.callType,l=P(s.return.type,e),u=`__yo_wrap_${n}_call`,c=["void* self_ptr"];for(let _=0;_<s.parameters.length;_++){let p=s.parameters[_],f=P(p.type,e);c.push(`${f} arg${_+1}`)}if(t.emitDeclarationLine(`static ${l} ${u}(${c.join(", ")}) {`),$n(i)){let _=e.types[i.id]?.cName||`unknown_${i.id}`,p=te(i.fields[0].label);t.emitDeclarationLine(` ${_}* box = (${_}*)self_ptr;`);let f=i.fields[0].type,m=x(f)&&f.resolvedConcreteType?f.resolvedConcreteType:f,g=e.implClosureCallMap.get(m.id),h=(()=>{if(g)return g.functionCName;for(let[,v]of Object.entries(e.functions))if(v.value.closureInfo?.captureType?.id===m.id)return v.cName})(),d=[];if(h){d.push(`(void*)&box->${p}`);for(let v=0;v<s.parameters.length;v++)d.push(`arg${v+1}`);$r(s.return.type)?t.emitDeclarationLine(` ${h}(${d.join(", ")});`):t.emitDeclarationLine(` return ${h}(${d.join(", ")});`)}else{d.push(`box->${p}.data`);for(let v=0;v<s.parameters.length;v++)d.push(`arg${v+1}`);$r(s.return.type)?t.emitDeclarationLine(` box->${p}.call(${d.join(", ")});`):t.emitDeclarationLine(` return box->${p}.call(${d.join(", ")});`)}}else{t.emitDeclarationLine(" (void)self_ptr; /* Dyn(Fn): expected Box(...) data */");for(let _=0;_<s.parameters.length;_++)t.emitDeclarationLine(` (void)arg${_+1};`);$r(s.return.type)?t.emitDeclarationLine(" return;"):(t.emitDeclarationLine(` ${l} zero = (${l})0;`),t.emitDeclarationLine(" return zero;"))}t.emitDeclarationLine("}"),t.emitDeclarationLine("")}for(let a=0;a<r.dynType.requiredTraits.length;a++){let{traitType:s}=r.dynType.requiredTraits[a];if(kt(s))continue;let l=r.traitValues[a];if(!l){t.emitDeclarationLine(`/* Warning: Module value missing for module ${a} */`);continue}let c=l.type.fields;for(let _=0;_<c.length;_++){let p=c[_];if(p.label==="Self"||o.has(p.label))continue;let f=l.fields[_];if(!f||!ne(f)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function value */`);continue}let m=p.type;if(!G(m)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function type */`);continue}let g=f.funcId,h=e.functions[g]?.cName;if(!h){t.emitDeclarationLine(`/* Warning: Impl function for ${p.label} not found */`);continue}let d=`__yo_wrap_${n}_${p.label}`,v=P(m.return.type,e),T=["void* self_ptr"];for(let b=1;b<m.parameters.length;b++){let R=m.parameters[b],N=P(R.type,e);T.push(`${N} arg${b}`)}t.emitDeclarationLine(`static ${v} ${d}(${T.join(", ")}) {`);let $=m.parameters[0]?.type,C;if($n(i)){let b=e.types[i.id]?.cName||`unknown_${i.id}`,R=te(i.fields[0].label);t.emitDeclarationLine(` ${b}* box = (${b}*)self_ptr;`),$&&Ie($)?C=`&box->${R}`:C=`box->${R}`}else{let b=P(r.concreteType,e);t.emitDeclarationLine(` ${b} concrete_value = (${b})self_ptr;`),$&&Ie($)?C="&concrete_value":C="concrete_value"}let L=[C];for(let b=1;b<m.parameters.length;b++)L.push(`arg${b}`);$r(m.return.type)?t.emitDeclarationLine(` ${h}(${L.join(", ")});`):t.emitDeclarationLine(` return ${h}(${L.join(", ")});`),t.emitDeclarationLine("}"),t.emitDeclarationLine("")}}}}}function Bc(e){let t=e.emitter;if(e.dynImpls.size===0)return;t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn TypeId Statics ==="),t.emitDeclarationLine("// Unique static per concrete type \u2014 address is the runtime TypeId"),t.emitDeclarationLine("");let n=new Set;e.typeIdStatics||(e.typeIdStatics=new Map);for(let[,r]of e.dynImpls){let i=x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType,o=e.types[i.id]?.cName||`unknown_${i.id}`,a=`__yo_typeid_${o}`;!n.has(a)&&!e.typeIdStatics.has(i.id)&&(n.add(a),e.typeIdStatics.set(i.id,a),t.emitDeclarationLine(`static const char ${a} = 0; // TypeId for ${o}`))}t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Static Vtables ==="),t.emitDeclarationLine("// Static vtables for dynamic dispatch"),t.emitDeclarationLine("");for(let[r,i]of e.dynImpls){let o=e.types[i.dynType.id]?.cName||`__yo_dyn_${i.dynType.id}`,a=x(i.concreteType)&&i.concreteType.resolvedConcreteType?i.concreteType.resolvedConcreteType:i.concreteType,s=e.types[a.id]?.cName||`unknown_${a.id}`,l=`__yo_vtable_${r}`,u=`${o}_vtable`,c=`__yo_typeid_${s}`;t.emitDeclarationLine(`// Vtable for impl(${s}, ${i.dynType.requiredTraits.map(({traitType:f})=>f.typeName||"?").join(" + ")})`),t.emitDeclarationLine(`static const ${u} ${l} = {`),t.emitDeclarationLine(` .__yo_type_id = (uintptr_t)&${c},`);let _=new Set,p=new Set([k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]]);for(let{traitType:f}of i.dynType.requiredTraits){if(kt(f)){let m=`__yo_wrap_${r}_call`;t.emitDeclarationLine(` .call = ${m},`),_.add("call");continue}for(let m of f.fields)if(m.label!=="Self"&&!p.has(m.label)&&!_.has(m.label)&&(_.add(m.label),G(m.type))){let g=m.type;if(g.parameters.length>0){let h=g.parameters[0];if(h&&h.label==="self"){let d=`__yo_wrap_${r}_${m.label}`;t.emitDeclarationLine(` .${te(m.label)} = ${d},`)}}}}t.emitDeclarationLine("};"),t.emitDeclarationLine("")}}function Gc(e,t){let n=!yi(t),r=Pt(t)?"__declspec(thread)":"_Thread_local";e.emitLine(`
195
195
  // ============================================================================
196
- // Async/Await Runtime - Single-Threaded Cooperative Scheduler
196
+ // Async/Await Runtime - Per-Thread Cooperative Scheduler
197
197
  // ============================================================================
198
- // This implements a cooperative async runtime for single-threaded concurrency.
199
- // All async tasks run on the SAME thread - no parallelism, just interleaving.
198
+ // This implements a cooperative async runtime with per-thread event loops.
199
+ // Each OS thread has its own scheduler and I/O backend \u2014 no shared state.
200
+ // Multiple workers on the same thread cooperatively share the event loop.
200
201
  // Uses non-atomic reference counting (everything is thread-local).
201
202
  //
202
203
  // LAZY EXECUTION MODEL:
@@ -225,16 +226,16 @@ typedef struct {
225
226
  } __yo_async_task_queue_t;
226
227
 
227
228
  // Thread-local async runtime state
228
- ${zt(t)?"static __declspec(thread) __yo_async_task_queue_t __yo_thread_async_queue = {NULL, NULL, 0};":"static __thread __yo_async_task_queue_t __yo_thread_async_queue = {NULL, NULL, 0};"}
229
+ ${Pt(t)?"static __declspec(thread) __yo_async_task_queue_t __yo_thread_async_queue = {NULL, NULL, 0};":"static __thread __yo_async_task_queue_t __yo_thread_async_queue = {NULL, NULL, 0};"}
229
230
 
230
- // Async scheduler initialized flag
231
- static bool __yo_async_scheduler_initialized = false;
231
+ // Async scheduler initialized flag (per-thread \u2014 each thread has its own event loop)
232
+ static ${r} bool __yo_async_scheduler_initialized = false;
232
233
 
233
- // Count of active poll/fs_event watches (used by all platforms)
234
- static size_t __yo_active_watch_count = 0;
234
+ // Count of active poll/fs_event watches (per-thread event loop state)
235
+ static ${r} size_t __yo_active_watch_count = 0;
235
236
 
236
- ${n?`// Whether the I/O subsystem has been initialized
237
- static bool __yo_io_initialized = false;
237
+ ${n?`// Whether the I/O subsystem has been initialized (per-thread)
238
+ static ${r} bool __yo_io_initialized = false;
238
239
 
239
240
  // Forward declarations for I/O functions
240
241
  static void __yo_io_init(void);
@@ -433,7 +434,7 @@ ${n?` __yo_io_poll();
433
434
 
434
435
  // Get the number of hardware threads (CPU cores)
435
436
  static size_t __yo_thread_get_hardware_threads(void) {
436
- ${zt(t)?` SYSTEM_INFO sysinfo;
437
+ ${Pt(t)?` SYSTEM_INFO sysinfo;
437
438
  GetSystemInfo(&sysinfo);
438
439
  return (size_t)sysinfo.dwNumberOfProcessors;`:qn(t)?` int count;
439
440
  size_t size = sizeof(count);
@@ -452,14 +453,14 @@ static void __yo_thread_set_maximum_threads(size_t num) {
452
453
 
453
454
  // Get current thread ID (useful for debugging)
454
455
  static size_t __yo_get_thread_id(void) {
455
- ${zt(t)?" return (size_t)GetCurrentThreadId();":qn(t)?` uint64_t tid;
456
+ ${Pt(t)?" return (size_t)GetCurrentThreadId();":qn(t)?` uint64_t tid;
456
457
  pthread_threadid_np(NULL, &tid);
457
458
  return (size_t)tid;`:" return (size_t)syscall(SYS_gettid);"}
458
459
  }
459
460
 
460
461
  // Yield execution (allows other tasks to run)
461
462
  static void __yo_thread_yield(void) {
462
- ${zt(t)?" SwitchToThread();":" sched_yield();"}
463
+ ${Pt(t)?" SwitchToThread();":" sched_yield();"}
463
464
  }
464
465
 
465
466
  // Async yield - creates an immediately-ready Future for cooperative yielding
@@ -1042,10 +1043,10 @@ static uint64_t __yo_statx_blocks(void* statxbuf) {
1042
1043
  #include <time.h>
1043
1044
  #include <errno.h>
1044
1045
 
1045
- // kqueue file descriptor for async I/O
1046
- static int __yo_io_kq = -1;
1046
+ // kqueue file descriptor for async I/O (per-thread \u2014 each thread has its own event loop)
1047
+ static _Thread_local int __yo_io_kq = -1;
1047
1048
  // __yo_io_initialized is defined in runtime-core
1048
- static size_t __yo_pending_io_count = 0; // no _Atomic \u2014 single-threaded event loop
1049
+ static _Thread_local size_t __yo_pending_io_count = 0; // per-thread event loop counter
1049
1050
 
1050
1051
  // Pending operation types for kqueue completion dispatch
1051
1052
  typedef enum {
@@ -2557,9 +2558,9 @@ static uint64_t __yo_statx_blocks(void* statxbuf) {
2557
2558
  #include <arpa/inet.h>
2558
2559
  #include <sys/un.h>
2559
2560
 
2560
- static struct io_uring __yo_io_ring;
2561
+ static _Thread_local struct io_uring __yo_io_ring;
2561
2562
  // __yo_io_initialized is defined in runtime-core
2562
- static size_t __yo_pending_io_count = 0;
2563
+ static _Thread_local size_t __yo_pending_io_count = 0;
2563
2564
 
2564
2565
  // I/O Future types - __yo_io_future_t is defined in types/generation.ts
2565
2566
  // It has the same layout as async state machines (state, result, continuation_fn, continuation_sm)
@@ -5487,8 +5488,8 @@ static int32_t __yo_isatty(int32_t fd) { return _isatty(fd) ? 1 : 0; }
5487
5488
  // Async I/O Runtime (Windows - IOCP)
5488
5489
  // ============================================================================
5489
5490
  // __yo_io_initialized is defined in runtime-core
5490
- static size_t __yo_pending_io_count = 0;
5491
- static HANDLE __yo_io_iocp = NULL;
5491
+ static __declspec(thread) size_t __yo_pending_io_count = 0;
5492
+ static __declspec(thread) HANDLE __yo_io_iocp = NULL;
5492
5493
  static CRITICAL_SECTION __yo_dir_state_mutex;
5493
5494
 
5494
5495
  typedef struct __yo_win_timer_entry_t {
@@ -5497,7 +5498,7 @@ typedef struct __yo_win_timer_entry_t {
5497
5498
  struct __yo_win_timer_entry_t* next;
5498
5499
  } __yo_win_timer_entry_t;
5499
5500
 
5500
- static __yo_win_timer_entry_t* __yo_win_timer_head = NULL;
5501
+ static __declspec(thread) __yo_win_timer_entry_t* __yo_win_timer_head = NULL;
5501
5502
 
5502
5503
  typedef struct {
5503
5504
  OVERLAPPED overlapped;
@@ -7352,7 +7353,7 @@ typedef struct __yo_fs_event_s {
7352
7353
  struct __yo_fs_event_s* next;
7353
7354
  } __yo_fs_event_t;
7354
7355
 
7355
- static __yo_fs_event_t* __yo_active_fs_events = NULL;
7356
+ static __declspec(thread) __yo_fs_event_t* __yo_active_fs_events = NULL;
7356
7357
 
7357
7358
  static void* __yo_fs_event_init(void) {
7358
7359
  __yo_fs_event_t* handle = (__yo_fs_event_t*)__yo_malloc(sizeof(__yo_fs_event_t));
@@ -7526,7 +7527,7 @@ typedef struct __yo_poll_s {
7526
7527
  struct __yo_poll_s* next;
7527
7528
  } __yo_poll_t;
7528
7529
 
7529
- static __yo_poll_t* __yo_active_polls = NULL;
7530
+ static __declspec(thread) __yo_poll_t* __yo_active_polls = NULL;
7530
7531
 
7531
7532
  static void* __yo_poll_init(int32_t fd) {
7532
7533
  __yo_poll_t* handle = (__yo_poll_t*)__yo_malloc(sizeof(__yo_poll_t));
@@ -7735,7 +7736,7 @@ static int __yo_poll_and_fs_event_tick(void) {
7735
7736
  }
7736
7737
 
7737
7738
 
7738
- `)}function Xc(e,t){let n=zt(t),r=mi(t),i=qn(t);if(n){jc(e);return}e.emitLine(`
7739
+ `)}function Xc(e,t){let n=Pt(t),r=mi(t),i=qn(t);if(n){jc(e);return}e.emitLine(`
7739
7740
  // ============================================================================
7740
7741
  // File System Helper Functions
7741
7742
  // ============================================================================
@@ -8136,7 +8137,7 @@ static int32_t __yo_tty_get_winsize(int32_t fd, int32_t* width, int32_t* height)
8136
8137
  static int32_t __yo_isatty(int32_t fd) {
8137
8138
  return isatty(fd) ? 1 : 0;
8138
8139
  }
8139
- `),i&&Wc(e),r&&Yc(e)}function Qc(e,t){let n=zt(t),r=mi(t),i=qn(t);r?e.emitLine(`
8140
+ `),i&&Wc(e),r&&Yc(e)}function Qc(e,t){let n=Pt(t),r=mi(t),i=qn(t);r?e.emitLine(`
8140
8141
  // ============================================================================
8141
8142
  // Timer Operations (Linux - timerfd + io_uring)
8142
8143
  // ============================================================================
@@ -8224,8 +8225,8 @@ static __yo_io_future_t* __yo_async_sleep_start(uint64_t milliseconds) {
8224
8225
  // Timer Operations (macOS - kqueue EVFILT_TIMER)
8225
8226
  // ============================================================================
8226
8227
 
8227
- // Monotonically increasing timer ID for unique kqueue ident values
8228
- static uintptr_t __yo_timer_next_id = 1;
8228
+ // Monotonically increasing timer ID for unique kqueue ident values (per-thread)
8229
+ static _Thread_local uintptr_t __yo_timer_next_id = 1;
8229
8230
 
8230
8231
  // Timer context stored as kevent udata
8231
8232
  typedef struct __yo_timer_ctx_t {
@@ -8683,7 +8684,7 @@ ${i?` char* path;
8683
8684
  struct __yo_fs_event_s* next;
8684
8685
  } __yo_fs_event_t;
8685
8686
 
8686
- static __yo_fs_event_t* __yo_active_fs_events = NULL;
8687
+ static _Thread_local __yo_fs_event_t* __yo_active_fs_events = NULL;
8687
8688
  `),i&&e.emitLine(`
8688
8689
  static void __yo_fs_event_free_entries(__yo_fs_event_entry_t* head) {
8689
8690
  while (head) {
@@ -9032,7 +9033,7 @@ typedef struct __yo_poll_s {
9032
9033
  struct __yo_poll_s* next;
9033
9034
  } __yo_poll_t;
9034
9035
 
9035
- static __yo_poll_t* __yo_active_polls = NULL;
9036
+ static _Thread_local __yo_poll_t* __yo_active_polls = NULL;
9036
9037
 
9037
9038
  static void* __yo_poll_init(int32_t fd) {
9038
9039
  __yo_poll_t* handle = (__yo_poll_t*)__yo_malloc(sizeof(__yo_poll_t));
@@ -9189,8 +9190,8 @@ ${i?` {
9189
9190
 
9190
9191
  return count;
9191
9192
  }
9192
- `))}function Zc(e,t,n){Gc(e,t),mi(t)?Hc(e):qn(t)?qc(e):zt(t)&&Kc(e),yi(t)||Qc(e,t)}function Gy(e,t,n,r){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){rt(e,n,r);let i=e.$.deferredDupExpressions[0];if(F(i)&&i.$?.variableName)return Ee(i.$.variableName,i.$.env)}return t}function Wy(e,t,n){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){if(e.$?.variableName){let i=e.$.variableName;e.$.variableName=void 0;let o=M(e,t,n);e.$.variableName=i;let a=P(e.$.type,n),s=te(i);s!==o&&n.emitter.emitLine(`${t}${a} ${s} = ${o};`)}else{let i=M(e,t,n);n.emitter.emitLine(`${t}${i};`)}rt(e,t,n);let r=e.$.deferredDupExpressions[0];if(F(r)&&r.$?.variableName)return Ee(r.$.variableName,r.$.env)}return M(e,t,n)}function qy(e){if(F(e)&&E(e,k.___drop)&&e.args.length>=1){let t=e.args[0];if(t&&z(t))return Ee(t.token.value,t.$?.env)}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&z(e.func.args[0])){let t=e.func.args[0];return Ee(t.token.value,t.$?.env)}}function dn(e,t,n,r=!1,i=!1,o=!1){if(t.pendingDeferredDrops&&t.pendingDeferredDrops.length>0){let a=new Set;if(!i&&n.$?.deferredDropExpressions)for(let u of n.$.deferredDropExpressions){let c=In(u);c&&a.add(c)}let s=t.effectSmConsumedArgCNames,l=n.$?.env&&!o?t.pendingDeferredDrops.filter(u=>{let c=In(u);return!c||a.has(c)?!1:X(n.$.env,c).length>0}):t.pendingDeferredDrops.filter(u=>{let c=In(u);if(!c||a.has(c))return!1;if(s&&s.size>0){let _=qy(u);if(_&&s.has(_))return!1}return!0});if(l.length>0){let u=r?"Drop local variables before early completion":"Drop local variables before early return";t.emitter.emitLine(`${e}// ${u}`);for(let c of l){let _=M(c,e,t);_&&t.emitter.emitLine(`${e}${_};`)}}}}function tr(e,t,n,r=!1){if(!t.consumedVarPendingDrops||t.consumedVarPendingDrops.length===0)return;let i=n.$?.env&&!r?t.consumedVarPendingDrops.filter(o=>{let a=In(o);return a?X(n.$.env,a).length>0:!1}):[...t.consumedVarPendingDrops];if(i.length>0){t.emitter.emitLine(`${e}// Drop consumed variables (escape propagation)`);for(let o of i){let a=M(o,e,t);a&&t.emitter.emitLine(`${e}${a};`)}}}function Jc(e,t,n){let r=n;if(r.continuationVariables){let o=r.continuationVariables.get("resume");if(o&&"directReturnVar"in o){if(!o.isUnitReturn){let a=e.args[0];if(a){let s=M(a,t,n);s&&n.emitter.emitLine(`${t}${o.directReturnVar} = ${s};`)}}return dn(t,r,e,!1,!0),o.directExitLabel&&n.emitter.emitLine(`${t}goto ${o.directExitLabel};`),""}}let i=e.args[0];if(i){if(!e.$)throw new Error("Internal error: return expression missing metadata");if(!e.$.variableName&&!pe(e.$.type))return"// Error: return expression missing temporary variable name";let o,a=!1;if(r.inAsyncStateMachine&&i.$?.variableName){let _=i.$.variableName;i.$.variableName=void 0,o=M(i,t,n),i.$.variableName=_,a=!0}else if(i.$?.variableName&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){let _=i.$.variableName;i.$.variableName=void 0;let p=M(i,t,n);i.$.variableName=_;let f=P(i.$.type,n),m=Ee(_,i.$.env);m!==p&&n.emitter.emitLine(`${t}${f} ${m} = ${p};`),o=m}else o=M(i,t,n);let s=!1;if(i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,r);let _=i.$.deferredDupExpressions[0];F(_)&&_.$?.variableName&&(o=Ee(_.$.variableName,_.$.env),s=!0)}let l=P(e.$.type,n),u=e.$.variableName?Ee(e.$.variableName,e.$.env):void 0;if(!s&&!pe(e.$.type)&&u&&u!==o&&n.emitter.emitLine(`${t}${l} ${u} = ${o};`),e.$.deferredDropExpressions&&Ct(e,t,n),r.inAsyncStateMachine){let _=r.inAsyncStateMachine.futureType,f=Dt(_).isFuture.outputType,m=pe(f);dn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future`);let g;return m||(g=e.$.variableName&&a?e.$.variableName:e.$.variableName||o),Ar({emitter:n.emitter,indent:t,resultCode:g,debugLabel:n.currentFunctionName}),""}return dn(t,r,e),pe(e.$.type)?"return":`return ${s?o:u??o}`}else{if(e.$?.deferredDropExpressions&&Ct(e,t,n),r.inAsyncStateMachine){let o=r.inAsyncStateMachine.futureType,s=Dt(o).isFuture.outputType,l=pe(s);dn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future (early unit return)`);let u=l?void 0:`(${P(s,n)}){0}`;return Ar({emitter:n.emitter,indent:t,resultCode:u,debugLabel:n.currentFunctionName}),""}return dn(t,r,e),"return"}}function e_(e,t,n){let r=n;switch(e.tag){case"Atom":{let i=no(e,n),o=Gy(e,i,t,r);n.emitter.emitLine(`${t}return ${o};`);break}case"FnCall":{if(E(e,I.return)){let i=M(e,t,n);n.emitter.emitLine(`${t}${i};`)}else{let i=Wy(e,t,r);n.emitter.emitLine(`${t}return ${i};`)}break}}}function t_(e,t,n){let r=zt(n),i=mi(n),o=qn(n),a=r?"static unsigned __stdcall __yo_thread_entry(void* arg) {":"static void* __yo_thread_entry(void* arg) {",s=r?"return 0;":"return NULL;",l=r?"static unsigned __stdcall __yo_worker_thread_entry(void* arg) {":"static void* __yo_worker_thread_entry(void* arg) {",u=r?"return 0;":"return NULL;",c=r?"SwitchToThread();":"sched_yield();",_=r?`static __YO_THREAD_SYNC_TYPE __yo_worker_pool_mutex; // Pool-level mutex (initialized in __yo_worker_init_mutex)
9193
- static volatile int __yo_worker_pool_mutex_initialized = 0;`:"static __YO_THREAD_SYNC_TYPE __yo_worker_pool_mutex = __YO_THREAD_SYNC_INIT; // Pool-level mutex",p=r?`
9193
+ `))}function Zc(e,t,n){Gc(e,t),mi(t)?Hc(e):qn(t)?qc(e):Pt(t)&&Kc(e),yi(t)||Qc(e,t)}function Wy(e,t,n,r){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){rt(e,n,r);let i=e.$.deferredDupExpressions[0];if(F(i)&&i.$?.variableName)return Ee(i.$.variableName,i.$.env)}return t}function qy(e,t,n){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){if(e.$?.variableName){let i=e.$.variableName;e.$.variableName=void 0;let o=M(e,t,n);e.$.variableName=i;let a=P(e.$.type,n),s=te(i);s!==o&&n.emitter.emitLine(`${t}${a} ${s} = ${o};`)}else{let i=M(e,t,n);n.emitter.emitLine(`${t}${i};`)}rt(e,t,n);let r=e.$.deferredDupExpressions[0];if(F(r)&&r.$?.variableName)return Ee(r.$.variableName,r.$.env)}return M(e,t,n)}function Yy(e){if(F(e)&&E(e,k.___drop)&&e.args.length>=1){let t=e.args[0];if(t&&z(t))return Ee(t.token.value,t.$?.env)}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&z(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&z(e.func.args[0])){let t=e.func.args[0];return Ee(t.token.value,t.$?.env)}}function dn(e,t,n,r=!1,i=!1,o=!1){if(t.pendingDeferredDrops&&t.pendingDeferredDrops.length>0){let a=new Set;if(!i&&n.$?.deferredDropExpressions)for(let u of n.$.deferredDropExpressions){let c=In(u);c&&a.add(c)}let s=t.effectSmConsumedArgCNames,l=n.$?.env&&!o?t.pendingDeferredDrops.filter(u=>{let c=In(u);return!c||a.has(c)?!1:X(n.$.env,c).length>0}):t.pendingDeferredDrops.filter(u=>{let c=In(u);if(!c||a.has(c))return!1;if(s&&s.size>0){let _=Yy(u);if(_&&s.has(_))return!1}return!0});if(l.length>0){let u=r?"Drop local variables before early completion":"Drop local variables before early return";t.emitter.emitLine(`${e}// ${u}`);for(let c of l){let _=M(c,e,t);_&&t.emitter.emitLine(`${e}${_};`)}}}}function tr(e,t,n,r=!1){if(!t.consumedVarPendingDrops||t.consumedVarPendingDrops.length===0)return;let i=n.$?.env&&!r?t.consumedVarPendingDrops.filter(o=>{let a=In(o);return a?X(n.$.env,a).length>0:!1}):[...t.consumedVarPendingDrops];if(i.length>0){t.emitter.emitLine(`${e}// Drop consumed variables (escape propagation)`);for(let o of i){let a=M(o,e,t);a&&t.emitter.emitLine(`${e}${a};`)}}}function Jc(e,t,n){let r=n;if(r.continuationVariables){let o=r.continuationVariables.get("resume");if(o&&"directReturnVar"in o){if(!o.isUnitReturn){let a=e.args[0];if(a){let s=M(a,t,n);s&&n.emitter.emitLine(`${t}${o.directReturnVar} = ${s};`)}}return dn(t,r,e,!1,!0),o.directExitLabel&&n.emitter.emitLine(`${t}goto ${o.directExitLabel};`),""}}let i=e.args[0];if(i){if(!e.$)throw new Error("Internal error: return expression missing metadata");if(!e.$.variableName&&!pe(e.$.type))return"// Error: return expression missing temporary variable name";let o,a=!1;if(r.inAsyncStateMachine&&i.$?.variableName){let _=i.$.variableName;i.$.variableName=void 0,o=M(i,t,n),i.$.variableName=_,a=!0}else if(i.$?.variableName&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){let _=i.$.variableName;i.$.variableName=void 0;let p=M(i,t,n);i.$.variableName=_;let f=P(i.$.type,n),m=Ee(_,i.$.env);m!==p&&n.emitter.emitLine(`${t}${f} ${m} = ${p};`),o=m}else o=M(i,t,n);let s=!1;if(i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,r);let _=i.$.deferredDupExpressions[0];F(_)&&_.$?.variableName&&(o=Ee(_.$.variableName,_.$.env),s=!0)}let l=P(e.$.type,n),u=e.$.variableName?Ee(e.$.variableName,e.$.env):void 0;if(!s&&!pe(e.$.type)&&u&&u!==o&&n.emitter.emitLine(`${t}${l} ${u} = ${o};`),e.$.deferredDropExpressions&&bt(e,t,n),r.inAsyncStateMachine){let _=r.inAsyncStateMachine.futureType,f=Dt(_).isFuture.outputType,m=pe(f);dn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future`);let g;return m||(g=e.$.variableName&&a?e.$.variableName:e.$.variableName||o),Ar({emitter:n.emitter,indent:t,resultCode:g,debugLabel:n.currentFunctionName}),""}return dn(t,r,e),pe(e.$.type)?"return":`return ${s?o:u??o}`}else{if(e.$?.deferredDropExpressions&&bt(e,t,n),r.inAsyncStateMachine){let o=r.inAsyncStateMachine.futureType,s=Dt(o).isFuture.outputType,l=pe(s);dn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future (early unit return)`);let u=l?void 0:`(${P(s,n)}){0}`;return Ar({emitter:n.emitter,indent:t,resultCode:u,debugLabel:n.currentFunctionName}),""}return dn(t,r,e),"return"}}function e_(e,t,n){let r=n;switch(e.tag){case"Atom":{let i=no(e,n),o=Wy(e,i,t,r);n.emitter.emitLine(`${t}return ${o};`);break}case"FnCall":{if(E(e,I.return)){let i=M(e,t,n);n.emitter.emitLine(`${t}${i};`)}else{let i=qy(e,t,r);n.emitter.emitLine(`${t}return ${i};`)}break}}}function t_(e,t,n,r){let i=Pt(n),o=mi(n),a=qn(n),s=i?"static unsigned __stdcall __yo_thread_entry(void* arg) {":"static void* __yo_thread_entry(void* arg) {",l=i?"return 0;":"return NULL;",u=i?"static unsigned __stdcall __yo_worker_thread_entry(void* arg) {":"static void* __yo_worker_thread_entry(void* arg) {",c=i?"return 0;":"return NULL;",_=i?"SwitchToThread();":"sched_yield();",p=i?`static __YO_THREAD_SYNC_TYPE __yo_worker_pool_mutex; // Pool-level mutex (initialized in __yo_worker_init_mutex)
9194
+ static volatile int __yo_worker_pool_mutex_initialized = 0;`:"static __YO_THREAD_SYNC_TYPE __yo_worker_pool_mutex = __YO_THREAD_SYNC_INIT; // Pool-level mutex",f=i?`
9194
9195
  // Initialize the worker pool mutex on Windows (must be called before any use)
9195
9196
  static void __yo_worker_init_mutex(void) {
9196
9197
  if (!__yo_worker_pool_mutex_initialized) {
@@ -9198,16 +9199,16 @@ static void __yo_worker_init_mutex(void) {
9198
9199
  __yo_worker_pool_mutex_initialized = 1;
9199
9200
  }
9200
9201
  }
9201
- `:"",f=r?"__yo_worker_init_mutex();":"",m;r?m=` SYSTEM_INFO sysinfo;
9202
+ `:"",m=i?"__yo_worker_init_mutex();":"",g;i?g=` SYSTEM_INFO sysinfo;
9202
9203
  GetSystemInfo(&sysinfo);
9203
- return (size_t)sysinfo.dwNumberOfProcessors;`:o?m=` int count;
9204
+ return (size_t)sysinfo.dwNumberOfProcessors;`:a?g=` int count;
9204
9205
  size_t size = sizeof(count);
9205
9206
  if (sysctlbyname("hw.ncpu", &count, &size, NULL, 0) == 0) {
9206
9207
  return (size_t)count;
9207
9208
  }
9208
- return 1;`:m=` long count = sysconf(_SC_NPROCESSORS_ONLN);
9209
- return count > 0 ? (size_t)count : 1;`;let g;i?g=` int cpu = sched_getcpu();
9210
- return cpu;`:r?g=" return (int)GetCurrentProcessorNumber();":g=" return -1;",e.emitLine(`
9209
+ return 1;`:g=` long count = sysconf(_SC_NPROCESSORS_ONLN);
9210
+ return count > 0 ? (size_t)count : 1;`;let h;o?h=` int cpu = sched_getcpu();
9211
+ return cpu;`:i?h=" return (int)GetCurrentProcessorNumber();":h=" return -1;",e.emitLine(`
9211
9212
  // ============================================================================
9212
9213
  // Parallelism Runtime - Thread and Worker
9213
9214
  // ============================================================================
@@ -9229,16 +9230,22 @@ typedef struct __yo_thread_entry_args_t {
9229
9230
  } __yo_thread_entry_args_t;
9230
9231
 
9231
9232
  // Thread entry point
9232
- ${a}
9233
+ ${s}
9233
9234
  __yo_thread_entry_args_t* args = (__yo_thread_entry_args_t*)arg;
9234
9235
 
9235
9236
  PARALLELISM_DEBUG("[THREAD] Thread started (tid=%zu)\\n", (size_t)__yo_get_thread_id());
9236
9237
 
9237
9238
  // Initialize thread-local GC for this thread
9238
9239
  __yo_gc_init_thread();
9240
+ ${r?`
9241
+ // Initialize per-thread async event loop (io_uring/kqueue/IOCP)
9242
+ __yo_async_scheduler_init();`:""}
9239
9243
 
9240
9244
  // Call user's function with closure
9241
9245
  args->fn(args->closure);
9246
+ ${r?`
9247
+ // Drain per-thread event loop \u2014 wait for all async tasks spawned in this thread
9248
+ __yo_async_wait_all();`:""}
9242
9249
 
9243
9250
  PARALLELISM_DEBUG("[THREAD] Thread completed (tid=%zu)\\n", (size_t)__yo_get_thread_id());
9244
9251
 
@@ -9253,7 +9260,7 @@ ${a}
9253
9260
  // Free args
9254
9261
  __yo_free(args);
9255
9262
 
9256
- ${s}
9263
+ ${l}
9257
9264
  }
9258
9265
 
9259
9266
  // Spawn a new OS thread (returns by value)
@@ -9322,17 +9329,20 @@ typedef struct __yo_worker_thread_t {
9322
9329
  static __yo_worker_thread_t* __yo_worker_threads = NULL; // Array of worker threads
9323
9330
  static size_t __yo_worker_num_threads = 0; // Number of worker threads
9324
9331
  static size_t __yo_worker_next_thread = 0; // Round-robin counter for task distribution
9325
- ${_}
9326
- static volatile int __yo_worker_pool_initialized = 0; // Pool initialization flag
9327
9332
  ${p}
9333
+ static volatile int __yo_worker_pool_initialized = 0; // Pool initialization flag
9334
+ ${f}
9328
9335
  // Worker thread entry point
9329
- ${l}
9336
+ ${u}
9330
9337
  __yo_worker_thread_t* worker = (__yo_worker_thread_t*)arg;
9331
9338
 
9332
9339
  PARALLELISM_DEBUG("[WORKER] Worker thread started (tid=%zu)\\n", (size_t)__yo_get_thread_id());
9333
9340
 
9334
9341
  // Initialize thread-local GC for this worker thread
9335
9342
  __yo_gc_init_thread();
9343
+ ${r?`
9344
+ // Initialize per-thread async event loop (io_uring/kqueue/IOCP)
9345
+ __yo_async_scheduler_init();`:""}
9336
9346
 
9337
9347
  // Signal that this thread has started
9338
9348
  worker->started = 1;
@@ -9366,6 +9376,9 @@ ${l}
9366
9376
  if (task != NULL) {
9367
9377
  PARALLELISM_DEBUG("[WORKER] Executing task (tid=%zu)\\n", (size_t)__yo_get_thread_id());
9368
9378
  task->fn(task->closure);
9379
+ ${r?`
9380
+ // Drain per-thread event loop \u2014 wait for all async tasks from this task
9381
+ __yo_async_wait_all();`:""}
9369
9382
 
9370
9383
  // Free task closure and task node
9371
9384
  if (task->closure) {
@@ -9383,7 +9396,7 @@ ${l}
9383
9396
  // Final GC cleanup
9384
9397
  __yo_gc_collect();
9385
9398
 
9386
- ${u}
9399
+ ${c}
9387
9400
  }
9388
9401
 
9389
9402
  // Initialize the worker pool with the specified number of threads
@@ -9422,7 +9435,7 @@ static void __yo_worker_pool_init(size_t num_threads) {
9422
9435
  __yo_worker_thread_t* worker = &__yo_worker_threads[i];
9423
9436
  while (!worker->started) {
9424
9437
  // Busy wait with yield to let threads start
9425
- ${c}
9438
+ ${_}
9426
9439
  }
9427
9440
  }
9428
9441
 
@@ -9482,18 +9495,18 @@ static void __yo_worker_pool_shutdown(void) {
9482
9495
 
9483
9496
  // Get number of hardware threads (CPU cores)
9484
9497
  static size_t __yo_get_hardware_threads(void) {
9485
- ${m}
9498
+ ${g}
9486
9499
  }
9487
9500
 
9488
9501
  // Get CPU ID that the current thread is running on
9489
9502
  // Returns -1 if CPU affinity information is not available
9490
9503
  static int __yo_get_cpu_id(void) {
9491
- ${g}
9504
+ ${h}
9492
9505
  }
9493
9506
 
9494
9507
  // Set the number of worker threads (must be called before first spawn)
9495
9508
  static void __yo_worker_set_num_threads(size_t num) {
9496
- ${f}
9509
+ ${m}
9497
9510
  __YO_THREAD_SYNC_LOCK(&__yo_worker_pool_mutex);
9498
9511
  if (!__yo_worker_pool_initialized) {
9499
9512
  // Pool not initialized yet, just set for later
@@ -9507,7 +9520,7 @@ static void __yo_worker_set_num_threads(size_t num) {
9507
9520
 
9508
9521
  // Get the number of worker threads
9509
9522
  static size_t __yo_worker_get_num_threads(void) {
9510
- ${f}
9523
+ ${m}
9511
9524
  __YO_THREAD_SYNC_LOCK(&__yo_worker_pool_mutex);
9512
9525
  size_t num = __yo_worker_num_threads;
9513
9526
  if (num == 0) {
@@ -9520,7 +9533,7 @@ static size_t __yo_worker_get_num_threads(void) {
9520
9533
  // Spawn a task on the worker pool
9521
9534
  // Uses round-robin distribution for thread affinity
9522
9535
  static void __yo_worker_spawn(__yo_thread_fn fn, void* closure) {
9523
- ${f}
9536
+ ${m}
9524
9537
  __YO_THREAD_SYNC_LOCK(&__yo_worker_pool_mutex);
9525
9538
 
9526
9539
  // Initialize pool on first spawn if not already done
@@ -9559,7 +9572,7 @@ static void __yo_worker_spawn(__yo_thread_fn fn, void* closure) {
9559
9572
  __yo_cond_signal(&worker->cond);
9560
9573
  __yo_mutex_unlock(&worker->mutex);
9561
9574
  }
9562
- `)}function dl(e){let t=e.emitter,n=!1;for(let r in e.types){let{type:i,cName:o}=e.types[r];if(!("requiredTraits"in i&&"negativeTraits"in i))continue;n||(t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Type Forward Declarations ==="),n=!0);let a=`${o}_vtable`;t.emitDeclarationLine(`typedef struct ${a}_s ${a};`),t.emitDeclarationLine(`typedef struct { // ${i.typeName||"Dyn"} : ${A(i)} (value type - fat pointer)`),t.emitDeclarationLine(" void* data; // Pointer to boxed data (with __yo_ref_header_t)"),t.emitDeclarationLine(` const ${a}* vtable; // Pointer to static vtable (no allocation needed)`),t.emitDeclarationLine(`} ${o};`),t.emitDeclarationLine("")}}function ml(e,t,n){let r=n.emitter,i=`${t}_vtable`;r.emitDeclarationLine(`typedef struct ${i}_s { // Vtable for ${A(e)}`),r.emitDeclarationLine(" uintptr_t __yo_type_id; // Runtime type identity (address of unique static per concrete type)");let o=new Set,a=new Set([k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]]);for(let{traitType:s}of e.requiredTraits){if(bt(s)){let l=s.isFn.callType,u=P(l.return.type,n),c=l.parameters.map(_=>{let p=P(_.type,n),f=te(_.label);return`${p} ${f}`}).join(", ");r.emitDeclarationLine(` ${u} (*call)(void* self${c?", "+c:""}); // Call function pointer`),o.add("call");continue}for(let l of s.fields){if(l.label==="Self"||a.has(l.label)||o.has(l.label))continue;o.add(l.label);let u=te(l.label);if(G(l.type)){let c=l.type;if(c.parameters.length>0){let _=c.parameters[0];if(_&&_.label==="self"){let p=P(c.return.type,n),f=c.parameters.map((m,g)=>{if(g===0)return"void* self";{let h=P(m.type,n),d=te(m.label);return`${h} ${d}`}}).join(", ");r.emitDeclarationLine(` ${p} (*${u})(${f}); // Method pointer for ${l.label}`)}}}else{let c=P(l.type,n);r.emitDeclarationLine(` ${c} ${u}; // Non-function member ${l.label}`)}}}r.emitDeclarationLine(`} ${i};`),r.emitDeclarationLine("")}function yl(e){let t=e.emitter;if(e.dynImpls.size===0)return;t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Box Types ==="),t.emitDeclarationLine("// These structs wrap concrete types for dynamic dispatch"),t.emitDeclarationLine("");let n=new Set;for(let[,r]of e.dynImpls){let i=x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType,a=`__yo_dyn_box_${e.types[i.id]?.cName||`unknown_${i.id}`}`;if(n.has(a))continue;n.add(a);let s=P(i,e);t.emitDeclarationLine("typedef struct {"),t.emitDeclarationLine(" __yo_ref_header_t header;"),t.emitDeclarationLine(` ${s} value;`),t.emitDeclarationLine(`} ${a};`),t.emitDeclarationLine(""),t.emitDeclarationLine(`static ${a}* __yo_new_${a}(${s} value);`),t.emitDeclarationLine(`static void __yo_dispose_${a}(void* ptr);`),t.emitDeclarationLine("")}}function n_(e){let t=e.debugGc?"#define __YO_DEBUG_GC 1":"// #define __YO_DEBUG_GC 1",n=e.debugParallelism?"#define __YO_DEBUG_PARALLELISM 1":"// #define __YO_DEBUG_PARALLELISM 1",r=e.debugAsyncAwait?"#define __YO_DEBUG_ASYNC_AWAIT 1":"// #define __YO_DEBUG_ASYNC_AWAIT 1";e.emitter.emitDeclarationLine(`// Non-atomic Reference Counting with Thread-Local Cycle Collection
9575
+ `)}function dl(e){let t=e.emitter,n=!1;for(let r in e.types){let{type:i,cName:o}=e.types[r];if(!("requiredTraits"in i&&"negativeTraits"in i))continue;n||(t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Type Forward Declarations ==="),n=!0);let a=`${o}_vtable`;t.emitDeclarationLine(`typedef struct ${a}_s ${a};`),t.emitDeclarationLine(`typedef struct { // ${i.typeName||"Dyn"} : ${A(i)} (value type - fat pointer)`),t.emitDeclarationLine(" void* data; // Pointer to boxed data (with __yo_ref_header_t)"),t.emitDeclarationLine(` const ${a}* vtable; // Pointer to static vtable (no allocation needed)`),t.emitDeclarationLine(`} ${o};`),t.emitDeclarationLine("")}}function ml(e,t,n){let r=n.emitter,i=`${t}_vtable`;r.emitDeclarationLine(`typedef struct ${i}_s { // Vtable for ${A(e)}`),r.emitDeclarationLine(" uintptr_t __yo_type_id; // Runtime type identity (address of unique static per concrete type)");let o=new Set,a=new Set([k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]]);for(let{traitType:s}of e.requiredTraits){if(kt(s)){let l=s.isFn.callType,u=P(l.return.type,n),c=l.parameters.map(_=>{let p=P(_.type,n),f=te(_.label);return`${p} ${f}`}).join(", ");r.emitDeclarationLine(` ${u} (*call)(void* self${c?", "+c:""}); // Call function pointer`),o.add("call");continue}for(let l of s.fields){if(l.label==="Self"||a.has(l.label)||o.has(l.label))continue;o.add(l.label);let u=te(l.label);if(G(l.type)){let c=l.type;if(c.parameters.length>0){let _=c.parameters[0];if(_&&_.label==="self"){let p=P(c.return.type,n),f=c.parameters.map((m,g)=>{if(g===0)return"void* self";{let h=P(m.type,n),d=te(m.label);return`${h} ${d}`}}).join(", ");r.emitDeclarationLine(` ${p} (*${u})(${f}); // Method pointer for ${l.label}`)}}}else{let c=P(l.type,n);r.emitDeclarationLine(` ${c} ${u}; // Non-function member ${l.label}`)}}}r.emitDeclarationLine(`} ${i};`),r.emitDeclarationLine("")}function yl(e){let t=e.emitter;if(e.dynImpls.size===0)return;t.emitDeclarationLine(""),t.emitDeclarationLine("// === Dyn Box Types ==="),t.emitDeclarationLine("// These structs wrap concrete types for dynamic dispatch"),t.emitDeclarationLine("");let n=new Set;for(let[,r]of e.dynImpls){let i=x(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType,a=`__yo_dyn_box_${e.types[i.id]?.cName||`unknown_${i.id}`}`;if(n.has(a))continue;n.add(a);let s=P(i,e);t.emitDeclarationLine("typedef struct {"),t.emitDeclarationLine(" __yo_ref_header_t header;"),t.emitDeclarationLine(` ${s} value;`),t.emitDeclarationLine(`} ${a};`),t.emitDeclarationLine(""),t.emitDeclarationLine(`static ${a}* __yo_new_${a}(${s} value);`),t.emitDeclarationLine(`static void __yo_dispose_${a}(void* ptr);`),t.emitDeclarationLine("")}}function n_(e){let t=e.debugGc?"#define __YO_DEBUG_GC 1":"// #define __YO_DEBUG_GC 1",n=e.debugParallelism?"#define __YO_DEBUG_PARALLELISM 1":"// #define __YO_DEBUG_PARALLELISM 1",r=e.debugAsyncAwait?"#define __YO_DEBUG_ASYNC_AWAIT 1":"// #define __YO_DEBUG_ASYNC_AWAIT 1";e.emitter.emitDeclarationLine(`// Non-atomic Reference Counting with Thread-Local Cycle Collection
9563
9576
  // Based on QuickJS trial deletion algorithm
9564
9577
  // See CYCLE_COLLECTION.md for design details
9565
9578
 
@@ -9601,7 +9614,7 @@ typedef enum {
9601
9614
 
9602
9615
  // GC flags
9603
9616
  #define __YO_GC_TRACKED 0x01 // Object is tracked by GC (might participate in cycles)
9604
- `),zt(e.targetInfo)?e.emitter.emitDeclarationLine(`// Thread synchronization for stop-the-world GC (Windows)
9617
+ `),Pt(e.targetInfo)?e.emitter.emitDeclarationLine(`// Thread synchronization for stop-the-world GC (Windows)
9605
9618
  #ifndef WIN32_LEAN_AND_MEAN
9606
9619
  #define WIN32_LEAN_AND_MEAN
9607
9620
  #endif
@@ -9740,7 +9753,7 @@ typedef struct __yo_io_future_t {
9740
9753
  } __yo_io_future_t;
9741
9754
 
9742
9755
  // Forward declarations will be added here if needed
9743
- `);for(let p in e.types){let{type:f,cName:m}=e.types[p];if(!Fe(f)&&!(f.isExtern==="c"&&f.externName)){if(Kt(f))e.emitter.emitDeclarationLine(`typedef struct ${m}_struct ${m}; // Forward declaration`);else if(ce(f)){if(f.isNewtype&&f.fields.length===1)continue;e.emitter.emitDeclarationLine(`typedef struct ${m}_struct ${m}; // Forward declaration`)}else if(ge(f)){let g=Yt(f),h=Fn(f);!g&&!h&&e.emitter.emitDeclarationLine(`typedef struct ${m}_struct ${m}; // Forward declaration`)}}}e.emitter.emitDeclarationLine(""),Yy(e),Hy(e),hl(e),jy(e);for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||ge(f)&&Fn(f)&&gl(f,m,e)}let i=[];for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||(ce(f)?i.push({typeId:p,type:f,cName:m,kind:"struct"}):ge(f)&&!Fn(f)&&!Yt(f)?i.push({typeId:p,type:f,cName:m,kind:"enum"}):we(f)&&i.push({typeId:p,type:f,cName:m,kind:"tuple"}))}let o=new Map,a=new Map(i.map(p=>[p.typeId,p])),s=new Map(i.map(p=>[p.cName,p.typeId]));function l(p){if(Ie(p)){let m=p.childType;if(ce(m)&&m.isNewtype)return m}else if(ge(p)){let f=Yt(p);if(f&&Ie(f)){let g=f.childType;if(ce(g)&&g.isNewtype)return g}}return null}for(let{typeId:p,type:f,kind:m}of i)if(o.set(p,new Set),m==="struct"&&ce(f))for(let g of f.fields){let h=g.type;x(h)&&h.resolvedConcreteType&&(h=h.resolvedConcreteType);let d=l(h);if(d){let v=P(d,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}if(ge(h)){if(!Yt(h)){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}}else if(ce(h)&&h.isNewtype){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}else if(ce(h)&&!h.isReferenceSemantics&&!h.isNewtype){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}else if(we(h)){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}}else if(m==="enum"&&ge(f)){for(let g of f.variants)if(g.fields){for(let h of g.fields)if(ge(h.type)){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}else if(ce(h.type)&&h.type.isNewtype){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}else if(we(h.type)){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}else if(ce(h.type)&&!h.type.isReferenceSemantics&&!h.type.isNewtype){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}}}else if(m==="tuple"&&we(f)){for(let g of f.fields)if(we(g.type)){let h=P(g.type,e),d=s.get(h);d&&d!==p&&a.has(d)&&o.get(p).add(d)}else if(ge(g.type)){let h=P(g.type,e),d=s.get(h);d&&d!==p&&a.has(d)&&o.get(p).add(d)}else if(ce(g.type)&&!g.type.isReferenceSemantics&&!g.type.isNewtype){let h=P(g.type,e),d=s.get(h);d&&d!==p&&a.has(d)&&o.get(p).add(d)}}let u=new Map;for(let[p,f]of o)u.set(p,f.size);let c=[];for(let[p,f]of u)f===0&&c.push(p);let _=[];for(;c.length>0;){let p=c.shift(),f=a.get(p);_.push({type:f.type,cName:f.cName,kind:f.kind});for(let[m,g]of o)if(g.has(p)){let h=(u.get(m)||1)-1;u.set(m,h),h===0&&c.push(m)}}if(_.length<i.length)for(let p of i)_.find(f=>f.cName===p.cName)||_.push({type:p.type,cName:p.cName,kind:p.kind});dl(e);for(let{type:p,cName:f,kind:m}of _)m==="struct"&&ce(p)?Xy(p,f,e):m==="enum"&&ge(p)?gl(p,f,e):m==="tuple"&&we(p)&&Qy(p,f,e);for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||ge(f)&&Yt(f)&&gl(f,m,e)}for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||(be(f)?ml(f,m,e):it(f)&&Zy(f,m,e))}Ky(e)}function Yy(e){let t=e.emitter;for(let[n,{childType:r,length:i}]of e.arrayStructTypes)t.emitDeclarationLine("typedef struct { // Array wrapper struct"),t.emitDeclarationLine(` ${r} data[${i}];`),t.emitDeclarationLine(`} ${n};`),t.emitDeclarationLine("")}function Hy(e){let t=e.emitter;for(let[n,{childType:r}]of e.sliceStructTypes)t.emitDeclarationLine("typedef struct { // Slice wrapper struct"),t.emitDeclarationLine(` ${r}* data;`),t.emitDeclarationLine(" size_t length;"),t.emitDeclarationLine(`} ${n};`),t.emitDeclarationLine("")}function hl(e){let t=e.emitter;if(e.isoTypes){for(let[n,r]of e.isoTypes){let{childTypeCName:i,structGenerated:o}=r;o||(t.emitDeclarationLine("typedef struct { // Iso wrapper struct"),t.emitDeclarationLine(" __yo_ref_header_t header; // Atomic RC header"),t.emitDeclarationLine(" _Atomic bool extracted; // Extraction flag"),t.emitDeclarationLine(` ${i} value; // Inner value`),t.emitDeclarationLine(`} ${n}_struct;`),t.emitDeclarationLine(`typedef ${n}_struct* ${n};`),t.emitDeclarationLine(""),t.emitDeclarationLine(`${n} __yo_create_iso_${n}(${i} value);`),t.emitDeclarationLine(""),r.structGenerated=!0)}for(let[n,r]of e.isoTypes){let{optionTypeCName:i,extractGenerated:o}=r;o||!i||t.emitDeclarationLine(`${i} __yo_iso_extract_${n}(${n} iso);`)}for(let[n,r]of e.isoTypes){let{structGenerated:i}=r;i&&(t.emitDeclarationLine(`void __yo_iso_dispose_${n}(${n} iso);`),t.emitDeclarationLine(`static void __yo_dispose_iso_${n}(void* ptr);`))}for(let[n,r]of e.isoTypes){let{childTypeCName:i,createGenerated:o}=r;o||(t.emitLine(`
9756
+ `);for(let p in e.types){let{type:f,cName:m}=e.types[p];if(!Fe(f)&&!(f.isExtern==="c"&&f.externName)){if(Kt(f))e.emitter.emitDeclarationLine(`typedef struct ${m}_struct ${m}; // Forward declaration`);else if(ce(f)){if(f.isNewtype&&f.fields.length===1)continue;e.emitter.emitDeclarationLine(`typedef struct ${m}_struct ${m}; // Forward declaration`)}else if(ge(f)){let g=Yt(f),h=Fn(f);!g&&!h&&e.emitter.emitDeclarationLine(`typedef struct ${m}_struct ${m}; // Forward declaration`)}}}e.emitter.emitDeclarationLine(""),Hy(e),jy(e),hl(e),Ky(e);for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||ge(f)&&Fn(f)&&gl(f,m,e)}let i=[];for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||(ce(f)?i.push({typeId:p,type:f,cName:m,kind:"struct"}):ge(f)&&!Fn(f)&&!Yt(f)?i.push({typeId:p,type:f,cName:m,kind:"enum"}):we(f)&&i.push({typeId:p,type:f,cName:m,kind:"tuple"}))}let o=new Map,a=new Map(i.map(p=>[p.typeId,p])),s=new Map(i.map(p=>[p.cName,p.typeId]));function l(p){if(Ie(p)){let m=p.childType;if(ce(m)&&m.isNewtype)return m}else if(ge(p)){let f=Yt(p);if(f&&Ie(f)){let g=f.childType;if(ce(g)&&g.isNewtype)return g}}return null}for(let{typeId:p,type:f,kind:m}of i)if(o.set(p,new Set),m==="struct"&&ce(f))for(let g of f.fields){let h=g.type;x(h)&&h.resolvedConcreteType&&(h=h.resolvedConcreteType);let d=l(h);if(d){let v=P(d,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}if(ge(h)){if(!Yt(h)){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}}else if(ce(h)&&h.isNewtype){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}else if(ce(h)&&!h.isReferenceSemantics&&!h.isNewtype){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}else if(we(h)){let v=P(h,e),T=s.get(v);T&&T!==p&&a.has(T)&&o.get(p).add(T)}}else if(m==="enum"&&ge(f)){for(let g of f.variants)if(g.fields){for(let h of g.fields)if(ge(h.type)){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}else if(ce(h.type)&&h.type.isNewtype){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}else if(we(h.type)){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}else if(ce(h.type)&&!h.type.isReferenceSemantics&&!h.type.isNewtype){let d=P(h.type,e),v=s.get(d);v&&v!==p&&a.has(v)&&o.get(p).add(v)}}}else if(m==="tuple"&&we(f)){for(let g of f.fields)if(we(g.type)){let h=P(g.type,e),d=s.get(h);d&&d!==p&&a.has(d)&&o.get(p).add(d)}else if(ge(g.type)){let h=P(g.type,e),d=s.get(h);d&&d!==p&&a.has(d)&&o.get(p).add(d)}else if(ce(g.type)&&!g.type.isReferenceSemantics&&!g.type.isNewtype){let h=P(g.type,e),d=s.get(h);d&&d!==p&&a.has(d)&&o.get(p).add(d)}}let u=new Map;for(let[p,f]of o)u.set(p,f.size);let c=[];for(let[p,f]of u)f===0&&c.push(p);let _=[];for(;c.length>0;){let p=c.shift(),f=a.get(p);_.push({type:f.type,cName:f.cName,kind:f.kind});for(let[m,g]of o)if(g.has(p)){let h=(u.get(m)||1)-1;u.set(m,h),h===0&&c.push(m)}}if(_.length<i.length)for(let p of i)_.find(f=>f.cName===p.cName)||_.push({type:p.type,cName:p.cName,kind:p.kind});dl(e);for(let{type:p,cName:f,kind:m}of _)m==="struct"&&ce(p)?Qy(p,f,e):m==="enum"&&ge(p)?gl(p,f,e):m==="tuple"&&we(p)&&Zy(p,f,e);for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||ge(f)&&Yt(f)&&gl(f,m,e)}for(let p in e.types){let{type:f,cName:m}=e.types[p];Fe(f)||f.isExtern==="c"&&f.externName||(be(f)?ml(f,m,e):it(f)&&Jy(f,m,e))}Xy(e)}function Hy(e){let t=e.emitter;for(let[n,{childType:r,length:i}]of e.arrayStructTypes)t.emitDeclarationLine("typedef struct { // Array wrapper struct"),t.emitDeclarationLine(` ${r} data[${i}];`),t.emitDeclarationLine(`} ${n};`),t.emitDeclarationLine("")}function jy(e){let t=e.emitter;for(let[n,{childType:r}]of e.sliceStructTypes)t.emitDeclarationLine("typedef struct { // Slice wrapper struct"),t.emitDeclarationLine(` ${r}* data;`),t.emitDeclarationLine(" size_t length;"),t.emitDeclarationLine(`} ${n};`),t.emitDeclarationLine("")}function hl(e){let t=e.emitter;if(e.isoTypes){for(let[n,r]of e.isoTypes){let{childTypeCName:i,structGenerated:o}=r;o||(t.emitDeclarationLine("typedef struct { // Iso wrapper struct"),t.emitDeclarationLine(" __yo_ref_header_t header; // Atomic RC header"),t.emitDeclarationLine(" _Atomic bool extracted; // Extraction flag"),t.emitDeclarationLine(` ${i} value; // Inner value`),t.emitDeclarationLine(`} ${n}_struct;`),t.emitDeclarationLine(`typedef ${n}_struct* ${n};`),t.emitDeclarationLine(""),t.emitDeclarationLine(`${n} __yo_create_iso_${n}(${i} value);`),t.emitDeclarationLine(""),r.structGenerated=!0)}for(let[n,r]of e.isoTypes){let{optionTypeCName:i,extractGenerated:o}=r;o||!i||t.emitDeclarationLine(`${i} __yo_iso_extract_${n}(${n} iso);`)}for(let[n,r]of e.isoTypes){let{structGenerated:i}=r;i&&(t.emitDeclarationLine(`void __yo_iso_dispose_${n}(${n} iso);`),t.emitDeclarationLine(`static void __yo_dispose_iso_${n}(void* ptr);`))}for(let[n,r]of e.isoTypes){let{childTypeCName:i,createGenerated:o}=r;o||(t.emitLine(`
9744
9757
  ${n} __yo_create_iso_${n}(${i} value) {
9745
9758
  ${n} iso = (${n})__yo_malloc(sizeof(${n}_struct));
9746
9759
  iso->header.ref_count = 1;
@@ -9773,7 +9786,7 @@ ${i} __yo_iso_extract_${n}(${n} iso) {
9773
9786
  result.data.Some.value = iso->value;
9774
9787
  }
9775
9788
  return result;
9776
- }`)}r.extractGenerated=!0}}}}function jy(e){let t=e.emitter;if(e.arcTypes)for(let[n,r]of e.arcTypes)r.structGenerated||(t.emitDeclarationLine(`typedef struct ${n}_struct ${n}_struct;`),t.emitDeclarationLine(`typedef ${n}_struct* ${n};`),t.emitDeclarationLine(""))}function Ky(e){let t=e.emitter;if(e.arcTypes){for(let[n,r]of e.arcTypes){let{childTypeCName:i}=r;r.structGenerated||(t.emitDeclarationLine(`struct ${n}_struct { // Arc wrapper`),t.emitDeclarationLine(" __yo_ref_header_t header; // Atomic RC header"),t.emitDeclarationLine(` ${i} value; // Inner value`),t.emitDeclarationLine("};"),t.emitDeclarationLine(""),t.emitDeclarationLine(`${n} __yo_create_arc_${n}(${i} value);`),t.emitDeclarationLine(""),r.structGenerated=!0)}for(let[n,r]of e.arcTypes)r.structGenerated&&(t.emitDeclarationLine(`void __yo_arc_dispose_${n}(${n} arc);`),t.emitDeclarationLine(`static void __yo_dispose_arc_${n}(void* ptr);`));for(let[n,r]of e.arcTypes){let{childTypeCName:i,createGenerated:o}=r;o||(t.emitLine(`
9789
+ }`)}r.extractGenerated=!0}}}}function Ky(e){let t=e.emitter;if(e.arcTypes)for(let[n,r]of e.arcTypes)r.structGenerated||(t.emitDeclarationLine(`typedef struct ${n}_struct ${n}_struct;`),t.emitDeclarationLine(`typedef ${n}_struct* ${n};`),t.emitDeclarationLine(""))}function Xy(e){let t=e.emitter;if(e.arcTypes){for(let[n,r]of e.arcTypes){let{childTypeCName:i}=r;r.structGenerated||(t.emitDeclarationLine(`struct ${n}_struct { // Arc wrapper`),t.emitDeclarationLine(" __yo_ref_header_t header; // Atomic RC header"),t.emitDeclarationLine(` ${i} value; // Inner value`),t.emitDeclarationLine("};"),t.emitDeclarationLine(""),t.emitDeclarationLine(`${n} __yo_create_arc_${n}(${i} value);`),t.emitDeclarationLine(""),r.structGenerated=!0)}for(let[n,r]of e.arcTypes)r.structGenerated&&(t.emitDeclarationLine(`void __yo_arc_dispose_${n}(${n} arc);`),t.emitDeclarationLine(`static void __yo_dispose_arc_${n}(void* ptr);`));for(let[n,r]of e.arcTypes){let{childTypeCName:i,createGenerated:o}=r;o||(t.emitLine(`
9777
9790
  ${n} __yo_create_arc_${n}(${i} value) {
9778
9791
  ${n} arc = (${n})__yo_malloc(sizeof(${n}_struct));
9779
9792
  arc->header.ref_count = 1;
@@ -9788,7 +9801,7 @@ void __yo_arc_dispose_${n}(${n} arc) {
9788
9801
  }`),t.emitLine(`
9789
9802
  static void __yo_dispose_arc_${n}(void* ptr) {
9790
9803
  __yo_arc_dispose_${n}((${n})ptr);
9791
- }`),r.disposeGenerated=!0}}}function Xy(e,t,n){let r=n.emitter;if(e.isNewtype&&e.fields.length===1){let i=e.fields[0].type,o=P(i,n);r.emitDeclarationLine(`typedef ${o} ${t}; // ${e.typeName} : ${A(e)} (newtype - zero-cost abstraction)`),r.emitDeclarationLine("");return}if(e.isReferenceSemantics){r.emitDeclarationLine(`struct ${t}_struct { // ${e.typeName} : ${A(e)} (reference counted)`),r.emitDeclarationLine(" __yo_ref_header_t header; // Reference count header");for(let i of e.fields){let o=P(i.type,n),a=te(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine("};")}else{r.emitDeclarationLine(`struct ${t}_struct { // ${e.typeName} : ${A(e)}`);for(let i of e.fields){let o=P(i.type,n),a=te(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine("};")}r.emitDeclarationLine("")}function Qy(e,t,n){let r=n.emitter;if(r.emitDeclarationLine(`typedef struct { // ${e.typeName} : ${A(e)}`),e.fields.length===0)r.emitDeclarationLine(" uint8_t _dummy; // zero-sized type marker");else for(let i=0;i<e.fields.length;i++){let o=e.fields[i],a=P(o.type,n),s=`_${i}`;r.emitDeclarationLine(` ${a} ${s};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function Zy(e,t,n){let r=n.emitter;r.emitDeclarationLine(`typedef union { // ${e.typeName} : ${A(e)}`);for(let i of e.fields){let o=P(i.type,n),a=te(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function gl(e,t,n){let r=n.emitter,i=Yt(e);if(i){let l=P(i,n);r.emitDeclarationLine(`typedef ${l} ${t}; // ${e.typeName} : ${A(e)} (optimized as nullable pointer)`),r.emitDeclarationLine("");return}if(Fn(e)){r.emitDeclarationLine(`typedef enum { // ${e.typeName} : ${A(e)} (optimized as simple enum)`);for(let l=0;l<e.variants.length;l++){let u=e.variants[l];if(u){let c=Bt(e,u.name,n),_=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${c} = ${p}${_}`)}}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("");return}let a=`${t}_tag`;r.emitDeclarationLine("typedef enum {");for(let l=0;l<e.variants.length;l++){let u=e.variants[l];if(u){let c=Bt(e,u.name,n),_=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${c} = ${p}${_}`)}}r.emitDeclarationLine(`} ${a};`),r.emitDeclarationLine("");let s=`${t}_data`;r.emitDeclarationLine("typedef union {");for(let l of e.variants)if(l.fields&&l.fields.length>0){let u=l.fields.filter(c=>!pe(c.type));if(u.length>0){let c=l.name;r.emitDeclarationLine(" struct {");for(let _ of u){let p=P(_.type,n),f=te(_.label);r.emitDeclarationLine(` ${p} ${f};`)}r.emitDeclarationLine(` } ${c};`)}}r.emitDeclarationLine(`} ${s};`),r.emitDeclarationLine(""),r.emitDeclarationLine(`struct ${t}_struct { // ${e.typeName} : ${A(e)}`),r.emitDeclarationLine(` ${a} tag;`),r.emitDeclarationLine(` ${s} data;`),r.emitDeclarationLine("};"),r.emitDeclarationLine("")}function Jy(e,t){let n=Vn(t,"Dispose");if(!n)return;let r={...n,receiverType:e};if(e.trait)for(let o of e.trait.fields){if(!o.assignedValue||!Tt(o.assignedValue))continue;let a=o.assignedValue,s=a.type;if(Y({type:r,env:t},{type:s,env:t}))return a}let i=Va({concreteType:e,traitType:n,env:t});if(i)return i.traitValue}function eg(e,t,n){let r=Jy(e,t);if(!r)return;let i=r.type.fields.findIndex(s=>s.label===k.dispose[0]);if(i<0)return;let o=r.fields[i];if(!ne(o))return;let a=n.functions[o.funcId]?.cName;if(a)return a;for(let s in n.functions){let l=n.functions[s],u=l.value,c=u.specializedType??u.type;if(u.funcName===k.dispose[0]&&c.SelfType&&Y({type:c.SelfType,env:t},{type:e,env:t}))return l.cName}}function r_(e){e.emitter.emitLine("// Function implementations"),Xc(e.emitter,e.targetInfo),e.usesAsync&&Zc(e.emitter,e.targetInfo,e.debugAsyncAwait),e.usesParallelism&&t_(e.emitter,e.debugParallelism,e.targetInfo),ng(e),ig(e);for(let t in e.functions){let{value:n,cName:r}=e.functions[t],i=r==="__yo_user_main",o=n.body?.$?.effectAnalysis,a=o&&o.hasEffects;if(!i&&!n.type.isClosure&&n.specializedFunctionCaches?.length>0||!i&&!a&&!n.isModuleEffectMember&&!n.type.isClosure&&!n.specializedType&&(n.specializedFunctionCaches?.length??0)===0&&Ft(n.specializedType??n.type).length===0&&[...n.type.implicitParameters,...n.type.parameters.filter(d=>d.isImplicit)].some(d=>G(d.type)))continue;let l=n.specializedType&&!Pn(n.type),u=n.specializedType??n.type,c=Ft(u).length>0,_=n.type.parameters.some(d=>d.isCompileTimeOnly);if(!i&&(!n.isModuleEffectMember||_)&&!n.specializedType&&(n.specializedFunctionCaches?.length??0)===0&&(sr(n.type)||Wr(n))||!i&&n.isIoAsyncStateMachineClosure||!i&&!a&&!c&&!n.isModuleEffectMember&&(sr(n.type)&&!n.type.isClosure||n.specializedFunctionCaches?.length>0&&!n.type.isClosure||n.specializedType&&!l||Wr(n)||Ki(n)||n.isIoAsyncStateMachineClosure))continue;let p=n.specializedType??n.type,f=!a&&!n.isModuleEffectMember&&(p.parameters.some(d=>Fe(d.type))||p.forallParameters.length>0),m=Fe(p.return.type),g=x(p.return.type)&&p.return.type.requiredTraits.length>0;if(f||m&&!g&&!n.isModuleEffectMember)continue;let h=n.body?.$?.effectAnalysis;h&&h.hasEffects,a_(n,r,e)}hl(e)}function i_(e){let t=e.emitter,n=!1,r=null;for(let a in e.functions){let{cName:s,value:l}=e.functions[a];if(s==="__yo_user_main"){n=!0,r=l;break}}if(!n||!r)return;let i=r.type.return.type;if(!pe(i))throw new Error(`main function must return unit , but it returns ${A(i)}. Use 'main :: (fn() -> unit)' instead. For exit codes, use 'exit(code)' from std/libc/stdlib.yo`);{let s=Ft(r.type).map(()=>"NULL").join(", "),l=s?`(${s})`:"()",u=e.usesAsync?`
9804
+ }`),r.disposeGenerated=!0}}}function Qy(e,t,n){let r=n.emitter;if(e.isNewtype&&e.fields.length===1){let i=e.fields[0].type,o=P(i,n);r.emitDeclarationLine(`typedef ${o} ${t}; // ${e.typeName} : ${A(e)} (newtype - zero-cost abstraction)`),r.emitDeclarationLine("");return}if(e.isReferenceSemantics){r.emitDeclarationLine(`struct ${t}_struct { // ${e.typeName} : ${A(e)} (reference counted)`),r.emitDeclarationLine(" __yo_ref_header_t header; // Reference count header");for(let i of e.fields){let o=P(i.type,n),a=te(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine("};")}else{r.emitDeclarationLine(`struct ${t}_struct { // ${e.typeName} : ${A(e)}`);for(let i of e.fields){let o=P(i.type,n),a=te(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine("};")}r.emitDeclarationLine("")}function Zy(e,t,n){let r=n.emitter;if(r.emitDeclarationLine(`typedef struct { // ${e.typeName} : ${A(e)}`),e.fields.length===0)r.emitDeclarationLine(" uint8_t _dummy; // zero-sized type marker");else for(let i=0;i<e.fields.length;i++){let o=e.fields[i],a=P(o.type,n),s=`_${i}`;r.emitDeclarationLine(` ${a} ${s};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function Jy(e,t,n){let r=n.emitter;r.emitDeclarationLine(`typedef union { // ${e.typeName} : ${A(e)}`);for(let i of e.fields){let o=P(i.type,n),a=te(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function gl(e,t,n){let r=n.emitter,i=Yt(e);if(i){let l=P(i,n);r.emitDeclarationLine(`typedef ${l} ${t}; // ${e.typeName} : ${A(e)} (optimized as nullable pointer)`),r.emitDeclarationLine("");return}if(Fn(e)){r.emitDeclarationLine(`typedef enum { // ${e.typeName} : ${A(e)} (optimized as simple enum)`);for(let l=0;l<e.variants.length;l++){let u=e.variants[l];if(u){let c=Bt(e,u.name,n),_=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${c} = ${p}${_}`)}}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("");return}let a=`${t}_tag`;r.emitDeclarationLine("typedef enum {");for(let l=0;l<e.variants.length;l++){let u=e.variants[l];if(u){let c=Bt(e,u.name,n),_=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${c} = ${p}${_}`)}}r.emitDeclarationLine(`} ${a};`),r.emitDeclarationLine("");let s=`${t}_data`;r.emitDeclarationLine("typedef union {");for(let l of e.variants)if(l.fields&&l.fields.length>0){let u=l.fields.filter(c=>!pe(c.type));if(u.length>0){let c=l.name;r.emitDeclarationLine(" struct {");for(let _ of u){let p=P(_.type,n),f=te(_.label);r.emitDeclarationLine(` ${p} ${f};`)}r.emitDeclarationLine(` } ${c};`)}}r.emitDeclarationLine(`} ${s};`),r.emitDeclarationLine(""),r.emitDeclarationLine(`struct ${t}_struct { // ${e.typeName} : ${A(e)}`),r.emitDeclarationLine(` ${a} tag;`),r.emitDeclarationLine(` ${s} data;`),r.emitDeclarationLine("};"),r.emitDeclarationLine("")}function eg(e,t){let n=Vn(t,"Dispose");if(!n)return;let r={...n,receiverType:e};if(e.trait)for(let o of e.trait.fields){if(!o.assignedValue||!Tt(o.assignedValue))continue;let a=o.assignedValue,s=a.type;if(Y({type:r,env:t},{type:s,env:t}))return a}let i=Va({concreteType:e,traitType:n,env:t});if(i)return i.traitValue}function tg(e,t,n){let r=eg(e,t);if(!r)return;let i=r.type.fields.findIndex(s=>s.label===k.dispose[0]);if(i<0)return;let o=r.fields[i];if(!ne(o))return;let a=n.functions[o.funcId]?.cName;if(a)return a;for(let s in n.functions){let l=n.functions[s],u=l.value,c=u.specializedType??u.type;if(u.funcName===k.dispose[0]&&c.SelfType&&Y({type:c.SelfType,env:t},{type:e,env:t}))return l.cName}}function r_(e){e.emitter.emitLine("// Function implementations"),Xc(e.emitter,e.targetInfo),e.usesAsync&&Zc(e.emitter,e.targetInfo,e.debugAsyncAwait),e.usesParallelism&&t_(e.emitter,e.debugParallelism,e.targetInfo,e.usesAsync??!1),rg(e),og(e);for(let t in e.functions){let{value:n,cName:r}=e.functions[t],i=r==="__yo_user_main",o=n.body?.$?.effectAnalysis,a=o&&o.hasEffects;if(!i&&!n.type.isClosure&&n.specializedFunctionCaches?.length>0||!i&&!a&&!n.isModuleEffectMember&&!n.type.isClosure&&!n.specializedType&&(n.specializedFunctionCaches?.length??0)===0&&$t(n.specializedType??n.type).length===0&&[...n.type.implicitParameters,...n.type.parameters.filter(d=>d.isImplicit)].some(d=>G(d.type)))continue;let l=n.specializedType&&!Pn(n.type),u=n.specializedType??n.type,c=$t(u).length>0,_=n.type.parameters.some(d=>d.isCompileTimeOnly);if(!i&&(!n.isModuleEffectMember||_)&&!n.specializedType&&(n.specializedFunctionCaches?.length??0)===0&&(sr(n.type)||Wr(n))||!i&&n.isIoAsyncStateMachineClosure||!i&&!a&&!c&&!n.isModuleEffectMember&&(sr(n.type)&&!n.type.isClosure||n.specializedFunctionCaches?.length>0&&!n.type.isClosure||n.specializedType&&!l||Wr(n)||Ki(n)||n.isIoAsyncStateMachineClosure))continue;let p=n.specializedType??n.type,f=!a&&!n.isModuleEffectMember&&(p.parameters.some(d=>Fe(d.type))||p.forallParameters.length>0),m=Fe(p.return.type),g=x(p.return.type)&&p.return.type.requiredTraits.length>0;if(f||m&&!g&&!n.isModuleEffectMember)continue;let h=n.body?.$?.effectAnalysis;h&&h.hasEffects,a_(n,r,e)}hl(e)}function i_(e){let t=e.emitter,n=!1,r=null;for(let a in e.functions){let{cName:s,value:l}=e.functions[a];if(s==="__yo_user_main"){n=!0,r=l;break}}if(!n||!r)return;let i=r.type.return.type;if(!pe(i))throw new Error(`main function must return unit , but it returns ${A(i)}. Use 'main :: (fn() -> unit)' instead. For exit codes, use 'exit(code)' from std/libc/stdlib.yo`);{let s=$t(r.type).map(()=>"NULL").join(", "),l=s?`(${s})`:"()",u=e.usesAsync?`
9792
9805
  // Initialize async runtime
9793
9806
  __yo_async_scheduler_init();`:"",c=e.usesAsync?`
9794
9807
  // Wait for all async tasks to complete
@@ -9805,7 +9818,7 @@ int main(int argc, char** argv) {
9805
9818
  ${c}
9806
9819
  return 0;
9807
9820
  }
9808
- `)}}function o_(e){for(let t in e.functions){let{value:n}=e.functions[t];if(Wr(n))continue;let r=n.body?.$?.effectAnalysis;if(!r||!r.hasEffects)continue;if(n.specializedType){let a=n.specializedType,s=a.forallParameters.length>0||a.parameters.some(_=>_.isCompileTimeOnly),l=a.parameters.some(_=>!_.isCompileTimeOnly&&x(_.type)&&!Ce(_.type));if(s||l)continue;let u=n.specializedType.parameters.some(_=>Fe(_.type)),c=Fe(n.specializedType.return.type);if(u||c)continue}let i=Ft(n.specializedType??n.type);if(i.length===0&&n.specializedType){let a=Ft(n.type);a.some(s=>s.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0)&&(i=a)}i.length>0}}function a_(e,t,n){let r=n.emitter,i=t,o=e.specializedType??e.type,a;if(e.body&&Ce(o.return.type)){let L=qo(e.body);L?.$?.asyncStateMachineStructName?a=`${L.$.asyncStateMachineStructName}*`:e.body.$?.type&&x(e.body.$.type)&&Ce(e.body.$.type)&&(a=P(e.body.$.type,n))}e.body&&x(o.return.type)&&!Ce(o.return.type)&&!e.specializedType&&!e.isModuleEffectMember&&e.body.$?.type&&(a=P(e.body.$.type,n));let s=e.specializedType&&Ft(o).length===0&&Ft(e.type).some(L=>L.fieldFunctionType.forallParameters&&L.fieldFunctionType.forallParameters.length>0)?e.type:void 0,l=a?hr(o,t,n,a,s):hr(o,t,n,void 0,s),c=t==="__yo_user_main"||n.exportedFunctionLabels?.has(e.funcId)?"":"static ";r.emitLine(`${c}${l} {`);let _=n.currentFunctionName,p=n.currentFunctionType;n.currentFunctionName=i,n.currentFunctionType=o;let f=n.isModuleEffectMemberFunction,m=n.overrideReturnTypeStr;e.isModuleEffectMember&&(n.isModuleEffectMemberFunction=!0),n.overrideReturnTypeStr=a;let g=n.currentEvidenceParams,h=Ft(o);if(h.length===0&&e.specializedType){let L=Ft(e.type);L.some(b=>b.fieldFunctionType.forallParameters&&b.fieldFunctionType.forallParameters.length>0)&&(h=L)}if(h.length>0){let L=new Map;for(let b of h)L.set(`${b.implicitLabel}.${b.fieldLabel}`,b);n.currentEvidenceParams=L}let d=n.currentClosureCaptures,v=n.currentClosureCaptureFrameLevel,T=n.currentClosureType,$=n.currentClosureCaptureTypeCName;if(o.isClosure){let L=e.closureInfo;if(L){let b=L.closureType.isFn,R=L.captureType;if(n.currentClosureType=b.callType,R&&ce(R)&&R.fields.length>0){let N=R.fields.map(D=>D.label);n.currentClosureCaptures=N,n.currentClosureCaptureFrameLevel=e.frameLevel;let B=n.types[R.id]?.cName;B&&(n.currentClosureCaptureTypeCName=B)}}}if(e.funcName===k.___dispose[0]&&o.SelfType){let L=eg(o.SelfType,e.type.env,n);if(L){let b=o.parameters[0]?.label==="__yo_self"?"__yo_self":o.parameters[0]?.label??"__yo_self";r.emitLine(` ${L}(${b}); // Call user's dispose method`)}}tg(e.body,o," ",n),n.currentFunctionName=_,n.currentFunctionType=p,n.isModuleEffectMemberFunction=f,n.overrideReturnTypeStr=m,n.currentEvidenceParams=g,n.currentClosureCaptures=d,n.currentClosureCaptureFrameLevel=v,n.currentClosureType=T,n.currentClosureCaptureTypeCName=$,r.emitLine("}")}function tg(e,t,n,r){let i=r.emitter;if(F(e)&&E(e,I.begin)){let o=e.args;r.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]],r.consumedVarPendingDrops=[...e.$?.consumedVariableDropExpressions??[]];let a=!1;for(let s=0;s<o.length-1;s++){let l=o[s];E(l,I.return)&&(a=!0);let u=M(l,n,r);if(u&&(!l.$||!ut(l.$.env.modulePath,u))&&i.emitLine(`${n}${u};`),a)break;if(nt(l.$?.controlFlow)){a=!0;break}}if(!a&&o.length>0){let s=o[o.length-1];if(Ce(t.return.type)&&s){let u=Rt(s),c=s.$?.type,_=c&&Ce(c);if(u||_){let p=M(s,n,r);if(e.$?.deferredDropExpressions&&e.$.deferredDropExpressions.length>0&&c){let f=P(c,r),m=`_yo_async_return_${Math.random().toString(36).substr(2,9)}`;i.emitLine(`${n}${f} ${m} = ${p};`),Ct(e,n,r),i.emitLine(`${n}return ${m};`)}else i.emitLine(`${n}return ${p};`);return}}else if(s&&pe(t.return.type)){let u=M(s,n,r);u&&i.emitLine(`${n}${u};`),Ct(e,n,r)}else if(s){let u=nt(s.$?.controlFlow),c=pe(s.$?.type)||F(s)&&E(s,I.tuple)&&s.args.length===0,_=o.length>1?o[o.length-2]:null,p=nt(_?.$?.controlFlow);if(!(c&&p))if(u){let f=M(s,n,r);f&&i.emitLine(`${n}${f};`)}else{if(s.$?.deferredDupExpressions&&s.$.deferredDupExpressions.length>0){if(s.$?.variableName){let g=P(t.return.type,r),h=Ee(s.$.variableName,s.$.env),d=M(s,n,r);h!==d&&i.emitLine(`${n}${g} ${h} = ${d};`)}rt(s,n,r);let m=s.$.deferredDupExpressions[0];if(F(m)&&m.$?.variableName){let g=te(m.$.variableName);Ct(e,n,r),i.emitLine(`${n}return ${g};`);return}}let f=M(s,n,r);Ct(e,n,r),f&&i.emitLine(`${n}return ${f};`)}}}else if(a&&o.length>0){let s=o[o.length-1];s&&pe(s.$?.type)}}else if(Ct(e,n,r),pe(t.return.type)){let o=M(e,n,r);o&&i.emitLine(`${n}${o};`)}else e_(e,n,r)}function s_(e){for(let t in e.functions){let{value:n,cName:r}=e.functions[t];if(Wr(n)||!n.specializedType||!Pn(n.type))continue;let i=n.specializedType,o=i.forallParameters.length>0||i.parameters.some(_=>_.isCompileTimeOnly),a=i.parameters.some(_=>!_.isCompileTimeOnly&&x(_.type)&&!Ce(_.type));if(o||a)continue;let s=n.specializedType.parameters.some(_=>Fe(_.type)),l=Fe(n.specializedType.return.type);if(s||l)continue;let u=n.body?.$?.effectAnalysis;u&&u.hasEffects||n.isModuleEffectMember||Ft(n.specializedType??n.type).length>0||a_(n,r,e)}}function ng(e){let t=e.emitter;t.emitLine(`// Non-atomic reference counting functions (thread-local)
9821
+ `)}}function o_(e){for(let t in e.functions){let{value:n}=e.functions[t];if(Wr(n))continue;let r=n.body?.$?.effectAnalysis;if(!r||!r.hasEffects)continue;if(n.specializedType){let a=n.specializedType,s=a.forallParameters.length>0||a.parameters.some(_=>_.isCompileTimeOnly),l=a.parameters.some(_=>!_.isCompileTimeOnly&&x(_.type)&&!Ce(_.type));if(s||l)continue;let u=n.specializedType.parameters.some(_=>Fe(_.type)),c=Fe(n.specializedType.return.type);if(u||c)continue}let i=$t(n.specializedType??n.type);if(i.length===0&&n.specializedType){let a=$t(n.type);a.some(s=>s.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0)&&(i=a)}i.length>0}}function a_(e,t,n){let r=n.emitter,i=t,o=e.specializedType??e.type,a;if(e.body&&Ce(o.return.type)){let L=qo(e.body);L?.$?.asyncStateMachineStructName?a=`${L.$.asyncStateMachineStructName}*`:e.body.$?.type&&x(e.body.$.type)&&Ce(e.body.$.type)&&(a=P(e.body.$.type,n))}e.body&&x(o.return.type)&&!Ce(o.return.type)&&!e.specializedType&&!e.isModuleEffectMember&&e.body.$?.type&&(a=P(e.body.$.type,n));let s=e.specializedType&&$t(o).length===0&&$t(e.type).some(L=>L.fieldFunctionType.forallParameters&&L.fieldFunctionType.forallParameters.length>0)?e.type:void 0,l=a?hr(o,t,n,a,s):hr(o,t,n,void 0,s),c=t==="__yo_user_main"||n.exportedFunctionLabels?.has(e.funcId)?"":"static ";r.emitLine(`${c}${l} {`);let _=n.currentFunctionName,p=n.currentFunctionType;n.currentFunctionName=i,n.currentFunctionType=o;let f=n.isModuleEffectMemberFunction,m=n.overrideReturnTypeStr;e.isModuleEffectMember&&(n.isModuleEffectMemberFunction=!0),n.overrideReturnTypeStr=a;let g=n.currentEvidenceParams,h=$t(o);if(h.length===0&&e.specializedType){let L=$t(e.type);L.some(b=>b.fieldFunctionType.forallParameters&&b.fieldFunctionType.forallParameters.length>0)&&(h=L)}if(h.length>0){let L=new Map;for(let b of h)L.set(`${b.implicitLabel}.${b.fieldLabel}`,b);n.currentEvidenceParams=L}let d=n.currentClosureCaptures,v=n.currentClosureCaptureFrameLevel,T=n.currentClosureType,$=n.currentClosureCaptureTypeCName;if(o.isClosure){let L=e.closureInfo;if(L){let b=L.closureType.isFn,R=L.captureType;if(n.currentClosureType=b.callType,R&&ce(R)&&R.fields.length>0){let N=R.fields.map(D=>D.label);n.currentClosureCaptures=N,n.currentClosureCaptureFrameLevel=e.frameLevel;let B=n.types[R.id]?.cName;B&&(n.currentClosureCaptureTypeCName=B)}}}if(e.funcName===k.___dispose[0]&&o.SelfType){let L=tg(o.SelfType,e.type.env,n);if(L){let b=o.parameters[0]?.label==="__yo_self"?"__yo_self":o.parameters[0]?.label??"__yo_self";r.emitLine(` ${L}(${b}); // Call user's dispose method`)}}ng(e.body,o," ",n),n.currentFunctionName=_,n.currentFunctionType=p,n.isModuleEffectMemberFunction=f,n.overrideReturnTypeStr=m,n.currentEvidenceParams=g,n.currentClosureCaptures=d,n.currentClosureCaptureFrameLevel=v,n.currentClosureType=T,n.currentClosureCaptureTypeCName=$,r.emitLine("}")}function ng(e,t,n,r){let i=r.emitter;if(F(e)&&E(e,I.begin)){let o=e.args;r.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]],r.consumedVarPendingDrops=[...e.$?.consumedVariableDropExpressions??[]];let a=!1;for(let s=0;s<o.length-1;s++){let l=o[s];E(l,I.return)&&(a=!0);let u=M(l,n,r);if(u&&(!l.$||!ut(l.$.env.modulePath,u))&&i.emitLine(`${n}${u};`),a)break;if(nt(l.$?.controlFlow)){a=!0;break}}if(!a&&o.length>0){let s=o[o.length-1];if(Ce(t.return.type)&&s){let u=Rt(s),c=s.$?.type,_=c&&Ce(c);if(u||_){let p=M(s,n,r);if(e.$?.deferredDropExpressions&&e.$.deferredDropExpressions.length>0&&c){let f=P(c,r),m=`_yo_async_return_${Math.random().toString(36).substr(2,9)}`;i.emitLine(`${n}${f} ${m} = ${p};`),bt(e,n,r),i.emitLine(`${n}return ${m};`)}else i.emitLine(`${n}return ${p};`);return}}else if(s&&pe(t.return.type)){let u=M(s,n,r);u&&i.emitLine(`${n}${u};`),bt(e,n,r)}else if(s){let u=nt(s.$?.controlFlow),c=pe(s.$?.type)||F(s)&&E(s,I.tuple)&&s.args.length===0,_=o.length>1?o[o.length-2]:null,p=nt(_?.$?.controlFlow);if(!(c&&p))if(u){let f=M(s,n,r);f&&i.emitLine(`${n}${f};`)}else{if(s.$?.deferredDupExpressions&&s.$.deferredDupExpressions.length>0){if(s.$?.variableName){let g=P(t.return.type,r),h=Ee(s.$.variableName,s.$.env),d=M(s,n,r);h!==d&&i.emitLine(`${n}${g} ${h} = ${d};`)}rt(s,n,r);let m=s.$.deferredDupExpressions[0];if(F(m)&&m.$?.variableName){let g=te(m.$.variableName);bt(e,n,r),i.emitLine(`${n}return ${g};`);return}}let f=M(s,n,r);bt(e,n,r),f&&i.emitLine(`${n}return ${f};`)}}}else if(a&&o.length>0){let s=o[o.length-1];s&&pe(s.$?.type)}}else if(bt(e,n,r),pe(t.return.type)){let o=M(e,n,r);o&&i.emitLine(`${n}${o};`)}else e_(e,n,r)}function s_(e){for(let t in e.functions){let{value:n,cName:r}=e.functions[t];if(Wr(n)||!n.specializedType||!Pn(n.type))continue;let i=n.specializedType,o=i.forallParameters.length>0||i.parameters.some(_=>_.isCompileTimeOnly),a=i.parameters.some(_=>!_.isCompileTimeOnly&&x(_.type)&&!Ce(_.type));if(o||a)continue;let s=n.specializedType.parameters.some(_=>Fe(_.type)),l=Fe(n.specializedType.return.type);if(s||l)continue;let u=n.body?.$?.effectAnalysis;u&&u.hasEffects||n.isModuleEffectMember||$t(n.specializedType??n.type).length>0||a_(n,r,e)}}function rg(e){let t=e.emitter;t.emitLine(`// Non-atomic reference counting functions (thread-local)
9809
9822
  // Flag to prevent double RC decrements during GC collection.
9810
9823
  // When set, __yo_decr_rc skips all tracked objects because the GC
9811
9824
  // already accounts for their references via trial deletion.
@@ -9877,12 +9890,12 @@ static void __yo_decr_rc_atomic(void* ptr) {
9877
9890
  }`),t.emitDeclarationLine("static _Thread_local int __yo_effect_escaped = 0; // Thread-local flag for module effect escape detection"),t.emitDeclarationLine("static _Thread_local _Alignas(16) char __yo_effect_escape_value[64]; // Thread-local buffer for escape value storage"),t.emitLine(`// Per-thread GC tracking state for cycle collection
9878
9891
  static _Thread_local __yo_thread_gc_state_t* __yo_current_thread_gc = NULL; // Current thread's GC state
9879
9892
  static __yo_thread_gc_state_t* __yo_all_thread_gcs = NULL; // Global list of all thread GC states (for cleanup)
9880
- ${zt(e.targetInfo)?"static __YO_THREAD_SYNC_TYPE __yo_thread_list_mutex;":"static __YO_THREAD_SYNC_TYPE __yo_thread_list_mutex = __YO_THREAD_SYNC_INIT;"}
9893
+ ${Pt(e.targetInfo)?"static __YO_THREAD_SYNC_TYPE __yo_thread_list_mutex;":"static __YO_THREAD_SYNC_TYPE __yo_thread_list_mutex = __YO_THREAD_SYNC_INIT;"}
9881
9894
  static size_t __yo_gc_min_threshold = 256; // Minimum threshold for adaptive scaling
9882
9895
  static size_t __yo_gc_collect_threshold = 256; // Adaptive: starts at min, grows to 2x live objects after each GC
9883
9896
 
9884
9897
  // Thread cleanup infrastructure
9885
- ${zt(e.targetInfo)?`// Windows: Use native TLS API instead of C11 tss_t (better compiler support)
9898
+ ${Pt(e.targetInfo)?`// Windows: Use native TLS API instead of C11 tss_t (better compiler support)
9886
9899
  static DWORD __yo_thread_cleanup_key = TLS_OUT_OF_INDEXES;
9887
9900
  static volatile LONG __yo_thread_cleanup_init_started = 0;
9888
9901
  static volatile LONG __yo_thread_cleanup_init_done = 0;
@@ -9915,7 +9928,7 @@ static void __yo_init_thread_cleanup_key(void) {
9915
9928
  static void __yo_init_thread_gc() {
9916
9929
  if (__yo_current_thread_gc != NULL) return;
9917
9930
 
9918
- ${zt(e.targetInfo)?` __yo_init_thread_cleanup_key();
9931
+ ${Pt(e.targetInfo)?` __yo_init_thread_cleanup_key();
9919
9932
  if (__yo_thread_cleanup_key != TLS_OUT_OF_INDEXES) {
9920
9933
  TlsSetValue(__yo_thread_cleanup_key, (void*)1);
9921
9934
  }`:` pthread_once(&__yo_thread_cleanup_once, __yo_init_thread_cleanup_key);
@@ -10217,7 +10230,7 @@ static void __yo_process_cleanup(void) {
10217
10230
  __yo_cleanup_thread_gc();
10218
10231
  }
10219
10232
 
10220
- ${zt(e.targetInfo)?` if (__yo_thread_cleanup_key != TLS_OUT_OF_INDEXES) {
10233
+ ${Pt(e.targetInfo)?` if (__yo_thread_cleanup_key != TLS_OUT_OF_INDEXES) {
10221
10234
  TlsFree(__yo_thread_cleanup_key);
10222
10235
  __yo_thread_cleanup_key = TLS_OUT_OF_INDEXES;
10223
10236
  }`:` if (__yo_thread_cleanup_key != (pthread_key_t)(-1)) {
@@ -10225,7 +10238,7 @@ ${zt(e.targetInfo)?` if (__yo_thread_cleanup_key != TLS_OUT_OF_INDEXES) {
10225
10238
  }`}
10226
10239
  }
10227
10240
 
10228
- ${zt(e.targetInfo)?`static INIT_ONCE __yo_process_cleanup_once = INIT_ONCE_STATIC_INIT;
10241
+ ${Pt(e.targetInfo)?`static INIT_ONCE __yo_process_cleanup_once = INIT_ONCE_STATIC_INIT;
10229
10242
  static BOOL CALLBACK __yo_process_cleanup_init_callback(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *Context) {
10230
10243
  (void)InitOnce; (void)Parameter; (void)Context;
10231
10244
  InitializeCriticalSection(&__yo_thread_list_mutex);
@@ -10240,7 +10253,7 @@ static void __yo_init_process_cleanup(void) {
10240
10253
  if (cleanup_initialized) return;
10241
10254
  cleanup_initialized = true;
10242
10255
  atexit(__yo_process_cleanup);
10243
- }`}`)}function rg(e){let t=e.emitter;for(let n in e.types){let{type:r,cName:i}=e.types[n];if(ce(r)&&r.isReferenceSemantics){if(r.fields.some(s=>Fe(s.type)))continue;let a=`__yo_traverse_${i}`;t.emitLine(`static void ${a}(void* ptr, void (*visit)(void*)) {`),t.emitLine(` ${i}* obj = (${i}*)ptr;`);for(let s of r.fields){let l=te(s.label),u=s.type;if(ce(u)&&u.isReferenceSemantics)t.emitLine(` if (obj->${l}) {`),t.emitLine(` visit(obj->${l});`),t.emitLine(" }");else if(ge(u)){let c=u;if(!Yt(c)){if(!Fn(c)){t.emitLine(` switch (obj->${l}.tag) {`);for(let p of c.variants||[])if(p.fields&&p.fields.length>0){let f=p.fields.filter(m=>ce(m.type)&&m.type.isReferenceSemantics);if(f.length>0){let m=Bt(c,p.name,e);t.emitLine(` case ${m}:`);for(let g of f)t.emitLine(` if (obj->${l}.data.${p.name}.${te(g.label)}) {`),t.emitLine(` visit(obj->${l}.data.${p.name}.${te(g.label)});`),t.emitLine(" }");t.emitLine(" break;")}}t.emitLine(" }")}}}}t.emitLine("}"),t.emitLine("")}}}function ig(e){let t=e.emitter;rg(e);for(let n in e.types){let{type:r,cName:i}=e.types[n];if(ce(r)&&r.isReferenceSemantics){if(r.fields.some(c=>Fe(c.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(c=>{let _=P(c.type,e),p=te(c.label);return`${_} ${p}`}).join(", ");t.emitLine(`static ${i}* ${a}(${s}) {`),t.emitLine(` ${i}* obj = (${i}*)__yo_malloc(sizeof(${i}));`),t.emitLine(" obj->header.ref_count = 1; // Start with one reference"),t.emitLine(" obj->header.gc_flags = 0;"),t.emitLine(" obj->header.gc_mark = __YO_GC_UNMARKED;"),t.emitLine(" obj->header.gc_next = NULL;"),t.emitLine(" obj->header.gc_prev = NULL;");let l=r.trait.fields.find(c=>c.label===k.___dispose[0]&&c.assignedValue&&ne(c.assignedValue));if(l&&ne(l.assignedValue)){let c=l.assignedValue,_=e.functions[c.funcId]?.cName||c.funcId;t.emitLine(` obj->header.dispose_fn = (void(*)(void*))${_};`)}else t.emitLine(" obj->header.dispose_fn = NULL;");let u=`__yo_traverse_${i}`;t.emitLine(` obj->header.traverse_fn = ${u};`),r.fields.forEach(c=>{let _=te(c.label);t.emitLine(` obj->${_} = ${_};`)}),wr(r,new Set,r.env)&&t.emitLine(" __yo_gc_register(obj);"),t.emitLine(" return obj;"),t.emitLine("}"),t.emitLine("")}}}function l_(e){let t=e.emitter;if(!(!e.closureCaptureMap||e.closureCaptureMap.size===0)){t.emitLine("// Closure dispose functions - one per closure instance (closure type + capture type)"),t.emitLine("");for(let[n]of e.closureCaptureMap){let r=`__yo_dispose_closure_${n}`;t.emitDeclarationLine(`static void ${r}(void* closure_ptr);`)}for(let[n,{closureCName:r,captureType:i,captureCName:o}]of e.closureCaptureMap){let a=`__yo_dispose_closure_${n}`,s=i.trait.fields.find(c=>c.label===k.___drop[0]);if(!s||!s.assignedValue||!ne(s.assignedValue))continue;let l=s.assignedValue,u=e.functions[l.funcId]?.cName;u&&(t.emitLine(`static void ${a}(void* closure_ptr) { // Dispose for ${r} with ${o} (Impl closure - value type)`),t.emitLine(" if (closure_ptr) {"),t.emitLine(` ${r}* closure = (${r}*)closure_ptr;`),t.emitLine(" if (closure->data) {"),t.emitLine(` ${u}(*(${o}*)closure->data); // Drop the capture struct (dereference pointer to pass by value)`),t.emitLine(" // Note: capture data is stack-allocated for Impl closures, no __yo_free needed"),t.emitLine(" }"),t.emitLine(" }"),t.emitLine("}"),t.emitLine(""))}}}function u_(e){let t=new Map;for(let[,n]of e.dynImpls){let r=e.types[n.dynType.id]?.cName||`__yo_dyn_${n.dynType.id}`,i=x(n.concreteType)&&n.concreteType.resolvedConcreteType?n.concreteType.resolvedConcreteType:n.concreteType,a=`${(()=>{let s=e.types[i.id]?.cName;if(s)return s;let l=nn(i);return(l?e.types[l.id]?.cName:void 0)||`unknown_${i.id}`})()}_${r}`;t.set(a,n)}e.dynImpls=t}var za=class{constructor(){this.exportedFunctionNames=new Set;this._needsIntelAsmSyntax=!1;this.emitter=new Ci}compileModule(t,n,r={}){this.emitter.emitDeclarationLine(`
10256
+ }`}`)}function ig(e){let t=e.emitter;for(let n in e.types){let{type:r,cName:i}=e.types[n];if(ce(r)&&r.isReferenceSemantics){if(r.fields.some(s=>Fe(s.type)))continue;let a=`__yo_traverse_${i}`;t.emitLine(`static void ${a}(void* ptr, void (*visit)(void*)) {`),t.emitLine(` ${i}* obj = (${i}*)ptr;`);for(let s of r.fields){let l=te(s.label),u=s.type;if(ce(u)&&u.isReferenceSemantics)t.emitLine(` if (obj->${l}) {`),t.emitLine(` visit(obj->${l});`),t.emitLine(" }");else if(ge(u)){let c=u;if(!Yt(c)){if(!Fn(c)){t.emitLine(` switch (obj->${l}.tag) {`);for(let p of c.variants||[])if(p.fields&&p.fields.length>0){let f=p.fields.filter(m=>ce(m.type)&&m.type.isReferenceSemantics);if(f.length>0){let m=Bt(c,p.name,e);t.emitLine(` case ${m}:`);for(let g of f)t.emitLine(` if (obj->${l}.data.${p.name}.${te(g.label)}) {`),t.emitLine(` visit(obj->${l}.data.${p.name}.${te(g.label)});`),t.emitLine(" }");t.emitLine(" break;")}}t.emitLine(" }")}}}}t.emitLine("}"),t.emitLine("")}}}function og(e){let t=e.emitter;ig(e);for(let n in e.types){let{type:r,cName:i}=e.types[n];if(ce(r)&&r.isReferenceSemantics){if(r.fields.some(c=>Fe(c.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(c=>{let _=P(c.type,e),p=te(c.label);return`${_} ${p}`}).join(", ");t.emitLine(`static ${i}* ${a}(${s}) {`),t.emitLine(` ${i}* obj = (${i}*)__yo_malloc(sizeof(${i}));`),t.emitLine(" obj->header.ref_count = 1; // Start with one reference"),t.emitLine(" obj->header.gc_flags = 0;"),t.emitLine(" obj->header.gc_mark = __YO_GC_UNMARKED;"),t.emitLine(" obj->header.gc_next = NULL;"),t.emitLine(" obj->header.gc_prev = NULL;");let l=r.trait.fields.find(c=>c.label===k.___dispose[0]&&c.assignedValue&&ne(c.assignedValue));if(l&&ne(l.assignedValue)){let c=l.assignedValue,_=e.functions[c.funcId]?.cName||c.funcId;t.emitLine(` obj->header.dispose_fn = (void(*)(void*))${_};`)}else t.emitLine(" obj->header.dispose_fn = NULL;");let u=`__yo_traverse_${i}`;t.emitLine(` obj->header.traverse_fn = ${u};`),r.fields.forEach(c=>{let _=te(c.label);t.emitLine(` obj->${_} = ${_};`)}),wr(r,new Set,r.env)&&t.emitLine(" __yo_gc_register(obj);"),t.emitLine(" return obj;"),t.emitLine("}"),t.emitLine("")}}}function l_(e){let t=e.emitter;if(!(!e.closureCaptureMap||e.closureCaptureMap.size===0)){t.emitLine("// Closure dispose functions - one per closure instance (closure type + capture type)"),t.emitLine("");for(let[n]of e.closureCaptureMap){let r=`__yo_dispose_closure_${n}`;t.emitDeclarationLine(`static void ${r}(void* closure_ptr);`)}for(let[n,{closureCName:r,captureType:i,captureCName:o}]of e.closureCaptureMap){let a=`__yo_dispose_closure_${n}`,s=i.trait.fields.find(c=>c.label===k.___drop[0]);if(!s||!s.assignedValue||!ne(s.assignedValue))continue;let l=s.assignedValue,u=e.functions[l.funcId]?.cName;u&&(t.emitLine(`static void ${a}(void* closure_ptr) { // Dispose for ${r} with ${o} (Impl closure - value type)`),t.emitLine(" if (closure_ptr) {"),t.emitLine(` ${r}* closure = (${r}*)closure_ptr;`),t.emitLine(" if (closure->data) {"),t.emitLine(` ${u}(*(${o}*)closure->data); // Drop the capture struct (dereference pointer to pass by value)`),t.emitLine(" // Note: capture data is stack-allocated for Impl closures, no __yo_free needed"),t.emitLine(" }"),t.emitLine(" }"),t.emitLine("}"),t.emitLine(""))}}}function u_(e){let t=new Map;for(let[,n]of e.dynImpls){let r=e.types[n.dynType.id]?.cName||`__yo_dyn_${n.dynType.id}`,i=x(n.concreteType)&&n.concreteType.resolvedConcreteType?n.concreteType.resolvedConcreteType:n.concreteType,a=`${(()=>{let s=e.types[i.id]?.cName;if(s)return s;let l=nn(i);return(l?e.types[l.id]?.cName:void 0)||`unknown_${i.id}`})()}_${r}`;t.set(a,n)}e.dynImpls=t}var za=class{constructor(){this.exportedFunctionNames=new Set;this._needsIntelAsmSyntax=!1;this.emitter=new Ci}compileModule(t,n,r={}){this.emitter.emitDeclarationLine(`
10244
10257
  // Module ${t}`),this.emitter.emitDeclarationLine(`// Module ID: ${Ui(t)}`);let i={functions:{},externFunctions:{},types:{},arrayStructTypes:new Map,sliceStructTypes:new Map([["Slice_uint8_t_u42_",{childType:"uint8_t*"}]]),spawnedFunctionSignatures:new Map,spawnedClosureSignatures:new Map,closureCaptureMap:new Map,implClosureCallMap:new Map,dynImpls:new Map,currentFunctionName:"",emitter:this.emitter,cIncludes:new Set(["<stdbool.h>","<stdint.h>","<stddef.h>","<stdarg.h>","<stdatomic.h>","<stdlib.h>","<stdio.h>","<string.h>","<errno.h>","<fcntl.h>"]),debugGc:r.debugGc??!1,debugParallelism:r.debugParallelism??!1,debugAsyncAwait:r.debugAsyncAwait??!1,targetInfo:Wo(),deferredAsyncBlocks:[],allocator:r.allocator??"mimalloc",isLibrary:r.isLibrary??!1,currentModuleId:r.isLibrary?Ui(t):void 0};if(Ko(n,i),Mc(n,i),r.isLibrary&&i.exportedFunctionLabels)for(let[o]of i.exportedFunctionLabels){let a=i.functions[o];a&&this.exportedFunctionNames.add(a.cName)}Rc(i),mc(i),yc(i),this.emitter.emitDeclarationLine(`
10245
10258
  // Future state enum - shared by all Future types
10246
10259
  typedef enum {
@@ -10253,77 +10266,82 @@ typedef enum {
10253
10266
  static int32_t __yo_argc;
10254
10267
  static uint8_t** __yo_argv;
10255
10268
  static Slice_uint8_t_u42_ __yo_args;
10256
- `),u_(i),yl(i),Vc(i),kc(i),o_(i),r_(i),Uc(i),zc(i),Bc(i),Pc(i),Nc(i),r.isLibrary||i_(i),l_(i),Fc(i),s_(i),i.needsIntelAsmSyntax&&(this._needsIntelAsmSyntax=!0)}print(){return this.emitter.print()}getExportedFunctionNames(){return this.exportedFunctionNames}get needsIntelAsmSyntax(){return this._needsIntelAsmSyntax}};var c_=0;function __(e){return e.$?.variableName?!0:(e.$?.value!==void 0,!1)}function Ba(e,t){if(F(e)){e.$?.variableName&&t.add(e.$.variableName);for(let n of e.args)Ba(n,t);e.func&&Ba(e.func,t)}}function p_(e,t,n){let r=n,i=r.pendingDeferredDrops;if(!(!i||e.size===0)){r.shortCircuitHandledDropVarNames||(r.shortCircuitHandledDropVarNames=new Set);for(let o of i){let a=In(o);if(a&&e.has(a)){let s=M(o,t,n);s&&n.emitter.emitLine(`${t}${s};`),r.shortCircuitHandledDropVarNames.add(a)}}}}function f_(e,t,n){if(e.args.length===0)return"true";if(e.args.length===1)return M(e.args[0],t,n);let r=[];for(let l of e.args){let u=l.$?.value;if(Re(u)){if(u.value===!1)return"false";continue}r.push(l)}if(r.length===0)return"true";if(r.length===1)return M(r[0],t,n);if(!r.slice(1).some(l=>__(l)))return`(${r.map(u=>M(u,t,n)).join(" && ")})`;let o=`__yo_sc_${c_++}`;n.emitter.emitLine(`${t}bool ${o} = false;`);let a=t,s=r.length-1;for(let l=0;l<r.length;l++){let u=M(r[l],a,n);l<r.length-1?(n.emitter.emitLine(`${a}if (${u}) {`),a+=" "):n.emitter.emitLine(`${a}${o} = ${u};`)}for(let l=s-1;l>=0;l--){let u=r[l+1],c=new Set;Ba(u,c),p_(c,a,n),a=a.slice(2),n.emitter.emitLine(`${a}}`)}return o}function d_(e,t,n){if(e.args.length===0)return"false";if(e.args.length===1)return M(e.args[0],t,n);let r=[];for(let l of e.args){let u=l.$?.value;if(Re(u)){if(u.value===!0)return"true";continue}r.push(l)}if(r.length===0)return"false";if(r.length===1)return M(r[0],t,n);if(!r.slice(1).some(l=>__(l)))return`(${r.map(u=>M(u,t,n)).join(" || ")})`;let o=`__yo_sc_${c_++}`;n.emitter.emitLine(`${t}bool ${o} = true;`);let a=t,s=r.length-1;for(let l=0;l<r.length;l++){let u=M(r[l],a,n);l<r.length-1?(n.emitter.emitLine(`${a}if (!(${u})) {`),a+=" "):n.emitter.emitLine(`${a}${o} = ${u};`)}for(let l=s-1;l>=0;l--){let u=r[l+1],c=new Set;Ba(u,c),p_(c,a,n),a=a.slice(2),n.emitter.emitLine(`${a}}`)}return o}function m_(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_arc_dispose requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type;return!o||!$t(o)?"// Error: __yo_arc_dispose requires an Arc type":`__yo_arc_dispose_${P(o,n)}(${i})`}function vl(e){let t=e.func.$?.value;return O(t)&&$t(t.value)&&e.args.length===1}function y_(e,t,n){if(!vl(e))return"/* Error: generateArcTypeCall called on non-Arc type call */";let i=(e.func.$?.value).value,o=i.childType,a=e.args[0],s=M(a,t,n),l=P(i,n),u=P(o,n);return n.arcTypes||(n.arcTypes=new Map),n.arcTypes.has(l)||n.arcTypes.set(l,{childTypeCName:u,arcType:i}),`__yo_create_arc_${l}(${s})`}function g_(e,t,n){let r=e.$?.runtimeArgExprsInOrder,i=e.$?.type,o=e.$?.variableName;if(ke(i)&&r){let a=n,s=r.map(u=>{let c=M(u,t,n);if(u.$?.deferredDupExpressions&&u.$.deferredDupExpressions.length>0){rt(u,t,a);let _=u.$.deferredDupExpressions[0];if(F(_)&&_.$?.variableName)return Ee(_.$.variableName,_.$.env)}return c}).join(", "),l=P(i,n);if(o&&e.$?.type){let u=`(${l}){ .data = { ${s} } }`,c=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${c} = ${u};`),o}else return`(${l}){ .data = { ${s} } }`}}function h_(e,t,n){let r=n.emitter,i=e.args[0],o=e.args[1],a=i.$?.value;if(!a||!O(a)||!ke(a.value))return"/* ERROR: __yo_array_fill first argument must be an ArrayType */";let s=a.value,l=s.length;if(!ze(l))return"/* ERROR: __yo_array_fill requires compile-time known array length */";let u=P(s,n),c=M(o,t,n),_=e.$?.variableName||`temp_array_${Date.now()}`,p=`i_${qe(e.$?.env.modulePath??"")}`;return r.emitLine(`${t}${u} ${_};`),r.emitLine(`${t}for (int ${p} = 0; ${p} < ${l.value}; ${p}++) {`),r.emitLine(`${t} ${_}.data[${p}] = ${c};`),r.emitLine(`${t}}`),_}function v_(e,t,n){if(e.$?.isCompileTimeOnlyAssignment)return"";let r=e.args[0],i=e.args[1],o=!1;if(F(r)&&E(r,":",2)&&(o=!0,r=r.args[0]),F(r)&&E(r,I.comptime)||F(r)&&E(r,I.given))return"";if(r.$?.pathCollection&&r.$?.pathCollection.length>0){let l=r.$.pathCollection[0];if(l&&l.length>=2){let u=l[0];if(typeof u=="string"&&r.$?.env){let c=X(r.$.env,u);if(c.length>0&&c[c.length-1].isCompileTimeOnly)return""}}}if(z(r)&&r.$?.env){let l=r.token.value,u=X(r.$.env,l);if(u.length>0&&u[u.length-1].isCompileTimeOnly)return""}if(!r.$?.type)return`// Error: No type information for left-hand side ${w(r)}
10257
- `;let a=M(r,t,n),s=!1;if(e.$?.variableName){let l=e.$.variableName,u=n;if((u.inAsyncStateMachine||u.inEffectStateMachine)&&a.startsWith("sm->")){let _=u.stateMachineVariables?.get(l);if(!_&&u.stateMachineVariables){for(let[,p]of u.stateMachineVariables)if(p.name===l){_=p;break}}if(_&&_.kind!=="outer"){let p=`var_${_.id}`;pe(r.$.type)||n.emitter.emitLine(`${t}sm->${p} = ${a}; // Save old value for deferred drop`)}else s=!0}else{let _=st(r.$.type,l,n);ke(r.$.type)?n.emitter.emitLine(`${t}${_} = ${a}; // Save old value for later use`):pe(r.$.type)||n.emitter.emitLine(`${t}${_} = ${a}; // Save old value for later use`)}}if(ke(r.$.type)){let l=M(i,t,n),u=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Wt(i.$.type),c=n,_=l;if(!u&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){if(i.$?.variableName&&i.$?.type){let f=Ee(i.$.variableName,i.$.env);if(f!==l.trim()){let m=i.$.convertedRuntimeType||i.$.type,g=P(m,n);n.emitter.emitLine(`${t}${g} ${f} = ${l};`)}}rt(i,t,c);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(_=Ee(p.$.variableName,p.$.env))}if(o){let p=st(r.$.type,M(r,t,n),n);n.emitter.emitLine(`${t}${p} = ${_};`)}else n.emitter.emitLine(`${t}${a} = ${_};`)}else{let l=M(i,t,n),u=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Wt(i.$.type),c=n,_=l;if(!u&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){if(i.$?.variableName&&i.$?.type){let f=Ee(i.$.variableName,i.$.env);if(f!==l.trim()){let m=i.$.convertedRuntimeType||i.$.type,g=P(m,n);n.emitter.emitLine(`${t}${g} ${f} = ${l};`)}}rt(i,t,c);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(_=Ee(p.$.variableName,p.$.env))}if(!pe(r.$.type)){let p=r.$.type,f=i.$?.type,m,g=ut(i.$.env.modulePath,_.trim());g&&n.tempVarAsyncStructNames&&(m=n.tempVarAsyncStructNames.get(_.trim()));let h=o&&f&&Ce(p)&&Ce(f),d;g&&h?m?d=`${m}*`:d=P(f,n):h&&m?d=`${m}*`:d=P(h?f:p,n);let v=(c.inAsyncStateMachine||c.inEffectStateMachine)&&a.startsWith("sm->");n.emitter.emitLine(`${t}${o&&!v?d+" ":""}${a} = ${_};`)}}return s?"":e.$?.variableName??""}function E_(e,t,n){let r=e.args[0];if(!r)return"// Error: await requires exactly 1 argument";let i=r.$?.type;if(!i||!Ce(i))return"// Error: await argument must be a Future type";let o=Dt(i);if(!o)return"// Error: could not extract Future module from type";let a=n;if(a.inAsyncStateMachine||a.inEffectStateMachine)return"";if(pn(e)){let s=M(r,t,n),l=P(i,n),u=o.isFuture.outputType;x(u)&&(u.resolvedConcreteType?u=u.resolvedConcreteType:e.$?.type&&!x(e.$.type)?u=e.$.type:e.$?.type&&x(e.$.type)&&e.$.type.resolvedConcreteType&&(u=e.$.type.resolvedConcreteType));let c=a.emitter,_=pe(u)||x(u)&&pe(e.$?.type??u),p=e.$?.variableName?`__sync_future_${e.$.variableName}`:"__sync_future",f=e.$?.variableName?`__pre_await_state_${e.$.variableName}`:"__pre_await_state";c.emitLine(`${t}// Synchronous await (io.await outside state machine)`),c.emitLine(`${t}${l} ${p} = ${s};`),c.emitLine(`${t}int ${f} = ${p}->state;`),jo(r.$?.type)||(c.emitLine(`${t}if (${f} == 0 && ${p}->__yo_resume_fn) {`),ag(e,p,t,n),c.emitLine(`${t} __yo_incr_rc((void*)${p}); // event loop reference`),c.emitLine(`${t} ${p}->__yo_resume_fn((void*)${p});`),c.emitLine(`${t}}`)),c.emitLine(`${t}{`),c.emitLine(`${t} int __await_state = ${p}->state;`),c.emitLine(`${t} while (__await_state != -1 && __await_state != -2) {`),c.emitLine(`${t} __yo_async_poll_step();`),c.emitLine(`${t} __await_state = ${p}->state;`),c.emitLine(`${t} }`),c.emitLine(`${t} if (__await_state == -2) {`);let g=Dt(i),h=g?.isFuture.effects?.some(d=>G(d.type)||Te(d.type)||d.isEffectRowSpread)??!1;if(h){c.emitLine(`${t} if (${f} == -2) {`),c.emitLine(`${t} fprintf(stderr, "panic: attempted to await an aborted Future\\n");`),c.emitLine(`${t} abort();`),c.emitLine(`${t} }`);let d=a.pendingDeferredDrops;if(d){let $=e.$?.variableName;a.pendingDeferredDrops=d.filter(C=>In(C)!==$)}dn(t+" ",a,e),a.pendingDeferredDrops=d;let v=og(g,a),T=a.currentFunctionType?.return?.type;if(v)if(c.emitLine(`${t} __yo_effect_escaped = 0;`),T&&!pe(T)){let $=P(T,n);$!=="void"?(c.emitLine(`${t} ${$} _esc_result;`),c.emitLine(`${t} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${$}));`),c.emitLine(`${t} return _esc_result;`)):c.emitLine(`${t} return;`)}else c.emitLine(`${t} return;`);else if(c.emitLine(`${t} __yo_effect_escaped = 1;`),T&&!pe(T)){let $=P(T,n);c.emitLine(`${t} return (${$}){0};`)}else c.emitLine(`${t} return;`)}else c.emitLine(`${t} fprintf(stderr, "panic: attempted to await an aborted Future\\n");`),c.emitLine(`${t} abort();`);if(c.emitLine(`${t} }`),c.emitLine(`${t}}`),_)return"";{let d=e.$?.variableName||"__sync_await_result",v=P(u,n),T=st(u,d,n);if(h){if(c.emitLine(`${t}${T};`),c.emitLine(`${t}if (${p}->state == -1) {`),Le(u)){let $=On(u,n);$?c.emitLine(`${t} ${d} = ${$}(${p}->result);`):c.emitLine(`${t} ${d} = ${p}->result;`)}else c.emitLine(`${t} ${d} = ${p}->result;`);c.emitLine(`${t}} else {`),c.emitLine(`${t} ${d} = (${v}){0};`),c.emitLine(`${t}}`)}else if(Le(u)){let $=On(u,n);$?c.emitLine(`${t}${T} = ${$}(${p}->result);`):c.emitLine(`${t}${T} = ${p}->result;`)}else c.emitLine(`${t}${T} = ${p}->result;`);return d}}return"// Error: await should only be used inside async blocks"}function $_(e,t,n){let r=e.args[0];if(!r)return"// Error: io.state requires exactly 1 argument";let i=r.$?.type;if(!i||!Ce(i))return"// Error: io.state argument must be a Future type";let a=n.emitter,s=M(r,t,n),l=e.$?.variableName?`__raw_state_${e.$.variableName}`:"__raw_state",u=e.$?.variableName||"__io_state_result";return a.emitLine(`${t}int ${l} = ${s}->state;`),a.emitLine(`${t}int32_t ${u} = (${l} > 0) ? 1 : ${l};`),u}function C_(e,t,n){let i=n.emitter,o=F(e.func)?e.func.args[0]:e.args[0];if(!o)return"// Error: JoinHandle.await requires a self argument";let a=M(o,t,n),s=e.$?.type;if(!s||!ge(s))return"// Error: JoinHandle.await return type must be Option(T)";let l=P(s,n),c=s.variants.find(C=>C.name==="Some")?.fields?.[0]?.type,_=!c||pe(c),p=_?"uint8_t":c?P(c,n):"uint8_t",f=Bt(s,"Some",n),m=Bt(s,"None",n),g=e.$?.variableName||"jh",h=`__jh_future_${g}`,d=`__jh_header_${g}`,v=e.$?.variableName||"__jh_result",T=`__yo_jh_header_${g}`;i.emitLine(`${t}// JoinHandle.await \u2014 poll spawned task, return Option(T)`);let $=st(s,v,n);if(i.emitLine(`${t}${$};`),i.emitLine(`${t}{`),i.emitLine(`${t} void* ${h} = ${a}.__future;`),i.emitLine(`${t} struct ${T} {`),i.emitLine(`${t} __yo_ref_header_t header;`),i.emitLine(`${t} int state;`),i.emitLine(`${t} ${p} result;`),i.emitLine(`${t} void (*continuation_fn)(void*);`),i.emitLine(`${t} void* continuation_sm;`),i.emitLine(`${t} void (*__yo_resume_fn)(void*);`),i.emitLine(`${t} };`),i.emitLine(`${t} struct ${T}* ${d} = (struct ${T}*)${h};`),i.emitLine(`${t} int __jh_state = ${d}->state;`),i.emitLine(`${t} while (__jh_state != -1 && __jh_state != -2) {`),i.emitLine(`${t} __yo_async_poll_step();`),i.emitLine(`${t} __jh_state = ${d}->state;`),i.emitLine(`${t} }`),i.emitLine(`${t} if (__jh_state == -1) {`),_)i.emitLine(`${t} ${v} = (${l}){ .tag = ${f} };`);else if(c&&Le(c)){let C=On(c,n);C?i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${C}(${d}->result) } } };`):i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${d}->result } } };`)}else i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${d}->result } } };`);return i.emitLine(`${t} } else {`),i.emitLine(`${t} __yo_effect_escaped = 0;`),i.emitLine(`${t} ${v} = (${l}){ .tag = ${m} };`),i.emitLine(`${t} }`),i.emitLine(`${t}}`),v}function og(e,t){let n=e.isFuture.effects;if(!n?.length)return!1;let r=b_(n),i=t.currentEvidenceParams;for(let o of r)if(G(o.type)){let a=`${o.label}.${o.label}`;if(!i?.has(a))return!0}else if(Te(o.type)){let a=!1;if(i){for(let[s]of i)if(s.startsWith(`${o.label}.`)){a=!0;break}}if(!a)return!0}return!1}function b_(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function ag(e,t,n,r){let i=e.args[0];if(!i?.$?.type)return;let o=Dt(i.$.type);if(!o?.isFuture.effects?.length)return;let a=b_(o.isFuture.effects),s=r,l=s.emitter,u=e.args.find(c=>F(c)&&E(c,I.using));if(u){let c=u.args;for(let _=0;_<a.length&&_<c.length;_++){let p=a[_],f=c[_];if(G(p.type)){let m=M(f,n,r),g=p.label;l.emitLine(`${n} ${t}->__capture.${g} = (void*)${m};`)}else Te(p.type)&&T_(p.type,t,n,f.$?.value,s,e)}}else for(let c of a)if(G(c.type)){let _=lg(c.label,s,e);_&&l.emitLine(`${n} ${t}->__capture.${c.label} = (void*)${_};`)}else Te(c.type)&&T_(c.type,t,n,void 0,s,e)}function T_(e,t,n,r,i,o){let a=i.emitter;for(let s of e.fields){if(!G(s.type))continue;let l;if(i.stateMachineVariables){for(let[,u]of i.stateMachineVariables)if(u.name===s.label&&u.kind==="outer"){l=`sm->__capture.${s.label}`;break}}if(!l&&r&&We(r)){let u=e.fields.indexOf(s),c=r.fields[u];if(c&&ne(c)){let _=i.functions[c.funcId];_&&(l=_.cName)}}if(!l&&i.currentEvidenceParams){for(let u of i.currentEvidenceParams.values())if(u.fieldLabel===s.label){l=u.cParamName;break}}l||(l=sg(s.label,e,i,o)),l&&a.emitLine(`${n} ${t}->__capture.${s.label} = (void*)${l};`)}}function sg(e,t,n,r){let i=r.$?.env??r.func.$?.env;if(!i)return;let o=fn(i,a=>a.isImplicit===!0);for(let a=o.length-1;a>=0;a--){let s=o[a],l=s.value?.[s.value.length-1];if(l&&We(l)){let u=l.type.fields.findIndex(c=>c.label===e);if(u>=0){let c=l.fields[u];if(c&&ne(c)){let _=n.functions[c.funcId]?.cName;if(_)return _}}}}}function lg(e,t,n){if(t.currentEvidenceParams){for(let r of t.currentEvidenceParams.values())if(r.fieldLabel===e)return r.cParamName}if(t.stateMachineVariables){for(let[,r]of t.stateMachineVariables)if(r.name===e&&r.kind==="outer")return`sm->__capture.${e}`}}function k_(e,t,n){let r=e.$?.variableName,i=e.$?.type,o=n;if(r&&i){!pe(i)&&!nt(e.$?.controlFlow)&&n.emitter.emitLine(`${t}${P(i,n)} ${r};`),n.emitter.emitLine(`${t}{ // begin block`);let a=o.pendingDeferredDrops,s=e.$?.deferredDropExpressions??[];o.pendingDeferredDrops=[...s,...a??[]];let l=o.consumedVarPendingDrops,u=e.$?.consumedVariableDropExpressions??[];o.consumedVarPendingDrops=[...u,...l??[]];let c=[],_=!pe(i)&&!nt(e.$?.controlFlow);for(let p=0;p<e.args.length;p++){let f=e.args[p],m=M(f,t+" ",n);c.push(m);let g=p===e.args.length-1;m&&!(g&&_)&&(f.$&&ut(f.$.env.modulePath,m)||n.emitter.emitLine(`${t} ${m};`))}if(_){let p=e.args[e.args.length-1],f=c[c.length-1];if(p.$?.deferredDupExpressions&&p.$.deferredDupExpressions.length>0){if(p.$?.variableName){let g=p.$.variableName;p.$.variableName=void 0;let h=M(p,t+" ",n);p.$.variableName=g;let d=P(p.$.type,n),v=Ee(g,p.$.env);v!==h&&n.emitter.emitLine(`${t} ${d} ${v} = ${h};`),f=v}rt(p,t+" ",n);let m=p.$.deferredDupExpressions[0];F(m)&&m.$?.variableName&&(f=Ee(m.$.variableName,m.$.env))}n.emitter.emitLine(`${t} ${r} = ${f};`)}if(e.$?.deferredDropExpressions)for(let p of e.$.deferredDropExpressions){if(o.shortCircuitHandledDropVarNames){let m=In(p);if(m&&o.shortCircuitHandledDropVarNames.has(m)){o.shortCircuitHandledDropVarNames.delete(m);continue}}let f=M(p,t+" ",n);f&&n.emitter.emitLine(`${t} ${f};`)}return n.emitter.emitLine(`${t}} // end begin block`),o.pendingDeferredDrops=a,o.consumedVarPendingDrops=l,pe(i)||nt(e.$?.controlFlow)?"":r}else{n.emitter.emitLine(`${t}{ // begin block`);let a=o.pendingDeferredDrops,s=e.$?.deferredDropExpressions??[];o.pendingDeferredDrops=[...s,...a??[]];let l=o.consumedVarPendingDrops,u=e.$?.consumedVariableDropExpressions??[];if(o.consumedVarPendingDrops=[...u,...l??[]],e.args.map(_=>M(_,t+" ",n)).forEach(_=>{_&&n.emitter.emitLine(`${t} ${_};`)}),e.$?.deferredDropExpressions)for(let _ of e.$.deferredDropExpressions){if(o.shortCircuitHandledDropVarNames){let f=In(_);if(f&&o.shortCircuitHandledDropVarNames.has(f)){o.shortCircuitHandledDropVarNames.delete(f);continue}}let p=M(_,t+" ",n);p&&n.emitter.emitLine(`${t} ${p};`)}return n.emitter.emitLine(`${t}} // end begin block`),o.pendingDeferredDrops=a,o.consumedVarPendingDrops=l,""}}function w_(e,t,n){let r=e.args[0];if(F(r)&&E(r,I.comptime,1)||F(r)&&E(r,I.given,1))return"";if(!r.$?.type)return`// Error: No type information for left-hand side ${w(r)}
10258
- `;let i=r.token.value,o=st(r.$.type,i,n);return n.emitter.emitLine(`${t}${o};`),""}function F_(e,t,n){if(e.$){let r=e.$.variableName,i=e.$.type,o=i&&pe(i),a=-1;for(let _=0;_<e.args.length;_++){let p=e.args[_];if(F(p)&&E(p,"=>",2)){let f=p.args[0];if(f&&!(Re(f.$?.value)&&f.$.value.value===!1)){a=_;break}}}let s=!1;if(a>=0){let _=e.args[a];if(_&&F(_)&&E(_,"=>",2)){let p=_.args[0];p&&Re(p.$?.value)&&p.$.value.value===!0&&(s=!0)}}if(!o&&r&&!s){let _=P(i,n);n.emitter.emitLine(`${t}${_} ${r};`)}if(s&&a>=0){let _=e.args[a];if(_&&F(_)&&E(_,"=>",2)){let p=_.args[1];if(p){let f=M(p,t,n);r&&!o&&(f&&f!==""&&!f.startsWith("goto")&&f!=="continue"&&f!=="break"&&!f.includes("return")?n.emitter.emitLine(`${t}${r} = ${f};`):f&&(f.startsWith("goto")||f==="continue"||f==="break"||f.includes("return"))&&n.emitter.emitLine(`${t}${f};`))}}return o?"":r??""}let l=t,u=0,c=!1;for(let _=0;_<e.args.length;_++){let p=e.args[_];if(F(p)&&E(p,"=>",2)){let f=p.args[0],m=p.args[1];if(f&&m){if(Re(f.$?.value)&&f.$.value.value===!1)continue;if(c){if(n.emitter.emitLine(`${l}else {`),u++,l+=" ",!(Re(f.$?.value)&&f.$.value.value===!0)){let T=M(f,l,n);n.emitter.emitLine(`${l}if (${T}) {`)}}else{if(Re(f.$?.value)&&f.$.value.value===!0)n.emitter.emitLine(`${l}{`);else{let v=M(f,l,n);n.emitter.emitLine(`${l}if (${v}) {`)}c=!0}let g=Re(f.$?.value)&&f.$.value.value===!0,h=c&&g?l:l+" ";if(F(m)&&E(m,I.begin)){let v=m.args,T=n,$=T.pendingDeferredDrops,C=m.$?.deferredDropExpressions??[];T.pendingDeferredDrops=[...C,...$??[]];let L=T.consumedVarPendingDrops,b=m.$?.consumedVariableDropExpressions??[];T.consumedVarPendingDrops=[...b,...L??[]];for(let R=0;R<v.length-1;R++){let N=v[R],B=M(N,h,n);if(B&&N.$&&!ut(N.$.env.modulePath,B)&&n.emitter.emitLine(`${h}${B};`),nt(N.$?.controlFlow))break}if(v.length>0){let R=v[v.length-1];R.$?.deferredDupExpressions&&rt(R,h,n);let N=M(R,h,n);N&&(N==="continue"||N==="break"||N.startsWith("goto")||F(R)&&E(R,I.return)||N.includes("return")?n.emitter.emitLine(`${h}${N};`):r&&!o&&n.emitter.emitLine(`${h}${r} = ${N};`))}m.$?.deferredDropExpressions&&Ct(m,h,n),T.pendingDeferredDrops=$,T.consumedVarPendingDrops=L}else{m.$?.deferredDupExpressions&&rt(m,h,n);let v=M(m,h,n);v==="continue"||v==="break"||v.startsWith("goto")||F(m)&&E(m,I.return)||v.includes("return")?n.emitter.emitLine(`${h}${v};`):v===""||!v||r&&(o||n.emitter.emitLine(`${h}${r} = ${v};`))}!(c&&g)&&n.emitter.emitLine(`${l}}`)}}}for(let _=0;_<u;_++)l=l.slice(0,-2),n.emitter.emitLine(`${l}}`);return o?"":r??""}return'/* "cond" expression is not evaluated */'}function L_(e,t,n){let r=e.args[0];return M(r,t,n)}function A_(e,t,n){let r=e.args[0],i=r.$?.type;if(!i||!be(i))throw new Error("downcast codegen: expected Dyn type as first argument");let o=M(r,t,n),s=e.args[1].$?.value;if(!s||!O(s))throw new Error("downcast codegen: expected TypeValue as second argument");let l=s.value,u=P(l,n),c=n.types[l.id]?.cName||u,_=`__yo_typeid_${te(c)}`;n.typeIdStatics||(n.typeIdStatics=new Map),n.typeIdStatics.has(l.id)||(n.typeIdStatics.set(l.id,_),n.emitter.emitDeclarationLine(`static const char ${_} = 0;`)),n.cIncludes.add("<stdint.h>");let p=`${o}.vtable->__yo_type_id == (uintptr_t)&${_}`,f,m=!1,g="",h="";for(let[,R]of n.dynImpls){if(R.dynType.id!==i.id)continue;if((x(R.concreteType)&&R.concreteType.resolvedConcreteType?R.concreteType.resolvedConcreteType:R.concreteType).id===l.id&&$n(R.dataType)){m=!0,g=n.types[R.dataType.id]?.cName||`unknown_box_${R.dataType.id}`,h=te(R.dataType.fields[0].label);break}}if(m){let R=pt(l);if(!R){let N=l;for(;Er(N)&&N.fields.length===1;)N=N.fields[0].type;R=pt(N)}R?f=`((${u})__yo_incr_rc((void*)((${g}*)${o}.data)->${h}))`:f=`((${u})((${g}*)${o}.data)->${h})`}else f=`((${u})__yo_incr_rc((void*)${o}.data))`;let d=e.$?.type;if(!d||!ge(d))throw new Error("downcast codegen: expected Option enum as result type");if(Yt(d))return`((${p}) ? ${f} : NULL)`;let T=P(d,n),$=Bt(d,"Some",n),C=Bt(d,"None",n),L=`(${T}){ .tag = ${$}, .data = { .Some = { .value = ${f} } } }`,b=`(${T}){ .tag = ${C} }`;return`((${p}) ? ${L} : ${b})`}function I_(e,t,n){if(!e.$?.dynCallTraitValues||e.$.dynCallTraitValues.length===0)return"/* Error: dyn() call missing trait values */";let r=e.$?.runtimeArgExprsInOrder?.[0]??e.args[0];if(!r)return"/* Error: dyn() requires a value argument */";let i=e.$.type;if(!be(i))return"/* Error: dyn() result type is not DynType */";let o=r.$?.type;if(!o)return"/* Error: dyn() value has no type */";let a=e.$.dynCallTraitValues;if(!a||a.length===0)return"/* Error: dyn() call missing trait values */";if(!pt(o)&&!$n(o))return"/* Error: dyn() requires an object type (use box() for value types) */";let s=$n(o)?o.fields[0].type:o,l=x(s)&&s.resolvedConcreteType?s.resolvedConcreteType:s,u=n.types[i.id]?.cName||`__yo_dyn_${i.id}`,_=`${(()=>{let d=n.types[l.id]?.cName;if(d)return d;let v=nn(l);return(v?n.types[v.id]?.cName:void 0)||`unknown_${l.id}`})()}_${u}`;n.dynImpls.set(_,{dynType:i,concreteType:s,dataType:o,traitValues:a});let p=M(r,t,n);if(r.$?.variableName&&p!==r.$.variableName){let d=st(r.$.type,r.$.variableName,n);n.emitter.emitLine(`${t}${d} = ${p};`),p=r.$.variableName}if(r.$?.deferredDupExpressions&&r.$.deferredDupExpressions.length>0){rt(r,t,n);let d=r.$.deferredDupExpressions[0];F(d)&&d.$?.variableName&&(p=Ee(d.$.variableName,d.$.env))}let f=e.$?.variableName;if(!f)return"/* Error: dyn() expression missing temp variable name */";let m=n,g;if(m.inAsyncStateMachine&&m.stateMachineVariables){for(let[,d]of m.stateMachineVariables)if(d.kind==="local"&&d.id===f){g=`sm->${rn(d.id,"local",m.stateMachineFieldAliases)}`;break}}let h=`__yo_vtable_${_}`;return g?(n.emitter.emitLine(`${t}${g} = (${u}){`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${h}`),n.emitter.emitLine(`${t}};`),g):(n.emitter.emitLine(`${t}${u} ${f} = {`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${h}`),n.emitter.emitLine(`${t}};`),f)}function S_(e,t,n){return e.args.length!==0?"// Error: __yo_gc_collect requires exactly 0 arguments":"__yo_gc_collect()"}function N_(e,t,n){let r=e.args[0],i=e.args[1],o=n;if(F(r)&&E(r,I.comptime,1)||F(r)&&E(r,I.given,1))return"";if((o.inAsyncStateMachine||o.inEffectStateMachine)&&z(r)&&z(i)){let a=r.token.value,s=i.token.value,l=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(c=>c.name===a),u=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(c=>c.name===s);if(a===s&&(l||u))return""}if(e.$?.runtimeDestructurings){let a=e.$.runtimeDestructurings,s=M(i,t,n),l=i.$?.type;return a.forEach(({label:u,type:c,variableName:_})=>{let p=te(_,c.isExtern==="c"),f=st(c,p,n);if(l&&ce(l)&&l.isNewtype&&l.fields.length===1){let h=l.fields[0];if(h&&h.label===u){n.emitter.emitLine(`${t}${f} = ${s}; // Destructuring ${u} (newtype)`);return}}let m=u.match(/^\d+$/)?`_${u}`:te(u,c.isExtern==="c");if(l&&we(l)&&!u.match(/^\d+$/)){let h=l.fields.findIndex(d=>d.label===u);m=h>=0?`_${h}`:m}let g=l&&pt(l)?"->":".";n.emitter.emitLine(`${t}${f} = ${s}${g}${m}; // Destructuring ${u}`)}),""}if(z(r)){let a=r.token.value;if(!r.$?.type)return`// Error: No type information for variable ${a}
10259
- `;if(r.$?.env){let u=X(r.$.env,a);if(u.length>0&&u[u.length-1].isCompileTimeOnly)return""}let s=!1,l;if((o.inAsyncStateMachine||o.inEffectStateMachine)&&o.stateMachineVariables&&r.$?.env){let u=X(r.$.env,a);if(u.length>0){let c=u[u.length-1],_=c.isOwningTheSameRcValueAs?c.isOwningTheSameRcValueAs.id:c.id;o.stateMachineVariables.has(_)&&(s=!0,l=_)}}if(ke(r.$.type))if(F(i)&&E(i,I.array)){let u=M(i,t,n);if(s&&l){let c=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${c} = ${u};`)}else if(!pe(r.$.type)){let c=st(r.$.type,a,n);n.emitter.emitLine(`${t}${c} = ${u};`)}}else{let u;if(i.$?.variableName){let c=Ee(i.$.variableName,i.$.env),_=M(i,t,n);if(!s){let p=st(i.$.type,c,n);c!==_&&n.emitter.emitLine(`${t}${p} = ${_};`)}u=c}else u=M(i,t,n);if(s&&l){let c=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${c} = ${u};`)}else if(!pe(r.$.type)){let c=st(r.$.type,a,n);n.emitter.emitLine(`${t}${c} = ${u};`)}}else{let u,c=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Wt(i.$.type),_=F(i)&&Rt(i);if(i.$?.variableName){let p=Ee(i.$.variableName,i.$.env),f=Ee(a,r.$.env);if(p===f){if(u=M(i,t,n),!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let m=i.$.deferredDupExpressions[0];F(m)&&m.$?.variableName&&(u=Ee(m.$.variableName,m.$.env))}}else if(z(i)&&p===Ee(i.token.value,i.$.env)){if(u=M(i,t,n),!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let m=i.$.deferredDupExpressions[0];F(m)&&m.$?.variableName&&(u=Ee(m.$.variableName,m.$.env))}}else if(z(i)&&o.currentClosureCaptures&&o.currentClosureCaptures.includes(i.token.value)&&i.$?.env&&o.currentClosureCaptureFrameLevel!==void 0&&vr(i.token.value,i.$.env,o.currentClosureCaptureFrameLevel)){let m=o.currentClosureType;if(m&&m.isClosure){let g=Object.values(o.types).find(h=>h.type===m);g?u=`((${`${g.cName}_capture`}*)closure_context->data)->${Ee(i.token.value,i.$.env)}`:u=`closure_context->${Ee(i.token.value,i.$.env)}`}else u=`closure_context->${Ee(i.token.value,i.$.env)}`}else{let m=M(i,t,n);if(m.trim()!==p){let g=i.$.convertedRuntimeType||i.$.type,h=st(g,p,n);n.emitter.emitLine(`${t}${h} = ${m};`)}if(!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let g=i.$.deferredDupExpressions[0];F(g)&&g.$?.variableName?u=Ee(g.$.variableName,g.$.env):u=p}else u=p}}else if(u=M(i,t,n),!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(u=Ee(p.$.variableName,p.$.env))}if(Qe(r.$.type)){let p=r.$.type;if(s&&l){let f=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${f} = ${u};`)}else if(!pe(p)){let f=st(p,a,n);n.emitter.emitLine(`${t}${f} = ${u};`)}}else if(s&&l){let p=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${p} = ${u};`)}else{let p=ut(i.$.env.modulePath,u.trim()),f;if(p&&n.tempVarAsyncStructNames){let m=n.tempVarAsyncStructNames.get(u.trim());m?f=`${m}*`:f=P(r.$.type,n)}else f=P(r.$.type,n);pe(r.$.type)||n.emitter.emitLine(`${t}${f} ${Ee(a,r.$.env)} = ${u};`)}}return""}}var ug=0;function Xo(e,t,n,r,i=" "){if(k.__yo_op_add.includes(e))return`((${t[0]}) + (${t[1]}))`;if(k.__yo_op_sub.includes(e))return`((${t[0]}) - (${t[1]}))`;if(k.__yo_op_mul.includes(e))return`((${t[0]}) * (${t[1]}))`;if(k.__yo_op_div.includes(e))return`((${t[0]}) / (${t[1]}))`;if(k.__yo_op_mod.includes(e))return`((${t[0]}) % (${t[1]}))`;if(k.__yo_op_neg.includes(e))return`(-(${t[0]}))`;if(k.__yo_op_eq.includes(e))return`((${t[0]}) == (${t[1]}))`;if(k.__yo_op_neq.includes(e))return`((${t[0]}) != (${t[1]}))`;if(k.__yo_op_lt.includes(e))return`((${t[0]}) < (${t[1]}))`;if(k.__yo_op_lte.includes(e))return`((${t[0]}) <= (${t[1]}))`;if(k.__yo_op_gt.includes(e))return`((${t[0]}) > (${t[1]}))`;if(k.__yo_op_gte.includes(e))return`((${t[0]}) >= (${t[1]}))`;if(k.__yo_op_not.includes(e))return`(!(${t[0]}))`;if(k.__yo_op_bit_and.includes(e))return`((${t[0]}) & (${t[1]}))`;if(k.__yo_op_bit_or.includes(e))return`((${t[0]}) | (${t[1]}))`;if(k.__yo_op_bit_xor.includes(e))return`((${t[0]}) ^ (${t[1]}))`;if(k.__yo_op_bit_complement.includes(e))return`(~(${t[0]}))`;if(k.__yo_op_bit_left_shift.includes(e))return`((${t[0]}) << (${t[1]}))`;if(k.__yo_op_bit_right_shift.includes(e))return`((${t[0]}) >> (${t[1]}))`;if(k.__yo_noop.includes(e))return"";if(k.__yo_return_self.includes(e))return`(*${t[0]})`;if(k.__yo_ms_sleep.includes(e))return zt(r.targetInfo)?`Sleep(${t[0]})`:`usleep((${t[0]}) * 1000)`;if(k.__yo_decr_rc.includes(e))return`__yo_decr_rc((void*)(${t[0]}))`;if(k.__yo_as.includes(e)&&n.$?.type){let o=P(n.$.type,r),a=n.args[0]?.$?.type;return a&&ge(a)&&!Fn(a)?`((${o})((${t[0]}).tag))`:`((${o})(${t[0]}))`}else{if(k.__yo_ptr_add.includes(e))return`(${t[0]} + ${t[1]})`;if(k.__yo_ptr_sub.includes(e))return`(${t[0]} - ${t[1]})`;if(k.__yo_ptr_diff.includes(e))return`(${t[0]} - ${t[1]})`;if(k.__yo_ptr_eq.includes(e))return`(${t[0]} == ${t[1]})`;if(k.__yo_ptr_neq.includes(e))return`(${t[0]} != ${t[1]})`;if(k.__yo_ptr_lt.includes(e))return`(${t[0]} < ${t[1]})`;if(k.__yo_ptr_lte.includes(e))return`(${t[0]} <= ${t[1]})`;if(k.__yo_ptr_gt.includes(e))return`(${t[0]} > ${t[1]})`;if(k.__yo_ptr_gte.includes(e))return`(${t[0]} >= ${t[1]})`;if(k.__yo_slice_len.includes(e))return`(${t[0]}.length)`;if(k.__yo_slice_new.includes(e)&&n.$?.type)return`(${P(n.$.type,r)}){ .data = ${t[0]}, .length = ${t[1]} }`;if(k.__yo_getrandom.includes(e))return`getrandom(${t[0]}, ${t[1]}, ${t[2]})`;if(k.__yo_arc4random_buf.includes(e))return`(arc4random_buf(${t[0]}, ${t[1]}), (void)0)`;if(k.__yo_bcrypt_gen_random.includes(e))return`(int32_t)BCryptGenRandom(NULL, ${t[0]}, ${t[1]}, BCRYPT_USE_SYSTEM_PREFERRED_RNG)`;if(k.__yo_maybe_uninit_new.includes(e)&&n.$?.type){let o=P(n.$.type,r),a=`__yo_uninit_${ug++}`;return r.emitter.emitLine(`${i}${o} ${a};`),a}else return k.__yo_maybe_uninit_as_ptr.includes(e)&&n.$?.type?`((${P(n.$.type,r)})(${t[0]}))`:k.__yo_maybe_uninit_assume_init.includes(e)?`(${t[0]})`:`/* Unhandled operator ${e} */`}}function V_(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_extract requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type;if(!o||!kt(o))return"// Error: __yo_iso_extract requires an Iso type";let a=P(o,n),s=e.$?.type;if(s&&n.isoTypes?.has(a)){let c=n.isoTypes.get(a);c.optionTypeCName||(c.optionTypeCName=P(s,n))}let l=`__yo_iso_extract_${a}(${i})`,u=e.$?.variableName;return u&&s?(n.emitter.emitLine(`${t}${P(s,n)} ${u} = ${l};`),u):l}function x_(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_dispose requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type;return!o||!kt(o)?"// Error: __yo_iso_dispose requires an Iso type":`__yo_iso_dispose_${P(o,n)}(${i})`}function Tl(e){let t=e.func.$?.value;return O(t)&&kt(t.value)&&e.args.length===1}function D_(e,t,n){if(!Tl(e))return"/* Error: generateIsoTypeCall called on non-Iso type call */";let i=(e.func.$?.value).value,o=i.childType,a=e.args[0],s=M(a,t,n),l=P(i,n),u=P(o,n);return n.isoTypes||(n.isoTypes=new Map),n.isoTypes.has(l)||n.isoTypes.set(l,{childTypeCName:u,isoType:i}),`__yo_create_iso_${l}(${s})`}function Nr(e){return e===""||e==="break"||e==="continue"||e.startsWith("goto")||e.includes("return")}function Vr(e,t,n){if(F(e)&&E(e,I.begin)){let r=e.args,i=n,o=i.pendingDeferredDrops,a=e.$?.deferredDropExpressions??[];i.pendingDeferredDrops=[...a,...o??[]];let s=i.consumedVarPendingDrops,l=e.$?.consumedVariableDropExpressions??[];i.consumedVarPendingDrops=[...l,...s??[]];for(let c=0;c<r.length-1;c++){let _=r[c],p=M(_,t,n);if(p&&n.emitter.emitLine(`${t}${p};`),nt(_.$?.controlFlow))break}let u="";if(r.length>0){let c=r[r.length-1];if(c.$?.deferredDupExpressions&&c.$.deferredDupExpressions.length>0){if(c.$?.variableName){let p=c.$.variableName;c.$.variableName=void 0;let f=M(c,t,n);c.$.variableName=p;let m=P(c.$.type,n),g=Ee(p,c.$.env);g!==f&&n.emitter.emitLine(`${t}${m} ${g} = ${f};`)}rt(c,t,n);let _=c.$.deferredDupExpressions[0];F(_)&&_.$?.variableName?u=Ee(_.$.variableName,_.$.env):u=M(c,t,n)}else u=M(c,t,n)}return e.$?.deferredDropExpressions&&Ct(e,t,n),i.pendingDeferredDrops=o,i.consumedVarPendingDrops=s,u}else return e.$?.deferredDupExpressions&&rt(e,t,n),M(e,t,n)}function O_(e,t,n){if(!e.$)return'/* "match" expression is not evaluated */';let r=e.$.variableName,i=e.$.type,o=i&&pe(i);if(!o&&r){let g=P(i,n);n.emitter.emitLine(`${t}${g} ${r};`)}let a=M(e.args[0],t,n),s=e.args[0].$?.type;if(!s)return'// Error: "match" expression requires a valid type';if(e.$.isPrimitiveMatch)return _g(e,t,n,a,s,r,o);let l,u;if(Ie(s)?(u=s.childType,l=s.tag):pt(s)?(u=s,l="ref_semantics"):u=s,!ge(u))return'// Error: "match" expression requires an enum type';if(!n.types[u.id]?.cName)return`// Error: "match" expression enum type ${u.typeName} has no C name`;let _=Yt(u);if(_){let g=e.args.slice(1),h=null,d=null;for(let v of g)if(F(v)&&E(v,"=>",2)){if(!v.args[0]?.$?.caseExecuted)continue;let T=v.args[0],$=v.args[1];if(T&&$&&F(T)&&E(T,"."))h={caseBody:$};else{let C=T.func;if(C&&F(C)&&E(C,".")){let L=C.args[0];if(L&&z(L)){let b=L.token.value;d={caseBody:$,variantName:b,casePattern:T}}}}}if(n.emitter.emitLine(`${t}if (${l&&l!=="ref_semantics"?"*":""}${a} != NULL) {`),d){let v;if(F(d.casePattern)&&d.casePattern.args.length>0){let L=d.casePattern.args[0];if(L&&z(L)){v=te(L.token.value);let b=_;n.emitter.emitLine(`${t} ${P(b,n)} ${v} = ${a};`)}}let T=n;v&&(T.inAsyncStateMachine||T.inEffectStateMachine)&&(T.localShadowedVariables||(T.localShadowedVariables=new Set),T.localShadowedVariables.add(v));let $=Vr(d.caseBody,t+" ",n);v&&T.localShadowedVariables&&T.localShadowedVariables.delete(v);let C=Nr($);if(!o&&r&&!C){let L=$||a;n.emitter.emitLine(`${t} ${r} = ${L};`)}else $&&$!==""&&n.emitter.emitLine(`${t} ${$};`)}if(n.emitter.emitLine(`${t}} else {`),h){let v=Vr(h.caseBody,t+" ",n),T=Nr(v);!o&&r&&!T?n.emitter.emitLine(`${t} ${r} = ${v};`):v&&v!==""&&n.emitter.emitLine(`${t} ${v};`)}return n.emitter.emitLine(`${t}}`),o?"":r??""}if(Fn(u)){n.emitter.emitLine(`${t}switch (${l&&l!=="ref_semantics"?"*":""}${a}) {`);let g=n.insideMatch;n.insideMatch=!0;let h=e.args.slice(1);for(let d=0;d<h.length;d++){let v=h[d];if(F(v)&&E(v,"=>",2)){if(!v.args[0]?.$?.caseExecuted)continue;let T=v.args[0],$=v.args[1];if(T&&$&&z(T)&&T.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let C=Vr($,t+" ",n);!o&&r&&C&&!Nr(C)?n.emitter.emitLine(`${t} ${r} = ${C};`):C&&n.emitter.emitLine(`${t} ${C};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(T&&$&&F(T)&&E(T,".",1)){let C=T.args[0].token.value,L=Bt(u,C,n);n.emitter.emitLine(`${t}case ${L}: {`);let b=Vr($,t+" ",n);!o&&r&&b&&!Nr(b)?n.emitter.emitLine(`${t} ${r} = ${b};`):b&&n.emitter.emitLine(`${t} ${b};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}}return n.insideMatch=g,n.emitter.emitLine(`${t}}`),o?"":r??""}n.emitter.emitLine(`${t}switch (${l==="ref_semantics"||l?a+"->tag":"("+a+").tag"}) {`);let f=n.insideMatch;n.insideMatch=!0;let m=e.args.slice(1);for(let g=0;g<m.length;g++){let h=m[g];if(F(h)&&E(h,"=>",2)){if(!h.args[0]?.$?.caseExecuted)continue;let d=h.args[0],v=h.args[1];if(d&&v&&z(d)&&d.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let T=Vr(v,t+" ",n);!o&&r&&T&&!Nr(T)?n.emitter.emitLine(`${t} ${r} = ${T};`):T&&n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(d&&v&&F(d)&&d.func.tag==="Atom"&&d.func.token.value==="."&&d.args.length>=1){let T=d.args[0].token.value,$=Bt(u,T,n);if(n.emitter.emitLine(`${t}case ${$}: {`),d.args.length>1){let L=u.variants.find(b=>b.name===T);if(L&&L.fields){let b=d.args.slice(1);if(b.some(N=>F(N)&&E(N,":",2))){for(let N of b)if(F(N)&&E(N,":",2)){let B=N.args[0],D=N.args[1];if(!z(B))continue;let V=B.token.value,U=L.fields.find(re=>re.label===V);if(!U||pe(U.type))continue;if(z(D)){let re=D.token.value;if(re!=="_"){let j=te(re),W=te(V),le=P(U.type,n),_e=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${le} ${j} = ${a}${_e}data.${T}.${W};`);let ve=n;if((ve?.inAsyncStateMachine||ve?.inEffectStateMachine)&&ve.stateMachineVariables){let q;if(D.$?.env){let Z=X(D.$.env,re);Z.length>0&&(q=Z[Z.length-1].id)}if(q&&ve.stateMachineVariables.has(q)){let Z=rn(q,"local",ve.stateMachineFieldAliases);n.emitter.emitLine(`${t} sm->${Z} = ${j};`)}}}}}}else for(let N=0;N<b.length&&N<L.fields.length;N++){let B=b[N],D=L.fields[N];if(z(B)&&D){if(pe(D.type))continue;let V=B.token.value;if(V!=="_"){let U=te(V),re=te(D.label),j=P(D.type,n),W=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${j} ${U} = ${a}${W}data.${T}.${re};`);let le=n;if((le?.inAsyncStateMachine||le?.inEffectStateMachine)&&le.stateMachineVariables){let _e;if(B.$?.env){let ve=X(B.$.env,V);ve.length>0&&(_e=ve[ve.length-1].id)}_e&&le.stateMachineVariables.has(_e)&&n.emitter.emitLine(`${t} sm->${rn(_e,"local",le.stateMachineFieldAliases)} = ${U};`)}}}}}}if(F(v)&&E(v,"=>",2)){let L=v.args[0];n.emitter.emitLine(`${t} ${P(s,n)} ${te(L.token.value)} = ${a};`),v=v.args[1]}let C=Vr(v,t+" ",n);!o&&r&&C&&!Nr(C)?n.emitter.emitLine(`${t} ${r} = ${C};`):C&&n.emitter.emitLine(`${t} ${C};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(d&&v&&F(d)&&F(d.func)&&d.func.func.tag==="Atom"&&d.func.func.token.value==="."&&d.func.args.length===1){let T=d.func.args[0].token.value,$=Bt(u,T,n),C=d.args;n.emitter.emitLine(`${t}case ${$}: {`);let L=u.variants.find(R=>R.name===T);if(L&&L.fields&&C.length>0)if(C.some(N=>F(N)&&E(N,":",2))){for(let N of C)if(F(N)&&E(N,":",2)){let B=N.args[0],D=N.args[1];if(!z(B))continue;let V=B.token.value,U=L.fields.find(re=>re.label===V);if(!U)continue;if(z(D)){let re=D.token.value;if(re!=="_"){let j=te(re);if(pe(U.type))n.emitter.emitLine(`${t} // ${j} is unit type (no value)`);else{let W=te(V),le=P(U.type,n),_e=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${le} ${j} = ${a}${_e}data.${T}.${W};`);let ve=n;if((ve?.inAsyncStateMachine||ve?.inEffectStateMachine)&&ve.stateMachineVariables){let q;if(D.$?.env){let Z=X(D.$.env,j);Z.length>0&&(q=Z[Z.length-1].id)}q&&ve.stateMachineVariables.has(q)&&n.emitter.emitLine(`${t} sm->${rn(q,"local",ve.stateMachineFieldAliases)} = ${j};`)}}}}}}else for(let N=0;N<Math.min(C.length,L.fields.length);N++){let B=C[N],D=L.fields[N];if(B.tag==="Atom"&&D){let V=B.token.value;if(V!=="_"){let U=te(V);if(pe(D.type))n.emitter.emitLine(`${t} // ${U} is unit type (no value)`);else{let re=te(D.label),j=P(D.type,n),W=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${j} ${U} = ${a}${W}data.${T}.${re};`);let le=n;if((le?.inAsyncStateMachine||le?.inEffectStateMachine)&&le.stateMachineVariables){let _e;if(B.$?.env){let ve=X(B.$.env,V);ve.length>0&&(_e=ve[ve.length-1].id)}_e&&le.stateMachineVariables.has(_e)&&n.emitter.emitLine(`${t} sm->${rn(_e,"local",le.stateMachineFieldAliases)} = ${U};`)}}}}}if(F(v)&&E(v,"=>",2)){let R=v.args[0];n.emitter.emitLine(`${t} ${P(s,n)} ${te(R.token.value)} = ${a};`),v=v.args[1]}let b=Vr(v,t+" ",n);!o&&r&&b&&!Nr(b)?n.emitter.emitLine(`${t} ${r} = ${b};`):b&&n.emitter.emitLine(`${t} ${b};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}}return n.insideMatch=f,n.emitter.emitLine(`${t}}`),e.$?.deferredDropExpressions&&Ct(e,t,n),o?"":r??""}function cg(e){return F(e)?E(e,"|",2):!1}function El(e){if(!cg(e))return[e];let t=e,n=t.args[0],r=t.args[1];return[...El(n),...El(r)]}function M_(e){if(e!==void 0){if(ze(e))return String(e.value);if(Re(e))return e.value?"true":"false"}}function _g(e,t,n,r,i,o,a){let s=n.insideMatch;n.insideMatch=!0,n.emitter.emitLine(`${t}switch (${r}) {`);let l=e.args.slice(1);for(let u=0;u<l.length;u++){let c=l[u];if(F(c)&&E(c,"=>",2)){if(!c.args[0]?.$?.caseExecuted)continue;let _=c.args[0],p=c.args[1];if(!_||!p)continue;if(z(_)&&_.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let h=Vr(p,t+" ",n);!a&&o&&h&&!Nr(h)?n.emitter.emitLine(`${t} ${o} = ${h};`):h&&n.emitter.emitLine(`${t} ${h};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`);continue}let f=El(_),m=_.$?.primitivePatternValues;if(m&&m.length>0)for(let h of m){let d=M_(h);d!==void 0&&n.emitter.emitLine(`${t}case ${d}:`)}else for(let h of f){let d=h.$?.value,v=M_(d);v!==void 0&&n.emitter.emitLine(`${t}case ${v}:`)}n.emitter.emitLine(`${t}{`);let g=Vr(p,t+" ",n);!a&&o&&g&&!Nr(g)?n.emitter.emitLine(`${t} ${o} = ${g};`):g&&n.emitter.emitLine(`${t} ${g};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}return n.insideMatch=s,n.emitter.emitLine(`${t}}`),e.$?.deferredDropExpressions&&Ct(e,t,n),a?"":o??""}function R_(e,t,n){if(e.$?.runtimeDestructurings&&e.$.runtimeDestructurings.length>0){let r=e.args[0];if(!r||!r.$?.type)return"// Error: open expression has no argument or type";let i=r.$.type,o=r.$.value;if(ce(i)&&o===void 0){let a=M(r,t,n),s=e.$.runtimeDestructurings;for(let l of s){let u=P(l.type,n),c=te(l.variableName),_=te(l.label);n.emitter.emitLine(`${t}${u} ${c} = ${a}.${_};`)}}}return""}function P_(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(!r||r.length!==1)return"/* Error: __yo_thread_spawn requires exactly 1 argument */";let i=r[0],o=i.$?.type;if(!o)return"/* Error: __yo_thread_spawn argument has no type */";let a,s;if(x(o)){let g=o;g.resolvedConcreteType&&(a=g.resolvedConcreteType.id,s=g.resolvedConcreteType)}else ce(o)&&(a=o.id,s=o);if(!a||!s)return"/* Error: __yo_thread_spawn could not determine concrete closure type */";let l=n.implClosureCallMap.get(a);if(!l)return`/* Error: __yo_thread_spawn could not find closure function for type ${a} */`;let u=l.functionCName,c=P(s,n),_=M(i,t,n),p=i.$?.variableName?Ee(i.$.variableName,i.$.env):_,f=`_thread_closure_data_${qe(e.$?.env.modulePath??"")}`;n.emitter.emitLine(`${t}${c}* ${f} = (${c}*)__yo_malloc(sizeof(${c}));`),n.emitter.emitLine(`${t}*${f} = ${p};`);let m=e.$?.variableName;return m?(n.emitter.emitLine(`${t}__yo_thread_t ${m} = __yo_thread_spawn(${u}, ${f});`),m):`__yo_thread_spawn(${u}, ${f})`}function U_(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(!r||r.length!==1)return"/* Error: __yo_worker_spawn requires exactly 1 argument */";let i=r[0],o=i.$?.type;if(!o)return"/* Error: __yo_worker_spawn argument has no type */";let a,s;if(x(o)){let m=o;m.resolvedConcreteType&&(a=m.resolvedConcreteType.id,s=m.resolvedConcreteType)}else ce(o)&&(a=o.id,s=o);if(!a||!s)return"/* Error: __yo_worker_spawn could not determine concrete closure type */";let l=n.implClosureCallMap.get(a);if(!l)return`/* Error: __yo_worker_spawn could not find closure function for type ${a} */`;let u=l.functionCName,c=P(s,n),_=M(i,t,n),p=i.$?.variableName?Ee(i.$.variableName,i.$.env):_,f=`_worker_closure_data_${qe(e.$?.env.modulePath??"")}`;return n.emitter.emitLine(`${t}${c}* ${f} = (${c}*)__yo_malloc(sizeof(${c}));`),n.emitter.emitLine(`${t}*${f} = ${p};`),n.emitter.emitLine(`${t}__yo_worker_spawn(${u}, ${f});`),""}function z_(e,t,n){let r=e.args[0];return r?`__yo_thread_set_maximum_threads(${M(r,t,n)})`:"// Error: __yo_thread_set_maximum_threads requires exactly 1 argument"}function B_(e,t){let n=t;if(!(n.inAsyncStateMachine||n.inEffectStateMachine)||!n.stateMachineVariables)return e;for(let[r,i]of n.stateMachineVariables)if(i.name===e)return`sm->${i.kind==="outer"?`__capture.${i.name}`:`var_${r}`}`;return e}function Ln(e,t,n){let r=n;if(!(r.inAsyncStateMachine||r.inEffectStateMachine)||!r.stateMachineVariables)return;let i=r.stateMachineVariables.get(e);if(!i){for(let[,o]of r.stateMachineVariables)if(o.name===e){i=o;break}}if(i&&i.kind!=="outer"){if(i.type&&Ce(i.type))return;let o=`var_${i.id}`,a=te(e);n.emitter.emitLine(`${t}sm->${o} = ${a};`)}}function q_(e,t,n){if(e.$?.value!==void 0&&!de(e.$.value))return e.$?.deferredDropExpressions&&Ct(e,t,n),pe(e.$.type)?"":Qt(e.$.value,n,e);let r=e.func.$?.value,i=e.func.$?.type??(ne(r)?r.specializedType??r.type:void 0);if(G(i)){let o=e.$?.runtimeArgExprsInOrder;if(o){let a=!1;if(F(e.func)&&E(e.func,".",2)){let c=e.func.args[0]?.$?.type;c&&be(c)&&(a=!0)}let s=o.map((u,c)=>{if(u.$?.variableName&&u.$?.type){let _=n,p=_.currentClosureCaptures&&_.currentClosureCaptures.includes(u.$.variableName)&&z(u)&&u.$.env&&_.currentClosureCaptureFrameLevel!==void 0&&vr(u.token.value,u.$.env,_.currentClosureCaptureFrameLevel),f=M(u,t,n),m=!1;if(z(u)&&u.$.env&&u.$.variableName){let v=X(u.$.env,u.$.variableName);v.length>0&&v[v.length-1].isCompileTimeOnly&&(m=!0)}let g=(_.inAsyncStateMachine||_.inEffectStateMachine)&&f.startsWith("sm->"),h=!1;if(f&&f!==u.$.variableName&&!p&&!g&&!m){let v=Ee(u.$.variableName,u.$.env);if(f!==v){let T=u.$.convertedRuntimeType||u.$.type,$=st(T,u.$.variableName,n);n.emitter.emitLine(`${t}${$} = ${f};`),h=!0,Ln(u.$.variableName,t,n)}}let d=h?u.$.variableName:f;if(u.$?.deferredDupExpressions&&u.$.deferredDupExpressions.length>0){let v=new Set;u.$?.variableName&&v.add(Ee(u.$.variableName,u.$.env)),f&&v.add(f),z(u)&&v.add(Ee(u.token.value,u.$.env));let T=u.$.deferredDupExpressions.find($=>{let C=Ra($);return C?v.has(Ee(C,$.$?.env)):!1});T&&(rt(u,t,_),F(T)&&T.$?.variableName&&(d=Ee(T.$.variableName,T.$.env)))}if(a&&c===0){if(F(e.func)&&E(e.func,".",2)){let $=e.func.args[0]?.$?.type,C=e.func.args[1];if(z(C)&&be($)){let L=C.token.value;if($.trait.fields.find(R=>R.label===L))return g?f:te(d,u.$.type.isExtern==="c")}}let v=u.$?.type;return v&&Ie(v)?g?`${f}->data`:`${te(d,u.$.type.isExtern==="c")}->data`:g?`(${f}).data`:`(${te(d,u.$.type.isExtern==="c")}).data`}else return p||g||m?f:te(d,u.$.type.isExtern==="c")}else if(a&&c===0){let _=M(u,t,n);if(F(e.func)&&E(e.func,".",2)){let m=e.func.args[0]?.$?.type,g=e.func.args[1];if(z(g)&&be(m)){let h=g.token.value;if(m.trait.fields.find(v=>v.label===h))return _}}let p=u.$?.type;return p&&Ie(p)?`(${_})->data`:`(${_}).data`}else return M(u,t,n)}),l=s.join(", ");if(i.isExtern==="yo"&&i.externName){let u=i.externName;return gi.includes(u)?Xo(u,s,e,n,t):u==="__yo_thread_spawn"?P_(e,t,n):u==="__yo_worker_spawn"?U_(e,t,n):pe(i.return.type)?(n.emitter.emitLine(`${t}${u}(${l});`),e.$?.deferredDropExpressions&&Ct(e,t,n),""):`${u}(${l})`}{let u=n;if(u.currentEvidenceParams?.size){let c=e.func.token?.value,_;if(c==="."&&F(e.func)&&E(e.func,".",2)){let p=e.func.args[1];p&&z(p)&&(c=p.token.value);let f=e.func.args[0];if(f&&z(f))_=f.token.value;else if(f&&F(f)&&E(f,".",2)){let m=f.args[0];m&&z(m)&&(_=m.token.value)}}if(c&&c!=="."){for(let p of u.currentEvidenceParams.values())if(p.fieldLabel===c||p.implicitLabel===c||p.fieldPath[p.fieldPath.length-1]===c){if(_&&_!==p.implicitLabel)continue;return W_(p.cParamName,i,s,o,e,t,u,p)}}}}if(ne(r)){let u=Ki(r);if(u)return Xo(u,s,e,n,t);let c=r.specializedType??r.type,_=n;if(_.currentEvidenceParams&&r.isModuleEffectMember){let f,m=e.func.$?.env??e.$?.env;if(m)for(let g of _.currentEvidenceParams.values()){let h=X(m,g.implicitLabel),v=h[h.length-1]?.value?.[0];if(v&&We(v)){let T=v,$=!0;for(let C=0;C<g.fieldPath.length-1;C++){let L=g.fieldPath[C],b=T.type.fields.findIndex(R=>R.label===L);if(b>=0&&T.fields[b]&&We(T.fields[b]))T=T.fields[b];else{$=!1;break}}if($){let C=g.fieldPath[g.fieldPath.length-1],L=T.type.fields.findIndex(b=>b.label===C);if(L>=0){let b=T.fields[L];if(b&&ne(b)&&b.funcId===r.funcId){f=g;break}}}}}if(f){let g=f.cParamName;return W_(g,c,s,o,e,t,_,f)}}let p=n.functions[r.funcId]?.cName;if(p){let f=r.specializedType??r.type,m=Ft(f);if(m.length===0&&r.specializedType){let d=Ft(r.type);d.length>0&&d.some(v=>v.fieldFunctionType.forallParameters&&v.fieldFunctionType.forallParameters.length>0)&&(m=d)}if(m.length>0){let{args:d,isHandlerInstallation:v}=$l(m,r,e,n);if(d.length>0){let T=l?`${l}, ${d.join(", ")}`:d.join(", ");return Cl(p,T,c,e,o,t,n,v)}}let g=r.isControlFunction||r.isModuleEffectMember||r.body?.$?.effectAnalysis?.hasEffects,h=!1;if(g){if(r.isControlFunction||r.isModuleEffectMember){let d=e.func?.$?.env??e.$?.env;if(d){let v=Bo(d,T=>T.isImplicit===!0&&ne(T.value?.[0])&&T.value[0].funcId===r.funcId);v>=0&&v>d.functionDeclarationFrameLevel&&d.frames[v]?.isBeginBlockFrame&&(h=!0)}}else if(r.specializedType){let d=Ft(r.type);if(d.length>0){let v=e.func?.$?.env??e.$?.env;if(v)for(let T of d){let $=Bo(v,C=>C.isImplicit===!0&&(C.name===T.implicitLabel||C.name===T.fieldLabel));if($>=0&&$>v.functionDeclarationFrameLevel&&v.frames[$]?.isBeginBlockFrame){h=!0;break}}}}}if(pe(c.return.type))return n.emitter.emitLine(`${t}${p}(${l});`),e.$?.deferredDropExpressions&&Ct(e,t,n),g&&G_(t,n,h,e),"";{let d=e.$?.variableName;if(d){let v=r.specializedType?.return.type??c.return.type,T=e.$?.type,$=T&&Ce(T),C=v&&Ce(v),L;if($&&C){let b=r.body;if(b&&E(b,"begin")){let R=b.args;if(R.length>0){let N=R[R.length-1];Rt(N)&&(b=N)}}if(b&&Rt(b)&&b.$?.asyncStateMachineStructName){let R=b.$.asyncStateMachineStructName;L=`${R}*`,n.tempVarAsyncStructNames||(n.tempVarAsyncStructNames=new Map),n.tempVarAsyncStructNames.set(d,R)}else T&&x(T)&&T.resolvedConcreteType?L=P(T,n):L=P(v,n)}else L=P(v??T,n);return n.emitter.emitLine(`${t}${L} ${d} = ${p}(${l});`),Ln(d,t,n),e.$?.deferredDropExpressions&&Ct(e,t,n),g&&G_(t,n,h,e),d}else return`// Error: Regular function call returns ${P(r.specializedType?.return.type??c.return.type,n)} but no temp variable assigned`}}}else{let u=n.externFunctions[i.id];if(u){let c=u.cName;return e.$?.deferredDropExpressions&&Ct(e,t,n),`${c}(${l})`}else{let c=M(e.func,t,n);if(r&&G(r.type)){let d=Ft(r.type);if(d.length>0){let{args:v,isHandlerInstallation:T}=$l(d,r,e,n);if(v.length>0){let $=l?`${l}, ${v.join(", ")}`:v.join(", ");return Cl(c,$,i,e,o,t,n,T)}}}let _=e.$?.type??i.return.type,p=P(_,n),f=i.parameters.filter(d=>!d.isCompileTimeOnly).map(d=>P(d.type,n)),m=`((${p} (*)(${f.join(", ")}))${c})`,g=n,h=c.includes("__capture.")&&!!g.inAsyncStateMachine;if(h&&n.emitter.emitLine(`${t}__yo_effect_escaped = 0;`),pe(i.return.type)||pe(_)){if(n.emitter.emitLine(`${t}${m}(${l});`),e.$?.deferredDropExpressions&&Ct(e,t,n),h){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let d of o)if(d.$?.variableName&&d.$?.type&&Le(d.$.type)){let v=B_(te(d.$.variableName),n),T=Ir(v,d.$.type,n);T&&(n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} memset(&${v}, 0, sizeof(${v}));`))}}Mn({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return""}else{let d=e.$?.variableName;if(d){let v=i.return.type,T=e.$?.type,$=T&&v&&Ce(T)&&Ce(v)?v:T??v;if(n.emitter.emitLine(`${t}${P($,n)} ${d} = ${m}(${l});`),Ln(d,t,n),e.$?.deferredDropExpressions&&Ct(e,t,n),h){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let C of o)if(C.$?.variableName&&C.$?.type&&Le(C.$.type)){let L=B_(te(C.$.variableName),n),b=Ir(L,C.$.type,n);b&&(n.emitter.emitLine(`${t} ${b};`),n.emitter.emitLine(`${t} memset(&${L}, 0, sizeof(${L}));`))}}Mn({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return d}else return`// Error: Function parameter call returns ${P(i.return.type,n)} but no temp variable assigned`}}}}}else if(i&&Wt(i)){let o=i,a=nn(o),s=be(o);{let l=a.isFn.callType,u=e.$?.runtimeArgExprsInOrder;if(u){let c=n;for(let g of u)if(g.$?.variableName&&g.$?.type){let h=c.currentClosureCaptures&&c.currentClosureCaptures.includes(g.$.variableName)&&z(g)&&g.$.env&&c.currentClosureCaptureFrameLevel!==void 0&&vr(g.token.value,g.$.env,c.currentClosureCaptureFrameLevel),d=M(g,t,n),v=!1;if(z(g)&&g.$.env&&g.$.variableName){let $=X(g.$.env,g.$.variableName);$.length>0&&$[$.length-1].isCompileTimeOnly&&(v=!0)}let T=(c.inAsyncStateMachine||c.inEffectStateMachine)&&d.startsWith("sm->");if(d&&d!==g.$.variableName&&!h&&!T&&!v){let $=g.$.convertedRuntimeType||g.$.type,C=st($,g.$.variableName,n);n.emitter.emitLine(`${t}${C} = ${d};`),Ln(g.$.variableName,t,n)}}let _=M(e.func,t,n),p=u.map(g=>{if(g.$?.variableName&&g.$?.type){if(c.currentClosureCaptures&&c.currentClosureCaptures.includes(g.$.variableName)&&z(g)&&g.$.env&&c.currentClosureCaptureFrameLevel!==void 0&&vr(g.token.value,g.$.env,c.currentClosureCaptureFrameLevel))return M(g,t,n);{let d=Ee(g.$.variableName,g.$.env),v=(c.inAsyncStateMachine||c.inEffectStateMachine)&&d.startsWith("sm->"),T=d;if(g.$?.deferredDupExpressions&&g.$.deferredDupExpressions.length>0){rt(g,t,c);let $=g.$.deferredDupExpressions[0];F($)&&$.$?.variableName&&(T=Ee($.$.variableName,$.$.env))}return v?d:T}}else return M(g,t,n)}),f;if(s){let g=[`(${_}).data`,...p];f=`(${_}).vtable->call(${g.join(", ")})`}else{let g;if(x(o)){let d=o;d.resolvedConcreteType&&(g=d.resolvedConcreteType.id)}let h=g?n.implClosureCallMap.get(g):void 0;if(h){let d=Ft(l);if(d.length>0){let{args:T,isHandlerInstallation:$}=$l(d,{},e,c);if(T.length>0){let C=[`&(${_})`,...p,...T];return Cl(h.functionCName,C.join(", "),l,e,u,t,c,$)}}let v=[`&(${_})`,...p];f=`${h.functionCName}(${v.join(", ")})`}else{let d=[`(${_}).data`,...p];f=`(${_}).call(${d.join(", ")})`}}let m=l.return.type;if(pe(m))return n.emitter.emitLine(`${t}${f};`),e.$?.deferredDropExpressions&&Ct(e,t,n),"";{let g=e.$?.variableName;return g?(n.emitter.emitLine(`${t}${P(m,n)} ${g} = ${f};`),Ln(g,t,n),e.$?.deferredDropExpressions&&Ct(e,t,n),g):`// Error: Closure call returns ${P(m,n)} but no temp variable assigned`}}else return"// Error: No runtime args found for closure call"}}else if(O(r))if(ce(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=o.fields.map(c=>c.label),u=e.$?.variableName;if(a&&s&&l.length===a.length){if(o.isNewtype&&o.fields.length===1){let c=a[0],_=M(c,t,n),p=_;if(c.$?.deferredDupExpressions&&c.$.deferredDupExpressions.length>0){let m=n;if(c.$?.variableName&&c.$?.type){let h=Ee(c.$.variableName,c.$.env);if(_!==h){let d=c.$.type,v=P(d,n);n.emitter.emitLine(`${t}${v} ${h} = ${_};`)}}rt(c,t,m);let g=c.$.deferredDupExpressions[0];F(g)&&g.$?.variableName&&(p=Ee(g.$.variableName,g.$.env))}let f=`((${s})(${p}))`;if(u&&e.$?.type){let m=st(e.$.type,u,n);return n.emitter.emitLine(`${t}${m} = ${f};`),Ln(u,t,n),u}else return f}if(o.isReferenceSemantics){let c=n,_=a.map(m=>{let g=M(m,t,n);if(m.$?.deferredDupExpressions&&m.$.deferredDupExpressions.length>0){if(m.$?.variableName&&m.$?.type){let d=Ee(m.$.variableName,m.$.env);if(g!==d){let v=m.$.type,T=P(v,n);n.emitter.emitLine(`${t}${T} ${d} = ${g};`)}}rt(m,t,c);let h=m.$.deferredDupExpressions[0];if(F(h)&&h.$?.variableName)return Ee(h.$.variableName,h.$.env)}return g}).join(", "),f=`${`__yo_new_${s}`}(${_})`;if(u&&e.$?.type){let m=st(e.$.type,u,n);return n.emitter.emitLine(`${t}${m} = ${f};`),Ln(u,t,n),u}else return f}else{let c=n,_=a.map((f,m)=>{let g=M(f,t,n),h=we(o)?`_${m}`:te(l[m],o.isExtern==="c"),d=g;if(f.$?.deferredDupExpressions&&f.$.deferredDupExpressions.length>0){if(f.$?.variableName&&f.$?.type){let T=Ee(f.$.variableName,f.$.env),$=f.$.type,C=P($,n);g!==T&&n.emitter.emitLine(`${t}${C} ${T} = ${g};`)}rt(f,t,c);let v=f.$.deferredDupExpressions[0];F(v)&&v.$?.variableName&&(d=Ee(v.$.variableName,v.$.env))}return`.${h} = `+d}).join(", "),p=`(${s}){ ${_} }`;if(u&&e.$?.type){let f=st(e.$.type,u,n);return n.emitter.emitLine(`${t}${f} = ${p};`),Ln(u,t,n),u}else return p}}}else{if(Wt(r.value))return"// Error: Closure construction should have been handled by closureFunctionValue check at top of generateFuncCall";if(it(r.value)){let o=e.$?.variableName,a=e.args[0];if(a&&F(a)&&E(a,":",2)){let s=a.args[0],l=a.args[1],u=n.types[r.value.id]?.cName;if(u&&z(s)&&l){let c=n,_=s.token.value,p=Ee(_,s.$?.env),m=M(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){rt(l,t,c);let h=l.$.deferredDupExpressions[0];F(h)&&h.$?.variableName&&(m=Ee(h.$.variableName,h.$.env))}let g=`(${u}){ .${p} = ${m} }`;if(o&&e.$?.type){let h=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${h} = ${g};`),Ln(o,t,n),o}else return g}}}else if(ge(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=e.$?.variableName;if(o.selectedVariantName&&a&&s){if(Yt(o)){let f=o.selectedVariantName,m=o.variants.find(g=>g.name===f);if(m){if(!m.fields||m.fields.length===0){let g="NULL";if(l&&e.$?.type){let h=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${h} = ${g};`),Ln(l,t,n),l}else return g}else if(m.fields.length===1){let g=M(a[0],t,n);if(l&&e.$?.type){let h=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${h} = ${g};`),Ln(l,t,n),l}else return g}}}if(Fn(o)){let f=o.selectedVariantName,m=Bt(o,f,n);if(l&&e.$?.type){let g=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${g} = ${m};`),Ln(l,t,n),l}else return m}let _=o.selectedVariantName,p=o.variants.find(f=>f.name===_);if(p){let f=p.fields?.filter(d=>!pe(d.type))||[],m=n,g=a.map((d,v)=>{if(p.fields){let T=p.fields[v];if(T&&!pe(T.type)){let $=M(d,t,n),C=Ee(T.label,d.$?.env),L=$;if(d.$?.variableName&&d.$?.type){let b=m.currentClosureCaptures&&m.currentClosureCaptures.includes(d.$.variableName)&&z(d)&&d.$.env&&m.currentClosureCaptureFrameLevel!==void 0&&vr(d.token.value,d.$.env,m.currentClosureCaptureFrameLevel),R=(m.inAsyncStateMachine||m.inEffectStateMachine)&&$.startsWith("sm->"),N=!1;if(z(d)&&d.$.env&&d.$.variableName){let D=X(d.$.env,d.$.variableName);D.length>0&&D[D.length-1].isCompileTimeOnly&&(N=!0)}let B=!1;if($&&$!==d.$.variableName&&!b&&!R&&!N){let D=Ee(d.$.variableName,d.$.env);if($!==D){let V=st(d.$.type,d.$.variableName,n);n.emitter.emitLine(`${t}${V} = ${$};`),B=!0,Ln(d.$.variableName,t,n)}}B&&(L=Ee(d.$.variableName,d.$.env))}if(d.$?.deferredDupExpressions&&d.$.deferredDupExpressions.length>0){rt(d,t,m);let b=d.$.deferredDupExpressions[0];F(b)&&b.$?.variableName&&(L=Ee(b.$.variableName,b.$.env))}return`.${C} = `+L}return""}else return""}).filter(d=>d).join(", "),h=f.length>0?`(${s}){ .tag = ${Bt(o,_,n)}, .data = { .${_} = { ${g} } } }`:`(${s}){ .tag = ${Bt(o,_,n)} }`;if(l&&e.$?.type){let d=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${d} = ${h};`),Ln(l,t,n),l}else return h}}}}else if(ke(i)){let o=e.args[0];if(o&&F(o)&&E(o,":")){let l=M(e.func,t,n),u=M(o.args[0],t,n),c=M(o.args[1],t,n),_=`Slice_${te(P(i.childType,n))}`;return n.sliceStructTypes.has(_)||n.sliceStructTypes.set(_,{childType:P(i.childType,n)}),`(${_}){ .data = &${l}.data[${u}], .length = (${c}) - (${u}) }`}else if(o&&z(o)&&o.token.value===":"){let l=M(e.func,t,n),u=i,c=u.childType,_=`Slice_${te(P(c,n))}`;return n.sliceStructTypes.has(_)||n.sliceStructTypes.set(_,{childType:P(c,n)}),ze(u.length)?`(${_}){ .data = &${l}.data[0], .length = ${u.length.value} }`:"/* Error: Cannot slice array with non-compile-time length */"}let a=M(e.func,t,n),s=M(o,t,n);return`${a}.data[${s}]`}else if(Qe(i)){let o=e.args[0];if(o&&F(o)&&E(o,":")){let l=M(e.func,t,n),u=M(o.args[0],t,n),c=M(o.args[1],t,n),_=`Slice_${te(P(i.childType,n))}`;return n.sliceStructTypes.has(_)||n.sliceStructTypes.set(_,{childType:P(i.childType,n)}),`(${_}){ .data = &${l}.data[${u}], .length = (${c}) - (${u}) }`}else if(o&&z(o)&&o.token.value===":"){let l=M(e.func,t,n),u=`Slice_${te(P(i.childType,n))}`;return n.sliceStructTypes.has(u)||n.sliceStructTypes.set(u,{childType:P(i.childType,n)}),`(${u}){ .data = ${l}.data, .length = ${l}.length }`}let a=M(e.func,t,n),s=M(o,t,n);return`${a}.data[${s}]`}else if(i&&Ie(i)&&Qe(i.childType)){let o=M(e.func,t,n),a=M(e.args[0],t,n);return`${o}.data[${a}]`}}function G_(e,t,n,r){let i=t.emitter;if(i.emitLine(`${e}if (__yo_effect_escaped) {`),t.inAsyncStateMachine||(dn(e+" ",t,r,!1,!0,!1),tr(e+" ",t,r)),t.inAsyncStateMachine)n&&i.emitLine(`${e} __yo_effect_escaped = 0;`),Mn({emitter:i,indent:e+" ",resultCode:void 0,debugLabel:void 0});else if(n){i.emitLine(`${e} __yo_effect_escaped = 0;`);let o=t.currentFunctionType?.return.type;if(o&&!pe(o)){let a=P(o,t);a!=="void"?(i.emitLine(`${e} ${a} _esc_result;`),i.emitLine(`${e} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${a}));`),i.emitLine(`${e} return _esc_result;`)):i.emitLine(`${e} return;`)}else i.emitLine(`${e} return;`)}else{let o=t.currentFunctionType?.return.type;if(o&&!pe(o)){let a=P(o,t);a!=="void"?i.emitLine(`${e} return (${a}){0};`):i.emitLine(`${e} return;`)}else i.emitLine(`${e} return;`)}i.emitLine(`${e}}`)}function W_(e,t,n,r,i,o,a,s){let l=n.join(", "),u=t.return.type,c=a.emitter,_;if(s?.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0){let p=i.$?.type?P(i.$.type,a):P(u,a),f=[],g=s.fieldFunctionType.parameters.filter(d=>!d.isCompileTimeOnly);for(let d=0;d<g.length;d++){let v=g[d].type,T=x(v)&&r?.[d]?.$?.type?r[d].$.type:v,$=G(T)?hr(T,"(*)",a):P(T,a);f.push($)}let h=f.join(", ");_=`((${p} (*)(${h}))${e})`}else _=e;if(pe(u)){if(c.emitLine(`${o}${_}(${l});`),i.$?.deferredDropExpressions&&Ct(i,o,a),c.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,i,!1,!0,!1),tr(o+" ",a,i)),a.inAsyncStateMachine)Mn({emitter:c,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let p=a.currentFunctionType?.return.type;if(p&&!pe(p)){let f=P(p,a);f!=="void"?c.emitLine(`${o} return (${f}){0};`):c.emitLine(`${o} return;`)}else c.emitLine(`${o} return;`)}return c.emitLine(`${o}}`),""}else{let p=i.$?.variableName;if(p){let f=s?.fieldFunctionType.forallParameters?.length&&i.$?.type?i.$.type:u,m=P(f,a);if(m==="void"||pe(f)){if(c.emitLine(`${o}${_}(${l});`),i.$?.deferredDropExpressions&&Ct(i,o,a),c.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,i,!1,!0,!1),tr(o+" ",a,i)),a.inAsyncStateMachine)Mn({emitter:c,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!pe(g)){let h=P(g,a);h!=="void"?c.emitLine(`${o} return (${h}){0};`):c.emitLine(`${o} return;`)}else c.emitLine(`${o} return;`)}return c.emitLine(`${o}}`),""}if(c.emitLine(`${o}${m} ${p} = ${_}(${l});`),i.$?.deferredDropExpressions&&Ct(i,o,a),c.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,i,!1,!0,!1),tr(o+" ",a,i)),a.inAsyncStateMachine)Mn({emitter:c,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!pe(g)){let h=P(g,a);h!=="void"?c.emitLine(`${o} return (${h}){0};`):c.emitLine(`${o} return;`)}else c.emitLine(`${o} return;`)}return c.emitLine(`${o}}`),p}else return`${_}(${l})`}}function $l(e,t,n,r){let i=[],o=t.body?.$?.effectAnalysis,a=!1;for(let s of e){let l=`${s.implicitLabel}.${s.fieldLabel}`,u=!1;if(r.currentEvidenceParams){let c=r.currentEvidenceParams.get(l);c&&(i.push(c.cParamName),u=!0)}if(!u){if(o){if(o.effectHandlerInfos)for(let c of o.effectHandlerInfos){if(c.effectParameterName!==s.fieldLabel&&c.effectParameterName!==s.implicitLabel)continue;let _=c.handlerValue;if(_&&ne(_)){if(_.specializedFunctionCaches?.length){let f=_.specializedFunctionCaches[0].specializedFunction,m=r.functions[f.funcId]?.cName;if(m){i.push(`(void*)${m}`),u=!0,a=!0;break}}let p=r.functions[_.funcId]?.cName;if(p){i.push(p),u=!0,a=!0;break}}}if(!u&&o.handlerValue&&e.length===1){let c=o.handlerValue;if(c&&ne(c)){if(c.specializedFunctionCaches?.length){let _=c.specializedFunctionCaches[0].specializedFunction,p=r.functions[_.funcId]?.cName;p&&(i.push(`(void*)${p}`),u=!0,a=!0)}if(!u){let _=r.functions[c.funcId]?.cName;_&&(i.push(_),u=!0,a=!0)}}}}if(!u){let c=n.func.$?.env??n.$?.env;if(c){let _=X(c,s.implicitLabel),p=fn(c,d=>d.isImplicit===!0&&G(d.type)&&G(s.fieldFunctionType)&&d.type===s.fieldFunctionType),f=_[_.length-1],m=p[p.length-1],h=(m&&m!==f?m:f??m)?.value?.[0];if(h&&We(h)){let d=h,v=!0;for(let T=0;T<s.fieldPath.length-1;T++){let $=s.fieldPath[T],C=d.type.fields.findIndex(L=>L.label===$);if(C>=0&&d.fields[C]&&We(d.fields[C]))d=d.fields[C];else{v=!1;break}}if(v){let T=s.fieldPath[s.fieldPath.length-1],$=d.type.fields.findIndex(C=>C.label===T);if($>=0){let C=d.fields[$];if(C&&ne(C)){if(C.specializedFunctionCaches?.length>0){let L=C.specializedFunctionCaches[0].specializedFunction,b=r.functions[L.funcId]?.cName;b&&(i.push(`(void*)${b}`),u=!0)}if(!u){let L=r.functions[C.funcId]?.cName;L&&(i.push(L),u=!0)}}}}}else if(h&&ne(h)){if(h.specializedFunctionCaches?.length){let d=h.specializedFunctionCaches[0].specializedFunction,v=r.functions[d.funcId]?.cName;v&&(i.push(`(void*)${v}`),u=!0)}if(!u){let d=r.functions[h.funcId]?.cName;d&&(i.push(d),u=!0)}}u&&(a=!0)}}if(!u&&r.stateMachineVariables){let c=s.fieldPath[s.fieldPath.length-1];for(let[,_]of r.stateMachineVariables)if(_.name===c&&_.kind==="outer"){i.push(`sm->__capture.${c}`),u=!0;break}}if(!u)break}}return{args:i,isHandlerInstallation:a}}function Cl(e,t,n,r,i,o,a,s=!1){let l=a.emitter,u=n.return.type;if(l.emitLine(`${o}__yo_effect_escaped = 0;`),pe(u)){if(l.emitLine(`${o}${e}(${t});`),r.$?.deferredDropExpressions&&Ct(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,r,!1,!0,!1),tr(o+" ",a,r)),a.inAsyncStateMachine)Mn({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let c=a.currentFunctionType?.return.type;if(s&&l.emitLine(`${o} __yo_effect_escaped = 0;`),c&&!pe(c))if(s){let _=P(c,a);_!=="void"?(l.emitLine(`${o} ${_} _esc_result;`),l.emitLine(`${o} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${_}));`),l.emitLine(`${o} return _esc_result;`)):l.emitLine(`${o} return;`)}else{let _=P(c,a);_!=="void"?l.emitLine(`${o} return (${_}){0};`):l.emitLine(`${o} return;`)}else l.emitLine(`${o} return;`)}return l.emitLine(`${o}}`),""}else{let c=r.$?.variableName;if(c){let _=P(u,a);if(l.emitLine(`${o}${_} ${c} = ${e}(${t});`),Ln(c,o,a),r.$?.deferredDropExpressions&&Ct(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,r,!1,!0,!1),tr(o+" ",a,r)),a.inAsyncStateMachine)Mn({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let p=a.currentFunctionType?.return.type;if(s&&p&&!pe(p)){let f=P(p,a);l.emitLine(`${o} ${f} _esc_result;`),l.emitLine(`${o} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${f}));`),l.emitLine(`${o} __yo_effect_escaped = 0;`),l.emitLine(`${o} return _esc_result;`)}else if(p&&!pe(p)){let f=P(p,a);f!=="void"?l.emitLine(`${o} return (${f}){0};`):l.emitLine(`${o} return;`)}else s&&l.emitLine(`${o} __yo_effect_escaped = 0;`),l.emitLine(`${o} return;`)}return l.emitLine(`${o}}`),c}else return`${e}(${t})`}}function Y_(e,t,n){let r=n.emitter,i=e.$?.type;if(!i)return"// Error: panic() missing type information";if(e.args.length===0)r.emitLine(`${t}abort();`);else if(e.args.length===1){let a=e.args[0];if(a.$?.value&&Ve(a.$.value)){let s=a.$.value.value;r.emitLine(`${t}fprintf(stderr, "%s\\n", ${JSON.stringify(s)});`),r.emitLine(`${t}abort();`)}else{let s=M(a,t,n);r.emitLine(`${t}fprintf(stderr, "%s\\n", ${s});`),r.emitLine(`${t}abort();`)}}else return`// Error: panic accepts 0 or 1 arguments, got ${e.args.length}`;return`(*((${P(i,n)}*)NULL))`}var pg={reg:{x86_64:"r",aarch64:"r",x86:"r",arm:"r"},reg_byte:{x86_64:"q",x86:"q"},reg_abcd:{x86_64:"Q",x86:"Q"},xmm_reg:{x86_64:"x",aarch64:"w"},ymm_reg:{x86_64:"x"},imm:{x86_64:"i",aarch64:"i",x86:"i",arm:"i"},mem:{x86_64:"m",aarch64:"m",x86:"m",arm:"m"}},fg={rax:"a",eax:"a",ax:"a",al:"a",rbx:"b",ebx:"b",bx:"b",bl:"b",rcx:"c",ecx:"c",cx:"c",cl:"c",rdx:"d",edx:"d",dx:"d",dl:"d",rsi:"S",esi:"S",si:"S",rdi:"D",edi:"D",di:"D"},dg={e:"k",x:"w",l:"b",h:"h",w:"w"};function mg(e,t){if(!e)return"r";if(e.startsWith("raw:"))return e.slice(4);let n=fg[e];if(n)return n;let r=pg[e];return r?r[t]??r.x86_64??"r":e}function yg(e,t){let n="",r=0;for(;r<e.length;)if(e[r]==="{"){if(r+1<e.length&&e[r+1]==="{"){n+="{",r+=2;continue}let i=e.indexOf("}",r+1);if(i===-1){n+=e[r],r++;continue}let o=e.slice(r+1,i),a=o.indexOf(":"),s,l;a>=0?(s=o.slice(0,a),l=o.slice(a+1)):s=o;let u=l?dg[l]??l:void 0,c=parseInt(s,10);isNaN(c)?u?n+=`%${u}[${s}]`:n+=`%[${s}]`:u?n+=`%${u}${c}`:n+=`%${c}`,r=i+1}else e[r]==="}"&&r+1<e.length&&e[r+1]==="}"?(n+="}",r+=2):(n+=e[r],r++);return n}function gg(e,t,n,r){let i=e.args,o=n.targetInfo.arch;if(r==="const_val"){let d,v=0;i.length===2&&i[0].$?.value&&Ve(i[0].$.value)&&(d=i[0].$.value.value,v=1);let T=M(i[v],t,n);return{kind:"const_val",name:d,constraint:"",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}if(r==="sym"){let d,v=0;i.length===2&&i[0].$?.value&&Ve(i[0].$.value)&&(d=i[0].$.value.value,v=1);let T=M(i[v],t,n);return{kind:"sym",name:d,constraint:"i",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}let a,s=0;if(i.length>=2){let d=i[0];d.$?.value&&Ve(d.$.value)&&!(d.tag==="Atom"&&H_(d.token.value))&&(a=d.$.value.value,s=1)}let l=s<i.length-1,u,c;l?(u=hg(i[s],t,n),c=s+1):(a!==void 0&&(u=a),c=s);let _=mg(u,o),p=i[c];if(p.tag==="Atom"&&p.token.value==="_")return{kind:r,name:a,constraint:_,cExpr:"",cType:"int32_t",isDiscarded:!0,isVariableTarget:!1};if(p.$?.value&&O(p.$.value)){let d=p.$.value.value,v=P(d,n);return{kind:r,name:a,constraint:_,cExpr:"",cType:v,isDiscarded:!1,isVariableTarget:!1}}let f=M(p,t,n),m=P(p.$?.type,n),h=(r==="out"||r==="lateout")&&p.tag==="Atom";return{kind:r,name:a,constraint:_,cExpr:f,cType:m,isDiscarded:!1,isVariableTarget:h}}function H_(e){return["reg","reg_byte","reg_abcd","xmm_reg","ymm_reg","imm","mem"].includes(e)}function hg(e,t,n){if(e.tag==="Atom"&&H_(e.token.value))return e.token.value;if(e.$?.value&&Ve(e.$.value))return e.$.value.value;if(E(e,"raw",1)){let r=e;if(r.args[0].$?.value&&Ve(r.args[0].$.value))return`raw:${r.args[0].$.value.value}`}return"r"}function vg(e,t){let n=[];if((e.func.tag==="Atom"?e.func.token.value:"clobber")==="clobber_abi"){let i=t.targetInfo.arch;if(i==="x86_64")n.push("rax","rcx","rdx","rsi","rdi","r8","r9","r10","r11","xmm0","xmm1","xmm2","xmm3","xmm4","xmm5","xmm6","xmm7","xmm8","xmm9","xmm10","xmm11","xmm12","xmm13","xmm14","xmm15","cc","memory");else if(i==="aarch64"){for(let o=0;o<=18;o++)n.push(`x${o}`);n.push("x30");for(let o=0;o<=31;o++)n.push(`v${o}`);n.push("cc","memory")}return n}for(let i of e.args)i.$?.value&&Ve(i.$.value)?n.push(i.$.value.value):i.tag==="Atom"&&n.push(i.token.value);return n}function Tg(e){let t={isVolatile:!0,intelSyntax:!1,noreturn:!1,pure:!1};for(let n of e.args)if(n.tag==="Atom")switch(n.token.value){case"pure":t.pure=!0,t.isVolatile=!1;break;case"intel_syntax":t.intelSyntax=!0;break;case"noreturn":t.noreturn=!0;break;case"volatile":t.isVolatile=!0;break}return t}var bl=0;function j_(e,t,n){let r=n.emitter,i=e.$?.type;if(!i)return"/* Error: asm() missing type information */";if(yi(n.targetInfo))return r.emitLine(`${t}/* Error: inline assembly is not supported on WebAssembly */`),r.emitLine(`${t}abort();`),`(*((${P(i,n)}*)NULL))`;let o=[],a=0;for(;a<e.args.length;){let D=e.args[a];if(F(D))break;if(D.$?.value&&Ve(D.$.value))o.push(D.$.value.value),a++;else break}let s=o.join(`
10260
- `),l=[],u=[],c={isVolatile:!0,intelSyntax:!1,noreturn:!1,pure:!1};for(;a<e.args.length;){let D=e.args[a];if(!F(D)){a++;continue}let V=D.func.tag==="Atom"?D.func.token.value:void 0;if(!V){a++;continue}["in","out","inout","lateout","inlateout","const_val","sym"].includes(V)?l.push(gg(D,t,n,V)):V==="clobber"||V==="clobber_abi"?u.push(...vg(D,n)):V==="asm_options"&&(c=Tg(D)),a++}let _=new Map;for(let D=0;D<l.length;D++)l[D].name&&_.set(l[D].name,D);let p=s;for(let D=0;D<l.length;D++){let V=l[D];V.kind==="const_val"&&(V.name&&(p=p.replace(new RegExp(`\\{${V.name}(?::[^}]*)?\\}`,"g"),V.cExpr)),p=p.replace(new RegExp(`\\{${D}(?::[^}]*)?\\}`,"g"),V.cExpr))}let f=yg(p,_),m=[],g=[],h=[];for(let D=0;D<l.length;D++){let V=l[D];if(V.isDiscarded){let U=`__asm_discard_${bl++}`;h.push({varName:U,cType:V.cType,operandIdx:D}),r.emitLine(`${t}${V.cType} ${U};`)}else if(V.kind==="out"||V.kind==="lateout"){if(!V.isVariableTarget){if(V.cType){let U=`__asm_out_${bl++}`;m.push({varName:U,cType:V.cType,operandIdx:D}),r.emitLine(`${t}${V.cType} ${U};`)}}}else if(V.kind==="inout"||V.kind==="inlateout"){let U=`__asm_inout_${bl++}`;g.push({varName:U,cType:V.cType,initExpr:V.cExpr,operandIdx:D}),r.emitLine(`${t}${V.cType} ${U} = ${V.cExpr};`)}}let d=c.isVolatile?" __volatile__":"",v=f;c.intelSyntax&&(n.needsIntelAsmSyntax=!0);let T=JSON.stringify(v),$=[];for(let D=0;D<l.length;D++){let V=l[D];if(V.kind==="in"||V.kind==="const_val"||V.kind==="sym")continue;let U;V.kind==="out"||V.kind==="lateout"?U=V.kind==="lateout"?"=&":"=":U=V.kind==="inlateout"?"+&":"+";let re=`${U}${V.constraint}`,j=V.name?`[${V.name}] `:"",W;V.isDiscarded?W=h.find(_e=>_e.operandIdx===D).varName:V.isVariableTarget?W=V.cExpr:V.kind==="out"||V.kind==="lateout"?W=m.find(_e=>_e.operandIdx===D).varName:W=g.find(_e=>_e.operandIdx===D).varName,$.push(`${j}"${re}" (${W})`)}let C=[];for(let D=0;D<l.length;D++){let V=l[D];if(V.kind!=="in"&&V.kind!=="sym")continue;let U=V.constraint,re=V.name?`[${V.name}] `:"";C.push(`${re}"${U}" (${V.cExpr})`)}let L=u.map(D=>`"${D}"`),b=$.join(", "),R=C.join(", "),N=L.join(", ");if(r.emitLine(`${t}__asm__${d} (`),r.emitLine(`${t} ${T}`),r.emitLine(`${t} : ${b}`),r.emitLine(`${t} : ${R}`),r.emitLine(`${t} : ${N}`),r.emitLine(`${t});`),c.noreturn)return r.emitLine(`${t}__builtin_unreachable();`),`(*((${P(i,n)}*)NULL))`;if(pe(i))return"";let B=[];for(let D=0;D<l.length;D++){let V=l[D];if(!(V.isDiscarded||V.isVariableTarget)&&!(V.kind==="in"||V.kind==="const_val"||V.kind==="sym"))if(V.kind==="out"||V.kind==="lateout"){let U=m.find(re=>re.operandIdx===D);U&&B.push(U.varName)}else{let U=g.find(re=>re.operandIdx===D);U&&B.push(U.varName)}}if(B.length===1)return B[0];if(B.length>1){let D=P(i,n),V=B.map((U,re)=>`._${re} = ${U}`).join(", ");return`((${D}){ ${V} })`}return""}function K_(e,t,n){if(yi(n.targetInfo))return"/* global_asm skipped: not supported on this target */";let r=e.args[0];if(r.$?.value&&Ve(r.$.value)){let i=r.$.value.value;n.emitter.emitDeclarationLine(`__asm__(${JSON.stringify(i)});`)}return""}function X_(e,t,n){if(e.args.length!==2)return"/* ERROR: field access requires exactly 2 arguments */";let r=e.args[0],i=e.args[1];if(!r||!i)return"/* ERROR: invalid field access arguments */";let o=M(r,t,n),a=r.$?.type,s=r.$?.value;if(z(i)){let l=i.token.value,u=n;if(u.currentEvidenceParams&&z(r)){let _=`${r.token.value}.${l}`,p=u.currentEvidenceParams.get(_);if(p)return p.cParamName}if(e.$?.value&&ne(e.$.value)){let c=e.$.value;return n.functions[c.funcId]?.cName||c.funcId}if(!e.$?.value&&(k.___dispose.includes(l)||k.___drop.includes(l)||k.___dup.includes(l))&&a){let c=null;if((ce(a)||ge(a))&&(c=a.trait),c){let _=c.fields.find(p=>p.label===l&&p.assignedValue&&ne(p.assignedValue));if(_&&ne(_.assignedValue)){let p=_.assignedValue;return n.functions[p.funcId]?.cName||p.funcId}else return`/* ERROR: Rc method ${l} not found in type module */`}else return`/* ERROR: No module found for Rc method ${l} */`}if(Te(a)||We(s)){let c=e.$?.value;if(c){if(de(c)){if(c.variableName)return Ee(c.variableName,e.$?.env);if((u.inAsyncStateMachine||u.inEffectStateMachine)&&u.stateMachineVariables){for(let[,_]of u.stateMachineVariables)if(_.name===l&&_.kind==="outer")return`sm->__capture.${l}`}}else if(!We(c))return Qt(c,n,e)}return Ee(l,e.$?.env)}if(Er(a)&&a.fields.length===1){let c=a.fields[0];if(c&&c.label===l)return o}if(ge(a)){let c=a;if(Yt(c))return o;for(let p of c.variants)if(p.fields){for(let f of p.fields)if(f.label===l){let m=p.name;return`${o}.data.${m}.${te(l)}`}}return`/* ERROR: field ${l} not found in enum ${c.typeName} */`}else if(O(s)&&ge(s.value)){let c=s.value,_=c.variants.find(f=>f.name===l),p=n.types[c.id]?.cName;if(_&&!_.fields&&p){let f=Bt(c,_.name,n);return`(${p}){ .tag = ${f}, .data = { } }`}}else{if($t(a)&&l==="*")return`${o}->value`;if(Ie(a)){if(l==="*")return`(*${o})`;if(Qe(a.childType))return`${o}->${te(l)}`;{let c=0,_=a;for(;Ie(_);)c++,_=_.childType;if(c>0&&ce(_)&&_.isReferenceSemantics&&c++,Er(_)&&_.fields.length===1){let p=_.fields[0];if(p&&p.label===l)return c===1?`(*${o})`:`${"*".repeat(c)}(${o})`}return c>0?c===1?`${o}->${te(l)}`:`${`(${"*".repeat(c-1)}${o})`}->${te(l)}`:`${o}.${te(l)}`}}else if(we(a)){if(l.match(/^\d+$/))return`${o}._${l}`;{let c=a.fields.findIndex(_=>_.label===l);return`${o}._${c}`}}else return be(a)?`${o}.vtable->${te(l)}`:pt(a)?`${o}->${te(l)}`:`${o}.${te(l)}`}}return"/* ERROR: field name must be an identifier */"}function Q_(e,t,n){if(!e.$?.type)return`// Error: No type information for pointer/reference expression ${w(e)}
10261
- `;let i=e.args[0];if(F(i)){let l=i.func.$?.type;if(l&&ke(l)){let u=i.args[0];if(u&&F(u)&&E(u,":")){let c=M(i.func,t,n),_=M(u.args[0],t,n),p=M(u.args[1],t,n),f=`Slice_${te(P(l.childType,n))}`;return n.sliceStructTypes.has(f)||n.sliceStructTypes.set(f,{childType:P(l.childType,n)}),`(${f}){ .data = &${c}.data[${_}], .length = ${p} - ${_} }`}else if(u&&z(u)&&u.token.value===":"){let c=M(i.func,t,n),_=l,p=_.childType,f=`Slice_${te(P(p,n))}`;return n.sliceStructTypes.has(f)||n.sliceStructTypes.set(f,{childType:P(p,n)}),ze(_.length)?`(${f}){ .data = &${c}.data[0], .length = ${_.length.value} }`:"/* Error: Cannot slice array with non-compile-time length */"}}else if(l&&(Qe(l)||Ie(l)&&Qe(l.childType))){let u=Qe(l)?l:l.childType,c=i.args[0];if(c&&F(c)&&E(c,":")){let _=M(i.func,t,n),p=M(c.args[0],t,n),f=M(c.args[1],t,n),m=`Slice_${te(P(u.childType,n))}`;return n.sliceStructTypes.has(m)||n.sliceStructTypes.set(m,{childType:P(u.childType,n)}),`(${m}){ .data = &${_}.data[${p}], .length = ${f} - ${p} }`}else if(c&&z(c)&&c.token.value===":"){let _=M(i.func,t,n),p=`Slice_${te(P(u.childType,n))}`;return n.sliceStructTypes.has(p)||n.sliceStructTypes.set(p,{childType:P(u.childType,n)}),`(${p}){ .data = ${_}.data, .length = ${_}.length }`}}}let o=i.$?.value,a=i.$?.type;if(o!==void 0&&a){if(ze(o)||Re(o)){let l=M(i,t,n);return`(&(${P(a,n)}){${l}})`}if(Ve(o)&&i.$?.convertedRuntimeType)return`(&${M(i,t,n)})`}return`(&${M(i,t,n)})`}function Z_(e,t,n){let r=e.args[0];return r?`__yo_decr_rc(${M(r,t,n)})`:"// Error: __yo_decr_rc requires exactly 1 argument"}function J_(e,t,n){let r=e.args[0];return r?`__yo_incr_rc(${M(r,t,n)})`:"// Error: __yo_incr_rc requires exactly 1 argument"}function ep(e,t,n){let r=e.args[0];return r?M(r,t,n):"// Error: __yo_rc_own requires exactly 1 argument"}function tp(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_drop_array_element requires exactly 2 arguments";let o=M(r,t,n),a=M(i,t,n),s=r.$?.type;if(!s||!ke(s))return"// Error: __yo_drop_array_element requires an array type";let l=s.childType,u=x(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let _=u.length;if(!ze(_))return"// Error: array element has non-constant length";let p=`i_${Math.floor(Math.random()*1e6)}`,f=n.emitter;f.emitLine(`for (size_t ${p} = 0; ${p} < ${_.value}; ${p}++) {`);let m=`(${o}).data[${a}].data[${p}]`;f.emitLine(" { // drop nested array element");let g=Ir(m,u.childType,n);return g&&f.emitLine(` ${g};`),f.emitLine(" }"),f.emitLine("}"),""}let c=gr(u,n);return c?`${c}((${o}).data[${a}])`:"// No drop function for array element type"}function np(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_dup_array_element requires exactly 2 arguments";let o=M(r,t,n),a=M(i,t,n),s=r.$?.type;if(!s||!ke(s))return"// Error: __yo_dup_array_element requires an array type";let l=s.childType,u=x(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let _=u.length;if(!ze(_))return"// Error: array element has non-constant length";let p=`temp_array_${Math.floor(Math.random()*1e6)}`,f=`i_${Math.floor(Math.random()*1e6)}`,m=P(u,n),g=n.emitter;g.emitLine(`${m} ${p} = (${o}).data[${a}];`),g.emitLine(`for (size_t ${f} = 0; ${f} < ${_.value}; ${f}++) {`);let h=Xi(`${p}.data[${f}]`,u.childType,n);return g.emitLine(` ${p}.data[${f}] = ${h};`),g.emitLine("}"),p}let c=On(u,n);return c?`${c}((${o}).data[${a}])`:"// No dup function for array element type"}function rp(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_drop_tuple_element requires exactly 2 arguments";let o=M(r,t,n);M(i,t,n);let a=r.$?.type;if(!a||!we(a))return"// Error: __yo_drop_tuple_element requires a tuple type";let s=i.$?.value;if(!ze(s))return"// Error: __yo_drop_tuple_element requires a constant index";let l=Number(s.value);if(l<0||l>=a.fields.length)return"// Error: __yo_drop_tuple_element index out of bounds";let u=a.fields[l].type,c=x(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(we(c)){let p=`(${o})._${l}`;return Ir(p,c,n)}let _=gr(c,n);return _?`${_}((${o})._${l})`:"// No drop function for tuple element type"}function ip(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_dup_tuple_element requires exactly 2 arguments";let o=M(r,t,n);M(i,t,n);let a=r.$?.type;if(!a||!we(a))return"// Error: __yo_dup_tuple_element requires a tuple type";let s=i.$?.value;if(!ze(s))return"// Error: __yo_dup_tuple_element requires a constant index";let l=Number(s.value);if(l<0||l>=a.fields.length)return"// Error: __yo_dup_tuple_element index out of bounds";let u=a.fields[l].type,c=x(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(we(c)){let p=`(${o})._${l}`;return Xi(p,c,n)}let _=On(c,n);return _?`${_}((${o})._${l})`:"// No dup function for tuple element type"}function op(e,t,n){let r=e.args[0];if(!r)return"// Error: ___dup requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type??e.$?.type;return o?Xi(i,o,n):i}function ap(e,t,n){let r=e.args[0];if(!r)return"// Error: ___drop requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type??e.$?.type;return o?Ir(i,o,n):""}function sp(e,t,n){let r=e.args[0];return r?`__yo_decr_rc((void*)(${M(r,t,n)}).data)`:"// Error: __yo_dyn_drop requires exactly 1 argument"}function lp(e,t,n){let r=e.args[0];return r?`__yo_incr_rc((void*)(${M(r,t,n)}).data)`:"// Error: __yo_dyn_dup requires exactly 1 argument"}function up(e,t,n){let r=e.args[0];return r?`__yo_incr_rc_atomic(${M(r,t,n)})`:"// Error: __yo_incr_rc_atomic requires exactly 1 argument"}function cp(e,t,n){let r=e.args[0];return r?`__yo_decr_rc_atomic(${M(r,t,n)})`:"// Error: __yo_decr_rc_atomic requires exactly 1 argument"}function _p(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_sometype_drop requires exactly 1 argument";let i=r.$?.type;if(i&&x(i)&&Ce(i)){let o=M(r,t,n);return`if (${o} != NULL) { __yo_decr_rc((void*)${o}); }`}if(i&&x(i)&&i.resolvedConcreteType){let a=i.resolvedConcreteType.trait?.fields.find(s=>s.label===k.___drop[0]);if(a&&a.assignedValue&&ne(a.assignedValue)){let s=n.functions[a.assignedValue.funcId]?.cName;if(s){let l=M(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_drop: no-op */"}function pp(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_sometype_dup requires exactly 1 argument";let i=r.$?.type;if(i&&x(i)&&Ce(i))return`__yo_incr_rc((void*)${M(r,t,n)})`;if(i&&x(i)&&i.resolvedConcreteType){let a=i.resolvedConcreteType.trait?.fields.find(s=>s.label===k.___dup[0]);if(a&&a.assignedValue&&ne(a.assignedValue)){let s=n.functions[a.assignedValue.funcId]?.cName;if(s){let l=M(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_dup: no-op */"}function fp(e,t,n){if(e.args.length!==1)return"// Error: rc requires exactly 1 argument";let r=e.args[0],i=r.$?.type;if(!i)return"// Error: rc argument missing type information";let o=M(r,t,n);return sn(i)?`((__yo_ref_header_t*)(${o}))->ref_count`:"1"}function dp(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(r){let i=n,o=r.map(a=>{let s=M(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){rt(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return Ee(l.$.variableName,l.$.env)}return s}).join(", ");return`${n.currentFunctionName}(${o})`}else return`// Error: No arguments for recur call ${w(e)}
10262
- `}function mp(e,t,n){let r=e.args[0];return`sizeof(${M(r,t,n)})`}function yp(e,t,n){let r=e.$?.runtimeArgExprsInOrder,i=n.types[e.$?.type?.id??""]?.cName,o=e.$?.variableName;if(r&&i){let a=n,s=r.map((l,u)=>{let _=M(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){rt(l,t,a);let p=l.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(_=Ee(p.$.variableName,p.$.env))}return`._${u} = ${_}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${u} = ${l};`),o}else return`(${i}){ ${s} }`}else{if(e.args.length===0)return"";{let a=r??e.args;if(!i)return`/* Error: tuple type not found - typeId: ${e.$?.type?.id??"none"} */`;let s=a.map((l,u)=>{let c=M(l,t,n);return`._${u} = ${c}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${u} = ${l};`),o}else return`(${i}){ ${s} }`}}}function gp(e,t,n){let i=e.args[0].$?.value;if(!i||!O(i))throw new Error("typeid codegen: expected TypeValue argument");let o=i.value,a=o.id,s=n.types[a]?.cName||P(o,n),l=`__yo_typeid_${te(s)}`;return n.typeIdStatics||(n.typeIdStatics=new Map),n.typeIdStatics.has(a)||(n.typeIdStatics.set(a,l),n.emitter.emitDeclarationLine(`static const char ${l} = 0;`)),n.cIncludes.add("<stdint.h>"),`(uintptr_t)&${l}`}function Eg(e,t){if(F(e)&&E(e,I.begin)){let n=[];for(let r of e.args)if(F(r)&&E(r,"=",2)){let i=r.args[0],o=r.args[1],a=M(i,"",t),s=M(o,"",t);n.push(`${a} = ${s}`)}return n.join(", ")}else if(F(e)&&E(e,"=",2)){let n=e.args[0],r=e.args[1],i=M(n,"",t),o=M(r,"",t);return`${i} = ${o}`}return M(e,"",t)}function kl(e,t,n){if(F(e)&&E(e,I.begin)){let r=n,i=r.pendingDeferredDrops,o=e.$?.deferredDropExpressions??[],a=new Map;for(let c of o){let _=In(c);_&&a.set(_,c)}r.pendingDeferredDrops=[...i??[]];let s=r.consumedVarPendingDrops,l=e.$?.consumedVariableDropExpressions??[];r.consumedVarPendingDrops=[...l,...s??[]];let u=new Set;for(let c of e.args){let _=M(c,t,n);if(_&&n.emitter.emitLine(`${t}${_};`),c.$?.env&&a.size>u.size)for(let p of c.$.env.frames)for(let f of p.variables)a.has(f.name)&&!u.has(f.name)&&(u.add(f.name),r.pendingDeferredDrops.unshift(a.get(f.name)))}if(e.$?.deferredDropExpressions)for(let c of e.$.deferredDropExpressions){let _=M(c,t,n);_&&n.emitter.emitLine(`${t}${_};`)}r.pendingDeferredDrops=i,r.consumedVarPendingDrops=s}else{let r=M(e,t,n);r&&n.emitter.emitLine(`${t}${r};`)}}function hp(e,t,n){if(e.$?.comptimeUnrolledBodies){for(let i of e.$.comptimeUnrolledBodies)kl(i,t,n);return""}let r=e.args;if(r.length===2){let i=r[0],o=r[1],a=n.currentLoopLabel,s=`loop_${Math.random().toString(36).substr(2,9)}`;n.currentLoopLabel=s;let l=n,u=l.loopBodyDropsBaselineCount;l.loopBodyDropsBaselineCount=l.pendingDeferredDrops?.length??0,n.emitter.emitLine(`${t}while (true) {`);let c=M(i,t+" ",n);return n.emitter.emitLine(`${t} if (!(${c})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),kl(o,t+" ",n),n.emitter.emitLine(`${t}}`),n.emitter.emitLine(`${t}${s}:;`),l.loopBodyDropsBaselineCount=u,n.currentLoopLabel=a,""}else if(r.length===3){let i=r[0],o=r[1],a=r[2],s=n.currentLoopLabel,l=n.currentContinueLabel,u=`loop_${Math.random().toString(36).substr(2,9)}`,c=`continue_${Math.random().toString(36).substr(2,9)}`;n.currentLoopLabel=u,n.currentContinueLabel=c;let _=n,p=_.loopBodyDropsBaselineCount;_.loopBodyDropsBaselineCount=_.pendingDeferredDrops?.length??0,n.emitter.emitLine(`${t}while (true) {`);let f=M(i,t+" ",n);n.emitter.emitLine(`${t} if (!(${f})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),kl(a,t+" ",n),n.emitter.emitLine(`${t}${c}:;`);let m=Eg(o,n);return n.emitter.emitLine(`${t} ${m};`),n.emitter.emitLine(`${t}}`),n.emitter.emitLine(`${t}${u}:;`),_.loopBodyDropsBaselineCount=p,n.currentLoopLabel=s,n.currentContinueLabel=l,""}else return n.emitter.emitLine(`${t}/* Error: while loop expects 2 or 3 arguments, got ${r.length} */`),""}function $g(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function Cg(e,t,n,r){let i=e.args[0];if(!i?.$?.type)return;let o=e.args.find(_=>F(_)&&E(_,I.using));if(!o)return;let a=Dt(i.$.type);if(!a?.isFuture.effects?.length)return;let s=$g(a.isFuture.effects),l=o.args,u=r,c=u.emitter;for(let _=0;_<s.length&&_<l.length;_++){let p=s[_],f=l[_];if(G(p.type)){let m=p.label,g;if(u.currentEvidenceParams){for(let h of u.currentEvidenceParams.values())if(h.fieldLabel===m){g=h.cParamName;break}}if(!g&&u.stateMachineVariables){for(let[,h]of u.stateMachineVariables)if(h.name===m&&h.kind==="outer"){g=`sm->__capture.${m}`;break}}if(!g){let h=f.$?.value;if(h&&ne(h)){let d=r.functions[h.funcId];d&&(g=d.cName)}}g||(g=M(f,n,r)),g&&c.emitLine(`${n} ${t}->__capture.${m} = (void*)${g};`)}else if(Te(p.type)){let m=p.type;for(let g of m.fields){if(!G(g.type))continue;let h;if(u.stateMachineVariables){for(let[,d]of u.stateMachineVariables)if(d.name===g.label&&d.kind==="outer"){h=`sm->__capture.${g.label}`;break}}if(!h){let d=f.$?.value;if(d&&We(d)){let v=m.fields.indexOf(g),T=d.fields[v];if(T&&ne(T)){let $=r.functions[T.funcId];$&&(h=$.cName)}}}if(!h&&u.currentEvidenceParams){for(let d of u.currentEvidenceParams.values())if(d.fieldLabel===g.label){h=d.cParamName;break}}h||(h=bg(g.label,m,u,e)),h&&c.emitLine(`${n} ${t}->__capture.${g.label} = (void*)${h};`)}}}}function bg(e,t,n,r){let i=r.$?.env??r.func.$?.env;if(!i)return;let o=fn(i,a=>a.isImplicit===!0);for(let a=o.length-1;a>=0;a--){let s=o[a],l=s.value?.[s.value.length-1];if(l&&We(l)){let u=l.type.fields.findIndex(c=>c.label===e);if(u>=0){let c=l.fields[u];if(c&&ne(c)){let _=n.functions[c.funcId]?.cName;if(_)return _}}}}}function kg(e,t,n){let r=n,i=e.args[0],o=r.continuationVariables?.get("resume");if(o&&"directReturnVar"in o&&o.directExitLabel){if(i){let l=M(i,t,n);if(r.effectHandlerParamDrops)for(let u of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${u};`);r.emitter.emitLine(`${t}${o.directReturnVar} = ${l};`),r.emitter.emitLine(`${t}goto ${o.directExitLabel};`)}else{if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);r.emitter.emitLine(`${t}goto ${o.directExitLabel};`)}return""}if(r.inAsyncStateMachine){let l=r.emitter;if(i){let u=M(i,t,n);u&&u!=="(void)0"&&l.emitLine(`${t}(void)${u};`)}if(r.effectHandlerParamDrops)for(let u of r.effectHandlerParamDrops)l.emitLine(`${t}${u};`);return dn(t,r,e,!1,!0,!0),tr(t,r,e,!0),Mn({emitter:l,indent:t,debugLabel:r.currentFunctionName}),""}if((r.isModuleEffectMemberFunction||r.currentEvidenceParams&&r.currentEvidenceParams.size>0)&&r.emitter.emitLine(`${t}__yo_effect_escaped = 1;`),!i){if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);if(dn(t,r,e,!1,!0,!0),tr(t,r,e,!0),r.currentFunctionType){let l=r.currentFunctionType.return.type;if(!pe(l)){let u=r.overrideReturnTypeStr??P(l,n);if(u!=="void")return`return (${u}){0}`}}return"return"}let s=M(i,t,n);if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);if(dn(t,r,e,!1,!0,!0),tr(t,r,e,!0),(r.isModuleEffectMemberFunction||r.currentEvidenceParams&&r.currentEvidenceParams.size>0)&&r.currentFunctionType){let l=i.$?.type;if(l&&!pe(l)){let c=P(l,n);r.emitter.emitLine(`${t}{ ${c} _esc_val = ${s}; memcpy(__yo_effect_escape_value, &_esc_val, sizeof(${c})); }`)}let u=r.currentFunctionType.return.type;if(!pe(u)){let c=r.overrideReturnTypeStr??P(u,n);if(c!=="void")return`return (${c}){0}`}return"return"}return`return ${s}`}function vp(e,t,n){let r;switch(e.tag){case"FnCall":r=wg(e,t,n);break;case"Atom":r=no(e,n,t);break}return r}function wg(e,t,n){if(e.$?.macroExpansion)return M(e.$.macroExpansion,t,n);if(F(e.func)&&E(e.func,".",2)&&e.func.args[1]&&z(e.func.args[1])){let r=e.func.args[1].token.value,i=e.func.args[0],o=i?.$?.type;if(o&&x(o)&&Ce(o)){if(r===k.___drop[0]){let a=M(i,t,n);return`if (${a} != NULL) { __yo_decr_rc((void*)${a}); }`}if(r===k.___dup[0])return`__yo_incr_rc((void*)${M(i,t,n)})`}}if(Lc(e))return Ac(e,t,n);if(E(e,k.__yo_decr_rc))return Z_(e,t,n);if(E(e,k.__yo_incr_rc))return J_(e,t,n);if(E(e,k.__yo_rc_own))return ep(e,t,n);if(E(e,k.__yo_drop_array_element))return tp(e,t,n);if(E(e,k.__yo_dup_array_element))return np(e,t,n);if(E(e,k.__yo_drop_tuple_element))return rp(e,t,n);if(E(e,k.__yo_dup_tuple_element))return ip(e,t,n);if(E(e,k.___dup))return op(e,t,n);if(E(e,k.___drop))return ap(e,t,n);if(E(e,k.__yo_dyn_drop))return sp(e,t,n);if(E(e,k.__yo_dyn_dup))return lp(e,t,n);if(E(e,k.__yo_incr_rc_atomic))return up(e,t,n);if(E(e,k.__yo_decr_rc_atomic))return cp(e,t,n);if(E(e,k.__yo_iso_extract))return V_(e,t,n);if(E(e,k.__yo_iso_dispose))return x_(e,t,n);if(E(e,k.__yo_arc_dispose))return m_(e,t,n);if(Tl(e))return D_(e,t,n);if(vl(e))return y_(e,t,n);if(E(e,k.__yo_sometype_drop))return _p(e,t,n);if(E(e,k.__yo_sometype_dup))return pp(e,t,n);if(E(e,k.__yo_gc_collect))return S_(e,t,n);if(E(e,k.rc))return fp(e,t,n);if(E(e,k.panic))return Y_(e,t,n);if(E(e,k.asm))return j_(e,t,n);if(E(e,k.global_asm))return K_(e,t,n);if(E(e,I.test))return"/* test declaration skipped */";if(E(e,k.__yo_thread_set_maximum_threads))return z_(e,t,n);if(E(e,I.op_and))return f_(e,t,n);if(E(e,I.op_or))return d_(e,t,n);if(Rt(e))return e.$?.awaitAnalysis?Ic(e,t,n):Dc(e,t,n);if(E(e,I.dyn))return I_(e,t,n);if(pn(e))return E_(e,t,n);if(zu(e))return $_(e,t,n);if(Fa(e)){let r=e.args[0];if(!r)return"// Error: spawn requires a Future argument";let o=n.emitter,a=M(r,t,n),s=r.$?.type,l=s?P(s,n):"void*",u=e.$?.type,c=u?P(u,n):null,_=e.$?.variableName?`__spawn_future_${e.$.variableName}`:"__spawn_future",p=e.$?.variableName?`__spawn_state_${e.$.variableName}`:"__spawn_state";return o.emitLine(`${t}// io.spawn \u2014 start cold Future, return JoinHandle`),o.emitLine(`${t}${l} ${_} = ${a};`),o.emitLine(`${t}int ${p} = ${_}->state;`),o.emitLine(`${t}if (${p} == -2) {`),o.emitLine(`${t} fprintf(stderr, "panic: attempted to spawn an aborted Future\\n");`),o.emitLine(`${t} abort();`),o.emitLine(`${t}}`),jo(r.$?.type)||(o.emitLine(`${t}if (${p} == 0 && ${_}->__yo_resume_fn) {`),Cg(e,_,t,n),o.emitLine(`${t} __yo_incr_rc((void*)${_});`),o.emitLine(`${t} ${_}->__yo_resume_fn((void*)${_});`),o.emitLine(`${t}}`)),c?`(${c}){ .__future = (void*)${_} }`:`(void*)${_}`}if(Bu(e))return C_(e,t,n);if(E(e,I.return))return Jc(e,t,n);if(E(e,I.escape))return kg(e,t,n);if(E(e,k.__yo_array_fill,2))return h_(e,t,n);if(E(e,"::",2))return"";if(E(e,":",2))return w_(e,t,n);if(E(e,":=",2)){let r=N_(e,t,n);if(r!==void 0)return r}else{if(E(e,"=",2))return v_(e,t,n);if(e.$?.value&&!de(e.$?.value)&&!pe(e.$.type)&&!nt(e.$?.controlFlow)){let r=e.$.value;return Qt(r,n,e)}else{if(E(e,".",2))return X_(e,t,n);if(E(e,I.begin))return k_(e,t,n);if(E(e,I.cond))return F_(e,t,n);if(E(e,I.match))return O_(e,t,n);if(E(e,k.__yo_address_of,1))return Q_(e,t,n);if(E(e,I.tuple))return yp(e,t,n);if(E(e,I.array)){let r=g_(e,t,n);if(r!==void 0)return r}else{if(E(e,I.recur))return dp(e,t,n);if(E(e,I.runtime,1))return M(e.args[0],t,n);if(E(e,k.sizeof,1))return mp(e,t,n);if(E(e,k.typeid,1))return gp(e,t,n);if(E(e,k.downcast,2))return A_(e,t,n);if(E(e,gi)){let r=e.$?.runtimeArgExprsInOrder||e.args;if(r){let i=n,o=r.map(a=>{let s=M(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){rt(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return Ee(l.$.variableName,l.$.env)}return s});return Xo(e.func.token.value,o,e,n,t)}}else{if(E(e,I.while))return hp(e,t,n);if(E(e,"->",2)&&F(e.args[0])&&E(e.args[0],I.fn)){let r=e.$?.value;return ne(r)?Qt(r,n):"// Error: Anonymous function missing function value"}else{if(E(e,k.consume))return L_(e,t,n);if(E(e,k.comptime_expect_error)||E(e,k.comptime_assert)||E(e,k.__yo_var_print_info)||E(e,k.__yo_var_is_owning_the_rc_value)||E(e,k.__yo_var_has_other_aliases))return"";if(E(e,I.open))return R_(e,t,n);{let r=q_(e,t,n);if(r!==void 0)return r}}}}}}if(F(e))throw new Error(`Unhandled function call: ${w(e)}`);return`// Failed to transpile ${w(e)}`}function Tp({expr:e,env:t,context:n}){he(e,k.alignof,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});t=i.$.env;let o;i.$.value&&O(i.$.value)?o=i.$.value.value:o=i.$.type;let a=Kn(o),s;return a===null?s=K(gt(),{env:t,context:n}):s=Xt("Usize",a),e.$={env:t,type:gt(),value:s,pathCollection:[]},e}function Ep({expr:e,env:t,context:n}){let r=E(e,I.op_and)?"and":"or",i=e.args;if(i.length===0){let u=ft(r==="and");return e.$={env:t,type:Je(),value:u,pathCollection:[],isAccessingProperty:!1},e}let o=t,a,s=!1,l=!1;for(let u=0;u<i.length;u++){let c=i[u],_=S({expr:c,env:o,context:{...n}});if(!_.$||!cn(_.$.type))throw y({token:c.token,errorMessage:`Expected bool type for "${r}" argument, got:
10263
- ${w(c)}`});o=_.$.env;let p=_.$.value;if(de(p)){s=!0;continue}if(Re(p)){let f=p.value;if(r==="and"){if(!f){a=ft(!1);break}!s&&!l&&(a=ft(!0))}else{if(f){a=ft(!0);break}!s&&!l&&(a=ft(!1))}}else l=!0}return Re(a)||(l||s)&&(l?a=void 0:a=K(Je(),{env:o,context:n})),e.$={env:o,type:Je(),value:a,pathCollection:[],isAccessingProperty:!1},e}function $p({expr:e,env:t,context:n}){he(e,k.__yo_array_fill,2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});o.$?.env&&(t=o.$.env);let a=o.$?.value;if(!O(a)||!ke(a.value))throw y({token:r.token,errorMessage:`__yo_array_fill expects first argument to be an ArrayType, got ${a?Me(a):"undefined"}`});let s=a.value,l=S({expr:i,env:t,context:{...n,expectedType:{type:s.childType,env:t}}});l.$?.env&&(t=l.$.env);let u=l.$?.type,c=l.$?.value;if(!u)throw y({token:i.token,errorMessage:"Failed to evaluate fill value"});if(!c)throw y({token:i.token,errorMessage:"__yo_array_fill expects second argument to be a compile-time known value, got runtime value"});if(!Y({type:s.childType,env:t},{type:u,env:t}))throw y({token:i.token,errorMessage:`Fill value type ${A(u)} is not compatible with array element type ${A(s.childType)}`});let _=s.length;if(de(_)){let g=K(s,{env:t,context:n});return e.$={env:t,type:s,value:g,pathCollection:[]},e}let p;if(ze(_)){let g=_.value;if(p=typeof g=="bigint"?Number(g):g,!Number.isInteger(p)||p<0)throw y({token:i.token,errorMessage:`Array length must be a non-negative integer, got ${p}`})}else throw y({token:i.token,errorMessage:`Array length must be a compile-time known integer, got ${Me(_)}`});let f=[];if(de(c)){let g=K(s,{env:t,context:n});return e.$={env:t,type:s,value:g,pathCollection:[]},e}for(let g=0;g<p;g++)f.push(c);let m=Mr(s,f);return e.$={env:t,type:s,value:m,pathCollection:[]},e}function Cp({expr:e,env:t,context:n}){if(n.isValidatingFunctionDefinition||!n.isExecuting){let s=n.expectedType?.type??H.type;return e.$={env:t,type:s,value:pe(s)?H:K(s,{env:t,context:n}),pathCollection:[]},e}let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$||!Re(o.$.value))throw y({token:r.token,errorMessage:`Expected bool value for "comptime_assert", got:
10269
+ `),u_(i),yl(i),Vc(i),kc(i),o_(i),r_(i),Uc(i),zc(i),Bc(i),Pc(i),Nc(i),r.isLibrary||i_(i),l_(i),Fc(i),s_(i),i.needsIntelAsmSyntax&&(this._needsIntelAsmSyntax=!0)}print(){return this.emitter.print()}getExportedFunctionNames(){return this.exportedFunctionNames}get needsIntelAsmSyntax(){return this._needsIntelAsmSyntax}};var c_=0;function __(e){return e.$?.variableName?!0:(e.$?.value!==void 0,!1)}function Ba(e,t){if(F(e)){e.$?.variableName&&t.add(e.$.variableName);for(let n of e.args)Ba(n,t);e.func&&Ba(e.func,t)}}function p_(e,t,n){let r=n,i=r.pendingDeferredDrops;if(!(!i||e.size===0)){r.shortCircuitHandledDropVarNames||(r.shortCircuitHandledDropVarNames=new Set);for(let o of i){let a=In(o);if(a&&e.has(a)){let s=M(o,t,n);s&&n.emitter.emitLine(`${t}${s};`),r.shortCircuitHandledDropVarNames.add(a)}}}}function f_(e,t,n){if(e.args.length===0)return"true";if(e.args.length===1)return M(e.args[0],t,n);let r=[];for(let l of e.args){let u=l.$?.value;if(Re(u)){if(u.value===!1)return"false";continue}r.push(l)}if(r.length===0)return"true";if(r.length===1)return M(r[0],t,n);if(!r.slice(1).some(l=>__(l)))return`(${r.map(u=>M(u,t,n)).join(" && ")})`;let o=`__yo_sc_${c_++}`;n.emitter.emitLine(`${t}bool ${o} = false;`);let a=t,s=r.length-1;for(let l=0;l<r.length;l++){let u=M(r[l],a,n);l<r.length-1?(n.emitter.emitLine(`${a}if (${u}) {`),a+=" "):n.emitter.emitLine(`${a}${o} = ${u};`)}for(let l=s-1;l>=0;l--){let u=r[l+1],c=new Set;Ba(u,c),p_(c,a,n),a=a.slice(2),n.emitter.emitLine(`${a}}`)}return o}function d_(e,t,n){if(e.args.length===0)return"false";if(e.args.length===1)return M(e.args[0],t,n);let r=[];for(let l of e.args){let u=l.$?.value;if(Re(u)){if(u.value===!0)return"true";continue}r.push(l)}if(r.length===0)return"false";if(r.length===1)return M(r[0],t,n);if(!r.slice(1).some(l=>__(l)))return`(${r.map(u=>M(u,t,n)).join(" || ")})`;let o=`__yo_sc_${c_++}`;n.emitter.emitLine(`${t}bool ${o} = true;`);let a=t,s=r.length-1;for(let l=0;l<r.length;l++){let u=M(r[l],a,n);l<r.length-1?(n.emitter.emitLine(`${a}if (!(${u})) {`),a+=" "):n.emitter.emitLine(`${a}${o} = ${u};`)}for(let l=s-1;l>=0;l--){let u=r[l+1],c=new Set;Ba(u,c),p_(c,a,n),a=a.slice(2),n.emitter.emitLine(`${a}}`)}return o}function m_(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_arc_dispose requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type;return!o||!Ct(o)?"// Error: __yo_arc_dispose requires an Arc type":`__yo_arc_dispose_${P(o,n)}(${i})`}function vl(e){let t=e.func.$?.value;return O(t)&&Ct(t.value)&&e.args.length===1}function y_(e,t,n){if(!vl(e))return"/* Error: generateArcTypeCall called on non-Arc type call */";let i=(e.func.$?.value).value,o=i.childType,a=e.args[0],s=M(a,t,n),l=P(i,n),u=P(o,n);return n.arcTypes||(n.arcTypes=new Map),n.arcTypes.has(l)||n.arcTypes.set(l,{childTypeCName:u,arcType:i}),`__yo_create_arc_${l}(${s})`}function g_(e,t,n){let r=e.$?.runtimeArgExprsInOrder,i=e.$?.type,o=e.$?.variableName;if(ke(i)&&r){let a=n,s=r.map(u=>{let c=M(u,t,n);if(u.$?.deferredDupExpressions&&u.$.deferredDupExpressions.length>0){rt(u,t,a);let _=u.$.deferredDupExpressions[0];if(F(_)&&_.$?.variableName)return Ee(_.$.variableName,_.$.env)}return c}).join(", "),l=P(i,n);if(o&&e.$?.type){let u=`(${l}){ .data = { ${s} } }`,c=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${c} = ${u};`),o}else return`(${l}){ .data = { ${s} } }`}}function h_(e,t,n){let r=n.emitter,i=e.args[0],o=e.args[1],a=i.$?.value;if(!a||!O(a)||!ke(a.value))return"/* ERROR: __yo_array_fill first argument must be an ArrayType */";let s=a.value,l=s.length;if(!ze(l))return"/* ERROR: __yo_array_fill requires compile-time known array length */";let u=P(s,n),c=M(o,t,n),_=e.$?.variableName||`temp_array_${Date.now()}`,p=`i_${qe(e.$?.env.modulePath??"")}`;return r.emitLine(`${t}${u} ${_};`),r.emitLine(`${t}for (int ${p} = 0; ${p} < ${l.value}; ${p}++) {`),r.emitLine(`${t} ${_}.data[${p}] = ${c};`),r.emitLine(`${t}}`),_}function v_(e,t,n){if(e.$?.isCompileTimeOnlyAssignment)return"";let r=e.args[0],i=e.args[1],o=!1;if(F(r)&&E(r,":",2)&&(o=!0,r=r.args[0]),F(r)&&E(r,I.comptime)||F(r)&&E(r,I.given))return"";if(r.$?.pathCollection&&r.$?.pathCollection.length>0){let l=r.$.pathCollection[0];if(l&&l.length>=2){let u=l[0];if(typeof u=="string"&&r.$?.env){let c=X(r.$.env,u);if(c.length>0&&c[c.length-1].isCompileTimeOnly)return""}}}if(z(r)&&r.$?.env){let l=r.token.value,u=X(r.$.env,l);if(u.length>0&&u[u.length-1].isCompileTimeOnly)return""}if(!r.$?.type)return`// Error: No type information for left-hand side ${w(r)}
10270
+ `;let a=M(r,t,n),s=!1;if(e.$?.variableName){let l=e.$.variableName,u=n;if((u.inAsyncStateMachine||u.inEffectStateMachine)&&a.startsWith("sm->")){let _=u.stateMachineVariables?.get(l);if(!_&&u.stateMachineVariables){for(let[,p]of u.stateMachineVariables)if(p.name===l){_=p;break}}if(_&&_.kind!=="outer"){let p=`var_${_.id}`;pe(r.$.type)||n.emitter.emitLine(`${t}sm->${p} = ${a}; // Save old value for deferred drop`)}else s=!0}else{let _=st(r.$.type,l,n);ke(r.$.type)?n.emitter.emitLine(`${t}${_} = ${a}; // Save old value for later use`):pe(r.$.type)||n.emitter.emitLine(`${t}${_} = ${a}; // Save old value for later use`)}}if(ke(r.$.type)){let l=M(i,t,n),u=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Wt(i.$.type),c=n,_=l;if(!u&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){if(i.$?.variableName&&i.$?.type){let f=Ee(i.$.variableName,i.$.env);if(f!==l.trim()){let m=i.$.convertedRuntimeType||i.$.type,g=P(m,n);n.emitter.emitLine(`${t}${g} ${f} = ${l};`)}}rt(i,t,c);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(_=Ee(p.$.variableName,p.$.env))}if(o){let p=st(r.$.type,M(r,t,n),n);n.emitter.emitLine(`${t}${p} = ${_};`)}else n.emitter.emitLine(`${t}${a} = ${_};`)}else{let l=M(i,t,n),u=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Wt(i.$.type),c=n,_=l;if(!u&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){if(i.$?.variableName&&i.$?.type){let f=Ee(i.$.variableName,i.$.env);if(f!==l.trim()){let m=i.$.convertedRuntimeType||i.$.type,g=P(m,n);n.emitter.emitLine(`${t}${g} ${f} = ${l};`)}}rt(i,t,c);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(_=Ee(p.$.variableName,p.$.env))}if(!pe(r.$.type)){let p=r.$.type,f=i.$?.type,m,g=ut(i.$.env.modulePath,_.trim());g&&n.tempVarAsyncStructNames&&(m=n.tempVarAsyncStructNames.get(_.trim()));let h=o&&f&&Ce(p)&&Ce(f),d;g&&h?m?d=`${m}*`:d=P(f,n):h&&m?d=`${m}*`:d=P(h?f:p,n);let v=(c.inAsyncStateMachine||c.inEffectStateMachine)&&a.startsWith("sm->");n.emitter.emitLine(`${t}${o&&!v?d+" ":""}${a} = ${_};`)}}return s?"":e.$?.variableName??""}function E_(e,t,n){let r=e.args[0];if(!r)return"// Error: await requires exactly 1 argument";let i=r.$?.type;if(!i||!Ce(i))return"// Error: await argument must be a Future type";let o=Dt(i);if(!o)return"// Error: could not extract Future module from type";let a=n;if(a.inAsyncStateMachine||a.inEffectStateMachine)return"";if(pn(e)){let s=M(r,t,n),l=P(i,n),u=o.isFuture.outputType;x(u)&&(u.resolvedConcreteType?u=u.resolvedConcreteType:e.$?.type&&!x(e.$.type)?u=e.$.type:e.$?.type&&x(e.$.type)&&e.$.type.resolvedConcreteType&&(u=e.$.type.resolvedConcreteType));let c=a.emitter,_=pe(u)||x(u)&&pe(e.$?.type??u),p=e.$?.variableName?`__sync_future_${e.$.variableName}`:"__sync_future",f=e.$?.variableName?`__pre_await_state_${e.$.variableName}`:"__pre_await_state";c.emitLine(`${t}// Synchronous await (io.await outside state machine)`),c.emitLine(`${t}${l} ${p} = ${s};`),c.emitLine(`${t}int ${f} = ${p}->state;`),jo(r.$?.type)||(c.emitLine(`${t}if (${f} == 0 && ${p}->__yo_resume_fn) {`),sg(e,p,t,n),c.emitLine(`${t} __yo_incr_rc((void*)${p}); // event loop reference`),c.emitLine(`${t} ${p}->__yo_resume_fn((void*)${p});`),c.emitLine(`${t}}`)),c.emitLine(`${t}{`),c.emitLine(`${t} int __await_state = ${p}->state;`),c.emitLine(`${t} while (__await_state != -1 && __await_state != -2) {`),c.emitLine(`${t} __yo_async_poll_step();`),c.emitLine(`${t} __await_state = ${p}->state;`),c.emitLine(`${t} }`),c.emitLine(`${t} if (__await_state == -2) {`);let g=Dt(i),h=g?.isFuture.effects?.some(d=>G(d.type)||Te(d.type)||d.isEffectRowSpread)??!1;if(h){c.emitLine(`${t} if (${f} == -2) {`),c.emitLine(`${t} fprintf(stderr, "panic: attempted to await an aborted Future\\n");`),c.emitLine(`${t} abort();`),c.emitLine(`${t} }`);let d=a.pendingDeferredDrops;if(d){let $=e.$?.variableName;a.pendingDeferredDrops=d.filter(C=>In(C)!==$)}dn(t+" ",a,e),a.pendingDeferredDrops=d;let v=ag(g,a),T=a.currentFunctionType?.return?.type;if(v)if(c.emitLine(`${t} __yo_effect_escaped = 0;`),T&&!pe(T)){let $=P(T,n);$!=="void"?(c.emitLine(`${t} ${$} _esc_result;`),c.emitLine(`${t} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${$}));`),c.emitLine(`${t} return _esc_result;`)):c.emitLine(`${t} return;`)}else c.emitLine(`${t} return;`);else if(c.emitLine(`${t} __yo_effect_escaped = 1;`),T&&!pe(T)){let $=P(T,n);c.emitLine(`${t} return (${$}){0};`)}else c.emitLine(`${t} return;`)}else c.emitLine(`${t} fprintf(stderr, "panic: attempted to await an aborted Future\\n");`),c.emitLine(`${t} abort();`);if(c.emitLine(`${t} }`),c.emitLine(`${t}}`),_)return"";{let d=e.$?.variableName||"__sync_await_result",v=P(u,n),T=st(u,d,n);if(h){if(c.emitLine(`${t}${T};`),c.emitLine(`${t}if (${p}->state == -1) {`),Le(u)){let $=On(u,n);$?c.emitLine(`${t} ${d} = ${$}(${p}->result);`):c.emitLine(`${t} ${d} = ${p}->result;`)}else c.emitLine(`${t} ${d} = ${p}->result;`);c.emitLine(`${t}} else {`),c.emitLine(`${t} ${d} = (${v}){0};`),c.emitLine(`${t}}`)}else if(Le(u)){let $=On(u,n);$?c.emitLine(`${t}${T} = ${$}(${p}->result);`):c.emitLine(`${t}${T} = ${p}->result;`)}else c.emitLine(`${t}${T} = ${p}->result;`);return d}}return"// Error: await should only be used inside async blocks"}function $_(e,t,n){let r=e.args[0];if(!r)return"// Error: io.state requires exactly 1 argument";let i=r.$?.type;if(!i||!Ce(i))return"// Error: io.state argument must be a Future type";let a=n.emitter,s=M(r,t,n),l=e.$?.variableName?`__raw_state_${e.$.variableName}`:"__raw_state",u=e.$?.variableName||"__io_state_result";return a.emitLine(`${t}int ${l} = ${s}->state;`),a.emitLine(`${t}int32_t ${u} = (${l} > 0) ? 1 : ${l};`),u}function C_(e,t,n){let i=n.emitter,o=F(e.func)?e.func.args[0]:e.args[0];if(!o)return"// Error: JoinHandle.await requires a self argument";let a=M(o,t,n),s=e.$?.type;if(!s||!ge(s))return"// Error: JoinHandle.await return type must be Option(T)";let l=P(s,n),c=s.variants.find(C=>C.name==="Some")?.fields?.[0]?.type,_=!c||pe(c),p=_?"uint8_t":c?P(c,n):"uint8_t",f=Bt(s,"Some",n),m=Bt(s,"None",n),g=e.$?.variableName||"jh",h=`__jh_future_${g}`,d=`__jh_header_${g}`,v=e.$?.variableName||"__jh_result",T=`__yo_jh_header_${g}`;i.emitLine(`${t}// JoinHandle.await \u2014 poll spawned task, return Option(T)`);let $=st(s,v,n);if(i.emitLine(`${t}${$};`),i.emitLine(`${t}{`),i.emitLine(`${t} void* ${h} = ${a}.__future;`),i.emitLine(`${t} struct ${T} {`),i.emitLine(`${t} __yo_ref_header_t header;`),i.emitLine(`${t} int state;`),i.emitLine(`${t} ${p} result;`),i.emitLine(`${t} void (*continuation_fn)(void*);`),i.emitLine(`${t} void* continuation_sm;`),i.emitLine(`${t} void (*__yo_resume_fn)(void*);`),i.emitLine(`${t} };`),i.emitLine(`${t} struct ${T}* ${d} = (struct ${T}*)${h};`),i.emitLine(`${t} int __jh_state = ${d}->state;`),i.emitLine(`${t} while (__jh_state != -1 && __jh_state != -2) {`),i.emitLine(`${t} __yo_async_poll_step();`),i.emitLine(`${t} __jh_state = ${d}->state;`),i.emitLine(`${t} }`),i.emitLine(`${t} if (__jh_state == -1) {`),_)i.emitLine(`${t} ${v} = (${l}){ .tag = ${f} };`);else if(c&&Le(c)){let C=On(c,n);C?i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${C}(${d}->result) } } };`):i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${d}->result } } };`)}else i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${d}->result } } };`);return i.emitLine(`${t} } else {`),i.emitLine(`${t} __yo_effect_escaped = 0;`),i.emitLine(`${t} ${v} = (${l}){ .tag = ${m} };`),i.emitLine(`${t} }`),i.emitLine(`${t}}`),v}function ag(e,t){let n=e.isFuture.effects;if(!n?.length)return!1;let r=b_(n),i=t.currentEvidenceParams;for(let o of r)if(G(o.type)){let a=`${o.label}.${o.label}`;if(!i?.has(a))return!0}else if(Te(o.type)){let a=!1;if(i){for(let[s]of i)if(s.startsWith(`${o.label}.`)){a=!0;break}}if(!a)return!0}return!1}function b_(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function sg(e,t,n,r){let i=e.args[0];if(!i?.$?.type)return;let o=Dt(i.$.type);if(!o?.isFuture.effects?.length)return;let a=b_(o.isFuture.effects),s=r,l=s.emitter,u=e.args.find(c=>F(c)&&E(c,I.using));if(u){let c=u.args;for(let _=0;_<a.length&&_<c.length;_++){let p=a[_],f=c[_];if(G(p.type)){let m=M(f,n,r),g=p.label;l.emitLine(`${n} ${t}->__capture.${g} = (void*)${m};`)}else Te(p.type)&&T_(p.type,t,n,f.$?.value,s,e)}}else for(let c of a)if(G(c.type)){let _=ug(c.label,s,e);_&&l.emitLine(`${n} ${t}->__capture.${c.label} = (void*)${_};`)}else Te(c.type)&&T_(c.type,t,n,void 0,s,e)}function T_(e,t,n,r,i,o){let a=i.emitter;for(let s of e.fields){if(!G(s.type))continue;let l;if(i.stateMachineVariables){for(let[,u]of i.stateMachineVariables)if(u.name===s.label&&u.kind==="outer"){l=`sm->__capture.${s.label}`;break}}if(!l&&r&&We(r)){let u=e.fields.indexOf(s),c=r.fields[u];if(c&&ne(c)){let _=i.functions[c.funcId];_&&(l=_.cName)}}if(!l&&i.currentEvidenceParams){for(let u of i.currentEvidenceParams.values())if(u.fieldLabel===s.label){l=u.cParamName;break}}l||(l=lg(s.label,e,i,o)),l&&a.emitLine(`${n} ${t}->__capture.${s.label} = (void*)${l};`)}}function lg(e,t,n,r){let i=r.$?.env??r.func.$?.env;if(!i)return;let o=fn(i,a=>a.isImplicit===!0);for(let a=o.length-1;a>=0;a--){let s=o[a],l=s.value?.[s.value.length-1];if(l&&We(l)){let u=l.type.fields.findIndex(c=>c.label===e);if(u>=0){let c=l.fields[u];if(c&&ne(c)){let _=n.functions[c.funcId]?.cName;if(_)return _}}}}}function ug(e,t,n){if(t.currentEvidenceParams){for(let r of t.currentEvidenceParams.values())if(r.fieldLabel===e)return r.cParamName}if(t.stateMachineVariables){for(let[,r]of t.stateMachineVariables)if(r.name===e&&r.kind==="outer")return`sm->__capture.${e}`}}function k_(e,t,n){let r=e.$?.variableName,i=e.$?.type,o=n;if(r&&i){!pe(i)&&!nt(e.$?.controlFlow)&&n.emitter.emitLine(`${t}${P(i,n)} ${r};`),n.emitter.emitLine(`${t}{ // begin block`);let a=o.pendingDeferredDrops,s=e.$?.deferredDropExpressions??[];o.pendingDeferredDrops=[...s,...a??[]];let l=o.consumedVarPendingDrops,u=e.$?.consumedVariableDropExpressions??[];o.consumedVarPendingDrops=[...u,...l??[]];let c=[],_=!pe(i)&&!nt(e.$?.controlFlow);for(let p=0;p<e.args.length;p++){let f=e.args[p],m=M(f,t+" ",n);c.push(m);let g=p===e.args.length-1;m&&!(g&&_)&&(f.$&&ut(f.$.env.modulePath,m)||n.emitter.emitLine(`${t} ${m};`))}if(_){let p=e.args[e.args.length-1],f=c[c.length-1];if(p.$?.deferredDupExpressions&&p.$.deferredDupExpressions.length>0){if(p.$?.variableName){let g=p.$.variableName;p.$.variableName=void 0;let h=M(p,t+" ",n);p.$.variableName=g;let d=P(p.$.type,n),v=Ee(g,p.$.env);v!==h&&n.emitter.emitLine(`${t} ${d} ${v} = ${h};`),f=v}rt(p,t+" ",n);let m=p.$.deferredDupExpressions[0];F(m)&&m.$?.variableName&&(f=Ee(m.$.variableName,m.$.env))}n.emitter.emitLine(`${t} ${r} = ${f};`)}if(e.$?.deferredDropExpressions)for(let p of e.$.deferredDropExpressions){if(o.shortCircuitHandledDropVarNames){let m=In(p);if(m&&o.shortCircuitHandledDropVarNames.has(m)){o.shortCircuitHandledDropVarNames.delete(m);continue}}let f=M(p,t+" ",n);f&&n.emitter.emitLine(`${t} ${f};`)}return n.emitter.emitLine(`${t}} // end begin block`),o.pendingDeferredDrops=a,o.consumedVarPendingDrops=l,pe(i)||nt(e.$?.controlFlow)?"":r}else{n.emitter.emitLine(`${t}{ // begin block`);let a=o.pendingDeferredDrops,s=e.$?.deferredDropExpressions??[];o.pendingDeferredDrops=[...s,...a??[]];let l=o.consumedVarPendingDrops,u=e.$?.consumedVariableDropExpressions??[];if(o.consumedVarPendingDrops=[...u,...l??[]],e.args.map(_=>M(_,t+" ",n)).forEach(_=>{_&&n.emitter.emitLine(`${t} ${_};`)}),e.$?.deferredDropExpressions)for(let _ of e.$.deferredDropExpressions){if(o.shortCircuitHandledDropVarNames){let f=In(_);if(f&&o.shortCircuitHandledDropVarNames.has(f)){o.shortCircuitHandledDropVarNames.delete(f);continue}}let p=M(_,t+" ",n);p&&n.emitter.emitLine(`${t} ${p};`)}return n.emitter.emitLine(`${t}} // end begin block`),o.pendingDeferredDrops=a,o.consumedVarPendingDrops=l,""}}function w_(e,t,n){let r=e.args[0];if(F(r)&&E(r,I.comptime,1)||F(r)&&E(r,I.given,1))return"";if(!r.$?.type)return`// Error: No type information for left-hand side ${w(r)}
10271
+ `;let i=r.token.value,o=st(r.$.type,i,n);return n.emitter.emitLine(`${t}${o};`),""}function F_(e,t,n){if(e.$){let r=e.$.variableName,i=e.$.type,o=i&&pe(i),a=-1;for(let _=0;_<e.args.length;_++){let p=e.args[_];if(F(p)&&E(p,"=>",2)){let f=p.args[0];if(f&&!(Re(f.$?.value)&&f.$.value.value===!1)){a=_;break}}}let s=!1;if(a>=0){let _=e.args[a];if(_&&F(_)&&E(_,"=>",2)){let p=_.args[0];p&&Re(p.$?.value)&&p.$.value.value===!0&&(s=!0)}}if(!o&&r&&!s){let _=P(i,n);n.emitter.emitLine(`${t}${_} ${r};`)}if(s&&a>=0){let _=e.args[a];if(_&&F(_)&&E(_,"=>",2)){let p=_.args[1];if(p){let f=M(p,t,n);r&&!o&&(f&&f!==""&&!f.startsWith("goto")&&f!=="continue"&&f!=="break"&&!f.includes("return")?n.emitter.emitLine(`${t}${r} = ${f};`):f&&(f.startsWith("goto")||f==="continue"||f==="break"||f.includes("return"))&&n.emitter.emitLine(`${t}${f};`))}}return o?"":r??""}let l=t,u=0,c=!1;for(let _=0;_<e.args.length;_++){let p=e.args[_];if(F(p)&&E(p,"=>",2)){let f=p.args[0],m=p.args[1];if(f&&m){if(Re(f.$?.value)&&f.$.value.value===!1)continue;if(c){if(n.emitter.emitLine(`${l}else {`),u++,l+=" ",!(Re(f.$?.value)&&f.$.value.value===!0)){let T=M(f,l,n);n.emitter.emitLine(`${l}if (${T}) {`)}}else{if(Re(f.$?.value)&&f.$.value.value===!0)n.emitter.emitLine(`${l}{`);else{let v=M(f,l,n);n.emitter.emitLine(`${l}if (${v}) {`)}c=!0}let g=Re(f.$?.value)&&f.$.value.value===!0,h=c&&g?l:l+" ";if(F(m)&&E(m,I.begin)){let v=m.args,T=n,$=T.pendingDeferredDrops,C=m.$?.deferredDropExpressions??[];T.pendingDeferredDrops=[...C,...$??[]];let L=T.consumedVarPendingDrops,b=m.$?.consumedVariableDropExpressions??[];T.consumedVarPendingDrops=[...b,...L??[]];for(let R=0;R<v.length-1;R++){let N=v[R],B=M(N,h,n);if(B&&N.$&&!ut(N.$.env.modulePath,B)&&n.emitter.emitLine(`${h}${B};`),nt(N.$?.controlFlow))break}if(v.length>0){let R=v[v.length-1];R.$?.deferredDupExpressions&&rt(R,h,n);let N=M(R,h,n);N&&(N==="continue"||N==="break"||N.startsWith("goto")||F(R)&&E(R,I.return)||N.includes("return")?n.emitter.emitLine(`${h}${N};`):r&&!o&&n.emitter.emitLine(`${h}${r} = ${N};`))}m.$?.deferredDropExpressions&&bt(m,h,n),T.pendingDeferredDrops=$,T.consumedVarPendingDrops=L}else{m.$?.deferredDupExpressions&&rt(m,h,n);let v=M(m,h,n);v==="continue"||v==="break"||v.startsWith("goto")||F(m)&&E(m,I.return)||v.includes("return")?n.emitter.emitLine(`${h}${v};`):v===""||!v||r&&(o||n.emitter.emitLine(`${h}${r} = ${v};`))}!(c&&g)&&n.emitter.emitLine(`${l}}`)}}}for(let _=0;_<u;_++)l=l.slice(0,-2),n.emitter.emitLine(`${l}}`);return o?"":r??""}return'/* "cond" expression is not evaluated */'}function L_(e,t,n){let r=e.args[0];return M(r,t,n)}function A_(e,t,n){let r=e.args[0],i=r.$?.type;if(!i||!be(i))throw new Error("downcast codegen: expected Dyn type as first argument");let o=M(r,t,n),s=e.args[1].$?.value;if(!s||!O(s))throw new Error("downcast codegen: expected TypeValue as second argument");let l=s.value,u=P(l,n),c=n.types[l.id]?.cName||u,_=`__yo_typeid_${te(c)}`;n.typeIdStatics||(n.typeIdStatics=new Map),n.typeIdStatics.has(l.id)||(n.typeIdStatics.set(l.id,_),n.emitter.emitDeclarationLine(`static const char ${_} = 0;`)),n.cIncludes.add("<stdint.h>");let p=`${o}.vtable->__yo_type_id == (uintptr_t)&${_}`,f,m=!1,g="",h="";for(let[,R]of n.dynImpls){if(R.dynType.id!==i.id)continue;if((x(R.concreteType)&&R.concreteType.resolvedConcreteType?R.concreteType.resolvedConcreteType:R.concreteType).id===l.id&&$n(R.dataType)){m=!0,g=n.types[R.dataType.id]?.cName||`unknown_box_${R.dataType.id}`,h=te(R.dataType.fields[0].label);break}}if(m){let R=pt(l);if(!R){let N=l;for(;Er(N)&&N.fields.length===1;)N=N.fields[0].type;R=pt(N)}R?f=`((${u})__yo_incr_rc((void*)((${g}*)${o}.data)->${h}))`:f=`((${u})((${g}*)${o}.data)->${h})`}else f=`((${u})__yo_incr_rc((void*)${o}.data))`;let d=e.$?.type;if(!d||!ge(d))throw new Error("downcast codegen: expected Option enum as result type");if(Yt(d))return`((${p}) ? ${f} : NULL)`;let T=P(d,n),$=Bt(d,"Some",n),C=Bt(d,"None",n),L=`(${T}){ .tag = ${$}, .data = { .Some = { .value = ${f} } } }`,b=`(${T}){ .tag = ${C} }`;return`((${p}) ? ${L} : ${b})`}function I_(e,t,n){if(!e.$?.dynCallTraitValues||e.$.dynCallTraitValues.length===0)return"/* Error: dyn() call missing trait values */";let r=e.$?.runtimeArgExprsInOrder?.[0]??e.args[0];if(!r)return"/* Error: dyn() requires a value argument */";let i=e.$.type;if(!be(i))return"/* Error: dyn() result type is not DynType */";let o=r.$?.type;if(!o)return"/* Error: dyn() value has no type */";let a=e.$.dynCallTraitValues;if(!a||a.length===0)return"/* Error: dyn() call missing trait values */";if(!pt(o)&&!$n(o))return"/* Error: dyn() requires an object type (use box() for value types) */";let s=$n(o)?o.fields[0].type:o,l=x(s)&&s.resolvedConcreteType?s.resolvedConcreteType:s,u=n.types[i.id]?.cName||`__yo_dyn_${i.id}`,_=`${(()=>{let d=n.types[l.id]?.cName;if(d)return d;let v=nn(l);return(v?n.types[v.id]?.cName:void 0)||`unknown_${l.id}`})()}_${u}`;n.dynImpls.set(_,{dynType:i,concreteType:s,dataType:o,traitValues:a});let p=M(r,t,n);if(r.$?.variableName&&p!==r.$.variableName){let d=st(r.$.type,r.$.variableName,n);n.emitter.emitLine(`${t}${d} = ${p};`),p=r.$.variableName}if(r.$?.deferredDupExpressions&&r.$.deferredDupExpressions.length>0){rt(r,t,n);let d=r.$.deferredDupExpressions[0];F(d)&&d.$?.variableName&&(p=Ee(d.$.variableName,d.$.env))}let f=e.$?.variableName;if(!f)return"/* Error: dyn() expression missing temp variable name */";let m=n,g;if(m.inAsyncStateMachine&&m.stateMachineVariables){for(let[,d]of m.stateMachineVariables)if(d.kind==="local"&&d.id===f){g=`sm->${rn(d.id,"local",m.stateMachineFieldAliases)}`;break}}let h=`__yo_vtable_${_}`;return g?(n.emitter.emitLine(`${t}${g} = (${u}){`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${h}`),n.emitter.emitLine(`${t}};`),g):(n.emitter.emitLine(`${t}${u} ${f} = {`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${h}`),n.emitter.emitLine(`${t}};`),f)}function S_(e,t,n){return e.args.length!==0?"// Error: __yo_gc_collect requires exactly 0 arguments":"__yo_gc_collect()"}function N_(e,t,n){let r=e.args[0],i=e.args[1],o=n;if(F(r)&&E(r,I.comptime,1)||F(r)&&E(r,I.given,1))return"";if((o.inAsyncStateMachine||o.inEffectStateMachine)&&z(r)&&z(i)){let a=r.token.value,s=i.token.value,l=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(c=>c.name===a),u=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(c=>c.name===s);if(a===s&&(l||u))return""}if(e.$?.runtimeDestructurings){let a=e.$.runtimeDestructurings,s=M(i,t,n),l=i.$?.type;return a.forEach(({label:u,type:c,variableName:_})=>{let p=te(_,c.isExtern==="c"),f=st(c,p,n);if(l&&ce(l)&&l.isNewtype&&l.fields.length===1){let h=l.fields[0];if(h&&h.label===u){n.emitter.emitLine(`${t}${f} = ${s}; // Destructuring ${u} (newtype)`);return}}let m=u.match(/^\d+$/)?`_${u}`:te(u,c.isExtern==="c");if(l&&we(l)&&!u.match(/^\d+$/)){let h=l.fields.findIndex(d=>d.label===u);m=h>=0?`_${h}`:m}let g=l&&pt(l)?"->":".";n.emitter.emitLine(`${t}${f} = ${s}${g}${m}; // Destructuring ${u}`)}),""}if(z(r)){let a=r.token.value;if(!r.$?.type)return`// Error: No type information for variable ${a}
10272
+ `;if(r.$?.env){let u=X(r.$.env,a);if(u.length>0&&u[u.length-1].isCompileTimeOnly)return""}let s=!1,l;if((o.inAsyncStateMachine||o.inEffectStateMachine)&&o.stateMachineVariables&&r.$?.env){let u=X(r.$.env,a);if(u.length>0){let c=u[u.length-1],_=c.isOwningTheSameRcValueAs?c.isOwningTheSameRcValueAs.id:c.id;o.stateMachineVariables.has(_)&&(s=!0,l=_)}}if(ke(r.$.type))if(F(i)&&E(i,I.array)){let u=M(i,t,n);if(s&&l){let c=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${c} = ${u};`)}else if(!pe(r.$.type)){let c=st(r.$.type,a,n);n.emitter.emitLine(`${t}${c} = ${u};`)}}else{let u;if(i.$?.variableName){let c=Ee(i.$.variableName,i.$.env),_=M(i,t,n);if(!s){let p=st(i.$.type,c,n);c!==_&&n.emitter.emitLine(`${t}${p} = ${_};`)}u=c}else u=M(i,t,n);if(s&&l){let c=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${c} = ${u};`)}else if(!pe(r.$.type)){let c=st(r.$.type,a,n);n.emitter.emitLine(`${t}${c} = ${u};`)}}else{let u,c=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Wt(i.$.type),_=F(i)&&Rt(i);if(i.$?.variableName){let p=Ee(i.$.variableName,i.$.env),f=Ee(a,r.$.env);if(p===f){if(u=M(i,t,n),!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let m=i.$.deferredDupExpressions[0];F(m)&&m.$?.variableName&&(u=Ee(m.$.variableName,m.$.env))}}else if(z(i)&&p===Ee(i.token.value,i.$.env)){if(u=M(i,t,n),!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let m=i.$.deferredDupExpressions[0];F(m)&&m.$?.variableName&&(u=Ee(m.$.variableName,m.$.env))}}else if(z(i)&&o.currentClosureCaptures&&o.currentClosureCaptures.includes(i.token.value)&&i.$?.env&&o.currentClosureCaptureFrameLevel!==void 0&&vr(i.token.value,i.$.env,o.currentClosureCaptureFrameLevel)){let m=o.currentClosureType;if(m&&m.isClosure){let g=Object.values(o.types).find(h=>h.type===m);g?u=`((${`${g.cName}_capture`}*)closure_context->data)->${Ee(i.token.value,i.$.env)}`:u=`closure_context->${Ee(i.token.value,i.$.env)}`}else u=`closure_context->${Ee(i.token.value,i.$.env)}`}else{let m=M(i,t,n);if(m.trim()!==p){let g=i.$.convertedRuntimeType||i.$.type,h=st(g,p,n);n.emitter.emitLine(`${t}${h} = ${m};`)}if(!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let g=i.$.deferredDupExpressions[0];F(g)&&g.$?.variableName?u=Ee(g.$.variableName,g.$.env):u=p}else u=p}}else if(u=M(i,t,n),!c&&!_&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){rt(i,t,o);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(u=Ee(p.$.variableName,p.$.env))}if(Qe(r.$.type)){let p=r.$.type;if(s&&l){let f=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${f} = ${u};`)}else if(!pe(p)){let f=st(p,a,n);n.emitter.emitLine(`${t}${f} = ${u};`)}}else if(s&&l){let p=rn(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${p} = ${u};`)}else{let p=ut(i.$.env.modulePath,u.trim()),f;if(p&&n.tempVarAsyncStructNames){let m=n.tempVarAsyncStructNames.get(u.trim());m?f=`${m}*`:f=P(r.$.type,n)}else f=P(r.$.type,n);pe(r.$.type)||n.emitter.emitLine(`${t}${f} ${Ee(a,r.$.env)} = ${u};`)}}return""}}var cg=0;function Xo(e,t,n,r,i=" "){if(k.__yo_op_add.includes(e))return`((${t[0]}) + (${t[1]}))`;if(k.__yo_op_sub.includes(e))return`((${t[0]}) - (${t[1]}))`;if(k.__yo_op_mul.includes(e))return`((${t[0]}) * (${t[1]}))`;if(k.__yo_op_div.includes(e))return`((${t[0]}) / (${t[1]}))`;if(k.__yo_op_mod.includes(e))return`((${t[0]}) % (${t[1]}))`;if(k.__yo_op_neg.includes(e))return`(-(${t[0]}))`;if(k.__yo_op_eq.includes(e))return`((${t[0]}) == (${t[1]}))`;if(k.__yo_op_neq.includes(e))return`((${t[0]}) != (${t[1]}))`;if(k.__yo_op_lt.includes(e))return`((${t[0]}) < (${t[1]}))`;if(k.__yo_op_lte.includes(e))return`((${t[0]}) <= (${t[1]}))`;if(k.__yo_op_gt.includes(e))return`((${t[0]}) > (${t[1]}))`;if(k.__yo_op_gte.includes(e))return`((${t[0]}) >= (${t[1]}))`;if(k.__yo_op_not.includes(e))return`(!(${t[0]}))`;if(k.__yo_op_bit_and.includes(e))return`((${t[0]}) & (${t[1]}))`;if(k.__yo_op_bit_or.includes(e))return`((${t[0]}) | (${t[1]}))`;if(k.__yo_op_bit_xor.includes(e))return`((${t[0]}) ^ (${t[1]}))`;if(k.__yo_op_bit_complement.includes(e))return`(~(${t[0]}))`;if(k.__yo_op_bit_left_shift.includes(e))return`((${t[0]}) << (${t[1]}))`;if(k.__yo_op_bit_right_shift.includes(e))return`((${t[0]}) >> (${t[1]}))`;if(k.__yo_noop.includes(e))return"";if(k.__yo_return_self.includes(e))return`(*${t[0]})`;if(k.__yo_ms_sleep.includes(e))return Pt(r.targetInfo)?`Sleep(${t[0]})`:`usleep((${t[0]}) * 1000)`;if(k.__yo_decr_rc.includes(e))return`__yo_decr_rc((void*)(${t[0]}))`;if(k.__yo_as.includes(e)&&n.$?.type){let o=P(n.$.type,r),a=n.args[0]?.$?.type;return a&&ge(a)&&!Fn(a)?`((${o})((${t[0]}).tag))`:`((${o})(${t[0]}))`}else{if(k.__yo_ptr_add.includes(e))return`(${t[0]} + ${t[1]})`;if(k.__yo_ptr_sub.includes(e))return`(${t[0]} - ${t[1]})`;if(k.__yo_ptr_diff.includes(e))return`(${t[0]} - ${t[1]})`;if(k.__yo_ptr_eq.includes(e))return`(${t[0]} == ${t[1]})`;if(k.__yo_ptr_neq.includes(e))return`(${t[0]} != ${t[1]})`;if(k.__yo_ptr_lt.includes(e))return`(${t[0]} < ${t[1]})`;if(k.__yo_ptr_lte.includes(e))return`(${t[0]} <= ${t[1]})`;if(k.__yo_ptr_gt.includes(e))return`(${t[0]} > ${t[1]})`;if(k.__yo_ptr_gte.includes(e))return`(${t[0]} >= ${t[1]})`;if(k.__yo_slice_len.includes(e))return`(${t[0]}.length)`;if(k.__yo_slice_new.includes(e)&&n.$?.type)return`(${P(n.$.type,r)}){ .data = ${t[0]}, .length = ${t[1]} }`;if(k.__yo_getrandom.includes(e))return`getrandom(${t[0]}, ${t[1]}, ${t[2]})`;if(k.__yo_arc4random_buf.includes(e))return`(arc4random_buf(${t[0]}, ${t[1]}), (void)0)`;if(k.__yo_bcrypt_gen_random.includes(e))return`(int32_t)BCryptGenRandom(NULL, ${t[0]}, ${t[1]}, BCRYPT_USE_SYSTEM_PREFERRED_RNG)`;if(k.__yo_maybe_uninit_new.includes(e)&&n.$?.type){let o=P(n.$.type,r),a=`__yo_uninit_${cg++}`;return r.emitter.emitLine(`${i}${o} ${a};`),a}else return k.__yo_maybe_uninit_as_ptr.includes(e)&&n.$?.type?`((${P(n.$.type,r)})(${t[0]}))`:k.__yo_maybe_uninit_assume_init.includes(e)?`(${t[0]})`:`/* Unhandled operator ${e} */`}}function V_(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_extract requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type;if(!o||!wt(o))return"// Error: __yo_iso_extract requires an Iso type";let a=P(o,n),s=e.$?.type;if(s&&n.isoTypes?.has(a)){let c=n.isoTypes.get(a);c.optionTypeCName||(c.optionTypeCName=P(s,n))}let l=`__yo_iso_extract_${a}(${i})`,u=e.$?.variableName;return u&&s?(n.emitter.emitLine(`${t}${P(s,n)} ${u} = ${l};`),u):l}function x_(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_dispose requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type;return!o||!wt(o)?"// Error: __yo_iso_dispose requires an Iso type":`__yo_iso_dispose_${P(o,n)}(${i})`}function Tl(e){let t=e.func.$?.value;return O(t)&&wt(t.value)&&e.args.length===1}function D_(e,t,n){if(!Tl(e))return"/* Error: generateIsoTypeCall called on non-Iso type call */";let i=(e.func.$?.value).value,o=i.childType,a=e.args[0],s=M(a,t,n),l=P(i,n),u=P(o,n);return n.isoTypes||(n.isoTypes=new Map),n.isoTypes.has(l)||n.isoTypes.set(l,{childTypeCName:u,isoType:i}),`__yo_create_iso_${l}(${s})`}function Nr(e){return e===""||e==="break"||e==="continue"||e.startsWith("goto")||e.includes("return")}function Vr(e,t,n){if(F(e)&&E(e,I.begin)){let r=e.args,i=n,o=i.pendingDeferredDrops,a=e.$?.deferredDropExpressions??[];i.pendingDeferredDrops=[...a,...o??[]];let s=i.consumedVarPendingDrops,l=e.$?.consumedVariableDropExpressions??[];i.consumedVarPendingDrops=[...l,...s??[]];for(let c=0;c<r.length-1;c++){let _=r[c],p=M(_,t,n);if(p&&n.emitter.emitLine(`${t}${p};`),nt(_.$?.controlFlow))break}let u="";if(r.length>0){let c=r[r.length-1];if(c.$?.deferredDupExpressions&&c.$.deferredDupExpressions.length>0){if(c.$?.variableName){let p=c.$.variableName;c.$.variableName=void 0;let f=M(c,t,n);c.$.variableName=p;let m=P(c.$.type,n),g=Ee(p,c.$.env);g!==f&&n.emitter.emitLine(`${t}${m} ${g} = ${f};`)}rt(c,t,n);let _=c.$.deferredDupExpressions[0];F(_)&&_.$?.variableName?u=Ee(_.$.variableName,_.$.env):u=M(c,t,n)}else u=M(c,t,n)}return e.$?.deferredDropExpressions&&bt(e,t,n),i.pendingDeferredDrops=o,i.consumedVarPendingDrops=s,u}else return e.$?.deferredDupExpressions&&rt(e,t,n),M(e,t,n)}function O_(e,t,n){if(!e.$)return'/* "match" expression is not evaluated */';let r=e.$.variableName,i=e.$.type,o=i&&pe(i);if(!o&&r){let g=P(i,n);n.emitter.emitLine(`${t}${g} ${r};`)}let a=M(e.args[0],t,n),s=e.args[0].$?.type;if(!s)return'// Error: "match" expression requires a valid type';if(e.$.isPrimitiveMatch)return pg(e,t,n,a,s,r,o);let l,u;if(Ie(s)?(u=s.childType,l=s.tag):pt(s)?(u=s,l="ref_semantics"):u=s,!ge(u))return'// Error: "match" expression requires an enum type';if(!n.types[u.id]?.cName)return`// Error: "match" expression enum type ${u.typeName} has no C name`;let _=Yt(u);if(_){let g=e.args.slice(1),h=null,d=null;for(let v of g)if(F(v)&&E(v,"=>",2)){if(!v.args[0]?.$?.caseExecuted)continue;let T=v.args[0],$=v.args[1];if(T&&$&&F(T)&&E(T,"."))h={caseBody:$};else{let C=T.func;if(C&&F(C)&&E(C,".")){let L=C.args[0];if(L&&z(L)){let b=L.token.value;d={caseBody:$,variantName:b,casePattern:T}}}}}if(n.emitter.emitLine(`${t}if (${l&&l!=="ref_semantics"?"*":""}${a} != NULL) {`),d){let v;if(F(d.casePattern)&&d.casePattern.args.length>0){let L=d.casePattern.args[0];if(L&&z(L)){v=te(L.token.value);let b=_;n.emitter.emitLine(`${t} ${P(b,n)} ${v} = ${a};`)}}let T=n;v&&(T.inAsyncStateMachine||T.inEffectStateMachine)&&(T.localShadowedVariables||(T.localShadowedVariables=new Set),T.localShadowedVariables.add(v));let $=Vr(d.caseBody,t+" ",n);v&&T.localShadowedVariables&&T.localShadowedVariables.delete(v);let C=Nr($);if(!o&&r&&!C){let L=$||a;n.emitter.emitLine(`${t} ${r} = ${L};`)}else $&&$!==""&&n.emitter.emitLine(`${t} ${$};`)}if(n.emitter.emitLine(`${t}} else {`),h){let v=Vr(h.caseBody,t+" ",n),T=Nr(v);!o&&r&&!T?n.emitter.emitLine(`${t} ${r} = ${v};`):v&&v!==""&&n.emitter.emitLine(`${t} ${v};`)}return n.emitter.emitLine(`${t}}`),o?"":r??""}if(Fn(u)){n.emitter.emitLine(`${t}switch (${l&&l!=="ref_semantics"?"*":""}${a}) {`);let g=n.insideMatch;n.insideMatch=!0;let h=e.args.slice(1);for(let d=0;d<h.length;d++){let v=h[d];if(F(v)&&E(v,"=>",2)){if(!v.args[0]?.$?.caseExecuted)continue;let T=v.args[0],$=v.args[1];if(T&&$&&z(T)&&T.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let C=Vr($,t+" ",n);!o&&r&&C&&!Nr(C)?n.emitter.emitLine(`${t} ${r} = ${C};`):C&&n.emitter.emitLine(`${t} ${C};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(T&&$&&F(T)&&E(T,".",1)){let C=T.args[0].token.value,L=Bt(u,C,n);n.emitter.emitLine(`${t}case ${L}: {`);let b=Vr($,t+" ",n);!o&&r&&b&&!Nr(b)?n.emitter.emitLine(`${t} ${r} = ${b};`):b&&n.emitter.emitLine(`${t} ${b};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}}return n.insideMatch=g,n.emitter.emitLine(`${t}}`),o?"":r??""}n.emitter.emitLine(`${t}switch (${l==="ref_semantics"||l?a+"->tag":"("+a+").tag"}) {`);let f=n.insideMatch;n.insideMatch=!0;let m=e.args.slice(1);for(let g=0;g<m.length;g++){let h=m[g];if(F(h)&&E(h,"=>",2)){if(!h.args[0]?.$?.caseExecuted)continue;let d=h.args[0],v=h.args[1];if(d&&v&&z(d)&&d.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let T=Vr(v,t+" ",n);!o&&r&&T&&!Nr(T)?n.emitter.emitLine(`${t} ${r} = ${T};`):T&&n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(d&&v&&F(d)&&d.func.tag==="Atom"&&d.func.token.value==="."&&d.args.length>=1){let T=d.args[0].token.value,$=Bt(u,T,n);if(n.emitter.emitLine(`${t}case ${$}: {`),d.args.length>1){let L=u.variants.find(b=>b.name===T);if(L&&L.fields){let b=d.args.slice(1);if(b.some(N=>F(N)&&E(N,":",2))){for(let N of b)if(F(N)&&E(N,":",2)){let B=N.args[0],D=N.args[1];if(!z(B))continue;let V=B.token.value,U=L.fields.find(re=>re.label===V);if(!U||pe(U.type))continue;if(z(D)){let re=D.token.value;if(re!=="_"){let j=te(re),W=te(V),le=P(U.type,n),_e=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${le} ${j} = ${a}${_e}data.${T}.${W};`);let ve=n;if((ve?.inAsyncStateMachine||ve?.inEffectStateMachine)&&ve.stateMachineVariables){let q;if(D.$?.env){let Z=X(D.$.env,re);Z.length>0&&(q=Z[Z.length-1].id)}if(q&&ve.stateMachineVariables.has(q)){let Z=rn(q,"local",ve.stateMachineFieldAliases);n.emitter.emitLine(`${t} sm->${Z} = ${j};`)}}}}}}else for(let N=0;N<b.length&&N<L.fields.length;N++){let B=b[N],D=L.fields[N];if(z(B)&&D){if(pe(D.type))continue;let V=B.token.value;if(V!=="_"){let U=te(V),re=te(D.label),j=P(D.type,n),W=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${j} ${U} = ${a}${W}data.${T}.${re};`);let le=n;if((le?.inAsyncStateMachine||le?.inEffectStateMachine)&&le.stateMachineVariables){let _e;if(B.$?.env){let ve=X(B.$.env,V);ve.length>0&&(_e=ve[ve.length-1].id)}_e&&le.stateMachineVariables.has(_e)&&n.emitter.emitLine(`${t} sm->${rn(_e,"local",le.stateMachineFieldAliases)} = ${U};`)}}}}}}if(F(v)&&E(v,"=>",2)){let L=v.args[0];n.emitter.emitLine(`${t} ${P(s,n)} ${te(L.token.value)} = ${a};`),v=v.args[1]}let C=Vr(v,t+" ",n);!o&&r&&C&&!Nr(C)?n.emitter.emitLine(`${t} ${r} = ${C};`):C&&n.emitter.emitLine(`${t} ${C};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(d&&v&&F(d)&&F(d.func)&&d.func.func.tag==="Atom"&&d.func.func.token.value==="."&&d.func.args.length===1){let T=d.func.args[0].token.value,$=Bt(u,T,n),C=d.args;n.emitter.emitLine(`${t}case ${$}: {`);let L=u.variants.find(R=>R.name===T);if(L&&L.fields&&C.length>0)if(C.some(N=>F(N)&&E(N,":",2))){for(let N of C)if(F(N)&&E(N,":",2)){let B=N.args[0],D=N.args[1];if(!z(B))continue;let V=B.token.value,U=L.fields.find(re=>re.label===V);if(!U)continue;if(z(D)){let re=D.token.value;if(re!=="_"){let j=te(re);if(pe(U.type))n.emitter.emitLine(`${t} // ${j} is unit type (no value)`);else{let W=te(V),le=P(U.type,n),_e=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${le} ${j} = ${a}${_e}data.${T}.${W};`);let ve=n;if((ve?.inAsyncStateMachine||ve?.inEffectStateMachine)&&ve.stateMachineVariables){let q;if(D.$?.env){let Z=X(D.$.env,j);Z.length>0&&(q=Z[Z.length-1].id)}q&&ve.stateMachineVariables.has(q)&&n.emitter.emitLine(`${t} sm->${rn(q,"local",ve.stateMachineFieldAliases)} = ${j};`)}}}}}}else for(let N=0;N<Math.min(C.length,L.fields.length);N++){let B=C[N],D=L.fields[N];if(B.tag==="Atom"&&D){let V=B.token.value;if(V!=="_"){let U=te(V);if(pe(D.type))n.emitter.emitLine(`${t} // ${U} is unit type (no value)`);else{let re=te(D.label),j=P(D.type,n),W=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${j} ${U} = ${a}${W}data.${T}.${re};`);let le=n;if((le?.inAsyncStateMachine||le?.inEffectStateMachine)&&le.stateMachineVariables){let _e;if(B.$?.env){let ve=X(B.$.env,V);ve.length>0&&(_e=ve[ve.length-1].id)}_e&&le.stateMachineVariables.has(_e)&&n.emitter.emitLine(`${t} sm->${rn(_e,"local",le.stateMachineFieldAliases)} = ${U};`)}}}}}if(F(v)&&E(v,"=>",2)){let R=v.args[0];n.emitter.emitLine(`${t} ${P(s,n)} ${te(R.token.value)} = ${a};`),v=v.args[1]}let b=Vr(v,t+" ",n);!o&&r&&b&&!Nr(b)?n.emitter.emitLine(`${t} ${r} = ${b};`):b&&n.emitter.emitLine(`${t} ${b};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}}return n.insideMatch=f,n.emitter.emitLine(`${t}}`),e.$?.deferredDropExpressions&&bt(e,t,n),o?"":r??""}function _g(e){return F(e)?E(e,"|",2):!1}function El(e){if(!_g(e))return[e];let t=e,n=t.args[0],r=t.args[1];return[...El(n),...El(r)]}function M_(e){if(e!==void 0){if(ze(e))return String(e.value);if(Re(e))return e.value?"true":"false"}}function pg(e,t,n,r,i,o,a){let s=n.insideMatch;n.insideMatch=!0,n.emitter.emitLine(`${t}switch (${r}) {`);let l=e.args.slice(1);for(let u=0;u<l.length;u++){let c=l[u];if(F(c)&&E(c,"=>",2)){if(!c.args[0]?.$?.caseExecuted)continue;let _=c.args[0],p=c.args[1];if(!_||!p)continue;if(z(_)&&_.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let h=Vr(p,t+" ",n);!a&&o&&h&&!Nr(h)?n.emitter.emitLine(`${t} ${o} = ${h};`):h&&n.emitter.emitLine(`${t} ${h};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`);continue}let f=El(_),m=_.$?.primitivePatternValues;if(m&&m.length>0)for(let h of m){let d=M_(h);d!==void 0&&n.emitter.emitLine(`${t}case ${d}:`)}else for(let h of f){let d=h.$?.value,v=M_(d);v!==void 0&&n.emitter.emitLine(`${t}case ${v}:`)}n.emitter.emitLine(`${t}{`);let g=Vr(p,t+" ",n);!a&&o&&g&&!Nr(g)?n.emitter.emitLine(`${t} ${o} = ${g};`):g&&n.emitter.emitLine(`${t} ${g};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}return n.insideMatch=s,n.emitter.emitLine(`${t}}`),e.$?.deferredDropExpressions&&bt(e,t,n),a?"":o??""}function R_(e,t,n){if(e.$?.runtimeDestructurings&&e.$.runtimeDestructurings.length>0){let r=e.args[0];if(!r||!r.$?.type)return"// Error: open expression has no argument or type";let i=r.$.type,o=r.$.value;if(ce(i)&&o===void 0){let a=M(r,t,n),s=e.$.runtimeDestructurings;for(let l of s){let u=P(l.type,n),c=te(l.variableName),_=te(l.label);n.emitter.emitLine(`${t}${u} ${c} = ${a}.${_};`)}}}return""}function P_(e,t,n,r){if(!t.callType)return e;let i=$t(t.callType);if(i.length===0)return e;let o=i.map(()=>"NULL").join(", "),s=`__yo_spawn_wrapper_${qe(r)}`;return n.emitter.emitDeclarationLine(`
10273
+ // Spawn wrapper: bridges __yo_thread_fn to closure with evidence params
10274
+ static void ${s}(void* closure) {
10275
+ ${e}(closure, ${o});
10276
+ }
10277
+ `),s}function U_(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(!r||r.length!==1)return"/* Error: __yo_thread_spawn requires exactly 1 argument */";let i=r[0],o=i.$?.type;if(!o)return"/* Error: __yo_thread_spawn argument has no type */";let a,s;if(x(o)){let h=o;h.resolvedConcreteType&&(a=h.resolvedConcreteType.id,s=h.resolvedConcreteType)}else ce(o)&&(a=o.id,s=o);if(!a||!s)return"/* Error: __yo_thread_spawn could not determine concrete closure type */";let l=n.implClosureCallMap.get(a);if(!l)return`/* Error: __yo_thread_spawn could not find closure function for type ${a} */`;let u=l.functionCName,c=P(s,n),_=P_(u,l,n,e.$?.env.modulePath??""),p=M(i,t,n),f=i.$?.variableName?Ee(i.$.variableName,i.$.env):p,m=`_thread_closure_data_${qe(e.$?.env.modulePath??"")}`;n.emitter.emitLine(`${t}${c}* ${m} = (${c}*)__yo_malloc(sizeof(${c}));`),n.emitter.emitLine(`${t}*${m} = ${f};`);let g=e.$?.variableName;return g?(n.emitter.emitLine(`${t}__yo_thread_t ${g} = __yo_thread_spawn(${_}, ${m});`),g):`__yo_thread_spawn(${_}, ${m})`}function z_(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(!r||r.length!==1)return"/* Error: __yo_worker_spawn requires exactly 1 argument */";let i=r[0],o=i.$?.type;if(!o)return"/* Error: __yo_worker_spawn argument has no type */";let a,s;if(x(o)){let g=o;g.resolvedConcreteType&&(a=g.resolvedConcreteType.id,s=g.resolvedConcreteType)}else ce(o)&&(a=o.id,s=o);if(!a||!s)return"/* Error: __yo_worker_spawn could not determine concrete closure type */";let l=n.implClosureCallMap.get(a);if(!l)return`/* Error: __yo_worker_spawn could not find closure function for type ${a} */`;let u=l.functionCName,c=P(s,n),_=P_(u,l,n,e.$?.env.modulePath??""),p=M(i,t,n),f=i.$?.variableName?Ee(i.$.variableName,i.$.env):p,m=`_worker_closure_data_${qe(e.$?.env.modulePath??"")}`;return n.emitter.emitLine(`${t}${c}* ${m} = (${c}*)__yo_malloc(sizeof(${c}));`),n.emitter.emitLine(`${t}*${m} = ${f};`),n.emitter.emitLine(`${t}__yo_worker_spawn(${_}, ${m});`),""}function B_(e,t,n){let r=e.args[0];return r?`__yo_thread_set_maximum_threads(${M(r,t,n)})`:"// Error: __yo_thread_set_maximum_threads requires exactly 1 argument"}function G_(e,t){let n=t;if(!(n.inAsyncStateMachine||n.inEffectStateMachine)||!n.stateMachineVariables)return e;for(let[r,i]of n.stateMachineVariables)if(i.name===e)return`sm->${i.kind==="outer"?`__capture.${i.name}`:`var_${r}`}`;return e}function Ln(e,t,n){let r=n;if(!(r.inAsyncStateMachine||r.inEffectStateMachine)||!r.stateMachineVariables)return;let i=r.stateMachineVariables.get(e);if(!i){for(let[,o]of r.stateMachineVariables)if(o.name===e){i=o;break}}if(i&&i.kind!=="outer"){if(i.type&&Ce(i.type))return;let o=`var_${i.id}`,a=te(e);n.emitter.emitLine(`${t}sm->${o} = ${a};`)}}function Y_(e,t,n){if(e.$?.value!==void 0&&!de(e.$.value))return e.$?.deferredDropExpressions&&bt(e,t,n),pe(e.$.type)?"":Qt(e.$.value,n,e);let r=e.func.$?.value,i=e.func.$?.type??(ne(r)?r.specializedType??r.type:void 0);if(G(i)){let o=e.$?.runtimeArgExprsInOrder;if(o){let a=!1;if(F(e.func)&&E(e.func,".",2)){let c=e.func.args[0]?.$?.type;c&&be(c)&&(a=!0)}let s=o.map((u,c)=>{if(u.$?.variableName&&u.$?.type){let _=n,p=_.currentClosureCaptures&&_.currentClosureCaptures.includes(u.$.variableName)&&z(u)&&u.$.env&&_.currentClosureCaptureFrameLevel!==void 0&&vr(u.token.value,u.$.env,_.currentClosureCaptureFrameLevel),f=M(u,t,n),m=!1;if(z(u)&&u.$.env&&u.$.variableName){let v=X(u.$.env,u.$.variableName);v.length>0&&v[v.length-1].isCompileTimeOnly&&(m=!0)}let g=(_.inAsyncStateMachine||_.inEffectStateMachine)&&f.startsWith("sm->"),h=!1;if(f&&f!==u.$.variableName&&!p&&!g&&!m){let v=Ee(u.$.variableName,u.$.env);if(f!==v){let T=u.$.convertedRuntimeType||u.$.type,$=st(T,u.$.variableName,n);n.emitter.emitLine(`${t}${$} = ${f};`),h=!0,Ln(u.$.variableName,t,n)}}let d=h?u.$.variableName:f;if(u.$?.deferredDupExpressions&&u.$.deferredDupExpressions.length>0){let v=new Set;u.$?.variableName&&v.add(Ee(u.$.variableName,u.$.env)),f&&v.add(f),z(u)&&v.add(Ee(u.token.value,u.$.env));let T=u.$.deferredDupExpressions.find($=>{let C=Ra($);return C?v.has(Ee(C,$.$?.env)):!1});T&&(rt(u,t,_),F(T)&&T.$?.variableName&&(d=Ee(T.$.variableName,T.$.env)))}if(a&&c===0){if(F(e.func)&&E(e.func,".",2)){let $=e.func.args[0]?.$?.type,C=e.func.args[1];if(z(C)&&be($)){let L=C.token.value;if($.trait.fields.find(R=>R.label===L))return g?f:te(d,u.$.type.isExtern==="c")}}let v=u.$?.type;return v&&Ie(v)?g?`${f}->data`:`${te(d,u.$.type.isExtern==="c")}->data`:g?`(${f}).data`:`(${te(d,u.$.type.isExtern==="c")}).data`}else return p||g||m?f:te(d,u.$.type.isExtern==="c")}else if(a&&c===0){let _=M(u,t,n);if(F(e.func)&&E(e.func,".",2)){let m=e.func.args[0]?.$?.type,g=e.func.args[1];if(z(g)&&be(m)){let h=g.token.value;if(m.trait.fields.find(v=>v.label===h))return _}}let p=u.$?.type;return p&&Ie(p)?`(${_})->data`:`(${_}).data`}else return M(u,t,n)}),l=s.join(", ");if(i.isExtern==="yo"&&i.externName){let u=i.externName;return gi.includes(u)?Xo(u,s,e,n,t):u==="__yo_thread_spawn"?U_(e,t,n):u==="__yo_worker_spawn"?z_(e,t,n):pe(i.return.type)?(n.emitter.emitLine(`${t}${u}(${l});`),e.$?.deferredDropExpressions&&bt(e,t,n),""):`${u}(${l})`}{let u=n;if(u.currentEvidenceParams?.size){let c=e.func.token?.value,_;if(c==="."&&F(e.func)&&E(e.func,".",2)){let p=e.func.args[1];p&&z(p)&&(c=p.token.value);let f=e.func.args[0];if(f&&z(f))_=f.token.value;else if(f&&F(f)&&E(f,".",2)){let m=f.args[0];m&&z(m)&&(_=m.token.value)}}if(c&&c!=="."){for(let p of u.currentEvidenceParams.values())if(p.fieldLabel===c||p.implicitLabel===c||p.fieldPath[p.fieldPath.length-1]===c){if(_&&_!==p.implicitLabel)continue;return q_(p.cParamName,i,s,o,e,t,u,p)}}}}if(ne(r)){let u=Ki(r);if(u)return Xo(u,s,e,n,t);let c=r.specializedType??r.type,_=n;if(_.currentEvidenceParams&&r.isModuleEffectMember){let f,m=e.func.$?.env??e.$?.env;if(m)for(let g of _.currentEvidenceParams.values()){let h=X(m,g.implicitLabel),v=h[h.length-1]?.value?.[0];if(v&&We(v)){let T=v,$=!0;for(let C=0;C<g.fieldPath.length-1;C++){let L=g.fieldPath[C],b=T.type.fields.findIndex(R=>R.label===L);if(b>=0&&T.fields[b]&&We(T.fields[b]))T=T.fields[b];else{$=!1;break}}if($){let C=g.fieldPath[g.fieldPath.length-1],L=T.type.fields.findIndex(b=>b.label===C);if(L>=0){let b=T.fields[L];if(b&&ne(b)&&b.funcId===r.funcId){f=g;break}}}}}if(f){let g=f.cParamName;return q_(g,c,s,o,e,t,_,f)}}let p=n.functions[r.funcId]?.cName;if(p){let f=r.specializedType??r.type,m=$t(f);if(m.length===0&&r.specializedType){let d=$t(r.type);d.length>0&&d.some(v=>v.fieldFunctionType.forallParameters&&v.fieldFunctionType.forallParameters.length>0)&&(m=d)}if(m.length>0){let{args:d,isHandlerInstallation:v}=$l(m,r,e,n);if(d.length>0){let T=l?`${l}, ${d.join(", ")}`:d.join(", ");return Cl(p,T,c,e,o,t,n,v)}}let g=r.isControlFunction||r.isModuleEffectMember||r.body?.$?.effectAnalysis?.hasEffects,h=!1;if(g){if(r.isControlFunction||r.isModuleEffectMember){let d=e.func?.$?.env??e.$?.env;if(d){let v=Bo(d,T=>T.isImplicit===!0&&ne(T.value?.[0])&&T.value[0].funcId===r.funcId);v>=0&&v>d.functionDeclarationFrameLevel&&d.frames[v]?.isBeginBlockFrame&&(h=!0)}}else if(r.specializedType){let d=$t(r.type);if(d.length>0){let v=e.func?.$?.env??e.$?.env;if(v)for(let T of d){let $=Bo(v,C=>C.isImplicit===!0&&(C.name===T.implicitLabel||C.name===T.fieldLabel));if($>=0&&$>v.functionDeclarationFrameLevel&&v.frames[$]?.isBeginBlockFrame){h=!0;break}}}}}if(pe(c.return.type))return n.emitter.emitLine(`${t}${p}(${l});`),e.$?.deferredDropExpressions&&bt(e,t,n),g&&W_(t,n,h,e),"";{let d=e.$?.variableName;if(d){let v=r.specializedType?.return.type??c.return.type,T=e.$?.type,$=T&&Ce(T),C=v&&Ce(v),L;if($&&C){let b=r.body;if(b&&E(b,"begin")){let R=b.args;if(R.length>0){let N=R[R.length-1];Rt(N)&&(b=N)}}if(b&&Rt(b)&&b.$?.asyncStateMachineStructName){let R=b.$.asyncStateMachineStructName;L=`${R}*`,n.tempVarAsyncStructNames||(n.tempVarAsyncStructNames=new Map),n.tempVarAsyncStructNames.set(d,R)}else T&&x(T)&&T.resolvedConcreteType?L=P(T,n):L=P(v,n)}else L=P(v??T,n);return n.emitter.emitLine(`${t}${L} ${d} = ${p}(${l});`),Ln(d,t,n),e.$?.deferredDropExpressions&&bt(e,t,n),g&&W_(t,n,h,e),d}else return`// Error: Regular function call returns ${P(r.specializedType?.return.type??c.return.type,n)} but no temp variable assigned`}}}else{let u=n.externFunctions[i.id];if(u){let c=u.cName;return e.$?.deferredDropExpressions&&bt(e,t,n),`${c}(${l})`}else{let c=M(e.func,t,n);if(r&&G(r.type)){let d=$t(r.type);if(d.length>0){let{args:v,isHandlerInstallation:T}=$l(d,r,e,n);if(v.length>0){let $=l?`${l}, ${v.join(", ")}`:v.join(", ");return Cl(c,$,i,e,o,t,n,T)}}}let _=e.$?.type??i.return.type,p=P(_,n),f=i.parameters.filter(d=>!d.isCompileTimeOnly).map(d=>P(d.type,n)),m=`((${p} (*)(${f.join(", ")}))${c})`,g=n,h=c.includes("__capture.")&&!!g.inAsyncStateMachine;if(h&&n.emitter.emitLine(`${t}__yo_effect_escaped = 0;`),pe(i.return.type)||pe(_)){if(n.emitter.emitLine(`${t}${m}(${l});`),e.$?.deferredDropExpressions&&bt(e,t,n),h){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let d of o)if(d.$?.variableName&&d.$?.type&&Le(d.$.type)){let v=G_(te(d.$.variableName),n),T=Ir(v,d.$.type,n);T&&(n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} memset(&${v}, 0, sizeof(${v}));`))}}Mn({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return""}else{let d=e.$?.variableName;if(d){let v=i.return.type,T=e.$?.type,$=T&&v&&Ce(T)&&Ce(v)?v:T??v;if(n.emitter.emitLine(`${t}${P($,n)} ${d} = ${m}(${l});`),Ln(d,t,n),e.$?.deferredDropExpressions&&bt(e,t,n),h){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let C of o)if(C.$?.variableName&&C.$?.type&&Le(C.$.type)){let L=G_(te(C.$.variableName),n),b=Ir(L,C.$.type,n);b&&(n.emitter.emitLine(`${t} ${b};`),n.emitter.emitLine(`${t} memset(&${L}, 0, sizeof(${L}));`))}}Mn({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return d}else return`// Error: Function parameter call returns ${P(i.return.type,n)} but no temp variable assigned`}}}}}else if(i&&Wt(i)){let o=i,a=nn(o),s=be(o);{let l=a.isFn.callType,u=e.$?.runtimeArgExprsInOrder;if(u){let c=n;for(let g of u)if(g.$?.variableName&&g.$?.type){let h=c.currentClosureCaptures&&c.currentClosureCaptures.includes(g.$.variableName)&&z(g)&&g.$.env&&c.currentClosureCaptureFrameLevel!==void 0&&vr(g.token.value,g.$.env,c.currentClosureCaptureFrameLevel),d=M(g,t,n),v=!1;if(z(g)&&g.$.env&&g.$.variableName){let $=X(g.$.env,g.$.variableName);$.length>0&&$[$.length-1].isCompileTimeOnly&&(v=!0)}let T=(c.inAsyncStateMachine||c.inEffectStateMachine)&&d.startsWith("sm->");if(d&&d!==g.$.variableName&&!h&&!T&&!v){let $=g.$.convertedRuntimeType||g.$.type,C=st($,g.$.variableName,n);n.emitter.emitLine(`${t}${C} = ${d};`),Ln(g.$.variableName,t,n)}}let _=M(e.func,t,n),p=u.map(g=>{if(g.$?.variableName&&g.$?.type){if(c.currentClosureCaptures&&c.currentClosureCaptures.includes(g.$.variableName)&&z(g)&&g.$.env&&c.currentClosureCaptureFrameLevel!==void 0&&vr(g.token.value,g.$.env,c.currentClosureCaptureFrameLevel))return M(g,t,n);{let d=Ee(g.$.variableName,g.$.env),v=(c.inAsyncStateMachine||c.inEffectStateMachine)&&d.startsWith("sm->"),T=d;if(g.$?.deferredDupExpressions&&g.$.deferredDupExpressions.length>0){rt(g,t,c);let $=g.$.deferredDupExpressions[0];F($)&&$.$?.variableName&&(T=Ee($.$.variableName,$.$.env))}return v?d:T}}else return M(g,t,n)}),f;if(s){let g=[`(${_}).data`,...p];f=`(${_}).vtable->call(${g.join(", ")})`}else{let g;if(x(o)){let d=o;d.resolvedConcreteType&&(g=d.resolvedConcreteType.id)}let h=g?n.implClosureCallMap.get(g):void 0;if(h){let d=$t(l);if(d.length>0){let{args:T,isHandlerInstallation:$}=$l(d,{},e,c);if(T.length>0){let C=[`&(${_})`,...p,...T];return Cl(h.functionCName,C.join(", "),l,e,u,t,c,$)}}let v=[`&(${_})`,...p];f=`${h.functionCName}(${v.join(", ")})`}else{let d=[`(${_}).data`,...p];f=`(${_}).call(${d.join(", ")})`}}let m=l.return.type;if(pe(m))return n.emitter.emitLine(`${t}${f};`),e.$?.deferredDropExpressions&&bt(e,t,n),"";{let g=e.$?.variableName;return g?(n.emitter.emitLine(`${t}${P(m,n)} ${g} = ${f};`),Ln(g,t,n),e.$?.deferredDropExpressions&&bt(e,t,n),g):`// Error: Closure call returns ${P(m,n)} but no temp variable assigned`}}else return"// Error: No runtime args found for closure call"}}else if(O(r))if(ce(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=o.fields.map(c=>c.label),u=e.$?.variableName;if(a&&s&&l.length===a.length){if(o.isNewtype&&o.fields.length===1){let c=a[0],_=M(c,t,n),p=_;if(c.$?.deferredDupExpressions&&c.$.deferredDupExpressions.length>0){let m=n;if(c.$?.variableName&&c.$?.type){let h=Ee(c.$.variableName,c.$.env);if(_!==h){let d=c.$.type,v=P(d,n);n.emitter.emitLine(`${t}${v} ${h} = ${_};`)}}rt(c,t,m);let g=c.$.deferredDupExpressions[0];F(g)&&g.$?.variableName&&(p=Ee(g.$.variableName,g.$.env))}let f=`((${s})(${p}))`;if(u&&e.$?.type){let m=st(e.$.type,u,n);return n.emitter.emitLine(`${t}${m} = ${f};`),Ln(u,t,n),u}else return f}if(o.isReferenceSemantics){let c=n,_=a.map(m=>{let g=M(m,t,n);if(m.$?.deferredDupExpressions&&m.$.deferredDupExpressions.length>0){if(m.$?.variableName&&m.$?.type){let d=Ee(m.$.variableName,m.$.env);if(g!==d){let v=m.$.type,T=P(v,n);n.emitter.emitLine(`${t}${T} ${d} = ${g};`)}}rt(m,t,c);let h=m.$.deferredDupExpressions[0];if(F(h)&&h.$?.variableName)return Ee(h.$.variableName,h.$.env)}return g}).join(", "),f=`${`__yo_new_${s}`}(${_})`;if(u&&e.$?.type){let m=st(e.$.type,u,n);return n.emitter.emitLine(`${t}${m} = ${f};`),Ln(u,t,n),u}else return f}else{let c=n,_=a.map((f,m)=>{let g=M(f,t,n),h=we(o)?`_${m}`:te(l[m],o.isExtern==="c"),d=g;if(f.$?.deferredDupExpressions&&f.$.deferredDupExpressions.length>0){if(f.$?.variableName&&f.$?.type){let T=Ee(f.$.variableName,f.$.env),$=f.$.type,C=P($,n);g!==T&&n.emitter.emitLine(`${t}${C} ${T} = ${g};`)}rt(f,t,c);let v=f.$.deferredDupExpressions[0];F(v)&&v.$?.variableName&&(d=Ee(v.$.variableName,v.$.env))}return`.${h} = `+d}).join(", "),p=`(${s}){ ${_} }`;if(u&&e.$?.type){let f=st(e.$.type,u,n);return n.emitter.emitLine(`${t}${f} = ${p};`),Ln(u,t,n),u}else return p}}}else{if(Wt(r.value))return"// Error: Closure construction should have been handled by closureFunctionValue check at top of generateFuncCall";if(it(r.value)){let o=e.$?.variableName,a=e.args[0];if(a&&F(a)&&E(a,":",2)){let s=a.args[0],l=a.args[1],u=n.types[r.value.id]?.cName;if(u&&z(s)&&l){let c=n,_=s.token.value,p=Ee(_,s.$?.env),m=M(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){rt(l,t,c);let h=l.$.deferredDupExpressions[0];F(h)&&h.$?.variableName&&(m=Ee(h.$.variableName,h.$.env))}let g=`(${u}){ .${p} = ${m} }`;if(o&&e.$?.type){let h=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${h} = ${g};`),Ln(o,t,n),o}else return g}}}else if(ge(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=e.$?.variableName;if(o.selectedVariantName&&a&&s){if(Yt(o)){let f=o.selectedVariantName,m=o.variants.find(g=>g.name===f);if(m){if(!m.fields||m.fields.length===0){let g="NULL";if(l&&e.$?.type){let h=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${h} = ${g};`),Ln(l,t,n),l}else return g}else if(m.fields.length===1){let g=M(a[0],t,n);if(l&&e.$?.type){let h=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${h} = ${g};`),Ln(l,t,n),l}else return g}}}if(Fn(o)){let f=o.selectedVariantName,m=Bt(o,f,n);if(l&&e.$?.type){let g=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${g} = ${m};`),Ln(l,t,n),l}else return m}let _=o.selectedVariantName,p=o.variants.find(f=>f.name===_);if(p){let f=p.fields?.filter(d=>!pe(d.type))||[],m=n,g=a.map((d,v)=>{if(p.fields){let T=p.fields[v];if(T&&!pe(T.type)){let $=M(d,t,n),C=Ee(T.label,d.$?.env),L=$;if(d.$?.variableName&&d.$?.type){let b=m.currentClosureCaptures&&m.currentClosureCaptures.includes(d.$.variableName)&&z(d)&&d.$.env&&m.currentClosureCaptureFrameLevel!==void 0&&vr(d.token.value,d.$.env,m.currentClosureCaptureFrameLevel),R=(m.inAsyncStateMachine||m.inEffectStateMachine)&&$.startsWith("sm->"),N=!1;if(z(d)&&d.$.env&&d.$.variableName){let D=X(d.$.env,d.$.variableName);D.length>0&&D[D.length-1].isCompileTimeOnly&&(N=!0)}let B=!1;if($&&$!==d.$.variableName&&!b&&!R&&!N){let D=Ee(d.$.variableName,d.$.env);if($!==D){let V=st(d.$.type,d.$.variableName,n);n.emitter.emitLine(`${t}${V} = ${$};`),B=!0,Ln(d.$.variableName,t,n)}}B&&(L=Ee(d.$.variableName,d.$.env))}if(d.$?.deferredDupExpressions&&d.$.deferredDupExpressions.length>0){rt(d,t,m);let b=d.$.deferredDupExpressions[0];F(b)&&b.$?.variableName&&(L=Ee(b.$.variableName,b.$.env))}return`.${C} = `+L}return""}else return""}).filter(d=>d).join(", "),h=f.length>0?`(${s}){ .tag = ${Bt(o,_,n)}, .data = { .${_} = { ${g} } } }`:`(${s}){ .tag = ${Bt(o,_,n)} }`;if(l&&e.$?.type){let d=st(e.$.type,l,n);return n.emitter.emitLine(`${t}${d} = ${h};`),Ln(l,t,n),l}else return h}}}}else if(ke(i)){let o=e.args[0];if(o&&F(o)&&E(o,":")){let l=M(e.func,t,n),u=M(o.args[0],t,n),c=M(o.args[1],t,n),_=`Slice_${te(P(i.childType,n))}`;return n.sliceStructTypes.has(_)||n.sliceStructTypes.set(_,{childType:P(i.childType,n)}),`(${_}){ .data = &${l}.data[${u}], .length = (${c}) - (${u}) }`}else if(o&&z(o)&&o.token.value===":"){let l=M(e.func,t,n),u=i,c=u.childType,_=`Slice_${te(P(c,n))}`;return n.sliceStructTypes.has(_)||n.sliceStructTypes.set(_,{childType:P(c,n)}),ze(u.length)?`(${_}){ .data = &${l}.data[0], .length = ${u.length.value} }`:"/* Error: Cannot slice array with non-compile-time length */"}let a=M(e.func,t,n),s=M(o,t,n);return`${a}.data[${s}]`}else if(Qe(i)){let o=e.args[0];if(o&&F(o)&&E(o,":")){let l=M(e.func,t,n),u=M(o.args[0],t,n),c=M(o.args[1],t,n),_=`Slice_${te(P(i.childType,n))}`;return n.sliceStructTypes.has(_)||n.sliceStructTypes.set(_,{childType:P(i.childType,n)}),`(${_}){ .data = &${l}.data[${u}], .length = (${c}) - (${u}) }`}else if(o&&z(o)&&o.token.value===":"){let l=M(e.func,t,n),u=`Slice_${te(P(i.childType,n))}`;return n.sliceStructTypes.has(u)||n.sliceStructTypes.set(u,{childType:P(i.childType,n)}),`(${u}){ .data = ${l}.data, .length = ${l}.length }`}let a=M(e.func,t,n),s=M(o,t,n);return`${a}.data[${s}]`}else if(i&&Ie(i)&&Qe(i.childType)){let o=M(e.func,t,n),a=M(e.args[0],t,n);return`${o}.data[${a}]`}}function W_(e,t,n,r){let i=t.emitter;if(i.emitLine(`${e}if (__yo_effect_escaped) {`),t.inAsyncStateMachine||(dn(e+" ",t,r,!1,!0,!1),tr(e+" ",t,r)),t.inAsyncStateMachine)n&&i.emitLine(`${e} __yo_effect_escaped = 0;`),Mn({emitter:i,indent:e+" ",resultCode:void 0,debugLabel:void 0});else if(n){i.emitLine(`${e} __yo_effect_escaped = 0;`);let o=t.currentFunctionType?.return.type;if(o&&!pe(o)){let a=P(o,t);a!=="void"?(i.emitLine(`${e} ${a} _esc_result;`),i.emitLine(`${e} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${a}));`),i.emitLine(`${e} return _esc_result;`)):i.emitLine(`${e} return;`)}else i.emitLine(`${e} return;`)}else{let o=t.currentFunctionType?.return.type;if(o&&!pe(o)){let a=P(o,t);a!=="void"?i.emitLine(`${e} return (${a}){0};`):i.emitLine(`${e} return;`)}else i.emitLine(`${e} return;`)}i.emitLine(`${e}}`)}function q_(e,t,n,r,i,o,a,s){let l=n.join(", "),u=t.return.type,c=a.emitter,_;if(s?.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0){let p=i.$?.type?P(i.$.type,a):P(u,a),f=[],g=s.fieldFunctionType.parameters.filter(d=>!d.isCompileTimeOnly);for(let d=0;d<g.length;d++){let v=g[d].type,T=x(v)&&r?.[d]?.$?.type?r[d].$.type:v,$=G(T)?hr(T,"(*)",a):P(T,a);f.push($)}let h=f.join(", ");_=`((${p} (*)(${h}))${e})`}else _=e;if(pe(u)){if(c.emitLine(`${o}${_}(${l});`),i.$?.deferredDropExpressions&&bt(i,o,a),c.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,i,!1,!0,!1),tr(o+" ",a,i)),a.inAsyncStateMachine)Mn({emitter:c,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let p=a.currentFunctionType?.return.type;if(p&&!pe(p)){let f=P(p,a);f!=="void"?c.emitLine(`${o} return (${f}){0};`):c.emitLine(`${o} return;`)}else c.emitLine(`${o} return;`)}return c.emitLine(`${o}}`),""}else{let p=i.$?.variableName;if(p){let f=s?.fieldFunctionType.forallParameters?.length&&i.$?.type?i.$.type:u,m=P(f,a);if(m==="void"||pe(f)){if(c.emitLine(`${o}${_}(${l});`),i.$?.deferredDropExpressions&&bt(i,o,a),c.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,i,!1,!0,!1),tr(o+" ",a,i)),a.inAsyncStateMachine)Mn({emitter:c,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!pe(g)){let h=P(g,a);h!=="void"?c.emitLine(`${o} return (${h}){0};`):c.emitLine(`${o} return;`)}else c.emitLine(`${o} return;`)}return c.emitLine(`${o}}`),""}if(c.emitLine(`${o}${m} ${p} = ${_}(${l});`),i.$?.deferredDropExpressions&&bt(i,o,a),c.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,i,!1,!0,!1),tr(o+" ",a,i)),a.inAsyncStateMachine)Mn({emitter:c,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!pe(g)){let h=P(g,a);h!=="void"?c.emitLine(`${o} return (${h}){0};`):c.emitLine(`${o} return;`)}else c.emitLine(`${o} return;`)}return c.emitLine(`${o}}`),p}else return`${_}(${l})`}}function $l(e,t,n,r){let i=[],o=t.body?.$?.effectAnalysis,a=!1;for(let s of e){let l=`${s.implicitLabel}.${s.fieldLabel}`,u=!1;if(r.currentEvidenceParams){let c=r.currentEvidenceParams.get(l);c&&(i.push(c.cParamName),u=!0)}if(!u){if(o){if(o.effectHandlerInfos)for(let c of o.effectHandlerInfos){if(c.effectParameterName!==s.fieldLabel&&c.effectParameterName!==s.implicitLabel)continue;let _=c.handlerValue;if(_&&ne(_)){if(_.specializedFunctionCaches?.length){let f=_.specializedFunctionCaches[0].specializedFunction,m=r.functions[f.funcId]?.cName;if(m){i.push(`(void*)${m}`),u=!0,a=!0;break}}let p=r.functions[_.funcId]?.cName;if(p){i.push(p),u=!0,a=!0;break}}}if(!u&&o.handlerValue&&e.length===1){let c=o.handlerValue;if(c&&ne(c)){if(c.specializedFunctionCaches?.length){let _=c.specializedFunctionCaches[0].specializedFunction,p=r.functions[_.funcId]?.cName;p&&(i.push(`(void*)${p}`),u=!0,a=!0)}if(!u){let _=r.functions[c.funcId]?.cName;_&&(i.push(_),u=!0,a=!0)}}}}if(!u){let c=n.func.$?.env??n.$?.env;if(c){let _=X(c,s.implicitLabel),p=fn(c,d=>d.isImplicit===!0&&G(d.type)&&G(s.fieldFunctionType)&&d.type===s.fieldFunctionType),f=_[_.length-1],m=p[p.length-1],h=(m&&m!==f?m:f??m)?.value?.[0];if(h&&We(h)){let d=h,v=!0;for(let T=0;T<s.fieldPath.length-1;T++){let $=s.fieldPath[T],C=d.type.fields.findIndex(L=>L.label===$);if(C>=0&&d.fields[C]&&We(d.fields[C]))d=d.fields[C];else{v=!1;break}}if(v){let T=s.fieldPath[s.fieldPath.length-1],$=d.type.fields.findIndex(C=>C.label===T);if($>=0){let C=d.fields[$];if(C&&ne(C)){if(C.specializedFunctionCaches?.length>0){let L=C.specializedFunctionCaches[0].specializedFunction,b=r.functions[L.funcId]?.cName;b&&(i.push(`(void*)${b}`),u=!0)}if(!u){let L=r.functions[C.funcId]?.cName;L&&(i.push(L),u=!0)}}}}}else if(h&&ne(h)){if(h.specializedFunctionCaches?.length){let d=h.specializedFunctionCaches[0].specializedFunction,v=r.functions[d.funcId]?.cName;v&&(i.push(`(void*)${v}`),u=!0)}if(!u){let d=r.functions[h.funcId]?.cName;d&&(i.push(d),u=!0)}}u&&(a=!0)}}if(!u&&r.stateMachineVariables){let c=s.fieldPath[s.fieldPath.length-1];for(let[,_]of r.stateMachineVariables)if(_.name===c&&_.kind==="outer"){i.push(`sm->__capture.${c}`),u=!0;break}}if(!u)break}}return{args:i,isHandlerInstallation:a}}function Cl(e,t,n,r,i,o,a,s=!1){let l=a.emitter,u=n.return.type;if(l.emitLine(`${o}__yo_effect_escaped = 0;`),pe(u)){if(l.emitLine(`${o}${e}(${t});`),r.$?.deferredDropExpressions&&bt(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,r,!1,!0,!1),tr(o+" ",a,r)),a.inAsyncStateMachine)Mn({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let c=a.currentFunctionType?.return.type;if(s&&l.emitLine(`${o} __yo_effect_escaped = 0;`),c&&!pe(c))if(s){let _=P(c,a);_!=="void"?(l.emitLine(`${o} ${_} _esc_result;`),l.emitLine(`${o} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${_}));`),l.emitLine(`${o} return _esc_result;`)):l.emitLine(`${o} return;`)}else{let _=P(c,a);_!=="void"?l.emitLine(`${o} return (${_}){0};`):l.emitLine(`${o} return;`)}else l.emitLine(`${o} return;`)}return l.emitLine(`${o}}`),""}else{let c=r.$?.variableName;if(c){let _=P(u,a);if(l.emitLine(`${o}${_} ${c} = ${e}(${t});`),Ln(c,o,a),r.$?.deferredDropExpressions&&bt(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(dn(o+" ",a,r,!1,!0,!1),tr(o+" ",a,r)),a.inAsyncStateMachine)Mn({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let p=a.currentFunctionType?.return.type;if(s&&p&&!pe(p)){let f=P(p,a);l.emitLine(`${o} ${f} _esc_result;`),l.emitLine(`${o} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${f}));`),l.emitLine(`${o} __yo_effect_escaped = 0;`),l.emitLine(`${o} return _esc_result;`)}else if(p&&!pe(p)){let f=P(p,a);f!=="void"?l.emitLine(`${o} return (${f}){0};`):l.emitLine(`${o} return;`)}else s&&l.emitLine(`${o} __yo_effect_escaped = 0;`),l.emitLine(`${o} return;`)}return l.emitLine(`${o}}`),c}else return`${e}(${t})`}}function H_(e,t,n){let r=n.emitter,i=e.$?.type;if(!i)return"// Error: panic() missing type information";if(e.args.length===0)r.emitLine(`${t}abort();`);else if(e.args.length===1){let a=e.args[0];if(a.$?.value&&Ve(a.$.value)){let s=a.$.value.value;r.emitLine(`${t}fprintf(stderr, "%s\\n", ${JSON.stringify(s)});`),r.emitLine(`${t}abort();`)}else{let s=M(a,t,n);r.emitLine(`${t}fprintf(stderr, "%s\\n", ${s});`),r.emitLine(`${t}abort();`)}}else return`// Error: panic accepts 0 or 1 arguments, got ${e.args.length}`;return`(*((${P(i,n)}*)NULL))`}var fg={reg:{x86_64:"r",aarch64:"r",x86:"r",arm:"r"},reg_byte:{x86_64:"q",x86:"q"},reg_abcd:{x86_64:"Q",x86:"Q"},xmm_reg:{x86_64:"x",aarch64:"w"},ymm_reg:{x86_64:"x"},imm:{x86_64:"i",aarch64:"i",x86:"i",arm:"i"},mem:{x86_64:"m",aarch64:"m",x86:"m",arm:"m"}},dg={rax:"a",eax:"a",ax:"a",al:"a",rbx:"b",ebx:"b",bx:"b",bl:"b",rcx:"c",ecx:"c",cx:"c",cl:"c",rdx:"d",edx:"d",dx:"d",dl:"d",rsi:"S",esi:"S",si:"S",rdi:"D",edi:"D",di:"D"},mg={e:"k",x:"w",l:"b",h:"h",w:"w"};function yg(e,t){if(!e)return"r";if(e.startsWith("raw:"))return e.slice(4);let n=dg[e];if(n)return n;let r=fg[e];return r?r[t]??r.x86_64??"r":e}function gg(e,t){let n="",r=0;for(;r<e.length;)if(e[r]==="{"){if(r+1<e.length&&e[r+1]==="{"){n+="{",r+=2;continue}let i=e.indexOf("}",r+1);if(i===-1){n+=e[r],r++;continue}let o=e.slice(r+1,i),a=o.indexOf(":"),s,l;a>=0?(s=o.slice(0,a),l=o.slice(a+1)):s=o;let u=l?mg[l]??l:void 0,c=parseInt(s,10);isNaN(c)?u?n+=`%${u}[${s}]`:n+=`%[${s}]`:u?n+=`%${u}${c}`:n+=`%${c}`,r=i+1}else e[r]==="}"&&r+1<e.length&&e[r+1]==="}"?(n+="}",r+=2):(n+=e[r],r++);return n}function hg(e,t,n,r){let i=e.args,o=n.targetInfo.arch;if(r==="const_val"){let d,v=0;i.length===2&&i[0].$?.value&&Ve(i[0].$.value)&&(d=i[0].$.value.value,v=1);let T=M(i[v],t,n);return{kind:"const_val",name:d,constraint:"",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}if(r==="sym"){let d,v=0;i.length===2&&i[0].$?.value&&Ve(i[0].$.value)&&(d=i[0].$.value.value,v=1);let T=M(i[v],t,n);return{kind:"sym",name:d,constraint:"i",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}let a,s=0;if(i.length>=2){let d=i[0];d.$?.value&&Ve(d.$.value)&&!(d.tag==="Atom"&&j_(d.token.value))&&(a=d.$.value.value,s=1)}let l=s<i.length-1,u,c;l?(u=vg(i[s],t,n),c=s+1):(a!==void 0&&(u=a),c=s);let _=yg(u,o),p=i[c];if(p.tag==="Atom"&&p.token.value==="_")return{kind:r,name:a,constraint:_,cExpr:"",cType:"int32_t",isDiscarded:!0,isVariableTarget:!1};if(p.$?.value&&O(p.$.value)){let d=p.$.value.value,v=P(d,n);return{kind:r,name:a,constraint:_,cExpr:"",cType:v,isDiscarded:!1,isVariableTarget:!1}}let f=M(p,t,n),m=P(p.$?.type,n),h=(r==="out"||r==="lateout")&&p.tag==="Atom";return{kind:r,name:a,constraint:_,cExpr:f,cType:m,isDiscarded:!1,isVariableTarget:h}}function j_(e){return["reg","reg_byte","reg_abcd","xmm_reg","ymm_reg","imm","mem"].includes(e)}function vg(e,t,n){if(e.tag==="Atom"&&j_(e.token.value))return e.token.value;if(e.$?.value&&Ve(e.$.value))return e.$.value.value;if(E(e,"raw",1)){let r=e;if(r.args[0].$?.value&&Ve(r.args[0].$.value))return`raw:${r.args[0].$.value.value}`}return"r"}function Tg(e,t){let n=[];if((e.func.tag==="Atom"?e.func.token.value:"clobber")==="clobber_abi"){let i=t.targetInfo.arch;if(i==="x86_64")n.push("rax","rcx","rdx","rsi","rdi","r8","r9","r10","r11","xmm0","xmm1","xmm2","xmm3","xmm4","xmm5","xmm6","xmm7","xmm8","xmm9","xmm10","xmm11","xmm12","xmm13","xmm14","xmm15","cc","memory");else if(i==="aarch64"){for(let o=0;o<=18;o++)n.push(`x${o}`);n.push("x30");for(let o=0;o<=31;o++)n.push(`v${o}`);n.push("cc","memory")}return n}for(let i of e.args)i.$?.value&&Ve(i.$.value)?n.push(i.$.value.value):i.tag==="Atom"&&n.push(i.token.value);return n}function Eg(e){let t={isVolatile:!0,intelSyntax:!1,noreturn:!1,pure:!1};for(let n of e.args)if(n.tag==="Atom")switch(n.token.value){case"pure":t.pure=!0,t.isVolatile=!1;break;case"intel_syntax":t.intelSyntax=!0;break;case"noreturn":t.noreturn=!0;break;case"volatile":t.isVolatile=!0;break}return t}var bl=0;function K_(e,t,n){let r=n.emitter,i=e.$?.type;if(!i)return"/* Error: asm() missing type information */";if(yi(n.targetInfo))return r.emitLine(`${t}/* Error: inline assembly is not supported on WebAssembly */`),r.emitLine(`${t}abort();`),`(*((${P(i,n)}*)NULL))`;let o=[],a=0;for(;a<e.args.length;){let D=e.args[a];if(F(D))break;if(D.$?.value&&Ve(D.$.value))o.push(D.$.value.value),a++;else break}let s=o.join(`
10278
+ `),l=[],u=[],c={isVolatile:!0,intelSyntax:!1,noreturn:!1,pure:!1};for(;a<e.args.length;){let D=e.args[a];if(!F(D)){a++;continue}let V=D.func.tag==="Atom"?D.func.token.value:void 0;if(!V){a++;continue}["in","out","inout","lateout","inlateout","const_val","sym"].includes(V)?l.push(hg(D,t,n,V)):V==="clobber"||V==="clobber_abi"?u.push(...Tg(D,n)):V==="asm_options"&&(c=Eg(D)),a++}let _=new Map;for(let D=0;D<l.length;D++)l[D].name&&_.set(l[D].name,D);let p=s;for(let D=0;D<l.length;D++){let V=l[D];V.kind==="const_val"&&(V.name&&(p=p.replace(new RegExp(`\\{${V.name}(?::[^}]*)?\\}`,"g"),V.cExpr)),p=p.replace(new RegExp(`\\{${D}(?::[^}]*)?\\}`,"g"),V.cExpr))}let f=gg(p,_),m=[],g=[],h=[];for(let D=0;D<l.length;D++){let V=l[D];if(V.isDiscarded){let U=`__asm_discard_${bl++}`;h.push({varName:U,cType:V.cType,operandIdx:D}),r.emitLine(`${t}${V.cType} ${U};`)}else if(V.kind==="out"||V.kind==="lateout"){if(!V.isVariableTarget){if(V.cType){let U=`__asm_out_${bl++}`;m.push({varName:U,cType:V.cType,operandIdx:D}),r.emitLine(`${t}${V.cType} ${U};`)}}}else if(V.kind==="inout"||V.kind==="inlateout"){let U=`__asm_inout_${bl++}`;g.push({varName:U,cType:V.cType,initExpr:V.cExpr,operandIdx:D}),r.emitLine(`${t}${V.cType} ${U} = ${V.cExpr};`)}}let d=c.isVolatile?" __volatile__":"",v=f;c.intelSyntax&&(n.needsIntelAsmSyntax=!0);let T=JSON.stringify(v),$=[];for(let D=0;D<l.length;D++){let V=l[D];if(V.kind==="in"||V.kind==="const_val"||V.kind==="sym")continue;let U;V.kind==="out"||V.kind==="lateout"?U=V.kind==="lateout"?"=&":"=":U=V.kind==="inlateout"?"+&":"+";let re=`${U}${V.constraint}`,j=V.name?`[${V.name}] `:"",W;V.isDiscarded?W=h.find(_e=>_e.operandIdx===D).varName:V.isVariableTarget?W=V.cExpr:V.kind==="out"||V.kind==="lateout"?W=m.find(_e=>_e.operandIdx===D).varName:W=g.find(_e=>_e.operandIdx===D).varName,$.push(`${j}"${re}" (${W})`)}let C=[];for(let D=0;D<l.length;D++){let V=l[D];if(V.kind!=="in"&&V.kind!=="sym")continue;let U=V.constraint,re=V.name?`[${V.name}] `:"";C.push(`${re}"${U}" (${V.cExpr})`)}let L=u.map(D=>`"${D}"`),b=$.join(", "),R=C.join(", "),N=L.join(", ");if(r.emitLine(`${t}__asm__${d} (`),r.emitLine(`${t} ${T}`),r.emitLine(`${t} : ${b}`),r.emitLine(`${t} : ${R}`),r.emitLine(`${t} : ${N}`),r.emitLine(`${t});`),c.noreturn)return r.emitLine(`${t}__builtin_unreachable();`),`(*((${P(i,n)}*)NULL))`;if(pe(i))return"";let B=[];for(let D=0;D<l.length;D++){let V=l[D];if(!(V.isDiscarded||V.isVariableTarget)&&!(V.kind==="in"||V.kind==="const_val"||V.kind==="sym"))if(V.kind==="out"||V.kind==="lateout"){let U=m.find(re=>re.operandIdx===D);U&&B.push(U.varName)}else{let U=g.find(re=>re.operandIdx===D);U&&B.push(U.varName)}}if(B.length===1)return B[0];if(B.length>1){let D=P(i,n),V=B.map((U,re)=>`._${re} = ${U}`).join(", ");return`((${D}){ ${V} })`}return""}function X_(e,t,n){if(yi(n.targetInfo))return"/* global_asm skipped: not supported on this target */";let r=e.args[0];if(r.$?.value&&Ve(r.$.value)){let i=r.$.value.value;n.emitter.emitDeclarationLine(`__asm__(${JSON.stringify(i)});`)}return""}function Q_(e,t,n){if(e.args.length!==2)return"/* ERROR: field access requires exactly 2 arguments */";let r=e.args[0],i=e.args[1];if(!r||!i)return"/* ERROR: invalid field access arguments */";let o=M(r,t,n),a=r.$?.type,s=r.$?.value;if(z(i)){let l=i.token.value,u=n;if(u.currentEvidenceParams&&z(r)){let _=`${r.token.value}.${l}`,p=u.currentEvidenceParams.get(_);if(p)return p.cParamName}if(e.$?.value&&ne(e.$.value)){let c=e.$.value;return n.functions[c.funcId]?.cName||c.funcId}if(!e.$?.value&&(k.___dispose.includes(l)||k.___drop.includes(l)||k.___dup.includes(l))&&a){let c=null;if((ce(a)||ge(a))&&(c=a.trait),c){let _=c.fields.find(p=>p.label===l&&p.assignedValue&&ne(p.assignedValue));if(_&&ne(_.assignedValue)){let p=_.assignedValue;return n.functions[p.funcId]?.cName||p.funcId}else return`/* ERROR: Rc method ${l} not found in type module */`}else return`/* ERROR: No module found for Rc method ${l} */`}if(Te(a)||We(s)){let c=e.$?.value;if(c){if(de(c)){if(c.variableName)return Ee(c.variableName,e.$?.env);if((u.inAsyncStateMachine||u.inEffectStateMachine)&&u.stateMachineVariables){for(let[,_]of u.stateMachineVariables)if(_.name===l&&_.kind==="outer")return`sm->__capture.${l}`}}else if(!We(c))return Qt(c,n,e)}return Ee(l,e.$?.env)}if(Er(a)&&a.fields.length===1){let c=a.fields[0];if(c&&c.label===l)return o}if(ge(a)){let c=a;if(Yt(c))return o;for(let p of c.variants)if(p.fields){for(let f of p.fields)if(f.label===l){let m=p.name;return`${o}.data.${m}.${te(l)}`}}return`/* ERROR: field ${l} not found in enum ${c.typeName} */`}else if(O(s)&&ge(s.value)){let c=s.value,_=c.variants.find(f=>f.name===l),p=n.types[c.id]?.cName;if(_&&!_.fields&&p){let f=Bt(c,_.name,n);return`(${p}){ .tag = ${f}, .data = { } }`}}else{if(Ct(a)&&l==="*")return`${o}->value`;if(Ie(a)){if(l==="*")return`(*${o})`;if(Qe(a.childType))return`${o}->${te(l)}`;{let c=0,_=a;for(;Ie(_);)c++,_=_.childType;if(c>0&&ce(_)&&_.isReferenceSemantics&&c++,Er(_)&&_.fields.length===1){let p=_.fields[0];if(p&&p.label===l)return c===1?`(*${o})`:`${"*".repeat(c)}(${o})`}return c>0?c===1?`${o}->${te(l)}`:`${`(${"*".repeat(c-1)}${o})`}->${te(l)}`:`${o}.${te(l)}`}}else if(we(a)){if(l.match(/^\d+$/))return`${o}._${l}`;{let c=a.fields.findIndex(_=>_.label===l);return`${o}._${c}`}}else return be(a)?`${o}.vtable->${te(l)}`:pt(a)?`${o}->${te(l)}`:`${o}.${te(l)}`}}return"/* ERROR: field name must be an identifier */"}function Z_(e,t,n){if(!e.$?.type)return`// Error: No type information for pointer/reference expression ${w(e)}
10279
+ `;let i=e.args[0];if(F(i)){let l=i.func.$?.type;if(l&&ke(l)){let u=i.args[0];if(u&&F(u)&&E(u,":")){let c=M(i.func,t,n),_=M(u.args[0],t,n),p=M(u.args[1],t,n),f=`Slice_${te(P(l.childType,n))}`;return n.sliceStructTypes.has(f)||n.sliceStructTypes.set(f,{childType:P(l.childType,n)}),`(${f}){ .data = &${c}.data[${_}], .length = ${p} - ${_} }`}else if(u&&z(u)&&u.token.value===":"){let c=M(i.func,t,n),_=l,p=_.childType,f=`Slice_${te(P(p,n))}`;return n.sliceStructTypes.has(f)||n.sliceStructTypes.set(f,{childType:P(p,n)}),ze(_.length)?`(${f}){ .data = &${c}.data[0], .length = ${_.length.value} }`:"/* Error: Cannot slice array with non-compile-time length */"}}else if(l&&(Qe(l)||Ie(l)&&Qe(l.childType))){let u=Qe(l)?l:l.childType,c=i.args[0];if(c&&F(c)&&E(c,":")){let _=M(i.func,t,n),p=M(c.args[0],t,n),f=M(c.args[1],t,n),m=`Slice_${te(P(u.childType,n))}`;return n.sliceStructTypes.has(m)||n.sliceStructTypes.set(m,{childType:P(u.childType,n)}),`(${m}){ .data = &${_}.data[${p}], .length = ${f} - ${p} }`}else if(c&&z(c)&&c.token.value===":"){let _=M(i.func,t,n),p=`Slice_${te(P(u.childType,n))}`;return n.sliceStructTypes.has(p)||n.sliceStructTypes.set(p,{childType:P(u.childType,n)}),`(${p}){ .data = ${_}.data, .length = ${_}.length }`}}}let o=i.$?.value,a=i.$?.type;if(o!==void 0&&a){if(ze(o)||Re(o)){let l=M(i,t,n);return`(&(${P(a,n)}){${l}})`}if(Ve(o)&&i.$?.convertedRuntimeType)return`(&${M(i,t,n)})`}return`(&${M(i,t,n)})`}function J_(e,t,n){let r=e.args[0];return r?`__yo_decr_rc(${M(r,t,n)})`:"// Error: __yo_decr_rc requires exactly 1 argument"}function ep(e,t,n){let r=e.args[0];return r?`__yo_incr_rc(${M(r,t,n)})`:"// Error: __yo_incr_rc requires exactly 1 argument"}function tp(e,t,n){let r=e.args[0];return r?M(r,t,n):"// Error: __yo_rc_own requires exactly 1 argument"}function np(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_drop_array_element requires exactly 2 arguments";let o=M(r,t,n),a=M(i,t,n),s=r.$?.type;if(!s||!ke(s))return"// Error: __yo_drop_array_element requires an array type";let l=s.childType,u=x(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let _=u.length;if(!ze(_))return"// Error: array element has non-constant length";let p=`i_${Math.floor(Math.random()*1e6)}`,f=n.emitter;f.emitLine(`for (size_t ${p} = 0; ${p} < ${_.value}; ${p}++) {`);let m=`(${o}).data[${a}].data[${p}]`;f.emitLine(" { // drop nested array element");let g=Ir(m,u.childType,n);return g&&f.emitLine(` ${g};`),f.emitLine(" }"),f.emitLine("}"),""}let c=gr(u,n);return c?`${c}((${o}).data[${a}])`:"// No drop function for array element type"}function rp(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_dup_array_element requires exactly 2 arguments";let o=M(r,t,n),a=M(i,t,n),s=r.$?.type;if(!s||!ke(s))return"// Error: __yo_dup_array_element requires an array type";let l=s.childType,u=x(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let _=u.length;if(!ze(_))return"// Error: array element has non-constant length";let p=`temp_array_${Math.floor(Math.random()*1e6)}`,f=`i_${Math.floor(Math.random()*1e6)}`,m=P(u,n),g=n.emitter;g.emitLine(`${m} ${p} = (${o}).data[${a}];`),g.emitLine(`for (size_t ${f} = 0; ${f} < ${_.value}; ${f}++) {`);let h=Xi(`${p}.data[${f}]`,u.childType,n);return g.emitLine(` ${p}.data[${f}] = ${h};`),g.emitLine("}"),p}let c=On(u,n);return c?`${c}((${o}).data[${a}])`:"// No dup function for array element type"}function ip(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_drop_tuple_element requires exactly 2 arguments";let o=M(r,t,n);M(i,t,n);let a=r.$?.type;if(!a||!we(a))return"// Error: __yo_drop_tuple_element requires a tuple type";let s=i.$?.value;if(!ze(s))return"// Error: __yo_drop_tuple_element requires a constant index";let l=Number(s.value);if(l<0||l>=a.fields.length)return"// Error: __yo_drop_tuple_element index out of bounds";let u=a.fields[l].type,c=x(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(we(c)){let p=`(${o})._${l}`;return Ir(p,c,n)}let _=gr(c,n);return _?`${_}((${o})._${l})`:"// No drop function for tuple element type"}function op(e,t,n){let r=e.args[0],i=e.args[1];if(!r||!i)return"// Error: __yo_dup_tuple_element requires exactly 2 arguments";let o=M(r,t,n);M(i,t,n);let a=r.$?.type;if(!a||!we(a))return"// Error: __yo_dup_tuple_element requires a tuple type";let s=i.$?.value;if(!ze(s))return"// Error: __yo_dup_tuple_element requires a constant index";let l=Number(s.value);if(l<0||l>=a.fields.length)return"// Error: __yo_dup_tuple_element index out of bounds";let u=a.fields[l].type,c=x(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(we(c)){let p=`(${o})._${l}`;return Xi(p,c,n)}let _=On(c,n);return _?`${_}((${o})._${l})`:"// No dup function for tuple element type"}function ap(e,t,n){let r=e.args[0];if(!r)return"// Error: ___dup requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type??e.$?.type;return o?Xi(i,o,n):i}function sp(e,t,n){let r=e.args[0];if(!r)return"// Error: ___drop requires exactly 1 argument";let i=M(r,t,n),o=r.$?.type??e.$?.type;return o?Ir(i,o,n):""}function lp(e,t,n){let r=e.args[0];return r?`__yo_decr_rc((void*)(${M(r,t,n)}).data)`:"// Error: __yo_dyn_drop requires exactly 1 argument"}function up(e,t,n){let r=e.args[0];return r?`__yo_incr_rc((void*)(${M(r,t,n)}).data)`:"// Error: __yo_dyn_dup requires exactly 1 argument"}function cp(e,t,n){let r=e.args[0];return r?`__yo_incr_rc_atomic(${M(r,t,n)})`:"// Error: __yo_incr_rc_atomic requires exactly 1 argument"}function _p(e,t,n){let r=e.args[0];return r?`__yo_decr_rc_atomic(${M(r,t,n)})`:"// Error: __yo_decr_rc_atomic requires exactly 1 argument"}function pp(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_sometype_drop requires exactly 1 argument";let i=r.$?.type;if(i&&x(i)&&Ce(i)){let o=M(r,t,n);return`if (${o} != NULL) { __yo_decr_rc((void*)${o}); }`}if(i&&x(i)&&i.resolvedConcreteType){let a=i.resolvedConcreteType.trait?.fields.find(s=>s.label===k.___drop[0]);if(a&&a.assignedValue&&ne(a.assignedValue)){let s=n.functions[a.assignedValue.funcId]?.cName;if(s){let l=M(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_drop: no-op */"}function fp(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_sometype_dup requires exactly 1 argument";let i=r.$?.type;if(i&&x(i)&&Ce(i))return`__yo_incr_rc((void*)${M(r,t,n)})`;if(i&&x(i)&&i.resolvedConcreteType){let a=i.resolvedConcreteType.trait?.fields.find(s=>s.label===k.___dup[0]);if(a&&a.assignedValue&&ne(a.assignedValue)){let s=n.functions[a.assignedValue.funcId]?.cName;if(s){let l=M(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_dup: no-op */"}function dp(e,t,n){if(e.args.length!==1)return"// Error: rc requires exactly 1 argument";let r=e.args[0],i=r.$?.type;if(!i)return"// Error: rc argument missing type information";let o=M(r,t,n);return sn(i)?`((__yo_ref_header_t*)(${o}))->ref_count`:"1"}function mp(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(r){let i=n,o=r.map(a=>{let s=M(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){rt(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return Ee(l.$.variableName,l.$.env)}return s}).join(", ");return`${n.currentFunctionName}(${o})`}else return`// Error: No arguments for recur call ${w(e)}
10280
+ `}function yp(e,t,n){let r=e.args[0];return`sizeof(${M(r,t,n)})`}function gp(e,t,n){let r=e.$?.runtimeArgExprsInOrder,i=n.types[e.$?.type?.id??""]?.cName,o=e.$?.variableName;if(r&&i){let a=n,s=r.map((l,u)=>{let _=M(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){rt(l,t,a);let p=l.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(_=Ee(p.$.variableName,p.$.env))}return`._${u} = ${_}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${u} = ${l};`),o}else return`(${i}){ ${s} }`}else{if(e.args.length===0)return"";{let a=r??e.args;if(!i)return`/* Error: tuple type not found - typeId: ${e.$?.type?.id??"none"} */`;let s=a.map((l,u)=>{let c=M(l,t,n);return`._${u} = ${c}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=st(e.$.type,o,n);return n.emitter.emitLine(`${t}${u} = ${l};`),o}else return`(${i}){ ${s} }`}}}function hp(e,t,n){let i=e.args[0].$?.value;if(!i||!O(i))throw new Error("typeid codegen: expected TypeValue argument");let o=i.value,a=o.id,s=n.types[a]?.cName||P(o,n),l=`__yo_typeid_${te(s)}`;return n.typeIdStatics||(n.typeIdStatics=new Map),n.typeIdStatics.has(a)||(n.typeIdStatics.set(a,l),n.emitter.emitDeclarationLine(`static const char ${l} = 0;`)),n.cIncludes.add("<stdint.h>"),`(uintptr_t)&${l}`}function $g(e,t){if(F(e)&&E(e,I.begin)){let n=[];for(let r of e.args)if(F(r)&&E(r,"=",2)){let i=r.args[0],o=r.args[1],a=M(i,"",t),s=M(o,"",t);n.push(`${a} = ${s}`)}return n.join(", ")}else if(F(e)&&E(e,"=",2)){let n=e.args[0],r=e.args[1],i=M(n,"",t),o=M(r,"",t);return`${i} = ${o}`}return M(e,"",t)}function kl(e,t,n){if(F(e)&&E(e,I.begin)){let r=n,i=r.pendingDeferredDrops,o=e.$?.deferredDropExpressions??[],a=new Map;for(let c of o){let _=In(c);_&&a.set(_,c)}r.pendingDeferredDrops=[...i??[]];let s=r.consumedVarPendingDrops,l=e.$?.consumedVariableDropExpressions??[];r.consumedVarPendingDrops=[...l,...s??[]];let u=new Set;for(let c of e.args){let _=M(c,t,n);if(_&&n.emitter.emitLine(`${t}${_};`),c.$?.env&&a.size>u.size)for(let p of c.$.env.frames)for(let f of p.variables)a.has(f.name)&&!u.has(f.name)&&(u.add(f.name),r.pendingDeferredDrops.unshift(a.get(f.name)))}if(e.$?.deferredDropExpressions)for(let c of e.$.deferredDropExpressions){let _=M(c,t,n);_&&n.emitter.emitLine(`${t}${_};`)}r.pendingDeferredDrops=i,r.consumedVarPendingDrops=s}else{let r=M(e,t,n);r&&n.emitter.emitLine(`${t}${r};`)}}function vp(e,t,n){if(e.$?.comptimeUnrolledBodies){for(let i of e.$.comptimeUnrolledBodies)kl(i,t,n);return""}let r=e.args;if(r.length===2){let i=r[0],o=r[1],a=n.currentLoopLabel,s=`loop_${Math.random().toString(36).substr(2,9)}`;n.currentLoopLabel=s;let l=n,u=l.loopBodyDropsBaselineCount;l.loopBodyDropsBaselineCount=l.pendingDeferredDrops?.length??0,n.emitter.emitLine(`${t}while (true) {`);let c=M(i,t+" ",n);return n.emitter.emitLine(`${t} if (!(${c})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),kl(o,t+" ",n),n.emitter.emitLine(`${t}}`),n.emitter.emitLine(`${t}${s}:;`),l.loopBodyDropsBaselineCount=u,n.currentLoopLabel=a,""}else if(r.length===3){let i=r[0],o=r[1],a=r[2],s=n.currentLoopLabel,l=n.currentContinueLabel,u=`loop_${Math.random().toString(36).substr(2,9)}`,c=`continue_${Math.random().toString(36).substr(2,9)}`;n.currentLoopLabel=u,n.currentContinueLabel=c;let _=n,p=_.loopBodyDropsBaselineCount;_.loopBodyDropsBaselineCount=_.pendingDeferredDrops?.length??0,n.emitter.emitLine(`${t}while (true) {`);let f=M(i,t+" ",n);n.emitter.emitLine(`${t} if (!(${f})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),kl(a,t+" ",n),n.emitter.emitLine(`${t}${c}:;`);let m=$g(o,n);return n.emitter.emitLine(`${t} ${m};`),n.emitter.emitLine(`${t}}`),n.emitter.emitLine(`${t}${u}:;`),_.loopBodyDropsBaselineCount=p,n.currentLoopLabel=s,n.currentContinueLabel=l,""}else return n.emitter.emitLine(`${t}/* Error: while loop expects 2 or 3 arguments, got ${r.length} */`),""}function Cg(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;x(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),ot(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function bg(e,t,n,r){let i=e.args[0];if(!i?.$?.type)return;let o=e.args.find(_=>F(_)&&E(_,I.using));if(!o)return;let a=Dt(i.$.type);if(!a?.isFuture.effects?.length)return;let s=Cg(a.isFuture.effects),l=o.args,u=r,c=u.emitter;for(let _=0;_<s.length&&_<l.length;_++){let p=s[_],f=l[_];if(G(p.type)){let m=p.label,g;if(u.currentEvidenceParams){for(let h of u.currentEvidenceParams.values())if(h.fieldLabel===m){g=h.cParamName;break}}if(!g&&u.stateMachineVariables){for(let[,h]of u.stateMachineVariables)if(h.name===m&&h.kind==="outer"){g=`sm->__capture.${m}`;break}}if(!g){let h=f.$?.value;if(h&&ne(h)){let d=r.functions[h.funcId];d&&(g=d.cName)}}g||(g=M(f,n,r)),g&&c.emitLine(`${n} ${t}->__capture.${m} = (void*)${g};`)}else if(Te(p.type)){let m=p.type;for(let g of m.fields){if(!G(g.type))continue;let h;if(u.stateMachineVariables){for(let[,d]of u.stateMachineVariables)if(d.name===g.label&&d.kind==="outer"){h=`sm->__capture.${g.label}`;break}}if(!h){let d=f.$?.value;if(d&&We(d)){let v=m.fields.indexOf(g),T=d.fields[v];if(T&&ne(T)){let $=r.functions[T.funcId];$&&(h=$.cName)}}}if(!h&&u.currentEvidenceParams){for(let d of u.currentEvidenceParams.values())if(d.fieldLabel===g.label){h=d.cParamName;break}}h||(h=kg(g.label,m,u,e)),h&&c.emitLine(`${n} ${t}->__capture.${g.label} = (void*)${h};`)}}}}function kg(e,t,n,r){let i=r.$?.env??r.func.$?.env;if(!i)return;let o=fn(i,a=>a.isImplicit===!0);for(let a=o.length-1;a>=0;a--){let s=o[a],l=s.value?.[s.value.length-1];if(l&&We(l)){let u=l.type.fields.findIndex(c=>c.label===e);if(u>=0){let c=l.fields[u];if(c&&ne(c)){let _=n.functions[c.funcId]?.cName;if(_)return _}}}}}function wg(e,t,n){let r=n,i=e.args[0],o=r.continuationVariables?.get("resume");if(o&&"directReturnVar"in o&&o.directExitLabel){if(i){let l=M(i,t,n);if(r.effectHandlerParamDrops)for(let u of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${u};`);r.emitter.emitLine(`${t}${o.directReturnVar} = ${l};`),r.emitter.emitLine(`${t}goto ${o.directExitLabel};`)}else{if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);r.emitter.emitLine(`${t}goto ${o.directExitLabel};`)}return""}if(r.inAsyncStateMachine){let l=r.emitter;if(i){let u=M(i,t,n);u&&u!=="(void)0"&&l.emitLine(`${t}(void)${u};`)}if(r.effectHandlerParamDrops)for(let u of r.effectHandlerParamDrops)l.emitLine(`${t}${u};`);return dn(t,r,e,!1,!0,!0),tr(t,r,e,!0),Mn({emitter:l,indent:t,debugLabel:r.currentFunctionName}),""}if((r.isModuleEffectMemberFunction||r.currentEvidenceParams&&r.currentEvidenceParams.size>0)&&r.emitter.emitLine(`${t}__yo_effect_escaped = 1;`),!i){if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);if(dn(t,r,e,!1,!0,!0),tr(t,r,e,!0),r.currentFunctionType){let l=r.currentFunctionType.return.type;if(!pe(l)){let u=r.overrideReturnTypeStr??P(l,n);if(u!=="void")return`return (${u}){0}`}}return"return"}let s=M(i,t,n);if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);if(dn(t,r,e,!1,!0,!0),tr(t,r,e,!0),(r.isModuleEffectMemberFunction||r.currentEvidenceParams&&r.currentEvidenceParams.size>0)&&r.currentFunctionType){let l=i.$?.type;if(l&&!pe(l)){let c=P(l,n);r.emitter.emitLine(`${t}{ ${c} _esc_val = ${s}; memcpy(__yo_effect_escape_value, &_esc_val, sizeof(${c})); }`)}let u=r.currentFunctionType.return.type;if(!pe(u)){let c=r.overrideReturnTypeStr??P(u,n);if(c!=="void")return`return (${c}){0}`}return"return"}return`return ${s}`}function Tp(e,t,n){let r;switch(e.tag){case"FnCall":r=Fg(e,t,n);break;case"Atom":r=no(e,n,t);break}return r}function Fg(e,t,n){if(e.$?.macroExpansion)return M(e.$.macroExpansion,t,n);if(F(e.func)&&E(e.func,".",2)&&e.func.args[1]&&z(e.func.args[1])){let r=e.func.args[1].token.value,i=e.func.args[0],o=i?.$?.type;if(o&&x(o)&&Ce(o)){if(r===k.___drop[0]){let a=M(i,t,n);return`if (${a} != NULL) { __yo_decr_rc((void*)${a}); }`}if(r===k.___dup[0])return`__yo_incr_rc((void*)${M(i,t,n)})`}}if(Lc(e))return Ac(e,t,n);if(E(e,k.__yo_decr_rc))return J_(e,t,n);if(E(e,k.__yo_incr_rc))return ep(e,t,n);if(E(e,k.__yo_rc_own))return tp(e,t,n);if(E(e,k.__yo_drop_array_element))return np(e,t,n);if(E(e,k.__yo_dup_array_element))return rp(e,t,n);if(E(e,k.__yo_drop_tuple_element))return ip(e,t,n);if(E(e,k.__yo_dup_tuple_element))return op(e,t,n);if(E(e,k.___dup))return ap(e,t,n);if(E(e,k.___drop))return sp(e,t,n);if(E(e,k.__yo_dyn_drop))return lp(e,t,n);if(E(e,k.__yo_dyn_dup))return up(e,t,n);if(E(e,k.__yo_incr_rc_atomic))return cp(e,t,n);if(E(e,k.__yo_decr_rc_atomic))return _p(e,t,n);if(E(e,k.__yo_iso_extract))return V_(e,t,n);if(E(e,k.__yo_iso_dispose))return x_(e,t,n);if(E(e,k.__yo_arc_dispose))return m_(e,t,n);if(Tl(e))return D_(e,t,n);if(vl(e))return y_(e,t,n);if(E(e,k.__yo_sometype_drop))return pp(e,t,n);if(E(e,k.__yo_sometype_dup))return fp(e,t,n);if(E(e,k.__yo_gc_collect))return S_(e,t,n);if(E(e,k.rc))return dp(e,t,n);if(E(e,k.panic))return H_(e,t,n);if(E(e,k.asm))return K_(e,t,n);if(E(e,k.global_asm))return X_(e,t,n);if(E(e,I.test))return"/* test declaration skipped */";if(E(e,k.__yo_thread_set_maximum_threads))return B_(e,t,n);if(E(e,I.op_and))return f_(e,t,n);if(E(e,I.op_or))return d_(e,t,n);if(Rt(e))return e.$?.awaitAnalysis?Ic(e,t,n):Dc(e,t,n);if(E(e,I.dyn))return I_(e,t,n);if(pn(e))return E_(e,t,n);if(zu(e))return $_(e,t,n);if(Fa(e)){let r=e.args[0];if(!r)return"// Error: spawn requires a Future argument";let o=n.emitter,a=M(r,t,n),s=r.$?.type,l=s?P(s,n):"void*",u=e.$?.type,c=u?P(u,n):null,_=e.$?.variableName?`__spawn_future_${e.$.variableName}`:"__spawn_future",p=e.$?.variableName?`__spawn_state_${e.$.variableName}`:"__spawn_state";return o.emitLine(`${t}// io.spawn \u2014 start cold Future, return JoinHandle`),o.emitLine(`${t}${l} ${_} = ${a};`),o.emitLine(`${t}int ${p} = ${_}->state;`),o.emitLine(`${t}if (${p} == -2) {`),o.emitLine(`${t} fprintf(stderr, "panic: attempted to spawn an aborted Future\\n");`),o.emitLine(`${t} abort();`),o.emitLine(`${t}}`),jo(r.$?.type)||(o.emitLine(`${t}if (${p} == 0 && ${_}->__yo_resume_fn) {`),bg(e,_,t,n),o.emitLine(`${t} __yo_incr_rc((void*)${_});`),o.emitLine(`${t} ${_}->__yo_resume_fn((void*)${_});`),o.emitLine(`${t}}`)),c?`(${c}){ .__future = (void*)${_} }`:`(void*)${_}`}if(Bu(e))return C_(e,t,n);if(E(e,I.return))return Jc(e,t,n);if(E(e,I.escape))return wg(e,t,n);if(E(e,k.__yo_array_fill,2))return h_(e,t,n);if(E(e,"::",2))return"";if(E(e,":",2))return w_(e,t,n);if(E(e,":=",2)){let r=N_(e,t,n);if(r!==void 0)return r}else{if(E(e,"=",2))return v_(e,t,n);if(e.$?.value&&!de(e.$?.value)&&!pe(e.$.type)&&!nt(e.$?.controlFlow)){let r=e.$.value;return Qt(r,n,e)}else{if(E(e,".",2))return Q_(e,t,n);if(E(e,I.begin))return k_(e,t,n);if(E(e,I.cond))return F_(e,t,n);if(E(e,I.match))return O_(e,t,n);if(E(e,k.__yo_address_of,1))return Z_(e,t,n);if(E(e,I.tuple))return gp(e,t,n);if(E(e,I.array)){let r=g_(e,t,n);if(r!==void 0)return r}else{if(E(e,I.recur))return mp(e,t,n);if(E(e,I.runtime,1))return M(e.args[0],t,n);if(E(e,k.sizeof,1))return yp(e,t,n);if(E(e,k.typeid,1))return hp(e,t,n);if(E(e,k.downcast,2))return A_(e,t,n);if(E(e,gi)){let r=e.$?.runtimeArgExprsInOrder||e.args;if(r){let i=n,o=r.map(a=>{let s=M(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){rt(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return Ee(l.$.variableName,l.$.env)}return s});return Xo(e.func.token.value,o,e,n,t)}}else{if(E(e,I.while))return vp(e,t,n);if(E(e,"->",2)&&F(e.args[0])&&E(e.args[0],I.fn)){let r=e.$?.value;return ne(r)?Qt(r,n):"// Error: Anonymous function missing function value"}else{if(E(e,k.consume))return L_(e,t,n);if(E(e,k.comptime_expect_error)||E(e,k.comptime_assert)||E(e,k.__yo_var_print_info)||E(e,k.__yo_var_is_owning_the_rc_value)||E(e,k.__yo_var_has_other_aliases))return"";if(E(e,I.open))return R_(e,t,n);{let r=Y_(e,t,n);if(r!==void 0)return r}}}}}}if(F(e))throw new Error(`Unhandled function call: ${w(e)}`);return`// Failed to transpile ${w(e)}`}function Ep({expr:e,env:t,context:n}){he(e,k.alignof,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});t=i.$.env;let o;i.$.value&&O(i.$.value)?o=i.$.value.value:o=i.$.type;let a=Kn(o),s;return a===null?s=K(gt(),{env:t,context:n}):s=Xt("Usize",a),e.$={env:t,type:gt(),value:s,pathCollection:[]},e}function $p({expr:e,env:t,context:n}){let r=E(e,I.op_and)?"and":"or",i=e.args;if(i.length===0){let u=ft(r==="and");return e.$={env:t,type:Je(),value:u,pathCollection:[],isAccessingProperty:!1},e}let o=t,a,s=!1,l=!1;for(let u=0;u<i.length;u++){let c=i[u],_=S({expr:c,env:o,context:{...n}});if(!_.$||!cn(_.$.type))throw y({token:c.token,errorMessage:`Expected bool type for "${r}" argument, got:
10281
+ ${w(c)}`});o=_.$.env;let p=_.$.value;if(de(p)){s=!0;continue}if(Re(p)){let f=p.value;if(r==="and"){if(!f){a=ft(!1);break}!s&&!l&&(a=ft(!0))}else{if(f){a=ft(!0);break}!s&&!l&&(a=ft(!1))}}else l=!0}return Re(a)||(l||s)&&(l?a=void 0:a=K(Je(),{env:o,context:n})),e.$={env:o,type:Je(),value:a,pathCollection:[],isAccessingProperty:!1},e}function Cp({expr:e,env:t,context:n}){he(e,k.__yo_array_fill,2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});o.$?.env&&(t=o.$.env);let a=o.$?.value;if(!O(a)||!ke(a.value))throw y({token:r.token,errorMessage:`__yo_array_fill expects first argument to be an ArrayType, got ${a?Me(a):"undefined"}`});let s=a.value,l=S({expr:i,env:t,context:{...n,expectedType:{type:s.childType,env:t}}});l.$?.env&&(t=l.$.env);let u=l.$?.type,c=l.$?.value;if(!u)throw y({token:i.token,errorMessage:"Failed to evaluate fill value"});if(!c)throw y({token:i.token,errorMessage:"__yo_array_fill expects second argument to be a compile-time known value, got runtime value"});if(!Y({type:s.childType,env:t},{type:u,env:t}))throw y({token:i.token,errorMessage:`Fill value type ${A(u)} is not compatible with array element type ${A(s.childType)}`});let _=s.length;if(de(_)){let g=K(s,{env:t,context:n});return e.$={env:t,type:s,value:g,pathCollection:[]},e}let p;if(ze(_)){let g=_.value;if(p=typeof g=="bigint"?Number(g):g,!Number.isInteger(p)||p<0)throw y({token:i.token,errorMessage:`Array length must be a non-negative integer, got ${p}`})}else throw y({token:i.token,errorMessage:`Array length must be a compile-time known integer, got ${Me(_)}`});let f=[];if(de(c)){let g=K(s,{env:t,context:n});return e.$={env:t,type:s,value:g,pathCollection:[]},e}for(let g=0;g<p;g++)f.push(c);let m=Mr(s,f);return e.$={env:t,type:s,value:m,pathCollection:[]},e}function bp({expr:e,env:t,context:n}){if(n.isValidatingFunctionDefinition||!n.isExecuting){let s=n.expectedType?.type??H.type;return e.$={env:t,type:s,value:pe(s)?H:K(s,{env:t,context:n}),pathCollection:[]},e}let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$||!Re(o.$.value))throw y({token:r.token,errorMessage:`Expected bool value for "comptime_assert", got:
10264
10282
  ${w(r)}
10265
10283
 
10266
10284
  Value:
10267
10285
  ${Me(o.$?.value)}`,isAssertionError:!0});if(o.$.value.value)return e.$={env:t,type:H.type,value:H,pathCollection:[]},e;if(i){let s=S({expr:i,env:t,context:{...n}});if(s.$?.value)throw y({token:e.token,errorMessage:Ve(s.$.value)?s.$.value.value:Me(s.$.value),isAssertionError:!0})}throw y({token:e.token,errorMessage:`Assertion failed for "comptime_assert":
10268
- ${w(r)}`,isAssertionError:!0})}function bp({expr:e,env:t,context:n}){if(E(e,k.__yo_comptime_bool_not)||E(e,k.__yo_comptime_bool_to_comptime_string)){let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$||!cn(r.$.type)||!r.$.value)throw y({token:r.token,errorMessage:`Expected bool type for "${e.func.token.value}" argument, got:
10286
+ ${w(r)}`,isAssertionError:!0})}function kp({expr:e,env:t,context:n}){if(E(e,k.__yo_comptime_bool_not)||E(e,k.__yo_comptime_bool_to_comptime_string)){let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$||!cn(r.$.type)||!r.$.value)throw y({token:r.token,errorMessage:`Expected bool type for "${e.func.token.value}" argument, got:
10269
10287
  ${w(r)}`});t=r.$.env;let i;if(E(e,k.__yo_comptime_bool_not))Re(r.$.value)?i=ft(!r.$.value.value):i=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_bool_to_comptime_string))Re(r.$.value)?i=on(r.$.value.value.toString()):i=K(xt(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected function call for "${e.func.token.value}", expected "__yo_comptime_bool_not" or "__yo_comptime_bool_to_comptime_string" function`});e.$={env:t,type:i.type,value:i,pathCollection:[]}}else{let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$||!cn(r.$.type)||!r.$.value)throw y({token:r.token,errorMessage:`Expected bool type for "${e.func.token.value}" first argument, got:
10270
10288
  ${w(r)}`});t=r.$.env;let i=S({expr:e.args[1],env:t,context:{...n}});if(!i.$||!cn(i.$.type)||!i.$.value)throw y({token:i.token,errorMessage:`Expected bool type for "${e.func.token.value}" second argument, got:
10271
- ${w(i)}`});t=i.$.env;let o=r.$.value,a=i.$.value,s;if(E(e,k.__yo_comptime_bool_and))Re(o)&&Re(a)?s=ft(o.value&&a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_bool_or))Re(o)&&Re(a)?s=ft(o.value||a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_bool_eq))Re(o)&&Re(a)?s=ft(o.value===a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_bool_neq))Re(o)&&Re(a)?s=ft(o.value!==a.value):s=K(Je(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected function call for comptime_bool operations: ${w(e)}`});e.$={env:t,type:s.type,value:s,pathCollection:[]}}return e}function kp({expr:e,env:t,context:n}){let r=Ae(e.args[0]),i=e.args[1]?Ae(e.args[1]):void 0;try{S({expr:r,env:t,context:{...n}})}catch{return e.$={env:t,type:H.type,value:H,pathCollection:[]},e}if(i){let o=S({expr:i,env:t,context:{...n}});if(o.$?.value)throw y({token:e.token,errorMessage:Ve(o.$.value)?o.$.value.value:Me(o.$.value)})}throw y({token:e.token,errorMessage:`Expected compile error, but the expression was evaluated successfully:
10272
- ${w(r)}`})}function Fg(e){return{...e,forallParameters:e.forallParameters.map(t=>({...t,isCompileTimeOnly:!0})),parameters:e.parameters.map(t=>({...t,isCompileTimeOnly:!0})),return:{...e.return,isCompileTimeOnly:!0}}}function ro(e,t,n){if(e.type.return.isCompileTimeOnly||e.type.isExtern||e.type.forallParameters.length>0)return;for(let i of e.type.parameters)if(pr(i.type,t))return;if(pr(e.type.return.type,t))return;let r=Fg(e.type);try{let i=Ae(e.body),o=Pe(r.env);for(let l of r.parameters){let{env:u}=me({env:o,variable:{name:l.label,type:l.type,isCompileTimeOnly:!0,value:[K(l.type,{variableName:l.label,env:o,context:n})],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});o=u}let a={tag:"Function",type:r,body:i,frameLevel:e.frameLevel,funcName:e.funcName?`${e.funcName}_comptime`:void 0,funcId:`${e.funcId}_comptime`,definitionSiteEnclosingFunctionType:e.definitionSiteEnclosingFunctionType,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},s=ht({expr:i,env:o,context:{...n,isExecuting:!0,forceCompileTimeBindings:!0,isAnalyzingCtfeCapability:!0,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:r,value:a,evaluationEnv:o},expectedType:{type:r.return.type,env:o}},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(s.$?.value!==void 0)return a.body=s,ct(o,!0),a;ct(o,!0);return}catch{return}}function wp({expr:e,env:t,context:n}){let r=e.args[0];if(!r)throw y({token:e.token,errorMessage:"comptime_fn requires exactly one argument (a function)"});let i=S({expr:r,env:t,context:n});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate argument to comptime_fn"});let o=i.$.value;if(!ne(o))throw y({token:r.token,errorMessage:`comptime_fn requires a function argument, got: ${Me(o)}`});if(o.type.return.isCompileTimeOnly)return e.$={env:t,type:o.type,value:o,pathCollection:[]},e;let a=ro(o,t,n);if(a)return e.$={env:t,type:a.type,value:a,pathCollection:[]},e;throw y({token:r.token,errorMessage:"comptime_fn: Failed to create compile-time version of function. The function body cannot be evaluated at compile time."})}function Fp({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_car,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10289
+ ${w(i)}`});t=i.$.env;let o=r.$.value,a=i.$.value,s;if(E(e,k.__yo_comptime_bool_and))Re(o)&&Re(a)?s=ft(o.value&&a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_bool_or))Re(o)&&Re(a)?s=ft(o.value||a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_bool_eq))Re(o)&&Re(a)?s=ft(o.value===a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_bool_neq))Re(o)&&Re(a)?s=ft(o.value!==a.value):s=K(Je(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected function call for comptime_bool operations: ${w(e)}`});e.$={env:t,type:s.type,value:s,pathCollection:[]}}return e}function wp({expr:e,env:t,context:n}){let r=Ae(e.args[0]),i=e.args[1]?Ae(e.args[1]):void 0;try{S({expr:r,env:t,context:{...n}})}catch{return e.$={env:t,type:H.type,value:H,pathCollection:[]},e}if(i){let o=S({expr:i,env:t,context:{...n}});if(o.$?.value)throw y({token:e.token,errorMessage:Ve(o.$.value)?o.$.value.value:Me(o.$.value)})}throw y({token:e.token,errorMessage:`Expected compile error, but the expression was evaluated successfully:
10290
+ ${w(r)}`})}function Lg(e){return{...e,forallParameters:e.forallParameters.map(t=>({...t,isCompileTimeOnly:!0})),parameters:e.parameters.map(t=>({...t,isCompileTimeOnly:!0})),return:{...e.return,isCompileTimeOnly:!0}}}function ro(e,t,n){if(e.type.return.isCompileTimeOnly||e.type.isExtern||e.type.forallParameters.length>0)return;for(let i of e.type.parameters)if(pr(i.type,t))return;if(pr(e.type.return.type,t))return;let r=Lg(e.type);try{let i=Ae(e.body),o=Pe(r.env);for(let l of r.parameters){let{env:u}=me({env:o,variable:{name:l.label,type:l.type,isCompileTimeOnly:!0,value:[K(l.type,{variableName:l.label,env:o,context:n})],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});o=u}let a={tag:"Function",type:r,body:i,frameLevel:e.frameLevel,funcName:e.funcName?`${e.funcName}_comptime`:void 0,funcId:`${e.funcId}_comptime`,definitionSiteEnclosingFunctionType:e.definitionSiteEnclosingFunctionType,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},s=ht({expr:i,env:o,context:{...n,isExecuting:!0,forceCompileTimeBindings:!0,isAnalyzingCtfeCapability:!0,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:r,value:a,evaluationEnv:o},expectedType:{type:r.return.type,env:o}},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(s.$?.value!==void 0)return a.body=s,ct(o,!0),a;ct(o,!0);return}catch{return}}function Fp({expr:e,env:t,context:n}){let r=e.args[0];if(!r)throw y({token:e.token,errorMessage:"comptime_fn requires exactly one argument (a function)"});let i=S({expr:r,env:t,context:n});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate argument to comptime_fn"});let o=i.$.value;if(!ne(o))throw y({token:r.token,errorMessage:`comptime_fn requires a function argument, got: ${Me(o)}`});if(o.type.return.isCompileTimeOnly)return e.$={env:t,type:o.type,value:o,pathCollection:[]},e;let a=ro(o,t,n);if(a)return e.$={env:t,type:a.type,value:a,pathCollection:[]},e;throw y({token:r.token,errorMessage:"comptime_fn: Failed to create compile-time version of function. The function body cannot be evaluated at compile time."})}function Lp({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_car,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10273
10291
  ${w(r)}`});if(!Vt(i.$.type))throw y({token:r.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" argument, got:
10274
10292
  ${w(r)}`});let o=i.$.type,a=i.$.value;if(!a)throw y({token:r.token,errorMessage:`Expected ComptimeList value for "${e.func.token.value}" argument, got:
10275
- ${w(r)}`});if(e.$={env:i.$.env,type:o.childType,value:K(o.childType,{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},lr(a)){let s=a.elements;if(s.length>0)e.$.value=s[0];else throw y({token:r.token,errorMessage:`Unexpected empty ComptimeList for "${e.func.token.value}" argument`})}return e}function Lp({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_cdr,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10293
+ ${w(r)}`});if(e.$={env:i.$.env,type:o.childType,value:K(o.childType,{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},lr(a)){let s=a.elements;if(s.length>0)e.$.value=s[0];else throw y({token:r.token,errorMessage:`Unexpected empty ComptimeList for "${e.func.token.value}" argument`})}return e}function Ap({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_cdr,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10276
10294
  ${w(r)}`});if(!Vt(i.$.type))throw y({token:r.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" argument, got:
10277
10295
  ${w(r)}`});let o=i.$.type,a=i.$.value;if(!a)throw y({token:r.token,errorMessage:`Expected ComptimeList value for "${e.func.token.value}" argument, got:
10278
- ${w(r)}`});if(e.$={env:i.$.env,type:o,value:K(o,{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},lr(a)){let s=a.elements;if(s.length>0)e.$.value=zn(o.childType,[...s.slice(1)]);else throw y({token:r.token,errorMessage:`Unexpected empty ComptimeList for "${e.func.token.value}" argument`})}return e}function Ap({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_cons,2);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the first argument expression for "${e.func.token.value}":
10296
+ ${w(r)}`});if(e.$={env:i.$.env,type:o,value:K(o,{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},lr(a)){let s=a.elements;if(s.length>0)e.$.value=zn(o.childType,[...s.slice(1)]);else throw y({token:r.token,errorMessage:`Unexpected empty ComptimeList for "${e.func.token.value}" argument`})}return e}function Ip({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_cons,2);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the first argument expression for "${e.func.token.value}":
10279
10297
  ${w(r)}`});t=r.$.env;let i=r.$.value;if(!i)throw y({token:r.token,errorMessage:`Expected Expr value for "${e.func.token.value}" first argument, got:
10280
10298
  ${w(r)}`});let o=S({expr:e.args[1],env:t,context:{...n}});if(!o.$)throw y({token:o.token,errorMessage:`Failed to evaluate the second argument expression for "${e.func.token.value}":
10281
10299
  ${w(o)}`});if(t=o.$.env,!Vt(o.$.type))throw y({token:o.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" second argument, got:
10282
10300
  ${w(o)}`});let a=o.$.value;if(!a)throw y({token:o.token,errorMessage:`Expected ComptimeList value for "${e.func.token.value}" second argument, got:
10283
- ${w(o)}`});let s=o.$.type,l=r.$.type;if(!Y({type:l,env:t},{type:s.childType,env:t}))throw y({token:r.token,errorMessage:`Type mismatch: cannot cons value of type "${A(l)}" to ComptimeList of base type "${A(s.childType)}" in "${e.func.token.value}"`});if(e.$={env:t,type:s,value:K(s,{env:t,context:n}),pathCollection:[],isAccessingProperty:!1},lr(a)){let u=[i,...a.elements];e.$.value=zn(s.childType,u)}return e}function Ip({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_append,2);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the first argument expression for "${e.func.token.value}":
10301
+ ${w(o)}`});let s=o.$.type,l=r.$.type;if(!Y({type:l,env:t},{type:s.childType,env:t}))throw y({token:r.token,errorMessage:`Type mismatch: cannot cons value of type "${A(l)}" to ComptimeList of base type "${A(s.childType)}" in "${e.func.token.value}"`});if(e.$={env:t,type:s,value:K(s,{env:t,context:n}),pathCollection:[],isAccessingProperty:!1},lr(a)){let u=[i,...a.elements];e.$.value=zn(s.childType,u)}return e}function Sp({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_append,2);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the first argument expression for "${e.func.token.value}":
10284
10302
  ${w(r)}`});if(t=r.$.env,!Vt(r.$.type))throw y({token:r.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" first argument, got:
10285
10303
  ${w(r)}`});let i=r.$.value;if(!i)throw y({token:r.token,errorMessage:`Expected Expr value for "${e.func.token.value}" first argument, got:
10286
10304
  ${w(r)}`});let o=S({expr:e.args[1],env:t,context:{...n}});if(!o.$)throw y({token:o.token,errorMessage:`Failed to evaluate the second argument expression for "${e.func.token.value}":
10287
10305
  ${w(o)}`});if(t=o.$.env,!Vt(o.$.type))throw y({token:o.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" second argument, got:
10288
10306
  ${w(o)}`});let a=o.$.value;if(!a)throw y({token:o.token,errorMessage:`Expected ComptimeList value for "${e.func.token.value}" second argument, got:
10289
- ${w(o)}`});let s=r.$.type,l=o.$.type;if(!Y({type:s,env:t},{type:l,env:t}))throw y({token:e.token,errorMessage:`Type mismatch: cannot append ComptimeList of base type "${A(l.childType)}" to ComptimeList of base type "${A(s.childType)}" in "${e.func.token.value}"`});if(e.$={env:t,type:s,value:K(s,{env:t,context:n}),pathCollection:[],isAccessingProperty:!1},lr(i)&&lr(a)){let u=[...i.elements,...a.elements];e.$.value=zn(s.childType,u)}return e}function Sp({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_length,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10307
+ ${w(o)}`});let s=r.$.type,l=o.$.type;if(!Y({type:s,env:t},{type:l,env:t}))throw y({token:e.token,errorMessage:`Type mismatch: cannot append ComptimeList of base type "${A(l.childType)}" to ComptimeList of base type "${A(s.childType)}" in "${e.func.token.value}"`});if(e.$={env:t,type:s,value:K(s,{env:t,context:n}),pathCollection:[],isAccessingProperty:!1},lr(i)&&lr(a)){let u=[...i.elements,...a.elements];e.$.value=zn(s.childType,u)}return e}function Np({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_length,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10290
10308
  ${w(r)}`});if(!Vt(i.$.type))throw y({token:r.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" argument, got:
10291
10309
  ${w(r)}`});let o=i.$.value;if(!o)throw y({token:r.token,errorMessage:`Expected ComptimeList value for "${e.func.token.value}" argument, got:
10292
- ${w(r)}`});if(e.$={env:i.$.env,type:gt(),value:K(gt(),{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},lr(o)){let a=o.elements.length,s=Xt("Usize",a);e.$.value=s}return e}function Np({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_element_type,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10310
+ ${w(r)}`});if(e.$={env:i.$.env,type:gt(),value:K(gt(),{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},lr(o)){let a=o.elements.length,s=Xt("Usize",a);e.$.value=s}return e}function Vp({expr:e,env:t,context:n}){he(e,k.__yo_comptime_list_element_type,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10293
10311
  ${w(r)}`});if(!O(i.$?.value))throw y({token:r.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" argument, got:
10294
10312
  ${w(r)}`});let o=i.$.value.value;if(!Vt(o))throw y({token:r.token,errorMessage:`Expected ComptimeList type for "${e.func.token.value}" argument, got:
10295
- ${A(o)}`});let a=ee(o.childType);return e.$={env:i.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function Wa(e){switch(e.tag){case"u8":return{min:0,max:255};case"i8":return{min:-128,max:127};case"u16":return{min:0,max:65535};case"i16":return{min:-32768,max:32767};case"u32":return{min:0,max:4294967295};case"i32":return{min:-2147483648,max:2147483647};case"u64":return{min:0n,max:18446744073709551615n};case"i64":return{min:-9223372036854775808n,max:9223372036854775807n};case"usize":{let t=br();return{min:0n,max:(1n<<BigInt(t))-1n}}case"isize":{let t=br();return{min:-(1n<<BigInt(t-1)),max:(1n<<BigInt(t-1))-1n}}case"comptime_int":return{min:-1/0,max:1/0};case"f32":case"f64":return;default:return}}function Vp(e){switch(e.tag){case"u8":return"U8";case"i8":return"I8";case"u16":return"U16";case"i16":return"I16";case"u32":return"U32";case"i32":return"I32";case"u64":return"U64";case"i64":return"I64";case"usize":return"Usize";case"isize":return"Isize";case"f32":return"F32";case"f64":return"F64";default:return}}function Qo(e){return or(e)||ar(e)||vt(e)||Nt(e)||jn(e)||e.isExtern==="c"&&x(e)}function Lg(e){return e.type.variants.find(r=>r.name===e.variantName)?.discriminant}function Ag(e){if(e&&ze(e))return e.value}function Ig(e){return An(e)||la(e)||ze(e)}function Ga(e,t,n){let r=Wa(t);if(r){let i=e,o=(s,l)=>{if(typeof s=="bigint"||typeof l=="bigint"){let u=typeof s=="bigint"?s:BigInt(Math.floor(s)),c=typeof l=="bigint"?l:BigInt(Math.floor(l));return u<c}return s<l},a=(s,l)=>{if(typeof s=="bigint"||typeof l=="bigint"){let u=typeof s=="bigint"?s:BigInt(Math.floor(s)),c=typeof l=="bigint"?l:BigInt(Math.floor(l));return u>c}return s>l};if(o(i,r.min)||a(i,r.max))throw y({token:n,errorMessage:`Value ${e} is out of range for type ${A(t)} (${r.min} to ${r.max})`})}if(vt(t)){let i=typeof e=="bigint"?e:BigInt(Math.floor(e));return ur(i)}if(Nt(t)){let i=typeof e=="bigint"?Number(e):e;return ua(i)}if(ar(t)){let i=Vp(t);if(i){let o=typeof e=="bigint"?Number(e):e;return Xt(i,o)}}if(or(t)){let i=Vp(t);if(i)if(i==="U64"||i==="I64"||i==="Usize"||i==="Isize"){let a=typeof e=="bigint"?e:BigInt(Math.floor(e));return Xt(i,a)}else{let a=typeof e=="bigint"?Number(e):Math.floor(e);return Xt(i,a)}}throw y({token:n,errorMessage:`Cannot create compile-time value for type ${A(t)}`})}function xp({targetType:e,argExpr:t,expr:n,callerEnv:r,context:i}){if(!Qo(e))return;let o=S({expr:t,env:r,context:{...i,expectedType:void 0}});if(!o.$)throw y({token:t.token,errorMessage:`Failed to evaluate argument: ${w(t)}`});let a=o.$.env,s=o.$.value,l=o.$.type;if(ge(l)&&It(s)){let c=Lg(s);if(c===void 0)throw y({token:t.token,errorMessage:`Failed to get discriminant for enum variant "${s.variantName}"`});if(Xn(e,a)){let _=Ga(c,e,n.token);return n.$={env:a,type:e,value:_,pathCollection:[]},{expr:n,env:a}}}if(!Qo(l)&&!vt(l)&&!Nt(l)&&!ge(l))throw y({token:t.token,errorMessage:`Cannot convert ${A(l)} to ${A(e)}. Expected a numeric type.`});let u=Ag(s);if(u!==void 0&&Xn(e,a)){let c=Ga(u,e,n.token);return n.$={env:a,type:e,value:c,pathCollection:[]},{expr:n,env:a}}if((vt(e)||Nt(e))&&u===void 0)throw y({token:t.token,errorMessage:`Cannot convert runtime value to ${A(e)}. Only compile-time values can be converted to ${A(e)}.`});if((vt(l)||Nt(l))&&Xn(e,a))if(u!==void 0){let c=Ga(u,e,n.token);return n.$={env:a,type:e,value:c,pathCollection:[]},{expr:n,env:a}}else return n.$={env:a,type:e,value:K(e,{variableName:"comptime_conversion_placeholder",env:a,context:i}),pathCollection:[]},{expr:n,env:a};if(jn(e)||!Ig(s)){let c={tag:"FnCall",func:{tag:"Atom",token:{...n.token,value:k.__yo_as[0],type:"identifier"},$:void 0},args:[o,n.func],token:n.token,$:{env:a,type:e,value:void 0,pathCollection:o.$.pathCollection}};return ga(n,c),{expr:n,env:a}}if(u!==void 0){let c=Ga(u,e,n.token);return n.$={env:a,type:e,value:c,pathCollection:[]},{expr:n,env:a}}throw y({token:n.token,errorMessage:"Unexpected case in numeric type conversion"})}function Pt(e){return e&&(An(e)||la(e)||ze(e))?e.value:null}function Yr(e,t,n,r){if(t.tag==="comptime_int"){let a=typeof e=="bigint"?e:BigInt(Math.floor(e));return ur(a)}if(t.tag==="comptime_float"){let a=typeof e=="bigint"?Number(e):e;return ua(a)}if(jn(t))return K(t,{env:n,context:r});let i=Sg(t),o=Vg(e,t);return Xt(i,o)}function Sg(e){switch(e.tag){case"u8":return"U8";case"i8":return"I8";case"u16":return"U16";case"i16":return"I16";case"u32":return"U32";case"i32":return"I32";case"u64":return"U64";case"i64":return"I64";case"usize":return"Usize";case"isize":return"Isize";case"f32":return"F32";case"f64":return"F64";case"comptime_int":return"ComptimeFloat";case"comptime_float":return"ComptimeFloat";default:throw new Error(`Unsupported numeric type: ${e.tag}`)}}function wl(e,t,n,r,i,o){let a=Wa(t);if(a===void 0||a.min===-1/0&&a.max===1/0)return;let s=(u,c)=>{if(typeof u=="bigint"||typeof c=="bigint"){let _=typeof u=="bigint"?u:BigInt(Math.floor(u)),p=typeof c=="bigint"?c:BigInt(Math.floor(c));return _<p}return u<c},l=(u,c)=>{if(typeof u=="bigint"||typeof c=="bigint"){let _=typeof u=="bigint"?u:BigInt(Math.floor(u)),p=typeof c=="bigint"?c:BigInt(Math.floor(c));return _>p}return u>c};if(s(e,a.min)||l(e,a.max))throw y({token:o,errorMessage:`Integer overflow in compile-time evaluation
10313
+ ${A(o)}`});let a=ee(o.childType);return e.$={env:i.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function Wa(e){switch(e.tag){case"u8":return{min:0,max:255};case"i8":return{min:-128,max:127};case"u16":return{min:0,max:65535};case"i16":return{min:-32768,max:32767};case"u32":return{min:0,max:4294967295};case"i32":return{min:-2147483648,max:2147483647};case"u64":return{min:0n,max:18446744073709551615n};case"i64":return{min:-9223372036854775808n,max:9223372036854775807n};case"usize":{let t=br();return{min:0n,max:(1n<<BigInt(t))-1n}}case"isize":{let t=br();return{min:-(1n<<BigInt(t-1)),max:(1n<<BigInt(t-1))-1n}}case"comptime_int":return{min:-1/0,max:1/0};case"f32":case"f64":return;default:return}}function xp(e){switch(e.tag){case"u8":return"U8";case"i8":return"I8";case"u16":return"U16";case"i16":return"I16";case"u32":return"U32";case"i32":return"I32";case"u64":return"U64";case"i64":return"I64";case"usize":return"Usize";case"isize":return"Isize";case"f32":return"F32";case"f64":return"F64";default:return}}function Qo(e){return or(e)||ar(e)||vt(e)||Nt(e)||jn(e)||e.isExtern==="c"&&x(e)}function Ag(e){return e.type.variants.find(r=>r.name===e.variantName)?.discriminant}function Ig(e){if(e&&ze(e))return e.value}function Sg(e){return An(e)||la(e)||ze(e)}function Ga(e,t,n){let r=Wa(t);if(r){let i=e,o=(s,l)=>{if(typeof s=="bigint"||typeof l=="bigint"){let u=typeof s=="bigint"?s:BigInt(Math.floor(s)),c=typeof l=="bigint"?l:BigInt(Math.floor(l));return u<c}return s<l},a=(s,l)=>{if(typeof s=="bigint"||typeof l=="bigint"){let u=typeof s=="bigint"?s:BigInt(Math.floor(s)),c=typeof l=="bigint"?l:BigInt(Math.floor(l));return u>c}return s>l};if(o(i,r.min)||a(i,r.max))throw y({token:n,errorMessage:`Value ${e} is out of range for type ${A(t)} (${r.min} to ${r.max})`})}if(vt(t)){let i=typeof e=="bigint"?e:BigInt(Math.floor(e));return ur(i)}if(Nt(t)){let i=typeof e=="bigint"?Number(e):e;return ua(i)}if(ar(t)){let i=xp(t);if(i){let o=typeof e=="bigint"?Number(e):e;return Xt(i,o)}}if(or(t)){let i=xp(t);if(i)if(i==="U64"||i==="I64"||i==="Usize"||i==="Isize"){let a=typeof e=="bigint"?e:BigInt(Math.floor(e));return Xt(i,a)}else{let a=typeof e=="bigint"?Number(e):Math.floor(e);return Xt(i,a)}}throw y({token:n,errorMessage:`Cannot create compile-time value for type ${A(t)}`})}function Dp({targetType:e,argExpr:t,expr:n,callerEnv:r,context:i}){if(!Qo(e))return;let o=S({expr:t,env:r,context:{...i,expectedType:void 0}});if(!o.$)throw y({token:t.token,errorMessage:`Failed to evaluate argument: ${w(t)}`});let a=o.$.env,s=o.$.value,l=o.$.type;if(ge(l)&&It(s)){let c=Ag(s);if(c===void 0)throw y({token:t.token,errorMessage:`Failed to get discriminant for enum variant "${s.variantName}"`});if(Xn(e,a)){let _=Ga(c,e,n.token);return n.$={env:a,type:e,value:_,pathCollection:[]},{expr:n,env:a}}}if(!Qo(l)&&!vt(l)&&!Nt(l)&&!ge(l))throw y({token:t.token,errorMessage:`Cannot convert ${A(l)} to ${A(e)}. Expected a numeric type.`});let u=Ig(s);if(u!==void 0&&Xn(e,a)){let c=Ga(u,e,n.token);return n.$={env:a,type:e,value:c,pathCollection:[]},{expr:n,env:a}}if((vt(e)||Nt(e))&&u===void 0)throw y({token:t.token,errorMessage:`Cannot convert runtime value to ${A(e)}. Only compile-time values can be converted to ${A(e)}.`});if((vt(l)||Nt(l))&&Xn(e,a))if(u!==void 0){let c=Ga(u,e,n.token);return n.$={env:a,type:e,value:c,pathCollection:[]},{expr:n,env:a}}else return n.$={env:a,type:e,value:K(e,{variableName:"comptime_conversion_placeholder",env:a,context:i}),pathCollection:[]},{expr:n,env:a};if(jn(e)||!Sg(s)){let c={tag:"FnCall",func:{tag:"Atom",token:{...n.token,value:k.__yo_as[0],type:"identifier"},$:void 0},args:[o,n.func],token:n.token,$:{env:a,type:e,value:void 0,pathCollection:o.$.pathCollection}};return ga(n,c),{expr:n,env:a}}if(u!==void 0){let c=Ga(u,e,n.token);return n.$={env:a,type:e,value:c,pathCollection:[]},{expr:n,env:a}}throw y({token:n.token,errorMessage:"Unexpected case in numeric type conversion"})}function Ut(e){return e&&(An(e)||la(e)||ze(e))?e.value:null}function Yr(e,t,n,r){if(t.tag==="comptime_int"){let a=typeof e=="bigint"?e:BigInt(Math.floor(e));return ur(a)}if(t.tag==="comptime_float"){let a=typeof e=="bigint"?Number(e):e;return ua(a)}if(jn(t))return K(t,{env:n,context:r});let i=Ng(t),o=xg(e,t);return Xt(i,o)}function Ng(e){switch(e.tag){case"u8":return"U8";case"i8":return"I8";case"u16":return"U16";case"i16":return"I16";case"u32":return"U32";case"i32":return"I32";case"u64":return"U64";case"i64":return"I64";case"usize":return"Usize";case"isize":return"Isize";case"f32":return"F32";case"f64":return"F64";case"comptime_int":return"ComptimeFloat";case"comptime_float":return"ComptimeFloat";default:throw new Error(`Unsupported numeric type: ${e.tag}`)}}function wl(e,t,n,r,i,o){let a=Wa(t);if(a===void 0||a.min===-1/0&&a.max===1/0)return;let s=(u,c)=>{if(typeof u=="bigint"||typeof c=="bigint"){let _=typeof u=="bigint"?u:BigInt(Math.floor(u)),p=typeof c=="bigint"?c:BigInt(Math.floor(c));return _<p}return u<c},l=(u,c)=>{if(typeof u=="bigint"||typeof c=="bigint"){let _=typeof u=="bigint"?u:BigInt(Math.floor(u)),p=typeof c=="bigint"?c:BigInt(Math.floor(c));return _>p}return u>c};if(s(e,a.min)||l(e,a.max))throw y({token:o,errorMessage:`Integer overflow in compile-time evaluation
10296
10314
  ${r} ${n==="multiply"?"*":n==="add"?"+":"-"} ${i} = ${e}
10297
- Result ${e} exceeds ${t.tag} range [${a.min}, ${a.max}]`,kind:"overflow"})}function Ng(e){switch(e.tag){case"u8":case"i8":return 8;case"u16":case"i16":return 16;case"u32":case"i32":return 32;case"u64":case"i64":return 64;case"usize":case"isize":return br();default:return null}}function Vg(e,t){if(t.tag==="u64"||t.tag==="i64"||t.tag==="usize"||t.tag==="isize"){let r=typeof e=="bigint"?e:BigInt(Math.floor(e)),i=Wa(t),o=typeof i.min=="bigint"?i.min:BigInt(i.min),a=typeof i.max=="bigint"?i.max:BigInt(i.max);return r<o?o:r>a?a:r}let n=typeof e=="bigint"?Number(e):e;switch(t.tag){case"u8":return Math.floor(Math.abs(n))%256;case"i8":return Math.max(-128,Math.min(127,Math.floor(n)));case"u16":return Math.floor(Math.abs(n))%65536;case"i16":return Math.max(-32768,Math.min(32767,Math.floor(n)));case"u32":return Math.floor(Math.abs(n))%4294967296;case"i32":return Math.max(-2147483648,Math.min(2147483647,Math.floor(n)));case"f32":case"f64":return n;default:return n}}function Zo(e,t,n,r,i,o){let a=Pt(e),s=Pt(t);return a===null||s===null?K(n,{env:i,context:o}):Yr(r(a,s),n,i,o)??K(n,{env:i,context:o})}function io(e,t,n,r,i){let o=Pt(e),a=Pt(t);if(o===null||a===null)return K(Je(),{env:r,context:i});if(typeof o=="bigint"||typeof a=="bigint"){let s=typeof o=="bigint"?o:BigInt(Math.floor(o)),l=typeof a=="bigint"?a:BigInt(Math.floor(a));return ft(n(s,l))}return ft(n(o,a))}function xg(e,t,n,r,i){let o=Pt(e);return o===null?K(t,{env:r,context:i}):Yr(n(o),t,r,i)??K(t,{env:r,context:i})}function Dp({expr:e,env:t,context:n}){let r=e.func.token.value,i=/^__yo_comptime_(u8|i8|u16|i16|u32|i32|u64|i64|usize|isize|f32|f64|int|float)_(add|sub|mul|div|mod|eq|neq|lt|lte|gt|gte|neg|to_comptime_string|bit_and|bit_or|bit_xor|bit_not|shl|shr)$/,o=r.match(i);if(!o)throw y({token:e.token,errorMessage:`Expected numeric function, got: ${r}`});let[,a,s]=o,u=(()=>{switch(a){case"u8":return Ii();case"i8":return Si();case"u16":return Ni();case"i16":return Vi();case"u32":return xi();case"i32":return Rr();case"u64":return Di();case"i64":return Mi();case"usize":return gt();case"isize":return Ai();case"f32":return Oi();case"f64":return Pr();case"int":case"comptime_int":return Or();case"float":case"comptime_float":return Li();default:throw new Error(`Unknown numeric type: ${a}`)}})();if(s==="neg"||s==="to_comptime_string"||s==="bit_not"){let h=S({expr:e.args[0],env:t,context:{...n}});if(!h.$||!h.$.value)throw y({token:h.token,errorMessage:`Expected ${a} type for "${r}" argument, got:
10298
- ${w(h)}`});t=h.$.env;let d;if(s==="neg")if(ze(h.$.value)){if(u.tag==="u8"||u.tag==="u16"||u.tag==="u32"||u.tag==="u64"||u.tag==="usize")throw y({token:e.token,errorMessage:`Cannot apply negation to unsigned type: ${a}`});d=xg(h.$.value,u,v=>-v,t,n)}else d=K(u,{env:t,context:n});else if(s==="bit_not")if(ze(h.$.value)||An(h.$.value)){let v=Pt(h.$.value);if(v!==null){let T=typeof v=="bigint"?v:BigInt(Math.floor(v)),$=Ng(u),C;if($!==null){let b=(1n<<BigInt($))-1n;if(C=T^b,Ql(u)){let R=1n<<BigInt($-1);C>=R&&(C=C-(1n<<BigInt($)))}}else C=~T;d=Yr(C,u,t,n)??K(u,{env:t,context:n})}else d=K(u,{env:t,context:n})}else d=K(u,{env:t,context:n});else if(s==="to_comptime_string")if(ze(h.$.value)){let v=Pt(h.$.value);v!==null?d=on(v.toString()):d=K(xt(),{env:t,context:n})}else d=K(xt(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected unary operation: ${s}`});return e.$={env:t,type:s==="to_comptime_string"?xt():u,value:d,pathCollection:[]},e}let c=S({expr:e.args[0],env:t,context:{...n}});if(!c.$||!c.$.value)throw y({token:c.token,errorMessage:`Expected ${a} type for "${r}" left argument, got:
10315
+ Result ${e} exceeds ${t.tag} range [${a.min}, ${a.max}]`,kind:"overflow"})}function Vg(e){switch(e.tag){case"u8":case"i8":return 8;case"u16":case"i16":return 16;case"u32":case"i32":return 32;case"u64":case"i64":return 64;case"usize":case"isize":return br();default:return null}}function xg(e,t){if(t.tag==="u64"||t.tag==="i64"||t.tag==="usize"||t.tag==="isize"){let r=typeof e=="bigint"?e:BigInt(Math.floor(e)),i=Wa(t),o=typeof i.min=="bigint"?i.min:BigInt(i.min),a=typeof i.max=="bigint"?i.max:BigInt(i.max);return r<o?o:r>a?a:r}let n=typeof e=="bigint"?Number(e):e;switch(t.tag){case"u8":return Math.floor(Math.abs(n))%256;case"i8":return Math.max(-128,Math.min(127,Math.floor(n)));case"u16":return Math.floor(Math.abs(n))%65536;case"i16":return Math.max(-32768,Math.min(32767,Math.floor(n)));case"u32":return Math.floor(Math.abs(n))%4294967296;case"i32":return Math.max(-2147483648,Math.min(2147483647,Math.floor(n)));case"f32":case"f64":return n;default:return n}}function Zo(e,t,n,r,i,o){let a=Ut(e),s=Ut(t);return a===null||s===null?K(n,{env:i,context:o}):Yr(r(a,s),n,i,o)??K(n,{env:i,context:o})}function io(e,t,n,r,i){let o=Ut(e),a=Ut(t);if(o===null||a===null)return K(Je(),{env:r,context:i});if(typeof o=="bigint"||typeof a=="bigint"){let s=typeof o=="bigint"?o:BigInt(Math.floor(o)),l=typeof a=="bigint"?a:BigInt(Math.floor(a));return ft(n(s,l))}return ft(n(o,a))}function Dg(e,t,n,r,i){let o=Ut(e);return o===null?K(t,{env:r,context:i}):Yr(n(o),t,r,i)??K(t,{env:r,context:i})}function Mp({expr:e,env:t,context:n}){let r=e.func.token.value,i=/^__yo_comptime_(u8|i8|u16|i16|u32|i32|u64|i64|usize|isize|f32|f64|int|float)_(add|sub|mul|div|mod|eq|neq|lt|lte|gt|gte|neg|to_comptime_string|bit_and|bit_or|bit_xor|bit_not|shl|shr)$/,o=r.match(i);if(!o)throw y({token:e.token,errorMessage:`Expected numeric function, got: ${r}`});let[,a,s]=o,u=(()=>{switch(a){case"u8":return Ii();case"i8":return Si();case"u16":return Ni();case"i16":return Vi();case"u32":return xi();case"i32":return Rr();case"u64":return Di();case"i64":return Mi();case"usize":return gt();case"isize":return Ai();case"f32":return Oi();case"f64":return Pr();case"int":case"comptime_int":return Or();case"float":case"comptime_float":return Li();default:throw new Error(`Unknown numeric type: ${a}`)}})();if(s==="neg"||s==="to_comptime_string"||s==="bit_not"){let h=S({expr:e.args[0],env:t,context:{...n}});if(!h.$||!h.$.value)throw y({token:h.token,errorMessage:`Expected ${a} type for "${r}" argument, got:
10316
+ ${w(h)}`});t=h.$.env;let d;if(s==="neg")if(ze(h.$.value)){if(u.tag==="u8"||u.tag==="u16"||u.tag==="u32"||u.tag==="u64"||u.tag==="usize")throw y({token:e.token,errorMessage:`Cannot apply negation to unsigned type: ${a}`});d=Dg(h.$.value,u,v=>-v,t,n)}else d=K(u,{env:t,context:n});else if(s==="bit_not")if(ze(h.$.value)||An(h.$.value)){let v=Ut(h.$.value);if(v!==null){let T=typeof v=="bigint"?v:BigInt(Math.floor(v)),$=Vg(u),C;if($!==null){let b=(1n<<BigInt($))-1n;if(C=T^b,Ql(u)){let R=1n<<BigInt($-1);C>=R&&(C=C-(1n<<BigInt($)))}}else C=~T;d=Yr(C,u,t,n)??K(u,{env:t,context:n})}else d=K(u,{env:t,context:n})}else d=K(u,{env:t,context:n});else if(s==="to_comptime_string")if(ze(h.$.value)){let v=Ut(h.$.value);v!==null?d=on(v.toString()):d=K(xt(),{env:t,context:n})}else d=K(xt(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected unary operation: ${s}`});return e.$={env:t,type:s==="to_comptime_string"?xt():u,value:d,pathCollection:[]},e}let c=S({expr:e.args[0],env:t,context:{...n}});if(!c.$||!c.$.value)throw y({token:c.token,errorMessage:`Expected ${a} type for "${r}" left argument, got:
10299
10317
  ${w(c)}`});t=c.$.env;let _=S({expr:e.args[1],env:t,context:{...n}});if(!_.$||!_.$.value)throw y({token:_.token,errorMessage:`Expected ${a} type for "${r}" right argument, got:
10300
- ${w(_)}`});t=_.$.env;let p=c.$.value,f=_.$.value,m,g;switch(s){case"add":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"||typeof d=="bigint"?(typeof h=="bigint"?h:BigInt(h))+(typeof d=="bigint"?d:BigInt(d)):h+d;wl(v,u,"add",h,d,e.token)}m=Zo(p,f,u,(v,T)=>{if(typeof v=="bigint"||typeof T=="bigint"){let $=typeof v=="bigint"?v:BigInt(v),C=typeof T=="bigint"?T:BigInt(T);return $+C}return v+T},t,n),g=u;break}case"sub":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"||typeof d=="bigint"?(typeof h=="bigint"?h:BigInt(h))-(typeof d=="bigint"?d:BigInt(d)):h-d;wl(v,u,"subtract",h,d,e.token)}m=Zo(p,f,u,(v,T)=>{if(typeof v=="bigint"||typeof T=="bigint"){let $=typeof v=="bigint"?v:BigInt(v),C=typeof T=="bigint"?T:BigInt(T);return $-C}return v-T},t,n),g=u;break}case"mul":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"||typeof d=="bigint"?(typeof h=="bigint"?h:BigInt(h))*(typeof d=="bigint"?d:BigInt(d)):h*d;wl(v,u,"multiply",h,d,e.token)}m=Zo(p,f,u,(v,T)=>{if(typeof v=="bigint"||typeof T=="bigint"){let $=typeof v=="bigint"?v:BigInt(v),C=typeof T=="bigint"?T:BigInt(T);return $*C}return v*T},t,n),g=u;break}case"div":{let h=Pt(f);if(h===0||h===0n)throw y({token:_.token,errorMessage:`Division by zero in "${r}" operation`});m=Zo(p,f,u,(d,v)=>{if(typeof d=="bigint"||typeof v=="bigint"){let T=typeof d=="bigint"?d:BigInt(d),$=typeof v=="bigint"?v:BigInt(v);return T/$}return or(u)||u.tag==="comptime_int"?Math.trunc(d/v):d/v},t,n),g=u;break}case"mod":{if(ar(u))throw y({token:e.token,errorMessage:`Modulo operation not supported for floating point types: ${a}`});let h=Pt(f);if(h===0||h===0n)throw y({token:_.token,errorMessage:`Modulo by zero in "${r}" operation`});m=Zo(p,f,u,(d,v)=>{if(typeof d=="bigint"||typeof v=="bigint"){let T=typeof d=="bigint"?d:BigInt(d),$=typeof v=="bigint"?v:BigInt(v);return T%$}return d%v},t,n),g=u;break}case"eq":m=io(p,f,(h,d)=>h===d,t,n),g=Je();break;case"neq":m=io(p,f,(h,d)=>h!==d,t,n),g=Je();break;case"lt":m=io(p,f,(h,d)=>h<d,t,n),g=Je();break;case"lte":m=io(p,f,(h,d)=>h<=d,t,n),g=Je();break;case"gt":m=io(p,f,(h,d)=>h>d,t,n),g=Je();break;case"gte":m=io(p,f,(h,d)=>h>=d,t,n),g=Je();break;case"bit_and":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?d:BigInt(Math.floor(d));m=Yr(v&T,u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"bit_or":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?d:BigInt(Math.floor(d));m=Yr(v|T,u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"bit_xor":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?d:BigInt(Math.floor(d));m=Yr(v^T,u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"shl":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?Number(d):Math.floor(d);m=Yr(v<<BigInt(T),u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"shr":{let h=Pt(p),d=Pt(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?Number(d):Math.floor(d);m=Yr(v>>BigInt(T),u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}default:throw y({token:e.token,errorMessage:`Unexpected binary operation: ${s}`})}return e.$={env:t,type:g,value:m,pathCollection:[]},e}function Mp({expr:e,env:t,context:n}){if(e.args.length===0)throw y({token:e.token,errorMessage:'Expected at least 1 argument for "comptime_print", got 0'});let r=[];for(let i of e.args){let o=S({expr:i,env:t,context:{...n}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate argument for "comptime_print": ${w(i)}`});t=o.$.env,Ve(o.$.value)?r.push(o.$.value.value):r.push(Me(o.$.value))}return!n.isValidatingFunctionDefinition&&n.isExecuting&&console.log(...r),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Op({expr:e,env:t,context:n}){if(E(e,k.__yo_comptime_string_length)||E(e,k.__yo_comptime_string_to_upper)||E(e,k.__yo_comptime_string_to_lower)){let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$||!Et(r.$.type)||!r.$.value)throw y({token:r.token,errorMessage:`Expected comptime_string type for "${e.func.token.value}" argument, got:
10318
+ ${w(_)}`});t=_.$.env;let p=c.$.value,f=_.$.value,m,g;switch(s){case"add":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"||typeof d=="bigint"?(typeof h=="bigint"?h:BigInt(h))+(typeof d=="bigint"?d:BigInt(d)):h+d;wl(v,u,"add",h,d,e.token)}m=Zo(p,f,u,(v,T)=>{if(typeof v=="bigint"||typeof T=="bigint"){let $=typeof v=="bigint"?v:BigInt(v),C=typeof T=="bigint"?T:BigInt(T);return $+C}return v+T},t,n),g=u;break}case"sub":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"||typeof d=="bigint"?(typeof h=="bigint"?h:BigInt(h))-(typeof d=="bigint"?d:BigInt(d)):h-d;wl(v,u,"subtract",h,d,e.token)}m=Zo(p,f,u,(v,T)=>{if(typeof v=="bigint"||typeof T=="bigint"){let $=typeof v=="bigint"?v:BigInt(v),C=typeof T=="bigint"?T:BigInt(T);return $-C}return v-T},t,n),g=u;break}case"mul":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"||typeof d=="bigint"?(typeof h=="bigint"?h:BigInt(h))*(typeof d=="bigint"?d:BigInt(d)):h*d;wl(v,u,"multiply",h,d,e.token)}m=Zo(p,f,u,(v,T)=>{if(typeof v=="bigint"||typeof T=="bigint"){let $=typeof v=="bigint"?v:BigInt(v),C=typeof T=="bigint"?T:BigInt(T);return $*C}return v*T},t,n),g=u;break}case"div":{let h=Ut(f);if(h===0||h===0n)throw y({token:_.token,errorMessage:`Division by zero in "${r}" operation`});m=Zo(p,f,u,(d,v)=>{if(typeof d=="bigint"||typeof v=="bigint"){let T=typeof d=="bigint"?d:BigInt(d),$=typeof v=="bigint"?v:BigInt(v);return T/$}return or(u)||u.tag==="comptime_int"?Math.trunc(d/v):d/v},t,n),g=u;break}case"mod":{if(ar(u))throw y({token:e.token,errorMessage:`Modulo operation not supported for floating point types: ${a}`});let h=Ut(f);if(h===0||h===0n)throw y({token:_.token,errorMessage:`Modulo by zero in "${r}" operation`});m=Zo(p,f,u,(d,v)=>{if(typeof d=="bigint"||typeof v=="bigint"){let T=typeof d=="bigint"?d:BigInt(d),$=typeof v=="bigint"?v:BigInt(v);return T%$}return d%v},t,n),g=u;break}case"eq":m=io(p,f,(h,d)=>h===d,t,n),g=Je();break;case"neq":m=io(p,f,(h,d)=>h!==d,t,n),g=Je();break;case"lt":m=io(p,f,(h,d)=>h<d,t,n),g=Je();break;case"lte":m=io(p,f,(h,d)=>h<=d,t,n),g=Je();break;case"gt":m=io(p,f,(h,d)=>h>d,t,n),g=Je();break;case"gte":m=io(p,f,(h,d)=>h>=d,t,n),g=Je();break;case"bit_and":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?d:BigInt(Math.floor(d));m=Yr(v&T,u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"bit_or":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?d:BigInt(Math.floor(d));m=Yr(v|T,u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"bit_xor":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?d:BigInt(Math.floor(d));m=Yr(v^T,u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"shl":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?Number(d):Math.floor(d);m=Yr(v<<BigInt(T),u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}case"shr":{let h=Ut(p),d=Ut(f);if(h!==null&&d!==null){let v=typeof h=="bigint"?h:BigInt(Math.floor(h)),T=typeof d=="bigint"?Number(d):Math.floor(d);m=Yr(v>>BigInt(T),u,t,n)??K(u,{env:t,context:n})}else m=K(u,{env:t,context:n});g=u;break}default:throw y({token:e.token,errorMessage:`Unexpected binary operation: ${s}`})}return e.$={env:t,type:g,value:m,pathCollection:[]},e}function Op({expr:e,env:t,context:n}){if(e.args.length===0)throw y({token:e.token,errorMessage:'Expected at least 1 argument for "comptime_print", got 0'});let r=[];for(let i of e.args){let o=S({expr:i,env:t,context:{...n}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate argument for "comptime_print": ${w(i)}`});t=o.$.env,Ve(o.$.value)?r.push(o.$.value.value):r.push(Me(o.$.value))}return!n.isValidatingFunctionDefinition&&n.isExecuting&&console.log(...r),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Rp({expr:e,env:t,context:n}){if(E(e,k.__yo_comptime_string_length)||E(e,k.__yo_comptime_string_to_upper)||E(e,k.__yo_comptime_string_to_lower)){let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$||!Et(r.$.type)||!r.$.value)throw y({token:r.token,errorMessage:`Expected comptime_string type for "${e.func.token.value}" argument, got:
10301
10319
  ${w(r)}`});t=r.$.env;let i;if(E(e,k.__yo_comptime_string_length))Ve(r.$.value)?i=ur(BigInt(r.$.value.value.length)):i=K(Or(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_to_upper))Ve(r.$.value)?i=on(r.$.value.value.toUpperCase()):i=K(xt(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_to_lower))Ve(r.$.value)?i=on(r.$.value.value.toLowerCase()):i=K(xt(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected function call for "${e.func.token.value}", expected string unary function`});e.$={env:t,type:i.type,value:i,pathCollection:[]}}else if(E(e,k.__yo_comptime_string_slice)){if(e.args.length<2||e.args.length>3)throw y({token:e.token,errorMessage:`"${e.func.token.value}" expects 2 or 3 arguments (string, start, end?), got ${e.args.length}`});let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$||!Et(r.$.type)||!r.$.value)throw y({token:r.token,errorMessage:`Expected comptime_string type for "${e.func.token.value}" string argument, got:
10302
10320
  ${w(r)}`});t=r.$.env;let i=S({expr:e.args[1],env:t,context:{...n}});if(!i.$||!vt(i.$.type)||!i.$.value)throw y({token:i.token,errorMessage:`Expected comptime_int type for "${e.func.token.value}" start argument, got:
10303
10321
  ${w(i)}`});t=i.$.env;let o;if(e.args.length===3){if(o=S({expr:e.args[2],env:t,context:{...n}}),!o.$||!vt(o.$.type)||!o.$.value)throw y({token:o.token,errorMessage:`Expected comptime_int type for "${e.func.token.value}" end argument, got:
10304
10322
  ${w(o)}`});t=o.$.env}let a;if(Ve(r.$.value)&&An(i.$.value)){let s=r.$.value.value,l=i.$.value.value,u=typeof l=="bigint"?Number(l):l,c=s.length;if(o&&o.$&&o.$.value&&An(o.$.value)){let _=o.$.value.value;c=typeof _=="bigint"?Number(_):_}a=on(s.slice(u,c))}else a=K(xt(),{env:t,context:n});e.$={env:t,type:a.type,value:a,pathCollection:[]}}else{let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$||!Et(r.$.type)||!r.$.value)throw y({token:r.token,errorMessage:`Expected comptime_string type for "${e.func.token.value}" first argument, got:
10305
10323
  ${w(r)}`});t=r.$.env;let i=S({expr:e.args[1],env:t,context:{...n}});if(!i.$||!Et(i.$.type)||!i.$.value)throw y({token:i.token,errorMessage:`Expected comptime_string type for "${e.func.token.value}" second argument, got:
10306
- ${w(i)}`});t=i.$.env;let o=r.$.value,a=i.$.value,s;if(E(e,k.__yo_comptime_string_concat))Ve(o)&&Ve(a)?s=on(o.value+a.value):s=K(xt(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_eq))Ve(o)&&Ve(a)?s=ft(o.value===a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_neq))Ve(o)&&Ve(a)?s=ft(o.value!==a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_lt))Ve(o)&&Ve(a)?s=ft(o.value<a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_lte))Ve(o)&&Ve(a)?s=ft(o.value<=a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_gt))Ve(o)&&Ve(a)?s=ft(o.value>a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_gte))Ve(o)&&Ve(a)?s=ft(o.value>=a.value):s=K(Je(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected function call for comptime_string operations: ${w(e)}`});e.$={env:t,type:s.type,value:s,pathCollection:[]}}return e}function Rp({expr:e,env:t,context:n}){he(e,k.consume,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});return t=i.$.env,t=Tn(i,t),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function oo({functionCalleeExpr:e,functionType:t,functionValue:n,argValues:r,callerEnv:i,calleeEnv:o,context:a}){if(a.isAnalyzingCtfeCapability)return{value:K(t.return.type,{variableName:"ctfe_analysis_result_"+qe(i.modulePath),env:t.env,context:a}),callerEnv:i,calleeEnv:o};let s=[...r.forallArgs.map(T=>T.value),...r.args.map(T=>T.value)];if(s.some(T=>!T))throw y({token:e?.token??ae,errorMessage:"Failed to call the function for compile-time. Some arguments are not compile-time evaluated correctly."});let l=s,u=t.return.type,c=He(u),_=n.funcId,p=n.calledComptimeFunctionCaches,f=c?p.find(T=>T.argValues.length===l.length&&T.argValues.every(($,C)=>{let L=l[C];return O($)&&O(L)?x($.value)&&x(L.value)||Fe($.value)||Fe(L.value)?$.value.id===L.value.id:x($.value)&&!x(L.value)?!1:Y({type:$.value,env:T.env},{type:L.value,env:i},!0):At({value:$,env:T.env},{value:L,env:i})})):void 0;if(f)return{callerEnv:i,calleeEnv:o,value:f.value};let m=n.body,g={funcId:_,argValues:l,value:K(t.return.type,{variableName:t.return.label,recursiveTypeRef:{functionValue:n,argValues:l},env:o,context:a}),env:o,body:Ae(m)};n.calledComptimeFunctionCaches.push(g);let h=n.calledComptimeFunctionCaches.length-1,d;try{d=ht({expr:g.body,env:o,context:{...a,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:t,value:n,evaluationEnv:o},isEvaluatingLoopBody:void 0,capturedVariables:void 0,isExecuting:!a.isValidatingFunctionDefinition,functionReturnImplConcreteType:[],SelfType:t.SelfType??a.SelfType,forceCompileTimeBindings:!0},variablesToAdd:[]})}catch(T){throw n.calledComptimeFunctionCaches.splice(h,1),T}if(!d.$)throw y({token:n.body.token,errorMessage:"Function body is not evaluated correctly"});let v=d.$.value;if(!v)throw y({token:n.body.token,errorMessage:"Function body is not evaluated correctly. Expected to return a compile-time known value."});if(o=d.$.env,O(v)){let T=v.value;!T.typeName&&n.funcName&&(T.typeName=n.funcName+`(${l.map($=>Me($)).join(", ")})`),(ce(T)||ge(T)||it(T)||Te(T)||De(T))&&(T.functionValue||(T.functionValue=n))}return c?n.calledComptimeFunctionCaches[h]={funcId:_,argValues:l,value:v,env:d.$.env,body:d}:n.calledComptimeFunctionCaches.splice(h,1),{value:v,callerEnv:i,calleeEnv:o}}function Fl(e,t,n){let i=X(t,"Option").find(f=>f.value?.[0]&&ne(f.value[0])&&G(f.type));if(!i||!i.value?.[0]||!ne(i.value[0]))throw new Error("Cannot find Option type constructor in environment");let o=i.value[0],a=o.type,s=a.parameters[0],l=ee(e),u=Pe(a.env),{env:c}=me({env:u,variable:{name:s.label,token:ae,type:l.type,isCompileTimeOnly:!0,initializedAtToken:ae,consumedAtToken:void 0,value:[l],isOwningTheRcValue:!1}}),{value:_,callerEnv:p}=oo({functionCalleeExpr:void 0,functionType:a,functionValue:o,argValues:{forallArgs:[],args:[{value:l,parameterType:s.type,argType:tt()}],variadicArgs:[]},callerEnv:t,calleeEnv:c,context:n});if(!O(_))throw new Error("Option type constructor did not return a type value");return{optionType:_.value,env:p}}function Pp({expr:e,env:t,context:n}){he(e,[k.__yo_decr_rc[0]],1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_decr_rc[0]}":
10307
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Up({expr:e,env:t,context:n}){he(e,[k.__yo_incr_rc[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_incr_rc[0]}":
10308
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function zp({expr:e,env:t,context:n}){he(e,[k.__yo_incr_rc_atomic[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_incr_rc_atomic[0]}":
10309
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Bp({expr:e,env:t,context:n}){he(e,[k.__yo_decr_rc_atomic[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_decr_rc_atomic[0]}":
10310
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Gp({expr:e,env:t,context:n}){he(e,[k.__yo_rc_own[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_incr_rc[0]}":
10311
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}function Wp({expr:e,env:t,context:n}){he(e,[k.__yo_dyn_drop[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_dyn_drop[0]}":
10312
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function qp({expr:e,env:t,context:n}){he(e,[k.__yo_dyn_dup[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_dyn_dup[0]}":
10313
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Yp({expr:e,env:t,context:n}){he(e,[k.__yo_sometype_drop[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_sometype_drop[0]}":
10314
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Hp({expr:e,env:t,context:n}){he(e,[k.__yo_sometype_dup[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_sometype_dup[0]}":
10315
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function jp({expr:e,env:t,context:n}){he(e,[k.__yo_iso_extract[0]],1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_iso_extract[0]}":
10316
- ${w(r)}`});t=i.$.env;let o=i.$.type;if(!kt(o))throw y({token:r.token,errorMessage:`${k.__yo_iso_extract[0]} expects an Iso type, but got: ${A(o)}`});let a=o.childType,{optionType:s,env:l}=Fl(a,t,n);return t=l,e.$={env:t,type:s,value:void 0,pathCollection:i.$.pathCollection||[]},Ge(e,!0),e}function Kp({expr:e,env:t,context:n}){he(e,[k.__yo_iso_dispose[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_iso_dispose[0]}":
10317
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Xp({expr:e,env:t,context:n}){he(e,[k.__yo_arc_dispose[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_arc_dispose[0]}":
10318
- ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Qp({expr:e,env:t,context:n}){he(e,[k.__yo_drop_array_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the array argument for "${k.__yo_drop_array_element[0]}":
10324
+ ${w(i)}`});t=i.$.env;let o=r.$.value,a=i.$.value,s;if(E(e,k.__yo_comptime_string_concat))Ve(o)&&Ve(a)?s=on(o.value+a.value):s=K(xt(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_eq))Ve(o)&&Ve(a)?s=ft(o.value===a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_neq))Ve(o)&&Ve(a)?s=ft(o.value!==a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_lt))Ve(o)&&Ve(a)?s=ft(o.value<a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_lte))Ve(o)&&Ve(a)?s=ft(o.value<=a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_gt))Ve(o)&&Ve(a)?s=ft(o.value>a.value):s=K(Je(),{env:t,context:n});else if(E(e,k.__yo_comptime_string_gte))Ve(o)&&Ve(a)?s=ft(o.value>=a.value):s=K(Je(),{env:t,context:n});else throw y({token:e.token,errorMessage:`Unexpected function call for comptime_string operations: ${w(e)}`});e.$={env:t,type:s.type,value:s,pathCollection:[]}}return e}function Pp({expr:e,env:t,context:n}){he(e,k.consume,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});return t=i.$.env,t=Tn(i,t),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function oo({functionCalleeExpr:e,functionType:t,functionValue:n,argValues:r,callerEnv:i,calleeEnv:o,context:a}){if(a.isAnalyzingCtfeCapability)return{value:K(t.return.type,{variableName:"ctfe_analysis_result_"+qe(i.modulePath),env:t.env,context:a}),callerEnv:i,calleeEnv:o};let s=[...r.forallArgs.map(T=>T.value),...r.args.map(T=>T.value)];if(s.some(T=>!T))throw y({token:e?.token??ae,errorMessage:"Failed to call the function for compile-time. Some arguments are not compile-time evaluated correctly."});let l=s,u=t.return.type,c=He(u),_=n.funcId,p=n.calledComptimeFunctionCaches,f=c?p.find(T=>T.argValues.length===l.length&&T.argValues.every(($,C)=>{let L=l[C];return O($)&&O(L)?x($.value)&&x(L.value)||Fe($.value)||Fe(L.value)?$.value.id===L.value.id:x($.value)&&!x(L.value)?!1:Y({type:$.value,env:T.env},{type:L.value,env:i},!0):At({value:$,env:T.env},{value:L,env:i})})):void 0;if(f)return{callerEnv:i,calleeEnv:o,value:f.value};let m=n.body,g={funcId:_,argValues:l,value:K(t.return.type,{variableName:t.return.label,recursiveTypeRef:{functionValue:n,argValues:l},env:o,context:a}),env:o,body:Ae(m)};n.calledComptimeFunctionCaches.push(g);let h=n.calledComptimeFunctionCaches.length-1,d;try{d=ht({expr:g.body,env:o,context:{...a,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:t,value:n,evaluationEnv:o},isEvaluatingLoopBody:void 0,capturedVariables:void 0,isExecuting:!a.isValidatingFunctionDefinition,functionReturnImplConcreteType:[],SelfType:t.SelfType??a.SelfType,forceCompileTimeBindings:!0},variablesToAdd:[]})}catch(T){throw n.calledComptimeFunctionCaches.splice(h,1),T}if(!d.$)throw y({token:n.body.token,errorMessage:"Function body is not evaluated correctly"});let v=d.$.value;if(!v)throw y({token:n.body.token,errorMessage:"Function body is not evaluated correctly. Expected to return a compile-time known value."});if(o=d.$.env,O(v)){let T=v.value;!T.typeName&&n.funcName&&(T.typeName=n.funcName+`(${l.map($=>Me($)).join(", ")})`),(ce(T)||ge(T)||it(T)||Te(T)||De(T))&&(T.functionValue||(T.functionValue=n))}return c?n.calledComptimeFunctionCaches[h]={funcId:_,argValues:l,value:v,env:d.$.env,body:d}:n.calledComptimeFunctionCaches.splice(h,1),{value:v,callerEnv:i,calleeEnv:o}}function Fl(e,t,n){let i=X(t,"Option").find(f=>f.value?.[0]&&ne(f.value[0])&&G(f.type));if(!i||!i.value?.[0]||!ne(i.value[0]))throw new Error("Cannot find Option type constructor in environment");let o=i.value[0],a=o.type,s=a.parameters[0],l=ee(e),u=Pe(a.env),{env:c}=me({env:u,variable:{name:s.label,token:ae,type:l.type,isCompileTimeOnly:!0,initializedAtToken:ae,consumedAtToken:void 0,value:[l],isOwningTheRcValue:!1}}),{value:_,callerEnv:p}=oo({functionCalleeExpr:void 0,functionType:a,functionValue:o,argValues:{forallArgs:[],args:[{value:l,parameterType:s.type,argType:tt()}],variadicArgs:[]},callerEnv:t,calleeEnv:c,context:n});if(!O(_))throw new Error("Option type constructor did not return a type value");return{optionType:_.value,env:p}}function Up({expr:e,env:t,context:n}){he(e,[k.__yo_decr_rc[0]],1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_decr_rc[0]}":
10325
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function zp({expr:e,env:t,context:n}){he(e,[k.__yo_incr_rc[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_incr_rc[0]}":
10326
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Bp({expr:e,env:t,context:n}){he(e,[k.__yo_incr_rc_atomic[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_incr_rc_atomic[0]}":
10327
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Gp({expr:e,env:t,context:n}){he(e,[k.__yo_decr_rc_atomic[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_decr_rc_atomic[0]}":
10328
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Wp({expr:e,env:t,context:n}){he(e,[k.__yo_rc_own[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_incr_rc[0]}":
10329
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}function qp({expr:e,env:t,context:n}){he(e,[k.__yo_dyn_drop[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_dyn_drop[0]}":
10330
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Yp({expr:e,env:t,context:n}){he(e,[k.__yo_dyn_dup[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_dyn_dup[0]}":
10331
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Hp({expr:e,env:t,context:n}){he(e,[k.__yo_sometype_drop[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_sometype_drop[0]}":
10332
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function jp({expr:e,env:t,context:n}){he(e,[k.__yo_sometype_dup[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_sometype_dup[0]}":
10333
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Kp({expr:e,env:t,context:n}){he(e,[k.__yo_iso_extract[0]],1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_iso_extract[0]}":
10334
+ ${w(r)}`});t=i.$.env;let o=i.$.type;if(!wt(o))throw y({token:r.token,errorMessage:`${k.__yo_iso_extract[0]} expects an Iso type, but got: ${A(o)}`});let a=o.childType,{optionType:s,env:l}=Fl(a,t,n);return t=l,e.$={env:t,type:s,value:void 0,pathCollection:i.$.pathCollection||[]},Ge(e,!0),e}function Xp({expr:e,env:t,context:n}){he(e,[k.__yo_iso_dispose[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_iso_dispose[0]}":
10335
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Qp({expr:e,env:t,context:n}){he(e,[k.__yo_arc_dispose[0]]);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.__yo_arc_dispose[0]}":
10336
+ ${w(r)}`});return t=i.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Zp({expr:e,env:t,context:n}){he(e,[k.__yo_drop_array_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the array argument for "${k.__yo_drop_array_element[0]}":
10319
10337
  ${w(r)}`});t=o.$.env;let a=S({expr:i,env:t,context:{...n}});if(!a.$)throw y({token:i.token,errorMessage:`Failed to evaluate the index argument for "${k.__yo_drop_array_element[0]}":
10320
- ${w(i)}`});return t=a.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Zp({expr:e,env:t,context:n}){he(e,[k.__yo_dup_array_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the array argument for "${k.__yo_dup_array_element[0]}":
10338
+ ${w(i)}`});return t=a.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Jp({expr:e,env:t,context:n}){he(e,[k.__yo_dup_array_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the array argument for "${k.__yo_dup_array_element[0]}":
10321
10339
  ${w(r)}`});t=o.$.env;let a=S({expr:i,env:t,context:{...n}});if(!a.$)throw y({token:i.token,errorMessage:`Failed to evaluate the index argument for "${k.__yo_dup_array_element[0]}":
10322
- ${w(i)}`});t=a.$.env;let s=o.$.type;if(!s||!ke(s))throw y({token:r.token,errorMessage:`Expected array type for "${k.__yo_dup_array_element[0]}"`});let l=s.childType;return e.$={env:t,type:l,value:void 0,pathCollection:[]},e}function Jp({expr:e,env:t,context:n}){he(e,[k.__yo_drop_tuple_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the tuple argument for "${k.__yo_drop_tuple_element[0]}":
10340
+ ${w(i)}`});t=a.$.env;let s=o.$.type;if(!s||!ke(s))throw y({token:r.token,errorMessage:`Expected array type for "${k.__yo_dup_array_element[0]}"`});let l=s.childType;return e.$={env:t,type:l,value:void 0,pathCollection:[]},e}function ef({expr:e,env:t,context:n}){he(e,[k.__yo_drop_tuple_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the tuple argument for "${k.__yo_drop_tuple_element[0]}":
10323
10341
  ${w(r)}`});t=o.$.env;let a=S({expr:i,env:t,context:{...n}});if(!a.$)throw y({token:i.token,errorMessage:`Failed to evaluate the index argument for "${k.__yo_drop_tuple_element[0]}":
10324
- ${w(i)}`});return t=a.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function ef({expr:e,env:t,context:n}){he(e,[k.__yo_dup_tuple_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the tuple argument for "${k.__yo_dup_tuple_element[0]}":
10342
+ ${w(i)}`});return t=a.$.env,e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function tf({expr:e,env:t,context:n}){he(e,[k.__yo_dup_tuple_element[0]],2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the tuple argument for "${k.__yo_dup_tuple_element[0]}":
10325
10343
  ${w(r)}`});t=o.$.env;let a=S({expr:i,env:t,context:{...n}});if(!a.$)throw y({token:i.token,errorMessage:`Failed to evaluate the index argument for "${k.__yo_dup_tuple_element[0]}":
10326
- ${w(i)}`});t=a.$.env;let s=o.$.type;if(!s||!we(s))throw y({token:r.token,errorMessage:`Expected tuple type for "${k.__yo_dup_tuple_element[0]}"`});let l=a.$.value;if(!ze(l))throw y({token:i.token,errorMessage:`Expected number value for index in "${k.__yo_dup_tuple_element[0]}"`});let u=Number(l.value);if(u<0||u>=s.fields.length)throw y({token:i.token,errorMessage:`Index out of bounds for tuple in "${k.__yo_dup_tuple_element[0]}"`});let c=s.fields[u].type;return e.$={env:t,type:c,value:void 0,pathCollection:[]},e}function tf({expr:e,env:t,context:n}){he(e,k.downcast,2);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate dyn value argument for downcast."});t=i.$.env;let o=i.$.type;if(!o||!be(o))throw y({token:r.token,errorMessage:`downcast expects a Dyn type as first argument, got ${o?A(o):"unknown"}.`});let a=e.args[1],s=S({expr:a,env:t,context:{...n}});if(!s.$)throw y({token:a.token,errorMessage:"Failed to evaluate type argument for downcast."});if(t=s.$.env,!s.$.value||!O(s.$.value))throw y({token:a.token,errorMessage:`downcast expects a type as second argument, got ${s.$.type?A(s.$.type):"unknown"}.`});let l=s.$.value.value,{optionType:u,env:c}=Fl(l,t,n);t=c;let _=K(u,{env:t,context:n});return e.$={env:t,type:u,value:_,pathCollection:[]},Ge(e,!0),e}function Jo(e){if(e.result.kind!=="type")throw new Error("Expected type call result");return e.result.result}function nf(e){if(e.result.kind!=="module-type")throw new Error("Expected module type call result");return e.result.result}function rf(e){if(e.result.kind!=="trait-type")throw new Error("Expected trait type call result");return e.result.result}function of(e){if(e.result.kind!=="array")throw new Error("Expected array call result");return e.result.result}function ao(e,t,n,r,i){if(!i.isEvaluatingFunctionBodyOrAsyncBlock)return;let o;if(i.isEvaluatingFunctionBodyOrAsyncBlock&&(o=i.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv),!o||t>=o.frames.length)return;let a,s=-1;for(let c=0;c<o.frames.length;c++){let _=o.frames[c]?.variables.find(p=>p.name===e);if(_){a=_,s=c;break}}if(!a||s<0||a.isCompileTimeOnly)return;i.capturedVariables||(i.capturedVariables=new Map);let l=i.capturedVariables.get(e),u=l&&(l.usageType==="own"||l.usageType==="write"&&n==="read")?l.usageType:n;i.capturedVariables.set(e,{frameLevel:s,usageType:u,token:r})}function Dg(e){let t=e;if(F(t)&&E(t,"?=",2)&&(t=t.args[0]),F(t)&&E(t,"=",2)&&(t=t.args[0]),!F(t)||!E(t,":",2))return;let n=t.args[0],r=t.args[1];if(!F(n)||!E(n,I.comptime)||n.args.length!==1)return;let i=n.args[0];if(!(!z(i)||!je(i)))return{name:i.token.value,typeExpr:r,token:i.token}}function Ll({expr:e,env:t,context:n,isParameterComptimeByDefault:r,allowVariableShadowing:i}){let o,a=r,s=!1,l=!1,u,c,_,p,f,m=e,g,h,d,v;if(F(m)&&E(m,"=")){let N=m.args[0];if(N&&F(N)&&E(N,":",2))u=N,c=m.args[1],v=c,m=u;else throw y({token:m.func.token,errorMessage:'Use "?=" for default parameter values. Assigned values require an explicit type: (name : Type) = value.'})}if(F(m)&&E(m,":=",2))throw y({token:m.func.token,errorMessage:'":=" is not allowed in parameter lists. Use (name : Type) = value instead.'});if(F(m)&&E(m,"?=",2)&&(c=m.args[1],u=m.args[0],d=c,m=u),F(m)&&E(m,":",2)?(c=m.args[1],u=m.args[0],g=c):v?u=m:d?(g=void 0,u=m):g=m,!g)throw y({token:e.token,errorMessage:d?"Default parameters must specify a type: (name : Type) ?= value.":'Expected an explicit type annotation for function parameter. Use "(name : Type)".'});if(u){if(F(u)&&E(u,I.comptime)){if(r)throw y({token:u.token,errorMessage:'"forall"/"using" parameters are "comptime" by default. Not needed to use "comptime" modifier.'});if(a=!0,u.args.length!==1)throw y({token:u.token,errorMessage:`Expected one argument for "comptime" , got ${u.args.length}`});u=u.args[0]}if(F(u)&&E(u,"own")){if(l=!0,u.args.length!==1)throw y({token:u.token,errorMessage:`Expected one argument for "own", got ${u.args.length}`});u=u.args[0]}if(F(u)&&E(u,I.quote)){if(s=!0,u.args.length!==1)throw y({token:u.token,errorMessage:`Expected one argument for "quote" (or ":"), got ${u.args.length}`});if(a)throw y({token:u.token,errorMessage:'Cannot use "comptime" with "quote" (or ":"). "quote" parameters means compile-time only, so "comptime" is redundant.'});a=!0,u=u.args[0]}if(!z(u)||!je(u))throw y({token:u.token,errorMessage:`Expected identifier for parameter label, got ${w(u)}`});o=u.token.value,h=u}if(!o)throw y({token:e.token,errorMessage:`Expected a label for function parameter, got ${w(e)}`});if(o==="Self")throw y({token:h?.token??e.token,errorMessage:"Not allowed to use 'Self' as the label."});{if(v){let N=S({expr:v,env:t,context:{...n}});if(!N.$)throw y({token:v.token,errorMessage:`Failed to evaluate assigned value expression: ${w(v)}`});t=N.$.env;let B=N.$.value;if(!O(B))throw y({token:v.token,errorMessage:`Expected type value for = assignment, got ${Me(B)}`});if(_=tt(),f=B,!a)throw y({token:v.token,errorMessage:`Assigned value (=) is only allowed for compile-time parameters. Use "comptime(${o})" or put this in "forall(...)".`})}if(g){let N=S({expr:g,env:t,context:{...n}});if(!N.$)throw y({token:g.token,errorMessage:`(3) Failed to evaluate type expression: ${w(g)}`});t=N.$.env;let B=N.$.value;if(O(B))_=B.value;else throw y({token:g.token,errorMessage:`Expected type for function parameter, got ${Me(B)}`})}if(d){let N=S({expr:d,env:t,context:{...n}});if(N.$?.env&&(t=N.$?.env),p=N.$?.value,!p)throw y({token:d.token,errorMessage:`Expected a compile-time known value for default parameter, got ${w(d)}`});if(!_)_=p.type;else if(!Y({type:_,env:t},{type:p.type,env:t}))throw y({token:d.token,errorMessage:`Incompatible default value type:
10344
+ ${w(i)}`});t=a.$.env;let s=o.$.type;if(!s||!we(s))throw y({token:r.token,errorMessage:`Expected tuple type for "${k.__yo_dup_tuple_element[0]}"`});let l=a.$.value;if(!ze(l))throw y({token:i.token,errorMessage:`Expected number value for index in "${k.__yo_dup_tuple_element[0]}"`});let u=Number(l.value);if(u<0||u>=s.fields.length)throw y({token:i.token,errorMessage:`Index out of bounds for tuple in "${k.__yo_dup_tuple_element[0]}"`});let c=s.fields[u].type;return e.$={env:t,type:c,value:void 0,pathCollection:[]},e}function nf({expr:e,env:t,context:n}){he(e,k.downcast,2);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate dyn value argument for downcast."});t=i.$.env;let o=i.$.type;if(!o||!be(o))throw y({token:r.token,errorMessage:`downcast expects a Dyn type as first argument, got ${o?A(o):"unknown"}.`});let a=e.args[1],s=S({expr:a,env:t,context:{...n}});if(!s.$)throw y({token:a.token,errorMessage:"Failed to evaluate type argument for downcast."});if(t=s.$.env,!s.$.value||!O(s.$.value))throw y({token:a.token,errorMessage:`downcast expects a type as second argument, got ${s.$.type?A(s.$.type):"unknown"}.`});let l=s.$.value.value,{optionType:u,env:c}=Fl(l,t,n);t=c;let _=K(u,{env:t,context:n});return e.$={env:t,type:u,value:_,pathCollection:[]},Ge(e,!0),e}function Jo(e){if(e.result.kind!=="type")throw new Error("Expected type call result");return e.result.result}function rf(e){if(e.result.kind!=="module-type")throw new Error("Expected module type call result");return e.result.result}function of(e){if(e.result.kind!=="trait-type")throw new Error("Expected trait type call result");return e.result.result}function af(e){if(e.result.kind!=="array")throw new Error("Expected array call result");return e.result.result}function ao(e,t,n,r,i){if(!i.isEvaluatingFunctionBodyOrAsyncBlock)return;let o;if(i.isEvaluatingFunctionBodyOrAsyncBlock&&(o=i.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv),!o||t>=o.frames.length)return;let a,s=-1;for(let c=0;c<o.frames.length;c++){let _=o.frames[c]?.variables.find(p=>p.name===e);if(_){a=_,s=c;break}}if(!a||s<0||a.isCompileTimeOnly)return;i.capturedVariables||(i.capturedVariables=new Map);let l=i.capturedVariables.get(e),u=l&&(l.usageType==="own"||l.usageType==="write"&&n==="read")?l.usageType:n;i.capturedVariables.set(e,{frameLevel:s,usageType:u,token:r})}function Mg(e){let t=e;if(F(t)&&E(t,"?=",2)&&(t=t.args[0]),F(t)&&E(t,"=",2)&&(t=t.args[0]),!F(t)||!E(t,":",2))return;let n=t.args[0],r=t.args[1];if(!F(n)||!E(n,I.comptime)||n.args.length!==1)return;let i=n.args[0];if(!(!z(i)||!je(i)))return{name:i.token.value,typeExpr:r,token:i.token}}function Ll({expr:e,env:t,context:n,isParameterComptimeByDefault:r,allowVariableShadowing:i}){let o,a=r,s=!1,l=!1,u,c,_,p,f,m=e,g,h,d,v;if(F(m)&&E(m,"=")){let N=m.args[0];if(N&&F(N)&&E(N,":",2))u=N,c=m.args[1],v=c,m=u;else throw y({token:m.func.token,errorMessage:'Use "?=" for default parameter values. Assigned values require an explicit type: (name : Type) = value.'})}if(F(m)&&E(m,":=",2))throw y({token:m.func.token,errorMessage:'":=" is not allowed in parameter lists. Use (name : Type) = value instead.'});if(F(m)&&E(m,"?=",2)&&(c=m.args[1],u=m.args[0],d=c,m=u),F(m)&&E(m,":",2)?(c=m.args[1],u=m.args[0],g=c):v?u=m:d?(g=void 0,u=m):g=m,!g)throw y({token:e.token,errorMessage:d?"Default parameters must specify a type: (name : Type) ?= value.":'Expected an explicit type annotation for function parameter. Use "(name : Type)".'});if(u){if(F(u)&&E(u,I.comptime)){if(r)throw y({token:u.token,errorMessage:'"forall"/"using" parameters are "comptime" by default. Not needed to use "comptime" modifier.'});if(a=!0,u.args.length!==1)throw y({token:u.token,errorMessage:`Expected one argument for "comptime" , got ${u.args.length}`});u=u.args[0]}if(F(u)&&E(u,"own")){if(l=!0,u.args.length!==1)throw y({token:u.token,errorMessage:`Expected one argument for "own", got ${u.args.length}`});u=u.args[0]}if(F(u)&&E(u,I.quote)){if(s=!0,u.args.length!==1)throw y({token:u.token,errorMessage:`Expected one argument for "quote" (or ":"), got ${u.args.length}`});if(a)throw y({token:u.token,errorMessage:'Cannot use "comptime" with "quote" (or ":"). "quote" parameters means compile-time only, so "comptime" is redundant.'});a=!0,u=u.args[0]}if(!z(u)||!je(u))throw y({token:u.token,errorMessage:`Expected identifier for parameter label, got ${w(u)}`});o=u.token.value,h=u}if(!o)throw y({token:e.token,errorMessage:`Expected a label for function parameter, got ${w(e)}`});if(o==="Self")throw y({token:h?.token??e.token,errorMessage:"Not allowed to use 'Self' as the label."});{if(v){let N=S({expr:v,env:t,context:{...n}});if(!N.$)throw y({token:v.token,errorMessage:`Failed to evaluate assigned value expression: ${w(v)}`});t=N.$.env;let B=N.$.value;if(!O(B))throw y({token:v.token,errorMessage:`Expected type value for = assignment, got ${Me(B)}`});if(_=tt(),f=B,!a)throw y({token:v.token,errorMessage:`Assigned value (=) is only allowed for compile-time parameters. Use "comptime(${o})" or put this in "forall(...)".`})}if(g){let N=S({expr:g,env:t,context:{...n}});if(!N.$)throw y({token:g.token,errorMessage:`(3) Failed to evaluate type expression: ${w(g)}`});t=N.$.env;let B=N.$.value;if(O(B))_=B.value;else throw y({token:g.token,errorMessage:`Expected type for function parameter, got ${Me(B)}`})}if(d){let N=S({expr:d,env:t,context:{...n}});if(N.$?.env&&(t=N.$?.env),p=N.$?.value,!p)throw y({token:d.token,errorMessage:`Expected a compile-time known value for default parameter, got ${w(d)}`});if(!_)_=p.type;else if(!Y({type:_,env:t},{type:p.type,env:t}))throw y({token:d.token,errorMessage:`Incompatible default value type:
10327
10345
  - Expected: ${A(_)}
10328
10346
  - Got : ${A(p.type)}`})}if(!_)throw y({token:e.token,errorMessage:"Expected type for function parameter}"});if(a&&pr(_,t))throw y({token:u?.token??e.token,errorMessage:`Parameter marked as "comptime" but type is not available at compile-time:
10329
10347
  ${A(_)}`});if(!a&&_r(_,t))throw y({token:u?.token??e.token,errorMessage:`Parameter marked as runtime but type is not available at runtime:
@@ -10345,7 +10363,7 @@ use_id :: (fn(forall(T : Type),
10345
10363
  ) -> T) {
10346
10364
  return val.id();
10347
10365
  }
10348
- `});let $=X(t,o),C=$.length>0?$[$.length-1]:void 0,L=$.find(N=>{if(N.value&&O(N.value[0])){let B=N.value[0];if(x(B.value))return!0}return!1}),b=T,R=_;if(L){let N=L.value[0],B=N.value;if(f&&O(f)&&x(f.value)){let D=f.value,V=[...B.requiredTraits];for(let re of D.requiredTraits)V.some(j=>j.traitType.id===re.traitType.id)||V.push(re);let U=[...B.negativeTraits??[]];if(D.negativeTraits)for(let re of D.negativeTraits)U.some(j=>j.traitType.id===re.traitType.id)||U.push(re);B.requiredTraits=V,B.negativeTraits=U}b=N,R=wt(B)}else if(C&&C.isCompileTimeOnly&&C.value&&C.frameLevel===t.frames.length-1)b=C.value[0],R=C.type;else{let{env:N}=me({env:t,variable:{name:o,type:_,isCompileTimeOnly:a,value:f?[f]:a?[K(_,{variableName:o,env:t,context:n})]:void 0,token:u?.token??e.token,initializedAtToken:u?.token??e.token,consumedAtToken:void 0,isOwningTheRcValue:l,isOwningTheSameRcValueAs:void 0,isReassignable:!1},allowVariableShadowing:i});t=N}return u&&(u.$={env:t,type:R,value:b,pathCollection:[]}),u!==e&&g!==e&&(e.$={env:t,type:H.type,value:H,pathCollection:[]}),bt(_),{parameter:{label:o,type:_,exprs:fi({expr:e,labelExpr:h,typeExpr:g,defaultValueExpr:d,assignedValueExpr:v}),isCompileTimeOnly:a,isQuote:s,isOwningTheRcValue:l,isImplicit:!1,assignedValue:f},env:t}}function Mg({constraintExprs:e,env:t,context:n}){let r=[];for(let i of e){if(!F(i)||!E(i,"<:",2))continue;let o=i.args[0];if(z(o)){let s=o.token.value;if(X(t,s).length===0){let u=bn(tt(),s,{env:t,context:n}),c=ee(u),{env:_}=me({env:t,variable:{name:s,type:wt(u),isCompileTimeOnly:!0,value:[c],token:o.token,initializedAtToken:o.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=_,o.$={env:t,type:wt(u),value:c,pathCollection:[]}}}let a=Al({constraintExprs:[i],env:t,context:n,collectPendingTraits:!0});t=a.env,r.push(...a.pendingTraits)}return{env:t,pendingConstraints:r}}function af({pendingConstraints:e,env:t,context:n}){let r=[];for(let i of e){let o=Og({lhsExpr:i.lhsExpr,traitExpr:i.traitExpr,originalConstraintExpr:i.originalConstraintExpr,env:t,context:n});t=o.env,o.success||r.push(i)}return{env:t,pendingConstraints:r}}function sf({concreteType:e,traitExpr:t,isNegated:n,constraintExpr:r,env:i,context:o}){let a;try{a=S({expr:t,env:i,context:{...o}})}catch{return{env:i,success:!1}}if(!a.$||!a.$.value||!O(a.$.value))return{env:i,success:!1};i=a.$.env;let s=a.$.value;if(!De(s.value))throw y({token:t.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(s.value)}`});let l=s.value,u=St({targetType:e,traitType:l,env:i});if(n){if(u)throw y({token:r.token,errorMessage:`Type ${A(e)} must NOT implement ${A(l)}, but it does.`})}else if(!u)throw y({token:r.token,errorMessage:`Type ${A(e)} does not implement required trait ${A(l)}.`});return{env:i,success:!0}}function Og({lhsExpr:e,traitExpr:t,originalConstraintExpr:n,env:r,context:i}){let o=!1,a=t;F(t)&&E(t,"!")&&t.args.length===1&&(o=!0,a=t.args[0]);let s;if(z(e)){let _=e.token.value,p=X(r,_);if(p.length===0)return{env:r,success:!1};let f=p[p.length-1];if(f.value&&O(f.value[0])&&x(f.value[0].value))s=f.value[0].value;else if(f.value&&O(f.value[0]))try{return sf({concreteType:f.value[0].value,traitExpr:a,isNegated:o,constraintExpr:n,env:r,context:i})}catch{return{env:r,success:!1}}else return{env:r,success:!1}}else{let _;try{_=S({expr:e,env:r,context:{...i}})}catch{return{env:r,success:!1}}if(!_.$||!_.$.value||!O(_.$.value))return{env:r,success:!1};r=_.$.env;let p=_.$.value;if(!x(p.value))try{return sf({concreteType:p.value,traitExpr:a,isNegated:o,constraintExpr:n,env:r,context:i})}catch{return{env:r,success:!1}}s=p.value}let l;try{l=S({expr:a,env:r,context:{...i}})}catch{return{env:r,success:!1}}if(!l.$||!l.$.value||!O(l.$.value))return{env:r,success:!1};r=l.$.env;let u=l.$.value;if(!De(u.value))throw y({token:a.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(u.value)}`});let c=u.value;if(c.receiverType)throw y({token:a.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});return r=er({env:r,someType:s,traitType:c,isNegated:o}),{env:r,success:!0}}function Al({constraintExprs:e,env:t,context:n,collectPendingTraits:r=!1}){let i=[];for(let o of e){if(!F(o)||!E(o,"<:",2))throw y({token:o.token,errorMessage:`Expected constraint in the form "T <: Trait" or "T <: (Trait1, Trait2)", got: ${w(o)}`});let a=o.args[0],s=o.args[1],l;if(z(a)){let c=a.token.value,_=X(t,c);if(_.length>0){let p=_[_.length-1];if(p.value&&O(p.value[0])&&x(p.value[0].value))l=p.value[0].value;else if(p.value&&O(p.value[0])){let f=p.value[0].value;t=lf({concreteType:f,rhsExpr:s,constraintExpr:o,env:t,context:n});continue}else throw y({token:a.token,errorMessage:`Expected type for left-hand side of where clause constraint, got variable "${c}".`})}else{l=bn(tt(),c,{env:t,context:n});let p=ee(l),{env:f}=me({env:t,variable:{name:c,type:wt(l),isCompileTimeOnly:!0,value:[p],token:a.token,initializedAtToken:a.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=f,a.$={env:t,type:wt(l),value:p,pathCollection:[]}}}else{let c=S({expr:a,env:t,context:{...n}});if(!c.$||!c.$.value||!O(c.$.value))throw y({token:a.token,errorMessage:"Expected type for left-hand side of where clause constraint."});t=c.$.env;let _=c.$.value;if(!x(_.value)){t=lf({concreteType:_.value,rhsExpr:s,constraintExpr:o,env:t,context:n});continue}l=_.value}let u=[];F(s)&&E(s,I.tuple)?u.push(...s.args):u.push(s);for(let c=0;c<u.length;c++){let _=u[c],p=!1,f=_;F(_)&&E(_,"!")&&_.args.length===1&&(p=!0,f=_.args[0]);let m;try{m=S({expr:f,env:t,context:{...n}})}catch(d){if(r){i.push({lhsExpr:a,traitExpr:_,originalConstraintExpr:o});continue}throw d}if(!m.$||!m.$.value||!O(m.$.value)){if(r){i.push({lhsExpr:a,traitExpr:_,originalConstraintExpr:o});continue}throw y({token:f.token,errorMessage:"Expected trait type for right-hand side of where clause constraint."})}t=m.$.env;let g=m.$.value;if(!De(g.value))throw y({token:f.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(g.value)}`});let h=g.value;if(h.receiverType)throw y({token:f.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});t=er({env:t,someType:l,traitType:h,isNegated:p})}}return{env:t,pendingTraits:i}}function Hr({constraintExprs:e,env:t,context:n}){return e.length===0?{env:t}:{env:Al({constraintExprs:e,env:t,context:n,collectPendingTraits:!1}).env}}function lf({concreteType:e,rhsExpr:t,constraintExpr:n,env:r,context:i}){let o=[];if(F(t)&&E(t,I.tuple))for(let a of t.args)F(a)&&E(a,"!")&&a.args.length===1?o.push({expr:a.args[0],isNegated:!0}):o.push({expr:a,isNegated:!1});else F(t)&&E(t,"!")&&t.args.length===1?o.push({expr:t.args[0],isNegated:!0}):o.push({expr:t,isNegated:!1});for(let{expr:a,isNegated:s}of o){let l=S({expr:a,env:r,context:{...i}});if(!l.$||!l.$.value||!O(l.$.value))throw y({token:a.token,errorMessage:"Expected trait type for right-hand side of where clause constraint."});r=l.$.env;let u=l.$.value;if(!De(u.value))throw y({token:a.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(u.value)}`});let c=u.value,_=St({targetType:e,traitType:c,env:r});if(s){if(_)throw y({token:n.token,errorMessage:`Type ${A(e)} must NOT implement ${A(c)}, but it does.`})}else if(!_)throw y({token:n.token,errorMessage:`Type ${A(e)} does not implement required trait ${A(c)}.`})}return r}function Il({parameterExprs:e,env:t,context:n}){t=Pe(t);let r=[],i=[],o=[],a,s,l=!1;if(e.length>0){let p=e[0];if(F(p)&&E(p,I.forall)){let f=p.args;for(let m=0;m<f.length;m++){let g=f[m];if(F(g)&&E(g,"...")&&g.args.length===1&&z(g.args[0])){let T=g.args[0].token.value;if(i.find(N=>N.label===T))throw y({token:g.token,errorMessage:`Duplicate label "${T}" in type parameter`});let C=pi(T,t),L=gn(1),{env:b}=me({env:t,variable:{name:T,type:L,isCompileTimeOnly:!0,value:[ee(C)],token:g.args[0].token,initializedAtToken:g.args[0].token,consumedAtToken:void 0,isOwningTheRcValue:!1}});t=b,g.$={env:t,type:L,value:ee(C),pathCollection:[]};let R={label:T,type:L,isCompileTimeOnly:!0,isQuote:!1,isOwningTheRcValue:!1,isImplicit:!1,isEffectRowSpread:!1,exprs:fi({expr:g,labelExpr:g.args[0],typeExpr:g.args[0],defaultValueExpr:void 0,assignedValueExpr:void 0})};i.push(R);continue}let{parameter:h,env:d}=Ll({expr:g,env:t,context:{...n},isParameterComptimeByDefault:!0,allowVariableShadowing:!0});if(i.find(T=>T.label===h.label))throw y({token:g.token,errorMessage:`Duplicate label "${h.label}" in type parameter`});i.push(h),t=d}}}let u=0;for(let p=0;p<e.length;p++){let f=e[p];if(F(f)&&E(f,I.using)){if(u++,u>1)throw y({token:f.token,errorMessage:'Only one "using(...)" clause is allowed per function signature. Combine all implicit parameters into a single using(), e.g.: using(a : TypeA, b : TypeB)'});let m=f.args;for(let g=0;g<m.length;g++){let h=m[g];if(F(h)&&E(h,"...")&&h.args.length===1&&z(h.args[0])){let N=h.args[0].token.value,D=X(t,N).at(-1);if(!D)throw y({token:h.token,errorMessage:`Effect row variable "${N}" not found in scope. Declare it with forall(..., ...(${N}))`});let V,U=D.value?.[0];if(U&&O(U)&&ot(U.value)){let j=U.value;for(let W of j.implicitParameters)o.push({...W,isEffectRowSpread:!1});continue}else if(U&&O(U)){if(!(x(U.value)&&U.value.isEffectsRow||ot(U.value)))throw y({token:h.token,errorMessage:`"...(${N})" requires "${N}" to be a forall-declared effect row variable, but it resolves to a concrete type. Use individual effect types directly in using(), e.g. using(name : ${N}) instead of using(...(${N}))`});V=U.value}else if(U&&de(U)&&ot(U.type)){let j=U.type;for(let W of j.implicitParameters)o.push({...W,isEffectRowSpread:!1});continue}else if(U&&de(U))V=pi(N,t);else throw y({token:h.token,errorMessage:`Effect row variable "${N}" has invalid value. Expected a type.`});let re={label:N,type:V,isCompileTimeOnly:!0,isImplicit:!0,isEffectRowSpread:!0,isQuote:!1,isOwningTheRcValue:!1,exprs:fi({expr:h,labelExpr:h.args[0],typeExpr:h.args[0],defaultValueExpr:void 0,assignedValueExpr:void 0})};o.push(re);continue}if(!(F(h)&&(E(h,":")||E(h,"=")||E(h,"?=")||E(h,":="))))throw y({token:h.token,errorMessage:'Implicit parameter requires a label. Use "using(name : Type)" instead of "using(Type)".'});let{parameter:v,env:T}=Ll({expr:h,env:t,context:{...n},isParameterComptimeByDefault:!0,allowVariableShadowing:!0});if(i.find(N=>N.label===v.label))throw y({token:h.token,errorMessage:`Duplicate label "${v.label}" in implicit parameter (already in forall)`});if(o.find(N=>N.label===v.label))throw y({token:h.token,errorMessage:`Duplicate label "${v.label}" in implicit parameter`});let L={...v,isCompileTimeOnly:!0,isImplicit:!0};o.push(L);let R=T.frames[T.frames.length-1].variables.find(N=>N.name===v.label);R&&(R.isImplicit=!0),t=T}}}let c=new Set;for(let p=0;p<e.length;p++){let f=e[p];if(F(f)&&(E(f,I.forall)||E(f,I.using)||E(f,I.where)||E(f,"...")))continue;let m=Dg(f);if(m){let g=S({expr:m.typeExpr,env:t,context:{...n}});if(g.$?.env&&(t=g.$.env),!g.$||!g.$.value||!O(g.$.value))continue;let h=g.$.value.value,d=K(h,{variableName:m.name,env:t,context:n}),{env:v}=me({env:t,variable:{name:m.name,type:h,isCompileTimeOnly:!0,value:[d],token:m.token,initializedAtToken:m.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=v,c.add(p)}}let _=[];if(e.length>0){let p=e[e.length-1];if(F(p)&&E(p,I.where)){if(s=p.args,s.length===0)throw y({token:p.token,errorMessage:"The where clause must have at least one constraint."});let f=Mg({constraintExprs:s,env:t,context:n});t=f.env,_=f.pendingConstraints}}for(let p=0;p<e.length;p++){let f=e[p];if(F(f)&&E(f,I.forall)){if(p!==0)throw y({token:f.token,errorMessage:`Expected type parameters to be the first argument, got ${p+1}`});continue}else{if(F(f)&&E(f,I.using))continue;if(F(f)&&E(f,I.where)){if(p!==e.length-1)throw y({token:f.token,errorMessage:"The where clause must be the last parameter in the function signature."});continue}else if(z(f)&&dt(f,"...")||F(f)&&E(f,"...")){l=!0;let m=!1,g=!1,h="...",d=f,v=H.type;if(F(f)){let C=f.args[0];if(C){if(F(C)&&E(C,I.comptime))throw m=!0,C.args.length!==1?y({token:C.token,errorMessage:`Expected one argument for "comptime" , got ${C.args.length}`}):(d=C.args[0],h=C.args[0].token.value,v=H.type,y({token:C.token,errorMessage:"...(comptime(param_name)) is not supported yet."}));if(F(C)&&E(C,I.quote)){if(m=!0,g=!0,C.args.length!==1)throw y({token:C.token,errorMessage:`Expected one argument for "quote" (or ":"), got ${C.args.length}`});d=C.args[0],h=C.args[0].token.value,v=xo()}else throw je(C)?(d=C,h=C.token.value,v=H.type,y({token:C.token,errorMessage:"...(param_name) is not supported yet."})):y({token:C.token,errorMessage:`Expected a valid variable name for variadic parameter, got ${w(C)}`})}else throw y({token:f.token,errorMessage:`Expected a name for variadic parameter, got ${w(f)}`})}else v=H.type;let T=Jt(A(v)),$={exprs:{expr:f,labelExpr:d,typeExpr:T},isCompileTimeOnly:m,isQuote:g,label:h,type:v,isOwningTheRcValue:!1,isImplicit:!1};if(a=$,h!=="..."){let{env:C}=me({env:t,variable:{name:h,type:v,isCompileTimeOnly:$.isCompileTimeOnly,value:m?[K(v,{variableName:h,env:t,context:n})]:void 0,token:d.token,initializedAtToken:d.token,consumedAtToken:void 0,isOwningTheRcValue:$.isOwningTheRcValue,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=C,d.$={env:t,type:v,value:m?K(v,{variableName:h,env:t,context:n}):void 0,pathCollection:[]}}}else{if(l)throw y({token:f.token,errorMessage:"Expected variadic parameter to be the last parameter before the normal parameters."});let{parameter:m,env:g}=Ll({expr:f,env:t,context:{...n},isParameterComptimeByDefault:!1,allowVariableShadowing:!0});if(r.find(d=>d.label===m.label))throw y({token:F(f)?f.args[0]?.token??f.token:f.token,errorMessage:`Duplicate label "${m.label}" in function parameter`});if(r.push(m),t=g,_.length>0){let d=af({pendingConstraints:_,env:t,context:n});t=d.env,_=d.pendingConstraints}}}}if(r.forEach((p,f)=>{if(p.isQuote&&Zr(p.type)&&f!==r.length-1)throw y({token:p.exprs.expr.token,errorMessage:"Expected ExprList type to be the last parameter."})}),_.length>0){let p=af({pendingConstraints:_,env:t,context:n});if(t=p.env,p.pendingConstraints.length>0){let f=p.pendingConstraints[0];Al({constraintExprs:[f.originalConstraintExpr],env:t,context:n,collectPendingTraits:!1})}}return{parameters:r,forallParameters:i,implicitParameters:o,variadicParameter:a,whereClauseExprs:s,env:t}}function qa({expr:e,env:t,context:n}){if(!E(e,"->",2))throw y({token:e.token,errorMessage:`Expected -> for function type, got:
10366
+ `});let $=X(t,o),C=$.length>0?$[$.length-1]:void 0,L=$.find(N=>{if(N.value&&O(N.value[0])){let B=N.value[0];if(x(B.value))return!0}return!1}),b=T,R=_;if(L){let N=L.value[0],B=N.value;if(f&&O(f)&&x(f.value)){let D=f.value,V=[...B.requiredTraits];for(let re of D.requiredTraits)V.some(j=>j.traitType.id===re.traitType.id)||V.push(re);let U=[...B.negativeTraits??[]];if(D.negativeTraits)for(let re of D.negativeTraits)U.some(j=>j.traitType.id===re.traitType.id)||U.push(re);B.requiredTraits=V,B.negativeTraits=U}b=N,R=Ft(B)}else if(C&&C.isCompileTimeOnly&&C.value&&C.frameLevel===t.frames.length-1)b=C.value[0],R=C.type;else{let{env:N}=me({env:t,variable:{name:o,type:_,isCompileTimeOnly:a,value:f?[f]:a?[K(_,{variableName:o,env:t,context:n})]:void 0,token:u?.token??e.token,initializedAtToken:u?.token??e.token,consumedAtToken:void 0,isOwningTheRcValue:l,isOwningTheSameRcValueAs:void 0,isReassignable:!1},allowVariableShadowing:i});t=N}return u&&(u.$={env:t,type:R,value:b,pathCollection:[]}),u!==e&&g!==e&&(e.$={env:t,type:H.type,value:H,pathCollection:[]}),kt(_),{parameter:{label:o,type:_,exprs:fi({expr:e,labelExpr:h,typeExpr:g,defaultValueExpr:d,assignedValueExpr:v}),isCompileTimeOnly:a,isQuote:s,isOwningTheRcValue:l,isImplicit:!1,assignedValue:f},env:t}}function Og({constraintExprs:e,env:t,context:n}){let r=[];for(let i of e){if(!F(i)||!E(i,"<:",2))continue;let o=i.args[0];if(z(o)){let s=o.token.value;if(X(t,s).length===0){let u=bn(tt(),s,{env:t,context:n}),c=ee(u),{env:_}=me({env:t,variable:{name:s,type:Ft(u),isCompileTimeOnly:!0,value:[c],token:o.token,initializedAtToken:o.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=_,o.$={env:t,type:Ft(u),value:c,pathCollection:[]}}}let a=Al({constraintExprs:[i],env:t,context:n,collectPendingTraits:!0});t=a.env,r.push(...a.pendingTraits)}return{env:t,pendingConstraints:r}}function sf({pendingConstraints:e,env:t,context:n}){let r=[];for(let i of e){let o=Rg({lhsExpr:i.lhsExpr,traitExpr:i.traitExpr,originalConstraintExpr:i.originalConstraintExpr,env:t,context:n});t=o.env,o.success||r.push(i)}return{env:t,pendingConstraints:r}}function lf({concreteType:e,traitExpr:t,isNegated:n,constraintExpr:r,env:i,context:o}){let a;try{a=S({expr:t,env:i,context:{...o}})}catch{return{env:i,success:!1}}if(!a.$||!a.$.value||!O(a.$.value))return{env:i,success:!1};i=a.$.env;let s=a.$.value;if(!De(s.value))throw y({token:t.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(s.value)}`});let l=s.value,u=St({targetType:e,traitType:l,env:i});if(n){if(u)throw y({token:r.token,errorMessage:`Type ${A(e)} must NOT implement ${A(l)}, but it does.`})}else if(!u)throw y({token:r.token,errorMessage:`Type ${A(e)} does not implement required trait ${A(l)}.`});return{env:i,success:!0}}function Rg({lhsExpr:e,traitExpr:t,originalConstraintExpr:n,env:r,context:i}){let o=!1,a=t;F(t)&&E(t,"!")&&t.args.length===1&&(o=!0,a=t.args[0]);let s;if(z(e)){let _=e.token.value,p=X(r,_);if(p.length===0)return{env:r,success:!1};let f=p[p.length-1];if(f.value&&O(f.value[0])&&x(f.value[0].value))s=f.value[0].value;else if(f.value&&O(f.value[0]))try{return lf({concreteType:f.value[0].value,traitExpr:a,isNegated:o,constraintExpr:n,env:r,context:i})}catch{return{env:r,success:!1}}else return{env:r,success:!1}}else{let _;try{_=S({expr:e,env:r,context:{...i}})}catch{return{env:r,success:!1}}if(!_.$||!_.$.value||!O(_.$.value))return{env:r,success:!1};r=_.$.env;let p=_.$.value;if(!x(p.value))try{return lf({concreteType:p.value,traitExpr:a,isNegated:o,constraintExpr:n,env:r,context:i})}catch{return{env:r,success:!1}}s=p.value}let l;try{l=S({expr:a,env:r,context:{...i}})}catch{return{env:r,success:!1}}if(!l.$||!l.$.value||!O(l.$.value))return{env:r,success:!1};r=l.$.env;let u=l.$.value;if(!De(u.value))throw y({token:a.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(u.value)}`});let c=u.value;if(c.receiverType)throw y({token:a.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});return r=er({env:r,someType:s,traitType:c,isNegated:o}),{env:r,success:!0}}function Al({constraintExprs:e,env:t,context:n,collectPendingTraits:r=!1}){let i=[];for(let o of e){if(!F(o)||!E(o,"<:",2))throw y({token:o.token,errorMessage:`Expected constraint in the form "T <: Trait" or "T <: (Trait1, Trait2)", got: ${w(o)}`});let a=o.args[0],s=o.args[1],l;if(z(a)){let c=a.token.value,_=X(t,c);if(_.length>0){let p=_[_.length-1];if(p.value&&O(p.value[0])&&x(p.value[0].value))l=p.value[0].value;else if(p.value&&O(p.value[0])){let f=p.value[0].value;t=uf({concreteType:f,rhsExpr:s,constraintExpr:o,env:t,context:n});continue}else throw y({token:a.token,errorMessage:`Expected type for left-hand side of where clause constraint, got variable "${c}".`})}else{l=bn(tt(),c,{env:t,context:n});let p=ee(l),{env:f}=me({env:t,variable:{name:c,type:Ft(l),isCompileTimeOnly:!0,value:[p],token:a.token,initializedAtToken:a.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=f,a.$={env:t,type:Ft(l),value:p,pathCollection:[]}}}else{let c=S({expr:a,env:t,context:{...n}});if(!c.$||!c.$.value||!O(c.$.value))throw y({token:a.token,errorMessage:"Expected type for left-hand side of where clause constraint."});t=c.$.env;let _=c.$.value;if(!x(_.value)){t=uf({concreteType:_.value,rhsExpr:s,constraintExpr:o,env:t,context:n});continue}l=_.value}let u=[];F(s)&&E(s,I.tuple)?u.push(...s.args):u.push(s);for(let c=0;c<u.length;c++){let _=u[c],p=!1,f=_;F(_)&&E(_,"!")&&_.args.length===1&&(p=!0,f=_.args[0]);let m;try{m=S({expr:f,env:t,context:{...n}})}catch(d){if(r){i.push({lhsExpr:a,traitExpr:_,originalConstraintExpr:o});continue}throw d}if(!m.$||!m.$.value||!O(m.$.value)){if(r){i.push({lhsExpr:a,traitExpr:_,originalConstraintExpr:o});continue}throw y({token:f.token,errorMessage:"Expected trait type for right-hand side of where clause constraint."})}t=m.$.env;let g=m.$.value;if(!De(g.value))throw y({token:f.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(g.value)}`});let h=g.value;if(h.receiverType)throw y({token:f.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});t=er({env:t,someType:l,traitType:h,isNegated:p})}}return{env:t,pendingTraits:i}}function Hr({constraintExprs:e,env:t,context:n}){return e.length===0?{env:t}:{env:Al({constraintExprs:e,env:t,context:n,collectPendingTraits:!1}).env}}function uf({concreteType:e,rhsExpr:t,constraintExpr:n,env:r,context:i}){let o=[];if(F(t)&&E(t,I.tuple))for(let a of t.args)F(a)&&E(a,"!")&&a.args.length===1?o.push({expr:a.args[0],isNegated:!0}):o.push({expr:a,isNegated:!1});else F(t)&&E(t,"!")&&t.args.length===1?o.push({expr:t.args[0],isNegated:!0}):o.push({expr:t,isNegated:!1});for(let{expr:a,isNegated:s}of o){let l=S({expr:a,env:r,context:{...i}});if(!l.$||!l.$.value||!O(l.$.value))throw y({token:a.token,errorMessage:"Expected trait type for right-hand side of where clause constraint."});r=l.$.env;let u=l.$.value;if(!De(u.value))throw y({token:a.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(u.value)}`});let c=u.value,_=St({targetType:e,traitType:c,env:r});if(s){if(_)throw y({token:n.token,errorMessage:`Type ${A(e)} must NOT implement ${A(c)}, but it does.`})}else if(!_)throw y({token:n.token,errorMessage:`Type ${A(e)} does not implement required trait ${A(c)}.`})}return r}function Il({parameterExprs:e,env:t,context:n}){t=Pe(t);let r=[],i=[],o=[],a,s,l=!1;if(e.length>0){let p=e[0];if(F(p)&&E(p,I.forall)){let f=p.args;for(let m=0;m<f.length;m++){let g=f[m];if(F(g)&&E(g,"...")&&g.args.length===1&&z(g.args[0])){let T=g.args[0].token.value;if(i.find(N=>N.label===T))throw y({token:g.token,errorMessage:`Duplicate label "${T}" in type parameter`});let C=pi(T,t),L=gn(1),{env:b}=me({env:t,variable:{name:T,type:L,isCompileTimeOnly:!0,value:[ee(C)],token:g.args[0].token,initializedAtToken:g.args[0].token,consumedAtToken:void 0,isOwningTheRcValue:!1}});t=b,g.$={env:t,type:L,value:ee(C),pathCollection:[]};let R={label:T,type:L,isCompileTimeOnly:!0,isQuote:!1,isOwningTheRcValue:!1,isImplicit:!1,isEffectRowSpread:!1,exprs:fi({expr:g,labelExpr:g.args[0],typeExpr:g.args[0],defaultValueExpr:void 0,assignedValueExpr:void 0})};i.push(R);continue}let{parameter:h,env:d}=Ll({expr:g,env:t,context:{...n},isParameterComptimeByDefault:!0,allowVariableShadowing:!0});if(i.find(T=>T.label===h.label))throw y({token:g.token,errorMessage:`Duplicate label "${h.label}" in type parameter`});i.push(h),t=d}}}let u=0;for(let p=0;p<e.length;p++){let f=e[p];if(F(f)&&E(f,I.using)){if(u++,u>1)throw y({token:f.token,errorMessage:'Only one "using(...)" clause is allowed per function signature. Combine all implicit parameters into a single using(), e.g.: using(a : TypeA, b : TypeB)'});let m=f.args;for(let g=0;g<m.length;g++){let h=m[g];if(F(h)&&E(h,"...")&&h.args.length===1&&z(h.args[0])){let N=h.args[0].token.value,D=X(t,N).at(-1);if(!D)throw y({token:h.token,errorMessage:`Effect row variable "${N}" not found in scope. Declare it with forall(..., ...(${N}))`});let V,U=D.value?.[0];if(U&&O(U)&&ot(U.value)){let j=U.value;for(let W of j.implicitParameters)o.push({...W,isEffectRowSpread:!1});continue}else if(U&&O(U)){if(!(x(U.value)&&U.value.isEffectsRow||ot(U.value)))throw y({token:h.token,errorMessage:`"...(${N})" requires "${N}" to be a forall-declared effect row variable, but it resolves to a concrete type. Use individual effect types directly in using(), e.g. using(name : ${N}) instead of using(...(${N}))`});V=U.value}else if(U&&de(U)&&ot(U.type)){let j=U.type;for(let W of j.implicitParameters)o.push({...W,isEffectRowSpread:!1});continue}else if(U&&de(U))V=pi(N,t);else throw y({token:h.token,errorMessage:`Effect row variable "${N}" has invalid value. Expected a type.`});let re={label:N,type:V,isCompileTimeOnly:!0,isImplicit:!0,isEffectRowSpread:!0,isQuote:!1,isOwningTheRcValue:!1,exprs:fi({expr:h,labelExpr:h.args[0],typeExpr:h.args[0],defaultValueExpr:void 0,assignedValueExpr:void 0})};o.push(re);continue}if(!(F(h)&&(E(h,":")||E(h,"=")||E(h,"?=")||E(h,":="))))throw y({token:h.token,errorMessage:'Implicit parameter requires a label. Use "using(name : Type)" instead of "using(Type)".'});let{parameter:v,env:T}=Ll({expr:h,env:t,context:{...n},isParameterComptimeByDefault:!0,allowVariableShadowing:!0});if(i.find(N=>N.label===v.label))throw y({token:h.token,errorMessage:`Duplicate label "${v.label}" in implicit parameter (already in forall)`});if(o.find(N=>N.label===v.label))throw y({token:h.token,errorMessage:`Duplicate label "${v.label}" in implicit parameter`});let L={...v,isCompileTimeOnly:!0,isImplicit:!0};o.push(L);let R=T.frames[T.frames.length-1].variables.find(N=>N.name===v.label);R&&(R.isImplicit=!0),t=T}}}let c=new Set;for(let p=0;p<e.length;p++){let f=e[p];if(F(f)&&(E(f,I.forall)||E(f,I.using)||E(f,I.where)||E(f,"...")))continue;let m=Mg(f);if(m){let g=S({expr:m.typeExpr,env:t,context:{...n}});if(g.$?.env&&(t=g.$.env),!g.$||!g.$.value||!O(g.$.value))continue;let h=g.$.value.value,d=K(h,{variableName:m.name,env:t,context:n}),{env:v}=me({env:t,variable:{name:m.name,type:h,isCompileTimeOnly:!0,value:[d],token:m.token,initializedAtToken:m.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=v,c.add(p)}}let _=[];if(e.length>0){let p=e[e.length-1];if(F(p)&&E(p,I.where)){if(s=p.args,s.length===0)throw y({token:p.token,errorMessage:"The where clause must have at least one constraint."});let f=Og({constraintExprs:s,env:t,context:n});t=f.env,_=f.pendingConstraints}}for(let p=0;p<e.length;p++){let f=e[p];if(F(f)&&E(f,I.forall)){if(p!==0)throw y({token:f.token,errorMessage:`Expected type parameters to be the first argument, got ${p+1}`});continue}else{if(F(f)&&E(f,I.using))continue;if(F(f)&&E(f,I.where)){if(p!==e.length-1)throw y({token:f.token,errorMessage:"The where clause must be the last parameter in the function signature."});continue}else if(z(f)&&dt(f,"...")||F(f)&&E(f,"...")){l=!0;let m=!1,g=!1,h="...",d=f,v=H.type;if(F(f)){let C=f.args[0];if(C){if(F(C)&&E(C,I.comptime))throw m=!0,C.args.length!==1?y({token:C.token,errorMessage:`Expected one argument for "comptime" , got ${C.args.length}`}):(d=C.args[0],h=C.args[0].token.value,v=H.type,y({token:C.token,errorMessage:"...(comptime(param_name)) is not supported yet."}));if(F(C)&&E(C,I.quote)){if(m=!0,g=!0,C.args.length!==1)throw y({token:C.token,errorMessage:`Expected one argument for "quote" (or ":"), got ${C.args.length}`});d=C.args[0],h=C.args[0].token.value,v=xo()}else throw je(C)?(d=C,h=C.token.value,v=H.type,y({token:C.token,errorMessage:"...(param_name) is not supported yet."})):y({token:C.token,errorMessage:`Expected a valid variable name for variadic parameter, got ${w(C)}`})}else throw y({token:f.token,errorMessage:`Expected a name for variadic parameter, got ${w(f)}`})}else v=H.type;let T=Jt(A(v)),$={exprs:{expr:f,labelExpr:d,typeExpr:T},isCompileTimeOnly:m,isQuote:g,label:h,type:v,isOwningTheRcValue:!1,isImplicit:!1};if(a=$,h!=="..."){let{env:C}=me({env:t,variable:{name:h,type:v,isCompileTimeOnly:$.isCompileTimeOnly,value:m?[K(v,{variableName:h,env:t,context:n})]:void 0,token:d.token,initializedAtToken:d.token,consumedAtToken:void 0,isOwningTheRcValue:$.isOwningTheRcValue,isOwningTheSameRcValueAs:void 0,isReassignable:!1}});t=C,d.$={env:t,type:v,value:m?K(v,{variableName:h,env:t,context:n}):void 0,pathCollection:[]}}}else{if(l)throw y({token:f.token,errorMessage:"Expected variadic parameter to be the last parameter before the normal parameters."});let{parameter:m,env:g}=Ll({expr:f,env:t,context:{...n},isParameterComptimeByDefault:!1,allowVariableShadowing:!0});if(r.find(d=>d.label===m.label))throw y({token:F(f)?f.args[0]?.token??f.token:f.token,errorMessage:`Duplicate label "${m.label}" in function parameter`});if(r.push(m),t=g,_.length>0){let d=sf({pendingConstraints:_,env:t,context:n});t=d.env,_=d.pendingConstraints}}}}if(r.forEach((p,f)=>{if(p.isQuote&&Zr(p.type)&&f!==r.length-1)throw y({token:p.exprs.expr.token,errorMessage:"Expected ExprList type to be the last parameter."})}),_.length>0){let p=sf({pendingConstraints:_,env:t,context:n});if(t=p.env,p.pendingConstraints.length>0){let f=p.pendingConstraints[0];Al({constraintExprs:[f.originalConstraintExpr],env:t,context:n,collectPendingTraits:!1})}}return{parameters:r,forallParameters:i,implicitParameters:o,variadicParameter:a,whereClauseExprs:s,env:t}}function qa({expr:e,env:t,context:n}){if(!E(e,"->",2))throw y({token:e.token,errorMessage:`Expected -> for function type, got:
10349
10367
  ${w(e)}
10350
10368
 
10351
10369
  Note: For closures, use Impl(Fn(...) -> ...) syntax.`});let r=e.args[0],i=e.args[1],o=[];if(F(r)&&(E(r,I.fn)||E(r,I.unsafe_fn)))o=r.args;else throw y({token:r.token,errorMessage:`Expected a "fn" or "unsafe_fn" call for parameter list, got:
@@ -10355,32 +10373,32 @@ ${w(g)}`});if(_r(d,t)&&!f&&(d=yt({type:d,expectedType:void 0,expr:void 0,env:t})
10355
10373
  comptime(${w(g)})
10356
10374
 
10357
10375
  Given type:
10358
- ${A(d)}`});if(n.isUnsafeFunctionType||kr(d,g.token),f&&pr(d,t))throw y({token:g.token,errorMessage:`Unexpected "comptime" for return type of ${A(d)} which can only be used at runtime.`});if(f){for(let $ of a)if(!$.isCompileTimeOnly)throw y({token:Zl($),errorMessage:"Expected all parameters to be compile time only given the return type is compile time only."})}if(m&&!Lt(d))throw y({token:g.token,errorMessage:`Expected Expr type for "unquote" return type, got ${A(d)}`});let T=ci({parameters:a,forallParameters:s,implicitParameters:l,variadicParameter:u,whereClauseExprs:c,return_:{type:d,typeExpr:g,isCompileTimeOnly:f,isUnquote:m,label:p??`fn_return_${qe(t.modulePath)}`},env:ct(t,!0),parametersFrame:t.frames[t.frames.length-1],SelfType:n.SelfType,SelfTraitType:n.SelfTraitType,SelfModuleType:n.SelfModuleType});return t=ct(t,!0),e.$={env:t,value:ee(T),type:wt(T),pathCollection:[]},e}function ea({parameter:e,calleeEnv:t,context:n,definitionSiteEnclosingFunctionType:r,functionType:i}){let o=e.exprs.typeExpr,a=e.exprs.defaultValueExpr;if(o){let s=r??(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0),l=S({expr:Ae(o),env:t,context:{...n,expectedType:void 0,SelfType:i.SelfType,SelfTraitType:i.SelfTraitType??n.SelfTraitType,SelfModuleType:i.SelfModuleType??n.SelfModuleType,isEvaluatingFunctionBodyOrAsyncBlock:s?{kind:"function-body",type:s,evaluationEnv:t}:void 0}});if(!O(l.$?.value))throw y({token:o.token,errorMessage:`Expected type for parameter, got:
10376
+ ${A(d)}`});if(n.isUnsafeFunctionType||kr(d,g.token),f&&pr(d,t))throw y({token:g.token,errorMessage:`Unexpected "comptime" for return type of ${A(d)} which can only be used at runtime.`});if(f){for(let $ of a)if(!$.isCompileTimeOnly)throw y({token:Zl($),errorMessage:"Expected all parameters to be compile time only given the return type is compile time only."})}if(m&&!Lt(d))throw y({token:g.token,errorMessage:`Expected Expr type for "unquote" return type, got ${A(d)}`});let T=ci({parameters:a,forallParameters:s,implicitParameters:l,variadicParameter:u,whereClauseExprs:c,return_:{type:d,typeExpr:g,isCompileTimeOnly:f,isUnquote:m,label:p??`fn_return_${qe(t.modulePath)}`},env:ct(t,!0),parametersFrame:t.frames[t.frames.length-1],SelfType:n.SelfType,SelfTraitType:n.SelfTraitType,SelfModuleType:n.SelfModuleType});return t=ct(t,!0),e.$={env:t,value:ee(T),type:Ft(T),pathCollection:[]},e}function ea({parameter:e,calleeEnv:t,context:n,definitionSiteEnclosingFunctionType:r,functionType:i}){let o=e.exprs.typeExpr,a=e.exprs.defaultValueExpr;if(o){let s=r??(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0),l=S({expr:Ae(o),env:t,context:{...n,expectedType:void 0,SelfType:i.SelfType,SelfTraitType:i.SelfTraitType??n.SelfTraitType,SelfModuleType:i.SelfModuleType??n.SelfModuleType,isEvaluatingFunctionBodyOrAsyncBlock:s?{kind:"function-body",type:s,evaluationEnv:t}:void 0}});if(!O(l.$?.value))throw y({token:o.token,errorMessage:`Expected type for parameter, got:
10359
10377
  ${w(l)}`});return l.$?.env&&(t=l.$?.env),{parameterType:l.$?.value.value,calleeEnv:t}}else if(a){let s=S({expr:Ae(a),env:t,context:{...n,expectedType:void 0,SelfType:i.SelfType,SelfTraitType:i.SelfTraitType??n.SelfTraitType,SelfModuleType:i.SelfModuleType??n.SelfModuleType}});if(!s.$)throw y({token:a.token,errorMessage:`Failed to evaluate default value expression:
10360
- ${w(a)}`});return t=s.$?.env,{parameterType:s.$.type,calleeEnv:t}}else return{parameterType:e.type,calleeEnv:t}}function Ei({functionType:e,calleeEnv:t,context:n,functionCalleeExpr:r}){let i=e.return,o=S({expr:Ae(i.typeExpr),env:t,context:{...n,SelfType:e.SelfType,SelfTraitType:e.SelfTraitType??n.SelfTraitType,SelfModuleType:e.SelfModuleType??n.SelfModuleType}}),a,s=o.$?.value;if(O(s))a=s.value;else throw y({token:r?.token??ae,errorMessage:"Function body is not evaluated correctly. Expected to return a type."});return x(a)&&(a=Ot(t,a)),{returnType:a,calleeEnv:o.$?.env??t}}function uf({expr:e,env:t,context:n}){let r=e.func,i=e.args;if(!z(r)||r.token.value!=="_")throw y({token:r.token,errorMessage:`Expected "_" for anonymous struct, got:
10378
+ ${w(a)}`});return t=s.$?.env,{parameterType:s.$.type,calleeEnv:t}}else return{parameterType:e.type,calleeEnv:t}}function Ei({functionType:e,calleeEnv:t,context:n,functionCalleeExpr:r}){let i=e.return,o=S({expr:Ae(i.typeExpr),env:t,context:{...n,SelfType:e.SelfType,SelfTraitType:e.SelfTraitType??n.SelfTraitType,SelfModuleType:e.SelfModuleType??n.SelfModuleType}}),a,s=o.$?.value;if(O(s))a=s.value;else throw y({token:r?.token??ae,errorMessage:"Function body is not evaluated correctly. Expected to return a type."});return x(a)&&(a=Ot(t,a)),{returnType:a,calleeEnv:o.$?.env??t}}function cf({expr:e,env:t,context:n}){let r=e.func,i=e.args;if(!z(r)||r.token.value!=="_")throw y({token:r.token,errorMessage:`Expected "_" for anonymous struct, got:
10361
10379
  ${w(r)}`});let o=ui(t),a=o.fields,s=[],l=[];for(let p=0;p<i.length;p++){let f=i[p],m,g=f,h;if(F(f)&&E(f,":",2)){if(m=f.args[0],g=f.args[1],!je(m))throw y({token:m.token,errorMessage:`Expected identifier for anonymous struct field label, got:
10362
- ${w(m)}`});h=m.token.value}{let d=S({expr:g,env:t,context:{...n,SelfType:o}});if(qt(d,n),!d.$)throw y({token:g.token,errorMessage:`Failed to evaluate the anonymous struct field expression: ${w(g)}`});t=d.$.env;let v=d.$.type,T={exprs:{expr:g,labelExpr:void 0,typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:g},type:v,label:h??`__field_${qe(t.modulePath)}`};a.push(T),l.push(d),d.$.value?s.push(d.$?.value):s.push(void 0),m&&(m.$=d.$)}}t=si({structType:o,env:t,context:n,errorToken:r.token});let u;u=s.some(p=>!p)?void 0:Bn(o,s);let c=ee(o);r.$={env:t,type:c.type,value:c,pathCollection:[]};let{env:_}=me({env:t,variable:{name:o.id,type:c.type,value:[c],initializedAtToken:e.token,token:e.token,isCompileTimeOnly:!0,consumedAtToken:void 0,isOwningTheRcValue:!1}});return t=_,e.$={env:t,type:o,value:u,pathCollection:[],runtimeArgExprsInOrder:l},Ge(e,!0),e}function cf({expr:e,env:t,context:n}){let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for Arc:
10380
+ ${w(m)}`});h=m.token.value}{let d=S({expr:g,env:t,context:{...n,SelfType:o}});if(qt(d,n),!d.$)throw y({token:g.token,errorMessage:`Failed to evaluate the anonymous struct field expression: ${w(g)}`});t=d.$.env;let v=d.$.type,T={exprs:{expr:g,labelExpr:void 0,typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:g},type:v,label:h??`__field_${qe(t.modulePath)}`};a.push(T),l.push(d),d.$.value?s.push(d.$?.value):s.push(void 0),m&&(m.$=d.$)}}t=si({structType:o,env:t,context:n,errorToken:r.token});let u;u=s.some(p=>!p)?void 0:Bn(o,s);let c=ee(o);r.$={env:t,type:c.type,value:c,pathCollection:[]};let{env:_}=me({env:t,variable:{name:o.id,type:c.type,value:[c],initializedAtToken:e.token,token:e.token,isCompileTimeOnly:!0,consumedAtToken:void 0,isOwningTheRcValue:!1}});return t=_,e.$={env:t,type:o,value:u,pathCollection:[],runtimeArgExprsInOrder:l},Ge(e,!0),e}function _f({expr:e,env:t,context:n}){let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for Arc:
10363
10381
  ${w(r)}`});if(t=i.$.env,!O(i.$.value))throw y({token:r.token,errorMessage:`Arc expects a type as argument, but got:
10364
- ${w(r)}`});let a=i.$.value.value,s=xu(a,t);t=fu({arcType:s,env:t,context:n});let l=ee(s);return e.$={env:t,type:l.type,value:l,pathCollection:[]},e}function _f({expr:e,env:t,context:n,arcType:r}){let i=e.args[0],o=S({expr:i,env:t,context:{...n,expectedType:{type:r.childType,env:t}}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate the argument expression for Arc value constructor:
10365
- ${w(i)}`});return t=o.$.env,t=Tn(o,t),e.$={env:t,type:r,value:void 0,pathCollection:o.$.pathCollection||[]},Ge(e,!0),e}function pf({expr:e,arrayType:t,arrayValue:n,sliceValue:r,argExprs:i,callerEnv:o,context:a}){if(i.length!==1)throw y({token:e.func.token,errorMessage:`Expect 1 argument for accessing array element, got ${i.length}.`});if(z(e.args[0])&&dt(e.args[0],":")||F(e.args[0])&&E(e.args[0],":")){let s=$a(t.childType);if(z(e.args[0]))return n?{value:pa(s,[n],0,n.elements.length),type:s,callerEnv:o}:r?{value:r,type:s,callerEnv:o}:{value:void 0,type:s,callerEnv:o};{let l=e.args[0].args[0],u=e.args[0].args[1],c=S({expr:l,env:o,context:{...a,expectedType:{type:gt(),env:o}}});if(!c.$)throw y({token:l.token,errorMessage:`Failed to evaluate start expression:
10382
+ ${w(r)}`});let a=i.$.value.value,s=xu(a,t);t=fu({arcType:s,env:t,context:n});let l=ee(s);return e.$={env:t,type:l.type,value:l,pathCollection:[]},e}function pf({expr:e,env:t,context:n,arcType:r}){let i=e.args[0],o=S({expr:i,env:t,context:{...n,expectedType:{type:r.childType,env:t}}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate the argument expression for Arc value constructor:
10383
+ ${w(i)}`});return t=o.$.env,t=Tn(o,t),e.$={env:t,type:r,value:void 0,pathCollection:o.$.pathCollection||[]},Ge(e,!0),e}function ff({expr:e,arrayType:t,arrayValue:n,sliceValue:r,argExprs:i,callerEnv:o,context:a}){if(i.length!==1)throw y({token:e.func.token,errorMessage:`Expect 1 argument for accessing array element, got ${i.length}.`});if(z(e.args[0])&&dt(e.args[0],":")||F(e.args[0])&&E(e.args[0],":")){let s=$a(t.childType);if(z(e.args[0]))return n?{value:pa(s,[n],0,n.elements.length),type:s,callerEnv:o}:r?{value:r,type:s,callerEnv:o}:{value:void 0,type:s,callerEnv:o};{let l=e.args[0].args[0],u=e.args[0].args[1],c=S({expr:l,env:o,context:{...a,expectedType:{type:gt(),env:o}}});if(!c.$)throw y({token:l.token,errorMessage:`Failed to evaluate start expression:
10366
10384
  ${w(l)}`});o=c.$.env;let _=c.$.type;if(!Y({type:gt(),env:o},{type:_,env:o}))throw y({token:l.token,errorMessage:`Expected usize for array start index, got:
10367
10385
  ${A(_)}`});let p=S({expr:u,env:o,context:{...a,expectedType:{type:gt(),env:o}}});if(!p.$)throw y({token:u.token,errorMessage:`Failed to evaluate end expression:
10368
10386
  ${w(u)}`});o=p.$.env;let f=p.$.type;if(!Y({type:gt(),env:o},{type:f,env:o}))throw y({token:u.token,errorMessage:`Expected usize for array end index, got:
10369
10387
  ${A(f)}`});if(n&&ze(c.$.value)&&ze(p.$.value)){let m=c.$.value.value,g=p.$.value.value,h=typeof m=="bigint"?Number(m):m,d=typeof g=="bigint"?Number(g):g;if(h<0||h>n.elements.length)throw y({token:l.token,errorMessage:`Slice start index out of bounds: ${h}. Expected index in range [0, ${n.elements.length}].`});if(d<h||d>n.elements.length)throw y({token:u.token,errorMessage:`Slice end index out of bounds: ${d}. Expected index in range [${h}, ${n.elements.length}].`});return{value:pa(s,[n],h,d),type:s,callerEnv:o}}if(r&&ze(c.$.value)&&ze(p.$.value)){let m=c.$.value.value,g=p.$.value.value,h=typeof m=="bigint"?Number(m):m,d=typeof g=="bigint"?Number(g):g,v=r.endIndex-r.startIndex;if(h<0||h>v)throw y({token:l.token,errorMessage:`Slice start index out of bounds: ${h}. Expected index in range [0, ${v}].`});if(d<h||d>v)throw y({token:u.token,errorMessage:`Slice end index out of bounds: ${d}. Expected index in range [${h}, ${v}].`});let T=r.startIndex+h,$=r.startIndex+d;return{value:pa(s,r.sourceArray,T,$),type:s,callerEnv:o}}return{value:void 0,type:s,callerEnv:o}}}else{let s=i[0],l=S({expr:s,env:o,context:{...a,expectedType:{type:gt(),env:o}}});if(!l.$)throw y({token:s.token,errorMessage:`Failed to evaluate argument expression:
10370
10388
  ${w(s)}`});o=l.$.env;let u=l.$.type;if(!Y({type:gt(),env:o},{type:u,env:o}))throw y({token:s.token,errorMessage:`Expected usize for array index, got:
10371
- ${A(u)}`});let c=t.childType;if(r)if(l.$.value)if(ze(l.$.value)){let _=l.$.value.value,p=typeof _=="bigint"?Number(_):_,f=r.endIndex-r.startIndex;if(p<0||p>=f)throw y({token:s.token,errorMessage:`Slice index out of bounds: ${p}. Expected index in range [0, ${f-1}].`});let m=r.startIndex+p,g=r.sourceArray[0];return{value:g.elements[m],index:p,arrayElementRef:{arrayValue:g,index:m},type:c,callerEnv:o}}else return{value:K(c,{env:o,context:a}),type:c,callerEnv:o};else return{value:void 0,type:yt({type:c,env:o}),callerEnv:o};if(n)if(l.$.value)if(ze(l.$.value)){let _=l.$.value.value,p=typeof _=="bigint"?Number(_):_;if(p<0||p>=n.elements.length)throw y({token:s.token,errorMessage:`Array index out of bounds: ${p}. Expected index in range [0, ${n.elements.length-1}].`});return{value:n.elements[p],index:p,arrayElementRef:{arrayValue:n,index:p},type:c,callerEnv:o}}else return{value:K(c,{env:o,context:a}),type:c,callerEnv:o};else return{value:void 0,type:yt({type:c,env:o}),callerEnv:o};else return{value:void 0,type:c,callerEnv:o}}}function ff({expr:e,arrayType:t,argExprs:n,callerEnv:r,context:i}){let o=t.length,a=t,s;if(ze(o)){if(s=Number(o.value),n.length!==s)throw y({token:e.func.token,errorMessage:`Array constructor expects ${s} elements, got ${n.length}.`})}else if(de(o)){s=n.length;let p=ur(BigInt(s));a=mr(t.childType,p)}else throw y({token:e.func.token,errorMessage:`Array length must be a known number value or unknown (_), got ${o}.`});let l=[],u=r,c=a.childType;for(let p=0;p<n.length;p++){let f=n[p],m=S({expr:f,env:u,context:{...i,expectedType:{type:c,env:u}}});if(!m.$)throw y({token:f.token,errorMessage:`Failed to evaluate array element at index ${p}.`});if(qt(m,i),u=m.$.env,p===0&&ke(c)&&de(c.length)&&ke(m.$.type)&&(c=m.$.type,a=mr(c,a.length)),!Y({type:c,env:u},{type:m.$.type,env:u}))throw y({token:f.token,errorMessage:`Array element at index ${p} has incompatible type:
10389
+ ${A(u)}`});let c=t.childType;if(r)if(l.$.value)if(ze(l.$.value)){let _=l.$.value.value,p=typeof _=="bigint"?Number(_):_,f=r.endIndex-r.startIndex;if(p<0||p>=f)throw y({token:s.token,errorMessage:`Slice index out of bounds: ${p}. Expected index in range [0, ${f-1}].`});let m=r.startIndex+p,g=r.sourceArray[0];return{value:g.elements[m],index:p,arrayElementRef:{arrayValue:g,index:m},type:c,callerEnv:o}}else return{value:K(c,{env:o,context:a}),type:c,callerEnv:o};else return{value:void 0,type:yt({type:c,env:o}),callerEnv:o};if(n)if(l.$.value)if(ze(l.$.value)){let _=l.$.value.value,p=typeof _=="bigint"?Number(_):_;if(p<0||p>=n.elements.length)throw y({token:s.token,errorMessage:`Array index out of bounds: ${p}. Expected index in range [0, ${n.elements.length-1}].`});return{value:n.elements[p],index:p,arrayElementRef:{arrayValue:n,index:p},type:c,callerEnv:o}}else return{value:K(c,{env:o,context:a}),type:c,callerEnv:o};else return{value:void 0,type:yt({type:c,env:o}),callerEnv:o};else return{value:void 0,type:c,callerEnv:o}}}function df({expr:e,arrayType:t,argExprs:n,callerEnv:r,context:i}){let o=t.length,a=t,s;if(ze(o)){if(s=Number(o.value),n.length!==s)throw y({token:e.func.token,errorMessage:`Array constructor expects ${s} elements, got ${n.length}.`})}else if(de(o)){s=n.length;let p=ur(BigInt(s));a=mr(t.childType,p)}else throw y({token:e.func.token,errorMessage:`Array length must be a known number value or unknown (_), got ${o}.`});let l=[],u=r,c=a.childType;for(let p=0;p<n.length;p++){let f=n[p],m=S({expr:f,env:u,context:{...i,expectedType:{type:c,env:u}}});if(!m.$)throw y({token:f.token,errorMessage:`Failed to evaluate array element at index ${p}.`});if(qt(m,i),u=m.$.env,p===0&&ke(c)&&de(c.length)&&ke(m.$.type)&&(c=m.$.type,a=mr(c,a.length)),!Y({type:c,env:u},{type:m.$.type,env:u}))throw y({token:f.token,errorMessage:`Array element at index ${p} has incompatible type:
10372
10390
  - Expected: ${A(c)}
10373
- - Given : ${A(m.$.type)}`});m.$.value!==void 0?l.push(m.$.value):l.push(K(c,{env:u,context:i}))}let _=Mr(a,l);return e.$={env:u,value:_,type:a,pathCollection:[]},e}function df({capturedVariables:e,env:t,closureToken:n}){let r=t;for(let[i,o]of e.entries())if(o.frameLevel<t.frames.length&&o.usageType==="own"){let a=X(r,i);if(a.length>0){let s=a[a.length-1];s.consumedAtToken||(r=Be(r,s,{...s,consumedAtToken:n}))}}return r}function so(e){let t=[];for(let[n]of e.entries())t.push([n]);return t}function Ya({wrapperType:e,captureType:t,env:n,errorToken:r}){for(let{traitType:i}of e.requiredTraits)if(!bt(i)&&!St({targetType:t,traitType:i,env:n})){let o=t.fields.filter(l=>!St({targetType:l.type,traitType:i,env:n})),a=A(i),s=o.map(l=>`\`${l.label}\` has type \`${A(l.type)}\` which does not implement \`${a}\``).join(`
10391
+ - Given : ${A(m.$.type)}`});m.$.value!==void 0?l.push(m.$.value):l.push(K(c,{env:u,context:i}))}let _=Mr(a,l);return e.$={env:u,value:_,type:a,pathCollection:[]},e}function mf({capturedVariables:e,env:t,closureToken:n}){let r=t;for(let[i,o]of e.entries())if(o.frameLevel<t.frames.length&&o.usageType==="own"){let a=X(r,i);if(a.length>0){let s=a[a.length-1];s.consumedAtToken||(r=Be(r,s,{...s,consumedAtToken:n}))}}return r}function so(e){let t=[];for(let[n]of e.entries())t.push([n]);return t}function Ya({wrapperType:e,captureType:t,env:n,errorToken:r}){for(let{traitType:i}of e.requiredTraits)if(!kt(i)&&!St({targetType:t,traitType:i,env:n})){let o=t.fields.filter(l=>!St({targetType:l.type,traitType:i,env:n})),a=A(i),s=o.map(l=>`\`${l.label}\` has type \`${A(l.type)}\` which does not implement \`${a}\``).join(`
10374
10392
  `);throw y({token:r,errorMessage:`Closure does not implement \`${a}\` because captured variable ${s}`})}}function Ha({expectedCaptureType:e,capturedVariablesWithValues:t,env:n,closureToken:r,context:i}){let o=e,a;if(o===void 0)if(t&&t.size>0){let s=ui(n),l=Array.from(t.entries()).map(([c,_])=>({label:c,type:_.type,isCompileTimeOnly:!1,assignedValue:void 0,isEffectParam:_.isEffectParam||void 0,exprs:{expr:{tag:"Atom",token:_.token},labelExpr:void 0,typeExpr:void 0,defaultValueExpr:void 0}}));s.fields=l,o=s,n=si({structType:s,env:n,context:{...i},errorToken:r});let u=Array.from(t.values()).map(c=>c.value);u.every(c=>c!==void 0)?a=Bn(s,u):a=void 0}else{let s=ui(n);s.fields=[],n=si({structType:s,env:n,context:{...i},errorToken:r}),o=s,a=Bn(s,[])}else if(t&&t.size>0){let s=o,l=Array.from(t.keys()),u=s.fields.map(_=>_.label);for(let _ of l)if(!u.includes(_))throw y({token:r,errorMessage:`Captured variable "${_}" does not exist in expected capture struct "${A(s)}"`});for(let _ of s.fields)if(!l.includes(_.label))throw y({token:r,errorMessage:`Expected capture struct field "${_.label}" is not captured by this closure`});for(let[_,p]of t.entries()){let f=s.fields.find(m=>m.label===_);if(f&&!Y({type:f.type,env:n},{type:p.type,env:n}))throw y({token:p.token,errorMessage:`Captured variable "${_}" has type "${A(p.type)}" but expected struct field has type "${A(f.type)}"`})}let c=Array.from(t.values()).map(_=>_.value);c.every(_=>_!==void 0)?a=Bn(o,c):a=void 0}else a=Bn(o,[]);return{captureType:o,captureValue:a}}function ja({capturedVariables:e,env:t}){let n=new Map;for(let[r,i]of e.entries())if(i.frameLevel<t.frames.length){let a=t.frames[i.frameLevel].variables.find(s=>s.name===r);a&&!a.isCompileTimeOnly&&n.set(r,{...i,value:a.value?.[0],type:a.type})}return n}function Ka({capturedVariablesWithValues:e,env:t,context:n}){let r=[],i=t;if(e&&e.size>0){for(let[o,a]of e.entries())if(Le(a.type)){let s=Jt(`${k.___dup[0]}(${o})`),l=S({expr:s,env:i,context:{...n}});r.push(l),l.$&&l.$.env&&(i=l.$.env)}}return{capturedVariableDupExpressions:r.length>0?r:void 0,env:i}}function Sl({functionBodyExpr:e,functionType:t,functionValue:n,env:r,context:i}){if(!Fe(t.return.type))return;let o;try{let a=Ae(e),s=lo({...i,capturedVariables:void 0},t,{...n},r),l=ht({expr:a,env:r,context:s.evaluationContext,variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(o=l.$?.type,et(l.$?.controlFlow,"escape")&&!et(l.$?.controlFlow,"return"))return}catch{return}if(o&&!Y({type:t.return.type,env:r},{type:o,env:r},!0))throw y({token:t.return.typeExpr.token,errorMessage:`Incompatible function return type for:
10375
10393
  - Expected: ${A(t.return.type)}
10376
- - Given : ${A(o)}`})}function lo(e,t,n,r){let i={kind:"function-body",type:t,value:n,evaluationEnv:r},o=new Map,a;if(e.isEvaluatingFunctionBodyOrAsyncBlock){let l=e.isEvaluatingFunctionBodyOrAsyncBlock;l.kind==="function-body"?a=l.type.return.type:a=xn()}return{evaluationContext:{...e,isExecuting:!1,isValidatingFunctionDefinition:!0,isEvaluatingFunctionBodyOrAsyncBlock:i,isEvaluatingFunctionType:!1,isEvaluatingLoopBody:void 0,capturedVariables:o,expectedType:{type:t.return.type,env:r},functionReturnImplConcreteType:[],enclosingFunctionReturnType:a,isInsideGivenHandler:e.isInsideGivenHandler,forceCompileTimeBindings:!1,isAnalyzingCtfeCapability:!1},functionBodyContext:i}}function mf({expr:e,functionType:t,callerEnv:n,context:r}){let i=e.func,o=e.args;if(o.length!==1)throw y({token:i.token,errorMessage:`Failed to implement the function. Expected 1 argument for the function body, got ${o.length}.`});let a=o[0],s=!1,l=r.expectedType?.type,u=l&&G(l)&&l.parameters.length===t.parameters.length&&l.parameters.some((L,b)=>L.label!==t.parameters[b].label),c=Pe(s?n:Ma(n));if(u&&l&&G(l)){for(let L of t.forallParameters){let{env:b}=me({env:c,variable:{name:L.label,type:L.type,isCompileTimeOnly:!0,value:[K(L.type,{variableName:L.label,env:c,context:r})],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});c=b}for(let L=0;L<t.parameters.length;L++){let b=t.parameters[L],R=l.parameters[L],N=b.label,B=R.label,{env:D}=me({env:c,variable:{name:N,type:b.type,isCompileTimeOnly:b.isCompileTimeOnly,value:b.isCompileTimeOnly?[K(b.type,{variableName:B,env:c,context:r})]:void 0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:b.isOwningTheRcValue,parameterAlias:N!==B?B:void 0}});c=D}}else c=Pe(c,t.parametersFrame);let _=c.frames[c.frames.length-1],p={...t,parametersFrame:_,env:t.env},f={tag:"Function",type:p,body:a,frameLevel:c.frames.length-1,funcName:void 0,funcId:`fn_${qe(c.modulePath)}`,definitionSiteEnclosingFunctionType:r.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?r.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]};if(p.whereClauseExprs?.length){let L=p.whereClauseExprs.map(R=>Ae(R));c=Hr({constraintExprs:L,env:c,context:{...r,isEvaluatingFunctionType:!0}}).env}let m=p.forallParameters.length>0||p.parameters.some(L=>Fe(L.type))||p.SelfType&&Fe(p.SelfType),g,h;if(m)Sl({functionBodyExpr:a,functionType:p,functionValue:f,env:c,context:r}),a.$={env:c,type:t.return.type,value:t.return.isCompileTimeOnly?K(t.return.type,{variableName:"function_body",env:c,context:r}):void 0,pathCollection:[]},h={...r,capturedVariables:void 0},g=a;else{if(h=lo({...r,capturedVariables:void 0},p,f,c).evaluationContext,g=ht({expr:a,env:c,context:h,variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),!g.$)throw y({token:a.token,errorMessage:"Failed to evaluate the function body."});c=g.$.env}let d=h.capturedVariables,v=g.$?.type;if(Qn(g)&&(f.isControlFunction=!0),!f.isControlFunction&&v&&!Y({type:p.return.type,env:c},{type:v,env:c}))throw y({token:p.return.typeExpr.token,errorMessage:`Incompatible function return type for:
10394
+ - Given : ${A(o)}`})}function lo(e,t,n,r){let i={kind:"function-body",type:t,value:n,evaluationEnv:r},o=new Map,a;if(e.isEvaluatingFunctionBodyOrAsyncBlock){let l=e.isEvaluatingFunctionBodyOrAsyncBlock;l.kind==="function-body"?a=l.type.return.type:a=xn()}return{evaluationContext:{...e,isExecuting:!1,isValidatingFunctionDefinition:!0,isEvaluatingFunctionBodyOrAsyncBlock:i,isEvaluatingFunctionType:!1,isEvaluatingLoopBody:void 0,capturedVariables:o,expectedType:{type:t.return.type,env:r},functionReturnImplConcreteType:[],enclosingFunctionReturnType:a,isInsideGivenHandler:e.isInsideGivenHandler,forceCompileTimeBindings:!1,isAnalyzingCtfeCapability:!1},functionBodyContext:i}}function yf({expr:e,functionType:t,callerEnv:n,context:r}){let i=e.func,o=e.args;if(o.length!==1)throw y({token:i.token,errorMessage:`Failed to implement the function. Expected 1 argument for the function body, got ${o.length}.`});let a=o[0],s=!1,l=r.expectedType?.type,u=l&&G(l)&&l.parameters.length===t.parameters.length&&l.parameters.some((L,b)=>L.label!==t.parameters[b].label),c=Pe(s?n:Ma(n));if(u&&l&&G(l)){for(let L of t.forallParameters){let{env:b}=me({env:c,variable:{name:L.label,type:L.type,isCompileTimeOnly:!0,value:[K(L.type,{variableName:L.label,env:c,context:r})],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1}});c=b}for(let L=0;L<t.parameters.length;L++){let b=t.parameters[L],R=l.parameters[L],N=b.label,B=R.label,{env:D}=me({env:c,variable:{name:N,type:b.type,isCompileTimeOnly:b.isCompileTimeOnly,value:b.isCompileTimeOnly?[K(b.type,{variableName:B,env:c,context:r})]:void 0,token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:b.isOwningTheRcValue,parameterAlias:N!==B?B:void 0}});c=D}}else c=Pe(c,t.parametersFrame);let _=c.frames[c.frames.length-1],p={...t,parametersFrame:_,env:t.env},f={tag:"Function",type:p,body:a,frameLevel:c.frames.length-1,funcName:void 0,funcId:`fn_${qe(c.modulePath)}`,definitionSiteEnclosingFunctionType:r.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?r.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]};if(p.whereClauseExprs?.length){let L=p.whereClauseExprs.map(R=>Ae(R));c=Hr({constraintExprs:L,env:c,context:{...r,isEvaluatingFunctionType:!0}}).env}let m=p.forallParameters.length>0||p.parameters.some(L=>Fe(L.type))||p.SelfType&&Fe(p.SelfType),g,h;if(m)Sl({functionBodyExpr:a,functionType:p,functionValue:f,env:c,context:r}),a.$={env:c,type:t.return.type,value:t.return.isCompileTimeOnly?K(t.return.type,{variableName:"function_body",env:c,context:r}):void 0,pathCollection:[]},h={...r,capturedVariables:void 0},g=a;else{if(h=lo({...r,capturedVariables:void 0},p,f,c).evaluationContext,g=ht({expr:a,env:c,context:h,variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),!g.$)throw y({token:a.token,errorMessage:"Failed to evaluate the function body."});c=g.$.env}let d=h.capturedVariables,v=g.$?.type;if(Qn(g)&&(f.isControlFunction=!0),!f.isControlFunction&&v&&!Y({type:p.return.type,env:c},{type:v,env:c}))throw y({token:p.return.typeExpr.token,errorMessage:`Incompatible function return type for:
10377
10395
  - Expected: ${A(p.return.type)}
10378
- - Given : ${A(v)}`});if(x(p.return.type)&&!p.return.type.resolvedConcreteType&&(x(v)?x(v)&&v.resolvedConcreteType&&(p.return.type.resolvedConcreteType=v.resolvedConcreteType):p.return.type.resolvedConcreteType=v),p.return.isCompileTimeOnly&&g.$&&!g.$.value)throw y({token:p.return.typeExpr.token,errorMessage:"Expected to return a compile-time value, but got runtime value."});c=ct(c,!0);let T=n;s&&d&&d.size>0&&(T=df({capturedVariables:d,env:n,closureToken:e.token}));let $=f,C=p;if(r.isAnalyzingCtfeCapability||r.forceCompileTimeBindings){let L=ro(f,T,r);L&&($=L,C=L.type)}return e.$={env:T,value:$,type:C,pathCollection:d&&d.size>0?so(d):[]},e}function yf({expr:e,fnModuleType:t,wrapperType:n,callerEnv:r,context:i}){let o=e.func,a=e.args;if(a.length!==1)throw y({token:o.token,errorMessage:`Fn module type expects exactly 1 argument (the closure body), got ${a.length}`});let s=a[0],l=Pe(r,t.isFn.callType.parametersFrame);if(t.isFn.callType.whereClauseExprs?.length){let $=t.isFn.callType.whereClauseExprs.map(L=>Ae(L));l=Hr({constraintExprs:$,env:l,context:{...i,isEvaluatingFunctionType:!0}}).env}let u={tag:"Function",type:t.isFn.callType,body:s,frameLevel:l.frames.length-1,funcName:void 0,funcId:`closure_${qe(l.modulePath)}`,definitionSiteEnclosingFunctionType:i.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?i.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},{evaluationContext:c}=lo(i,t.isFn.callType,u,l),_=ht({expr:s,env:l,context:c,variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(!_.$)throw y({token:s.token,errorMessage:"Failed to evaluate the closure body."});l=_.$.env;let p=c.capturedVariables,f=_.$.type;if(!Y({type:t.isFn.callType.return.type,env:l},{type:f,env:l}))throw y({token:t.isFn.callType.return.typeExpr.token,errorMessage:`Incompatible closure return type:
10396
+ - Given : ${A(v)}`});if(x(p.return.type)&&!p.return.type.resolvedConcreteType&&(x(v)?x(v)&&v.resolvedConcreteType&&(p.return.type.resolvedConcreteType=v.resolvedConcreteType):p.return.type.resolvedConcreteType=v),p.return.isCompileTimeOnly&&g.$&&!g.$.value)throw y({token:p.return.typeExpr.token,errorMessage:"Expected to return a compile-time value, but got runtime value."});c=ct(c,!0);let T=n;s&&d&&d.size>0&&(T=mf({capturedVariables:d,env:n,closureToken:e.token}));let $=f,C=p;if(r.isAnalyzingCtfeCapability||r.forceCompileTimeBindings){let L=ro(f,T,r);L&&($=L,C=L.type)}return e.$={env:T,value:$,type:C,pathCollection:d&&d.size>0?so(d):[]},e}function gf({expr:e,fnModuleType:t,wrapperType:n,callerEnv:r,context:i}){let o=e.func,a=e.args;if(a.length!==1)throw y({token:o.token,errorMessage:`Fn module type expects exactly 1 argument (the closure body), got ${a.length}`});let s=a[0],l=Pe(r,t.isFn.callType.parametersFrame);if(t.isFn.callType.whereClauseExprs?.length){let $=t.isFn.callType.whereClauseExprs.map(L=>Ae(L));l=Hr({constraintExprs:$,env:l,context:{...i,isEvaluatingFunctionType:!0}}).env}let u={tag:"Function",type:t.isFn.callType,body:s,frameLevel:l.frames.length-1,funcName:void 0,funcId:`closure_${qe(l.modulePath)}`,definitionSiteEnclosingFunctionType:i.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?i.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},{evaluationContext:c}=lo(i,t.isFn.callType,u,l),_=ht({expr:s,env:l,context:c,variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(!_.$)throw y({token:s.token,errorMessage:"Failed to evaluate the closure body."});l=_.$.env;let p=c.capturedVariables,f=_.$.type;if(!Y({type:t.isFn.callType.return.type,env:l},{type:f,env:l}))throw y({token:t.isFn.callType.return.typeExpr.token,errorMessage:`Incompatible closure return type:
10379
10397
  - Expected: ${A(t.isFn.callType.return.type)}
10380
- - Given : ${A(f)}`});if(t.isFn.callType.return.isCompileTimeOnly&&!_.$.value)throw y({token:t.isFn.callType.return.typeExpr.token,errorMessage:"Expected to return a compile-time value, but got runtime value."});l=ct(l,!0);let m=p&&p.size>0?ja({capturedVariables:p,env:r}):void 0,g=r,{capturedVariableDupExpressions:h,env:d}=Ka({capturedVariablesWithValues:m,env:r,context:i});g=d;let{captureType:v}=Ha({expectedCaptureType:void 0,capturedVariablesWithValues:m,env:g,closureToken:e.token,context:{...i}});u.closureInfo={closureType:t,captureType:v},x(n)&&v&&Ya({wrapperType:n,captureType:v,env:g,errorToken:e.token});let T;return x(n)?(n.resolvedConcreteType=v,T={...n,resolvedConcreteType:v}):be(n)?T=n:T=t,e.$={env:g,value:void 0,type:T,pathCollection:p&&p.size>0?so(p):[],deferredDupExpressions:h&&h.length>0?h:void 0,captureType:v,closureFunctionValue:u},be(n)&&Ge(e,!0),e}function gf({expr:e,comptimeListType:t,argExprs:n,callerEnv:r,context:i}){let o=[],a=r,s=t.childType;for(let u=0;u<n.length;u++){let c=n[u],_=S({expr:c,env:a,context:{...i,expectedType:{type:s,env:a}}});if(!_.$)throw y({token:c.token,errorMessage:`Failed to evaluate ComptimeList element at index ${u}.`});if(qt(_,i),a=_.$.env,!Y({type:s,env:a},{type:_.$.type,env:a}))throw y({token:c.token,errorMessage:`ComptimeList element at index ${u} has incompatible type:
10398
+ - Given : ${A(f)}`});if(t.isFn.callType.return.isCompileTimeOnly&&!_.$.value)throw y({token:t.isFn.callType.return.typeExpr.token,errorMessage:"Expected to return a compile-time value, but got runtime value."});l=ct(l,!0);let m=p&&p.size>0?ja({capturedVariables:p,env:r}):void 0,g=r,{capturedVariableDupExpressions:h,env:d}=Ka({capturedVariablesWithValues:m,env:r,context:i});g=d;let{captureType:v}=Ha({expectedCaptureType:void 0,capturedVariablesWithValues:m,env:g,closureToken:e.token,context:{...i}});u.closureInfo={closureType:t,captureType:v},x(n)&&v&&Ya({wrapperType:n,captureType:v,env:g,errorToken:e.token});let T;return x(n)?(n.resolvedConcreteType=v,T={...n,resolvedConcreteType:v}):be(n)?T=n:T=t,e.$={env:g,value:void 0,type:T,pathCollection:p&&p.size>0?so(p):[],deferredDupExpressions:h&&h.length>0?h:void 0,captureType:v,closureFunctionValue:u},be(n)&&Ge(e,!0),e}function hf({expr:e,comptimeListType:t,argExprs:n,callerEnv:r,context:i}){let o=[],a=r,s=t.childType;for(let u=0;u<n.length;u++){let c=n[u],_=S({expr:c,env:a,context:{...i,expectedType:{type:s,env:a}}});if(!_.$)throw y({token:c.token,errorMessage:`Failed to evaluate ComptimeList element at index ${u}.`});if(qt(_,i),a=_.$.env,!Y({type:s,env:a},{type:_.$.type,env:a}))throw y({token:c.token,errorMessage:`ComptimeList element at index ${u} has incompatible type:
10381
10399
  - Expected: ${A(s)}
10382
- - Given : ${A(_.$.type)}`});if(_.$.value!==void 0)o.push(_.$.value);else throw y({token:c.token,errorMessage:`Expected compile-time known value for ComptimeList element at index ${u}, got ${A(_.$.type)}`})}let l=zn(t.childType,o);return e.$={env:a,value:l,type:t,pathCollection:[]},e}function Tf(e,t,n,r=!1,i){let o=G(n)?n:void 0,s=wa(e,{detect(u,c,_){if(u.tag!=="FnCall")return;if(hf(u,t,i,!0)){let f=[];for(let g of u.args)g.$?.type&&f.push(g.$.type);if(f.length===0&&o)for(let g of o.parameters)g.isCompileTimeOnly||f.push(g.type);let m=u.$?.type??o?.return.type;if(f.length>0&&m){let g=Mo(c);_.push({index:_.length,expr:u,operationArgTypes:f,operationResultType:m,targetVariableId:g})}}if(r&&!hf(u,t,i)){let f=Rg(u,t);if(f){let m=n,g=m.parameters.filter(d=>!d.isCompileTimeOnly).map(d=>d.type),h=f.viaClosure?m.return.type:u.$?.type;if(g.length>0&&h){let d=Mo(c);_.push({index:_.length,expr:u,operationArgTypes:g,operationResultType:h,targetVariableId:d,isTransitiveEffectCall:!0,isTransitiveClosureCall:f.viaClosure})}}}},shouldSkipBody(u){return Rt(u)}}),l=s.capturedVariables.map(u=>({id:u.id,name:u.name,type:u.type,isOwningTheSameRcValueAs:void 0}));return{effectCallPoints:s.suspensionPoints,capturedVariables:l,hasEffects:s.hasSuspensions,variableIdRemapping:s.variableIdRemapping,effectParameterName:t,effectParameterType:n,effectFieldPath:i}}function hf(e,t,n,r=!1){if(e.tag!=="FnCall")return!1;let i=e.func;if(!n||n.length===0){if(i.tag!=="Atom"||i.token.value!==t)return!1;let l=i.$?.type;return!(!r&&(!l||!G(l))||r&&l&&!G(l))}let o=[],a=i;for(;a.tag==="FnCall"&&E(a,".")&&a.args.length>=2;){let l=a.args[1];if(!l||l.tag!=="Atom")return!1;o.unshift(l.token.value),a=a.args[0]}if(a.tag!=="Atom"||a.token.value!==t||o.length!==n.length)return!1;for(let l=0;l<o.length;l++)if(o[l]!==n[l])return!1;let s=i.$?.type;return!(!r&&(!s||!G(s))||r&&s&&!G(s))}function Rg(e,t){if(e.tag!=="FnCall")return;let n=e.func.$?.type;if(!n)return;if(G(n)){if(!n.implicitParameters)return;for(let i of n.implicitParameters){if(i.label===t&&(G(i.type)||Te(i.type)))return{matched:!0,viaClosure:!1};if(i.isEffectRowSpread&&vf(i,t,e.func.$?.env))return{matched:!0,viaClosure:!1}}return}let r=nn(n);if(r){let i=r.isFn.callType;if(i.implicitParameters)for(let o of i.implicitParameters){if(o.label===t&&(G(o.type)||Te(o.type)))return{matched:!0,viaClosure:!0};if(o.isEffectRowSpread&&vf(o,t,e.func.$?.env))return{matched:!0,viaClosure:!0}}}}function vf(e,t,n){if(!n)return!1;let r=e.type,i;if(x(r)&&r.isEffectsRow){let a=X(n,e.label).at(-1)?.value?.[0];if(a&&O(a)&&ot(a.value))i=a.value;else{let s=Ot(n,r);ot(s)&&(i=s)}}else ot(r)&&(i=r);if(i){for(let o of i.implicitParameters)if(o.label===t&&(G(o.type)||Te(o.type)))return!0}return!1}function $f(e,t){for(let n=0;n<e.fields.length;n++){let r=e.fields[n];if(G(r.type)){let i=t?.fields[n];if(i&&ne(i)&&i.isControlFunction)return!0}if(Te(r.type)){let i=t?.fields[n];if($f(r.type,i&&We(i)?i:void 0))return!0}}return!1}function Pg({variablesToDrop:e,env:t,context:n}){let r=[],i=t;for(let o of e){let a=Jt(`${k.___drop[0]}(${o.name})`),s=S({expr:a,env:i,context:{...n,expectedType:void 0}});if(r.push(s),s.$?.env)i=s.$.env;else throw y({token:a.token,errorMessage:`Failed to evaluate "___drop" expression for variable "${o.name}":
10383
- ${w(a)}`})}return{deferredDropExpressions:r.length>0?r:void 0,env:i}}function Ug({functionType:e,definitionSiteEnclosingFunctionType:t,parameter:n,argExprs:r,argIndex:i,calleeEnv:o,callerEnv:a,context:s,isMethodCall:l,runtimeArgExprsInOrder:u}){let c=r[i],_;if(c&&F(c)&&E(c,":",2)){if(_=c.args[0],c=c.args[1],!z(_))throw y({token:_.token,errorMessage:`Expected identifier for label, got:
10400
+ - Given : ${A(_.$.type)}`});if(_.$.value!==void 0)o.push(_.$.value);else throw y({token:c.token,errorMessage:`Expected compile-time known value for ComptimeList element at index ${u}, got ${A(_.$.type)}`})}let l=zn(t.childType,o);return e.$={env:a,value:l,type:t,pathCollection:[]},e}function Ef(e,t,n,r=!1,i){let o=G(n)?n:void 0,s=wa(e,{detect(u,c,_){if(u.tag!=="FnCall")return;if(vf(u,t,i,!0)){let f=[];for(let g of u.args)g.$?.type&&f.push(g.$.type);if(f.length===0&&o)for(let g of o.parameters)g.isCompileTimeOnly||f.push(g.type);let m=u.$?.type??o?.return.type;if(f.length>0&&m){let g=Mo(c);_.push({index:_.length,expr:u,operationArgTypes:f,operationResultType:m,targetVariableId:g})}}if(r&&!vf(u,t,i)){let f=Pg(u,t);if(f){let m=n,g=m.parameters.filter(d=>!d.isCompileTimeOnly).map(d=>d.type),h=f.viaClosure?m.return.type:u.$?.type;if(g.length>0&&h){let d=Mo(c);_.push({index:_.length,expr:u,operationArgTypes:g,operationResultType:h,targetVariableId:d,isTransitiveEffectCall:!0,isTransitiveClosureCall:f.viaClosure})}}}},shouldSkipBody(u){return Rt(u)}}),l=s.capturedVariables.map(u=>({id:u.id,name:u.name,type:u.type,isOwningTheSameRcValueAs:void 0}));return{effectCallPoints:s.suspensionPoints,capturedVariables:l,hasEffects:s.hasSuspensions,variableIdRemapping:s.variableIdRemapping,effectParameterName:t,effectParameterType:n,effectFieldPath:i}}function vf(e,t,n,r=!1){if(e.tag!=="FnCall")return!1;let i=e.func;if(!n||n.length===0){if(i.tag!=="Atom"||i.token.value!==t)return!1;let l=i.$?.type;return!(!r&&(!l||!G(l))||r&&l&&!G(l))}let o=[],a=i;for(;a.tag==="FnCall"&&E(a,".")&&a.args.length>=2;){let l=a.args[1];if(!l||l.tag!=="Atom")return!1;o.unshift(l.token.value),a=a.args[0]}if(a.tag!=="Atom"||a.token.value!==t||o.length!==n.length)return!1;for(let l=0;l<o.length;l++)if(o[l]!==n[l])return!1;let s=i.$?.type;return!(!r&&(!s||!G(s))||r&&s&&!G(s))}function Pg(e,t){if(e.tag!=="FnCall")return;let n=e.func.$?.type;if(!n)return;if(G(n)){if(!n.implicitParameters)return;for(let i of n.implicitParameters){if(i.label===t&&(G(i.type)||Te(i.type)))return{matched:!0,viaClosure:!1};if(i.isEffectRowSpread&&Tf(i,t,e.func.$?.env))return{matched:!0,viaClosure:!1}}return}let r=nn(n);if(r){let i=r.isFn.callType;if(i.implicitParameters)for(let o of i.implicitParameters){if(o.label===t&&(G(o.type)||Te(o.type)))return{matched:!0,viaClosure:!0};if(o.isEffectRowSpread&&Tf(o,t,e.func.$?.env))return{matched:!0,viaClosure:!0}}}}function Tf(e,t,n){if(!n)return!1;let r=e.type,i;if(x(r)&&r.isEffectsRow){let a=X(n,e.label).at(-1)?.value?.[0];if(a&&O(a)&&ot(a.value))i=a.value;else{let s=Ot(n,r);ot(s)&&(i=s)}}else ot(r)&&(i=r);if(i){for(let o of i.implicitParameters)if(o.label===t&&(G(o.type)||Te(o.type)))return!0}return!1}function Cf(e,t){for(let n=0;n<e.fields.length;n++){let r=e.fields[n];if(G(r.type)){let i=t?.fields[n];if(i&&ne(i)&&i.isControlFunction)return!0}if(Te(r.type)){let i=t?.fields[n];if(Cf(r.type,i&&We(i)?i:void 0))return!0}}return!1}function Ug({variablesToDrop:e,env:t,context:n}){let r=[],i=t;for(let o of e){let a=Jt(`${k.___drop[0]}(${o.name})`),s=S({expr:a,env:i,context:{...n,expectedType:void 0}});if(r.push(s),s.$?.env)i=s.$.env;else throw y({token:a.token,errorMessage:`Failed to evaluate "___drop" expression for variable "${o.name}":
10401
+ ${w(a)}`})}return{deferredDropExpressions:r.length>0?r:void 0,env:i}}function zg({functionType:e,definitionSiteEnclosingFunctionType:t,parameter:n,argExprs:r,argIndex:i,calleeEnv:o,callerEnv:a,context:s,isMethodCall:l,runtimeArgExprsInOrder:u}){let c=r[i],_;if(c&&F(c)&&E(c,":",2)){if(_=c.args[0],c=c.args[1],!z(_))throw y({token:_.token,errorMessage:`Expected identifier for label, got:
10384
10402
  ${w(_)}`});let C=_.token.value;if(n.label==="")throw y({token:_.token,errorMessage:"Named argument call is not allowed for this parameter (it has no label)."});if(n.label!==C)throw y({token:_.token,errorMessage:`Named argument is not supported. Label is only used for readibility.
10385
10403
  Expected ${n?`label "${n.label}"`:"no label"} at the argument position, but got "${C}".`})}let{parameterType:p,calleeEnv:f}=ea({functionType:e,definitionSiteEnclosingFunctionType:t,parameter:n,calleeEnv:o,context:{...s,isEvaluatingFunctionType:!0}});o=f;let m;if(!c||z(c)&&dt(c,I.undefined))if(n.exprs.defaultValueExpr)m=S({expr:Ae(n.exprs.defaultValueExpr),env:o,context:{...s,expectedType:{type:p,env:o}}}),m.$?.env&&(o=m.$?.env),c&&(c.$=m.$),n.isCompileTimeOnly||u.push(m);else throw y({token:c?.token??ae,errorMessage:`Expected default value for parameter "${n.label}"`});else if(n.isQuote)if(Lt(p))m=Ae(c),m.$={type:_n(),value:Gn(c),env:a,pathCollection:[]};else throw y({token:c.token,errorMessage:`Expected "Expr" type for "quote" parameter "${n.label}", got:
10386
10404
  ${A(p)}`});else{let C=e.ioBuiltin==="io_await"||e.ioBuiltin==="io_state"||e.ioBuiltin==="io_spawn"||e.ioBuiltin==="join_handle_await"?void 0:{type:p,env:o};if(m=S({expr:c,env:a,context:{...s,expectedType:C}}),m.$?.env&&(a=m.$?.env),n.isCompileTimeOnly||u.push(m),ii(m,a),n.isOwningTheRcValue&&!n.isCompileTimeOnly){let L=m.$?.variableName,b=L?X(a,L):[];(b.length?b[b.length-1]:void 0)?.isOwningTheRcValue?a=Tn(m,a,!0):(qt(m,s),m.$?.env&&(a=m.$.env),a=Tn(m,a,!0))}}if(!m.$)throw y({token:c?.token??ae,errorMessage:"Failed to evaluate argument expression."});let g=m.$.type;if(!m.$?.value&&n.isCompileTimeOnly)throw y({token:c?.token??ae,errorMessage:`Cannot assign runtime argument to compile-time parameter:
@@ -10390,7 +10408,7 @@ Got: ${Me(m.$.value)}`});let h=m.$.value;if(!n.isCompileTimeOnly&&ti(g,m.$.env
10390
10408
  ${w(m)}`});let d=n.isCompileTimeOnly||s.forceCompileTimeBindings===!0,{env:v}=me({env:o,variable:{name:n.label,type:g,isCompileTimeOnly:d,value:h?[h]:void 0,token:c?.token??ae,initializedAtToken:c?.token??ae,consumedAtToken:void 0,isOwningTheRcValue:n.isOwningTheRcValue}});if(o=v,h&&O(h)&&x(h.value)){let C=h.value,L=Wn(a,C);if(L){for(let b of L.requiredTraits){let R={...b,receiverType:C};o=er({env:o,someType:C,traitType:R,isNegated:!1})}for(let b of L.negativeTraits){let R={...b,receiverType:C};o=er({env:o,someType:C,traitType:R,isNegated:!0})}}}try{let{expectedEnv:C}=Ze({type:p,env:o},{type:g,env:a});o=C}catch(C){throw y({token:c?.token??ae,errorMessage:`Failed to synthesize types for parameter "${n.label}":
10391
10409
  ${C.message}`})}let{parameterType:T,calleeEnv:$}=ea({functionType:e,definitionSiteEnclosingFunctionType:t,parameter:n,calleeEnv:o,context:{...s,isEvaluatingFunctionType:!0}});if(o=$,!Y({type:T,env:o},{type:g,env:a},i===0&&l))throw y({token:c?.token??ae,errorMessage:`Type mismatch for parameter "${n.label}":
10392
10410
  Expected: ${A(T)}
10393
- Got: ${A(g)}`});return{calleeEnv:o,callerEnv:a,context:{...s},argValue:h,argType:g,parameterType:T}}function uo(e){if(e&&ne(e))return e}function Xa(e){let t=process.env[e];return t==="1"||t?.toLowerCase()==="true"}var Qa=Xa("YO_DEBUG_CALL")||Xa("YO_DEBUG_CALL_PROFILE")||Xa("YO_DEBUG_EVAL")||Xa("YO_DEBUG_EVAL_PROFILE"),Ef=globalThis,Tr=Ef.__yoCallProfilerState??(Ef.__yoCallProfilerState={tryCallCount:0,specializeCount:0,cacheHitCount:0,cacheMissCount:0,specializeNames:new Map,tryCallNames:new Map});function jr({expr:e,functionValue:t,functionType:n,functionCalleeExpr:r,argExprs:i,callerEnv:o,context:a,isMethodCall:s,skipSpecialization:l,skipCtfeExecution:u}){if(Qa){Tr.tryCallCount++;let J="(unknown)";t&&"funcName"in t&&t.funcName?J=t.funcName:t&&"funcId"in t?J=String(t.funcId):r&&(J=w(r).slice(0,60)),Tr.tryCallNames.set(J,(Tr.tryCallNames.get(J)??0)+1),Tr.tryCallCount<=5&&console.log(`[DEBUG tryCall] #${Tr.tryCallCount}: name=${J}, hasFuncValue=${!!t}, hasFuncCalleeExpr=${!!r}`)}t&&(t.specializedType?n=t.specializedType:n=t.type);let c,_=[],p=[],f=[],m=t?.definitionSiteEnclosingFunctionType,g=0;i.length>0&&F(i[0])&&E(i[0],I.forall)&&(c=i[0],g=1);let h,d=i.slice(g),v=d.findIndex(J=>F(J)&&E(J,I.using));if(v!==-1){let J=d.findIndex((Q,oe)=>oe>v&&F(Q)&&E(Q,I.using));if(J!==-1)throw y({token:d[J].token,errorMessage:'Only one "using(...)" is allowed per function call. Combine all implicit arguments into a single using(), e.g.: func(..., using(a, b))'});h=d[v],d=[...d.slice(0,v),...d.slice(v+1)]}let T=n.parameters.length,$=d;if(!n.variadicParameter){if($.length>T){let J=n.parameters.at(-1);if(!(J&&J.isQuote&&Zr(J.type)))throw y({token:r?.token??ae,errorMessage:`Too many arguments for function call:
10411
+ Got: ${A(g)}`});return{calleeEnv:o,callerEnv:a,context:{...s},argValue:h,argType:g,parameterType:T}}function uo(e){if(e&&ne(e))return e}function Xa(e){let t=process.env[e];return t==="1"||t?.toLowerCase()==="true"}var Qa=Xa("YO_DEBUG_CALL")||Xa("YO_DEBUG_CALL_PROFILE")||Xa("YO_DEBUG_EVAL")||Xa("YO_DEBUG_EVAL_PROFILE"),$f=globalThis,Tr=$f.__yoCallProfilerState??($f.__yoCallProfilerState={tryCallCount:0,specializeCount:0,cacheHitCount:0,cacheMissCount:0,specializeNames:new Map,tryCallNames:new Map});function jr({expr:e,functionValue:t,functionType:n,functionCalleeExpr:r,argExprs:i,callerEnv:o,context:a,isMethodCall:s,skipSpecialization:l,skipCtfeExecution:u}){if(Qa){Tr.tryCallCount++;let J="(unknown)";t&&"funcName"in t&&t.funcName?J=t.funcName:t&&"funcId"in t?J=String(t.funcId):r&&(J=w(r).slice(0,60)),Tr.tryCallNames.set(J,(Tr.tryCallNames.get(J)??0)+1),Tr.tryCallCount<=5&&console.log(`[DEBUG tryCall] #${Tr.tryCallCount}: name=${J}, hasFuncValue=${!!t}, hasFuncCalleeExpr=${!!r}`)}t&&(t.specializedType?n=t.specializedType:n=t.type);let c,_=[],p=[],f=[],m=t?.definitionSiteEnclosingFunctionType,g=0;i.length>0&&F(i[0])&&E(i[0],I.forall)&&(c=i[0],g=1);let h,d=i.slice(g),v=d.findIndex(J=>F(J)&&E(J,I.using));if(v!==-1){let J=d.findIndex((Q,oe)=>oe>v&&F(Q)&&E(Q,I.using));if(J!==-1)throw y({token:d[J].token,errorMessage:'Only one "using(...)" is allowed per function call. Combine all implicit arguments into a single using(), e.g.: func(..., using(a, b))'});h=d[v],d=[...d.slice(0,v),...d.slice(v+1)]}let T=n.parameters.length,$=d;if(!n.variadicParameter){if($.length>T){let J=n.parameters.at(-1);if(!(J&&J.isQuote&&Zr(J.type)))throw y({token:r?.token??ae,errorMessage:`Too many arguments for function call:
10394
10412
  Expected: ${T} arguments
10395
10413
  Got: ${$.length} arguments`})}else if($.length<T&&!n.parameters.slice($.length).every(Q=>Q.exprs.defaultValueExpr!==void 0))throw y({token:r?.token??ae,errorMessage:`Too few arguments for function call:
10396
10414
  Expected: ${T} arguments
@@ -10399,31 +10417,31 @@ ${w(ye)}`});if(Q.label!==ye.token.value)throw y({token:ye.token,errorMessage:`Ex
10399
10417
  ${w(ue)}`:"Expected type for default value."});ie=Ye.$?.value}else throw y({token:ue?.token??r?.token??ae,errorMessage:"Type parameter does not have default value."});else{let Ye=S({expr:ue,env:o,context:{...a,expectedType:{type:Q.type,env:b}}});if(Ye.$?.env&&(o=Ye.$.env),!O(Ye.$?.value))throw y({token:ue.token,errorMessage:`Expected type for argument, got:
10400
10418
  ${w(ue)}`});ie=Ye.$?.value}ye&&(ye.$={env:b,type:ie.type,value:ie,pathCollection:[]});let{parameterType:Ne,calleeEnv:$e}=ea({parameter:Q,calleeEnv:b,definitionSiteEnclosingFunctionType:m,context:{...a,isEvaluatingFunctionType:!0},functionType:n});b=$e;let{expectedEnv:Xe,givenEnv:_t}=Ze({type:Ne,env:b},{type:ie.type,env:o});if(b=Xe,o=_t,!Y({type:Ne,env:b},{type:ie.type,env:o}))throw y({token:ue?.token??r?.token??ae,errorMessage:`Type mismatch for type parameter "${Q.label}":
10401
10419
  Expected: ${A(Ne)}
10402
- Got: ${A(ie.type)}`});if(Q.label)if(oe)b=Be(b,oe,{...oe,value:[ie]});else{let Ye=ue?.token??r?.token??ae,{env:Gt}=me({env:b,variable:{name:Q.label,type:ie.type,isCompileTimeOnly:!0,value:[ie],token:Ye,initializedAtToken:Ye,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=Gt}_.push({value:ie,argType:ie.type,parameterType:Ne})}}if(a.expectedType&&!c&&n.forallParameters.length>0&&!n.return.isUnquote)try{let{returnType:J,calleeEnv:Q}=Ei({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r}),{expectedEnv:oe}=Ze({type:J,env:Q},{type:a.expectedType.type,env:a.expectedType.env});b=oe}catch{}if(h&&n.implicitParameters.length>0&&n.implicitParameters.some(Q=>Q.isEffectRowSpread)){let oe=n.implicitParameters.filter(ye=>!ye.isEffectRowSpread).length,ue=h.args.slice(oe);if(ue.length>0){let ye=[];for(let $e of ue){if(!z($e))throw y({token:$e.token,errorMessage:`Expected identifier for using() argument in effect row spread, got ${w($e)}`});let Xe=$e.token.value,Ye=X(o,Xe).at(-1);if(!Ye)throw y({token:$e.token,errorMessage:`Variable "${Xe}" not found for using() argument in effect row spread.`});$e.$={env:o,type:Ye.type,value:Ye.value?.[0],variableName:Xe,pathCollection:[]},ye.push({label:Xe,type:Ye.type,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:$e,labelExpr:$e,typeExpr:void 0,defaultValueExpr:void 0}})}let ie=Lr(ye),Ne=ee(ie);for(let $e of n.implicitParameters){if(!$e.isEffectRowSpread)continue;let Xe=$e.label,Ye=X(b,Xe).at(-1);Ye&&(b=Be(b,Ye,{...Ye,value:[Ne]})),x($e.type)&&$e.type.isEffectsRow&&($e.type.resolvedConcreteType=ie)}}}n.ioBuiltin==="io_async"&&(a={...a,isInsideIoAsyncCall:!0});let R=n.parameters.length;for(let J=0;J<R;J++){let Q=n.parameters[J],{calleeEnv:oe,callerEnv:ue,context:ye,argValue:ie,argType:Ne,parameterType:$e}=Ug({functionType:n,definitionSiteEnclosingFunctionType:m,parameter:Q,argExprs:i,argIndex:J,callerEnv:o,calleeEnv:b,context:a,isMethodCall:s,runtimeArgExprsInOrder:f});b=oe,o=ue,a=ye,p.push({value:ie,parameterType:$e,argType:Ne})}if(!c&&n.forallParameters.length>0){for(let J of n.forallParameters)if(J.label){let oe=X(b,J.label).at(-1);if(oe?.value?.[0]&&O(oe.value[0])){let ue=oe.value[0];if(x(ue.value)&&ue.value.resolvedConcreteType&&(!ue.value.requiredTraits||ue.value.requiredTraits.length===0)){let ye=ee(ue.value.resolvedConcreteType);b=Be(b,oe,{...oe,value:[ye]})}}}}if(!c&&n.forallParameters.length>0){for(let J of n.forallParameters)if(J.label){let oe=X(b,J.label).at(-1);oe?.value?.[0]&&O(oe.value[0])&&_.push({value:oe.value[0],argType:oe.value[0].type,parameterType:J.type})}}if(n.whereClauseExprs?.length){let J=n.whereClauseExprs.map(oe=>Ae(oe));b=Hr({constraintExprs:J,env:b,context:{...a,isEvaluatingFunctionType:!0}}).env}let{returnType:N,calleeEnv:B}=Ei({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});if(b=B,a.expectedType&&!n.return.isUnquote){let{expectedEnv:J}=Ze({type:N,env:b},{type:a.expectedType.type,env:a.expectedType.env});b=J;let Q=Ei({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});N=Q.returnType,b=Q.calleeEnv,Y({type:a.expectedType.type,env:a.expectedType.env},{type:N,env:b})&&(N=a.expectedType.type)}let D=[];if(n.variadicParameter){for(let J=0;J<L.length;J++){let Q=L[J],oe;if(n.variadicParameter.isQuote)oe=Ae(Q),oe.$={type:_n(),value:Gn(Q),env:o,pathCollection:[]},D.push({value:oe.$.value,argType:oe.$.type});else{if(oe=S({expr:Q,env:o,context:{...a}}),!oe.$?.env)throw y({token:Q.token,errorMessage:`Failed to evaluate the expression:
10403
- ${w(Q)}`});o=oe.$.env,D.push({value:oe.$.value,argType:oe.$.type}),n.variadicParameter.isCompileTimeOnly||f.push(Q)}}if(n.variadicParameter.label!=="..."){if(n.variadicParameter.isQuote){let J=zn(_n(),D.map(oe=>oe.value)),{env:Q}=me({env:b,variable:{name:n.variadicParameter.label,type:J.type,isCompileTimeOnly:n.variadicParameter.isCompileTimeOnly,value:[J],token:n.variadicParameter.exprs.expr.token,initializedAtToken:n.variadicParameter.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=Q}}}let V=[],U=[];if(n.implicitParameters.length>0)for(let J=0;J<n.implicitParameters.length;J++){let Q=n.implicitParameters[J],oe=!1;if(Q.isEffectRowSpread){let ie=[],$e=X(b,Q.label).at(-1)?.value?.[0],Xe;if($e&&O($e)&&ot($e.value))Xe=$e.value;else if(x(Q.type)&&Q.type.isEffectsRow){let _t=Ot(b,Q.type);ot(_t)&&(Xe=_t)}else ot(Q.type)&&(Xe=Q.type);if(!Xe&&x(Q.type)&&Q.type.isEffectsRow){let _t=fn(o,Ut=>Ut.isImplicit===!0&&Ut.isCompileTimeOnly===!0&&(G(Ut.type)||Te(Ut.type))),Ye=new Set(n.implicitParameters.filter(Ut=>!Ut.isEffectRowSpread).map(Ut=>Ut.label)),Gt=_t.filter(Ut=>!Ye.has(Ut.name));if(Gt.length>0){for(let rr of Gt){let Qr=rr.value?.[0];if(Qr){U.push({value:Qr,parameterType:rr.type,argType:rr.type});let{env:gm}=me({env:b,variable:{name:rr.name,type:rr.type,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[Qr],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=gm}}let Ut=Lr(Gt.map(rr=>({label:rr.name,type:rr.type,isCompileTimeOnly:!0,isQuote:!1,isOwningTheRcValue:!1,isImplicit:!0,exprs:{expr:void 0,labelExpr:void 0,typeExpr:void 0}}))),mn=ee(Ut),Dr=X(b,Q.label).at(-1);Dr&&(b=Be(b,Dr,{...Dr,value:[mn],type:Ut})),oe=!0;continue}}ie=Xe?.implicitParameters??[];for(let _t of ie){let Ye=_t.type,Ut=fn(o,mn=>mn.isImplicit===!0&&mn.isCompileTimeOnly===!0&&mn.name===_t.label&&Y({type:Ye,env:b},{type:mn.type,env:o})).at(-1);if(Ut?.value?.[0]){let mn=Ut.value[0];U.push({value:mn,parameterType:Ye,argType:Ut.type});let{env:Yn}=me({env:b,variable:{name:_t.label,type:Ye,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[mn],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Yn}else{let Yn=fn(o,Qr=>Qr.isImplicit===!0&&Qr.isCompileTimeOnly===!0&&Y({type:Ye,env:b},{type:Qr.type,env:o})).at(-1);if(!Yn?.value?.[0])throw y({token:r?.token??e?.token??ae,errorMessage:`No "given" variable found for effect row parameter "${_t.label}" of type ${A(Ye)} (expanded from effect row ...(${Q.label})).
10420
+ Got: ${A(ie.type)}`});if(Q.label)if(oe)b=Be(b,oe,{...oe,value:[ie]});else{let Ye=ue?.token??r?.token??ae,{env:Gt}=me({env:b,variable:{name:Q.label,type:ie.type,isCompileTimeOnly:!0,value:[ie],token:Ye,initializedAtToken:Ye,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=Gt}_.push({value:ie,argType:ie.type,parameterType:Ne})}}if(a.expectedType&&!c&&n.forallParameters.length>0&&!n.return.isUnquote)try{let{returnType:J,calleeEnv:Q}=Ei({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r}),{expectedEnv:oe}=Ze({type:J,env:Q},{type:a.expectedType.type,env:a.expectedType.env});b=oe}catch{}if(h&&n.implicitParameters.length>0&&n.implicitParameters.some(Q=>Q.isEffectRowSpread)){let oe=n.implicitParameters.filter(ye=>!ye.isEffectRowSpread).length,ue=h.args.slice(oe);if(ue.length>0){let ye=[];for(let $e of ue){if(!z($e))throw y({token:$e.token,errorMessage:`Expected identifier for using() argument in effect row spread, got ${w($e)}`});let Xe=$e.token.value,Ye=X(o,Xe).at(-1);if(!Ye)throw y({token:$e.token,errorMessage:`Variable "${Xe}" not found for using() argument in effect row spread.`});$e.$={env:o,type:Ye.type,value:Ye.value?.[0],variableName:Xe,pathCollection:[]},ye.push({label:Xe,type:Ye.type,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:$e,labelExpr:$e,typeExpr:void 0,defaultValueExpr:void 0}})}let ie=Lr(ye),Ne=ee(ie);for(let $e of n.implicitParameters){if(!$e.isEffectRowSpread)continue;let Xe=$e.label,Ye=X(b,Xe).at(-1);Ye&&(b=Be(b,Ye,{...Ye,value:[Ne]})),x($e.type)&&$e.type.isEffectsRow&&($e.type.resolvedConcreteType=ie)}}}n.ioBuiltin==="io_async"&&(a={...a,isInsideIoAsyncCall:!0});let R=n.parameters.length;for(let J=0;J<R;J++){let Q=n.parameters[J],{calleeEnv:oe,callerEnv:ue,context:ye,argValue:ie,argType:Ne,parameterType:$e}=zg({functionType:n,definitionSiteEnclosingFunctionType:m,parameter:Q,argExprs:i,argIndex:J,callerEnv:o,calleeEnv:b,context:a,isMethodCall:s,runtimeArgExprsInOrder:f});b=oe,o=ue,a=ye,p.push({value:ie,parameterType:$e,argType:Ne})}if(!c&&n.forallParameters.length>0){for(let J of n.forallParameters)if(J.label){let oe=X(b,J.label).at(-1);if(oe?.value?.[0]&&O(oe.value[0])){let ue=oe.value[0];if(x(ue.value)&&ue.value.resolvedConcreteType&&(!ue.value.requiredTraits||ue.value.requiredTraits.length===0)){let ye=ee(ue.value.resolvedConcreteType);b=Be(b,oe,{...oe,value:[ye]})}}}}if(!c&&n.forallParameters.length>0){for(let J of n.forallParameters)if(J.label){let oe=X(b,J.label).at(-1);oe?.value?.[0]&&O(oe.value[0])&&_.push({value:oe.value[0],argType:oe.value[0].type,parameterType:J.type})}}if(n.whereClauseExprs?.length){let J=n.whereClauseExprs.map(oe=>Ae(oe));b=Hr({constraintExprs:J,env:b,context:{...a,isEvaluatingFunctionType:!0}}).env}let{returnType:N,calleeEnv:B}=Ei({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});if(b=B,a.expectedType&&!n.return.isUnquote){let{expectedEnv:J}=Ze({type:N,env:b},{type:a.expectedType.type,env:a.expectedType.env});b=J;let Q=Ei({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});N=Q.returnType,b=Q.calleeEnv,Y({type:a.expectedType.type,env:a.expectedType.env},{type:N,env:b})&&(N=a.expectedType.type)}let D=[];if(n.variadicParameter){for(let J=0;J<L.length;J++){let Q=L[J],oe;if(n.variadicParameter.isQuote)oe=Ae(Q),oe.$={type:_n(),value:Gn(Q),env:o,pathCollection:[]},D.push({value:oe.$.value,argType:oe.$.type});else{if(oe=S({expr:Q,env:o,context:{...a}}),!oe.$?.env)throw y({token:Q.token,errorMessage:`Failed to evaluate the expression:
10421
+ ${w(Q)}`});o=oe.$.env,D.push({value:oe.$.value,argType:oe.$.type}),n.variadicParameter.isCompileTimeOnly||f.push(Q)}}if(n.variadicParameter.label!=="..."){if(n.variadicParameter.isQuote){let J=zn(_n(),D.map(oe=>oe.value)),{env:Q}=me({env:b,variable:{name:n.variadicParameter.label,type:J.type,isCompileTimeOnly:n.variadicParameter.isCompileTimeOnly,value:[J],token:n.variadicParameter.exprs.expr.token,initializedAtToken:n.variadicParameter.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=Q}}}let V=[],U=[];if(n.implicitParameters.length>0)for(let J=0;J<n.implicitParameters.length;J++){let Q=n.implicitParameters[J],oe=!1;if(Q.isEffectRowSpread){let ie=[],$e=X(b,Q.label).at(-1)?.value?.[0],Xe;if($e&&O($e)&&ot($e.value))Xe=$e.value;else if(x(Q.type)&&Q.type.isEffectsRow){let _t=Ot(b,Q.type);ot(_t)&&(Xe=_t)}else ot(Q.type)&&(Xe=Q.type);if(!Xe&&x(Q.type)&&Q.type.isEffectsRow){let _t=fn(o,zt=>zt.isImplicit===!0&&zt.isCompileTimeOnly===!0&&(G(zt.type)||Te(zt.type))),Ye=new Set(n.implicitParameters.filter(zt=>!zt.isEffectRowSpread).map(zt=>zt.label)),Gt=_t.filter(zt=>!Ye.has(zt.name));if(Gt.length>0){for(let rr of Gt){let Qr=rr.value?.[0];if(Qr){U.push({value:Qr,parameterType:rr.type,argType:rr.type});let{env:hm}=me({env:b,variable:{name:rr.name,type:rr.type,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[Qr],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=hm}}let zt=Lr(Gt.map(rr=>({label:rr.name,type:rr.type,isCompileTimeOnly:!0,isQuote:!1,isOwningTheRcValue:!1,isImplicit:!0,exprs:{expr:void 0,labelExpr:void 0,typeExpr:void 0}}))),mn=ee(zt),Dr=X(b,Q.label).at(-1);Dr&&(b=Be(b,Dr,{...Dr,value:[mn],type:zt})),oe=!0;continue}}ie=Xe?.implicitParameters??[];for(let _t of ie){let Ye=_t.type,zt=fn(o,mn=>mn.isImplicit===!0&&mn.isCompileTimeOnly===!0&&mn.name===_t.label&&Y({type:Ye,env:b},{type:mn.type,env:o})).at(-1);if(zt?.value?.[0]){let mn=zt.value[0];U.push({value:mn,parameterType:Ye,argType:zt.type});let{env:Yn}=me({env:b,variable:{name:_t.label,type:Ye,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[mn],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Yn}else{let Yn=fn(o,Qr=>Qr.isImplicit===!0&&Qr.isCompileTimeOnly===!0&&Y({type:Ye,env:b},{type:Qr.type,env:o})).at(-1);if(!Yn?.value?.[0])throw y({token:r?.token??e?.token??ae,errorMessage:`No "given" variable found for effect row parameter "${_t.label}" of type ${A(Ye)} (expanded from effect row ...(${Q.label})).
10404
10422
  Please ensure a given variable of matching type is in scope.`});let Dr=Yn.value[0];U.push({value:Dr,parameterType:Ye,argType:Yn.type});let{env:rr}=me({env:b,variable:{name:_t.label,type:Ye,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[Dr],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=rr}}continue}let{parameterType:ue,calleeEnv:ye}=ea({parameter:Q,calleeEnv:b,definitionSiteEnclosingFunctionType:m,context:{...a,isEvaluatingFunctionType:!0},functionType:n});if(b=ye,h){let ie=h.args[J],Ne=ie&&z(ie)&&dt(ie,I.undefined);if(ie&&!Ne){let $e=S({expr:ie,env:o,context:{...a}});if(!$e.$)throw y({token:ie.token,errorMessage:`Failed to evaluate using() argument: ${w(ie)}`});o=$e.$.env;let Xe=$e.$.value,_t=$e.$.type;if(!Xe)throw y({token:ie.token,errorMessage:`Expected compile-time value for using() argument, got runtime value: ${w(ie)}`});if(!Y({type:ue,env:b},{type:_t,env:o}))throw y({token:ie.token,errorMessage:`Incompatible type for implicit parameter "${Q.label}":
10405
10423
  Expected: ${A(ue)}
10406
10424
  Got: ${A(_t)}`});U.push({value:Xe,parameterType:ue,argType:_t});let Ye=X(b,Q.label);if(Ye.length>0){let Gt=Ye[Ye.length-1];b=Be(b,Gt,{...Gt,type:ue,isImplicit:!0,value:[Xe]})}else{let{env:Gt}=me({env:b,variable:{name:Q.label,type:ue,isCompileTimeOnly:!0,isImplicit:!0,value:[Xe],token:Q.exprs.labelExpr?.token??ae,initializedAtToken:Q.exprs.labelExpr?.token??ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Gt}oe=!0}}if(!oe){let ie=fn(o,Gt=>Gt.isImplicit===!0&&Gt.isCompileTimeOnly===!0&&Y({type:ue,env:b},{type:Gt.type,env:o}));if(ie.length===0)throw y({token:r?.token??e?.token??ae,errorMessage:`No "given" variable found for implicit parameter "${Q.label}" of type ${A(ue)}.
10407
10425
  Please declare a given variable with a compatible type, e.g.:
10408
10426
  given(${Q.label}) := <value>;
10409
10427
  Or pass it explicitly:
10410
- ${t?.funcName??"func"}(..., using(<value>))`});if(ie[ie.length-1].isFromEffectSpread&&!(()=>{if(!r||!z(r))return!1;let Ut=r.token.value,mn=a.isEvaluatingFunctionBodyOrAsyncBlock;return!mn||mn.kind!=="function-body"?!1:mn.type.parameters.some(Dr=>Dr.label===Ut)})())throw y({token:r?.token??e?.token??ae,errorMessage:`Effect "${Q.label}" of type ${A(ue)} is available through an effect row spread but not explicitly declared in the function's using clause.
10428
+ ${t?.funcName??"func"}(..., using(<value>))`});if(ie[ie.length-1].isFromEffectSpread&&!(()=>{if(!r||!z(r))return!1;let zt=r.token.value,mn=a.isEvaluatingFunctionBodyOrAsyncBlock;return!mn||mn.kind!=="function-body"?!1:mn.type.parameters.some(Dr=>Dr.label===zt)})())throw y({token:r?.token??e?.token??ae,errorMessage:`Effect "${Q.label}" of type ${A(ue)} is available through an effect row spread but not explicitly declared in the function's using clause.
10411
10429
  Add it explicitly:
10412
- using(${Q.label} : ${A(ue)}, ...(E))`});let $e=ie;if($e.length>1){let Gt=Bo(o,Ut=>Ut.isImplicit===!0&&Ut.isCompileTimeOnly===!0&&Y({type:ue,env:b},{type:Ut.type,env:o}));if(Gt>=0){let mn=o.frames[Gt].variables.filter(Yn=>Yn.isImplicit===!0&&Yn.isCompileTimeOnly===!0&&Y({type:ue,env:b},{type:Yn.type,env:o}));mn.length>0&&($e=mn)}}if($e.length>1)throw y({token:r?.token??e?.token??ae,errorMessage:`Ambiguous implicit parameter "${Q.label}": found ${$e.length} "given" variables with compatible type ${A(ue)} in the same scope.
10413
- Please use explicit using() to disambiguate.`});let Xe=$e[$e.length-1],_t=Xe.value?.[0];if(!_t)throw y({token:r?.token??e?.token??ae,errorMessage:`The "given" variable "${Xe.name}" has no compile-time value.`});U.push({value:_t,parameterType:ue,argType:Xe.type});let{env:Ye}=me({env:b,variable:{name:Q.label,type:ue,isCompileTimeOnly:!0,isImplicit:!0,value:[_t],token:Q.exprs.labelExpr?.token??ae,initializedAtToken:Q.exprs.labelExpr?.token??ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Ye}}let re={args:p,forallArgs:_,implicitArgs:U,variadicArgs:D},j;if(n.return.isCompileTimeOnly)if(u)j=K(N,{variableName:n.return.label,env:n.env,context:a});else if(ne(t)){let{value:J,callerEnv:Q,calleeEnv:oe}=oo({functionCalleeExpr:r,functionType:n,functionValue:t,argValues:re,callerEnv:o,calleeEnv:b,context:{...a}});j=J,N=J.type,o=Q,b=oe}else{let J=He(N)&&N.level===0,Q=`${n.id}_return_sometype`;if(J)if(a.expectedType?.type)j=ee(a.expectedType.type);else if(a.isEvaluatingFunctionType){let oe=bn(N,n.return.label,{id:Q,env:b,context:a});oe.functionApplication=e;let ue=Ot(b,oe);j=ee(ue)}else throw y({token:e?.token??r?.token??ae,errorMessage:"Cannot infer comptime return type. Please provide the expected type."});else j=K(N,{variableName:n.return.label,env:n.env,context:a})}Gg({returnType:N,env:b,expr:e,context:a});let W,le=a.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&a.isEvaluatingFunctionBodyOrAsyncBlock.value&&ne(a.isEvaluatingFunctionBodyOrAsyncBlock.value)&&t&&ne(t)&&a.isEvaluatingFunctionBodyOrAsyncBlock.value.funcId===t.funcId,_e=re.implicitArgs?.some(J=>de(J.value)),ve=_e&&!re.implicitArgs?.some(J=>de(J.value)&&!Te(J.parameterType)),q=re.args.some(J=>J.argType&&x(J.argType)),Z=ve&&q,se=(()=>{if(!_e||!n.implicitParameters.some(ue=>ue.isEffectRowSpread))return!1;let Q=0;for(let ue of n.implicitParameters)ue.isEffectRowSpread||Q++;let oe=re.implicitArgs??[];for(let ue=0;ue<Q&&ue<oe.length;ue++)if(de(oe[ue].value))return!1;return!0})(),fe=Pn(n)&&!sr(n)&&n.implicitParameters.some(J=>Te(J.type)?J.type.fields.some(Q=>G(Q.type)&&Q.type.forallParameters.length===0):!!J.isEffectRowSpread);if(!l&&!fe&&t&&ne(t)&&!t.isControlFunction&&Pn(n)&&!le&&(!_e||Z||se)){if(W=zg({originalFunction:t,argValues:re,calleeEnv:b,callerEnv:o,context:a}),W&&x(N)){let J=W.body?.$?.type;J&&!x(J)&&(N=J,W.specializedType&&(W.specializedType={...W.specializedType,return:{...W.specializedType.return,type:J}}))}if(W){let J=new Set,Q=0;for(let oe=0;oe<n.parameters.length;oe++)if(!n.parameters[oe].isCompileTimeOnly){let ie=re.args[oe]?.value;ie&&ne(ie)&&ie.type.implicitParameters.some(Ne=>G(Ne.type)||Te(Ne.type))&&J.add(Q),Q++}if(J.size>0)for(let oe=f.length-1;oe>=0;oe--)J.has(oe)&&f.splice(oe,1)}}if(!l&&t&&ne(t)&&t.isControlFunction&&n.forallParameters.length>0&&!W&&(W=Bg({originalFunction:t,argValues:re,calleeEnv:b,callerEnv:o,context:a}),W&&x(N))){let J=W.body?.$?.type;J&&!x(J)&&(N=J,W.specializedType&&(W.specializedType={...W.specializedType,return:{...W.specializedType.return,type:J}}))}let xe=ji(o),Ke;if(xe.length>0){let J=Pg({variablesToDrop:xe,env:o,context:a});Ke=J.deferredDropExpressions,o=J.env}return{returnType:N,calleeEnv:b,callerEnv:o,pathCollection:V,argValues:re,returnValue:j,specializedFunctionValue:W,runtimeArgExprsInOrder:f,deferredDropExpressions:Ke}}function zg({originalFunction:e,argValues:t,calleeEnv:n,callerEnv:r,context:i}){if(Qa){Tr.specializeCount++;let D=e.funcName??e.funcId;Tr.specializeNames.set(D,(Tr.specializeNames.get(D)??0)+1)}let o=e.type,a=[],s=[];t.forallArgs&&a.push(...t.forallArgs.map(D=>D.value)),t.implicitArgs&&a.push(...t.implicitArgs.map(D=>D.value)),o.parameters.forEach((D,V)=>{let U=t.args[V];if(D.isCompileTimeOnly)U.value&&a.push(U.value);else if(U.value&&ne(U.value)&&U.value.type.implicitParameters.some(j=>G(j.type)||Te(j.type)))U.value&&a.push(U.value);else{let W=x(U.argType)&&U.argType.resolvedConcreteType&&!Ce(U.argType)?U.argType.resolvedConcreteType:U.argType;s.push({...D,type:W})}});let l=s.map(D=>D.type),u=e.specializedFunctionCaches.find(D=>D.compileTimeArgValues.length===a.length&&D.compileTimeArgValues.every((re,j)=>{let W=a[j];return At({value:re,env:D.env},{value:W,env:r})})?D.runtimeParameterTypes.length===l.length&&D.runtimeParameterTypes.every((re,j)=>{let W=l[j];return Y({type:re,env:D.env},{type:W,env:r},!0)}):!1);if(u)return Qa&&Tr.cacheHitCount++,u.specializedFunction;Qa&&Tr.cacheMissCount++;let c=n;for(let D of r.frames)for(let V of D.variables){if(!V.isCompileTimeOnly||X(c,V.name).length>0)continue;let{env:re}=me({env:c,variable:{...V},allowVariableShadowing:!0});c=re}for(let D of s){let V=X(c,D.label);if(V.length>0){let U=V[V.length-1],re={...U,value:void 0};c=Be(c,U,re)}}let _=Ae(e.body),{returnType:p,calleeEnv:f}=Ei({functionType:o,calleeEnv:c,context:{...i,isEvaluatingFunctionType:!0},functionCalleeExpr:void 0});c=f;let m=i.enclosingFunctionReturnType,g=t.implicitArgs?.some(D=>ne(D.value)&&D.value.isControlFunction||We(D.value)&&$f(D.value.type,D.value))??!1,h=ht({expr:_,env:c,context:{...i,expectedType:{type:p,env:c},isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:o,value:e,evaluationEnv:c},isEvaluatingLoopBody:void 0,capturedVariables:void 0,functionReturnImplConcreteType:[],hasControlFunctionImplicitParams:g,...m?{enclosingFunctionReturnType:m}:{}},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(!h.$)throw y({token:e.body.token,errorMessage:"Failed to evaluate function body for specialization."});let d=[],v=0;for(let D=0;D<o.implicitParameters.length;D++){let V=o.implicitParameters[D];if(G(V.type)){let U=t.implicitArgs?.[v];(U&&ne(U.value)?U.value:void 0)?.isControlFunction&&d.push({handlerArgIndex:v,label:V.label,type:V.type,fromSpread:!1}),v+=1}else if(V.isEffectRowSpread){let U=V.type;if(x(U)){let j=X(c,V.label).at(-1)?.value?.[0];if(j&&O(j)&&ot(j.value))U=j.value;else{let W=Ot(c,U);W&&(U=W)}}if(ot(U)){for(let re=0;re<U.implicitParameters.length;re++){let j=U.implicitParameters[re];if(G(j.type)){let W=t.implicitArgs?.[v+re];(W&&ne(W.value)?W.value:void 0)?.isControlFunction&&d.push({handlerArgIndex:v+re,label:j.label,type:j.type,fromSpread:!0})}else if(Te(j.type)){let W=t.implicitArgs?.[v+re],le=W&&We(W.value)?W.value:void 0,_e=[],ve=(q,Z,se)=>{for(let Se=0;Se<q.fields.length;Se++){let fe=q.fields[Se];if(G(fe.type)){let xe=se?.fields[Se];if(xe&&ne(xe)&&xe.isControlFunction){let Ke=xe.specializedType??fe.type;_e.push({path:[...Z,fe.label],type:Ke})}}else if(Te(fe.type)){let xe=se?.fields[Se];ve(fe.type,[...Z,fe.label],xe&&We(xe)?xe:void 0)}}};ve(j.type,[],le);for(let q of _e)d.push({handlerArgIndex:v+re,label:j.label,type:q.type,fromSpread:!0,effectFieldPath:q.path})}}v+=U.implicitParameters.length}else v+=1}else if(Te(V.type)){let U=[],re=t.implicitArgs?.[v],j=(W,le,_e)=>{for(let ve=0;ve<W.fields.length;ve++){let q=W.fields[ve];if(G(q.type)){let Z=_e?.fields[ve];if(Z&&ne(Z)&&Z.isControlFunction){let se=Z.specializedType??q.type;U.push({path:[...le,q.label],type:se})}}else if(Te(q.type)){let Z=_e?.fields[ve];j(q.type,[...le,q.label],Z&&We(Z)?Z:void 0)}}};j(V.type,[],re&&We(re.value)?re.value:void 0);for(let W of U)d.push({handlerArgIndex:v,label:V.label,type:W.type,fromSpread:!1,effectFieldPath:W.path});v+=1}else v+=1}let T=[];for(let D of d){let V=Tf(h,D.label,D.type,!0,D.effectFieldPath);if(V.hasEffects){let U=t.implicitArgs?.[D.handlerArgIndex],re,j=D.effectFieldPath;if(U&&ne(U.value))re=U.value;else if(U&&We(U.value)&&j&&j.length>0){let W=U.value;for(let le of j){if(!We(W)){W=void 0;break}let _e=W.type.fields.findIndex(ve=>ve.label===le);if(_e<0||!W.fields[_e]){W=void 0;break}W=W.fields[_e]}W&&ne(W)&&(re=W)}if(re){let W=re,le=D.type,_e=!W.body.$;if(!_e&&W.isControlFunction&&F(W.body)&&W.body.args.length>0&&!W.body.args[0]?.$&&(_e=!0),_e&&G(le)&&le.forallParameters.length>0&&V.effectCallPoints.length>0){let ve=new Map,q=le.return.type,Z=V.effectCallPoints[0].operationResultType;if(x(q)&&ve.set(q.name,Z),ve.size===0&&le.forallParameters.length===1){let J=le.forallParameters[0];ve.set(J.label,Z)}let se=Ae(W.body),Se=W.body.$?.env??c;Se=Pe(Se);for(let J of le.forallParameters){let Q=ve.get(J.label);Q&&(Se=me({env:Se,variable:{name:J.label,type:J.type,isCompileTimeOnly:!0,value:[ee(Q)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0}).env)}let fe=W.specializedType??W.type,xe=W.definitionSiteEnclosingFunctionType?.return.type??xn(),Ke={...i,expectedType:void 0,enclosingFunctionReturnType:xe,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:fe,value:W,evaluationEnv:Se}};try{let J=Kr({expr:se,env:Se,context:Ke}),Q=fe.parameters.map(ie=>{if(ie.isCompileTimeOnly)return ie;if(x(ie.type)){let Ne=ve.get(ie.type.name);if(Ne)return{...ie,type:Ne}}return ie}),oe=fe.return.type;if(x(oe)){let ie=ve.get(oe.name);ie&&(oe=ie)}let ue={...fe,parameters:Q,return:{...fe.return,type:oe}},ye={...W,body:J,specializedType:ue};V.handlerValue=ye,V.effectParameterType=ue;for(let ie of V.effectCallPoints)ie.isTransitiveEffectCall&&(ie.operationArgTypes=ie.operationArgTypes.map(Ne=>x(Ne)?ve.get(Ne.name)??Ne:Ne))}catch(J){if(F(W.body)&&W.body.args.length>0&&!W.body.args[0]?.$)throw J;V.handlerValue=W}}else V.handlerValue=W}else U&&(V.handlerValue=U.value);T.push({analysis:V,ctlParam:D})}}if(T.length===1)h.$.effectAnalysis=T[0].analysis;else if(T.length>1){let D=[],V=new Map,U=new Map,re=[];for(let le=0;le<T.length;le++){let{analysis:_e}=T[le];re.push({effectParameterName:_e.effectParameterName,effectParameterType:_e.effectParameterType,effectFieldPath:_e.effectFieldPath,handlerValue:_e.handlerValue,operationArgTypes:_e.effectCallPoints.length>0?_e.effectCallPoints[0].operationArgTypes:[],operationResultType:_e.effectCallPoints.length>0?_e.effectCallPoints[0].operationResultType:{tag:"unit"}});for(let ve of _e.effectCallPoints)D.push({...ve,effectIndex:le});for(let ve of _e.capturedVariables)V.has(ve.id)||V.set(ve.id,ve);for(let[ve,q]of _e.variableIdRemapping)U.set(ve,q)}if(F(h)&&E(h,I.begin)){let le=h.args,_e=new Map;for(let q=0;q<le.length;q++)_e.set(le[q],q);let ve=q=>{for(let Z=0;Z<le.length;Z++)if(Nl(le[Z],q.expr))return Z;return 999};D.sort((q,Z)=>ve(q)-ve(Z))}for(let le=0;le<D.length;le++)D[le].index=le;let j=T[0].analysis,W={effectCallPoints:D,capturedVariables:Array.from(V.values()),hasEffects:!0,variableIdRemapping:U,effectParameterName:j.effectParameterName,effectParameterType:j.effectParameterType,effectFieldPath:j.effectFieldPath,handlerValue:j.handlerValue,effectHandlerInfos:re};h.$.effectAnalysis=W}let $=[],C=D=>{if(O(D)){let V=D.value;if(!V.typeName&&V.id)return`${Me(D)}_id${V.id}`}return ne(D)?`fn_${D.funcId}`:Me(D)};o.forallParameters.forEach((D,V)=>{if(V<t.forallArgs.length){let U=t.forallArgs[V];$.push(te(C(U.value)))}else{let U=D.label,re=X(n,U);re.length>0&&re[re.length-1]?.value?.[0]?$.push(te(C(re[re.length-1].value[0]))):$.push("unknown")}}),o.parameters.forEach((D,V)=>{if(D.isCompileTimeOnly&&V<t.args.length){let U=t.args[V];U?$.push(te(C(U.value))):$.push("unknown")}}),t.implicitArgs&&t.implicitArgs.forEach(D=>{$.push(te(C(D.value)))}),s.forEach((D,V)=>{let U=D.type;(!U.typeName&&U.id||Fe(U))&&$.push(`rtparam${V}_${te(A(U))}_id${U.id}`)});let L=$.join("_"),b=[];for(let D of o.implicitParameters)if(D.isEffectRowSpread){let V=D.type;if(x(V)){if(t.forallArgs){for(let U=0;U<o.forallParameters.length;U++)if(o.forallParameters[U].label===V.name&&U<t.forallArgs.length){let j=t.forallArgs[U].value;O(j)&&ot(j.value)&&(V=j.value);break}}if(x(V)&&V.resolvedConcreteType&&ot(V.resolvedConcreteType)&&(V=V.resolvedConcreteType),x(V)){let U=X(c,V.name);if(U.length>0){let j=U[U.length-1].value?.[0];j&&O(j)&&ot(j.value)&&(V=j.value)}}}ot(V)&&b.push(...V.implicitParameters)}else Te(D.type)&&b.push(D);let R=ci({forallParameters:[],parameters:s,implicitParameters:b.length>0?b:void 0,variadicParameter:void 0,return_:{...o.return,type:p},parametersFrame:c.frames[c.frames.length-1],env:o.env,SelfType:o.SelfType}),N={...e,specializedType:R,body:h,isControlFunction:e.isControlFunction||Qn(h),funcId:`${e.funcId}_${L}`,funcName:`${e.funcName}_${L}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},B={funcId:e.funcId,compileTimeArgValues:a,runtimeParameterTypes:l,specializedFunction:N,env:h.$.env};return e.specializedFunctionCaches=[...e.specializedFunctionCaches,B],N}function Bg({originalFunction:e,calleeEnv:t,callerEnv:n,context:r}){let i=e.type,o=r.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?r.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:i.return.type,a=e.definitionSiteEnclosingFunctionType?.return.type??xn(),s=te(A(o)),l=e.specializedFunctionCaches.find(d=>d.specializedFunction.funcId===`${e.funcId}_ctl_${s}`);if(l)return l.specializedFunction;let u=Pe(t);for(let d of n.frames)for(let v of d.variables){if(!v.isCompileTimeOnly||X(u,v.name).length>0)continue;let{env:$}=me({env:u,variable:{...v},allowVariableShadowing:!0});u=$}for(let d of i.forallParameters){let v=o,{env:T}=me({env:u,variable:{name:d.label,type:d.type,isCompileTimeOnly:!0,value:[ee(v)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});u=T}let c=Ae(e.body),_={...r,expectedType:void 0,enclosingFunctionReturnType:a,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:i,value:e,evaluationEnv:u},functionReturnImplConcreteType:[]},p=Kr({expr:c,env:u,context:_}),f={...e,body:p,isControlFunction:e.isControlFunction||Qn(p),funcId:`${e.funcId}_ctl_${s}`,funcName:`${e.funcName??e.funcId}_ctl_${s}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},m=new Set(i.forallParameters.map(d=>d.type)),g=d=>x(d)&&m.has(d)?o:d,h=ci({forallParameters:[],parameters:i.parameters.map(d=>({...d,type:g(d.type)})),implicitParameters:i.implicitParameters.length>0?i.implicitParameters:void 0,variadicParameter:void 0,return_:{...i.return,type:g(i.return.type)},parametersFrame:u.frames[u.frames.length-1],env:i.env,SelfType:i.SelfType});return f.specializedType=h,e.specializedFunctionCaches=[...e.specializedFunctionCaches,{funcId:e.funcId,compileTimeArgValues:[],runtimeParameterTypes:[],specializedFunction:f,env:p.$?.env??u}],f}function Gg({returnType:e,expr:t,env:n,context:r}){if(r.isEvaluatingFunctionType||r.expectedType)return;let i=us(e);for(let o of i){if(Ce(o)||Wt(o)||o.resolvedConcreteType||o.requiredTraits&&o.requiredTraits.length>0)continue;if(!X(n,o.name).length){let s=fn(n,()=>!0),l=!1;for(let u of s)if(O(u.value?.[0])){let c=u.value[0].value,_=us(c);for(let p of _)if(p.name===o.name){l=!0;break}if(l)break}if(l)continue;throw y({token:t?.token??ae,errorMessage:`Failed to infer the function call return type.
10414
- Please consider providing the expected type.`})}}}function Nl(e,t){if(e===t)return!0;if(e.tag==="FnCall"){if(Nl(e.func,t))return!0;for(let n of e.args)if(Nl(n,t))return!0}return!1}function Cf({expr:e,env:t,context:n}){let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for Iso:
10430
+ using(${Q.label} : ${A(ue)}, ...(E))`});let $e=ie;if($e.length>1){let Gt=Bo(o,zt=>zt.isImplicit===!0&&zt.isCompileTimeOnly===!0&&Y({type:ue,env:b},{type:zt.type,env:o}));if(Gt>=0){let mn=o.frames[Gt].variables.filter(Yn=>Yn.isImplicit===!0&&Yn.isCompileTimeOnly===!0&&Y({type:ue,env:b},{type:Yn.type,env:o}));mn.length>0&&($e=mn)}}if($e.length>1)throw y({token:r?.token??e?.token??ae,errorMessage:`Ambiguous implicit parameter "${Q.label}": found ${$e.length} "given" variables with compatible type ${A(ue)} in the same scope.
10431
+ Please use explicit using() to disambiguate.`});let Xe=$e[$e.length-1],_t=Xe.value?.[0];if(!_t)throw y({token:r?.token??e?.token??ae,errorMessage:`The "given" variable "${Xe.name}" has no compile-time value.`});U.push({value:_t,parameterType:ue,argType:Xe.type});let{env:Ye}=me({env:b,variable:{name:Q.label,type:ue,isCompileTimeOnly:!0,isImplicit:!0,value:[_t],token:Q.exprs.labelExpr?.token??ae,initializedAtToken:Q.exprs.labelExpr?.token??ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Ye}}let re={args:p,forallArgs:_,implicitArgs:U,variadicArgs:D},j;if(n.return.isCompileTimeOnly)if(u)j=K(N,{variableName:n.return.label,env:n.env,context:a});else if(ne(t)){let{value:J,callerEnv:Q,calleeEnv:oe}=oo({functionCalleeExpr:r,functionType:n,functionValue:t,argValues:re,callerEnv:o,calleeEnv:b,context:{...a}});j=J,N=J.type,o=Q,b=oe}else{let J=He(N)&&N.level===0,Q=`${n.id}_return_sometype`;if(J)if(a.expectedType?.type)j=ee(a.expectedType.type);else if(a.isEvaluatingFunctionType){let oe=bn(N,n.return.label,{id:Q,env:b,context:a});oe.functionApplication=e;let ue=Ot(b,oe);j=ee(ue)}else throw y({token:e?.token??r?.token??ae,errorMessage:"Cannot infer comptime return type. Please provide the expected type."});else j=K(N,{variableName:n.return.label,env:n.env,context:a})}Wg({returnType:N,env:b,expr:e,context:a});let W,le=a.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&a.isEvaluatingFunctionBodyOrAsyncBlock.value&&ne(a.isEvaluatingFunctionBodyOrAsyncBlock.value)&&t&&ne(t)&&a.isEvaluatingFunctionBodyOrAsyncBlock.value.funcId===t.funcId,_e=re.implicitArgs?.some(J=>de(J.value)),ve=_e&&!re.implicitArgs?.some(J=>de(J.value)&&!Te(J.parameterType)),q=re.args.some(J=>J.argType&&x(J.argType)),Z=ve&&q,se=(()=>{if(!_e||!n.implicitParameters.some(ue=>ue.isEffectRowSpread))return!1;let Q=0;for(let ue of n.implicitParameters)ue.isEffectRowSpread||Q++;let oe=re.implicitArgs??[];for(let ue=0;ue<Q&&ue<oe.length;ue++)if(de(oe[ue].value))return!1;return!0})(),fe=Pn(n)&&!sr(n)&&n.implicitParameters.some(J=>Te(J.type)?J.type.fields.some(Q=>G(Q.type)&&Q.type.forallParameters.length===0):!!J.isEffectRowSpread);if(!l&&!fe&&t&&ne(t)&&!t.isControlFunction&&Pn(n)&&!le&&(!_e||Z||se)){if(W=Bg({originalFunction:t,argValues:re,calleeEnv:b,callerEnv:o,context:a}),W&&x(N)){let J=W.body?.$?.type;J&&!x(J)&&(N=J,W.specializedType&&(W.specializedType={...W.specializedType,return:{...W.specializedType.return,type:J}}))}if(W){let J=new Set,Q=0;for(let oe=0;oe<n.parameters.length;oe++)if(!n.parameters[oe].isCompileTimeOnly){let ie=re.args[oe]?.value;ie&&ne(ie)&&ie.type.implicitParameters.some(Ne=>G(Ne.type)||Te(Ne.type))&&J.add(Q),Q++}if(J.size>0)for(let oe=f.length-1;oe>=0;oe--)J.has(oe)&&f.splice(oe,1)}}if(!l&&t&&ne(t)&&t.isControlFunction&&n.forallParameters.length>0&&!W&&(W=Gg({originalFunction:t,argValues:re,calleeEnv:b,callerEnv:o,context:a}),W&&x(N))){let J=W.body?.$?.type;J&&!x(J)&&(N=J,W.specializedType&&(W.specializedType={...W.specializedType,return:{...W.specializedType.return,type:J}}))}let xe=ji(o),Ke;if(xe.length>0){let J=Ug({variablesToDrop:xe,env:o,context:a});Ke=J.deferredDropExpressions,o=J.env}return{returnType:N,calleeEnv:b,callerEnv:o,pathCollection:V,argValues:re,returnValue:j,specializedFunctionValue:W,runtimeArgExprsInOrder:f,deferredDropExpressions:Ke}}function Bg({originalFunction:e,argValues:t,calleeEnv:n,callerEnv:r,context:i}){if(Qa){Tr.specializeCount++;let D=e.funcName??e.funcId;Tr.specializeNames.set(D,(Tr.specializeNames.get(D)??0)+1)}let o=e.type,a=[],s=[];t.forallArgs&&a.push(...t.forallArgs.map(D=>D.value)),t.implicitArgs&&a.push(...t.implicitArgs.map(D=>D.value)),o.parameters.forEach((D,V)=>{let U=t.args[V];if(D.isCompileTimeOnly)U.value&&a.push(U.value);else if(U.value&&ne(U.value)&&U.value.type.implicitParameters.some(j=>G(j.type)||Te(j.type)))U.value&&a.push(U.value);else{let W=x(U.argType)&&U.argType.resolvedConcreteType&&!Ce(U.argType)?U.argType.resolvedConcreteType:U.argType;s.push({...D,type:W})}});let l=s.map(D=>D.type),u=e.specializedFunctionCaches.find(D=>D.compileTimeArgValues.length===a.length&&D.compileTimeArgValues.every((re,j)=>{let W=a[j];return At({value:re,env:D.env},{value:W,env:r})})?D.runtimeParameterTypes.length===l.length&&D.runtimeParameterTypes.every((re,j)=>{let W=l[j];return Y({type:re,env:D.env},{type:W,env:r},!0)}):!1);if(u)return Qa&&Tr.cacheHitCount++,u.specializedFunction;Qa&&Tr.cacheMissCount++;let c=n;for(let D of r.frames)for(let V of D.variables){if(!V.isCompileTimeOnly||X(c,V.name).length>0)continue;let{env:re}=me({env:c,variable:{...V},allowVariableShadowing:!0});c=re}for(let D of s){let V=X(c,D.label);if(V.length>0){let U=V[V.length-1],re={...U,value:void 0};c=Be(c,U,re)}}let _=Ae(e.body),{returnType:p,calleeEnv:f}=Ei({functionType:o,calleeEnv:c,context:{...i,isEvaluatingFunctionType:!0},functionCalleeExpr:void 0});c=f;let m=i.enclosingFunctionReturnType,g=t.implicitArgs?.some(D=>ne(D.value)&&D.value.isControlFunction||We(D.value)&&Cf(D.value.type,D.value))??!1,h=ht({expr:_,env:c,context:{...i,expectedType:{type:p,env:c},isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:o,value:e,evaluationEnv:c},isEvaluatingLoopBody:void 0,capturedVariables:void 0,functionReturnImplConcreteType:[],hasControlFunctionImplicitParams:g,...m?{enclosingFunctionReturnType:m}:{}},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(!h.$)throw y({token:e.body.token,errorMessage:"Failed to evaluate function body for specialization."});let d=[],v=0;for(let D=0;D<o.implicitParameters.length;D++){let V=o.implicitParameters[D];if(G(V.type)){let U=t.implicitArgs?.[v];(U&&ne(U.value)?U.value:void 0)?.isControlFunction&&d.push({handlerArgIndex:v,label:V.label,type:V.type,fromSpread:!1}),v+=1}else if(V.isEffectRowSpread){let U=V.type;if(x(U)){let j=X(c,V.label).at(-1)?.value?.[0];if(j&&O(j)&&ot(j.value))U=j.value;else{let W=Ot(c,U);W&&(U=W)}}if(ot(U)){for(let re=0;re<U.implicitParameters.length;re++){let j=U.implicitParameters[re];if(G(j.type)){let W=t.implicitArgs?.[v+re];(W&&ne(W.value)?W.value:void 0)?.isControlFunction&&d.push({handlerArgIndex:v+re,label:j.label,type:j.type,fromSpread:!0})}else if(Te(j.type)){let W=t.implicitArgs?.[v+re],le=W&&We(W.value)?W.value:void 0,_e=[],ve=(q,Z,se)=>{for(let Se=0;Se<q.fields.length;Se++){let fe=q.fields[Se];if(G(fe.type)){let xe=se?.fields[Se];if(xe&&ne(xe)&&xe.isControlFunction){let Ke=xe.specializedType??fe.type;_e.push({path:[...Z,fe.label],type:Ke})}}else if(Te(fe.type)){let xe=se?.fields[Se];ve(fe.type,[...Z,fe.label],xe&&We(xe)?xe:void 0)}}};ve(j.type,[],le);for(let q of _e)d.push({handlerArgIndex:v+re,label:j.label,type:q.type,fromSpread:!0,effectFieldPath:q.path})}}v+=U.implicitParameters.length}else v+=1}else if(Te(V.type)){let U=[],re=t.implicitArgs?.[v],j=(W,le,_e)=>{for(let ve=0;ve<W.fields.length;ve++){let q=W.fields[ve];if(G(q.type)){let Z=_e?.fields[ve];if(Z&&ne(Z)&&Z.isControlFunction){let se=Z.specializedType??q.type;U.push({path:[...le,q.label],type:se})}}else if(Te(q.type)){let Z=_e?.fields[ve];j(q.type,[...le,q.label],Z&&We(Z)?Z:void 0)}}};j(V.type,[],re&&We(re.value)?re.value:void 0);for(let W of U)d.push({handlerArgIndex:v,label:V.label,type:W.type,fromSpread:!1,effectFieldPath:W.path});v+=1}else v+=1}let T=[];for(let D of d){let V=Ef(h,D.label,D.type,!0,D.effectFieldPath);if(V.hasEffects){let U=t.implicitArgs?.[D.handlerArgIndex],re,j=D.effectFieldPath;if(U&&ne(U.value))re=U.value;else if(U&&We(U.value)&&j&&j.length>0){let W=U.value;for(let le of j){if(!We(W)){W=void 0;break}let _e=W.type.fields.findIndex(ve=>ve.label===le);if(_e<0||!W.fields[_e]){W=void 0;break}W=W.fields[_e]}W&&ne(W)&&(re=W)}if(re){let W=re,le=D.type,_e=!W.body.$;if(!_e&&W.isControlFunction&&F(W.body)&&W.body.args.length>0&&!W.body.args[0]?.$&&(_e=!0),_e&&G(le)&&le.forallParameters.length>0&&V.effectCallPoints.length>0){let ve=new Map,q=le.return.type,Z=V.effectCallPoints[0].operationResultType;if(x(q)&&ve.set(q.name,Z),ve.size===0&&le.forallParameters.length===1){let J=le.forallParameters[0];ve.set(J.label,Z)}let se=Ae(W.body),Se=W.body.$?.env??c;Se=Pe(Se);for(let J of le.forallParameters){let Q=ve.get(J.label);Q&&(Se=me({env:Se,variable:{name:J.label,type:J.type,isCompileTimeOnly:!0,value:[ee(Q)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0}).env)}let fe=W.specializedType??W.type,xe=W.definitionSiteEnclosingFunctionType?.return.type??xn(),Ke={...i,expectedType:void 0,enclosingFunctionReturnType:xe,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:fe,value:W,evaluationEnv:Se}};try{let J=Kr({expr:se,env:Se,context:Ke}),Q=fe.parameters.map(ie=>{if(ie.isCompileTimeOnly)return ie;if(x(ie.type)){let Ne=ve.get(ie.type.name);if(Ne)return{...ie,type:Ne}}return ie}),oe=fe.return.type;if(x(oe)){let ie=ve.get(oe.name);ie&&(oe=ie)}let ue={...fe,parameters:Q,return:{...fe.return,type:oe}},ye={...W,body:J,specializedType:ue};V.handlerValue=ye,V.effectParameterType=ue;for(let ie of V.effectCallPoints)ie.isTransitiveEffectCall&&(ie.operationArgTypes=ie.operationArgTypes.map(Ne=>x(Ne)?ve.get(Ne.name)??Ne:Ne))}catch(J){if(F(W.body)&&W.body.args.length>0&&!W.body.args[0]?.$)throw J;V.handlerValue=W}}else V.handlerValue=W}else U&&(V.handlerValue=U.value);T.push({analysis:V,ctlParam:D})}}if(T.length===1)h.$.effectAnalysis=T[0].analysis;else if(T.length>1){let D=[],V=new Map,U=new Map,re=[];for(let le=0;le<T.length;le++){let{analysis:_e}=T[le];re.push({effectParameterName:_e.effectParameterName,effectParameterType:_e.effectParameterType,effectFieldPath:_e.effectFieldPath,handlerValue:_e.handlerValue,operationArgTypes:_e.effectCallPoints.length>0?_e.effectCallPoints[0].operationArgTypes:[],operationResultType:_e.effectCallPoints.length>0?_e.effectCallPoints[0].operationResultType:{tag:"unit"}});for(let ve of _e.effectCallPoints)D.push({...ve,effectIndex:le});for(let ve of _e.capturedVariables)V.has(ve.id)||V.set(ve.id,ve);for(let[ve,q]of _e.variableIdRemapping)U.set(ve,q)}if(F(h)&&E(h,I.begin)){let le=h.args,_e=new Map;for(let q=0;q<le.length;q++)_e.set(le[q],q);let ve=q=>{for(let Z=0;Z<le.length;Z++)if(Nl(le[Z],q.expr))return Z;return 999};D.sort((q,Z)=>ve(q)-ve(Z))}for(let le=0;le<D.length;le++)D[le].index=le;let j=T[0].analysis,W={effectCallPoints:D,capturedVariables:Array.from(V.values()),hasEffects:!0,variableIdRemapping:U,effectParameterName:j.effectParameterName,effectParameterType:j.effectParameterType,effectFieldPath:j.effectFieldPath,handlerValue:j.handlerValue,effectHandlerInfos:re};h.$.effectAnalysis=W}let $=[],C=D=>{if(O(D)){let V=D.value;if(!V.typeName&&V.id)return`${Me(D)}_id${V.id}`}return ne(D)?`fn_${D.funcId}`:Me(D)};o.forallParameters.forEach((D,V)=>{if(V<t.forallArgs.length){let U=t.forallArgs[V];$.push(te(C(U.value)))}else{let U=D.label,re=X(n,U);re.length>0&&re[re.length-1]?.value?.[0]?$.push(te(C(re[re.length-1].value[0]))):$.push("unknown")}}),o.parameters.forEach((D,V)=>{if(D.isCompileTimeOnly&&V<t.args.length){let U=t.args[V];U?$.push(te(C(U.value))):$.push("unknown")}}),t.implicitArgs&&t.implicitArgs.forEach(D=>{$.push(te(C(D.value)))}),s.forEach((D,V)=>{let U=D.type;(!U.typeName&&U.id||Fe(U))&&$.push(`rtparam${V}_${te(A(U))}_id${U.id}`)});let L=$.join("_"),b=[];for(let D of o.implicitParameters)if(D.isEffectRowSpread){let V=D.type;if(x(V)){if(t.forallArgs){for(let U=0;U<o.forallParameters.length;U++)if(o.forallParameters[U].label===V.name&&U<t.forallArgs.length){let j=t.forallArgs[U].value;O(j)&&ot(j.value)&&(V=j.value);break}}if(x(V)&&V.resolvedConcreteType&&ot(V.resolvedConcreteType)&&(V=V.resolvedConcreteType),x(V)){let U=X(c,V.name);if(U.length>0){let j=U[U.length-1].value?.[0];j&&O(j)&&ot(j.value)&&(V=j.value)}}}ot(V)&&b.push(...V.implicitParameters)}else Te(D.type)&&b.push(D);let R=ci({forallParameters:[],parameters:s,implicitParameters:b.length>0?b:void 0,variadicParameter:void 0,return_:{...o.return,type:p},parametersFrame:c.frames[c.frames.length-1],env:o.env,SelfType:o.SelfType}),N={...e,specializedType:R,body:h,isControlFunction:e.isControlFunction||Qn(h),funcId:`${e.funcId}_${L}`,funcName:`${e.funcName}_${L}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},B={funcId:e.funcId,compileTimeArgValues:a,runtimeParameterTypes:l,specializedFunction:N,env:h.$.env};return e.specializedFunctionCaches=[...e.specializedFunctionCaches,B],N}function Gg({originalFunction:e,calleeEnv:t,callerEnv:n,context:r}){let i=e.type,o=r.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?r.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:i.return.type,a=e.definitionSiteEnclosingFunctionType?.return.type??xn(),s=te(A(o)),l=e.specializedFunctionCaches.find(d=>d.specializedFunction.funcId===`${e.funcId}_ctl_${s}`);if(l)return l.specializedFunction;let u=Pe(t);for(let d of n.frames)for(let v of d.variables){if(!v.isCompileTimeOnly||X(u,v.name).length>0)continue;let{env:$}=me({env:u,variable:{...v},allowVariableShadowing:!0});u=$}for(let d of i.forallParameters){let v=o,{env:T}=me({env:u,variable:{name:d.label,type:d.type,isCompileTimeOnly:!0,value:[ee(v)],token:ae,initializedAtToken:ae,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});u=T}let c=Ae(e.body),_={...r,expectedType:void 0,enclosingFunctionReturnType:a,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:i,value:e,evaluationEnv:u},functionReturnImplConcreteType:[]},p=Kr({expr:c,env:u,context:_}),f={...e,body:p,isControlFunction:e.isControlFunction||Qn(p),funcId:`${e.funcId}_ctl_${s}`,funcName:`${e.funcName??e.funcId}_ctl_${s}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},m=new Set(i.forallParameters.map(d=>d.type)),g=d=>x(d)&&m.has(d)?o:d,h=ci({forallParameters:[],parameters:i.parameters.map(d=>({...d,type:g(d.type)})),implicitParameters:i.implicitParameters.length>0?i.implicitParameters:void 0,variadicParameter:void 0,return_:{...i.return,type:g(i.return.type)},parametersFrame:u.frames[u.frames.length-1],env:i.env,SelfType:i.SelfType});return f.specializedType=h,e.specializedFunctionCaches=[...e.specializedFunctionCaches,{funcId:e.funcId,compileTimeArgValues:[],runtimeParameterTypes:[],specializedFunction:f,env:p.$?.env??u}],f}function Wg({returnType:e,expr:t,env:n,context:r}){if(r.isEvaluatingFunctionType||r.expectedType)return;let i=us(e);for(let o of i){if(Ce(o)||Wt(o)||o.resolvedConcreteType||o.requiredTraits&&o.requiredTraits.length>0)continue;if(!X(n,o.name).length){let s=fn(n,()=>!0),l=!1;for(let u of s)if(O(u.value?.[0])){let c=u.value[0].value,_=us(c);for(let p of _)if(p.name===o.name){l=!0;break}if(l)break}if(l)continue;throw y({token:t?.token??ae,errorMessage:`Failed to infer the function call return type.
10432
+ Please consider providing the expected type.`})}}}function Nl(e,t){if(e===t)return!0;if(e.tag==="FnCall"){if(Nl(e.func,t))return!0;for(let n of e.args)if(Nl(n,t))return!0}return!1}function bf({expr:e,env:t,context:n}){let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for Iso:
10415
10433
  ${w(r)}`});if(t=i.$.env,!O(i.$.value))throw y({token:r.token,errorMessage:`Iso expects a type as argument, but got:
10416
- ${w(r)}`});let a=i.$.value.value,s=Vu(a,t);t=pu({isoType:s,env:t,context:n});let l=ee(s);return e.$={env:t,type:l.type,value:l,pathCollection:[]},e}function bf({expr:e,env:t,context:n,isoType:r}){let i=e.args[0],o=S({expr:i,env:t,context:{...n,expectedType:{type:r.childType,env:t}}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate the argument expression for Iso value constructor:
10434
+ ${w(r)}`});let a=i.$.value.value,s=Vu(a,t);t=pu({isoType:s,env:t,context:n});let l=ee(s);return e.$={env:t,type:l.type,value:l,pathCollection:[]},e}function kf({expr:e,env:t,context:n,isoType:r}){let i=e.args[0],o=S({expr:i,env:t,context:{...n,expectedType:{type:r.childType,env:t}}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate the argument expression for Iso value constructor:
10417
10435
  ${w(i)}`});t=o.$.env;let a=o.$?.variableName;if(a){let s=X(t,a);if(s.length>0){let l=s[s.length-1];if(wr(l.type,new Set,t))throw y({token:i.token,errorMessage:`Cannot isolate variable ${a} because its type may form RC cycles.`});if(!l.isOwningTheRcValue)throw y({token:i.token,errorMessage:`Cannot isolate variable ${a} because it does not own its RC value.`});let c=t.frames.flatMap(_=>_.variables).filter(_=>_.isOwningTheSameRcValueAs?.id===l.id&&_.id!==l.id);if(c.length>0){let _=c.map(p=>p.name).join(", ");throw y({token:i.token,errorMessage:`Cannot isolate ${a}, also owned by: ${_}
10418
- Iso requires unique ownership (no aliases). Drop other aliases first.`})}}else throw y({token:i.token,errorMessage:`Variable ${a} not found in the environment.`})}return t=Tn(o,t),e.$={env:t,type:r,value:void 0,pathCollection:o.$.pathCollection||[]},Ge(e,!0),e}function kf({moduleExpr:e,moduleType:t,argExprs:n,callerEnv:r,context:i}){if(n.length>t.fields.length)throw y({token:e.token,errorMessage:"Failed to implement the module. Too many fields provided."});let o=Array(t.fields.length).fill(void 0),a={...t,fields:t.fields.map((l,u)=>({...l,assignedValue:o[u]}))};for(let l=0;l<t.fields.length;l++){let u=t.fields[l],c=!1,_;for(let p=0;p<n.length;p++){let f=n[p],m;if(F(f)&&E(f,":",2)){if(m=f.args[0],f=f.args[1],!z(m))throw y({token:m.token,errorMessage:`Expected identifier for label, got:
10436
+ Iso requires unique ownership (no aliases). Drop other aliases first.`})}}else throw y({token:i.token,errorMessage:`Variable ${a} not found in the environment.`})}return t=Tn(o,t),e.$={env:t,type:r,value:void 0,pathCollection:o.$.pathCollection||[]},Ge(e,!0),e}function wf({moduleExpr:e,moduleType:t,argExprs:n,callerEnv:r,context:i}){if(n.length>t.fields.length)throw y({token:e.token,errorMessage:"Failed to implement the module. Too many fields provided."});let o=Array(t.fields.length).fill(void 0),a={...t,fields:t.fields.map((l,u)=>({...l,assignedValue:o[u]}))};for(let l=0;l<t.fields.length;l++){let u=t.fields[l],c=!1,_;for(let p=0;p<n.length;p++){let f=n[p],m;if(F(f)&&E(f,":",2)){if(m=f.args[0],f=f.args[1],!z(m))throw y({token:m.token,errorMessage:`Expected identifier for label, got:
10419
10437
  ${w(m)}`});_=m.token.value}else throw y({token:f.token,errorMessage:`Expected member label, but got:
10420
10438
  ${w(f)}`});if(!t.fields.find(g=>g.label===_))throw y({token:m.token,errorMessage:`Module member with label "${_}" does not exist in the module type.`});if(u.label===_){if(c=!0,u.assignedValue)throw y({token:f.token,errorMessage:`Module member "${u.label}" already has a assigned value:
10421
10439
  ${Me(u.assignedValue)}`});let g,h=u.exprs.typeExpr,d=u.exprs.defaultValueExpr;if(h){let L=S({expr:Ae(h),env:Pe(t.env,r.frames[r.frames.length-1]),context:{...i,expectedType:void 0,ReceiverType:void 0,SelfType:void 0,SelfModuleType:t}}).$?.value;if(!O(L))throw y({token:f.token,errorMessage:`Failed to evaluate the module member "${_}"`});g=L.value}else if(d){let L=S({expr:Ae(d),env:Pe(t.env,r.frames[r.frames.length-1]),context:{...i,expectedType:void 0,ReceiverType:void 0,SelfType:void 0}}).$?.value;if(!L)throw y({token:f.token,errorMessage:`Failed to evaluate the module member "${_}"`});g=L.type}else throw y({token:f.token,errorMessage:`Module member "${_}" has no type or default value or assigned value.`});let v=S({expr:f,env:r,context:{...i,expectedType:{type:g,env:r},ReceiverType:void 0,SelfType:void 0}}),T=v.$?.type;if(!T)throw y({token:f.token,errorMessage:`Failed to evaluate the module member "${_}"`});if(v.$?.env&&(r=v.$.env),!Y({type:g,env:r},{type:T,env:r}))throw y({token:f.token,errorMessage:`Type mismatch for the module member "${_}":
10422
10440
  Expected: ${A(g)}
10423
- Got: ${A(T)}`});let $=v.$?.value;T.ioBuiltin&&(t.fields[l].type.ioBuiltin=T.ioBuiltin),ne($)&&($.funcId+=`_${u.label}`,!$.specializedType&&G(g)&&($.specializedType={...g,parameters:$.type.parameters,parametersFrame:$.type.parametersFrame})),o[l]=$,a.fields[l].assignedValue=$,f.$={env:r,type:T,value:$,pathCollection:[]},m&&(m.$=f.$);break}}if(!c){let p=u.defaultValue,f=u.assignedValue,m=f;if(!f&&p&&(m=p),!m)throw y({token:e.token,errorMessage:`Module member "${u.label}" is not provided and has no required/default value.`});o[l]=m,a.fields[l].assignedValue=m}}return{moduleValue:ca({...t},o),callerEnv:r}}function wf({targetType:e,argExpr:t,expr:n,callerEnv:r,context:i}){if(!Ie(e))return;let o=S({expr:t,env:r,context:{...i,expectedType:void 0}});if(!o.$)throw y({token:t.token,errorMessage:`Failed to evaluate argument: ${w(t)}`});let a=o.$.env,s=o.$.type;if(Et(s)&&(Hn(e.childType)||ki(e.childType))){let u=yt({type:s,expectedType:e,expr:o,env:a});return o.$={...o.$,type:u,convertedRuntimeType:u},Object.assign(n,o),n.$=o.$,{expr:n,env:a}}if(!Ie(s))throw y({token:t.token,errorMessage:`Cannot cast ${A(s)} to ${A(e)}. Expected a pointer type or comptime_string.`});let l={tag:"FnCall",func:{tag:"Atom",token:{...n.token,value:k.__yo_as[0],type:"identifier"},$:void 0},args:[o,n.func],token:n.token,$:{env:a,type:e,value:void 0,pathCollection:o.$.pathCollection,runtimeArgExprsInOrder:[o]}};return ga(n,l),{expr:n,env:a}}function Ff({traitType:e,argExprs:t,callerEnv:n,context:r}){let i=[];for(let a of t){if(!F(a)||!E(a,":=",2))throw y({token:a.token,errorMessage:`Expected ":=" for trait specialization (binding associated types), got:
10441
+ Got: ${A(T)}`});let $=v.$?.value;T.ioBuiltin&&(t.fields[l].type.ioBuiltin=T.ioBuiltin),ne($)&&($.funcId+=`_${u.label}`,!$.specializedType&&G(g)&&($.specializedType={...g,parameters:$.type.parameters,parametersFrame:$.type.parametersFrame})),o[l]=$,a.fields[l].assignedValue=$,f.$={env:r,type:T,value:$,pathCollection:[]},m&&(m.$=f.$);break}}if(!c){let p=u.defaultValue,f=u.assignedValue,m=f;if(!f&&p&&(m=p),!m)throw y({token:e.token,errorMessage:`Module member "${u.label}" is not provided and has no required/default value.`});o[l]=m,a.fields[l].assignedValue=m}}return{moduleValue:ca({...t},o),callerEnv:r}}function Ff({targetType:e,argExpr:t,expr:n,callerEnv:r,context:i}){if(!Ie(e))return;let o=S({expr:t,env:r,context:{...i,expectedType:void 0}});if(!o.$)throw y({token:t.token,errorMessage:`Failed to evaluate argument: ${w(t)}`});let a=o.$.env,s=o.$.type;if(Et(s)&&(Hn(e.childType)||ki(e.childType))){let u=yt({type:s,expectedType:e,expr:o,env:a});return o.$={...o.$,type:u,convertedRuntimeType:u},Object.assign(n,o),n.$=o.$,{expr:n,env:a}}if(!Ie(s))throw y({token:t.token,errorMessage:`Cannot cast ${A(s)} to ${A(e)}. Expected a pointer type or comptime_string.`});let l={tag:"FnCall",func:{tag:"Atom",token:{...n.token,value:k.__yo_as[0],type:"identifier"},$:void 0},args:[o,n.func],token:n.token,$:{env:a,type:e,value:void 0,pathCollection:o.$.pathCollection,runtimeArgExprsInOrder:[o]}};return ga(n,l),{expr:n,env:a}}function Lf({traitType:e,argExprs:t,callerEnv:n,context:r}){let i=[];for(let a of t){if(!F(a)||!E(a,":=",2))throw y({token:a.token,errorMessage:`Expected ":=" for trait specialization (binding associated types), got:
10424
10442
  ${w(a)}`});let s=a.args[0],l=a.args[1];if(!z(s))throw y({token:s.token,errorMessage:`Expected identifier for associated type label, got:
10425
10443
  ${w(s)}`});let u=s.token.value,c=e.fields.find(p=>p.label===u);if(!c)throw y({token:s.token,errorMessage:`Field "${u}" not found in trait "${e.typeName??"unknown"}".`});if(!c.unassignedSomeType&&!He(c.type))throw y({token:s.token,errorMessage:`Field "${u}" is not an associated type. Only associated type fields can be constrained with ":=".`});let _=S({expr:l,env:n,context:{...r}});if(!_.$||!O(_.$.value))throw y({token:l.token,errorMessage:`Expected type for associated type constraint "${u}", got:
10426
- ${w(l)}`});n=_.$.env,i.push({label:u,constraintType:_.$.value.value})}return{specializedTraitType:{...e,associatedTypeConstraints:i},callerEnv:n}}function Lf({traitExpr:e,traitType:t,argExprs:n,callerEnv:r,context:i}){if(n.length>t.fields.length)throw y({token:e.token,errorMessage:"Failed to implement the trait. Too many fields provided."});let o=Array(t.fields.length).fill(void 0),a={...t,fields:t.fields.map((_,p)=>({..._,assignedValue:o[p]}))},s=i.ReceiverType,l=i.ReceiverType??a;if(!s)throw y({token:e.token,errorMessage:`Receiver type is undefined when implementing trait.
10444
+ ${w(l)}`});n=_.$.env,i.push({label:u,constraintType:_.$.value.value})}return{specializedTraitType:{...e,associatedTypeConstraints:i},callerEnv:n}}function Af({traitExpr:e,traitType:t,argExprs:n,callerEnv:r,context:i}){if(n.length>t.fields.length)throw y({token:e.token,errorMessage:"Failed to implement the trait. Too many fields provided."});let o=Array(t.fields.length).fill(void 0),a={...t,fields:t.fields.map((_,p)=>({..._,assignedValue:o[p]}))},s=i.ReceiverType,l=i.ReceiverType??a;if(!s)throw y({token:e.token,errorMessage:`Receiver type is undefined when implementing trait.
10427
10445
  Please consider using "impl" to specify the receiver type explicitly, like:
10428
10446
 
10429
10447
  // impl receiverType, traitImplementation
@@ -10441,11 +10459,11 @@ ${w(f)}`});if(f){let d=f.token.value,v=e.find(T=>T.label===d);if(v){if(v.assigne
10441
10459
  ${Ri(v)}`});_=v}else throw y({token:p.token,errorMessage:`Failed to find "${d}" in the type.`})}if(a.has(_))throw y({token:p.token,errorMessage:`Type member "${_.label}" is already implemented.`});let m=e.indexOf(_),g=S({expr:p,env:r,context:{...i,expectedType:{type:_.type,env:r}}});if(!g.$)throw y({token:p.token,errorMessage:`Failed to evaluate argument expression:
10442
10460
  ${w(p)}`});qt(g,i),r=g.$.env;let h=g.$.type;if(ti(_.type,r)||(h=yt({type:h,expectedType:_.type,expr:g,env:r})),f&&(f.$=g.$),!Y({type:_.type,env:r},{type:h,env:r}))throw y({token:p.token,errorMessage:`Type mismatch for type member "${_.label}":
10443
10461
  Expected: ${A(_.type)}
10444
- Got: ${A(h)}`});s[m]=g.$?.value,l[m]=g,a.add(_)}if(!o)for(let c=0;c<e.length;c++){let _=e[c];if(!a.has(_)){if(!_.defaultValue&&!_.assignedValue)throw y({token:t.token,errorMessage:`Type member "${_.label}" is not provided and has no default value or assigned value.`});s[c]=_.defaultValue??_.assignedValue,l[c]=_.exprs.defaultValueExpr??_.exprs.assignedValueExpr}}return{values:s,pathCollection:[],callerEnv:r,runtimeArgExprsInOrder:l}}function Wg(e,t,n){if(!e.recursiveTypeRef)return;let{functionValue:r,argValues:i}=e.recursiveTypeRef,o=r.calledComptimeFunctionCaches.find(s=>s.argValues.length===i.length&&s.argValues.every((l,u)=>{let c=i[u];return O(l)&&O(c)?Y({type:l.value,env:s.env},{type:c.value,env:t},!0):At({value:l,env:s.env},{value:c,env:t})}));if(o&&O(o.value)&&!(x(o.value.value)&&o.value.value.recursiveTypeRef))return o.value.value;if(n?.SelfType&&pt(n.SelfType)||n?.SelfType&&ce(n.SelfType))return n.SelfType;let a=r.calledComptimeFunctionCaches.find(s=>!(!O(s.value)||x(s.value.value)&&s.value.value.recursiveTypeRef));if(a&&O(a.value))return a.value.value}function Rn({expr:e,env:t,context:n,givenFunc:r,forMacroExpansion:i}){let o=e.func,a=e.args,s,l=[];if(r)l=[r];else if(F(o)){let d=S({expr:o,env:t,context:{...n}});if(o=d,d.$?.type)l=[{type:d.$.type,value:d.$.value}];else if(F(d)&&E(d,".",2)){let v=d.args[0];s=d.args[1];let T=v.$?.type;if(!T)throw y({token:v.token,errorMessage:"Expected to be evaluated."});let $=v.$?.value,C=O($);if(z(s)){let L=s.token.value;if(C){let b=$.value;l=oc({env:t,context:n,methodName:L,type:b}).map(N=>({type:N.type,value:N.value,args:a}))}else l=il({env:t,context:n,methodName:L,receiverType:T,isInfixOperatorCall:!1}).map(R=>{let N;if(R.needsPointerConversion){let B={tag:"Atom",token:v.token,$:void 0};B.token={...v.token,value:"&",type:"identifier"},N=[{tag:"FnCall",func:B,args:[v],token:v.token,$:void 0},...a]}else N=[v,...a];return{type:R.type,value:R.value,needsPointerConversion:R.needsPointerConversion,args:N}})}else{let L=S({expr:s,env:t,context:{...n}});L.$?.env&&(t=L.$?.env),s=L;let b=s.$?.type,R=s.$?.value;if(!b)throw y({token:s.token,errorMessage:"Expected to be a function."});l=[{type:b,value:R}],a=[v,...a]}}else throw y({token:o.token,errorMessage:`Expected type for function call, got ${w(d)}`})}else{let d=o.token.value;if(d==="_"){let v=n.expectedType;if(!v||x(v.type))return uf({expr:e,env:t,context:n});l=[{type:wt(v.type),value:ee(v.type)}],o.$={env:t,type:l[0].type,value:l[0].value,pathCollection:[]}}else if(ir(d)&&e.isInfix){let v=a[0];if(!v)throw y({token:o.token,errorMessage:`Expected first argument for operator, got:
10462
+ Got: ${A(h)}`});s[m]=g.$?.value,l[m]=g,a.add(_)}if(!o)for(let c=0;c<e.length;c++){let _=e[c];if(!a.has(_)){if(!_.defaultValue&&!_.assignedValue)throw y({token:t.token,errorMessage:`Type member "${_.label}" is not provided and has no default value or assigned value.`});s[c]=_.defaultValue??_.assignedValue,l[c]=_.exprs.defaultValueExpr??_.exprs.assignedValueExpr}}return{values:s,pathCollection:[],callerEnv:r,runtimeArgExprsInOrder:l}}function qg(e,t,n){if(!e.recursiveTypeRef)return;let{functionValue:r,argValues:i}=e.recursiveTypeRef,o=r.calledComptimeFunctionCaches.find(s=>s.argValues.length===i.length&&s.argValues.every((l,u)=>{let c=i[u];return O(l)&&O(c)?Y({type:l.value,env:s.env},{type:c.value,env:t},!0):At({value:l,env:s.env},{value:c,env:t})}));if(o&&O(o.value)&&!(x(o.value.value)&&o.value.value.recursiveTypeRef))return o.value.value;if(n?.SelfType&&pt(n.SelfType)||n?.SelfType&&ce(n.SelfType))return n.SelfType;let a=r.calledComptimeFunctionCaches.find(s=>!(!O(s.value)||x(s.value.value)&&s.value.value.recursiveTypeRef));if(a&&O(a.value))return a.value.value}function Rn({expr:e,env:t,context:n,givenFunc:r,forMacroExpansion:i}){let o=e.func,a=e.args,s,l=[];if(r)l=[r];else if(F(o)){let d=S({expr:o,env:t,context:{...n}});if(o=d,d.$?.type)l=[{type:d.$.type,value:d.$.value}];else if(F(d)&&E(d,".",2)){let v=d.args[0];s=d.args[1];let T=v.$?.type;if(!T)throw y({token:v.token,errorMessage:"Expected to be evaluated."});let $=v.$?.value,C=O($);if(z(s)){let L=s.token.value;if(C){let b=$.value;l=oc({env:t,context:n,methodName:L,type:b}).map(N=>({type:N.type,value:N.value,args:a}))}else l=il({env:t,context:n,methodName:L,receiverType:T,isInfixOperatorCall:!1}).map(R=>{let N;if(R.needsPointerConversion){let B={tag:"Atom",token:v.token,$:void 0};B.token={...v.token,value:"&",type:"identifier"},N=[{tag:"FnCall",func:B,args:[v],token:v.token,$:void 0},...a]}else N=[v,...a];return{type:R.type,value:R.value,needsPointerConversion:R.needsPointerConversion,args:N}})}else{let L=S({expr:s,env:t,context:{...n}});L.$?.env&&(t=L.$?.env),s=L;let b=s.$?.type,R=s.$?.value;if(!b)throw y({token:s.token,errorMessage:"Expected to be a function."});l=[{type:b,value:R}],a=[v,...a]}}else throw y({token:o.token,errorMessage:`Expected type for function call, got ${w(d)}`})}else{let d=o.token.value;if(d==="_"){let v=n.expectedType;if(!v||x(v.type))return cf({expr:e,env:t,context:n});l=[{type:Ft(v.type),value:ee(v.type)}],o.$={env:t,type:l[0].type,value:l[0].value,pathCollection:[]}}else if(ir(d)&&e.isInfix){let v=a[0];if(!v)throw y({token:o.token,errorMessage:`Expected first argument for operator, got:
10445
10463
  ${w(o)}`});let $=S({expr:v,env:t,context:{...n,expectedType:void 0}}).$?.type;if(!$)throw y({token:v.token,errorMessage:"Expected to be evaluated."});let C=d;s=o,l=il({env:t,context:n,methodName:C,receiverType:$,isInfixOperatorCall:!0}).map(b=>({type:b.type,value:b.value,needsPointerConversion:b.needsPointerConversion}))}else if(d==="Call"&&n.SelfType){let v=ee(n.SelfType);l=[{type:v.type,value:v}]}else{let v=S({expr:o,env:t,context:{...n}});if(o=v,!v.$)throw y({token:o.token,errorMessage:"Failed to evaluate the callee:"});if(Te(v.$.type)){let T=v.$.type,$=T.fields.findIndex(L=>L.label==="Call");if($<0)throw y({token:o.token,errorMessage:'Calling a module value which does not have "Call" element is not allowed.'});let C=T.fields[$];if(C.assignedValue){let L=C.assignedValue;hn(L)?l=L.fields.map(b=>({type:b.type,value:b})):l=[{type:L.type,value:L}]}else throw y({token:o.token,errorMessage:`Calling a module value whose "Call" element doesn't have assigned value is not allowed.`})}else l=[{type:v.$.type,value:v.$.value}]}}let u=l.length===1&&G(l[0].type)&&l[0].type.return.isCompileTimeOnly&&!l[0].type.return.isUnquote&&!He(l[0].type.return.type)&&l[0].type.forallParameters.length===0,p=l.length===1&&(G(l[0].type)||(x(l[0].type)||be(l[0].type))&&!!nn(l[0].type))?l.map(d=>({...d,result:{kind:"function",result:void 0}})):l.map(d=>{let v=d.args??a;if(G(d.type))try{let T=jr({functionValue:uo(d.value),functionType:d.type,expr:Ae(e),functionCalleeExpr:o,argExprs:v.map($=>Ae($)),callerEnv:rl(t),context:{...n,isInFunctionCallCheckingPhase:!0},isMethodCall:!!s,skipSpecialization:!0,skipCtfeExecution:!0});return{...d,result:{kind:"function",result:T}}}catch(T){if(T instanceof yn&&T.kind==="overflow")throw lt([{token:e.token,errorMessage:`Failed to call the function:
10446
10464
  `},...T.tokenAndErrorList],T.isAssertionError);return{...d,result:{kind:"error",error:T}}}else if((x(d.type)||be(d.type))&&nn(d.type)){let T=nn(d.type);try{let $=jr({functionValue:uo(d.value),functionType:T.isFn.callType,expr:Ae(e),functionCalleeExpr:o,argExprs:v.map(C=>Ae(C)),callerEnv:rl(t),context:{...n,isInFunctionCallCheckingPhase:!0},isMethodCall:!!s,skipSpecialization:!0,skipCtfeExecution:!0});return{...d,result:{kind:"function",result:$}}}catch($){if($ instanceof yn&&$.kind==="overflow")throw lt([{token:e.token,errorMessage:`Failed to call the function:
10447
- `},...$.tokenAndErrorList],$.isAssertionError);return{...d,result:{kind:"error",error:$}}}}else{let T=d.value;if(O(T)&&x(T.value)&&T.value.recursiveTypeRef){let $=Wg(T.value,t,n);$&&(T=ee($),d.value=T,d.type=T.type)}if(O(T)&&ce(T.value))try{let $=Za({typeFields:T.value.fields,functionCalleeExpr:o,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"type",result:$}}}catch($){return{...d,result:{kind:"error",error:$}}}else if(O(T)&&ge(T.value)){let $=T.value,C=$.variants.find(L=>L.name===$.selectedVariantName);if(C)try{let L=Za({typeFields:C.fields||[],functionCalleeExpr:o,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"type",result:L}}}catch(L){return{...d,result:{kind:"error",error:L}}}else return{...d,result:{kind:"error",error:y({token:e.token,errorMessage:"Enum variant not selected for enum type"})}}}else if(O(T)&&it(T.value))try{let $=Za({typeFields:T.value.fields,functionCalleeExpr:o,argExprs:v,callerEnv:t,context:{...n},isUnionType:!0});return{...d,result:{kind:"type",result:$}}}catch($){return{...d,result:{kind:"error",error:$}}}else if(O(T)&&Te(T.value)){let $=T.value;try{let C=kf({moduleExpr:o,moduleType:$,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"module-type",result:C}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&De(T.value)){let $=T.value;if(v.some(L=>F(L)&&E(L,":=",2)))try{let L=Ff({traitExpr:o,traitType:$,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"trait-specialization",result:L}}}catch(L){return{...d,result:{kind:"error",error:L}}}try{let L=Lf({traitExpr:o,traitType:$,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"trait-type",result:L}}}catch(L){return{...d,result:{kind:"error",error:L}}}}else if(O(T)&&G(T.value)){let $=T.value;try{return mf({expr:e,functionType:$,callerEnv:t,context:{...n}}),{...d,result:{kind:"function-type"}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&ke(T.value)){let $=T.value;try{return ff({expr:e,arrayType:$,argExprs:v,callerEnv:t,context:{...n}}),{...d,result:{kind:"array-type"}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&Vt(T.value)){let $=T.value;try{return gf({expr:e,comptimeListType:$,argExprs:v,callerEnv:t,context:{...n}}),{...d,result:{kind:"array-type"}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&(x(T.value)||be(T.value))){let $=T.value,C=nn($);if(C)try{return yf({expr:e,fnModuleType:C,wrapperType:$,callerEnv:t,context:{...n}}),{...d,result:{kind:"closure-type"}}}catch(L){return{...d,result:{kind:"error",error:L}}}else if(x($)&&$.recursiveTypeRef)try{let L=[];for(let b of v){let R=S({expr:b,env:t,context:{...n}});if(!R.$)throw y({token:b.token,errorMessage:"Failed to evaluate argument"});t=R.$.env,L.push(R)}return{...d,result:{kind:"type",result:{values:L.map(b=>b.$.value),pathCollection:[],runtimeArgExprsInOrder:L,callerEnv:t}}}}catch(L){return{...d,result:{kind:"error",error:L}}}else return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Invalid function call on type:
10448
- ${O(T)?A(T.value):A(d.type)}`})}}}else if(ke(d.type)||Qe(d.type))try{let $=d.value,C=Un($)?$:void 0,L=sa($)?$:void 0,b=pf({expr:e,arrayType:d.type,arrayValue:C,sliceValue:L,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"array",result:b}}}catch($){return{...d,result:{kind:"error",error:$}}}else if(O(T)&&Qo(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Numeric type conversion expects exactly 1 argument, got ${v.length}`})}};try{let C=xp({targetType:$,argExpr:v[0],expr:e,callerEnv:t,context:{...n}});return C?{...d,result:{kind:"numeric-type",result:C}}:{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Failed to convert to numeric type ${A($)}`})}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&Ie(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Pointer type casting expects exactly 1 argument, got ${v.length}`})}};try{let C=wf({targetType:$,argExpr:v[0],expr:e,callerEnv:t,context:{...n}});return C?{...d,result:{kind:"pointer-type",result:C}}:{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Failed to cast to pointer type ${A($)}`})}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&kt(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Iso value constructor expects exactly 1 argument, got ${v.length}`})}};try{let C=bf({expr:e,env:t,context:{...n},isoType:$});return{...d,result:{kind:"iso-value",result:C}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&$t(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Arc value constructor expects exactly 1 argument, got ${v.length}`})}};try{let C=_f({expr:e,env:t,context:{...n},arcType:$});return{...d,result:{kind:"arc-value",result:C}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Invalid function call on type:
10465
+ `},...$.tokenAndErrorList],$.isAssertionError);return{...d,result:{kind:"error",error:$}}}}else{let T=d.value;if(O(T)&&x(T.value)&&T.value.recursiveTypeRef){let $=qg(T.value,t,n);$&&(T=ee($),d.value=T,d.type=T.type)}if(O(T)&&ce(T.value))try{let $=Za({typeFields:T.value.fields,functionCalleeExpr:o,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"type",result:$}}}catch($){return{...d,result:{kind:"error",error:$}}}else if(O(T)&&ge(T.value)){let $=T.value,C=$.variants.find(L=>L.name===$.selectedVariantName);if(C)try{let L=Za({typeFields:C.fields||[],functionCalleeExpr:o,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"type",result:L}}}catch(L){return{...d,result:{kind:"error",error:L}}}else return{...d,result:{kind:"error",error:y({token:e.token,errorMessage:"Enum variant not selected for enum type"})}}}else if(O(T)&&it(T.value))try{let $=Za({typeFields:T.value.fields,functionCalleeExpr:o,argExprs:v,callerEnv:t,context:{...n},isUnionType:!0});return{...d,result:{kind:"type",result:$}}}catch($){return{...d,result:{kind:"error",error:$}}}else if(O(T)&&Te(T.value)){let $=T.value;try{let C=wf({moduleExpr:o,moduleType:$,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"module-type",result:C}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&De(T.value)){let $=T.value;if(v.some(L=>F(L)&&E(L,":=",2)))try{let L=Lf({traitExpr:o,traitType:$,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"trait-specialization",result:L}}}catch(L){return{...d,result:{kind:"error",error:L}}}try{let L=Af({traitExpr:o,traitType:$,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"trait-type",result:L}}}catch(L){return{...d,result:{kind:"error",error:L}}}}else if(O(T)&&G(T.value)){let $=T.value;try{return yf({expr:e,functionType:$,callerEnv:t,context:{...n}}),{...d,result:{kind:"function-type"}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&ke(T.value)){let $=T.value;try{return df({expr:e,arrayType:$,argExprs:v,callerEnv:t,context:{...n}}),{...d,result:{kind:"array-type"}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&Vt(T.value)){let $=T.value;try{return hf({expr:e,comptimeListType:$,argExprs:v,callerEnv:t,context:{...n}}),{...d,result:{kind:"array-type"}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&(x(T.value)||be(T.value))){let $=T.value,C=nn($);if(C)try{return gf({expr:e,fnModuleType:C,wrapperType:$,callerEnv:t,context:{...n}}),{...d,result:{kind:"closure-type"}}}catch(L){return{...d,result:{kind:"error",error:L}}}else if(x($)&&$.recursiveTypeRef)try{let L=[];for(let b of v){let R=S({expr:b,env:t,context:{...n}});if(!R.$)throw y({token:b.token,errorMessage:"Failed to evaluate argument"});t=R.$.env,L.push(R)}return{...d,result:{kind:"type",result:{values:L.map(b=>b.$.value),pathCollection:[],runtimeArgExprsInOrder:L,callerEnv:t}}}}catch(L){return{...d,result:{kind:"error",error:L}}}else return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Invalid function call on type:
10466
+ ${O(T)?A(T.value):A(d.type)}`})}}}else if(ke(d.type)||Qe(d.type))try{let $=d.value,C=Un($)?$:void 0,L=sa($)?$:void 0,b=ff({expr:e,arrayType:d.type,arrayValue:C,sliceValue:L,argExprs:v,callerEnv:t,context:{...n}});return{...d,result:{kind:"array",result:b}}}catch($){return{...d,result:{kind:"error",error:$}}}else if(O(T)&&Qo(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Numeric type conversion expects exactly 1 argument, got ${v.length}`})}};try{let C=Dp({targetType:$,argExpr:v[0],expr:e,callerEnv:t,context:{...n}});return C?{...d,result:{kind:"numeric-type",result:C}}:{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Failed to convert to numeric type ${A($)}`})}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&Ie(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Pointer type casting expects exactly 1 argument, got ${v.length}`})}};try{let C=Ff({targetType:$,argExpr:v[0],expr:e,callerEnv:t,context:{...n}});return C?{...d,result:{kind:"pointer-type",result:C}}:{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Failed to cast to pointer type ${A($)}`})}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&wt(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Iso value constructor expects exactly 1 argument, got ${v.length}`})}};try{let C=kf({expr:e,env:t,context:{...n},isoType:$});return{...d,result:{kind:"iso-value",result:C}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else if(O(T)&&Ct(T.value)){let $=T.value;if(v.length!==1)return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Arc value constructor expects exactly 1 argument, got ${v.length}`})}};try{let C=pf({expr:e,env:t,context:{...n},arcType:$});return{...d,result:{kind:"arc-value",result:C}}}catch(C){return{...d,result:{kind:"error",error:C}}}}else return{...d,result:{kind:"error",error:y({token:o.token,errorMessage:`Invalid function call on type:
10449
10467
  ${O(T)?A(T.value):A(d.type)}`})}}}}),f=p.filter(d=>d.result.kind!=="error"),m=f.filter(d=>G(d.type)&&d.type.return.isCompileTimeOnly);if(m.length===1&&(f=m),f.length>1){let d=f.filter(v=>G(v.type)?v.type.parameters.some($=>vt($.type)||Nt($.type)||Et($.type)):!1);d.length===1&&(f=d)}if(f.length===0){if(p.length===1&&p[0].result.kind==="error"){let d=p[0].result.error;throw d instanceof yn?lt([{token:e.token,errorMessage:`Failed to call the function:
10450
10468
 
10451
10469
  ${d.tokenAndErrorList.filter(({token:v})=>v.modulePath!==e.token.modulePath).map(({errorMessage:v})=>`- ${v}`).join(`
@@ -10464,89 +10482,89 @@ ${f.map(d=>`${A(d.type)}`).join(`
10464
10482
  `)}
10465
10483
  `});let g=f[0];if(n.isInFunctionCallCheckingPhase&&u){let d=g.type,{returnType:v}=Ei({functionType:d,calleeEnv:d.env,context:{...n,isEvaluatingFunctionType:!0},functionCalleeExpr:o});return t=ct(t),e.$={env:t,type:v,value:K(v,{variableName:"checking_phase_placeholder_"+qe(t.modulePath),env:t,context:n}),pathCollection:[]},e}if(i)if(G(g.type)&&g.type.return.isUnquote){let{returnValue:d,callerEnv:v,pathCollection:T,deferredDropExpressions:$}=jr({functionValue:uo(g.value),functionType:g.type,expr:e,functionCalleeExpr:o,argExprs:g.args??a,callerEnv:t,context:n,isMethodCall:!!s});return t=ct(v),e.$={env:t,type:_n(),value:d,originType:_n(),pathCollection:T,deferredDropExpressions:$},e}else throw y({token:o.token,errorMessage:"Expected macro function call for macro_expand."});if(G(g.type)){let d=g.type;{let{returnType:v,returnValue:T,callerEnv:$,pathCollection:C,specializedFunctionValue:L,runtimeArgExprsInOrder:b,deferredDropExpressions:R}=jr({functionValue:uo(g.value),functionType:g.type,expr:e,functionCalleeExpr:o,argExprs:g.args??a,callerEnv:t,context:n,isMethodCall:!!s});if(t=ct($),d.return.isUnquote)if(ln(T)){let D=S({expr:T.value,env:t,context:{...n}});return e.$={env:D.$?.env||t,type:D.$?.type||v,value:D.$?.value,originType:D.$?.originType||D.$?.type||v,pathCollection:D.$?.pathCollection||[],macroExpansion:D,variableName:D.$?.variableName},e}else throw y({token:e.token,errorMessage:`Expected macro function to return an Expr value, got:
10466
10484
  ${Me(T)}`});let N=e.$?.variableName,B=v;if(x(v))if(g.value&&ne(g.value)){let D=g.value.body;if(D.$?.type){let V=D.$.type;x(V)&&V.resolvedConcreteType&&(V=V.resolvedConcreteType),B={...v,resolvedConcreteType:V}}}else G(g.type)&&g.type.return?.type&&!x(g.type.return.type)&&(B={...v,resolvedConcreteType:g.type.return.type});if(e.$={env:t,type:B,value:T,originType:B,pathCollection:C,runtimeArgExprsInOrder:b,deferredDropExpressions:R,variableName:N},d.ioBuiltin==="io_async"&&b[0]){let D=b[0],V=D.$?.closureFunctionValue;if(V?.body?.$?.awaitAnalysis){e.$.awaitAnalysis=V.body.$.awaitAnalysis,e.$.captureType=D.$?.captureType,e.$.deferredDupExpressions=D.$?.deferredDupExpressions,D.$?.deferredDupExpressions&&(D.$.deferredDupExpressions=void 0);let re=D.$?.captureType;if(re&&e.$.awaitAnalysis){let j=new Set(re.fields.map(W=>W.label));e.$.awaitAnalysis={...e.$.awaitAnalysis,capturedVariables:e.$.awaitAnalysis.capturedVariables.map(W=>j.has(W.name)?{...W,kind:"outer"}:W)}}V.isIoAsyncStateMachineClosure=!0}else D.$?.deferredDupExpressions&&(D.$.deferredDupExpressions=void 0);let U=D.$?.variableName;if(U&&e.$.env){let re=X(e.$.env,U),j=re[re.length-1];j&&(e.$.env=Be(e.$.env,j,{...j,consumedAtToken:e.token}))}}Ge(e,!0),o.$={env:t,type:g.type,value:L||g.value,pathCollection:[]},s&&(s.$={env:t,type:g.type,value:L||g.value,pathCollection:[]})}return e}else if((x(g.type)||be(g.type))&&nn(g.type)){let d=nn(g.type),{returnType:v,returnValue:T,callerEnv:$,pathCollection:C,specializedFunctionValue:L,runtimeArgExprsInOrder:b,deferredDropExpressions:R}=jr({functionValue:uo(g.value),functionType:d.isFn.callType,expr:e,functionCalleeExpr:o,argExprs:g.args??a,callerEnv:t,context:n,isMethodCall:!!s});if(t=ct($),d.isFn.callType.return.isUnquote)if(ln(T)){let N=S({expr:T.value,env:t,context:{...n}});return e.$={env:N.$?.env||t,type:N.$?.type||v,value:N.$?.value,originType:N.$?.originType||N.$?.type||v,pathCollection:N.$?.pathCollection||[],macroExpansion:N},e}else throw y({token:e.token,errorMessage:`Expected macro closure to return an Expr value, got:
10467
- ${Me(T)}`});return e.$={env:t,type:v,value:T,originType:v,pathCollection:C,runtimeArgExprsInOrder:b,deferredDropExpressions:R},Ge(e,!0),o.$={env:t,type:g.type,value:L||g.value,pathCollection:[]},s&&(s.$={env:t,type:g.type,value:L||g.value,pathCollection:[]}),e}else{let d=g.value;if(O(d)&&ce(d.value)){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let{values:T,pathCollection:$,callerEnv:C,runtimeArgExprsInOrder:L}=Jo(g);if(t=C,!T)throw y({token:o.token,errorMessage:"Error evaluating struct call."});let b=T.some(R=>!R)?void 0:Bn(v,T);return e.$.value=pt(v)?void 0:b,e.$.pathCollection=$,e.$.env=t,e.$.runtimeArgExprsInOrder=L,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&ge(d.value)){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let T=v.variants.find(R=>R.name===v.selectedVariantName);if(!T)throw y({token:e.token,errorMessage:"Enum variant not selected for enum type"});let{values:$,pathCollection:C,callerEnv:L,runtimeArgExprsInOrder:b}=Jo(g);if(t=L,$.every(R=>!!R)){let R=Jr(v,T.name,$);e.$.value=R}return e.$.pathCollection=C,e.$.env=t,e.$.runtimeArgExprsInOrder=b,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&it(d.value)){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let{pathCollection:T,callerEnv:$,runtimeArgExprsInOrder:C}=Jo(g);return t=$,e.$.value=void 0,e.$.pathCollection=T,e.$.env=t,e.$.runtimeArgExprsInOrder=C,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&Te(d.value)){let{moduleValue:v,callerEnv:T}=nf(g);return t=T,e.$={env:t,type:v.type,value:v,originType:v.type,pathCollection:[]},o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&De(d.value)){if(g.result.kind==="trait-specialization"){let $=g.result.result;t=$.callerEnv;let C=ee($.specializedTraitType);return e.$={env:t,type:C.type,value:C,pathCollection:[]},o.$={env:t,type:d.type,value:d,pathCollection:[]},e}let{traitValue:v,callerEnv:T}=rf(g);return t=T,e.$={env:t,type:v.type,value:v,originType:v.type,pathCollection:[]},o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else{if(O(d)&&G(d.value))return e;if(O(d)&&ke(d.value))return e;if(O(d)&&Vt(d.value))return e;if(O(d)&&(x(d.value)||be(d.value))){if(g.result.kind==="type"&&x(d.value)&&d.value.recursiveTypeRef){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let{pathCollection:T,callerEnv:$,runtimeArgExprsInOrder:C}=Jo(g);return t=$,e.$.value=void 0,e.$.pathCollection=T,e.$.env=t,e.$.runtimeArgExprsInOrder=C,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}return e}else{if(O(d)&&Qo(d.value))return e;if(O(d)&&Ie(d.value))return e;if(O(d)&&kt(d.value))return e;if(O(d)&&$t(d.value))return e;if(ke(g.type)||Qe(g.type)){let{value:v,index:T,type:$,arrayElementRef:C,callerEnv:L}=of(g),b=o.$?.pathCollection??[];return a.length===1&&typeof T=="number"&&(b.length>0?b=b.map(R=>[...R,T.toString()]):o.$?.variableName&&(b=[[o.$.variableName,T.toString()]])),e.$={env:L,type:$,value:v,originType:o.$?.originType??g.type,pathCollection:b,sourceVariable:o.$?.sourceVariable,arrayElementRef:C,isAccessingProperty:!0},o.$={env:t,type:g.type,value:g.value,pathCollection:o.$?.pathCollection??[],isAccessingProperty:!0},Ge(e,!1),e}}}}throw y({token:e.token,errorMessage:`Function call is not implemented yet:
10468
- ${w(e)}`})}function qg(e){if(!e.$?.type||!we(e.$.type))throw y({token:e.token,errorMessage:`Expected tuple type for drop generation:
10485
+ ${Me(T)}`});return e.$={env:t,type:v,value:T,originType:v,pathCollection:C,runtimeArgExprsInOrder:b,deferredDropExpressions:R},Ge(e,!0),o.$={env:t,type:g.type,value:L||g.value,pathCollection:[]},s&&(s.$={env:t,type:g.type,value:L||g.value,pathCollection:[]}),e}else{let d=g.value;if(O(d)&&ce(d.value)){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let{values:T,pathCollection:$,callerEnv:C,runtimeArgExprsInOrder:L}=Jo(g);if(t=C,!T)throw y({token:o.token,errorMessage:"Error evaluating struct call."});let b=T.some(R=>!R)?void 0:Bn(v,T);return e.$.value=pt(v)?void 0:b,e.$.pathCollection=$,e.$.env=t,e.$.runtimeArgExprsInOrder=L,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&ge(d.value)){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let T=v.variants.find(R=>R.name===v.selectedVariantName);if(!T)throw y({token:e.token,errorMessage:"Enum variant not selected for enum type"});let{values:$,pathCollection:C,callerEnv:L,runtimeArgExprsInOrder:b}=Jo(g);if(t=L,$.every(R=>!!R)){let R=Jr(v,T.name,$);e.$.value=R}return e.$.pathCollection=C,e.$.env=t,e.$.runtimeArgExprsInOrder=b,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&it(d.value)){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let{pathCollection:T,callerEnv:$,runtimeArgExprsInOrder:C}=Jo(g);return t=$,e.$.value=void 0,e.$.pathCollection=T,e.$.env=t,e.$.runtimeArgExprsInOrder=C,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&Te(d.value)){let{moduleValue:v,callerEnv:T}=rf(g);return t=T,e.$={env:t,type:v.type,value:v,originType:v.type,pathCollection:[]},o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else if(O(d)&&De(d.value)){if(g.result.kind==="trait-specialization"){let $=g.result.result;t=$.callerEnv;let C=ee($.specializedTraitType);return e.$={env:t,type:C.type,value:C,pathCollection:[]},o.$={env:t,type:d.type,value:d,pathCollection:[]},e}let{traitValue:v,callerEnv:T}=of(g);return t=T,e.$={env:t,type:v.type,value:v,originType:v.type,pathCollection:[]},o.$={env:t,type:d.type,value:d,pathCollection:[]},e}else{if(O(d)&&G(d.value))return e;if(O(d)&&ke(d.value))return e;if(O(d)&&Vt(d.value))return e;if(O(d)&&(x(d.value)||be(d.value))){if(g.result.kind==="type"&&x(d.value)&&d.value.recursiveTypeRef){let v=d.value;e.$={env:t,type:v,originType:v,pathCollection:[]};let{pathCollection:T,callerEnv:$,runtimeArgExprsInOrder:C}=Jo(g);return t=$,e.$.value=void 0,e.$.pathCollection=T,e.$.env=t,e.$.runtimeArgExprsInOrder=C,Ge(e,!0),o.$={env:t,type:d.type,value:d,pathCollection:[]},e}return e}else{if(O(d)&&Qo(d.value))return e;if(O(d)&&Ie(d.value))return e;if(O(d)&&wt(d.value))return e;if(O(d)&&Ct(d.value))return e;if(ke(g.type)||Qe(g.type)){let{value:v,index:T,type:$,arrayElementRef:C,callerEnv:L}=af(g),b=o.$?.pathCollection??[];return a.length===1&&typeof T=="number"&&(b.length>0?b=b.map(R=>[...R,T.toString()]):o.$?.variableName&&(b=[[o.$.variableName,T.toString()]])),e.$={env:L,type:$,value:v,originType:o.$?.originType??g.type,pathCollection:b,sourceVariable:o.$?.sourceVariable,arrayElementRef:C,isAccessingProperty:!0},o.$={env:t,type:g.type,value:g.value,pathCollection:o.$?.pathCollection??[],isAccessingProperty:!0},Ge(e,!1),e}}}}throw y({token:e.token,errorMessage:`Function call is not implemented yet:
10486
+ ${w(e)}`})}function Yg(e){if(!e.$?.type||!we(e.$.type))throw y({token:e.token,errorMessage:`Expected tuple type for drop generation:
10469
10487
  ${w(e)}`});if(!e.$.variableName)throw y({token:e.token,errorMessage:`Expected variable name for drop generation:
10470
10488
  ${w(e)}`});let n=e.$.type.fields.map((i,o)=>({index:o,element:i,needsDrop:Le(x(i.type)&&i.type.resolvedConcreteType?i.type.resolvedConcreteType:i.type)})).filter(({needsDrop:i})=>i);return n.length===0?"":`begin(
10471
10489
  ${n.map(({index:i})=>`${k.__yo_drop_tuple_element[0]}(${e.$.variableName}, ${i})`).join(`,
10472
10490
  `)}
10473
- )`}function Yg(e){if(!e.$?.type||!ke(e.$.type))throw y({token:e.token,errorMessage:`Expected array type for drop generation:
10491
+ )`}function Hg(e){if(!e.$?.type||!ke(e.$.type))throw y({token:e.token,errorMessage:`Expected array type for drop generation:
10474
10492
  ${w(e)}`});if(!e.$.variableName)throw y({token:e.token,errorMessage:`Expected variable name for drop generation:
10475
10493
  ${w(e)}`});let t=e.$.type,n=t.childType,r=x(n)&&n.resolvedConcreteType?n.resolvedConcreteType:n;if(!Le(r))return"";let i=t.length;if(!ze(i))return"";let o=i.value,a=[];for(let s=0;s<o;s++)a.push(`${k.__yo_drop_array_element[0]}(${e.$.variableName}, ${s})`);return`begin(
10476
10494
  ${a.join(`,
10477
10495
  `)}
10478
- )`}function Af({expr:e,env:t,context:n}){he(e,k.___drop,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.___drop[0]}":
10496
+ )`}function If({expr:e,env:t,context:n}){he(e,k.___drop,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.___drop[0]}":
10479
10497
  ${w(r)}`});t=i.$.env;let o=i.$?.variableName;if(!o)throw y({token:r.token,errorMessage:`Expected variable name as argument to "${k.___drop[0]}":
10480
10498
  ${w(i)}
10481
10499
 
10482
10500
  Original expression:
10483
- ${w(r)}`});let a=i.$.type,l=x(a)&&a.resolvedConcreteType&&!Ce(a)?a.resolvedConcreteType:a;if(Le(l))if(we(l)){let u=qg(i);if(u){let c=Jt(u);t=Tn(i,t,!0);let _=S({expr:c,env:t,context:{...n}});return F(_)?(dr(e,_),e):_}else return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}else if(ke(l)){let u=Yg(i);if(u){let c=Jt(u);t=Tn(i,t,!0);let _=S({expr:c,env:t,context:{...n}});return F(_)?(dr(e,_),e):_}else return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}else{if(x(l)&&!Ce(l))return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e;{let u=i.$?.variableName;if(u){let g=X(t,u),h=g.length?g[g.length-1]:void 0;if(h&&!h.isOwningTheRcValue)return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e}let c=Jt(`(${w(i)}).___drop()`),_=Rn({env:t,context:{...n},expr:c});if(!_.$?.env)throw y({token:e.token,errorMessage:`Failed to get updated environment after evaluating "${k.___drop[0]}" method call:
10501
+ ${w(r)}`});let a=i.$.type,l=x(a)&&a.resolvedConcreteType&&!Ce(a)?a.resolvedConcreteType:a;if(Le(l))if(we(l)){let u=Yg(i);if(u){let c=Jt(u);t=Tn(i,t,!0);let _=S({expr:c,env:t,context:{...n}});return F(_)?(dr(e,_),e):_}else return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}else if(ke(l)){let u=Hg(i);if(u){let c=Jt(u);t=Tn(i,t,!0);let _=S({expr:c,env:t,context:{...n}});return F(_)?(dr(e,_),e):_}else return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}else{if(x(l)&&!Ce(l))return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e;{let u=i.$?.variableName;if(u){let g=X(t,u),h=g.length?g[g.length-1]:void 0;if(h&&!h.isOwningTheRcValue)return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e}let c=Jt(`(${w(i)}).___drop()`),_=Rn({env:t,context:{...n},expr:c});if(!_.$?.env)throw y({token:e.token,errorMessage:`Failed to get updated environment after evaluating "${k.___drop[0]}" method call:
10484
10502
  ${w(c)}`});let f=X(_.$.env,o).at(-1);if(!f)throw y({token:e.token,errorMessage:`Variable "${o}" not found in environment after evaluating "${k.___drop[0]}" method call:
10485
- ${w(c)}`});let m=Be(_.$.env,f,{...f,consumedAtToken:e.token});return _.$.env=m,_}}else return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e}function Hg(e){if(!e.$?.type||!we(e.$.type))throw new Error("Expected tuple type for dup generation");if(!e.$.variableName)throw y({token:e.token,errorMessage:`Expected variable name for drop generation:
10503
+ ${w(c)}`});let m=Be(_.$.env,f,{...f,consumedAtToken:e.token});return _.$.env=m,_}}else return t=Tn(i,t,!0),e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e}function jg(e){if(!e.$?.type||!we(e.$.type))throw new Error("Expected tuple type for dup generation");if(!e.$.variableName)throw y({token:e.token,errorMessage:`Expected variable name for drop generation:
10486
10504
  ${w(e)}`});let n=e.$.type.fields.map((i,o)=>({index:o,element:i,needsDup:Le(i.type)}));return n.every(({needsDup:i})=>!i)?"":`begin(
10487
10505
  ${n.map(({index:i,needsDup:o})=>o?`${k.__yo_dup_tuple_element[0]}(${e.$?.variableName}, ${i})`:"").filter(i=>i.length>0).join(`,
10488
10506
  `)}
10489
- )`}function jg(e){if(!e.$?.type||!ke(e.$.type))throw new Error("Expected array type for dup generation");if(!e.$.variableName)throw y({token:e.token,errorMessage:`Expected variable name for dup generation:
10507
+ )`}function Kg(e){if(!e.$?.type||!ke(e.$.type))throw new Error("Expected array type for dup generation");if(!e.$.variableName)throw y({token:e.token,errorMessage:`Expected variable name for dup generation:
10490
10508
  ${w(e)}`});let t=e.$.type,n=t.childType;if(!Le(n))return"";if(ze(t.length)){let r=t.length.value;return`begin(
10491
10509
  ${Array.from({length:Number(r)},(i,o)=>`${k.__yo_dup_array_element[0]}(${e.$?.variableName}, ${o})`).join(", ")}
10492
- )`}else return""}function If({expr:e,env:t,context:n}){he(e,k.___dup,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.___dup[0]}":
10493
- ${w(r)}`});t=i.$.env;let o=i.$.type,a=x(o)&&o.resolvedConcreteType?o.resolvedConcreteType:o;if(Le(a))if(we(a)){let s=Hg(i);if(s){let l=Jt(s),u=S({expr:l,env:t,context:{...n}});return F(u)?(dr(e,u),e):u}else return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}else if(ke(a)){let s=jg(i);if(s){let l=Jt(s),u=S({expr:l,env:t,context:{...n}});return F(u)?(dr(e,u),e):u}else return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}else{if(x(a)&&!Ce(a))return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e;{let s=Jt(`(${w(i)}).___dup()`),l=Rn({env:t,context:{...n},expr:s}),u=l.$?.variableName;if(!u||!l.$)throw y({token:e.token,errorMessage:`Failed to evaluate the "${k.___dup[0]}" method call:
10494
- ${w(s)}`});let c=X(l.$.env,u);if(c.length){let _=c[c.length-1];if(_.isOwningTheRcValue){let p=Be(l.$.env,_,{..._,isOwningTheRcValue:!1});l.$.env=p}}return l}}return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}function Sf({expr:e,env:t,context:n}){he(e,k.__yo_expr_is_atom,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10510
+ )`}else return""}function Sf({expr:e,env:t,context:n}){he(e,k.___dup,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${k.___dup[0]}":
10511
+ ${w(r)}`});t=i.$.env;let o=i.$.type,a=x(o)&&o.resolvedConcreteType?o.resolvedConcreteType:o;if(Le(a))if(we(a)){let s=jg(i);if(s){let l=Jt(s),u=S({expr:l,env:t,context:{...n}});return F(u)?(dr(e,u),e):u}else return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}else if(ke(a)){let s=Kg(i);if(s){let l=Jt(s),u=S({expr:l,env:t,context:{...n}});return F(u)?(dr(e,u),e):u}else return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}else{if(x(a)&&!Ce(a))return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e;{let s=Jt(`(${w(i)}).___dup()`),l=Rn({env:t,context:{...n},expr:s}),u=l.$?.variableName;if(!u||!l.$)throw y({token:e.token,errorMessage:`Failed to evaluate the "${k.___dup[0]}" method call:
10512
+ ${w(s)}`});let c=X(l.$.env,u);if(c.length){let _=c[c.length-1];if(_.isOwningTheRcValue){let p=Be(l.$.env,_,{..._,isOwningTheRcValue:!1});l.$.env=p}}return l}}return e.$={env:t,type:i.$.type,value:void 0,pathCollection:[]},e}function Nf({expr:e,env:t,context:n}){he(e,k.__yo_expr_is_atom,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10495
10513
  ${w(r)}`});if(!Lt(i.$.type))throw y({token:r.token,errorMessage:`Expected expression type for "${e.func.token.value}" argument, got:
10496
10514
  ${w(r)}`});let o=i.$.value;if(!o)throw y({token:r.token,errorMessage:`Expected expression value for "${e.func.token.value}" argument, got:
10497
- ${w(r)}`});let a=ln(o)?ft(z(o.value)):K(Je(),{env:i.$.env,context:n});return e.$={env:i.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function Nf({expr:e,env:t,context:n}){he(e,k.__yo_expr_is_fn_call,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10515
+ ${w(r)}`});let a=ln(o)?ft(z(o.value)):K(Je(),{env:i.$.env,context:n});return e.$={env:i.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function Vf({expr:e,env:t,context:n}){he(e,k.__yo_expr_is_fn_call,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10498
10516
  ${w(r)}`});if(!Lt(i.$.type))throw y({token:r.token,errorMessage:`Expected expression type for "${e.func.token.value}" argument, got:
10499
10517
  ${w(r)}`});let o=i.$.value;if(!o)throw y({token:r.token,errorMessage:`Expected expression value for "${e.func.token.value}" argument, got:
10500
- ${w(r)}`});let a=ln(o)?ft(F(o.value)):K(Je(),{env:i.$.env,context:n});return e.$={env:i.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function Vf({expr:e,env:t,context:n}){he(e,k.__yo_expr_get_callee,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10518
+ ${w(r)}`});let a=ln(o)?ft(F(o.value)):K(Je(),{env:i.$.env,context:n});return e.$={env:i.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function xf({expr:e,env:t,context:n}){he(e,k.__yo_expr_get_callee,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10501
10519
  ${w(r)}`});if(!Lt(i.$.type))throw y({token:r.token,errorMessage:`Expected expression type for "${e.func.token.value}" argument, got:
10502
10520
  ${w(r)}`});let o=i.$.value;if(!o)throw y({token:r.token,errorMessage:`Expected expression value for "${e.func.token.value}" argument, got:
10503
10521
  ${w(r)}`});if(e.$={env:i.$.env,type:_n(),value:K(_n(),{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},ln(o))if(F(o.value)){let a=o.value.func,s=Gn(a);e.$.value=s}else throw y({token:r.token,errorMessage:`Expected function call expression for argument, got:
10504
- ${w(e)}`});return e}function xf({expr:e,env:t,context:n}){he(e,k.__yo_expr_get_args,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10522
+ ${w(e)}`});return e}function Df({expr:e,env:t,context:n}){he(e,k.__yo_expr_get_args,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10505
10523
  ${w(r)}`});if(!Lt(i.$.type))throw y({token:r.token,errorMessage:`Expected expression type for "${e.func.token.value}" argument, got:
10506
10524
  ${w(r)}`});let o=i.$.value;if(!o)throw y({token:r.token,errorMessage:`Expected expression value for "${e.func.token.value}" argument, got:
10507
10525
  ${w(r)}`});if(e.$={env:i.$.env,type:xo(),value:K(xo(),{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},ln(o))if(F(o.value)){let a=o.value.args,s=zn(_n(),a.map(l=>Gn(l)));e.$.value=s}else throw y({token:r.token,errorMessage:`Expected function call expression for argument, got:
10508
- ${w(e)}`});return e}function Df({expr:e,env:t,context:n}){he(e,k.__yo_expr_to_string,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10526
+ ${w(e)}`});return e}function Mf({expr:e,env:t,context:n}){he(e,k.__yo_expr_to_string,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10509
10527
  ${w(r)}`});if(!Lt(i.$.type))throw y({token:r.token,errorMessage:`Expected expression type for "${e.func.token.value}" argument, got:
10510
10528
  ${w(r)}`});let o=i.$.value;if(!o)throw y({token:r.token,errorMessage:`Expected expression value for "${e.func.token.value}" argument, got:
10511
- ${w(r)}`});return e.$={env:i.$.env,type:xt(),value:K(xt(),{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},ln(o)&&(e.$.value=on(w(o.value))),e}function Mf({expr:e,env:t,context:n}){he(e,k.__yo_expr_eq,2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the first argument expression for "${e.func.token.value}":
10529
+ ${w(r)}`});return e.$={env:i.$.env,type:xt(),value:K(xt(),{env:i.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},ln(o)&&(e.$.value=on(w(o.value))),e}function Of({expr:e,env:t,context:n}){he(e,k.__yo_expr_eq,2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the first argument expression for "${e.func.token.value}":
10512
10530
  ${w(r)}`});if(!Lt(o.$.type))throw y({token:r.token,errorMessage:`Expected expression type for "${e.func.token.value}" first argument, got:
10513
10531
  ${w(r)}`});let a=o.$.value;if(!a)throw y({token:r.token,errorMessage:`Expected expression value for "${e.func.token.value}" first argument, got:
10514
10532
  ${w(r)}`});t=o.$.env;let s=S({expr:i,env:t,context:{...n}});if(!s.$)throw y({token:i.token,errorMessage:`Failed to evaluate the second argument expression for "${e.func.token.value}":
10515
10533
  ${w(i)}`});if(!Lt(s.$.type))throw y({token:i.token,errorMessage:`Expected expression type for "${e.func.token.value}" second argument, got:
10516
10534
  ${w(i)}`});let l=s.$.value;if(!l)throw y({token:i.token,errorMessage:`Expected expression value for "${e.func.token.value}" second argument, got:
10517
- ${w(i)}`});t=s.$.env;let u;return ln(a)&&ln(l)?u=ft(At({value:a,env:t},{value:l,env:t})):u=K(Je(),{env:t,context:n}),e.$={env:t,type:u.type,value:u,pathCollection:[],isAccessingProperty:!1},e}function Of({expr:e,env:t}){return he(e,k.__yo_gc_collect,0),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Rf({expr:e,env:t,context:n}){let r=e.args[0],i="";if(r){if(e.args.length>1)throw y({token:e.args[1].token,errorMessage:`Expected "gensym" with 0 or 1 argument, got: ${e.args.length}`});let l=S({expr:r,env:t,context:{...n}});if(!l.$)throw y({token:r.token,errorMessage:`Failed to evaluate the prefix argument for "gensym":
10535
+ ${w(i)}`});t=s.$.env;let u;return ln(a)&&ln(l)?u=ft(At({value:a,env:t},{value:l,env:t})):u=K(Je(),{env:t,context:n}),e.$={env:t,type:u.type,value:u,pathCollection:[],isAccessingProperty:!1},e}function Rf({expr:e,env:t}){return he(e,k.__yo_gc_collect,0),e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function Pf({expr:e,env:t,context:n}){let r=e.args[0],i="";if(r){if(e.args.length>1)throw y({token:e.args[1].token,errorMessage:`Expected "gensym" with 0 or 1 argument, got: ${e.args.length}`});let l=S({expr:r,env:t,context:{...n}});if(!l.$)throw y({token:r.token,errorMessage:`Failed to evaluate the prefix argument for "gensym":
10518
10536
  ${w(r)}`});if(!Ve(l.$.value))throw y({token:r.token,errorMessage:`Expected comptime_string for prefix argument, got:
10519
- ${w(r)}`});i=l.$.value.value}let o=i+qe(t.modulePath),a={tag:"Atom",token:{modulePath:t.modulePath,inputString:t.inputString,type:"identifier",position:e.func.token.position,value:o}},s=Gn(a);return e.$={env:t,pathCollection:[],type:s.type,value:s},e}function Pf({expr:e,env:t,context:n}){if(!E(e,I.Impl))throw y({token:e.token,errorMessage:`Expected "Impl", got:
10537
+ ${w(r)}`});i=l.$.value.value}let o=i+qe(t.modulePath),a={tag:"Atom",token:{modulePath:t.modulePath,inputString:t.inputString,type:"identifier",position:e.func.token.position,value:o}},s=Gn(a);return e.$={env:t,pathCollection:[],type:s.type,value:s},e}function Uf({expr:e,env:t,context:n}){if(!E(e,I.Impl))throw y({token:e.token,errorMessage:`Expected "Impl", got:
10520
10538
  ${w(e)}`});if(e.args.length===0)throw y({token:e.token,errorMessage:"Impl requires at least one trait argument."});let r=[],i=[],o;for(let l of e.args){let u=F(l)&&E(l,"!")&&l.args.length===1,c=u?l.args[0]:l,_=S({expr:c,env:t,context:{...n}});if(!_.$)throw y({token:c.token,errorMessage:"Failed to evaluate Impl argument."});if(t=_.$.env,!_.$.value||!O(_.$.value)||!De(_.$.value.value))throw y({token:c.token,errorMessage:`Impl argument must be a trait type, got: ${w(c)}`});let p=_.$.value.value;if(oa(p)){if(o!==void 0)throw y({token:c.token,errorMessage:"Impl can only have one Concrete(T) specifier"});o=p.isConcrete.concreteType;continue}u?i.push(p):r.push(p)}let a=bn(tt(),"Impl",{requiredTraits:r,negativeTraits:i,env:t,context:n});o!==void 0&&(a.resolvedConcreteType=o);let s=ee(a);return e.$={env:t,type:s.type,value:s,pathCollection:[]},e}function ta({expr:e,env:t,context:n}){if(z(e))return e;{let r=e.func,i=e.args;if(z(r)&&dt(r,I.unquote)&&i.length===1){let o=i[0],a=S({expr:o,env:t,context:{...n}});if(!a.$||!Lt(a.$.type)||!a.$.value)throw y({token:o.token,errorMessage:`Expected expression type for "unquote" argument, got:
10521
10539
  ${w(o)}`});let s=a.$.value;if(de(s))return e;if(ln(s))return s.value;throw y({token:o.token,errorMessage:`Expected expression value for "unquote" argument, got:
10522
10540
  ${Me(s)}`})}else{let o=ta({expr:r,env:t,context:{...n}}),a=[];for(let l=0;l<i.length;l++){let u=i[l];if(F(u)&&E(u,I.unquote_splicing)){let c;if(u.args.length!==1)throw y({token:u.token,errorMessage:`Expected exactly one argument for "unquote_splicing", got ${u.args.length}`});let _=u.args[0],p=S({expr:_,env:t,context:{...n}});if(!p.$||!Zr(p.$.type)||!p.$.value)throw y({token:_.token,errorMessage:`Expected ExprList for "unquote_splicing" argument, got:
10523
- ${w(_)}`});let f=p.$.value;Jl(f)&&f.elements.every(m=>ln(m))&&(c=f.elements.map(m=>m.value)),c?c.forEach(m=>{a.push(m)}):a.push(u)}else a.push(ta({expr:u,env:t,context:{...n}}))}return{...e,func:o,args:a}}}}function Uf({expr:e,env:t,context:n}){he(e,I.quote,1);let r=ta({expr:e.args[0],env:t,context:{...n}}),i=Gn(r);return e.$={env:t,type:i.type,value:i,pathCollection:[]},e}function zf({expr:e,env:t,context:n}){if(e.args.length!==1&&e.args.length!==2)throw y({token:e.token,errorMessage:`"macro_expand" expects 1 or 2 arguments, but got ${e.args.length}`});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "macro_expand":
10541
+ ${w(_)}`});let f=p.$.value;Jl(f)&&f.elements.every(m=>ln(m))&&(c=f.elements.map(m=>m.value)),c?c.forEach(m=>{a.push(m)}):a.push(u)}else a.push(ta({expr:u,env:t,context:{...n}}))}return{...e,func:o,args:a}}}}function zf({expr:e,env:t,context:n}){he(e,I.quote,1);let r=ta({expr:e.args[0],env:t,context:{...n}}),i=Gn(r);return e.$={env:t,type:i.type,value:i,pathCollection:[]},e}function Bf({expr:e,env:t,context:n}){if(e.args.length!==1&&e.args.length!==2)throw y({token:e.token,errorMessage:`"macro_expand" expects 1 or 2 arguments, but got ${e.args.length}`});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "macro_expand":
10524
10542
  ${r.toString()}`});if(t=i.$.env,!Lt(i.$.type))throw y({token:r.token,errorMessage:`The argument expression for "macro_expand" must be an Expr value, but got: ${A(i.$.type)}`});let o=null;if(e.args.length===2){let s=e.args[1],l=S({expr:s,env:t,context:{...n}});if(!l.$)throw y({token:s.token,errorMessage:`Failed to evaluate the level argument expression for "macro_expand":
10525
- ${s.toString()}`});if(!vt(l.$.type))throw y({token:s.token,errorMessage:`The level argument for "macro_expand" must be a comptime_int value, but got: ${A(l.$.type)}`});if(!An(l.$.value))throw y({token:s.token,errorMessage:'The level argument for "macro_expand" must be a comptime_int value'});let u=l.$.value.value;if(o=typeof u=="bigint"?Number(u):u,o<0)throw y({token:s.token,errorMessage:`The level argument for "macro_expand" must be non-negative, but got: ${o}`})}let a=i.$.value;if(ln(a)){let s=a.value,l=t,u=0;for(;F(s)&&(o===null||u<o);)try{let c=Rn({expr:s,env:l,context:{...n},forMacroExpansion:!0});if(!c.$)break;if(l=c.$.env,ln(c.$.value)){let _=c.$.value.value;if(w(_)===w(s))break;s=_,u++}else break}catch(c){if(c instanceof yn&&c.isAssertionError)throw c;break}s=ta({expr:s,env:l,context:{...n}}),e.$={env:l,type:_n(),value:Gn(s),pathCollection:i.$.pathCollection}}else e.$={env:t,type:i.$.type,value:i.$.value,pathCollection:i.$.pathCollection};return e}function Bf({expr:e,env:t,context:n}){if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="function-body"&&n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="test-block")throw y({token:e.token,errorMessage:"panic() can only be called inside a function body or test block"});if(n.isAnalyzingCtfeCapability)throw y({token:e.token,errorMessage:'Cannot use "panic" during compile-time function evaluation analysis. Functions containing "panic" cannot be evaluated at compile time.'});let r=n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:H.type;if(e.args.length>0){let i=e.args[0],o=S({expr:i,env:t,context:{...n}});if(!o.$)throw y({token:i.token,errorMessage:"Failed to evaluate panic message"});if(!o.$.value||!Ve(o.$.value)&&!(de(o.$.value)&&Et(o.$.value.type)))throw y({token:i.token,errorMessage:"panic message must be a comptime_string"})}return e.$={env:t,type:r,value:void 0,pathCollection:[]},e}var qf=new Set(["reg","reg_byte","reg_abcd","xmm_reg","ymm_reg","imm","mem"]),xl=new Set(["in"]),Dl=new Set(["out","lateout"]),Yf=new Set(["inout","inlateout"]),Hf=new Set(["const_val","sym"]),Kg=new Set([...xl,...Dl,...Yf,...Hf,"clobber","clobber_abi","asm_options"]),Gf=new Set(["pure","nomem","readonly","nostack","preserves_flags","att_syntax","intel_syntax","volatile","noreturn"]);function Vl(e){return or(e)||ar(e)||Ie(e)||cn(e)}function Xg(e){return e.tag==="Atom"&&qf.has(e.token.value)}function Qg(e){return!F(e)||e.func.tag!=="Atom"?!1:Kg.has(e.func.token.value)}function Wf(e){return e.tag==="Atom"&&e.token.value==="_"}function Zg(e,t,n){if(e.tag==="Atom"&&qf.has(e.token.value))return e.token.value;let r=S({expr:e,env:t,context:{...n}});if(r.$?.value&&Ve(r.$.value))return r.$.value.value;if(E(e,"raw",1)){let o=e.args[0],a=S({expr:o,env:t,context:{...n}});if(a.$?.value&&Ve(a.$.value))return`raw:${a.$.value.value}`}throw y({token:e.token,errorMessage:'Invalid asm constraint. Expected a register class (reg, imm, mem, ...), an explicit register name string, or raw("constraint").'})}function Jg(e,t,n,r){let i=e.args;if(r==="const_val"||r==="sym")return eh(e,t,n,r);if(i.length<1||i.length>3)throw y({token:e.token,errorMessage:`asm ${r}() expects 1 to 3 arguments, got ${i.length}.`});let o,a;if(i.length>=2){let g=i[0];if(Xg(g))a=0;else if(Wf(g))a=0;else{let h=S({expr:g,env:t,context:{...n}});h.$?.value&&Ve(h.$.value)?(o=h.$.value.value,a=1):a=0}}else a=0;let s=a<i.length-1,l,u;s?(l=Zg(i[a],t,n),u=a+1):(o!==void 0&&(l=o),u=a);let c=i[u];if(!c)throw y({token:e.token,errorMessage:`asm ${r}() is missing its value/type argument.`});let _=xl.has(r);if(Dl.has(r)){if(Wf(c))return{kind:r,name:o,constraint:l,valueExpr:void 0,outputType:void 0,targetVarName:void 0,discarded:!0};if(c.tag==="Atom"){let h=c.token.value,d=X(t,h);if(d.length>0){let v=d[d.length-1];if(!(v.value&&O(v.value[0]))){let T=v.type;if(!Vl(T))throw y({token:c.token,errorMessage:`asm ${r}() target variable '${h}' has type that is not valid for inline assembly. Must be a primitive numeric, pointer, or bool type.`});let $;return v.initializedAtToken?$=S({expr:c,env:t,context:{...n}}):($=c,$.$={env:t,type:T,value:void 0,pathCollection:[]}),{kind:r,name:o,constraint:l,valueExpr:$,outputType:T,targetVarName:h,discarded:!1}}}}let g=S({expr:c,env:t,context:{...n}});if(g.$?.value&&O(g.$.value)){let h=g.$.value.value;if(!Vl(h))throw y({token:c.token,errorMessage:`asm ${r}() output type must be a primitive numeric, pointer, or bool type.`});return{kind:r,name:o,constraint:l,valueExpr:void 0,outputType:h,targetVarName:void 0,discarded:!1}}throw y({token:c.token,errorMessage:`asm ${r}() last argument must be a type, variable, or _ (discard).`})}let f=S({expr:c,env:t,context:{...n}});if(!f.$)throw y({token:c.token,errorMessage:`Failed to evaluate asm ${r}() value expression.`});let m=f.$.type;if(!Vl(m))throw y({token:c.token,errorMessage:`asm ${r}() value type is not valid for inline assembly. Must be a primitive numeric, pointer, or bool type.`});return _?{kind:r,name:o,constraint:l,valueExpr:f,outputType:void 0,targetVarName:void 0,discarded:!1}:{kind:r,name:o,constraint:l,valueExpr:f,outputType:m,targetVarName:void 0,discarded:!1}}function eh(e,t,n,r){let i=e.args;if(i.length<1||i.length>2)throw y({token:e.token,errorMessage:`asm ${r}() expects 1 or 2 arguments, got ${i.length}.`});let o,a=0;if(i.length===2){let u=S({expr:i[0],env:t,context:{...n}});u.$?.value&&Ve(u.$.value)&&(o=u.$.value.value,a=1)}let s=i[a],l=S({expr:s,env:t,context:{...n}});return{kind:r,name:o,constraint:void 0,valueExpr:l,outputType:void 0,targetVarName:void 0,discarded:!1}}function th(e,t,n){let r={noreturn:!1};for(let i of e.args)if(i.tag==="Atom"){let o=i.token.value;if(!Gf.has(o))throw y({token:i.token,errorMessage:`Unknown asm_options flag: '${o}'. Valid flags: ${[...Gf].join(", ")}.`});o==="noreturn"&&(r.noreturn=!0)}else throw y({token:e.token,errorMessage:"asm_options() arguments must be flag identifiers (e.g., pure, nomem, noreturn)."});return r}function jf({expr:e,env:t,context:n}){if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="function-body"&&n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="test-block")throw y({token:e.token,errorMessage:"asm() can only be called inside a function body or test block."});if(n.isAnalyzingCtfeCapability)throw y({token:e.token,errorMessage:'Cannot use "asm" during compile-time function evaluation analysis.'});if(e.args.length===0)throw y({token:e.token,errorMessage:"asm() requires at least one argument (the assembly template string)."});let r=[],i=0;for(;i<e.args.length;){let m=e.args[i];if(Qg(m))break;let g=S({expr:m,env:t,context:{...n}});if(g.$?.value&&Ve(g.$.value))r.push(g.$.value.value),i++;else if(g.$?.value&&de(g.$.value)&&Et(g.$.value.type))r.push(""),i++;else break}if(r.length===0)throw y({token:e.args[0].token,errorMessage:"First argument to asm() must be a compile-time string (the assembly template)."});let o=[],a={noreturn:!1};for(;i<e.args.length;){let m=e.args[i];if(!F(m))throw y({token:m.token,errorMessage:"asm() arguments after the template must be operand or option calls (in, out, inout, clobber, asm_options, etc.)."});let g=m.func.tag==="Atom"?m.func.token.value:void 0;if(!g)throw y({token:m.token,errorMessage:"asm() operand must be a named call like in(...), out(...), etc."});if(xl.has(g)||Dl.has(g)||Yf.has(g)||Hf.has(g))o.push(Jg(m,t,n,g));else if(g==="clobber"||g==="clobber_abi")for(let h of m.args){if(h.tag==="Atom"&&(h.token.value==="memory"||h.token.value==="cc"))continue;let d=S({expr:h,env:t,context:{...n}});if((!d.$?.value||!Ve(d.$.value))&&!(h.tag==="Atom"&&h.token.value==="memory")&&!(h.tag==="Atom"&&h.token.value==="cc"))throw y({token:h.token,errorMessage:`${g}() arguments must be compile-time strings (e.g., "memory", "cc", "rax").`})}else if(g==="asm_options")a=th(m,t,n);else throw y({token:m.token,errorMessage:`Unknown asm() operand or option: '${g}'. Expected: in, out, inout, lateout, inlateout, const_val, sym, clobber, clobber_abi, asm_options.`});i++}let s=t;for(let m of o){if(m.targetVarName===void 0||m.kind!=="out"&&m.kind!=="lateout")continue;let g=X(s,m.targetVarName);if(g.length>0){let h=g[g.length-1];h.initializedAtToken||(s=Be(s,h,{...h,initializedAtToken:e.token}))}}t=s;let l=[];for(let m of o)m.discarded||m.targetVarName===void 0&&(m.kind==="const_val"||m.kind==="sym"||m.kind!=="in"&&m.outputType&&l.push(m.outputType));let u;if(a.noreturn)u=n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:H.type;else if(l.length===0)u=H.type;else if(l.length===1)u=l[0];else{let m=l.map((g,h)=>({label:h.toString(),type:g,exprs:{expr:e,labelExpr:void 0,typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:void 0}}));u=qi(m)}let c=r.join(`
10526
- `),_=/\{([^}:]+)(?::[^}]*)?\}/g,p,f=new Set;for(let m=0;m<o.length;m++)if(o[m].name){if(f.has(o[m].name))throw y({token:e.token,errorMessage:`Duplicate asm operand name: '${o[m].name}'.`});f.add(o[m].name)}for(;(p=_.exec(c))!==null;){let m=p[1];if(m==="{"||m==="}")continue;let g=parseInt(m,10);if(isNaN(g)){if(!f.has(m))throw y({token:e.token,errorMessage:`asm template references undefined operand '{${m}}'.`})}else if(g<0||g>=o.length)throw y({token:e.token,errorMessage:`asm template references positional operand {${g}} but only ${o.length} operands are defined.`})}return e.$={env:t,type:u,value:void 0,pathCollection:[]},e}function Kf({expr:e,env:t,context:n}){if(e.args.length===0)throw y({token:e.token,errorMessage:"global_asm() requires at least one argument (the assembly string)."});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$?.value||!Ve(i.$.value)&&!(de(i.$.value)&&Et(i.$.value.type)))throw y({token:r.token,errorMessage:"global_asm() argument must be a compile-time string."});return e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e}function Xf({expr:e,env:t}){if(E(e,k.__yo_process_platform)){if(e.args.length!==0)throw y({token:e.token,errorMessage:`__yo_process_platform expects 0 arguments, got ${e.args.length}`});let n=Wo(),r=n.os,i=on(r);return e.$={env:t,type:xt(),value:i,pathCollection:[]},e}if(E(e,k.__yo_process_arch)){if(e.args.length!==0)throw y({token:e.token,errorMessage:`__yo_process_arch expects 0 arguments, got ${e.args.length}`});let n=Wo(),r=n.arch,i=on(r);return e.$={env:t,type:xt(),value:i,pathCollection:[]},e}throw y({token:e.token,errorMessage:`Unknown process function: ${e.func.token.value}`})}var Ol=class{constructor(){this.artifacts=[];this.testSuites=[];this.runSteps=[];this.steps=[];this.dependencies=[];this.pathDependencies=[];this.systemLibraries=[];this.dependencyArtifacts=[];this.modules=[];this.cliOptions=new Map;this.declaredOptions=new Map}setCliOptions(t){this.cliOptions=t}registerExecutable(t){this.artifacts.push({kind:"executable",...t})}registerStaticLibrary(t){this.artifacts.push({kind:"static_library",...t})}registerSharedLibrary(t){this.artifacts.push({kind:"shared_library",...t})}registerTest(t){this.testSuites.push(t)}registerRun(t,n){let r=`run:${t}`;this.runSteps.push({name:r,artifactName:t,args:n})}registerStep(t,n,r=[]){this.steps.push({name:t,description:n,dependencyNames:r})}addStepDependency(t,n){let r=this.findStep(t);r&&(r.dependencyNames.includes(n)||r.dependencyNames.push(n))}registerDependency(t){this.dependencies.push(t)}registerPathDependency(t){this.pathDependencies.push(t)}registerSystemLibrary(t){this.systemLibraries.push(t)}registerDependencyArtifact(t){this.dependencyArtifacts.some(n=>n.dependencyName===t.dependencyName&&n.artifactName===t.artifactName)||this.dependencyArtifacts.push(t)}registerModule(t){this.modules.some(n=>n.name===t.name)||this.modules.push(t)}registerModuleLink(t,n){let r=this.modules.find(i=>i.name===t);r&&!r.linkedSystemLibraries.includes(n)&&r.linkedSystemLibraries.push(n)}registerImportedModule(t,n){let r=this.findArtifact(t);if(r){if(r.importedModules.some(i=>i.importName===n.importName))return;r.importedModules.push(n)}}findModule(t){return this.modules.find(n=>n.name===t)}registerLink(t,n){let r=this.findArtifact(t);r&&(r.linkedArtifacts.includes(n)||r.linkedArtifacts.push(n))}findArtifact(t){return this.artifacts.find(n=>n.name===t)}findTest(t){return this.testSuites.find(n=>n.name===t)}findRunStep(t){return this.runSteps.find(n=>n.name===t)}findStep(t){return this.steps.find(n=>n.name===t)}findDependency(t){return this.dependencies.find(n=>n.name===t)}findPathDependency(t){return this.pathDependencies.find(n=>n.name===t)}findSystemLibrary(t){return this.systemLibraries.find(n=>n.name===t)}getStepNames(){return this.steps.map(t=>t.name)}resolveDependency(t){let n=this.findArtifact(t);if(n)return{kind:"artifact",value:n};let r=this.findTest(t);if(r)return{kind:"test",value:r};let i=this.findRunStep(t);if(i)return{kind:"run",value:i};let o=this.findStep(t);if(o)return{kind:"step",value:o}}resolveDependencies(t){let n=[],r=[],i=[];for(let o of t.dependencyNames){let a=this.resolveDependency(o);if(a)switch(a.kind){case"artifact":n.some(s=>s.name===a.value.name)||n.push(a.value);break;case"test":r.some(s=>s.name===a.value.name)||r.push(a.value);break;case"run":i.some(s=>s.name===a.value.name)||i.push(a.value);{let s=this.findArtifact(a.value.artifactName);s&&!n.some(l=>l.name===s.name)&&n.push(s)}break;case"step":{let s=this.resolveDependencies(a.value);for(let l of s.artifacts)n.some(u=>u.name===l.name)||n.push(l);for(let l of s.tests)r.some(u=>u.name===l.name)||r.push(l);for(let l of s.runs)i.some(u=>u.name===l.name)||i.push(l);break}}}return{artifacts:n,tests:r,runs:i}}clear(){this.artifacts=[],this.testSuites=[],this.runSteps=[],this.steps=[],this.dependencies=[],this.pathDependencies=[],this.systemLibraries=[],this.dependencyArtifacts=[],this.modules=[]}},Ml,nh,rh=new Map;function Qf(){return nh}function Zf(e){return rh.get(e)}function Rl(){return Ml||(Ml=new Ol),Ml}function Ue(e,t,n){if(!Ve(e))throw y({token:n,errorMessage:`Build function: expected comptime_string for "${t}", got ${e?"non-string":"undefined"}`});return e.value}function En(e,t){return e.$={env:t,type:xn(),value:H,pathCollection:[]},e}function co(e,t,n){return e.$={env:t,type:xt(),value:on(n),pathCollection:[]},e}function ih(e){for(let t of e.args){if(t===void 0)continue;let n=t.$?.value;if(n===void 0||de(n))return!0}return!1}function Jf({expr:e,env:t}){if(ih(e)){if(E(e,k.__yo_build_target_host)){let r=Gr();return co(e,t,r.triple)}return E(e,k.__yo_build_option)?co(e,t,""):En(e,t)}let n=Rl();if(E(e,k.__yo_build_executable)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_executable expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple,a=e.args.length>3?Ue(e.args[3].$?.value,"optimize",e.token):"debug",s=e.args.length>4?Ue(e.args[4].$?.value,"allocator",e.token):"mimalloc",l=e.args.length>5?Ue(e.args[5].$?.value,"sanitize",e.token):"none";return n.registerExecutable({name:r,root:i,target:o,optimize:a,allocator:s,sanitize:l,linkLibraries:[],includePaths:[],libraryPaths:[],cSources:[],cFlags:[],defines:[],strip:!1,staticLink:!1,runtimeFiles:[],linkedArtifacts:[],linkedSystemLibraries:[],importedModules:[]}),En(e,t)}if(E(e,k.__yo_build_static_library)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_static_library expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple,a=e.args.length>3?Ue(e.args[3].$?.value,"optimize",e.token):"debug";return n.registerStaticLibrary({name:r,root:i,target:o,optimize:a,allocator:"mimalloc",sanitize:"none",linkLibraries:[],includePaths:[],libraryPaths:[],cSources:[],cFlags:[],defines:[],strip:!1,staticLink:!1,runtimeFiles:[],linkedArtifacts:[],linkedSystemLibraries:[],importedModules:[]}),En(e,t)}if(E(e,k.__yo_build_shared_library)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_shared_library expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple,a=e.args.length>3?Ue(e.args[3].$?.value,"optimize",e.token):"debug";return n.registerSharedLibrary({name:r,root:i,target:o,optimize:a,allocator:"mimalloc",sanitize:"none",linkLibraries:[],includePaths:[],libraryPaths:[],cSources:[],cFlags:[],defines:[],strip:!1,staticLink:!1,runtimeFiles:[],linkedArtifacts:[],linkedSystemLibraries:[],importedModules:[]}),En(e,t)}if(E(e,k.__yo_build_link)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_link expects 2 arguments (artifact_name, library_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token),i=Ue(e.args[1].$?.value,"library_name",e.token);if(n.findSystemLibrary(i)){let o=n.findArtifact(r);o&&(o.linkedSystemLibraries.includes(i)||o.linkedSystemLibraries.push(i))}else n.registerLink(r,i);return En(e,t)}if(E(e,k.__yo_build_link_system_library)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_link_system_library expects 2 arguments (artifact_name, system_lib_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token),i=Ue(e.args[1].$?.value,"system_lib_name",e.token),o=n.findArtifact(r);return o&&(o.linkedSystemLibraries.includes(i)||o.linkedSystemLibraries.push(i)),En(e,t)}if(E(e,k.__yo_build_test)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_test expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple;return n.registerTest({name:r,root:i,target:o,verbose:!1,bail:!1,parallel:1}),En(e,t)}if(E(e,k.__yo_build_run)){if(e.args.length<1)throw y({token:e.token,errorMessage:`__yo_build_run expects at least 1 argument (artifact_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token);return n.registerRun(r,[]),En(e,t)}if(E(e,k.__yo_build_step)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_step expects 2 arguments (name, description), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"description",e.token);return n.registerStep(r,i),En(e,t)}if(E(e,k.__yo_build_step_depend_on)){if(e.args.length<3)throw y({token:e.token,errorMessage:`__yo_build_step_depend_on expects 3 arguments (step_name, dep_name, dep_kind), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"step_name",e.token),i=Ue(e.args[1].$?.value,"dep_name",e.token),o=e.args[2].$?.value,a=i;return o&&It(o)&&o.variantName==="Run"&&(a=`run:${i}`),n.addStepDependency(r,a),En(e,t)}if(E(e,k.__yo_build_target_host)){let r=Gr();return co(e,t,r.triple)}if(E(e,k.__yo_build_target_parse)){if(e.args.length!==1)throw y({token:e.token,errorMessage:`__yo_build_target_parse expects 1 argument (triple), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"triple",e.token),i=dc(r);return co(e,t,i.triple)}if(E(e,k.__yo_build_dependency)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_dependency expects at least 2 arguments (name, url), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"url",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"ref",e.token):"HEAD",a=e.args.length>3?Ue(e.args[3].$?.value,"path",e.token):"";return n.registerDependency({name:r,url:i,ref:o,path:a}),En(e,t)}if(E(e,k.__yo_build_path_dependency)){if(e.args.length!==2)throw y({token:e.token,errorMessage:`__yo_build_path_dependency expects 2 arguments (name, path), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"path",e.token);return n.registerPathDependency({name:r,path:i}),En(e,t)}if(E(e,k.__yo_build_system_library)){if(e.args.length<1)throw y({token:e.token,errorMessage:`__yo_build_system_library expects at least 1 argument (name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=e.args.length>1?Ue(e.args[1].$?.value,"fallback_include",e.token):"",o=e.args.length>2?Ue(e.args[2].$?.value,"fallback_lib",e.token):"",a=e.args.length>3?Ue(e.args[3].$?.value,"fallback_link",e.token):"",s=e.args.length>4?Ue(e.args[4].$?.value,"defines",e.token).split(/\s+/).filter(Boolean):[];return n.registerSystemLibrary({name:r,fallbackInclude:i,fallbackLib:o,fallbackLink:a,defines:s}),En(e,t)}if(E(e,k.__yo_build_option)){if(e.args.length<3)throw y({token:e.token,errorMessage:`__yo_build_option expects 3 arguments (name, description, default), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"description",e.token),o=Ue(e.args[2].$?.value,"default",e.token);n.declaredOptions.set(r,{description:i,defaultValue:o});let a=n.cliOptions.get(r)??o;return co(e,t,a)}if(E(e,k.__yo_build_dep_artifact)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_dep_artifact expects 2 arguments (dependency_name, artifact_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"dependency_name",e.token),i=Ue(e.args[1].$?.value,"artifact_name",e.token);return n.registerDependencyArtifact({dependencyName:r,artifactName:i}),En(e,t)}if(E(e,k.__yo_build_module)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_module expects 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token);return n.registerModule({name:r,root:i,linkedSystemLibraries:[]}),En(e,t)}if(E(e,k.__yo_build_module_link)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_module_link expects 2 arguments (module_name, system_library_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"module_name",e.token),i=Ue(e.args[1].$?.value,"system_library_name",e.token);return n.registerModuleLink(r,i),En(e,t)}if(E(e,k.__yo_build_add_import)){if(e.args.length<4)throw y({token:e.token,errorMessage:`__yo_build_add_import expects 4 arguments (artifact_name, import_name, module_name, dependency_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token),i=Ue(e.args[1].$?.value,"import_name",e.token),o=Ue(e.args[2].$?.value,"module_name",e.token),a=Ue(e.args[3].$?.value,"dependency_name",e.token),s=n.findArtifact(r);if(s){let l=s.importedModules.find(u=>u.importName===i);if(l)throw y({token:e.token,errorMessage:`Duplicate import name "${i}" on artifact "${r}". Already imported from module "${l.moduleName}".`})}return n.registerImportedModule(r,{importName:i,moduleName:o,dependencyName:a}),En(e,t)}if(E(e,k.__yo_build_dep_module)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_dep_module expects 2 arguments (dependency_name, module_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"dependency_name",e.token),i=Ue(e.args[1].$?.value,"module_name",e.token);return co(e,t,`${r}\0${i}`)}throw y({token:e.token,errorMessage:`Unknown build function: ${e.func.token.value}`})}function ed({expr:e,env:t,context:n}){he(e,k.__yo_address_of,1);let r=e.args[0],i=n.expectedType;i&&Ie(i.type)&&(i={...i,type:i.type.childType});let o=S({expr:r,env:t,context:{...n,expectedType:i}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for reference:
10543
+ ${s.toString()}`});if(!vt(l.$.type))throw y({token:s.token,errorMessage:`The level argument for "macro_expand" must be a comptime_int value, but got: ${A(l.$.type)}`});if(!An(l.$.value))throw y({token:s.token,errorMessage:'The level argument for "macro_expand" must be a comptime_int value'});let u=l.$.value.value;if(o=typeof u=="bigint"?Number(u):u,o<0)throw y({token:s.token,errorMessage:`The level argument for "macro_expand" must be non-negative, but got: ${o}`})}let a=i.$.value;if(ln(a)){let s=a.value,l=t,u=0;for(;F(s)&&(o===null||u<o);)try{let c=Rn({expr:s,env:l,context:{...n},forMacroExpansion:!0});if(!c.$)break;if(l=c.$.env,ln(c.$.value)){let _=c.$.value.value;if(w(_)===w(s))break;s=_,u++}else break}catch(c){if(c instanceof yn&&c.isAssertionError)throw c;break}s=ta({expr:s,env:l,context:{...n}}),e.$={env:l,type:_n(),value:Gn(s),pathCollection:i.$.pathCollection}}else e.$={env:t,type:i.$.type,value:i.$.value,pathCollection:i.$.pathCollection};return e}function Gf({expr:e,env:t,context:n}){if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="function-body"&&n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="test-block")throw y({token:e.token,errorMessage:"panic() can only be called inside a function body or test block"});if(n.isAnalyzingCtfeCapability)throw y({token:e.token,errorMessage:'Cannot use "panic" during compile-time function evaluation analysis. Functions containing "panic" cannot be evaluated at compile time.'});let r=n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:H.type;if(e.args.length>0){let i=e.args[0],o=S({expr:i,env:t,context:{...n}});if(!o.$)throw y({token:i.token,errorMessage:"Failed to evaluate panic message"});if(!o.$.value||!Ve(o.$.value)&&!(de(o.$.value)&&Et(o.$.value.type)))throw y({token:i.token,errorMessage:"panic message must be a comptime_string"})}return e.$={env:t,type:r,value:void 0,pathCollection:[]},e}var Yf=new Set(["reg","reg_byte","reg_abcd","xmm_reg","ymm_reg","imm","mem"]),xl=new Set(["in"]),Dl=new Set(["out","lateout"]),Hf=new Set(["inout","inlateout"]),jf=new Set(["const_val","sym"]),Xg=new Set([...xl,...Dl,...Hf,...jf,"clobber","clobber_abi","asm_options"]),Wf=new Set(["pure","nomem","readonly","nostack","preserves_flags","att_syntax","intel_syntax","volatile","noreturn"]);function Vl(e){return or(e)||ar(e)||Ie(e)||cn(e)}function Qg(e){return e.tag==="Atom"&&Yf.has(e.token.value)}function Zg(e){return!F(e)||e.func.tag!=="Atom"?!1:Xg.has(e.func.token.value)}function qf(e){return e.tag==="Atom"&&e.token.value==="_"}function Jg(e,t,n){if(e.tag==="Atom"&&Yf.has(e.token.value))return e.token.value;let r=S({expr:e,env:t,context:{...n}});if(r.$?.value&&Ve(r.$.value))return r.$.value.value;if(E(e,"raw",1)){let o=e.args[0],a=S({expr:o,env:t,context:{...n}});if(a.$?.value&&Ve(a.$.value))return`raw:${a.$.value.value}`}throw y({token:e.token,errorMessage:'Invalid asm constraint. Expected a register class (reg, imm, mem, ...), an explicit register name string, or raw("constraint").'})}function eh(e,t,n,r){let i=e.args;if(r==="const_val"||r==="sym")return th(e,t,n,r);if(i.length<1||i.length>3)throw y({token:e.token,errorMessage:`asm ${r}() expects 1 to 3 arguments, got ${i.length}.`});let o,a;if(i.length>=2){let g=i[0];if(Qg(g))a=0;else if(qf(g))a=0;else{let h=S({expr:g,env:t,context:{...n}});h.$?.value&&Ve(h.$.value)?(o=h.$.value.value,a=1):a=0}}else a=0;let s=a<i.length-1,l,u;s?(l=Jg(i[a],t,n),u=a+1):(o!==void 0&&(l=o),u=a);let c=i[u];if(!c)throw y({token:e.token,errorMessage:`asm ${r}() is missing its value/type argument.`});let _=xl.has(r);if(Dl.has(r)){if(qf(c))return{kind:r,name:o,constraint:l,valueExpr:void 0,outputType:void 0,targetVarName:void 0,discarded:!0};if(c.tag==="Atom"){let h=c.token.value,d=X(t,h);if(d.length>0){let v=d[d.length-1];if(!(v.value&&O(v.value[0]))){let T=v.type;if(!Vl(T))throw y({token:c.token,errorMessage:`asm ${r}() target variable '${h}' has type that is not valid for inline assembly. Must be a primitive numeric, pointer, or bool type.`});let $;return v.initializedAtToken?$=S({expr:c,env:t,context:{...n}}):($=c,$.$={env:t,type:T,value:void 0,pathCollection:[]}),{kind:r,name:o,constraint:l,valueExpr:$,outputType:T,targetVarName:h,discarded:!1}}}}let g=S({expr:c,env:t,context:{...n}});if(g.$?.value&&O(g.$.value)){let h=g.$.value.value;if(!Vl(h))throw y({token:c.token,errorMessage:`asm ${r}() output type must be a primitive numeric, pointer, or bool type.`});return{kind:r,name:o,constraint:l,valueExpr:void 0,outputType:h,targetVarName:void 0,discarded:!1}}throw y({token:c.token,errorMessage:`asm ${r}() last argument must be a type, variable, or _ (discard).`})}let f=S({expr:c,env:t,context:{...n}});if(!f.$)throw y({token:c.token,errorMessage:`Failed to evaluate asm ${r}() value expression.`});let m=f.$.type;if(!Vl(m))throw y({token:c.token,errorMessage:`asm ${r}() value type is not valid for inline assembly. Must be a primitive numeric, pointer, or bool type.`});return _?{kind:r,name:o,constraint:l,valueExpr:f,outputType:void 0,targetVarName:void 0,discarded:!1}:{kind:r,name:o,constraint:l,valueExpr:f,outputType:m,targetVarName:void 0,discarded:!1}}function th(e,t,n,r){let i=e.args;if(i.length<1||i.length>2)throw y({token:e.token,errorMessage:`asm ${r}() expects 1 or 2 arguments, got ${i.length}.`});let o,a=0;if(i.length===2){let u=S({expr:i[0],env:t,context:{...n}});u.$?.value&&Ve(u.$.value)&&(o=u.$.value.value,a=1)}let s=i[a],l=S({expr:s,env:t,context:{...n}});return{kind:r,name:o,constraint:void 0,valueExpr:l,outputType:void 0,targetVarName:void 0,discarded:!1}}function nh(e,t,n){let r={noreturn:!1};for(let i of e.args)if(i.tag==="Atom"){let o=i.token.value;if(!Wf.has(o))throw y({token:i.token,errorMessage:`Unknown asm_options flag: '${o}'. Valid flags: ${[...Wf].join(", ")}.`});o==="noreturn"&&(r.noreturn=!0)}else throw y({token:e.token,errorMessage:"asm_options() arguments must be flag identifiers (e.g., pure, nomem, noreturn)."});return r}function Kf({expr:e,env:t,context:n}){if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="function-body"&&n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="test-block")throw y({token:e.token,errorMessage:"asm() can only be called inside a function body or test block."});if(n.isAnalyzingCtfeCapability)throw y({token:e.token,errorMessage:'Cannot use "asm" during compile-time function evaluation analysis.'});if(e.args.length===0)throw y({token:e.token,errorMessage:"asm() requires at least one argument (the assembly template string)."});let r=[],i=0;for(;i<e.args.length;){let m=e.args[i];if(Zg(m))break;let g=S({expr:m,env:t,context:{...n}});if(g.$?.value&&Ve(g.$.value))r.push(g.$.value.value),i++;else if(g.$?.value&&de(g.$.value)&&Et(g.$.value.type))r.push(""),i++;else break}if(r.length===0)throw y({token:e.args[0].token,errorMessage:"First argument to asm() must be a compile-time string (the assembly template)."});let o=[],a={noreturn:!1};for(;i<e.args.length;){let m=e.args[i];if(!F(m))throw y({token:m.token,errorMessage:"asm() arguments after the template must be operand or option calls (in, out, inout, clobber, asm_options, etc.)."});let g=m.func.tag==="Atom"?m.func.token.value:void 0;if(!g)throw y({token:m.token,errorMessage:"asm() operand must be a named call like in(...), out(...), etc."});if(xl.has(g)||Dl.has(g)||Hf.has(g)||jf.has(g))o.push(eh(m,t,n,g));else if(g==="clobber"||g==="clobber_abi")for(let h of m.args){if(h.tag==="Atom"&&(h.token.value==="memory"||h.token.value==="cc"))continue;let d=S({expr:h,env:t,context:{...n}});if((!d.$?.value||!Ve(d.$.value))&&!(h.tag==="Atom"&&h.token.value==="memory")&&!(h.tag==="Atom"&&h.token.value==="cc"))throw y({token:h.token,errorMessage:`${g}() arguments must be compile-time strings (e.g., "memory", "cc", "rax").`})}else if(g==="asm_options")a=nh(m,t,n);else throw y({token:m.token,errorMessage:`Unknown asm() operand or option: '${g}'. Expected: in, out, inout, lateout, inlateout, const_val, sym, clobber, clobber_abi, asm_options.`});i++}let s=t;for(let m of o){if(m.targetVarName===void 0||m.kind!=="out"&&m.kind!=="lateout")continue;let g=X(s,m.targetVarName);if(g.length>0){let h=g[g.length-1];h.initializedAtToken||(s=Be(s,h,{...h,initializedAtToken:e.token}))}}t=s;let l=[];for(let m of o)m.discarded||m.targetVarName===void 0&&(m.kind==="const_val"||m.kind==="sym"||m.kind!=="in"&&m.outputType&&l.push(m.outputType));let u;if(a.noreturn)u=n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:H.type;else if(l.length===0)u=H.type;else if(l.length===1)u=l[0];else{let m=l.map((g,h)=>({label:h.toString(),type:g,exprs:{expr:e,labelExpr:void 0,typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:void 0}}));u=qi(m)}let c=r.join(`
10544
+ `),_=/\{([^}:]+)(?::[^}]*)?\}/g,p,f=new Set;for(let m=0;m<o.length;m++)if(o[m].name){if(f.has(o[m].name))throw y({token:e.token,errorMessage:`Duplicate asm operand name: '${o[m].name}'.`});f.add(o[m].name)}for(;(p=_.exec(c))!==null;){let m=p[1];if(m==="{"||m==="}")continue;let g=parseInt(m,10);if(isNaN(g)){if(!f.has(m))throw y({token:e.token,errorMessage:`asm template references undefined operand '{${m}}'.`})}else if(g<0||g>=o.length)throw y({token:e.token,errorMessage:`asm template references positional operand {${g}} but only ${o.length} operands are defined.`})}return e.$={env:t,type:u,value:void 0,pathCollection:[]},e}function Xf({expr:e,env:t,context:n}){if(e.args.length===0)throw y({token:e.token,errorMessage:"global_asm() requires at least one argument (the assembly string)."});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$?.value||!Ve(i.$.value)&&!(de(i.$.value)&&Et(i.$.value.type)))throw y({token:r.token,errorMessage:"global_asm() argument must be a compile-time string."});return e.$={env:t,type:H.type,value:void 0,pathCollection:[]},e}function Qf({expr:e,env:t}){if(E(e,k.__yo_process_platform)){if(e.args.length!==0)throw y({token:e.token,errorMessage:`__yo_process_platform expects 0 arguments, got ${e.args.length}`});let n=Wo(),r=n.os,i=on(r);return e.$={env:t,type:xt(),value:i,pathCollection:[]},e}if(E(e,k.__yo_process_arch)){if(e.args.length!==0)throw y({token:e.token,errorMessage:`__yo_process_arch expects 0 arguments, got ${e.args.length}`});let n=Wo(),r=n.arch,i=on(r);return e.$={env:t,type:xt(),value:i,pathCollection:[]},e}throw y({token:e.token,errorMessage:`Unknown process function: ${e.func.token.value}`})}var Ol=class{constructor(){this.artifacts=[];this.testSuites=[];this.runSteps=[];this.steps=[];this.dependencies=[];this.pathDependencies=[];this.systemLibraries=[];this.dependencyArtifacts=[];this.modules=[];this.cliOptions=new Map;this.declaredOptions=new Map}setCliOptions(t){this.cliOptions=t}registerExecutable(t){this.artifacts.push({kind:"executable",...t})}registerStaticLibrary(t){this.artifacts.push({kind:"static_library",...t})}registerSharedLibrary(t){this.artifacts.push({kind:"shared_library",...t})}registerTest(t){this.testSuites.push(t)}registerRun(t,n){let r=`run:${t}`;this.runSteps.push({name:r,artifactName:t,args:n})}registerStep(t,n,r=[]){this.steps.push({name:t,description:n,dependencyNames:r})}addStepDependency(t,n){let r=this.findStep(t);r&&(r.dependencyNames.includes(n)||r.dependencyNames.push(n))}registerDependency(t){this.dependencies.push(t)}registerPathDependency(t){this.pathDependencies.push(t)}registerSystemLibrary(t){this.systemLibraries.push(t)}registerDependencyArtifact(t){this.dependencyArtifacts.some(n=>n.dependencyName===t.dependencyName&&n.artifactName===t.artifactName)||this.dependencyArtifacts.push(t)}registerModule(t){this.modules.some(n=>n.name===t.name)||this.modules.push(t)}registerModuleLink(t,n){let r=this.modules.find(i=>i.name===t);r&&!r.linkedSystemLibraries.includes(n)&&r.linkedSystemLibraries.push(n)}registerImportedModule(t,n){let r=this.findArtifact(t);if(r){if(r.importedModules.some(i=>i.importName===n.importName))return;r.importedModules.push(n)}}findModule(t){return this.modules.find(n=>n.name===t)}registerLink(t,n){let r=this.findArtifact(t);r&&(r.linkedArtifacts.includes(n)||r.linkedArtifacts.push(n))}findArtifact(t){return this.artifacts.find(n=>n.name===t)}findTest(t){return this.testSuites.find(n=>n.name===t)}findRunStep(t){return this.runSteps.find(n=>n.name===t)}findStep(t){return this.steps.find(n=>n.name===t)}findDependency(t){return this.dependencies.find(n=>n.name===t)}findPathDependency(t){return this.pathDependencies.find(n=>n.name===t)}findSystemLibrary(t){return this.systemLibraries.find(n=>n.name===t)}getStepNames(){return this.steps.map(t=>t.name)}resolveDependency(t){let n=this.findArtifact(t);if(n)return{kind:"artifact",value:n};let r=this.findTest(t);if(r)return{kind:"test",value:r};let i=this.findRunStep(t);if(i)return{kind:"run",value:i};let o=this.findStep(t);if(o)return{kind:"step",value:o}}resolveDependencies(t){let n=[],r=[],i=[];for(let o of t.dependencyNames){let a=this.resolveDependency(o);if(a)switch(a.kind){case"artifact":n.some(s=>s.name===a.value.name)||n.push(a.value);break;case"test":r.some(s=>s.name===a.value.name)||r.push(a.value);break;case"run":i.some(s=>s.name===a.value.name)||i.push(a.value);{let s=this.findArtifact(a.value.artifactName);s&&!n.some(l=>l.name===s.name)&&n.push(s)}break;case"step":{let s=this.resolveDependencies(a.value);for(let l of s.artifacts)n.some(u=>u.name===l.name)||n.push(l);for(let l of s.tests)r.some(u=>u.name===l.name)||r.push(l);for(let l of s.runs)i.some(u=>u.name===l.name)||i.push(l);break}}}return{artifacts:n,tests:r,runs:i}}clear(){this.artifacts=[],this.testSuites=[],this.runSteps=[],this.steps=[],this.dependencies=[],this.pathDependencies=[],this.systemLibraries=[],this.dependencyArtifacts=[],this.modules=[]}},Ml,rh,ih=new Map;function Zf(){return rh}function Jf(e){return ih.get(e)}function Rl(){return Ml||(Ml=new Ol),Ml}function Ue(e,t,n){if(!Ve(e))throw y({token:n,errorMessage:`Build function: expected comptime_string for "${t}", got ${e?"non-string":"undefined"}`});return e.value}function En(e,t){return e.$={env:t,type:xn(),value:H,pathCollection:[]},e}function co(e,t,n){return e.$={env:t,type:xt(),value:on(n),pathCollection:[]},e}function oh(e){for(let t of e.args){if(t===void 0)continue;let n=t.$?.value;if(n===void 0||de(n))return!0}return!1}function ed({expr:e,env:t}){if(oh(e)){if(E(e,k.__yo_build_target_host)){let r=Gr();return co(e,t,r.triple)}return E(e,k.__yo_build_option)?co(e,t,""):En(e,t)}let n=Rl();if(E(e,k.__yo_build_executable)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_executable expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple,a=e.args.length>3?Ue(e.args[3].$?.value,"optimize",e.token):"debug",s=e.args.length>4?Ue(e.args[4].$?.value,"allocator",e.token):"mimalloc",l=e.args.length>5?Ue(e.args[5].$?.value,"sanitize",e.token):"none";return n.registerExecutable({name:r,root:i,target:o,optimize:a,allocator:s,sanitize:l,linkLibraries:[],includePaths:[],libraryPaths:[],cSources:[],cFlags:[],defines:[],strip:!1,staticLink:!1,runtimeFiles:[],linkedArtifacts:[],linkedSystemLibraries:[],importedModules:[]}),En(e,t)}if(E(e,k.__yo_build_static_library)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_static_library expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple,a=e.args.length>3?Ue(e.args[3].$?.value,"optimize",e.token):"debug";return n.registerStaticLibrary({name:r,root:i,target:o,optimize:a,allocator:"mimalloc",sanitize:"none",linkLibraries:[],includePaths:[],libraryPaths:[],cSources:[],cFlags:[],defines:[],strip:!1,staticLink:!1,runtimeFiles:[],linkedArtifacts:[],linkedSystemLibraries:[],importedModules:[]}),En(e,t)}if(E(e,k.__yo_build_shared_library)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_shared_library expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple,a=e.args.length>3?Ue(e.args[3].$?.value,"optimize",e.token):"debug";return n.registerSharedLibrary({name:r,root:i,target:o,optimize:a,allocator:"mimalloc",sanitize:"none",linkLibraries:[],includePaths:[],libraryPaths:[],cSources:[],cFlags:[],defines:[],strip:!1,staticLink:!1,runtimeFiles:[],linkedArtifacts:[],linkedSystemLibraries:[],importedModules:[]}),En(e,t)}if(E(e,k.__yo_build_link)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_link expects 2 arguments (artifact_name, library_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token),i=Ue(e.args[1].$?.value,"library_name",e.token);if(n.findSystemLibrary(i)){let o=n.findArtifact(r);o&&(o.linkedSystemLibraries.includes(i)||o.linkedSystemLibraries.push(i))}else n.registerLink(r,i);return En(e,t)}if(E(e,k.__yo_build_link_system_library)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_link_system_library expects 2 arguments (artifact_name, system_lib_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token),i=Ue(e.args[1].$?.value,"system_lib_name",e.token),o=n.findArtifact(r);return o&&(o.linkedSystemLibraries.includes(i)||o.linkedSystemLibraries.push(i)),En(e,t)}if(E(e,k.__yo_build_test)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_test expects at least 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"target",e.token):Gr().triple;return n.registerTest({name:r,root:i,target:o,verbose:!1,bail:!1,parallel:1}),En(e,t)}if(E(e,k.__yo_build_run)){if(e.args.length<1)throw y({token:e.token,errorMessage:`__yo_build_run expects at least 1 argument (artifact_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token);return n.registerRun(r,[]),En(e,t)}if(E(e,k.__yo_build_step)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_step expects 2 arguments (name, description), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"description",e.token);return n.registerStep(r,i),En(e,t)}if(E(e,k.__yo_build_step_depend_on)){if(e.args.length<3)throw y({token:e.token,errorMessage:`__yo_build_step_depend_on expects 3 arguments (step_name, dep_name, dep_kind), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"step_name",e.token),i=Ue(e.args[1].$?.value,"dep_name",e.token),o=e.args[2].$?.value,a=i;return o&&It(o)&&o.variantName==="Run"&&(a=`run:${i}`),n.addStepDependency(r,a),En(e,t)}if(E(e,k.__yo_build_target_host)){let r=Gr();return co(e,t,r.triple)}if(E(e,k.__yo_build_target_parse)){if(e.args.length!==1)throw y({token:e.token,errorMessage:`__yo_build_target_parse expects 1 argument (triple), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"triple",e.token),i=dc(r);return co(e,t,i.triple)}if(E(e,k.__yo_build_dependency)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_dependency expects at least 2 arguments (name, url), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"url",e.token),o=e.args.length>2?Ue(e.args[2].$?.value,"ref",e.token):"HEAD",a=e.args.length>3?Ue(e.args[3].$?.value,"path",e.token):"";return n.registerDependency({name:r,url:i,ref:o,path:a}),En(e,t)}if(E(e,k.__yo_build_path_dependency)){if(e.args.length!==2)throw y({token:e.token,errorMessage:`__yo_build_path_dependency expects 2 arguments (name, path), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"path",e.token);return n.registerPathDependency({name:r,path:i}),En(e,t)}if(E(e,k.__yo_build_system_library)){if(e.args.length<1)throw y({token:e.token,errorMessage:`__yo_build_system_library expects at least 1 argument (name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=e.args.length>1?Ue(e.args[1].$?.value,"fallback_include",e.token):"",o=e.args.length>2?Ue(e.args[2].$?.value,"fallback_lib",e.token):"",a=e.args.length>3?Ue(e.args[3].$?.value,"fallback_link",e.token):"",s=e.args.length>4?Ue(e.args[4].$?.value,"defines",e.token).split(/\s+/).filter(Boolean):[];return n.registerSystemLibrary({name:r,fallbackInclude:i,fallbackLib:o,fallbackLink:a,defines:s}),En(e,t)}if(E(e,k.__yo_build_option)){if(e.args.length<3)throw y({token:e.token,errorMessage:`__yo_build_option expects 3 arguments (name, description, default), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"description",e.token),o=Ue(e.args[2].$?.value,"default",e.token);n.declaredOptions.set(r,{description:i,defaultValue:o});let a=n.cliOptions.get(r)??o;return co(e,t,a)}if(E(e,k.__yo_build_dep_artifact)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_dep_artifact expects 2 arguments (dependency_name, artifact_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"dependency_name",e.token),i=Ue(e.args[1].$?.value,"artifact_name",e.token);return n.registerDependencyArtifact({dependencyName:r,artifactName:i}),En(e,t)}if(E(e,k.__yo_build_module)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_module expects 2 arguments (name, root), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"name",e.token),i=Ue(e.args[1].$?.value,"root",e.token);return n.registerModule({name:r,root:i,linkedSystemLibraries:[]}),En(e,t)}if(E(e,k.__yo_build_module_link)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_module_link expects 2 arguments (module_name, system_library_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"module_name",e.token),i=Ue(e.args[1].$?.value,"system_library_name",e.token);return n.registerModuleLink(r,i),En(e,t)}if(E(e,k.__yo_build_add_import)){if(e.args.length<4)throw y({token:e.token,errorMessage:`__yo_build_add_import expects 4 arguments (artifact_name, import_name, module_name, dependency_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"artifact_name",e.token),i=Ue(e.args[1].$?.value,"import_name",e.token),o=Ue(e.args[2].$?.value,"module_name",e.token),a=Ue(e.args[3].$?.value,"dependency_name",e.token),s=n.findArtifact(r);if(s){let l=s.importedModules.find(u=>u.importName===i);if(l)throw y({token:e.token,errorMessage:`Duplicate import name "${i}" on artifact "${r}". Already imported from module "${l.moduleName}".`})}return n.registerImportedModule(r,{importName:i,moduleName:o,dependencyName:a}),En(e,t)}if(E(e,k.__yo_build_dep_module)){if(e.args.length<2)throw y({token:e.token,errorMessage:`__yo_build_dep_module expects 2 arguments (dependency_name, module_name), got ${e.args.length}`});let r=Ue(e.args[0].$?.value,"dependency_name",e.token),i=Ue(e.args[1].$?.value,"module_name",e.token);return co(e,t,`${r}\0${i}`)}throw y({token:e.token,errorMessage:`Unknown build function: ${e.func.token.value}`})}function td({expr:e,env:t,context:n}){he(e,k.__yo_address_of,1);let r=e.args[0],i=n.expectedType;i&&Ie(i.type)&&(i={...i,type:i.type.childType});let o=S({expr:r,env:t,context:{...n,expectedType:i}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for reference:
10527
10545
  ${w(r)}`});if(t=o.$.env,O(o.$.value))throw y({token:r.token,errorMessage:`Cannot create a pointer to a type. Did you mean to use "*"?
10528
- ${w(r)}`});{let a=o.$.type;if(vt(a)||Nt(a)||Et(a)){let c=yt({type:a,expectedType:i?.type,expr:o,env:t});o.$.type=c,o.$.convertedRuntimeType=c,a=c}let s=_i(a),l=o.$.sourceVariable,u=o.$.arrayElementRef;if(u){let c=ss(s,[u.arrayValue],u.index);e.$={env:t,type:s,value:c,pathCollection:o.$.pathCollection}}else if(l&&l.value){let c=ss(s,l.value);e.$={env:t,type:s,value:c,pathCollection:o.$.pathCollection}}else e.$={env:t,type:s,value:void 0,pathCollection:o.$.pathCollection};return Ge(e,!1),e}}function td({expr:e,env:t,context:n}){he(e,k.rc,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});return t=i.$.env,sn(i.$.type)?e.$={env:t,type:gt(),value:void 0,pathCollection:[]}:e.$={env:t,type:gt(),value:Xt("Usize",1),pathCollection:[]},e}function nd({expr:e,env:t,context:n}){he(e,k.sizeof,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});t=i.$.env;let o;i.$.value&&O(i.$.value)?o=i.$.value.value:o=i.$.type;let a=Ur(o),s;return a===null?s=K(gt(),{env:t,context:n}):s=Xt("Usize",Math.ceil(a/8)),e.$={env:t,type:gt(),value:s,pathCollection:[]},e}function xr({expr:e,type:t,env:n,context:r}){if(we(t)&&F(e)&&E(e,I.tuple)){if(t.fields.length!==e.args.length)throw y({token:e.token,errorMessage:`Tuple size mismatch: expected ${t.fields.length} fields, got ${e.args.length}`});for(let i=0;i<t.fields.length;i++){let o=t.fields[i].type,a=e.args[i],{env:s}=xr({expr:a,type:o,env:n,context:{...r}});n=s}return e.$={env:n,type:t,pathCollection:[]},{expr:e,type:t,env:n}}else if(F(e)&&E(e,"_"))if(ce(t)||it(t)||Te(t)||De(t)){let i=Rn({expr:e,env:n,givenFunc:{type:wt(t),value:ee(t)},context:{...r}});if(!i.$?.type||!i.$?.env)throw y({token:e.token,errorMessage:`Failed to evaluate expr and type for struct:
10529
- ${w(e)}`});return{expr:i,type:i.$?.type,env:i.$?.env}}else throw y({token:e.token,errorMessage:`Cannot use _ with type ${A(t)}. Only supported with struct types.`});else if(F(e)&&E(e,".",1))if(ge(t)){let i=e.args[0];if(!z(i))throw y({token:e.token,errorMessage:`Expected identifier for enum variant, got ${w(i)}`});let o=i.token.value;if(!t.variants.find(l=>l.name===o))throw y({token:e.token,errorMessage:`Enum variant "${o}" not found in ${A(t)}`});let s={...t,selectedVariantName:o};return e.$={type:s,env:n,pathCollection:[]},{expr:e,type:s,env:n}}else throw y({token:e.token,errorMessage:`Cannot use . with type ${A(t)}. Only supported with enum types.`});else if(F(e)&&F(e.func)&&E(e.func,".",1))if(ge(t)){let i=e.func,o=i.args[0];if(!z(o))throw y({token:i.token,errorMessage:`Expected identifier for enum variant, got ${w(o)}`});let a=o.token.value;if(!t.variants.find(c=>c.name===a))throw y({token:e.token,errorMessage:`Enum variant "${a}" not found in ${A(t)}`});let l={...t,selectedVariantName:a},u=Rn({expr:e,env:n,givenFunc:{type:wt(l),value:ee(l)},context:{...r}});if(!u.$?.type||!u.$?.env)throw y({token:e.token,errorMessage:`Failed to evaluate expr and type for enum variant:
10530
- ${w(e)}`});return{expr:u,type:u.$?.type,env:u.$?.env}}else throw y({token:e.token,errorMessage:`Cannot use . with type ${A(t)}. Only supported with enum types.`});else if(e.$?.type&&t)try{let{expectedEnv:i}=Ze({type:t,env:n},{type:e.$.type,env:n});return{expr:e,type:t,env:i}}catch{return{expr:e,type:e.$?.type,env:n}}else throw y({token:e.token,errorMessage:`Failed to synthesize the type and expr: ${w(e)}`})}function rd({expr:e,env:t,context:n}){he(e,k.the,2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:"Failed to evaluate type expression."});if(t=o.$.env,!o.$.value||!O(o.$.value))throw y({token:r.token,errorMessage:`First argument to 'the' must be a type, got ${o.$.type}`});let a=o.$.value.value,s=S({expr:i,env:t,context:{...n,expectedType:{type:a,env:t}}});if(!s.$)throw y({token:i.token,errorMessage:"Failed to evaluate value expression."});if(t=s.$.env,!Y({type:a,env:t},{type:s.$.type,env:t})){if(Pi(a))try{let{expr:l,type:u,env:c}=xr({expr:i,type:a,env:t,context:{...n}});if(Y({type:a,env:c},{type:u,env:c}))return e.$={env:c,type:a,value:l.$?.value,pathCollection:l.$?.pathCollection||[]},e}catch{}throw y({token:i.token,errorMessage:`Type mismatch: expected '${A(a)}', got '${A(s.$.type)}'`})}return e.$={env:t,type:a,value:s.$.value,pathCollection:s.$.pathCollection},e}function id({expr:e,env:t,context:n}){he(e,k.__yo_type_to_comptime_string,1);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10546
+ ${w(r)}`});{let a=o.$.type;if(vt(a)||Nt(a)||Et(a)){let c=yt({type:a,expectedType:i?.type,expr:o,env:t});o.$.type=c,o.$.convertedRuntimeType=c,a=c}let s=_i(a),l=o.$.sourceVariable,u=o.$.arrayElementRef;if(u){let c=ss(s,[u.arrayValue],u.index);e.$={env:t,type:s,value:c,pathCollection:o.$.pathCollection}}else if(l&&l.value){let c=ss(s,l.value);e.$={env:t,type:s,value:c,pathCollection:o.$.pathCollection}}else e.$={env:t,type:s,value:void 0,pathCollection:o.$.pathCollection};return Ge(e,!1),e}}function nd({expr:e,env:t,context:n}){he(e,k.rc,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});return t=i.$.env,sn(i.$.type)?e.$={env:t,type:gt(),value:void 0,pathCollection:[]}:e.$={env:t,type:gt(),value:Xt("Usize",1),pathCollection:[]},e}function rd({expr:e,env:t,context:n}){he(e,k.sizeof,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression."});t=i.$.env;let o;i.$.value&&O(i.$.value)?o=i.$.value.value:o=i.$.type;let a=Ur(o),s;return a===null?s=K(gt(),{env:t,context:n}):s=Xt("Usize",Math.ceil(a/8)),e.$={env:t,type:gt(),value:s,pathCollection:[]},e}function xr({expr:e,type:t,env:n,context:r}){if(we(t)&&F(e)&&E(e,I.tuple)){if(t.fields.length!==e.args.length)throw y({token:e.token,errorMessage:`Tuple size mismatch: expected ${t.fields.length} fields, got ${e.args.length}`});for(let i=0;i<t.fields.length;i++){let o=t.fields[i].type,a=e.args[i],{env:s}=xr({expr:a,type:o,env:n,context:{...r}});n=s}return e.$={env:n,type:t,pathCollection:[]},{expr:e,type:t,env:n}}else if(F(e)&&E(e,"_"))if(ce(t)||it(t)||Te(t)||De(t)){let i=Rn({expr:e,env:n,givenFunc:{type:Ft(t),value:ee(t)},context:{...r}});if(!i.$?.type||!i.$?.env)throw y({token:e.token,errorMessage:`Failed to evaluate expr and type for struct:
10547
+ ${w(e)}`});return{expr:i,type:i.$?.type,env:i.$?.env}}else throw y({token:e.token,errorMessage:`Cannot use _ with type ${A(t)}. Only supported with struct types.`});else if(F(e)&&E(e,".",1))if(ge(t)){let i=e.args[0];if(!z(i))throw y({token:e.token,errorMessage:`Expected identifier for enum variant, got ${w(i)}`});let o=i.token.value;if(!t.variants.find(l=>l.name===o))throw y({token:e.token,errorMessage:`Enum variant "${o}" not found in ${A(t)}`});let s={...t,selectedVariantName:o};return e.$={type:s,env:n,pathCollection:[]},{expr:e,type:s,env:n}}else throw y({token:e.token,errorMessage:`Cannot use . with type ${A(t)}. Only supported with enum types.`});else if(F(e)&&F(e.func)&&E(e.func,".",1))if(ge(t)){let i=e.func,o=i.args[0];if(!z(o))throw y({token:i.token,errorMessage:`Expected identifier for enum variant, got ${w(o)}`});let a=o.token.value;if(!t.variants.find(c=>c.name===a))throw y({token:e.token,errorMessage:`Enum variant "${a}" not found in ${A(t)}`});let l={...t,selectedVariantName:a},u=Rn({expr:e,env:n,givenFunc:{type:Ft(l),value:ee(l)},context:{...r}});if(!u.$?.type||!u.$?.env)throw y({token:e.token,errorMessage:`Failed to evaluate expr and type for enum variant:
10548
+ ${w(e)}`});return{expr:u,type:u.$?.type,env:u.$?.env}}else throw y({token:e.token,errorMessage:`Cannot use . with type ${A(t)}. Only supported with enum types.`});else if(e.$?.type&&t)try{let{expectedEnv:i}=Ze({type:t,env:n},{type:e.$.type,env:n});return{expr:e,type:t,env:i}}catch{return{expr:e,type:e.$?.type,env:n}}else throw y({token:e.token,errorMessage:`Failed to synthesize the type and expr: ${w(e)}`})}function id({expr:e,env:t,context:n}){he(e,k.the,2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$)throw y({token:r.token,errorMessage:"Failed to evaluate type expression."});if(t=o.$.env,!o.$.value||!O(o.$.value))throw y({token:r.token,errorMessage:`First argument to 'the' must be a type, got ${o.$.type}`});let a=o.$.value.value,s=S({expr:i,env:t,context:{...n,expectedType:{type:a,env:t}}});if(!s.$)throw y({token:i.token,errorMessage:"Failed to evaluate value expression."});if(t=s.$.env,!Y({type:a,env:t},{type:s.$.type,env:t})){if(Pi(a))try{let{expr:l,type:u,env:c}=xr({expr:i,type:a,env:t,context:{...n}});if(Y({type:a,env:c},{type:u,env:c}))return e.$={env:c,type:a,value:l.$?.value,pathCollection:l.$?.pathCollection||[]},e}catch{}throw y({token:i.token,errorMessage:`Type mismatch: expected '${A(a)}', got '${A(s.$.type)}'`})}return e.$={env:t,type:a,value:s.$.value,pathCollection:s.$.pathCollection},e}function od({expr:e,env:t,context:n}){he(e,k.__yo_type_to_comptime_string,1);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10531
10549
  ${w(r)}`});if(!He(r.$.type))throw y({token:r.token,errorMessage:`Expected TypeHierarchy type for "${e.func.token.value}" argument, got:
10532
10550
  ${w(r)}`});let i=r.$.value;if(!i)throw y({token:r.token,errorMessage:`Expected type value for "${e.func.token.value}" argument, got:
10533
- ${w(r)}`});return e.$={env:r.$.env,type:xt(),value:K(xt(),{env:r.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},O(i)&&(e.$.value=on(A(i.value))),e}function od({expr:e,env:t,context:n}){let r=e.args,i=r[0],o=r[1],a=S({expr:i,env:t,context:{...n,expectedType:void 0,SelfType:void 0}});if(!O(a.$?.value))throw y({token:i.token,errorMessage:`Expected type, got:
10551
+ ${w(r)}`});return e.$={env:r.$.env,type:xt(),value:K(xt(),{env:r.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},O(i)&&(e.$.value=on(A(i.value))),e}function ad({expr:e,env:t,context:n}){let r=e.args,i=r[0],o=r[1],a=S({expr:i,env:t,context:{...n,expectedType:void 0,SelfType:void 0}});if(!O(a.$?.value))throw y({token:i.token,errorMessage:`Expected type, got:
10534
10552
  ${w(i)}`});let s=a.$.value.value;t=a.$.env;let l=S({expr:o,env:t,context:{...n,expectedType:void 0,SelfType:void 0}});if(!O(l.$?.value))throw y({token:o.token,errorMessage:`Expected type, got:
10535
- ${w(o)}`});let u=l.$.value.value;t=l.$.env;let c=Y({type:s,env:t},{type:u,env:t}),_=ft(c);return e.$={env:t,type:_.type,value:_,pathCollection:[]},e}function ad({expr:e,env:t,context:n}){he(e,k.__yo_type_contains_rc_type,1);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10553
+ ${w(o)}`});let u=l.$.value.value;t=l.$.env;let c=Y({type:s,env:t},{type:u,env:t}),_=ft(c);return e.$={env:t,type:_.type,value:_,pathCollection:[]},e}function sd({expr:e,env:t,context:n}){he(e,k.__yo_type_contains_rc_type,1);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10536
10554
  ${w(r)}`});if(!He(r.$.type))throw y({token:r.token,errorMessage:`Expected TypeHierarchy type for "${e.func.token.value}" argument, got:
10537
10555
  ${w(r)}`});let i=r.$.value;if(!i||!O(i))throw y({token:r.token,errorMessage:`Expected type value for "${e.func.token.value}" argument, got:
10538
- ${w(r)}`});let o=Le(i.value),a=ft(o);return e.$={env:r.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function sd({expr:e,env:t,context:n}){he(e,k.__yo_type_can_form_rc_cycle,1);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10556
+ ${w(r)}`});let o=Le(i.value),a=ft(o);return e.$={env:r.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function ld({expr:e,env:t,context:n}){he(e,k.__yo_type_can_form_rc_cycle,1);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for "${e.func.token.value}":
10539
10557
  ${w(r)}`});if(!He(r.$.type))throw y({token:r.token,errorMessage:`Expected TypeHierarchy type for "${e.func.token.value}" argument, got:
10540
10558
  ${w(r)}`});let i=r.$.value;if(!i||!O(i))throw y({token:r.token,errorMessage:`Expected type value for "${e.func.token.value}" argument, got:
10541
- ${w(r)}`});let o=wr(i.value,new Set,r.$.env),a=ft(o);return e.$={env:r.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function ld({expr:e,env:t,context:n}){he(e,k.__yo_type_impls,2);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the type argument for "${e.func.token.value}":
10559
+ ${w(r)}`});let o=wr(i.value,new Set,r.$.env),a=ft(o);return e.$={env:r.$.env,type:a.type,value:a,pathCollection:[],isAccessingProperty:!1},e}function ud({expr:e,env:t,context:n}){he(e,k.__yo_type_impls,2);let r=S({expr:e.args[0],env:t,context:{...n}});if(!r.$)throw y({token:r.token,errorMessage:`Failed to evaluate the type argument for "${e.func.token.value}":
10542
10560
  ${w(r)}`});if(!He(r.$.type))throw y({token:r.token,errorMessage:`Expected Type for first argument of "${e.func.token.value}", got:
10543
10561
  ${w(r)}`});let i=r.$.value;if(!i||!O(i))throw y({token:r.token,errorMessage:`Expected type value for first argument of "${e.func.token.value}", got:
10544
10562
  ${w(r)}`});t=r.$.env;let o=i.value,a=S({expr:e.args[1],env:t,context:{...n}});if(!a.$)throw y({token:a.token,errorMessage:`Failed to evaluate the trait argument for "${e.func.token.value}":
10545
10563
  ${w(a)}`});let s;if(O(a.$.value)){let u=a.$.value;if(!De(u.value))throw y({token:a.token,errorMessage:`Expected trait type for second argument of "${e.func.token.value}", got a non-trait type`});s=u.value}else if(De(a.$.type))s=a.$.type;else{if(He(a.$.type))return e.$={env:a.$.env,type:Je(),value:K(Je(),{env:a.$.env,context:n}),pathCollection:[],isAccessingProperty:!1},e;throw y({token:a.token,errorMessage:`Expected trait type for second argument of "${e.func.token.value}", got:
10546
- ${w(a)}`})}t=a.$.env;let l=ft(St({targetType:o,traitType:s,env:t}));return e.$={env:t,type:l.type,value:l,pathCollection:[],isAccessingProperty:!1},e}function ud({expr:e,env:t,context:n}){he(e,k.typeid,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression for typeid."});if(t=i.$.env,!i.$.value||!O(i.$.value))throw y({token:r.token,errorMessage:`typeid expects a type argument, got ${i.$.type?A(i.$.type):"unknown"}. Use is() or downcast() for runtime type checks on Dyn values.`});let o=K(gt(),{env:t,context:n});return e.$={env:t,type:gt(),value:o,pathCollection:[]},e}function cd({expr:e,env:t}){he(e,k.va_start);for(let n=0;n<e.args.length;n++){let r=e.args[n];if(!z(r)||!je(r))throw y({token:r.token,errorMessage:`Invalid argument for va_start. Expected identifier, got:
10547
- ${w(r)}`});if(n===0){let i=r.token.value,o=X(t,i);if(o.length===0)throw y({token:r.token,errorMessage:`Variable '${i}' not found in the environment.`});let a=o[o.length-1];t=Be(t,a,{...a,initializedAtToken:r.token})}if(n===1){let i=r.token.value;if(X(t,i).length===0)throw y({token:r.token,errorMessage:`Variable '${i}' not found in the environment.`})}}return e.$={type:H.type,value:H,env:t,pathCollection:[]},e}function _d({expr:e,env:t,context:n}){he(e,k.__yo_var_print_info,1);let r=e.args[0],i=S({expr:r,env:t,context:n});i.$&&(t=i.$.env);let o=i.$?.variableName;if(o){let a=X(t,o);if(a.length>0){let s=a.at(-1);console.log(ic(s))}}return e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function pd({expr:e,env:t,context:n}){he(e,k.__yo_var_is_owning_the_rc_value,1);let r=e.args[0],i=S({expr:r,env:t,context:n});i.$&&(t=i.$.env);let o=i.$?.variableName,a=!1;if(o){let s=X(t,o);s.length>0&&(a=s.at(-1).isOwningTheRcValue)}return e.$={env:t,type:Je(),value:ft(a),pathCollection:[]},e}function fd({expr:e,env:t,context:n}){he(e,k.__yo_var_has_other_aliases,1);let r=e.args[0],i=S({expr:r,env:t,context:n});i.$&&(t=i.$.env);let o=i.$?.variableName,a=!1;if(o){let s=X(t,o);if(s.length>0){let l=s.at(-1);if(l.isOwningTheSameRcValueAs)a=!0;else{let c=l.id;for(let _=t.frames.length-1;_>=0;_--){let p=t.frames[_];for(let f=0;f<p.variables.length;f++){let m=p.variables[f];if(m.isOwningTheSameRcValueAs&&m.isOwningTheSameRcValueAs.id===c){a=!0;break}}}}}}return e.$={env:t,type:Je(),value:ft(a),pathCollection:[]},e}function dd({expr:e,env:t,context:n}){let r=e.args[0],i=n.expectedType;i&&Ie(i.type)&&(i={...i,type:i.type.childType});let o=S({expr:r,env:t,context:{...n,expectedType:i}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for pointer:
10564
+ ${w(a)}`})}t=a.$.env;let l=ft(St({targetType:o,traitType:s,env:t}));return e.$={env:t,type:l.type,value:l,pathCollection:[],isAccessingProperty:!1},e}function cd({expr:e,env:t,context:n}){he(e,k.typeid,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:"Failed to evaluate expression for typeid."});if(t=i.$.env,!i.$.value||!O(i.$.value))throw y({token:r.token,errorMessage:`typeid expects a type argument, got ${i.$.type?A(i.$.type):"unknown"}. Use is() or downcast() for runtime type checks on Dyn values.`});let o=K(gt(),{env:t,context:n});return e.$={env:t,type:gt(),value:o,pathCollection:[]},e}function _d({expr:e,env:t}){he(e,k.va_start);for(let n=0;n<e.args.length;n++){let r=e.args[n];if(!z(r)||!je(r))throw y({token:r.token,errorMessage:`Invalid argument for va_start. Expected identifier, got:
10565
+ ${w(r)}`});if(n===0){let i=r.token.value,o=X(t,i);if(o.length===0)throw y({token:r.token,errorMessage:`Variable '${i}' not found in the environment.`});let a=o[o.length-1];t=Be(t,a,{...a,initializedAtToken:r.token})}if(n===1){let i=r.token.value;if(X(t,i).length===0)throw y({token:r.token,errorMessage:`Variable '${i}' not found in the environment.`})}}return e.$={type:H.type,value:H,env:t,pathCollection:[]},e}function pd({expr:e,env:t,context:n}){he(e,k.__yo_var_print_info,1);let r=e.args[0],i=S({expr:r,env:t,context:n});i.$&&(t=i.$.env);let o=i.$?.variableName;if(o){let a=X(t,o);if(a.length>0){let s=a.at(-1);console.log(ic(s))}}return e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function fd({expr:e,env:t,context:n}){he(e,k.__yo_var_is_owning_the_rc_value,1);let r=e.args[0],i=S({expr:r,env:t,context:n});i.$&&(t=i.$.env);let o=i.$?.variableName,a=!1;if(o){let s=X(t,o);s.length>0&&(a=s.at(-1).isOwningTheRcValue)}return e.$={env:t,type:Je(),value:ft(a),pathCollection:[]},e}function dd({expr:e,env:t,context:n}){he(e,k.__yo_var_has_other_aliases,1);let r=e.args[0],i=S({expr:r,env:t,context:n});i.$&&(t=i.$.env);let o=i.$?.variableName,a=!1;if(o){let s=X(t,o);if(s.length>0){let l=s.at(-1);if(l.isOwningTheSameRcValueAs)a=!0;else{let c=l.id;for(let _=t.frames.length-1;_>=0;_--){let p=t.frames[_];for(let f=0;f<p.variables.length;f++){let m=p.variables[f];if(m.isOwningTheSameRcValueAs&&m.isOwningTheSameRcValueAs.id===c){a=!0;break}}}}}}return e.$={env:t,type:Je(),value:ft(a),pathCollection:[]},e}function md({expr:e,env:t,context:n}){let r=e.args[0],i=n.expectedType;i&&Ie(i.type)&&(i={...i,type:i.type.childType});let o=S({expr:r,env:t,context:{...n,expectedType:i}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate the argument expression for pointer:
10548
10566
  ${w(r)}`});if(t=o.$.env,O(o.$.value)){let s=o.$.value.value,l=_i(s),u=ee(l);return e.$={env:t,type:u.type,value:u,pathCollection:[]},e}else throw y({token:r.token,errorMessage:`Cannot create a pointer to a value. Use "&" to create a pointer to a value:
10549
- ${w(r)}`})}function md({expr:e,env:t,context:n}){if(!E(e,I.Array,2))throw y({token:e.token,errorMessage:`Expected "Array(comptime(Type), comptime(usize))" with 2 arguments, like "Array(i32, 10)"
10567
+ ${w(r)}`})}function yd({expr:e,env:t,context:n}){if(!E(e,I.Array,2))throw y({token:e.token,errorMessage:`Expected "Array(comptime(Type), comptime(usize))" with 2 arguments, like "Array(i32, 10)"
10550
10568
  Got:
10551
10569
  ${w(e)}`});let r=e.args[0],i=e.args[1],o=z(i)&&i.token.value==="_",a=S({expr:r,env:t,context:{...n}});if(!a.$)throw y({token:r.token,errorMessage:`Failed to evaluate the element type expression:
10552
10570
  ${w(r)}`});if(!O(a.$.value))throw y({token:r.token,errorMessage:`Expected type for element type, got:
@@ -10555,26 +10573,26 @@ ${w(r)}
10555
10573
  If you are creating an array value with 1 element, please consider adding a "," in the end, like [1,]`});let s=a.$.value.value;if(o){let p=`_array_length_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,f=K(gt(),{variableName:p,env:a.$.env,context:n}),{env:m}=me({env:a.$.env,variable:{name:p,value:[f],type:gt(),isCompileTimeOnly:!0,token:i.token,initializedAtToken:i.token,consumedAtToken:void 0,isOwningTheRcValue:!1}}),g=mr(s,f),h=ee(g);return e.$={env:m,type:h.type,value:h,pathCollection:[]},e}let l=S({expr:i,env:t,context:{...n,expectedType:{type:gt(),env:t}}});if(!l.$)throw y({token:i.token,errorMessage:`Failed to evaluate the length expression:
10556
10574
  ${w(i)}`});if(!Y({type:gt(),env:t},{type:l.$.type,env:t}))throw y({token:i.token,errorMessage:`Expected usize for length, got:
10557
10575
  ${w(i)}`});let u=l.$.value;if(!u)throw y({token:i.token,errorMessage:`Expected compile-time known value for length, got:
10558
- ${w(i)}`});de(u)&&(u.type=gt());let c=mr(s,u),_=ee(c);return e.$={env:l.$.env,type:_.type,value:_,pathCollection:[]},e}function yd({expr:e,env:t,context:n}){return qa({expr:e,env:t,context:n})}function gd({expr:e,env:t,context:n}){he(e,I.ComptimeList,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the element type expression:
10576
+ ${w(i)}`});de(u)&&(u.type=gt());let c=mr(s,u),_=ee(c);return e.$={env:l.$.env,type:_.type,value:_,pathCollection:[]},e}function gd({expr:e,env:t,context:n}){return qa({expr:e,env:t,context:n})}function hd({expr:e,env:t,context:n}){he(e,I.ComptimeList,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the element type expression:
10559
10577
  ${w(r)}`});if(!O(i.$.value))throw y({token:r.token,errorMessage:`Expected type for element type, got:
10560
- ${w(r)}`});let o=i.$.value.value,a=Io(o),s=ee(a);return e.$={env:i.$.env,type:s.type,value:s,pathCollection:[]},e}function hd({expr:e,env:t,context:n}){if(e.args.length!==1)throw y({token:e.token,errorMessage:`Concrete type constructor expects exactly 1 argument, got ${e.args.length}. Usage: Concrete(T)`});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the concrete type expression for Concrete:
10578
+ ${w(r)}`});let o=i.$.value.value,a=Io(o),s=ee(a);return e.$={env:i.$.env,type:s.type,value:s,pathCollection:[]},e}function vd({expr:e,env:t,context:n}){if(e.args.length!==1)throw y({token:e.token,errorMessage:`Concrete type constructor expects exactly 1 argument, got ${e.args.length}. Usage: Concrete(T)`});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the concrete type expression for Concrete:
10561
10579
  ${w(r)}`});if(t=i.$.env,!O(i.$.value))throw y({token:r.token,errorMessage:`Concrete type constructor expects a type as its argument, but got:
10562
- ${w(r)}`});let o=i.$.value.value,a=Oe(t);return a.isConcrete={concreteType:o},a.id=`concrete_module_${o.id}`,e.$={env:t,type:wt(a),value:ee(a),pathCollection:[]},e}function vd({expr:e,env:t,context:n}){he(e,I.Dyn);let r=e.args,i=[],o=[];for(let u=0;u<r.length;u++){let c=r[u],_=F(c)&&E(c,"!")&&c.args.length===1,p=_?c.args[0]:c,f=S({expr:p,env:t,context:{...n}});if(!f.$||!f.$.value||!O(f.$.value)||!De(f.$.value.value))throw new Error(`Expected a trait type for argument ${u+1} of 'dyn' expression.`);t=f.$.env;let m=f.$.value.value;if(_){if(o.some(g=>g.id===m.id))throw y({token:p.token,errorMessage:`Trait type ${A(m)} is already included in negative constraints of '${I.Dyn}' expression.`});o.push(m)}else{if(i.some(g=>g.id===m.id))throw y({token:p.token,errorMessage:`Trait type ${A(m)} is already included in '${I.Dyn}' expression.`});i.push(m)}}{let u=new Set(i.map(_=>_.id)),c=[...i];for(;c.length>0;){let _=c.pop();if(_.selfConstraints)for(let p of _.selfConstraints)u.has(p.id)||(u.add(p.id),i.push(p),c.push(p))}}for(let u=0;u<i.length;u++){let c=i[u];for(let _=u+1;_<i.length;_++){let p=i[_];for(let f of c.fields)for(let m of p.fields)if(f.label===m.label&&f.label!=="")throw y({token:e.token,errorMessage:`Trait types ${A(c)} and ${A(p)} have conflicting function name '${f.label}' in '${I.Dyn[0]}' expression.`})}}let a=[k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]];for(let u of i)for(let c of u.fields)if(a.includes(c.label)&&G(c.type))throw y({token:e.token,errorMessage:`Trait type ${A(u)} cannot have function '${c.label}' as it is reserved in 'dyn' expression.`});let s=Do({requiredTraits:i,env:t,negativeTraits:o});t=No({dynType:s,env:t,context:n});let l=ee(s);return e.$={env:t,value:l,type:l.type,pathCollection:[]},e}function Xr({expr:e,tupleFieldIndex:t,env:n,context:r,forType:i}){let o,a=e,s,l,u,c,_,p,f=!1,m;if(F(e)&&E(e,"?=",2)&&(u=e.args[1],a=e.args[0]),F(a)&&(E(a,"=",2)||E(a,"::",2))){if(E(a,"::",2)){if(f=!0,s=a.args[0],!je(s))throw y({token:s.token,errorMessage:`Expected identifier for element label, got ${w(s)}`});o=s.token.value}_=a.args[1],a=a.args[0]}if(u&&_)throw y({token:e.token,errorMessage:"Cannot have both default value and required value for element."});if(F(a)&&E(a,":",2)){if(s=a.args[0],l=a.args[1],F(s)&&E(s,I.comptime,1)){if(f)throw y({token:s.token,errorMessage:'Cannot combine the use of "comptime" with ::'});f=!0,s=s.args[0]}if(!z(s)||!je(s))throw y({token:s.token,errorMessage:`Expected identifier for element label, got ${w(s)}`});o=s.token.value}else if(F(a)&&E(a,I.comptime,1)){if(f)throw y({token:a.token,errorMessage:'Cannot combine the use of "comptime" with "::"'});if(f=!0,s=a.args[0],!z(s)||!je(s))throw y({token:s.token,errorMessage:`Expected identifier for element label, got ${w(s)}`});o=s.token.value}else!u&&!_&&(l=a);let g=r.expectedType?.type,h;if(g&&(we(g)||ce(g)||Te(g)||De(g))){let v=g.fields[t];if(!v)throw y({token:e.token,errorMessage:`Failed to get the field at index ${t}`});h=v.type}if(l){let v=S({expr:l,env:n,context:{...r,expectedType:h?{type:h,env:n}:void 0}});v.$?.env&&(n=v.$?.env);let T=v.$?.value;if(!O(T))throw y({token:l.token,errorMessage:`(1) Expected type for element, got ${w(l)}`});m=T.value}if(_){if(!f)throw y({token:_.token,errorMessage:`Assigned value expression is only allowed for compile-time only.
10580
+ ${w(r)}`});let o=i.$.value.value,a=Oe(t);return a.isConcrete={concreteType:o},a.id=`concrete_module_${o.id}`,e.$={env:t,type:Ft(a),value:ee(a),pathCollection:[]},e}function Td({expr:e,env:t,context:n}){he(e,I.Dyn);let r=e.args,i=[],o=[];for(let u=0;u<r.length;u++){let c=r[u],_=F(c)&&E(c,"!")&&c.args.length===1,p=_?c.args[0]:c,f=S({expr:p,env:t,context:{...n}});if(!f.$||!f.$.value||!O(f.$.value)||!De(f.$.value.value))throw new Error(`Expected a trait type for argument ${u+1} of 'dyn' expression.`);t=f.$.env;let m=f.$.value.value;if(_){if(o.some(g=>g.id===m.id))throw y({token:p.token,errorMessage:`Trait type ${A(m)} is already included in negative constraints of '${I.Dyn}' expression.`});o.push(m)}else{if(i.some(g=>g.id===m.id))throw y({token:p.token,errorMessage:`Trait type ${A(m)} is already included in '${I.Dyn}' expression.`});i.push(m)}}{let u=new Set(i.map(_=>_.id)),c=[...i];for(;c.length>0;){let _=c.pop();if(_.selfConstraints)for(let p of _.selfConstraints)u.has(p.id)||(u.add(p.id),i.push(p),c.push(p))}}for(let u=0;u<i.length;u++){let c=i[u];for(let _=u+1;_<i.length;_++){let p=i[_];for(let f of c.fields)for(let m of p.fields)if(f.label===m.label&&f.label!=="")throw y({token:e.token,errorMessage:`Trait types ${A(c)} and ${A(p)} have conflicting function name '${f.label}' in '${I.Dyn[0]}' expression.`})}}let a=[k.___dup[0],k.___drop[0],k.___dispose[0],k.dispose[0]];for(let u of i)for(let c of u.fields)if(a.includes(c.label)&&G(c.type))throw y({token:e.token,errorMessage:`Trait type ${A(u)} cannot have function '${c.label}' as it is reserved in 'dyn' expression.`});let s=Do({requiredTraits:i,env:t,negativeTraits:o});t=No({dynType:s,env:t,context:n});let l=ee(s);return e.$={env:t,value:l,type:l.type,pathCollection:[]},e}function Xr({expr:e,tupleFieldIndex:t,env:n,context:r,forType:i}){let o,a=e,s,l,u,c,_,p,f=!1,m;if(F(e)&&E(e,"?=",2)&&(u=e.args[1],a=e.args[0]),F(a)&&(E(a,"=",2)||E(a,"::",2))){if(E(a,"::",2)){if(f=!0,s=a.args[0],!je(s))throw y({token:s.token,errorMessage:`Expected identifier for element label, got ${w(s)}`});o=s.token.value}_=a.args[1],a=a.args[0]}if(u&&_)throw y({token:e.token,errorMessage:"Cannot have both default value and required value for element."});if(F(a)&&E(a,":",2)){if(s=a.args[0],l=a.args[1],F(s)&&E(s,I.comptime,1)){if(f)throw y({token:s.token,errorMessage:'Cannot combine the use of "comptime" with ::'});f=!0,s=s.args[0]}if(!z(s)||!je(s))throw y({token:s.token,errorMessage:`Expected identifier for element label, got ${w(s)}`});o=s.token.value}else if(F(a)&&E(a,I.comptime,1)){if(f)throw y({token:a.token,errorMessage:'Cannot combine the use of "comptime" with "::"'});if(f=!0,s=a.args[0],!z(s)||!je(s))throw y({token:s.token,errorMessage:`Expected identifier for element label, got ${w(s)}`});o=s.token.value}else!u&&!_&&(l=a);let g=r.expectedType?.type,h;if(g&&(we(g)||ce(g)||Te(g)||De(g))){let v=g.fields[t];if(!v)throw y({token:e.token,errorMessage:`Failed to get the field at index ${t}`});h=v.type}if(l){let v=S({expr:l,env:n,context:{...r,expectedType:h?{type:h,env:n}:void 0}});v.$?.env&&(n=v.$?.env);let T=v.$?.value;if(!O(T))throw y({token:l.token,errorMessage:`(1) Expected type for element, got ${w(l)}`});m=T.value}if(_){if(!f)throw y({token:_.token,errorMessage:`Assigned value expression is only allowed for compile-time only.
10563
10581
  Please consider adding "comptime" modifier to the field label.`});let v=m?{type:m,env:n}:h?{type:h,env:n}:void 0,T=S({expr:_,env:n,context:{...r,expectedType:v,forceCompileTimeBindings:void 0}});if(!T.$)throw y({token:_.token,errorMessage:`Failed to evaluate required value expression: ${w(_)}`});if(n=T.$?.env,p=T.$.value,!p)throw y({token:_.token,errorMessage:`Expected compile-time known value for required value, got ${w(_)}`});let $=T.$.type;if(v){if(!Y({type:v.type,env:n},{type:$,env:n}))throw y({token:_.token,errorMessage:`Assigned value type mismatch:
10564
10582
  Expected type: ${A(v.type)}
10565
10583
  Given type: ${A($)}`});m=v.type}else m=$}if(u){let v=m?{type:m,env:n}:h?{type:h,env:n}:void 0,T=S({expr:u,env:n,context:{...r,expectedType:v}});if(!T.$)throw y({token:u.token,errorMessage:`Failed to evaluate default value expression: ${w(u)}`});if(n=T.$.env,c=T.$?.value,!c)throw y({token:u.token,errorMessage:`Expected compile-time known value for default value, got ${w(u)}`});let $=T.$.type;if(v){if(!Y({type:v.type,env:n},{type:$,env:n}))throw y({token:u.token,errorMessage:`Default value type mismatch:
10566
10584
  Expected type: ${A(v.type)}
10567
- Given type: ${A($)}`});m=v.type}else m=$}if(!m)throw y({token:e.token,errorMessage:"Failed to infer the element type"});if(i!=="tuple"&&!s)throw y({token:e.token,errorMessage:`Expected label for ${i} field, got ${w(a)}`});return s&&(s.$={env:n,type:m,value:p??c??void 0,pathCollection:[]}),e!==l&&(e.$={env:n,value:H,type:H.type,pathCollection:[]}),kr(m,e.token),{field:{label:o??`${t}`,type:m,exprs:{expr:e,labelExpr:s,typeExpr:l,defaultValueExpr:u,assignedValueExpr:_},defaultValue:c,assignedValue:p},env:n}}function Td({expr:e,env:t,context:n}){if(!E(e,I.enum))throw y({token:e.token,errorMessage:`Expected "enum", got:
10585
+ Given type: ${A($)}`});m=v.type}else m=$}if(!m)throw y({token:e.token,errorMessage:"Failed to infer the element type"});if(i!=="tuple"&&!s)throw y({token:e.token,errorMessage:`Expected label for ${i} field, got ${w(a)}`});return s&&(s.$={env:n,type:m,value:p??c??void 0,pathCollection:[]}),e!==l&&(e.$={env:n,value:H,type:H.type,pathCollection:[]}),kr(m,e.token),{field:{label:o??`${t}`,type:m,exprs:{expr:e,labelExpr:s,typeExpr:l,defaultValueExpr:u,assignedValueExpr:_},defaultValue:c,assignedValue:p},env:n}}function Ed({expr:e,env:t,context:n}){if(!E(e,I.enum))throw y({token:e.token,errorMessage:`Expected "enum", got:
10568
10586
  ${w(e)}`});let r=Su(t);ms({enumType:r,env:t,context:n}),n.currentModulePath&&(r.definedInModulePath=n.currentModulePath,r.trait.definedInModulePath=n.currentModulePath);let i=r.variants,o=0n;for(let s=0;s<e.args.length;s++){let l=e.args[s];if(F(l)&&E(l,"=",2)&&z(l.args[0])){let u=l.args[0],c=l.args[1];if(!je(u))throw y({token:u.token,errorMessage:`Expected identifier for enum variant, got:
10569
10587
  ${w(u)}`});let _=u.token.value;if(i.some(h=>h.name===_))throw y({token:u.token,errorMessage:`Duplicate variant name "${_}" in enum`});let p=S({expr:c,env:t,context:{...n,SelfType:r}});if(!p.$)throw y({token:c.token,errorMessage:`Failed to evaluate discriminant value: ${w(c)}`});t=p.$.env;let f=p.$.value,m=p.$.type;if(!An(f)&&!vt(m))throw y({token:c.token,errorMessage:`Enum discriminant must be a compile-time integer, got: ${w(c)}`});if(!An(f))throw y({token:c.token,errorMessage:`Enum discriminant must be a compile-time known value, got: ${w(c)}`});let g=typeof f.value=="bigint"?f.value:BigInt(f.value);i.push({name:_,discriminant:g}),o=g+1n}else{if(F(l)&&(E(l,"::",2)||E(l,"?=",2)))throw y({token:l.token,errorMessage:'Please use "impl" block to define members/methods for enum types.'});if(z(l)){let u=l.token.value;if(!je(l))throw y({token:l.token,errorMessage:`Expected identifier for enum variant, got:
10570
10588
  ${w(l)}`});if(i.some(c=>c.name===u))throw y({token:l.token,errorMessage:`Duplicate variant name "${u}" in enum`});i.push({name:u,discriminant:o}),o+=1n}else{let u=l,c;if(E(l,"=",2)){u=l.args[0];let m=l.args[1],g=S({expr:m,env:t,context:{...n,SelfType:r}});if(!g.$)throw y({token:m.token,errorMessage:`Failed to evaluate discriminant value: ${w(m)}`});t=g.$.env;let h=g.$.value;if(!An(h))throw y({token:m.token,errorMessage:`Enum discriminant must be a compile-time integer, got: ${w(m)}`});c=typeof h.value=="bigint"?h.value:BigInt(h.value)}if(E(u,":"))throw y({token:u.token,errorMessage:"Enum variant with : is not implemented yet"});if(!F(u)||!je(u.func))throw y({token:u.token,errorMessage:`Expected identifier for enum variant, got:
10571
- ${w(u)}`});let _=u.func.token.value;if(i.some(m=>m.name===_))throw y({token:u.func.token,errorMessage:`Duplicate variant name "${_}" in enum`});let p=[];for(let m=0;m<u.args.length;m++){let g=u.args[m],{field:h,env:d}=Xr({expr:g,env:t,tupleFieldIndex:m,context:{...n,SelfType:r},forType:"enum"});if(p.find(T=>T.label===h.label))throw y({token:F(g)?g.args[0]?.token??g.token:g.token,errorMessage:`Duplicate field label "${h.label}" in enum variant`});if(h.assignedValue)throw y({token:h.exprs.assignedValueExpr?.token??h.exprs.expr.token,errorMessage:"Enum variant field cannot have compile-time assigned value."});p.push(h),t=d}let f=c??o;i.push({name:_,fields:p,discriminant:f}),o=f+1n}}}t=gu({enumType:r,env:t,context:n,errorToken:e.token});let a=ee(r);return e.$={env:t,value:a,type:a.type,pathCollection:[]},e.func.$=e.$,e}function Ed({expr:e,env:t,context:n}){if(!E(e,"->",2))throw y({token:e.token,errorMessage:`Expected -> operator for Fn trait type, got:
10589
+ ${w(u)}`});let _=u.func.token.value;if(i.some(m=>m.name===_))throw y({token:u.func.token,errorMessage:`Duplicate variant name "${_}" in enum`});let p=[];for(let m=0;m<u.args.length;m++){let g=u.args[m],{field:h,env:d}=Xr({expr:g,env:t,tupleFieldIndex:m,context:{...n,SelfType:r},forType:"enum"});if(p.find(T=>T.label===h.label))throw y({token:F(g)?g.args[0]?.token??g.token:g.token,errorMessage:`Duplicate field label "${h.label}" in enum variant`});if(h.assignedValue)throw y({token:h.exprs.assignedValueExpr?.token??h.exprs.expr.token,errorMessage:"Enum variant field cannot have compile-time assigned value."});p.push(h),t=d}let f=c??o;i.push({name:_,fields:p,discriminant:f}),o=f+1n}}}t=gu({enumType:r,env:t,context:n,errorToken:e.token});let a=ee(r);return e.$={env:t,value:a,type:a.type,pathCollection:[]},e.func.$=e.$,e}function $d({expr:e,env:t,context:n}){if(!E(e,"->",2))throw y({token:e.token,errorMessage:`Expected -> operator for Fn trait type, got:
10572
10590
  ${w(e)}`});let r=e.args[0],i=e.args[1];if(!F(r)||!E(r,I.Fn))throw y({token:r.token,errorMessage:`Expected Fn(...) for function trait, got:
10573
10591
  ${w(r)}`});let o=r.args,{parameters:a,forallParameters:s,implicitParameters:l,variadicParameter:u,whereClauseExprs:c,env:_}=Il({parameterExprs:o,env:t,context:{...n,isEvaluatingFunctionType:!0}}),p=S({expr:i,env:_,context:{...n,isEvaluatingFunctionType:!0}});if(!p.$)throw y({token:i.token,errorMessage:"Failed to evaluate return type for Fn trait."});let f=p.$.value,m;if(O(f))m=f.value;else throw y({token:i.token,errorMessage:`Expected a type for Fn return type, got:
10574
- ${w(i)}`});let g=ci({parameters:a,forallParameters:s,implicitParameters:l,variadicParameter:u,whereClauseExprs:c,return_:{type:m,typeExpr:i,isCompileTimeOnly:!1,isUnquote:!1,label:`fn_return_${qe(t.modulePath)}`},env:ct(_,!0),parametersFrame:_.frames[_.frames.length-1],isClosure:!0}),h=Oe(ct(_,!0));return h.isFn={callType:g},t=ct(_,!0),e.$={env:t,type:wt(h),value:ee(h),pathCollection:[]},e}function $d({expr:e,env:t,context:n}){if(e.args.length<1)throw y({token:e.token,errorMessage:"Future type constructor expects at least 1 argument (output type). Usage: Future(T), Future(T, ...(E)), Future(T, Raise, ...(E))"});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the element type expression for Future:
10592
+ ${w(i)}`});let g=ci({parameters:a,forallParameters:s,implicitParameters:l,variadicParameter:u,whereClauseExprs:c,return_:{type:m,typeExpr:i,isCompileTimeOnly:!1,isUnquote:!1,label:`fn_return_${qe(t.modulePath)}`},env:ct(_,!0),parametersFrame:_.frames[_.frames.length-1],isClosure:!0}),h=Oe(ct(_,!0));return h.isFn={callType:g},t=ct(_,!0),e.$={env:t,type:Ft(h),value:ee(h),pathCollection:[]},e}function Cd({expr:e,env:t,context:n}){if(e.args.length<1)throw y({token:e.token,errorMessage:"Future type constructor expects at least 1 argument (output type). Usage: Future(T), Future(T, ...(E)), Future(T, Raise, ...(E))"});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the element type expression for Future:
10575
10593
  ${w(r)}`});if(t=i.$.env,!O(i.$.value))throw y({token:r.token,errorMessage:`Future type constructor expects a type as its first argument, but got:
10576
- ${w(r)}`});let o=i.$.value.value,a=[];for(let u=1;u<e.args.length;u++){let c=e.args[u],_=oh(c,t,n);a.push(_.effect),t=_.env}let s=Oe(t);s.isFuture={outputType:o,effects:a};let l=a.length>0?`_${a.map(u=>u.type.id).join("_")}`:"";return s.id=`future_trait_${o.id}${l}`,e.$={env:t,type:wt(s),value:ee(s),pathCollection:[]},e}function oh(e,t,n){if(F(e)&&E(e,"...")&&e.args.length===1&&z(e.args[0]))return ah(e,t);let r=S({expr:e,env:t,context:{...n}});if(!r.$||!O(r.$.value))throw y({token:e.token,errorMessage:`Future effect argument must be an effect type or ...(E) spread, but got:
10577
- ${w(e)}`});let i=r.$.value.value;return t=r.$.env,{effect:{label:sh(i,e),type:i,isCompileTimeOnly:!0,isImplicit:!0,isEffectRowSpread:!1,isQuote:!1,isOwningTheRcValue:!1,exprs:fi({expr:e,labelExpr:void 0,typeExpr:e,defaultValueExpr:void 0,assignedValueExpr:void 0})},env:t}}function ah(e,t){let n=e.args[0].token.value,i=X(t,n).at(-1);if(!i)throw y({token:e.token,errorMessage:`Effect row variable "${n}" not found in scope. Declare it with forall(..., ...(${n}))`});let o=i.value?.[0],a;if(o&&O(o))if(x(o.value)&&o.value.isEffectsRow||ot(o.value))a=o.value;else throw y({token:e.token,errorMessage:`"...(${n})" requires "${n}" to be a forall-declared effect row variable, but it resolves to a concrete type. Use individual effect types directly instead of spreading them, e.g. Future(T, ${n}) instead of Future(T, ...(${n}))`});else if(o&&de(o)&&ot(o.type))a=o.type;else if(o&&de(o)&&x(o.type)&&o.type.isEffectsRow)a=o.type;else if(o&&de(o)&&He(o.type))a=pi(n,t);else throw y({token:e.token,errorMessage:`Effect row variable "${n}" has invalid value. Expected a type.`});return{effect:{label:n,type:a,isCompileTimeOnly:!0,isImplicit:!0,isEffectRowSpread:!0,isQuote:!1,isOwningTheRcValue:!1,exprs:fi({expr:e,labelExpr:e.args[0],typeExpr:e.args[0],defaultValueExpr:void 0,assignedValueExpr:void 0})},env:t}}function sh(e,t){return Te(e)&&e.typeName?e.typeName:x(e)&&e.name?e.name:w(t)}function na({expr:e,moduleFieldIndex:t,env:n,context:r,isForEvaluatingModuleType:i}){let o,a=e,s,l,u,c,_,p,f;if(F(e)&&E(e,"?=",2)&&(u=e.args[1],a=e.args[0]),F(a)&&(E(a,"=",2)||E(a,"::",2)||E(a,":=",2))){if(E(a,"::",2))throw y({token:a.token,errorMessage:`Cannot use "::" for module field. Use ":=" instead.
10594
+ ${w(r)}`});let o=i.$.value.value,a=[];for(let u=1;u<e.args.length;u++){let c=e.args[u],_=ah(c,t,n);a.push(_.effect),t=_.env}let s=Oe(t);s.isFuture={outputType:o,effects:a};let l=a.length>0?`_${a.map(u=>u.type.id).join("_")}`:"";return s.id=`future_trait_${o.id}${l}`,e.$={env:t,type:Ft(s),value:ee(s),pathCollection:[]},e}function ah(e,t,n){if(F(e)&&E(e,"...")&&e.args.length===1&&z(e.args[0]))return sh(e,t);let r=S({expr:e,env:t,context:{...n}});if(!r.$||!O(r.$.value))throw y({token:e.token,errorMessage:`Future effect argument must be an effect type or ...(E) spread, but got:
10595
+ ${w(e)}`});let i=r.$.value.value;return t=r.$.env,{effect:{label:lh(i,e),type:i,isCompileTimeOnly:!0,isImplicit:!0,isEffectRowSpread:!1,isQuote:!1,isOwningTheRcValue:!1,exprs:fi({expr:e,labelExpr:void 0,typeExpr:e,defaultValueExpr:void 0,assignedValueExpr:void 0})},env:t}}function sh(e,t){let n=e.args[0].token.value,i=X(t,n).at(-1);if(!i)throw y({token:e.token,errorMessage:`Effect row variable "${n}" not found in scope. Declare it with forall(..., ...(${n}))`});let o=i.value?.[0],a;if(o&&O(o))if(x(o.value)&&o.value.isEffectsRow||ot(o.value))a=o.value;else throw y({token:e.token,errorMessage:`"...(${n})" requires "${n}" to be a forall-declared effect row variable, but it resolves to a concrete type. Use individual effect types directly instead of spreading them, e.g. Future(T, ${n}) instead of Future(T, ...(${n}))`});else if(o&&de(o)&&ot(o.type))a=o.type;else if(o&&de(o)&&x(o.type)&&o.type.isEffectsRow)a=o.type;else if(o&&de(o)&&He(o.type))a=pi(n,t);else throw y({token:e.token,errorMessage:`Effect row variable "${n}" has invalid value. Expected a type.`});return{effect:{label:n,type:a,isCompileTimeOnly:!0,isImplicit:!0,isEffectRowSpread:!0,isQuote:!1,isOwningTheRcValue:!1,exprs:fi({expr:e,labelExpr:e.args[0],typeExpr:e.args[0],defaultValueExpr:void 0,assignedValueExpr:void 0})},env:t}}function lh(e,t){return Te(e)&&e.typeName?e.typeName:x(e)&&e.name?e.name:w(t)}function na({expr:e,moduleFieldIndex:t,env:n,context:r,isForEvaluatingModuleType:i}){let o,a=e,s,l,u,c,_,p,f;if(F(e)&&E(e,"?=",2)&&(u=e.args[1],a=e.args[0]),F(a)&&(E(a,"=",2)||E(a,"::",2)||E(a,":=",2))){if(E(a,"::",2))throw y({token:a.token,errorMessage:`Cannot use "::" for module field. Use ":=" instead.
10578
10596
  All module fields are compile-time only by default.`});_=a.args[1],a=a.args[0]}if(u&&_)throw y({token:e.token,errorMessage:"Cannot have both default value and required value for module field."});if(F(a)&&E(a,":",2)){if(s=a.args[0],l=a.args[1],F(s)&&E(s,I.comptime,1))throw y({token:s.token,errorMessage:'No need to use "comptime" modifier. All module fields are compile-time only by default.'});if(!z(s)&&!je(s))throw y({token:s.token,errorMessage:`Expected identifier for tuple field label, got ${w(s)}`});o=s.token.value}else{if(F(a)&&E(a,I.comptime,1))throw y({token:a.token,errorMessage:'No need to use "comptime" modifier. All module fields are compile-time only by default.'});if(!u&&!_)throw y({token:e.token,errorMessage:`Expected label for module field, got ${w(a)}`});if(s=a,!je(s))throw y({token:s.token,errorMessage:`Expected identifier for module field label, got ${w(s)}`});if(!z(s)&&!je(s))throw y({token:s.token,errorMessage:`Expected identifier for module field label, got ${w(s)}`});o=s.token.value}let m=r.expectedType?.type,g;if(m&&Te(m)){let h=m.fields[t];if(!h)throw y({token:e.token,errorMessage:`Failed to get the field at index ${t}`});g=h.type}if(l){let h=S({expr:l,env:n,context:{...r,expectedType:g?{type:g,env:n}:void 0}});h.$?.env&&(n=h.$?.env);let d=h.$?.value;if(!O(d))throw y({token:l.token,errorMessage:`Expected type for module field, got ${w(l)}`});f=d.value}if(_){let h=f?{type:f,env:n}:g?{type:g,env:n}:void 0,d=S({expr:_,env:n,context:{...r,expectedType:h}});if(!d.$)throw y({token:_.token,errorMessage:`Failed to evaluate required value expression: ${w(_)}`});if(n=d.$?.env,p=d.$.value,!p)throw y({token:_.token,errorMessage:`Expected compile-time known value for required value, got ${w(_)}`});let v=d.$.type;if(h){if(!Y({type:h.type,env:n},{type:v,env:n}))throw y({token:_.token,errorMessage:`Assigned value type mismatch:
10579
10597
  Expected type: ${A(h.type)}
10580
10598
  Given type: ${A(v)}`});f=h.type}else f=v}if(u){let h=f?{type:f,env:n}:g?{type:g,env:n}:void 0,d=S({expr:u,env:n,context:{...r,expectedType:h}});if(!d.$)throw y({token:u.token,errorMessage:`Failed to evaluate default value expression: ${w(u)}`});if(n=d.$.env,c=d.$?.value,!c)throw y({token:u.token,errorMessage:`Expected compile-time known value for default value, got ${w(u)}`});let v=d.$.type;if(h){if(!Y({type:h.type,env:n},{type:v,env:n}))throw y({token:u.token,errorMessage:`Default value type mismatch:
@@ -10585,16 +10603,16 @@ Type expressions are required for all function parameters in module fields to su
10585
10603
  Type expressions are required for return types in module fields to support proper type specialization.`})}if(i&&u&&!G(f))throw y({token:u.token,errorMessage:`Default values (?=) are only allowed for function type module elements (excluding closures).
10586
10604
  Module field "${o??"unnamed"}" has type: ${A(f)}
10587
10605
 
10588
- To avoid circular dependency issues, please explicitly provide the value for this field.`});return s&&(s.$={env:n,type:f,value:p??K(f,{variableName:o,env:n,context:r}),pathCollection:[]}),e!==l&&(e.$={env:n,value:H,type:H.type,pathCollection:[]}),{field:{label:o??`__field_${qe(n.modulePath)}`,type:f,exprs:{expr:e,labelExpr:s,typeExpr:l,defaultValueExpr:u,assignedValueExpr:_},defaultValue:c,assignedValue:p},env:n}}function Cd({expr:e,env:t,context:n}){if(!E(e,I.module))throw y({token:e.token,errorMessage:`Expected "module", got:
10606
+ To avoid circular dependency issues, please explicitly provide the value for this field.`});return s&&(s.$={env:n,type:f,value:p??K(f,{variableName:o,env:n,context:r}),pathCollection:[]}),e!==l&&(e.$={env:n,value:H,type:H.type,pathCollection:[]}),{field:{label:o??`__field_${qe(n.modulePath)}`,type:f,exprs:{expr:e,labelExpr:s,typeExpr:l,defaultValueExpr:u,assignedValueExpr:_},defaultValue:c,assignedValue:p},env:n}}function bd({expr:e,env:t,context:n}){if(!E(e,I.module))throw y({token:e.token,errorMessage:`Expected "module", got:
10589
10607
  ${w(e)}`});let r=Ca(t),i=[];r.fields=i,n.currentModulePath&&(r.definedInModulePath=n.currentModulePath);let o=e.args;for(let s=0;s<o.length;s++){let l=o[s];if(F(l)&&E(l,"...",1)){let u=l.args[0],c=S({expr:u,env:t,context:{...n,SelfType:void 0}});if(!c.$)throw y({token:u.token,errorMessage:`Failed to evaluate the extended struct expression: ${w(u)}`});let _=c.$.value;if(O(_)&&Te(_.value)||de(_)&&Te(_.type)){let p;O(_)&&Te(_.value)?p=_.value:p=_.type;for(let f of p.fields){let m=i.findIndex(g=>g.label===f.label);if(m>=0){if(i[m].assignedValue&&f.assignedValue&&At({value:i[m].assignedValue,env:t},{value:f.assignedValue,env:t})||!i[m].assignedValue&&!f.assignedValue&&Y({type:i[m].type,env:t},{type:f.type,env:t}))continue;throw console.log(!!i[m].assignedValue,!!f.assignedValue),console.log(A(i[m].type),`
10590
10608
  `,A(f.type),`
10591
10609
  `,Y({type:i[m].type,env:t},{type:f.type,env:t})),y({token:u.token,errorMessage:`Duplicate label 1 "${f.label}" in module`})}else i.push(f)}}else if(We(_)){let p=_;for(let f=0;f<p.fields.length;f++){let m=p.fields[f],g=p.type.fields[f],h=i.findIndex(d=>d.label===g.label);if(h>=0){if(i[h].assignedValue&&g.assignedValue&&At({value:i[h].assignedValue,env:t},{value:g.assignedValue,env:t})||!i[h].assignedValue&&!g.assignedValue&&Y({type:i[h].type,env:t},{type:g.type,env:t}))continue;throw y({token:u.token,errorMessage:`Duplicate label 2 "${g.label}" in module`})}else i.push({...p.type.fields[f],assignedValue:m})}}else throw y({token:u.token,errorMessage:`Expected a Module type or value for extending, got ${w(u)}`})}else{let{field:u,env:c}=na({expr:l,env:t,moduleFieldIndex:s,context:{...n,SelfType:void 0,SelfModuleType:r},isForEvaluatingModuleType:!0});if(i.find(p=>p.label===u.label))throw y({token:F(l)?l.args[0]?.token??l.token:l.token,errorMessage:`Duplicate label 3 "${u.label}" in module`});i.push(u),t=c}}let a=ee(r);return e.$={env:t,value:a,type:a.type,pathCollection:[]},e.func.$=e.$,e}function _o({expr:e,env:t,context:n}){let r=E(e,I.object),i=E(e,I.struct),o=E(e,I.newtype);if(!i&&!r&&!o)throw y({token:e.token,errorMessage:`Expected "struct" or "object" or "newtype", got:
10592
- ${w(e)}`});let a=r,s=o,l=ui(t,a,s);ds({structType:l,env:t,context:n}),n.currentModulePath&&(l.definedInModulePath=n.currentModulePath,l.trait.definedInModulePath=n.currentModulePath);let u=l.fields;for(let _=0;_<e.args.length;_++){let p=e.args[_];{let{field:f,env:m}=Xr({expr:p,env:t,tupleFieldIndex:_,context:{...n,SelfType:l},forType:"struct"});if(u.find(h=>h.label===f.label))throw y({token:F(p)?p.args[0]?.token??p.token:p.token,errorMessage:`Duplicate label "${f.label}" in struct`});u.push(f),t=m}}if(s&&u.length!==1)throw y({token:e.token,errorMessage:`Newtype struct must have exactly one field, but got ${u.length} fields.`});t=si({structType:l,env:t,context:n,errorToken:e.token});let c=ee(l);return e.$={env:t,type:c.type,value:c,pathCollection:[]},e.func.$=e.$,e}function bd({expr:e,env:t,context:n}){return he(e,I.newtype),_o({expr:e,env:t,context:n})}function kd({expr:e,env:t,context:n}){if(!E(e,I.object))throw y({token:e.token,errorMessage:`Expected "object", got:
10593
- ${w(e)}`});return _o({expr:e,env:t,context:n})}function wd({expr:e,env:t,context:n}){he(e,I.Slice,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the element type expression:
10610
+ ${w(e)}`});let a=r,s=o,l=ui(t,a,s);ds({structType:l,env:t,context:n}),n.currentModulePath&&(l.definedInModulePath=n.currentModulePath,l.trait.definedInModulePath=n.currentModulePath);let u=l.fields;for(let _=0;_<e.args.length;_++){let p=e.args[_];{let{field:f,env:m}=Xr({expr:p,env:t,tupleFieldIndex:_,context:{...n,SelfType:l},forType:"struct"});if(u.find(h=>h.label===f.label))throw y({token:F(p)?p.args[0]?.token??p.token:p.token,errorMessage:`Duplicate label "${f.label}" in struct`});u.push(f),t=m}}if(s&&u.length!==1)throw y({token:e.token,errorMessage:`Newtype struct must have exactly one field, but got ${u.length} fields.`});t=si({structType:l,env:t,context:n,errorToken:e.token});let c=ee(l);return e.$={env:t,type:c.type,value:c,pathCollection:[]},e.func.$=e.$,e}function kd({expr:e,env:t,context:n}){return he(e,I.newtype),_o({expr:e,env:t,context:n})}function wd({expr:e,env:t,context:n}){if(!E(e,I.object))throw y({token:e.token,errorMessage:`Expected "object", got:
10611
+ ${w(e)}`});return _o({expr:e,env:t,context:n})}function Fd({expr:e,env:t,context:n}){he(e,I.Slice,1);let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:r.token,errorMessage:`Failed to evaluate the element type expression:
10594
10612
  ${w(r)}`});if(!O(i.$.value))throw y({token:r.token,errorMessage:`Expected type for element type, got:
10595
10613
  ${w(r)}
10596
10614
 
10597
- If you are creating an array value with 1 element, please consider adding a "," in the end, like [1,]`});let o=i.$.value.value,a=$a(o),s=ee(a);return e.$={env:i.$.env,type:s.type,value:s,pathCollection:[]},e}function Ld({lhsExpr:e,env:t,context:n,selfType:r}){if(z(e)&&e.token.value==="Self")return{env:t,someType:r,isSelf:!0};if(z(e)){let a=e.token.value,s=X(t,a);if(s.length>0){let _=s[s.length-1];if(_.value&&O(_.value[0])&&x(_.value[0].value))return{env:t,someType:_.value[0].value,isSelf:!1}}let l=bn(tt(),a,{env:t,context:n}),u=ee(l),{env:c}=me({env:t,variable:{name:a,type:wt(l),isCompileTimeOnly:!0,value:[u],token:e.token,initializedAtToken:e.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1},allowVariableShadowing:!0});return{env:c,someType:l,isSelf:!1}}let i=S({expr:e,env:t,context:{...n,SelfType:r}});if(!i.$||!i.$.value||!O(i.$.value))throw y({token:e.token,errorMessage:"Expected type for left-hand side of where clause constraint."});let o=i.$.value;if(!x(o.value))throw y({token:e.token,errorMessage:`Expected SomeType for left-hand side of where clause constraint, got ${A(o.value)}`});return{env:i.$.env,someType:o.value,isSelf:!1}}function lh({lhsExpr:e,traitExpr:t,env:n,context:r,selfType:i,traitType:o}){let a=!1,s=t;F(t)&&E(t,"!")&&t.args.length===1&&(a=!0,s=t.args[0]);let l;try{l=Ld({lhsExpr:e,env:n,context:r,selfType:i})}catch{return{env:n,success:!1}}n=l.env;let u;try{u=S({expr:s,env:n,context:{...r,SelfType:i}})}catch{return{env:n,success:!1}}if(!u.$||!u.$.value||!O(u.$.value))return{env:n,success:!1};n=u.$.env;let c=u.$.value;if(!De(c.value))throw y({token:s.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(c.value)}`});let _=c.value;if(_.receiverType)throw y({token:s.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});if(l.isSelf&&(o.selfConstraints||(o.selfConstraints=[]),o.negativeSelfConstraints||(o.negativeSelfConstraints=[]),a?o.negativeSelfConstraints.push(_):o.selfConstraints.push(_)),!l.isSelf){let p=n.frames.length-1;a?l.someType.negativeTraits.some(f=>f.traitType.id===_.id)||l.someType.negativeTraits.push({traitType:_,frameLevel:p}):l.someType.requiredTraits.some(f=>f.traitType.id===_.id)||l.someType.requiredTraits.push({traitType:_,frameLevel:p})}return n=er({env:n,someType:l.someType,traitType:_,isNegated:a}),{env:n,success:!0}}function Fd({constraintExprs:e,env:t,context:n,selfType:r,traitType:i,collectPendingTraits:o=!1}){let a=[];for(let s of e){if(!F(s)||!E(s,"<:",2))throw y({token:s.token,errorMessage:`Expected constraint in the form "T <: Trait" or "T <: (Trait1, Trait2)", got: ${w(s)}`});let l=s.args[0],u=s.args[1],c;try{c=Ld({lhsExpr:l,env:t,context:n,selfType:r})}catch{if(o){a.push({lhsExpr:l,traitExpr:u,originalConstraintExpr:s});continue}throw y({token:l.token,errorMessage:"Expected type for left-hand side of where clause constraint."})}t=c.env;let _=[];F(u)&&E(u,I.tuple)?_.push(...u.args):_.push(u);for(let p of _){let f=!1,m=p;F(p)&&E(p,"!")&&p.args.length===1&&(f=!0,m=p.args[0]);let g;try{g=S({expr:m,env:t,context:{...n,SelfType:r,SelfTraitType:i}})}catch(v){if(o){a.push({lhsExpr:l,traitExpr:p,originalConstraintExpr:s});continue}throw v}if(!g.$||!g.$.value||!O(g.$.value)){if(o){a.push({lhsExpr:l,traitExpr:p,originalConstraintExpr:s});continue}throw y({token:m.token,errorMessage:"Expected trait type for right-hand side of where clause constraint."})}t=g.$.env;let h=g.$.value;if(!De(h.value))throw y({token:m.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(h.value)}`});let d=h.value;if(d.receiverType)throw y({token:m.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});c.isSelf&&(i.selfConstraints||(i.selfConstraints=[]),i.negativeSelfConstraints||(i.negativeSelfConstraints=[]),f?i.negativeSelfConstraints.push(d):i.selfConstraints.push(d)),t=er({env:t,someType:c.someType,traitType:d,isNegated:f})}}return{env:t,pendingTraits:a}}function uh({expr:e,traitFieldIndex:t,env:n,context:r,isForEvaluatingTraitType:i}){let o,a=e,s,l,u,c,_,p,f;if(F(e)&&E(e,"?=",2)&&(u=e.args[1],a=e.args[0]),F(a)&&(E(a,"=",2)||E(a,"::",2)||E(a,":=",2))){if(E(a,"::",2))throw y({token:a.token,errorMessage:`Cannot use "::" for trait field. Use ":=" instead.
10615
+ If you are creating an array value with 1 element, please consider adding a "," in the end, like [1,]`});let o=i.$.value.value,a=$a(o),s=ee(a);return e.$={env:i.$.env,type:s.type,value:s,pathCollection:[]},e}function Ad({lhsExpr:e,env:t,context:n,selfType:r}){if(z(e)&&e.token.value==="Self")return{env:t,someType:r,isSelf:!0};if(z(e)){let a=e.token.value,s=X(t,a);if(s.length>0){let _=s[s.length-1];if(_.value&&O(_.value[0])&&x(_.value[0].value))return{env:t,someType:_.value[0].value,isSelf:!1}}let l=bn(tt(),a,{env:t,context:n}),u=ee(l),{env:c}=me({env:t,variable:{name:a,type:Ft(l),isCompileTimeOnly:!0,value:[u],token:e.token,initializedAtToken:e.token,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1},allowVariableShadowing:!0});return{env:c,someType:l,isSelf:!1}}let i=S({expr:e,env:t,context:{...n,SelfType:r}});if(!i.$||!i.$.value||!O(i.$.value))throw y({token:e.token,errorMessage:"Expected type for left-hand side of where clause constraint."});let o=i.$.value;if(!x(o.value))throw y({token:e.token,errorMessage:`Expected SomeType for left-hand side of where clause constraint, got ${A(o.value)}`});return{env:i.$.env,someType:o.value,isSelf:!1}}function uh({lhsExpr:e,traitExpr:t,env:n,context:r,selfType:i,traitType:o}){let a=!1,s=t;F(t)&&E(t,"!")&&t.args.length===1&&(a=!0,s=t.args[0]);let l;try{l=Ad({lhsExpr:e,env:n,context:r,selfType:i})}catch{return{env:n,success:!1}}n=l.env;let u;try{u=S({expr:s,env:n,context:{...r,SelfType:i}})}catch{return{env:n,success:!1}}if(!u.$||!u.$.value||!O(u.$.value))return{env:n,success:!1};n=u.$.env;let c=u.$.value;if(!De(c.value))throw y({token:s.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(c.value)}`});let _=c.value;if(_.receiverType)throw y({token:s.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});if(l.isSelf&&(o.selfConstraints||(o.selfConstraints=[]),o.negativeSelfConstraints||(o.negativeSelfConstraints=[]),a?o.negativeSelfConstraints.push(_):o.selfConstraints.push(_)),!l.isSelf){let p=n.frames.length-1;a?l.someType.negativeTraits.some(f=>f.traitType.id===_.id)||l.someType.negativeTraits.push({traitType:_,frameLevel:p}):l.someType.requiredTraits.some(f=>f.traitType.id===_.id)||l.someType.requiredTraits.push({traitType:_,frameLevel:p})}return n=er({env:n,someType:l.someType,traitType:_,isNegated:a}),{env:n,success:!0}}function Ld({constraintExprs:e,env:t,context:n,selfType:r,traitType:i,collectPendingTraits:o=!1}){let a=[];for(let s of e){if(!F(s)||!E(s,"<:",2))throw y({token:s.token,errorMessage:`Expected constraint in the form "T <: Trait" or "T <: (Trait1, Trait2)", got: ${w(s)}`});let l=s.args[0],u=s.args[1],c;try{c=Ad({lhsExpr:l,env:t,context:n,selfType:r})}catch{if(o){a.push({lhsExpr:l,traitExpr:u,originalConstraintExpr:s});continue}throw y({token:l.token,errorMessage:"Expected type for left-hand side of where clause constraint."})}t=c.env;let _=[];F(u)&&E(u,I.tuple)?_.push(...u.args):_.push(u);for(let p of _){let f=!1,m=p;F(p)&&E(p,"!")&&p.args.length===1&&(f=!0,m=p.args[0]);let g;try{g=S({expr:m,env:t,context:{...n,SelfType:r,SelfTraitType:i}})}catch(v){if(o){a.push({lhsExpr:l,traitExpr:p,originalConstraintExpr:s});continue}throw v}if(!g.$||!g.$.value||!O(g.$.value)){if(o){a.push({lhsExpr:l,traitExpr:p,originalConstraintExpr:s});continue}throw y({token:m.token,errorMessage:"Expected trait type for right-hand side of where clause constraint."})}t=g.$.env;let h=g.$.value;if(!De(h.value))throw y({token:m.token,errorMessage:`Expected trait type for right-hand side of where clause constraint, got: ${A(h.value)}`});let d=h.value;if(d.receiverType)throw y({token:m.token,errorMessage:"Trait type in where clause already has a receiver type assigned."});c.isSelf&&(i.selfConstraints||(i.selfConstraints=[]),i.negativeSelfConstraints||(i.negativeSelfConstraints=[]),f?i.negativeSelfConstraints.push(d):i.selfConstraints.push(d)),t=er({env:t,someType:c.someType,traitType:d,isNegated:f})}}return{env:t,pendingTraits:a}}function ch({expr:e,traitFieldIndex:t,env:n,context:r,isForEvaluatingTraitType:i}){let o,a=e,s,l,u,c,_,p,f;if(F(e)&&E(e,"?=",2)&&(u=e.args[1],a=e.args[0]),F(a)&&(E(a,"=",2)||E(a,"::",2)||E(a,":=",2))){if(E(a,"::",2))throw y({token:a.token,errorMessage:`Cannot use "::" for trait field. Use ":=" instead.
10598
10616
  All trait fields are compile-time only by default.`});_=a.args[1],a=a.args[0]}if(u&&_)throw y({token:e.token,errorMessage:"Cannot have both default value and required value for trait field."});if(F(a)&&E(a,":",2)){if(s=a.args[0],l=a.args[1],F(s)&&E(s,I.comptime,1))throw y({token:s.token,errorMessage:'No need to use "comptime" modifier. All trait fields are compile-time only by default.'});if(!z(s)&&!je(s))throw y({token:s.token,errorMessage:`Expected identifier for tuple field label, got ${w(s)}`});o=s.token.value}else{if(F(a)&&E(a,I.comptime,1))throw y({token:a.token,errorMessage:'No need to use "comptime" modifier. All trait fields are compile-time only by default.'});if(!u&&!_)throw y({token:e.token,errorMessage:`Expected label for trait field, got ${w(a)}`});if(s=a,!je(s))throw y({token:s.token,errorMessage:`Expected identifier for trait field label, got ${w(s)}`});if(!z(s)&&!je(s))throw y({token:s.token,errorMessage:`Expected identifier for trait field label, got ${w(s)}`});o=s.token.value}let m=r.expectedType?.type,g;if(m&&De(m)){let d=m.fields[t];if(!d)throw y({token:e.token,errorMessage:`Failed to get the field at index ${t}`});g=d.type}if(l){let d=S({expr:l,env:n,context:{...r,expectedType:g?{type:g,env:n}:void 0}});d.$?.env&&(n=d.$?.env);let v=d.$?.value;if(!O(v))throw y({token:l.token,errorMessage:`Expected type for trait field, got ${w(l)}`});f=v.value}if(_){let d=f?{type:f,env:n}:g?{type:g,env:n}:void 0,v=S({expr:_,env:n,context:{...r,expectedType:d}});if(!v.$)throw y({token:_.token,errorMessage:`Failed to evaluate required value expression: ${w(_)}`});if(n=v.$?.env,p=v.$.value,!p)throw y({token:_.token,errorMessage:`Expected compile-time known value for required value, got ${w(_)}`});let T=v.$.type;if(d){if(!Y({type:d.type,env:n},{type:T,env:n}))throw y({token:_.token,errorMessage:`Assigned value type mismatch:
10599
10617
  Expected type: ${A(d.type)}
10600
10618
  Given type: ${A(T)}`});f=d.type}else f=T}if(u){let d=f?{type:f,env:n}:g?{type:g,env:n}:void 0,v=S({expr:u,env:n,context:{...r,expectedType:d}});if(!v.$)throw y({token:u.token,errorMessage:`Failed to evaluate default value expression: ${w(u)}`});if(n=v.$.env,c=v.$?.value,!c)throw y({token:u.token,errorMessage:`Expected compile-time known value for default value, got ${w(u)}`});let T=v.$.type;if(d){if(!Y({type:d.type,env:n},{type:T,env:n}))throw y({token:u.token,errorMessage:`Default value type mismatch:
@@ -10606,8 +10624,8 @@ Type expressions are required for all function parameters in trait fields to sup
10606
10624
  Type expressions are required for return types in trait fields to support proper type specialization.`})}if(i&&u&&!G(f))throw y({token:u.token,errorMessage:`Default values (?=) are only allowed for function type trait elements (excluding closures).
10607
10625
  Trait field "${o??"unnamed"}" has type: ${A(f)}
10608
10626
 
10609
- To avoid circular dependency issues, please explicitly provide the value for this field.`});s&&(s.$={env:n,type:f,value:p??K(f,{variableName:o,env:n,context:r}),pathCollection:[]}),e!==l&&(e.$={env:n,value:H,type:H.type,pathCollection:[]});let h;if(i&&!p&&He(f)&&f.level===0){if(o){let d=X(n,o),v=d[d.length-1];v?.value&&O(v.value[0])&&x(v.value[0].value)&&(h=v.value[0].value)}h||(h=bn(f,o??`__associated_type_${qe(n.modulePath)}`,{env:n,context:r}))}return{field:{label:o??`__field_${qe(n.modulePath)}`,type:f,exprs:{expr:e,labelExpr:s,typeExpr:l,defaultValueExpr:u,assignedValueExpr:_},defaultValue:c,assignedValue:p,unassignedSomeType:h},env:n}}function Ad({expr:e,env:t,context:n}){if(!E(e,I.trait))throw y({token:e.token,errorMessage:`Expected "trait", got:
10610
- ${w(e)}`});let r=Oe(t),i=[];r.fields=i,n.currentModulePath&&(r.definedInModulePath=n.currentModulePath),t=Pe(t);let o=e.args,a=bn(tt(),"Self",{env:t,context:n});a.trait=r,Vn(t,"Runtime")&&(t=tn("Runtime",a,t,n));let l;if(o.length>0){let p=o[o.length-1];if(F(p)&&E(p,I.where)&&(l=p.args,l.length===0))throw y({token:p.token,errorMessage:"The where clause must have at least one constraint."})}let u=[],c={...n,SelfTraitType:r};if(l&&l.length>0){let p=Fd({constraintExprs:l,env:t,context:c,selfType:a,traitType:r,collectPendingTraits:!0});t=p.env,u=p.pendingTraits}for(let p=0;p<o.length;p++){let f=o[p];if(F(f)&&E(f,I.where)){if(p!==o.length-1)throw y({token:f.token,errorMessage:"The where clause must be the last argument in a trait definition."});continue}{let{field:m,env:g}=uh({expr:f,env:t,traitFieldIndex:p,context:{...c,SelfType:a,SelfTraitType:r},isForEvaluatingTraitType:!0});if(i.find(d=>d.label===m.label))throw y({token:F(f)?f.args[0]?.token??f.token:f.token,errorMessage:`Duplicate label 3 "${m.label}" in trait`});if(i.push(m),t=g,m.unassignedSomeType){let d=X(t,m.label),v=d[d.length-1];if((v?.value&&O(v.value[0])&&x(v.value[0].value)?v.value[0].value:void 0)?.id!==m.unassignedSomeType.id){let $=ee(m.unassignedSomeType),C=m.exprs.labelExpr?.token??m.exprs.expr.token??f.token,{env:L}=me({env:t,variable:{name:m.label,type:$.type,isCompileTimeOnly:!0,value:[$],token:C,initializedAtToken:C,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1},allowVariableShadowing:!0});t=L}}}}if(u.length>0){let p=[];for(let f of u){let m=lh({lhsExpr:f.lhsExpr,traitExpr:f.traitExpr,originalConstraintExpr:f.originalConstraintExpr,env:t,context:c,selfType:a,traitType:r});t=m.env,m.success||p.push(f)}if(p.length>0){let f=p[0];Fd({constraintExprs:[f.originalConstraintExpr],env:t,context:c,selfType:a,traitType:r,collectPendingTraits:!1})}}t=ct(t,!0);let _=ee(r);return e.$={env:t,value:_,type:_.type,pathCollection:[]},e.func.$=e.$,e}function ch({args:e,env:t,context:n,forType:r}){let i=[];for(let a=0;a<e.length;a++){let s=e[a],{field:l,env:u}=Xr({expr:s,env:t,tupleFieldIndex:a,context:{...n},forType:r});if(l.label&&i.find(_=>_.label===l.label))throw y({token:F(s)?s.args[0]?.token??s.token:s.token,errorMessage:`Duplicate label "${l.label}" in tuple`});i.push(l),t=u}return{type:qi(i),env:t}}function Id({expr:e,env:t,context:n}){if(e.args.length===0){let o=ee(xn());return e.$={env:t,value:o,type:o.type,pathCollection:[]},e}let{type:r,env:i}=ch({args:e.args,env:t,context:{...n},forType:"tuple"});return t=i,r.fields.forEach(o=>{if(o.exprs.defaultValueExpr)throw y({token:o.exprs.defaultValueExpr.token,errorMessage:"Tuple type cannot have default value."})}),t=hu({env:t,context:n,tupleType:r,errorToken:e.token}),e.$={env:t,value:ee(r),type:wt(r),pathCollection:[]},e}function Sd({expr:e,env:t,context:n}){if(!E(e,I.union))throw y({token:e.token,errorMessage:`Expected "union", got:
10627
+ To avoid circular dependency issues, please explicitly provide the value for this field.`});s&&(s.$={env:n,type:f,value:p??K(f,{variableName:o,env:n,context:r}),pathCollection:[]}),e!==l&&(e.$={env:n,value:H,type:H.type,pathCollection:[]});let h;if(i&&!p&&He(f)&&f.level===0){if(o){let d=X(n,o),v=d[d.length-1];v?.value&&O(v.value[0])&&x(v.value[0].value)&&(h=v.value[0].value)}h||(h=bn(f,o??`__associated_type_${qe(n.modulePath)}`,{env:n,context:r}))}return{field:{label:o??`__field_${qe(n.modulePath)}`,type:f,exprs:{expr:e,labelExpr:s,typeExpr:l,defaultValueExpr:u,assignedValueExpr:_},defaultValue:c,assignedValue:p,unassignedSomeType:h},env:n}}function Id({expr:e,env:t,context:n}){if(!E(e,I.trait))throw y({token:e.token,errorMessage:`Expected "trait", got:
10628
+ ${w(e)}`});let r=Oe(t),i=[];r.fields=i,n.currentModulePath&&(r.definedInModulePath=n.currentModulePath),t=Pe(t);let o=e.args,a=bn(tt(),"Self",{env:t,context:n});a.trait=r,Vn(t,"Runtime")&&(t=tn("Runtime",a,t,n));let l;if(o.length>0){let p=o[o.length-1];if(F(p)&&E(p,I.where)&&(l=p.args,l.length===0))throw y({token:p.token,errorMessage:"The where clause must have at least one constraint."})}let u=[],c={...n,SelfTraitType:r};if(l&&l.length>0){let p=Ld({constraintExprs:l,env:t,context:c,selfType:a,traitType:r,collectPendingTraits:!0});t=p.env,u=p.pendingTraits}for(let p=0;p<o.length;p++){let f=o[p];if(F(f)&&E(f,I.where)){if(p!==o.length-1)throw y({token:f.token,errorMessage:"The where clause must be the last argument in a trait definition."});continue}{let{field:m,env:g}=ch({expr:f,env:t,traitFieldIndex:p,context:{...c,SelfType:a,SelfTraitType:r},isForEvaluatingTraitType:!0});if(i.find(d=>d.label===m.label))throw y({token:F(f)?f.args[0]?.token??f.token:f.token,errorMessage:`Duplicate label 3 "${m.label}" in trait`});if(i.push(m),t=g,m.unassignedSomeType){let d=X(t,m.label),v=d[d.length-1];if((v?.value&&O(v.value[0])&&x(v.value[0].value)?v.value[0].value:void 0)?.id!==m.unassignedSomeType.id){let $=ee(m.unassignedSomeType),C=m.exprs.labelExpr?.token??m.exprs.expr.token??f.token,{env:L}=me({env:t,variable:{name:m.label,type:$.type,isCompileTimeOnly:!0,value:[$],token:C,initializedAtToken:C,consumedAtToken:void 0,isOwningTheRcValue:!1,isOwningTheSameRcValueAs:void 0,isReassignable:!1},allowVariableShadowing:!0});t=L}}}}if(u.length>0){let p=[];for(let f of u){let m=uh({lhsExpr:f.lhsExpr,traitExpr:f.traitExpr,originalConstraintExpr:f.originalConstraintExpr,env:t,context:c,selfType:a,traitType:r});t=m.env,m.success||p.push(f)}if(p.length>0){let f=p[0];Ld({constraintExprs:[f.originalConstraintExpr],env:t,context:c,selfType:a,traitType:r,collectPendingTraits:!1})}}t=ct(t,!0);let _=ee(r);return e.$={env:t,value:_,type:_.type,pathCollection:[]},e.func.$=e.$,e}function _h({args:e,env:t,context:n,forType:r}){let i=[];for(let a=0;a<e.length;a++){let s=e[a],{field:l,env:u}=Xr({expr:s,env:t,tupleFieldIndex:a,context:{...n},forType:r});if(l.label&&i.find(_=>_.label===l.label))throw y({token:F(s)?s.args[0]?.token??s.token:s.token,errorMessage:`Duplicate label "${l.label}" in tuple`});i.push(l),t=u}return{type:qi(i),env:t}}function Sd({expr:e,env:t,context:n}){if(e.args.length===0){let o=ee(xn());return e.$={env:t,value:o,type:o.type,pathCollection:[]},e}let{type:r,env:i}=_h({args:e.args,env:t,context:{...n},forType:"tuple"});return t=i,r.fields.forEach(o=>{if(o.exprs.defaultValueExpr)throw y({token:o.exprs.defaultValueExpr.token,errorMessage:"Tuple type cannot have default value."})}),t=hu({env:t,context:n,tupleType:r,errorToken:e.token}),e.$={env:t,value:ee(r),type:Ft(r),pathCollection:[]},e}function Nd({expr:e,env:t,context:n}){if(!E(e,I.union))throw y({token:e.token,errorMessage:`Expected "union", got:
10611
10629
  ${w(e)}`});let r=Nu(t);n.currentModulePath&&(r.definedInModulePath=n.currentModulePath,r.trait.definedInModulePath=n.currentModulePath);let i=[];r.fields=i;let o=e.args;for(let s=0;s<o.length;s++){let l=o[s],{field:u,env:c}=Xr({expr:l,env:t,tupleFieldIndex:s,context:{...n,SelfType:r},forType:"union"});if(i.find(p=>p.label===u.label))throw y({token:F(l)?l.args[0]?.token??l.token:l.token,errorMessage:`Duplicate label "${u.label}" in union field.`});if(u.defaultValue)throw y({token:u.exprs.defaultValueExpr?.token??u.exprs.expr.token,errorMessage:"Union type cannot have default value for its fields."});if(li(u.type,t)||!Fr(u.type,t))throw y({token:u.exprs.expr.token,errorMessage:"Union type fields must be runtime types."});if(Le(u.type))throw y({token:u.exprs.expr.token,errorMessage:"Union type cannot have field with garbage-collected type."});i.push(u),t=c}t=du({unionType:r,env:t,context:n}),t=mu({unionType:r,env:t,context:n}),t=yu({unionType:r,env:t,context:n});let a=ee(r);return e.$={env:t,value:a,type:a.type,pathCollection:[]},e.func.$=e.$,e}function Ja({expr:e,env:t,context:n}){let r=n.expectedType?.type;if(!r)throw y({token:e.token,errorMessage:`Expected a function type, got:
10612
10630
  ${w(e)}`});let i,o=!1,a,s;if(G(r))i=r;else if(x(r)){let q=nn(r);if(q)a=q,i=q.isFn.callType,o=!0,s=r;else throw y({token:e.token,errorMessage:`Expected a function type or Impl(Fn(...)), got:
10613
10631
  ${A(r)}`})}else throw y({token:e.token,errorMessage:`Expected a function type or Impl(Fn(...)), got:
@@ -10619,23 +10637,23 @@ Got: "${Se}"`})}for(let q=0;q<i.forallParameters.length;q++){let Z=f[q],se=
10619
10637
  Expected: "${se.label}"
10620
10638
  Got: "${Ke}"`})}let Se=Z.token.value,fe=se.label,{env:xe}=me({env:t,variable:{name:Se,type:se.type,isCompileTimeOnly:se.isCompileTimeOnly,value:se.isCompileTimeOnly?[K(se.type,{variableName:se.label,env:t,context:n})]:void 0,token:Z.token,initializedAtToken:Z.token,consumedAtToken:void 0,isOwningTheRcValue:se.isOwningTheRcValue,parameterAlias:Se!==fe?fe:void 0}});t=xe,Z.$={env:t,type:se.type,value:se.isCompileTimeOnly?K(se.type,{variableName:se.label,env:t,context:n}):void 0,pathCollection:[]}}let C=t.frames[t.frames.length-1],L={...i,forallParameters:i.forallParameters,implicitParameters:T?v:v.map((q,Z)=>{let se=m[Z];if(se&&z(se)){let Se=se.token.value;if(Se!==q.label)return{...q,label:Se}}return q}),parameters:i.parameters.map((q,Z)=>{if(q.isCompileTimeOnly)return q;{let se=g[Z];return{...q,label:z(se)?se.token.value:q.label,exprs:{...q.exprs,expr:se,labelExpr:se,typeExpr:q.exprs.typeExpr,defaultValueExpr:void 0}}}}),return:{...i.return,typeExpr:i.return.typeExpr},parametersFrame:C,env:Ma(i.env)};if(L.whereClauseExprs?.length){let q=L.whereClauseExprs.map(se=>Ae(se));t=Hr({constraintExprs:q,env:t,context:{...n,isEvaluatingFunctionType:!0}}).env}let b={tag:"Function",type:L,body:_,frameLevel:t.frames.length-1,funcId:`fn_${qe(t.modulePath)}`,definitionSiteEnclosingFunctionType:n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},R=!!a,N=f.length>0||i.parameters.some(q=>Fe(q.type))||i.SelfType&&Fe(i.SelfType),B,D;if(N)Sl({functionBodyExpr:_,functionType:i,functionValue:b,env:t,context:n}),_.$={env:t,type:i.return.type,value:i.return.isCompileTimeOnly?K(i.return.type,{variableName:"function_body",env:t,context:n}):void 0,pathCollection:[]},B={...n,isExecuting:!1,capturedVariables:new Map},D=_;else{let{evaluationContext:q}=lo({...n,isExecuting:!1,isValidatingFunctionDefinition:!1},i,b,t);if(B=q,n.isInsideIoAsyncCall&&o&&(B={...B,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"async-block",evaluationEnv:t}}),D=ht({expr:_,env:t,context:B,variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),!D.$)throw y({token:_.token,errorMessage:"Failed to evaluate the function body."});t=D.$.env}let V=B.capturedVariables;if(Qn(D)&&(b.isControlFunction=!0),D.$&&(i.implicitParameters.some(q=>Te(q.type))||n.isInsideIoAsyncCall)){let q=Uu(D);q.hasAwaits&&(D.$.awaitAnalysis=q)}let U=D.$?.type;if(x(i.return.type)&&!i.return.type.resolvedConcreteType&&U){let q=U;if(x(q)&&q.resolvedConcreteType&&(q=q.resolvedConcreteType),!x(q)){let Z=yt({type:q,expectedType:void 0,expr:D,env:t});i.return.type.resolvedConcreteType=Z}}if(!b.isControlFunction&&U&&!Y({type:i.return.type,env:t},{type:U,env:t}))throw y({token:_.token,errorMessage:`Incompatible return type:
10621
10639
  - Expected: ${A(i.return.type)}
10622
- - Got : ${A(U)}`});D.$?.env&&(t=D.$?.env),t=ct(t,!0),t=h;let re;if(R&&V&&V.size>0&&(re=ja({capturedVariables:V,env:t})),R&&$.length>0){re||(re=new Map);for(let q of $)re.set(q.name,{frameLevel:0,usageType:"read",token:q.token,value:void 0,type:q.type,isEffectParam:!0})}let j,W,le,_e,ve=b;if((n.isAnalyzingCtfeCapability||n.forceCompileTimeBindings)&&!o){let q=ro(b,t,n);q&&(ve=q)}if(o&&a&&s){_e=Ha({expectedCaptureType:void 0,capturedVariablesWithValues:re,env:t,closureToken:e.token,context:{...n}}).captureType;let Z=Du(L,t),{capturedVariableDupExpressions:se,env:Se}=Ka({capturedVariablesWithValues:re,env:t,context:n});le=se,t=Se,b.funcId=`closure_${qe(t.modulePath)}`,b.closureInfo={closureType:Z,captureType:_e,effectParamNames:$.length>0?$.map(fe=>fe.name):void 0},x(s)&&_e&&Ya({wrapperType:s,captureType:_e,env:t,errorToken:e.token}),s.resolvedConcreteType=_e,j={...s,resolvedConcreteType:_e},W=void 0}else j=ve.type,W=ve;return e.$={env:t,type:j,value:W,pathCollection:R&&V?so(V):[],deferredDupExpressions:o&&le?le:void 0,captureType:o?_e:void 0,closureFunctionValue:o?ve:void 0,isAnonymousFunctionDefinition:!0},R&&Ge(e,!0),e}function Nd({expr:e,env:t,context:n}){let r=e.args;if(r.length===0)throw y({token:e.token,errorMessage:`Expected at least one element in array, got ${r.length}`});let i=r.length,o,a;n.expectedType&&ke(n.expectedType.type)&&(a=n.expectedType.type.childType);let s=[],l=[];for(let _=0;_<r.length;_++){let p=r[_],f=S({expr:p,env:t,context:{...n,expectedType:a?{type:a,env:t}:void 0}});if(qt(f,n),!f.$)throw y({token:p.token,errorMessage:`Failed to evaluate array element: ${w(p)}`});if(t=f.$.env,s.push(f.$.value),!o)o=a||f.$.type;else if(!Y({type:o,env:t},{type:f.$.type,env:t}))if(Y({type:yt({type:o,expectedType:void 0,expr:void 0,env:t}),env:t},{type:f.$.type,env:t}))o=f.$.type;else throw y({token:p.token,errorMessage:`Array element type mismatch:
10640
+ - Got : ${A(U)}`});D.$?.env&&(t=D.$?.env),t=ct(t,!0),t=h;let re;if(R&&V&&V.size>0&&(re=ja({capturedVariables:V,env:t})),R&&$.length>0){re||(re=new Map);for(let q of $)re.set(q.name,{frameLevel:0,usageType:"read",token:q.token,value:void 0,type:q.type,isEffectParam:!0})}let j,W,le,_e,ve=b;if((n.isAnalyzingCtfeCapability||n.forceCompileTimeBindings)&&!o){let q=ro(b,t,n);q&&(ve=q)}if(o&&a&&s){_e=Ha({expectedCaptureType:void 0,capturedVariablesWithValues:re,env:t,closureToken:e.token,context:{...n}}).captureType;let Z=Du(L,t),{capturedVariableDupExpressions:se,env:Se}=Ka({capturedVariablesWithValues:re,env:t,context:n});le=se,t=Se,b.funcId=`closure_${qe(t.modulePath)}`,b.closureInfo={closureType:Z,captureType:_e,effectParamNames:$.length>0?$.map(fe=>fe.name):void 0},x(s)&&_e&&Ya({wrapperType:s,captureType:_e,env:t,errorToken:e.token}),s.resolvedConcreteType=_e,j={...s,resolvedConcreteType:_e},W=void 0}else j=ve.type,W=ve;return e.$={env:t,type:j,value:W,pathCollection:R&&V?so(V):[],deferredDupExpressions:o&&le?le:void 0,captureType:o?_e:void 0,closureFunctionValue:o?ve:void 0,isAnonymousFunctionDefinition:!0},R&&Ge(e,!0),e}function Vd({expr:e,env:t,context:n}){let r=e.args;if(r.length===0)throw y({token:e.token,errorMessage:`Expected at least one element in array, got ${r.length}`});let i=r.length,o,a;n.expectedType&&ke(n.expectedType.type)&&(a=n.expectedType.type.childType);let s=[],l=[];for(let _=0;_<r.length;_++){let p=r[_],f=S({expr:p,env:t,context:{...n,expectedType:a?{type:a,env:t}:void 0}});if(qt(f,n),!f.$)throw y({token:p.token,errorMessage:`Failed to evaluate array element: ${w(p)}`});if(t=f.$.env,s.push(f.$.value),!o)o=a||f.$.type;else if(!Y({type:o,env:t},{type:f.$.type,env:t}))if(Y({type:yt({type:o,expectedType:void 0,expr:void 0,env:t}),env:t},{type:f.$.type,env:t}))o=f.$.type;else throw y({token:p.token,errorMessage:`Array element type mismatch:
10623
10641
  Expected type: ${A(o)}
10624
- Given type: ${A(f.$.type)}`});l.push(f)}let u=mr(o,Xt("Usize",i)),c=s.every(_=>!!_)?Mr(u,s):void 0;return e.$={env:t,type:u,value:c,pathCollection:[],runtimeArgExprsInOrder:l},Ge(e,!0),e}function Vd(e,t){if(e.token.type==="bool"){let n=e.token.value==="true",r=ft(n);return e.$={env:t,value:r,type:r.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected bool literal, got ${e.tag}`})}function xd(e,t){if(e.token.type==="char"){let n=_h(e.token.value),r=ur(BigInt(n));return e.$={env:t,value:r,type:r.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected char literal, got ${e.tag}`})}function _h(e){let t=e.slice(1,-1);if(t.length===1)return t.charCodeAt(0);if(t.length===2&&t[0]==="\\"){let n=t[1];switch(n){case"n":return 10;case"t":return 9;case"r":return 13;case"\\":return 92;case"'":return 39;case'"':return 34;case"0":return 0;case"a":return 7;case"b":return 8;case"f":return 12;case"v":return 11;default:throw new Error(`Unknown escape sequence: \\${n}`)}}else throw new Error(`Invalid char literal: ${e}`)}function Dd({expr:e,env:t,context:n}){let r=[],i=e.args;if(i.length===0)throw y({token:e.token,errorMessage:`Expected at least one element in comptime_list, got ${i.length}`});let o;n.expectedType&&Vt(n.expectedType.type)&&(o=n.expectedType.type.childType);for(let s=0;s<i.length;s++){let l=i[s],u=S({expr:l,env:t,context:{...n}});if(!u.$||!u.$.value)throw y({token:l.token,errorMessage:`Failed to evaluate expr_list element. Expected compile-time known value:
10625
- ${w(l)}`});t=u.$.env;let c=u.$.value;if(r.push(c),!o)o=u.$.type;else if(!Y({type:o,env:t},{type:u.$.type,env:t}))throw y({token:l.token,errorMessage:`Mismatched element types in comptime_list. Expected element of type ${A(o)}, got ${A(u.$.type)}`})}let a=zn(o,r);return e.$={env:t,type:a.type,value:a,pathCollection:[]},e}function Md(e,t,n){let i=X(t,"Box").find(f=>f.value&&ne(f.value[0])&&G(f.type));if(!i||!i.value||!ne(i.value[0]))throw new Error("Cannot find Box type constructor in environment");let o=i.value[0],a=o.type,s=a.parameters[0],l=ee(e),u=Pe(a.env),{env:c}=me({env:u,variable:{name:s.label,token:ae,type:l.type,isCompileTimeOnly:!0,initializedAtToken:ae,consumedAtToken:void 0,value:[l],isOwningTheRcValue:!1}}),{value:_,callerEnv:p}=oo({functionCalleeExpr:void 0,functionType:a,functionValue:o,argValues:{forallArgs:[],args:[{value:l,parameterType:s.type,argType:tt()}],variadicArgs:[]},callerEnv:t,calleeEnv:c,context:n});if(!O(_)||!pt(_.value))throw new Error("Box type constructor did not return a type value");return{boxType:_.value,env:p}}function ph(e,t,n){try{let r=S({expr:e,env:t,context:n});if(!r.$)return!1;let i=r.$.value;return ne(i)?!!X(t,"box").find(s=>s.value&&ne(s.value[0])&&s.value[0]===i):O(i)?!!i.value?.typeName?.startsWith("Box("):!1}catch{return!1}}function Od({expr:e,env:t,context:n}){he(e,I.dyn,1);let r=e.args[0],i=n.expectedType,o;if(n.expectedType&&be(n.expectedType.type)){let h=n.expectedType.type;if(o=bn(tt(),"",{requiredTraits:h.requiredTraits.map(d=>d.traitType),negativeTraits:h.negativeTraits.map(d=>d.traitType),env:t,context:n}),F(r)&&ph(r.func,t,{...n})&&E(r.args[0],"=>")){let{boxType:d,env:v}=Md(o,t,n);t=v,i={type:d,env:t}}else i={type:o,env:n.expectedType.env}}else i=void 0;let a=S({expr:r,env:t,context:{...n,expectedType:i}});if(!a.$)throw y({token:r.token,errorMessage:`Failed to evaluate the value expression for 'dyn':
10626
- ${w(r)}`});let s=a.$.type,l=s,u=a;if(!pt(l)&&!(x(l)&&Ce(l))){let{boxType:h,env:d}=Md(l,t,{...n});t=d;let v={tag:"Atom",token:{...r.token,value:"box",type:"identifier"},$:void 0},T={tag:"FnCall",func:v,args:[a],token:r.token,$:void 0},$=S({expr:T,env:t,context:{...n,expectedType:{type:h,env:t}}});if(!$.$)throw y({token:r.token,errorMessage:`Failed to auto-box value for 'dyn':
10627
- ${w(r)}`});t=$.$.env,l=$.$.type,u=$,e.args[0]=$}else t=a.$.env;qt(u,n),t=u.$.env;let c=[],_=[],p=new Set,f;if(n.expectedType&&be(n.expectedType.type))f=n.expectedType.type;else if($n(l)){let h=l.fields[0].type;if(h.trait){let d=[];for(let v of h.trait.fields)v.assignedValue&&Tt(v.assignedValue)&&d.push(v.assignedValue.type);f=Do({requiredTraits:d,negativeTraits:[],env:t}),t=No({dynType:f,env:t,context:n})}else throw y({token:e.token,errorMessage:`'${I.dyn}' with Box(T) requires T to have a trait. Got boxed type: ${A(h)}`})}else if(l.trait){let h=[];for(let d of l.trait.fields)d.assignedValue&&Tt(d.assignedValue)&&h.push(d.assignedValue.type);f=Do({requiredTraits:h,negativeTraits:[],env:t}),t=No({dynType:f,env:t,context:n})}else throw y({token:e.token,errorMessage:`'${I.dyn}' requires either an expected Dyn type context, a SomeType (Impl) value, or a type with a trait. Got value type: ${A(l)}`});let m=[];if($n(l)){let h=l.fields[0].type;(x(h)||be(h))&&m.push(...h.negativeTraits.map(d=>d.traitType)??[])}for(let{traitType:h}of f.requiredTraits)for(let d of m)if(Y({type:h,env:t},{type:d,env:t}))throw y({token:e.token,errorMessage:`Required trait ${A(h)} is in the negative traits list and cannot be used.`});for(let{traitType:h}of f.requiredTraits)if(!p.has(h))if($n(l)&&(x(l.fields[0].type)||be(l.fields[0].type))){let d=l.fields[0].type,v=!1,T=x(d)&&d.resolvedConcreteType?d.resolvedConcreteType:s!==l?s:void 0;if(T?.trait){for(let $ of T.trait.fields)if($.assignedValue&&Tt($.assignedValue)&&Y({type:h,env:t},{type:$.assignedValue.type,env:t})){_.push($.assignedValue),c.push($.assignedValue.type),p.add(h),v=!0;break}}if(!v){let $=d.requiredTraits.map(C=>C.traitType);for(let C of $)if(Y({type:h,env:t},{type:C,env:t})){let L=[];for(let R=0;R<h.fields.length;R++){let N=h.fields[R],B=C.fields.findIndex(D=>D.label===N.label);B===-1?L.push(void 0):L.push(C.fields[B].assignedValue)}let b=Fi(h,L);_.push(b),c.push(b.type),p.add(h),v=!0;break}if(!v)throw y({token:e.token,errorMessage:`Required trait ${A(h)} not found in SomeType's requiredTraits.`})}}else{let d=$n(l)?l.fields[0].type:l;if(d.trait){let v=!1;for(let T of d.trait.fields)if(T.assignedValue&&Tt(T.assignedValue)&&Y({type:h,env:t},{type:T.assignedValue.type,env:t})){_.push(T.assignedValue),c.push(T.assignedValue.type),p.add(h),v=!0;break}if(!v)throw y({token:e.token,errorMessage:`Required trait ${A(h)} is not implemented by type ${A(l)}.`})}else throw y({token:e.token,errorMessage:`Cannot find trait ${A(h)} for value type ${A(l)}.`})}let g=[];for(let{traitType:h}of f.requiredTraits){let d=c.findIndex(v=>Y({type:h,env:t},{type:v,env:t}));if(d===-1)throw y({token:e.token,errorMessage:`No trait value found for expected trait type ${A(h)}.`});g.push(_[d])}return e.$={env:t,value:void 0,type:f,pathCollection:a.$.pathCollection,dynCallTraitValues:g},Ge(e,!0),e}function Rd(e,t,n){if(e.token.type==="float"){let r=parseFloat(e.token.value),i="ComptimeFloat";if(n.expectedType){let a=n.expectedType.type;Fo(a)?i="F32":Lo(a)&&(i="F64")}let o=Xt(i,r);return e.$={env:t,value:o,type:o.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected float literal, got ${e.tag}`})}function Pd(e,t,n){if(e.token.type==="integer"){let r=e.token.value.replace(/_/g,""),i=10;r.match(/^0x/i)?(i=16,r=r.slice(2)):r.match(/^0b/i)?(i=2,r=r.slice(2)):r.match(/^0o/i)&&(i=8,r=r.slice(2));let o="ComptimeInt";if(n.expectedType){let u=n.expectedType.type;ho(u)?o="Usize":vo(u)?o="Isize":Hn(u)?o="U8":To(u)?o="I8":Eo(u)?o="U16":$o(u)?o="I16":Co(u)?o="U32":bo(u)?o="I32":ko(u)?o="U64":wo(u)&&(o="I64")}let a=o==="U64"||o==="I64"||o==="Usize"||o==="Isize",s;a||o==="ComptimeInt"?i===16?s=BigInt("0x"+r):i===8?s=BigInt("0o"+r):i===2?s=BigInt("0b"+r):s=BigInt(r):s=parseInt(r,i);let l=Xt(o,s);return e.$={env:t,value:l,type:l.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected integer literal, got ${e.tag}`})}function Ud(e,t){if(e.token.type==="string"){let n=on(JSON.parse(e.token.value));return e.$={env:t,value:n,type:n.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected string literal, got ${e.tag}`})}function fh({expr:e,tupleFieldIndex:t,env:n,context:r,elementIndex:i,runtimeArgExprsInOrder:o}){let a=e,s=e,l;if(F(a)&&E(a,":",2)){let f=a.args[0];throw y({token:f.token,errorMessage:"Labelled field is not allowed in tuple value."})}let u=r.expectedType?.type,c;if(u){if(!we(u))throw y({token:e.token,errorMessage:`(2) Failed to evaluate the tuple fields. Expected type to be:
10642
+ Given type: ${A(f.$.type)}`});l.push(f)}let u=mr(o,Xt("Usize",i)),c=s.every(_=>!!_)?Mr(u,s):void 0;return e.$={env:t,type:u,value:c,pathCollection:[],runtimeArgExprsInOrder:l},Ge(e,!0),e}function xd(e,t){if(e.token.type==="bool"){let n=e.token.value==="true",r=ft(n);return e.$={env:t,value:r,type:r.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected bool literal, got ${e.tag}`})}function Dd(e,t){if(e.token.type==="char"){let n=ph(e.token.value),r=ur(BigInt(n));return e.$={env:t,value:r,type:r.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected char literal, got ${e.tag}`})}function ph(e){let t=e.slice(1,-1);if(t.length===1)return t.charCodeAt(0);if(t.length===2&&t[0]==="\\"){let n=t[1];switch(n){case"n":return 10;case"t":return 9;case"r":return 13;case"\\":return 92;case"'":return 39;case'"':return 34;case"0":return 0;case"a":return 7;case"b":return 8;case"f":return 12;case"v":return 11;default:throw new Error(`Unknown escape sequence: \\${n}`)}}else throw new Error(`Invalid char literal: ${e}`)}function Md({expr:e,env:t,context:n}){let r=[],i=e.args;if(i.length===0)throw y({token:e.token,errorMessage:`Expected at least one element in comptime_list, got ${i.length}`});let o;n.expectedType&&Vt(n.expectedType.type)&&(o=n.expectedType.type.childType);for(let s=0;s<i.length;s++){let l=i[s],u=S({expr:l,env:t,context:{...n}});if(!u.$||!u.$.value)throw y({token:l.token,errorMessage:`Failed to evaluate expr_list element. Expected compile-time known value:
10643
+ ${w(l)}`});t=u.$.env;let c=u.$.value;if(r.push(c),!o)o=u.$.type;else if(!Y({type:o,env:t},{type:u.$.type,env:t}))throw y({token:l.token,errorMessage:`Mismatched element types in comptime_list. Expected element of type ${A(o)}, got ${A(u.$.type)}`})}let a=zn(o,r);return e.$={env:t,type:a.type,value:a,pathCollection:[]},e}function Od(e,t,n){let i=X(t,"Box").find(f=>f.value&&ne(f.value[0])&&G(f.type));if(!i||!i.value||!ne(i.value[0]))throw new Error("Cannot find Box type constructor in environment");let o=i.value[0],a=o.type,s=a.parameters[0],l=ee(e),u=Pe(a.env),{env:c}=me({env:u,variable:{name:s.label,token:ae,type:l.type,isCompileTimeOnly:!0,initializedAtToken:ae,consumedAtToken:void 0,value:[l],isOwningTheRcValue:!1}}),{value:_,callerEnv:p}=oo({functionCalleeExpr:void 0,functionType:a,functionValue:o,argValues:{forallArgs:[],args:[{value:l,parameterType:s.type,argType:tt()}],variadicArgs:[]},callerEnv:t,calleeEnv:c,context:n});if(!O(_)||!pt(_.value))throw new Error("Box type constructor did not return a type value");return{boxType:_.value,env:p}}function fh(e,t,n){try{let r=S({expr:e,env:t,context:n});if(!r.$)return!1;let i=r.$.value;return ne(i)?!!X(t,"box").find(s=>s.value&&ne(s.value[0])&&s.value[0]===i):O(i)?!!i.value?.typeName?.startsWith("Box("):!1}catch{return!1}}function Rd({expr:e,env:t,context:n}){he(e,I.dyn,1);let r=e.args[0],i=n.expectedType,o;if(n.expectedType&&be(n.expectedType.type)){let h=n.expectedType.type;if(o=bn(tt(),"",{requiredTraits:h.requiredTraits.map(d=>d.traitType),negativeTraits:h.negativeTraits.map(d=>d.traitType),env:t,context:n}),F(r)&&fh(r.func,t,{...n})&&E(r.args[0],"=>")){let{boxType:d,env:v}=Od(o,t,n);t=v,i={type:d,env:t}}else i={type:o,env:n.expectedType.env}}else i=void 0;let a=S({expr:r,env:t,context:{...n,expectedType:i}});if(!a.$)throw y({token:r.token,errorMessage:`Failed to evaluate the value expression for 'dyn':
10644
+ ${w(r)}`});let s=a.$.type,l=s,u=a;if(!pt(l)&&!(x(l)&&Ce(l))){let{boxType:h,env:d}=Od(l,t,{...n});t=d;let v={tag:"Atom",token:{...r.token,value:"box",type:"identifier"},$:void 0},T={tag:"FnCall",func:v,args:[a],token:r.token,$:void 0},$=S({expr:T,env:t,context:{...n,expectedType:{type:h,env:t}}});if(!$.$)throw y({token:r.token,errorMessage:`Failed to auto-box value for 'dyn':
10645
+ ${w(r)}`});t=$.$.env,l=$.$.type,u=$,e.args[0]=$}else t=a.$.env;qt(u,n),t=u.$.env;let c=[],_=[],p=new Set,f;if(n.expectedType&&be(n.expectedType.type))f=n.expectedType.type;else if($n(l)){let h=l.fields[0].type;if(h.trait){let d=[];for(let v of h.trait.fields)v.assignedValue&&Tt(v.assignedValue)&&d.push(v.assignedValue.type);f=Do({requiredTraits:d,negativeTraits:[],env:t}),t=No({dynType:f,env:t,context:n})}else throw y({token:e.token,errorMessage:`'${I.dyn}' with Box(T) requires T to have a trait. Got boxed type: ${A(h)}`})}else if(l.trait){let h=[];for(let d of l.trait.fields)d.assignedValue&&Tt(d.assignedValue)&&h.push(d.assignedValue.type);f=Do({requiredTraits:h,negativeTraits:[],env:t}),t=No({dynType:f,env:t,context:n})}else throw y({token:e.token,errorMessage:`'${I.dyn}' requires either an expected Dyn type context, a SomeType (Impl) value, or a type with a trait. Got value type: ${A(l)}`});let m=[];if($n(l)){let h=l.fields[0].type;(x(h)||be(h))&&m.push(...h.negativeTraits.map(d=>d.traitType)??[])}for(let{traitType:h}of f.requiredTraits)for(let d of m)if(Y({type:h,env:t},{type:d,env:t}))throw y({token:e.token,errorMessage:`Required trait ${A(h)} is in the negative traits list and cannot be used.`});for(let{traitType:h}of f.requiredTraits)if(!p.has(h))if($n(l)&&(x(l.fields[0].type)||be(l.fields[0].type))){let d=l.fields[0].type,v=!1,T=x(d)&&d.resolvedConcreteType?d.resolvedConcreteType:s!==l?s:void 0;if(T?.trait){for(let $ of T.trait.fields)if($.assignedValue&&Tt($.assignedValue)&&Y({type:h,env:t},{type:$.assignedValue.type,env:t})){_.push($.assignedValue),c.push($.assignedValue.type),p.add(h),v=!0;break}}if(!v){let $=d.requiredTraits.map(C=>C.traitType);for(let C of $)if(Y({type:h,env:t},{type:C,env:t})){let L=[];for(let R=0;R<h.fields.length;R++){let N=h.fields[R],B=C.fields.findIndex(D=>D.label===N.label);B===-1?L.push(void 0):L.push(C.fields[B].assignedValue)}let b=Fi(h,L);_.push(b),c.push(b.type),p.add(h),v=!0;break}if(!v)throw y({token:e.token,errorMessage:`Required trait ${A(h)} not found in SomeType's requiredTraits.`})}}else{let d=$n(l)?l.fields[0].type:l;if(d.trait){let v=!1;for(let T of d.trait.fields)if(T.assignedValue&&Tt(T.assignedValue)&&Y({type:h,env:t},{type:T.assignedValue.type,env:t})){_.push(T.assignedValue),c.push(T.assignedValue.type),p.add(h),v=!0;break}if(!v)throw y({token:e.token,errorMessage:`Required trait ${A(h)} is not implemented by type ${A(l)}.`})}else throw y({token:e.token,errorMessage:`Cannot find trait ${A(h)} for value type ${A(l)}.`})}let g=[];for(let{traitType:h}of f.requiredTraits){let d=c.findIndex(v=>Y({type:h,env:t},{type:v,env:t}));if(d===-1)throw y({token:e.token,errorMessage:`No trait value found for expected trait type ${A(h)}.`});g.push(_[d])}return e.$={env:t,value:void 0,type:f,pathCollection:a.$.pathCollection,dynCallTraitValues:g},Ge(e,!0),e}function Pd(e,t,n){if(e.token.type==="float"){let r=parseFloat(e.token.value),i="ComptimeFloat";if(n.expectedType){let a=n.expectedType.type;Fo(a)?i="F32":Lo(a)&&(i="F64")}let o=Xt(i,r);return e.$={env:t,value:o,type:o.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected float literal, got ${e.tag}`})}function Ud(e,t,n){if(e.token.type==="integer"){let r=e.token.value.replace(/_/g,""),i=10;r.match(/^0x/i)?(i=16,r=r.slice(2)):r.match(/^0b/i)?(i=2,r=r.slice(2)):r.match(/^0o/i)&&(i=8,r=r.slice(2));let o="ComptimeInt";if(n.expectedType){let u=n.expectedType.type;ho(u)?o="Usize":vo(u)?o="Isize":Hn(u)?o="U8":To(u)?o="I8":Eo(u)?o="U16":$o(u)?o="I16":Co(u)?o="U32":bo(u)?o="I32":ko(u)?o="U64":wo(u)&&(o="I64")}let a=o==="U64"||o==="I64"||o==="Usize"||o==="Isize",s;a||o==="ComptimeInt"?i===16?s=BigInt("0x"+r):i===8?s=BigInt("0o"+r):i===2?s=BigInt("0b"+r):s=BigInt(r):s=parseInt(r,i);let l=Xt(o,s);return e.$={env:t,value:l,type:l.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected integer literal, got ${e.tag}`})}function zd(e,t){if(e.token.type==="string"){let n=on(JSON.parse(e.token.value));return e.$={env:t,value:n,type:n.type,pathCollection:[]},e}else throw y({token:e.token,errorMessage:`Expected string literal, got ${e.tag}`})}function dh({expr:e,tupleFieldIndex:t,env:n,context:r,elementIndex:i,runtimeArgExprsInOrder:o}){let a=e,s=e,l;if(F(a)&&E(a,":",2)){let f=a.args[0];throw y({token:f.token,errorMessage:"Labelled field is not allowed in tuple value."})}let u=r.expectedType?.type,c;if(u){if(!we(u))throw y({token:e.token,errorMessage:`(2) Failed to evaluate the tuple fields. Expected type to be:
10628
10646
  ${A(u)}`});let f=u.fields[t];if(!f)throw y({token:e.token,errorMessage:`Failed to get the tuple field at index ${t}`});c=f.type}let _=S({expr:s,env:n,context:{...r,expectedType:c?{type:c,env:n}:void 0}});if(qt(_,r),!_.$)throw y({token:s.token,errorMessage:`Failed to evaluate the tuple field: ${w(s)}`});n=_.$.env;let p=_.$.value;if(p&&O(_.$.value))throw y({token:s.token,errorMessage:`Cannot store a type value in tuple, please use module instead:
10629
- ${w(s)}`});return!c||!ti(c,n)?l=yt({type:_.$.type,expectedType:void 0,expr:void 0,env:n}):l=_.$.type,o.push(_),e!==s&&(e.$={env:n,type:l,value:p,pathCollection:[]}),{type:{exprs:{expr:e,labelExpr:void 0,typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:void 0},type:l,label:i.toString()},value:p,env:n}}function dh({args:e,env:t,context:n}){let r=[],i=[],o=[];for(let l=0;l<e.length;l++){let u=e[l],{type:c,value:_,env:p}=fh({expr:u,env:t,tupleFieldIndex:l,context:{...n},elementIndex:l,runtimeArgExprsInOrder:o});r.push(c),i.push(_),t=p}let a=qi(r),s=i.some(l=>!l)?void 0:_a(a,i);return{type:a,value:s,env:t,runtimeArgExprsInOrder:o}}function zd({expr:e,env:t,context:n}){if(!E(e,I.tuple))throw y({token:e.token,errorMessage:`Expected tuple, got ${e.tag}`});if(e.args.length===0)return e.$={env:t,value:H,type:H.type,pathCollection:[]},e;let{type:r,value:i,env:o,runtimeArgExprsInOrder:a}=dh({args:e.args,env:t,context:n});return t=o,r.fields.forEach(s=>{if(s.exprs.defaultValueExpr)throw y({token:s.exprs.defaultValueExpr.token,errorMessage:"Tuple value field cannot have default value."});if(s.exprs.labelExpr)throw y({token:s.exprs.labelExpr.token,errorMessage:"Tuple value field cannot have labels."})}),e.$={env:t,value:i,type:r,pathCollection:[],runtimeArgExprsInOrder:a},Ge(e,!0),e}function es({expr:e,env:t,context:n}){if(!E(e,":",2))throw y({token:e.token,errorMessage:'Expected ":" for variable binding.'});let r=e.args[0],i=e.args[1],o=S({expr:i,env:t,context:{...n}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate rhs expression:
10647
+ ${w(s)}`});return!c||!ti(c,n)?l=yt({type:_.$.type,expectedType:void 0,expr:void 0,env:n}):l=_.$.type,o.push(_),e!==s&&(e.$={env:n,type:l,value:p,pathCollection:[]}),{type:{exprs:{expr:e,labelExpr:void 0,typeExpr:void 0,defaultValueExpr:void 0,assignedValueExpr:void 0},type:l,label:i.toString()},value:p,env:n}}function mh({args:e,env:t,context:n}){let r=[],i=[],o=[];for(let l=0;l<e.length;l++){let u=e[l],{type:c,value:_,env:p}=dh({expr:u,env:t,tupleFieldIndex:l,context:{...n},elementIndex:l,runtimeArgExprsInOrder:o});r.push(c),i.push(_),t=p}let a=qi(r),s=i.some(l=>!l)?void 0:_a(a,i);return{type:a,value:s,env:t,runtimeArgExprsInOrder:o}}function Bd({expr:e,env:t,context:n}){if(!E(e,I.tuple))throw y({token:e.token,errorMessage:`Expected tuple, got ${e.tag}`});if(e.args.length===0)return e.$={env:t,value:H,type:H.type,pathCollection:[]},e;let{type:r,value:i,env:o,runtimeArgExprsInOrder:a}=mh({args:e.args,env:t,context:n});return t=o,r.fields.forEach(s=>{if(s.exprs.defaultValueExpr)throw y({token:s.exprs.defaultValueExpr.token,errorMessage:"Tuple value field cannot have default value."});if(s.exprs.labelExpr)throw y({token:s.exprs.labelExpr.token,errorMessage:"Tuple value field cannot have labels."})}),e.$={env:t,value:i,type:r,pathCollection:[],runtimeArgExprsInOrder:a},Ge(e,!0),e}function es({expr:e,env:t,context:n}){if(!E(e,":",2))throw y({token:e.token,errorMessage:'Expected ":" for variable binding.'});let r=e.args[0],i=e.args[1],o=S({expr:i,env:t,context:{...n}});if(!o.$)throw y({token:i.token,errorMessage:`Failed to evaluate rhs expression:
10630
10648
  ${w(i)}`});t=o.$.env;let a=o.$.value;if(!O(a))throw y({token:i.token,errorMessage:`Expected type for rhs, got ${w(i)}`});let s=a.value;if(ke(s)&&de(s.length))throw y({token:i.token,errorMessage:`Array type with inferred length '_' is not allowed in type annotations.
10631
10649
  Use explicit length like 'Array(i32, 3)' or omit the type annotation and initialize with 'arr := Array(i32, _)(1, 2, 3)'`});kr(s,o.token);let l=!1,u=!1;if(F(r)&&E(r,I.comptime)){if(l=!0,r.args.length!==1)throw y({token:r.token,errorMessage:`Expected one argument for "comptime" , got ${r.args.length}`});r=r.args[0]}if(F(r)&&E(r,I.given)){if(r.args.length!==1)throw y({token:r.token,errorMessage:`Expected exactly one argument for "given", got ${r.args.length}`});u=!0,l=!0,r=r.args[0]}if(l=l||n.forceCompileTimeBindings===!0,!l&&n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&n.isEvaluatingFunctionBodyOrAsyncBlock?.type.return.isCompileTimeOnly)throw y({token:r.token,errorMessage:"Unexpected runtime variable binding in a compile-time only function body."});if(!je(r))throw y({token:r.token,errorMessage:`Invalid binding to "${r.token.value}", expected identifier or operator`});if(_r(s,t)&&!l)throw y({token:r.token,errorMessage:`Expected "comptime" for compile-time known value binding:
10632
10650
  ${A(s)}`});if(pr(s,t)&&l)throw y({token:r.token,errorMessage:`Unexpected "comptime" for ${A(s)} which can only be used at runtime.`});let c=r.token.value;if(!l&&G(s)&&Pn(s))throw y({token:r.token,errorMessage:`Runtime variables with generic function types are not allowed:
10633
10651
  ${A(s)}
10634
10652
 
10635
10653
  Generic functions must be compile-time known to enable monomorphization. Consider using:
10636
- comptime(${c}) : ${A(s)}`});let{env:_}=me({env:t,variable:{name:c,type:s,isCompileTimeOnly:l,value:l?[K(s,{variableName:c,env:t,context:n})]:void 0,token:r.token,initializedAtToken:void 0,consumedAtToken:void 0,isReassignable:!0,isOwningTheRcValue:Le(s),isImplicit:u}});return t=_,r.$={env:t,type:s,pathCollection:[[c]]},e.$={env:t,type:H.type,value:H,pathCollection:[]},{expr:e,variableExpr:r,variableName:c}}function ts({expr:e,env:t,context:n,throwErrorOnUndefined:r}){let i=e.token.value;if(i==="Type"){let o=ee(tt());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Module"){let o=ee(gn(1));return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Trait"){let o=ee(gn(1));return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="unit"){let o=ee(xn());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="comptime_int"){let o=ee(Or());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="comptime_float"){let o=ee(Li());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="comptime_string"){let o=ee(xt());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="bool"){let o=ee(Je());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="usize"){let o=ee(gt());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="isize"){let o=ee(Ai());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u8"){let o=ee(Ii());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i8"){let o=ee(Si());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u16"){let o=ee(Ni());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i16"){let o=ee(Vi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u32"){let o=ee(xi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i32"){let o=ee(Rr());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u64"){let o=ee(Di());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i64"){let o=ee(Mi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="f32"){let o=ee(Oi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="f64"){let o=ee(Pr());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="char"){let o=ee(Tu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="short"){let o=ee(Eu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="ushort"){let o=ee($u());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="int"){let o=ee(Cu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="uint"){let o=ee(bu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="long"){let o=ee(ku());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="ulong"){let o=ee(wu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="longlong"){let o=ee(Fu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="ulonglong"){let o=ee(Lu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="longdouble"){let o=ee(Au());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="void"){let o=ee(Iu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Expr"){let o=ee(_n());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Self"&&n.SelfType){let o=ee(n.SelfType);return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="SelfTrait"&&n.SelfTraitType){let o=ee(n.SelfTraitType);return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="SelfModule"&&n.SelfModuleType){let o=ee(n.SelfModuleType);return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else{let o=X(t,i);if(o.length){let a=o[o.length-1];if(!a.initializedAtToken&&r&&!G(a.type)&&!O(a.value?.[0]))throw y({token:e.token,errorMessage:`Variable "${i}" is not initialized`});let s=a.type.isExtern==="c"&&de(a.value?.[0])&&!(G(a.type)||He(a.type))?void 0:a.value?.[0];if(e.$={env:t,type:a.type,value:s,originType:a.type,variableName:a.name,pathCollection:[[a.name]],sourceVariable:a},n.isEvaluatingFunctionBodyOrAsyncBlock&&n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&n.capturedVariables&&n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv){let l=n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv.frames.length;a.frameLevel<l&&ao(a.name,a.frameLevel,"own",e.token,n)}if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="async-block"){let l=n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv.frames.length;a.frameLevel<l&&ao(a.name,a.frameLevel,"own",e.token,n)}return e}else throw y({token:e.token,errorMessage:`Variable "${i}" not found.`})}}function Pl(e,t){let n=uu(t),r=`Right-hand side contains "${n}" from function.`;throw F(e)&&E(e,I.cond)?r=`Cannot assign "cond" expression to variable when all cases contain "${n}" statements. Consider using the "cond" result directly without assignment, or ensure at least one case doesn't return.`:F(e)&&E(e,I.match)?r=`Cannot assign "match" expression to variable when all cases contain "${n}" statements. Consider using the "match" result directly without assignment, or ensure at least one case doesn't return.`:F(e)&&E(e,I.begin)&&(r=`Cannot assign "begin" expression to variable when it contains "${n}" statement.`),y({token:e.token,errorMessage:r})}function mh(e,t){if(ke(e)&&de(e.length)){let n=e.length;if(n.variableName){let r=X(t,n.variableName);if(r.length>0){let i=r[r.length-1];if(i.value?.[0]&&!de(i.value[0]))return mr(e.childType,i.value[0])}}}return e}function Bd({expr:e,env:t,context:n}){if(!E(e,"=",2))throw y({token:e.token,errorMessage:'Expected "=" for assignment.'});let r=e.args[0],i=e.args[1];if(z(r)||F(r)&&E(r,":",2)){let o;if(z(r)){let d=ts({expr:r,env:t,context:{...n},throwErrorOnUndefined:!1});if(!d.$)throw y({token:r.token,errorMessage:`Failed to evaluate left-hand side of assignment: ${w(r)}`});t=d.$.env,r=d,o=r.token.value}else{let{expr:d,variableExpr:v,variableName:T}=es({expr:r,env:t,context:{...n}});d.$?.env&&(t=d.$?.env),r=v,o=T}let a=X(t,o);if(!a.length)throw y({token:r.token,errorMessage:`Variable ${o} not found in the environment`});let s=a[a.length-1];if(!s.isReassignable)throw y({token:r.token,errorMessage:`Cannot reassign "${o}".
10654
+ comptime(${c}) : ${A(s)}`});let{env:_}=me({env:t,variable:{name:c,type:s,isCompileTimeOnly:l,value:l?[K(s,{variableName:c,env:t,context:n})]:void 0,token:r.token,initializedAtToken:void 0,consumedAtToken:void 0,isReassignable:!0,isOwningTheRcValue:Le(s),isImplicit:u}});return t=_,r.$={env:t,type:s,pathCollection:[[c]]},e.$={env:t,type:H.type,value:H,pathCollection:[]},{expr:e,variableExpr:r,variableName:c}}function ts({expr:e,env:t,context:n,throwErrorOnUndefined:r}){let i=e.token.value;if(i==="Type"){let o=ee(tt());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Module"){let o=ee(gn(1));return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Trait"){let o=ee(gn(1));return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="unit"){let o=ee(xn());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="comptime_int"){let o=ee(Or());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="comptime_float"){let o=ee(Li());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="comptime_string"){let o=ee(xt());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="bool"){let o=ee(Je());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="usize"){let o=ee(gt());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="isize"){let o=ee(Ai());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u8"){let o=ee(Ii());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i8"){let o=ee(Si());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u16"){let o=ee(Ni());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i16"){let o=ee(Vi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u32"){let o=ee(xi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i32"){let o=ee(Rr());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="u64"){let o=ee(Di());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="i64"){let o=ee(Mi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="f32"){let o=ee(Oi());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="f64"){let o=ee(Pr());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="char"){let o=ee(Tu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="short"){let o=ee(Eu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="ushort"){let o=ee($u());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="int"){let o=ee(Cu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="uint"){let o=ee(bu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="long"){let o=ee(ku());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="ulong"){let o=ee(wu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="longlong"){let o=ee(Fu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="ulonglong"){let o=ee(Lu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="longdouble"){let o=ee(Au());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="void"){let o=ee(Iu());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Expr"){let o=ee(_n());return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="Self"&&n.SelfType){let o=ee(n.SelfType);return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="SelfTrait"&&n.SelfTraitType){let o=ee(n.SelfTraitType);return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else if(i==="SelfModule"&&n.SelfModuleType){let o=ee(n.SelfModuleType);return e.$={env:t,type:o.type,value:o,pathCollection:[]},e}else{let o=X(t,i);if(o.length){let a=o[o.length-1];if(!a.initializedAtToken&&r&&!G(a.type)&&!O(a.value?.[0]))throw y({token:e.token,errorMessage:`Variable "${i}" is not initialized`});let s=a.type.isExtern==="c"&&de(a.value?.[0])&&!(G(a.type)||He(a.type))?void 0:a.value?.[0];if(e.$={env:t,type:a.type,value:s,originType:a.type,variableName:a.name,pathCollection:[[a.name]],sourceVariable:a},n.isEvaluatingFunctionBodyOrAsyncBlock&&n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&n.capturedVariables&&n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv){let l=n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv.frames.length;a.frameLevel<l&&ao(a.name,a.frameLevel,"own",e.token,n)}if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="async-block"){let l=n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv.frames.length;a.frameLevel<l&&ao(a.name,a.frameLevel,"own",e.token,n)}return e}else throw y({token:e.token,errorMessage:`Variable "${i}" not found.`})}}function Pl(e,t){let n=uu(t),r=`Right-hand side contains "${n}" from function.`;throw F(e)&&E(e,I.cond)?r=`Cannot assign "cond" expression to variable when all cases contain "${n}" statements. Consider using the "cond" result directly without assignment, or ensure at least one case doesn't return.`:F(e)&&E(e,I.match)?r=`Cannot assign "match" expression to variable when all cases contain "${n}" statements. Consider using the "match" result directly without assignment, or ensure at least one case doesn't return.`:F(e)&&E(e,I.begin)&&(r=`Cannot assign "begin" expression to variable when it contains "${n}" statement.`),y({token:e.token,errorMessage:r})}function yh(e,t){if(ke(e)&&de(e.length)){let n=e.length;if(n.variableName){let r=X(t,n.variableName);if(r.length>0){let i=r[r.length-1];if(i.value?.[0]&&!de(i.value[0]))return mr(e.childType,i.value[0])}}}return e}function Gd({expr:e,env:t,context:n}){if(!E(e,"=",2))throw y({token:e.token,errorMessage:'Expected "=" for assignment.'});let r=e.args[0],i=e.args[1];if(z(r)||F(r)&&E(r,":",2)){let o;if(z(r)){let d=ts({expr:r,env:t,context:{...n},throwErrorOnUndefined:!1});if(!d.$)throw y({token:r.token,errorMessage:`Failed to evaluate left-hand side of assignment: ${w(r)}`});t=d.$.env,r=d,o=r.token.value}else{let{expr:d,variableExpr:v,variableName:T}=es({expr:r,env:t,context:{...n}});d.$?.env&&(t=d.$?.env),r=v,o=T}let a=X(t,o);if(!a.length)throw y({token:r.token,errorMessage:`Variable ${o} not found in the environment`});let s=a[a.length-1];if(!s.isReassignable)throw y({token:r.token,errorMessage:`Cannot reassign "${o}".
10637
10655
  You can mutate fields (e.g., ${o}.field = value) but cannot reassign itself.`});if(i=S({expr:i,env:t,context:{...n,expectedType:{type:s.type,env:t},isInsideGivenHandler:s.isImplicit?!0:n.isInsideGivenHandler}}),!i.$)throw y({token:i.token,errorMessage:`Failed to evaluate right-hand side of assignment: ${w(i)}`});t=i.$.env,ii(i,t),Br(i),qt(i,n),t=i.$.env,nt(i.$?.controlFlow)&&Pl(i,i.$.controlFlow);let l=i.$?.type;if(!l)try{let{expr:d,type:v,env:T}=xr({expr:i,type:s.type,env:t,context:{...n}});i=d,l=v,t=T}catch(d){throw y({token:i.token,errorMessage:`(evaluateAssignment) Failed to synthesize type for expression: ${w(i)}
10638
- ${d}`})}if(s.isCompileTimeOnly||(l=yt({type:l,expectedType:s.type,expr:i,env:t})),!Y({type:s.type,env:t},{type:l,env:t}))if(Pi(s.type))try{let{expr:d,type:v,env:T}=xr({expr:i,type:s.type,env:t,context:{...n}});if(Y({type:s.type,env:T},{type:v,env:T})){i=d,l=v,t=T;let $=mh(s.type,t);t=Be(t,s,{...s,type:$})}else throw y({token:r.token,errorMessage:`Incompatible types:
10656
+ ${d}`})}if(s.isCompileTimeOnly||(l=yt({type:l,expectedType:s.type,expr:i,env:t})),!Y({type:s.type,env:t},{type:l,env:t}))if(Pi(s.type))try{let{expr:d,type:v,env:T}=xr({expr:i,type:s.type,env:t,context:{...n}});if(Y({type:s.type,env:T},{type:v,env:T})){i=d,l=v,t=T;let $=yh(s.type,t);t=Be(t,s,{...s,type:$})}else throw y({token:r.token,errorMessage:`Incompatible types:
10639
10657
  - Expected: ${A(s.type)}
10640
10658
  - Given : ${A(l)}`})}catch{throw y({token:r.token,errorMessage:`Incompatible types:
10641
10659
  - Expected: ${A(s.type)}
@@ -10646,35 +10664,35 @@ Impl(...) uses static dispatch and the concrete type is fixed at first assignmen
10646
10664
  Consider using Dyn(...) for dynamic dispatch if you need to reassign to different implementations.`},{token:s.initializedAtToken??s.token,errorMessage:"First assigned here:"}]);if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&n.capturedVariables&&n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv){let C=n.isEvaluatingFunctionBodyOrAsyncBlock.evaluationEnv.frames.length;s.frameLevel<C&&ao(s.name,s.frameLevel,"own",r.token,n)}let d=s.isCompileTimeOnly&&_?an(_):void 0,v=ri(t.modulePath,o),T=Oo(i,t,t.modulePath),$=T;T?.consumedAtToken&&($=void 0),t=Be(t,s,{...s,id:v,value:d?[d]:void 0,type:p,isOwningTheRcValue:Le(p),isOwningTheSameRcValueAs:$}),f=!0}else{if(n.isEvaluatingLoopBody&&s.frameLevel<n.isEvaluatingLoopBody.env.frames.length)throw lt([{token:r.token,errorMessage:"Cannot initialize a variable that is defined outside the while loop."},{token:s.token,errorMessage:"Defined here:"}]);if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&s.frameLevel<n.isEvaluatingFunctionBodyOrAsyncBlock.type.env.frames.length)throw lt([{token:r.token,errorMessage:"Cannot initialize a variable that is defined outside the function body."},{token:s.token,errorMessage:"Defined here:"}]);let d=s.isCompileTimeOnly&&_?an(_):void 0,v=Oo(i,t,t.modulePath),T=v;v?.consumedAtToken&&(T=void 0),t=Be(t,s,{...s,initializedAtToken:r.token,value:d?[d]:void 0,type:p,isOwningTheRcValue:Le(p),isOwningTheSameRcValueAs:T})}let g=X(t,o),h=g[g.length-1];return r.$={env:t,type:h.type,value:h.isCompileTimeOnly?_:void 0,pathCollection:[[o]]},f?(e.$={env:t,value:s.value?.[0],type:s.type,pathCollection:[],isCompileTimeOnlyAssignment:s.isCompileTimeOnly},Ge(e,!0,m?.frameLevel===t.frames.length-1?m:void 0)):e.$={env:t,value:H,type:H.type,pathCollection:[],isCompileTimeOnlyAssignment:s.isCompileTimeOnly},e}else{let o=S({expr:r,env:t,context:{...n,expectedType:void 0,isLhsOfAssignment:!0}});if(!o.$)throw y({token:r.token,errorMessage:`Failed to evaluate left-hand side of assignment: ${w(r)}`});if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&o.$.pathCollection){for(let p of o.$.pathCollection)if(p.length>0){let f=p[0];if(typeof f=="string"){let m=X(t,f);if(m.length>0){let g=m[m.length-1];ao(f,g.frameLevel,"write",r.token,n)}}}}let a=o.$.type;if(i=S({expr:i,env:t,context:{...n,expectedType:{type:a,env:t}}}),!i.$)throw y({token:i.token,errorMessage:`Failed to evaluate right-hand side of assignment: ${w(i)}`});t=i.$.env,ii(i,t),Br(i),qt(i,n),t=i.$.env;let s=i.$?.type;if(!s)try{let{expr:p,type:f,env:m}=xr({expr:i,type:a,env:t,context:{...n}});i=p,s=f,t=m}catch(p){throw y({token:i.token,errorMessage:`(evaluateAssignment) Failed to synthesize type for expression: ${w(i)}
10647
10665
  ${p}`})}if(!Y({type:a,env:t},{type:s,env:t}))throw y({token:r.token,errorMessage:`Incompatible types:
10648
10666
  - Expected: ${A(a)}
10649
- - Given : ${A(s)}`});let l=!1;if(o.$.pathCollection&&o.$.pathCollection.length>0){let p=o.$.pathCollection[0];if(p&&p.length>=2){let f=p[0],m=p[1],g=X(t,f);if(g.length>0){let h=g[g.length-1];if(h.isCompileTimeOnly&&h.value?.[0]){let d=h.value[0];if(i.$?.value&&(l=!0),Cn(d)||hn(d)){let v=h.type,T=v.fields.findIndex($=>$.label===m);if(T>=0&&i.$?.value)if(ce(h.type)&&h.type.isReferenceSemantics){let $=[...d.fields];$[T]=i.$.value;let C=Bn(h.type,$),L=fn(t,b=>b.isCompileTimeOnly&&b.value?.[0]===d);for(let b of L)t=Be(t,b,{...b,value:[C]})}else{let $=[...d.fields];$[T]=i.$.value;let C;Cn(d)?C=Bn(v,$):C=_a(v,$),t=Be(t,h,{...h,value:[C]})}}else if(Un(d)){let v=parseInt(m,10);if(!isNaN(v)&&v>=0&&v<d.elements.length&&i.$?.value){let T=[...d.elements];T[v]=i.$.value;let $=h.type,C=Mr($,T);t=Be(t,h,{...h,value:[C]})}}else if(It(d)){let v=h.type,T=v.variants.find($=>$.name===d.variantName);if(T){let $=(T.fields??[]).findIndex(C=>C.label===m);if($>=0&&i.$?.value){let C=[...d.fields];C[$]=i.$.value;let L=Jr(v,d.variantName,C);t=Be(t,h,{...h,value:[L]})}}}}}}}let u=o.$.ptrTargetValue,c=o.$.ptrTargetIndex??0;if(u&&i.$?.value){let p=u[0];Un(p)?p.elements[c]=i.$.value:u[0]=i.$.value,l=!0}let _=o.$.arrayElementRef;return _&&i.$?.value&&(_.arrayValue.elements[_.index]=i.$.value,l=!0),!l&&o.$?.value!==void 0&&i.$?.value!==void 0&&(l=!0),e.$={env:t,value:o.$.value,type:o.$.type,pathCollection:[],isCompileTimeOnlyAssignment:l},l||Ge(e,!0),e}}function Gd({expr:e,env:t,context:n}){if(!E(e,I.c_include))throw y({token:e.token,errorMessage:`Expected c_include, got ${e.tag}`});let r,i=e.args;if(e.args[0]&&z(e.args[0])){let a=e.args[0];i=e.args.slice(1);let s=S({expr:a,env:t,context:{...n}});if(!s.$||!s.$.value)throw y({token:a.token,errorMessage:`Failed to evaluate C header file argument: ${w(a)}`});t=s.$.env;let l=s.$.value;if(!Ve(l))throw y({token:a.token,errorMessage:`Expected string for C header file argument, got ${w(a)}`});r=l.value}if(!r)throw y({token:e.token,errorMessage:`Expected C header file as first argument to c_include, such as:
10667
+ - Given : ${A(s)}`});let l=!1;if(o.$.pathCollection&&o.$.pathCollection.length>0){let p=o.$.pathCollection[0];if(p&&p.length>=2){let f=p[0],m=p[1],g=X(t,f);if(g.length>0){let h=g[g.length-1];if(h.isCompileTimeOnly&&h.value?.[0]){let d=h.value[0];if(i.$?.value&&(l=!0),Cn(d)||hn(d)){let v=h.type,T=v.fields.findIndex($=>$.label===m);if(T>=0&&i.$?.value)if(ce(h.type)&&h.type.isReferenceSemantics){let $=[...d.fields];$[T]=i.$.value;let C=Bn(h.type,$),L=fn(t,b=>b.isCompileTimeOnly&&b.value?.[0]===d);for(let b of L)t=Be(t,b,{...b,value:[C]})}else{let $=[...d.fields];$[T]=i.$.value;let C;Cn(d)?C=Bn(v,$):C=_a(v,$),t=Be(t,h,{...h,value:[C]})}}else if(Un(d)){let v=parseInt(m,10);if(!isNaN(v)&&v>=0&&v<d.elements.length&&i.$?.value){let T=[...d.elements];T[v]=i.$.value;let $=h.type,C=Mr($,T);t=Be(t,h,{...h,value:[C]})}}else if(It(d)){let v=h.type,T=v.variants.find($=>$.name===d.variantName);if(T){let $=(T.fields??[]).findIndex(C=>C.label===m);if($>=0&&i.$?.value){let C=[...d.fields];C[$]=i.$.value;let L=Jr(v,d.variantName,C);t=Be(t,h,{...h,value:[L]})}}}}}}}let u=o.$.ptrTargetValue,c=o.$.ptrTargetIndex??0;if(u&&i.$?.value){let p=u[0];Un(p)?p.elements[c]=i.$.value:u[0]=i.$.value,l=!0}let _=o.$.arrayElementRef;return _&&i.$?.value&&(_.arrayValue.elements[_.index]=i.$.value,l=!0),!l&&o.$?.value!==void 0&&i.$?.value!==void 0&&(l=!0),e.$={env:t,value:o.$.value,type:o.$.type,pathCollection:[],isCompileTimeOnlyAssignment:l},l||Ge(e,!0),e}}function Wd({expr:e,env:t,context:n}){if(!E(e,I.c_include))throw y({token:e.token,errorMessage:`Expected c_include, got ${e.tag}`});let r,i=e.args;if(e.args[0]&&z(e.args[0])){let a=e.args[0];i=e.args.slice(1);let s=S({expr:a,env:t,context:{...n}});if(!s.$||!s.$.value)throw y({token:a.token,errorMessage:`Failed to evaluate C header file argument: ${w(a)}`});t=s.$.env;let l=s.$.value;if(!Ve(l))throw y({token:a.token,errorMessage:`Expected string for C header file argument, got ${w(a)}`});r=l.value}if(!r)throw y({token:e.token,errorMessage:`Expected C header file as first argument to c_include, such as:
10650
10668
 
10651
- c_include "<stdio.h>" ...;`});let o=[];for(let a=0;a<i.length;a++){let s=i[a],{field:l,env:u}=na({expr:s,env:t,moduleFieldIndex:a,context:{...n,SelfType:void 0},isForEvaluatingModuleType:!1});if(o.find(p=>p.label===l.label))throw y({token:F(s)?s.args[0]?.token??s.token:s.token,errorMessage:`Duplicate label "${l.label}" in module`});if(He(l.type)||G(l.type)?l.type={...l.type,isExtern:"c",cInclude:r,externName:l.label}:l.type={...l.type,isExtern:"c",cInclude:r},l.assignedValue&&O(l.assignedValue)&&(ce(l.assignedValue.value)||ge(l.assignedValue.value)||it(l.assignedValue.value))){let p=l.assignedValue.value;p.isExtern="c",p.cInclude=r,p.externName=l.label}o.push(l),t=u;let{env:_}=me({env:t,variable:{name:l.label,type:l.type,value:[l.assignedValue??K(l.type,{variableName:l.label,env:t,context:n})],isCompileTimeOnly:!0,token:l.exprs.expr.token,initializedAtToken:l.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});t=_}return e.$={env:t,value:H,type:H.type,pathCollection:[]},e.func.$={env:t,value:H,type:H.type,pathCollection:[]},e}function Wd({expr:e,env:t,context:n}){if(!E(e,I.cond))throw y({token:e.token,errorMessage:`Expected "cond", got ${e.tag}`});let r=e.args;if(r.length===0)throw y({token:e.token,errorMessage:`Expected at least one statement in "cond", got ${r.length}`});let i=[];for(let c=0;c<r.length;c++){let _=r[c];if(!F(_)||!E(_,"=>",2))throw y({token:_.token,errorMessage:`Expected => for cond statement, got ${_.tag}`});let p=_.args[0],f=_.args[1],m=t;i.push({condExpr:p,caseBodyExpr:f,caseEnv:m})}let o=[];for(let c=0;c<i.length;c++){let{condExpr:_,caseBodyExpr:p,caseEnv:f}=i[c],m=z(_)?S({expr:_,env:f,context:{...n,expectedType:{type:Je(),env:f}}}):ht({expr:_,env:f,context:{...n,expectedType:{type:Je(),env:f}},variablesToAdd:[]});if(!m.$)throw y({token:m.token,errorMessage:`Failed to evaluate condition expression: ${w(m)}`});if(!cn(m.$.type))throw y({token:m.token,errorMessage:`Expected bool for cond statement, got ${w(m)} of type ${A(m.$.type)}`});let g=m.$.value,h=m.$.env;if(c===i.length-1&&!(Re(g)&&g.value===!0))throw y({token:m.token,errorMessage:'Expect the last condition to be compile-time known "true".'});if(o.push({condExpr:m,caseBodyExpr:p,caseEnv:h,condValue:g}),Re(g)&&g.value===!0)break}let a=-1;for(let c=0;c<o.length;c++){let{condValue:_}=o[c];if(Re(_)&&_.value===!0&&o.slice(0,c).every(({condValue:p})=>Re(p)&&p.value===!1)){a=c;break}}let s=[],l=[],u;if(a!==-1){let{caseBodyExpr:c,caseEnv:_,condExpr:p}=o[a];p.$&&(p.$.caseExecuted=!0);let f=ht({expr:c,env:_,context:{...n},variablesToAdd:[]});if(nt(f.$?.controlFlow))return e.$={env:f.$.env,type:n.expectedType?.type??f.$.type,value:f.$.value,pathCollection:f.$.pathCollection,controlFlow:f.$.controlFlow},e;{if(!f.$?.type)throw y({token:f.token,errorMessage:`Expected type for cond statement, got ${w(f)}`});s.push(f),l.push(f.$.value),u={type:f.$.type,env:f.$.env},t=f.$.env;let m;return m=l[0],e.$={env:t,type:n.expectedType?.type??u.type,value:m,pathCollection:[],variableName:f.$.variableName},f.$.variableName||Ge(e,!0),e}}else{let c=!1,_=[],p=[];for(let{condExpr:m,condValue:g,caseBodyExpr:h,caseEnv:d}of o){if(Re(g)&&g.value===!1)continue;m.$&&(m.$.caseExecuted=!0);let v=ht({expr:h,env:d,context:{...n,isExecuting:!1},variablesToAdd:[]});if(nt(v.$?.controlFlow)){_.push(v.$.controlFlow),et(v.$.controlFlow,"return")&&p.push(v);continue}else c=!0;if(!v.$?.type)throw y({token:v.token,errorMessage:`Expected type for cond statement, got ${w(v)}`});if(s.push(v),l.push(v.$.value),n.expectedType&&!Y(n.expectedType,{type:v.$.type,env:v.$.env}))throw y({token:v.token,errorMessage:`Incompatible type with expected type:
10669
+ c_include "<stdio.h>" ...;`});let o=[];for(let a=0;a<i.length;a++){let s=i[a],{field:l,env:u}=na({expr:s,env:t,moduleFieldIndex:a,context:{...n,SelfType:void 0},isForEvaluatingModuleType:!1});if(o.find(p=>p.label===l.label))throw y({token:F(s)?s.args[0]?.token??s.token:s.token,errorMessage:`Duplicate label "${l.label}" in module`});if(He(l.type)||G(l.type)?l.type={...l.type,isExtern:"c",cInclude:r,externName:l.label}:l.type={...l.type,isExtern:"c",cInclude:r},l.assignedValue&&O(l.assignedValue)&&(ce(l.assignedValue.value)||ge(l.assignedValue.value)||it(l.assignedValue.value))){let p=l.assignedValue.value;p.isExtern="c",p.cInclude=r,p.externName=l.label}o.push(l),t=u;let{env:_}=me({env:t,variable:{name:l.label,type:l.type,value:[l.assignedValue??K(l.type,{variableName:l.label,env:t,context:n})],isCompileTimeOnly:!0,token:l.exprs.expr.token,initializedAtToken:l.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});t=_}return e.$={env:t,value:H,type:H.type,pathCollection:[]},e.func.$={env:t,value:H,type:H.type,pathCollection:[]},e}function qd({expr:e,env:t,context:n}){if(!E(e,I.cond))throw y({token:e.token,errorMessage:`Expected "cond", got ${e.tag}`});let r=e.args;if(r.length===0)throw y({token:e.token,errorMessage:`Expected at least one statement in "cond", got ${r.length}`});let i=[];for(let c=0;c<r.length;c++){let _=r[c];if(!F(_)||!E(_,"=>",2))throw y({token:_.token,errorMessage:`Expected => for cond statement, got ${_.tag}`});let p=_.args[0],f=_.args[1],m=t;i.push({condExpr:p,caseBodyExpr:f,caseEnv:m})}let o=[];for(let c=0;c<i.length;c++){let{condExpr:_,caseBodyExpr:p,caseEnv:f}=i[c],m=z(_)?S({expr:_,env:f,context:{...n,expectedType:{type:Je(),env:f}}}):ht({expr:_,env:f,context:{...n,expectedType:{type:Je(),env:f}},variablesToAdd:[]});if(!m.$)throw y({token:m.token,errorMessage:`Failed to evaluate condition expression: ${w(m)}`});if(!cn(m.$.type))throw y({token:m.token,errorMessage:`Expected bool for cond statement, got ${w(m)} of type ${A(m.$.type)}`});let g=m.$.value,h=m.$.env;if(c===i.length-1&&!(Re(g)&&g.value===!0))throw y({token:m.token,errorMessage:'Expect the last condition to be compile-time known "true".'});if(o.push({condExpr:m,caseBodyExpr:p,caseEnv:h,condValue:g}),Re(g)&&g.value===!0)break}let a=-1;for(let c=0;c<o.length;c++){let{condValue:_}=o[c];if(Re(_)&&_.value===!0&&o.slice(0,c).every(({condValue:p})=>Re(p)&&p.value===!1)){a=c;break}}let s=[],l=[],u;if(a!==-1){let{caseBodyExpr:c,caseEnv:_,condExpr:p}=o[a];p.$&&(p.$.caseExecuted=!0);let f=ht({expr:c,env:_,context:{...n},variablesToAdd:[]});if(nt(f.$?.controlFlow))return e.$={env:f.$.env,type:n.expectedType?.type??f.$.type,value:f.$.value,pathCollection:f.$.pathCollection,controlFlow:f.$.controlFlow},e;{if(!f.$?.type)throw y({token:f.token,errorMessage:`Expected type for cond statement, got ${w(f)}`});s.push(f),l.push(f.$.value),u={type:f.$.type,env:f.$.env},t=f.$.env;let m;return m=l[0],e.$={env:t,type:n.expectedType?.type??u.type,value:m,pathCollection:[],variableName:f.$.variableName},f.$.variableName||Ge(e,!0),e}}else{let c=!1,_=[],p=[];for(let{condExpr:m,condValue:g,caseBodyExpr:h,caseEnv:d}of o){if(Re(g)&&g.value===!1)continue;m.$&&(m.$.caseExecuted=!0);let v=ht({expr:h,env:d,context:{...n,isExecuting:!1},variablesToAdd:[]});if(nt(v.$?.controlFlow)){_.push(v.$.controlFlow),et(v.$.controlFlow,"return")&&p.push(v);continue}else c=!0;if(!v.$?.type)throw y({token:v.token,errorMessage:`Expected type for cond statement, got ${w(v)}`});if(s.push(v),l.push(v.$.value),n.expectedType&&!Y(n.expectedType,{type:v.$.type,env:v.$.env}))throw y({token:v.token,errorMessage:`Incompatible type with expected type:
10652
10670
  - Expected: ${A(n.expectedType.type)}
10653
10671
  - Actual : ${A(v.$.type)}`});if(!nt(v.$.controlFlow)){if(!u)u={type:v.$.type,env:v.$.env};else if(!Y({type:u.type,env:u.env},{type:v.$.type,env:v.$.env}))if(Y({type:yt({type:u.type,expectedType:void 0,expr:void 0,env:u.env}),env:u.env},{type:v.$.type,env:v.$.env}))u={type:v.$.type,env:v.$.env};else throw y({token:v.token,errorMessage:`Incompatible types:
10654
10672
  - Previous: ${A(u.type)}
10655
- - Current : ${A(v.$.type)}`})}}let f=_.length>0?So(_):void 0;if(c||!nt(f)){if(c&&!u)throw y({token:e.token,errorMessage:"Failed to determine the type of value from the cond."});u||(u={type:H.type,env:t}),t=Gi(t,s.filter(g=>g.$&&!et(g.$.controlFlow,"return")&&!et(g.$.controlFlow,"escape")));let m;return l.some(g=>g===void 0)?m=void 0:m=K(u.type,{env:t,context:n}),e.$={env:t,type:n.expectedType?.type??u.type,value:m,pathCollection:[]},Ge(e,!0),e}else{if(_.length===0)throw y({token:e.token,errorMessage:"No control flows found but expected some."});if(et(f,"return")){if(!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:e.token,errorMessage:"All cases in cond are returning from function, but not evaluating in function body."});let m;if(p.length>0&&p[0].$?m=p[0].$.type:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?m=n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:n.expectedType&&(m=n.expectedType.type),!m)throw y({token:e.token,errorMessage:"Failed to determine the return type for cond statement."});e.$={env:t,type:m,value:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&Ao(n.isEvaluatingFunctionBodyOrAsyncBlock.type)?K(m,{env:t,context:n}):void 0,pathCollection:[],controlFlow:f}}else if(et(f,"escape")){if(!n.enclosingFunctionReturnType)throw y({token:e.token,errorMessage:'All cases in cond use "escape", but not inside a function with an enclosing function.'});let m=n.enclosingFunctionReturnType;e.$={env:t,type:m,value:void 0,pathCollection:[],controlFlow:f}}else if(et(f,"break")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in cond are breaking from loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:f}}else if(et(f,"continue")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in cond are continuing loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:f}}return e}}}function qd({expr:e,env:t,context:n}){let r=n.enclosingFunctionReturnType;if(!r)throw y({token:e.func.token,errorMessage:"`escape` can only be used inside a function that has an enclosing function."});if(!n.isInsideGivenHandler)throw y({token:e.func.token,errorMessage:"`escape` can only be used inside a `given` handler definition."});let i=e.args[0];if(!i)throw y({token:e.func.token,errorMessage:"`escape` requires exactly one argument."});let o=Kr({expr:i,env:t,context:{...n,expectedType:{type:r,env:t}}});if(!o.$)throw y({token:i.token,errorMessage:"Failed to evaluate the argument of `escape`."});if(!x(r)&&!Y({type:r,env:t},{type:o.$.type,env:t}))throw y({token:i.token,errorMessage:`Incompatible type for \`escape\` argument:
10673
+ - Current : ${A(v.$.type)}`})}}let f=_.length>0?So(_):void 0;if(c||!nt(f)){if(c&&!u)throw y({token:e.token,errorMessage:"Failed to determine the type of value from the cond."});u||(u={type:H.type,env:t}),t=Gi(t,s.filter(g=>g.$&&!et(g.$.controlFlow,"return")&&!et(g.$.controlFlow,"escape")));let m;return l.some(g=>g===void 0)?m=void 0:m=K(u.type,{env:t,context:n}),e.$={env:t,type:n.expectedType?.type??u.type,value:m,pathCollection:[]},Ge(e,!0),e}else{if(_.length===0)throw y({token:e.token,errorMessage:"No control flows found but expected some."});if(et(f,"return")){if(!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:e.token,errorMessage:"All cases in cond are returning from function, but not evaluating in function body."});let m;if(p.length>0&&p[0].$?m=p[0].$.type:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?m=n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:n.expectedType&&(m=n.expectedType.type),!m)throw y({token:e.token,errorMessage:"Failed to determine the return type for cond statement."});e.$={env:t,type:m,value:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&Ao(n.isEvaluatingFunctionBodyOrAsyncBlock.type)?K(m,{env:t,context:n}):void 0,pathCollection:[],controlFlow:f}}else if(et(f,"escape")){if(!n.enclosingFunctionReturnType)throw y({token:e.token,errorMessage:'All cases in cond use "escape", but not inside a function with an enclosing function.'});let m=n.enclosingFunctionReturnType;e.$={env:t,type:m,value:void 0,pathCollection:[],controlFlow:f}}else if(et(f,"break")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in cond are breaking from loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:f}}else if(et(f,"continue")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in cond are continuing loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:f}}return e}}}function Yd({expr:e,env:t,context:n}){let r=n.enclosingFunctionReturnType;if(!r)throw y({token:e.func.token,errorMessage:"`escape` can only be used inside a function that has an enclosing function."});if(!n.isInsideGivenHandler)throw y({token:e.func.token,errorMessage:"`escape` can only be used inside a `given` handler definition."});let i=e.args[0];if(!i)throw y({token:e.func.token,errorMessage:"`escape` requires exactly one argument."});let o=Kr({expr:i,env:t,context:{...n,expectedType:{type:r,env:t}}});if(!o.$)throw y({token:i.token,errorMessage:"Failed to evaluate the argument of `escape`."});if(!x(r)&&!Y({type:r,env:t},{type:o.$.type,env:t}))throw y({token:i.token,errorMessage:`Incompatible type for \`escape\` argument:
10656
10674
  - Expected (enclosing function return type): ${A(r)}
10657
- - Got: ${A(o.$.type)}`});return e.args[0]=o,e.$={...e.$,env:t,type:o.$.type,value:void 0,pathCollection:[],controlFlow:zr("escape")},e}function Yd({expr:e,env:t,context:n}){if(!E(e,I.extern))throw y({token:e.token,errorMessage:`Expected extern, got ${e.tag}`});let r="yo",i=e.args;if(e.args[0]&&z(e.args[0])){let a=e.args[0];i=e.args.slice(1);let s=S({expr:a,env:t,context:{...n}});if(!s.$||!s.$.value)throw y({token:a.token,errorMessage:`Failed to evaluate language argument: ${w(a)}`});t=s.$.env;let l=s.$.value;if(!Ve(l))throw y({token:a.token,errorMessage:`Expected string for language argument, got ${w(a)}`});if(l.value.toLocaleLowerCase()==="yo")r="yo";else if(l.value.toLocaleLowerCase()==="c")r="c";else throw y({token:a.token,errorMessage:`Unsupported language "${l.value}" for extern, expected "c" or "yo"`})}let o=[];for(let a=0;a<i.length;a++){let s=i[a],{field:l,env:u}=na({expr:s,env:t,moduleFieldIndex:a,context:{...n,SelfType:void 0},isForEvaluatingModuleType:!1});if(o.find(p=>p.label===l.label))throw y({token:F(s)?s.args[0]?.token??s.token:s.token,errorMessage:`Duplicate label "${l.label}" in module`});if(He(l.type)||G(l.type)?l.type={...l.type,isExtern:r,externName:l.label,...l.label==="__yo_io_async"?{ioBuiltin:"io_async"}:{},...l.label==="__yo_io_await"?{ioBuiltin:"io_await"}:{},...l.label==="__yo_io_state"?{ioBuiltin:"io_state"}:{},...l.label==="__yo_io_spawn"?{ioBuiltin:"io_spawn"}:{},...l.label==="__yo_join_handle_await"?{ioBuiltin:"join_handle_await"}:{}}:l.type={...l.type,isExtern:r},l.assignedValue&&O(l.assignedValue)&&(ce(l.assignedValue.value)||ge(l.assignedValue.value)||it(l.assignedValue.value))){let p=l.assignedValue.value;p.isExtern=r,p.externName=l.label}o.push(l),t=u;let{env:_}=me({env:t,variable:{name:l.label,type:l.type,value:[l.assignedValue??K(l.type,{variableName:l.label,env:t,context:n})],isCompileTimeOnly:!0,token:l.exprs.expr.token,initializedAtToken:l.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});t=_}return e.$={env:t,value:H,type:H.type,pathCollection:[]},e.func.$={env:t,value:H,type:H.type,pathCollection:[]},e}import{existsSync as fo}from"fs";import Zt from"path";import*as nr from"fs";import*as $i from"path";import*as Jd from"crypto";import{execSync as EB}from"child_process";import*as ra from"fs";import*as jd from"path";function yh(e){let t=[],n=e.split(`
10658
- `),r;for(let i of n){let o=i.trim();if(o===""||o.startsWith("#"))continue;if(o==="[[dependencies]]"){r&&r.name&&t.push(Hd(r)),r={};continue}if(r===void 0)continue;let a=o.indexOf("=");if(a===-1)continue;let s=o.slice(0,a).trim(),l=o.slice(a+1).trim();switch(l.length>=2&&l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),s){case"name":r.name=l;break;case"url":r.url=l;break;case"ref":r.ref=l;break;case"commit":r.commit=l;break;case"hash":r.hash=l;break}}return r&&r.name&&t.push(Hd(r)),{dependencies:t}}function Hd(e){return{name:e.name??"",url:e.url??"",ref:e.ref??"HEAD",commit:e.commit??"",hash:e.hash??""}}function Kd(e){let t=jd.join(e,"yo.lock");if(!ra.existsSync(t))return{dependencies:[]};let n=ra.readFileSync(t,"utf-8");return yh(n)}function Xd(e,t){return e.dependencies.find(n=>n.name===t)}import*as gh from"fs";import*as Ul from"os";import*as po from"path";function hh(){let e=process.env.YO_CACHE_DIR;if(e)return e;let t=process.env.XDG_CACHE_HOME;if(t)return po.join(t,"yo");if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??po.join(Ul.homedir(),"AppData","Local");return po.join(n,"yo","cache")}return po.join(Ul.homedir(),".cache","yo")}function Qd(){return po.join(hh(),"deps")}var bB={...process.env,GIT_TERMINAL_PROMPT:"0"};function vh(e){return Qd()}function Th(e){let t=Jd.createHash("sha256");return em(t,e,""),`sha256-${t.digest("hex")}`}function em(e,t,n){let r=n?$i.join(t,n):t,i=nr.readdirSync(r,{withFileTypes:!0});i.sort((o,a)=>Eh(o.name,a.name));for(let o of i){let a=n?`${n}/${o.name}`:o.name;if(o.isDirectory()){if(o.name.startsWith("."))continue;e.update(`dir:${a}
10659
- `),em(e,t,a)}else if(o.isFile()){if(o.name===zl)continue;e.update(`file:${a}
10660
- `);let s=nr.readFileSync($i.join(t,a));e.update(Ch(s))}}}function Eh(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n<r?-1:n>r?1:e<t?-1:e>t?1:0}var Zd=13,$h=10;function Ch(e){if(!e.includes(Zd))return e;let t=[];for(let n=0;n<e.length;n++)e[n]===Zd&&n+1<e.length&&e[n+1]===$h||t.push(e[n]);return Buffer.from(t)}var zl=".yo-content-hash";function bh(e,t){nr.writeFileSync($i.join(e,zl),t+`
10661
- `,"utf-8")}function kh(e,t,n){return $i.join(e,`${t}-${n.slice(0,12)}`)}function wh(e,t,n){let r=kh(e,t,n.commit);if(!nr.existsSync(r))return{status:"missing_path",cachedPath:r};if(!n.hash)return{status:"missing_hash",cachedPath:r};let i=$i.join(r,zl),o;try{o=nr.readFileSync(i,"utf-8").trim()}catch{o=Th(r),bh(r,o)}return o!==n.hash?{status:"hash_mismatch",cachedPath:r,actualHash:o}:{status:"ok",cachedPath:r,actualHash:o}}function Fh(e,t,n,r){return`Cached dependency "${e}" failed integrity check.
10675
+ - Got: ${A(o.$.type)}`});return e.args[0]=o,e.$={...e.$,env:t,type:o.$.type,value:void 0,pathCollection:[],controlFlow:zr("escape")},e}function Hd({expr:e,env:t,context:n}){if(!E(e,I.extern))throw y({token:e.token,errorMessage:`Expected extern, got ${e.tag}`});let r="yo",i=e.args;if(e.args[0]&&z(e.args[0])){let a=e.args[0];i=e.args.slice(1);let s=S({expr:a,env:t,context:{...n}});if(!s.$||!s.$.value)throw y({token:a.token,errorMessage:`Failed to evaluate language argument: ${w(a)}`});t=s.$.env;let l=s.$.value;if(!Ve(l))throw y({token:a.token,errorMessage:`Expected string for language argument, got ${w(a)}`});if(l.value.toLocaleLowerCase()==="yo")r="yo";else if(l.value.toLocaleLowerCase()==="c")r="c";else throw y({token:a.token,errorMessage:`Unsupported language "${l.value}" for extern, expected "c" or "yo"`})}let o=[];for(let a=0;a<i.length;a++){let s=i[a],{field:l,env:u}=na({expr:s,env:t,moduleFieldIndex:a,context:{...n,SelfType:void 0},isForEvaluatingModuleType:!1});if(o.find(p=>p.label===l.label))throw y({token:F(s)?s.args[0]?.token??s.token:s.token,errorMessage:`Duplicate label "${l.label}" in module`});if(He(l.type)||G(l.type)?l.type={...l.type,isExtern:r,externName:l.label,...l.label==="__yo_io_async"?{ioBuiltin:"io_async"}:{},...l.label==="__yo_io_await"?{ioBuiltin:"io_await"}:{},...l.label==="__yo_io_state"?{ioBuiltin:"io_state"}:{},...l.label==="__yo_io_spawn"?{ioBuiltin:"io_spawn"}:{},...l.label==="__yo_join_handle_await"?{ioBuiltin:"join_handle_await"}:{}}:l.type={...l.type,isExtern:r},l.assignedValue&&O(l.assignedValue)&&(ce(l.assignedValue.value)||ge(l.assignedValue.value)||it(l.assignedValue.value))){let p=l.assignedValue.value;p.isExtern=r,p.externName=l.label}o.push(l),t=u;let{env:_}=me({env:t,variable:{name:l.label,type:l.type,value:[l.assignedValue??K(l.type,{variableName:l.label,env:t,context:n})],isCompileTimeOnly:!0,token:l.exprs.expr.token,initializedAtToken:l.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});t=_}return e.$={env:t,value:H,type:H.type,pathCollection:[]},e.func.$={env:t,value:H,type:H.type,pathCollection:[]},e}import{existsSync as fo}from"fs";import Zt from"path";import*as nr from"fs";import*as $i from"path";import*as em from"crypto";import{execSync as CB}from"child_process";import*as ra from"fs";import*as Kd from"path";function gh(e){let t=[],n=e.split(`
10676
+ `),r;for(let i of n){let o=i.trim();if(o===""||o.startsWith("#"))continue;if(o==="[[dependencies]]"){r&&r.name&&t.push(jd(r)),r={};continue}if(r===void 0)continue;let a=o.indexOf("=");if(a===-1)continue;let s=o.slice(0,a).trim(),l=o.slice(a+1).trim();switch(l.length>=2&&l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),s){case"name":r.name=l;break;case"url":r.url=l;break;case"ref":r.ref=l;break;case"commit":r.commit=l;break;case"hash":r.hash=l;break}}return r&&r.name&&t.push(jd(r)),{dependencies:t}}function jd(e){return{name:e.name??"",url:e.url??"",ref:e.ref??"HEAD",commit:e.commit??"",hash:e.hash??""}}function Xd(e){let t=Kd.join(e,"yo.lock");if(!ra.existsSync(t))return{dependencies:[]};let n=ra.readFileSync(t,"utf-8");return gh(n)}function Qd(e,t){return e.dependencies.find(n=>n.name===t)}import*as hh from"fs";import*as Ul from"os";import*as po from"path";function vh(){let e=process.env.YO_CACHE_DIR;if(e)return e;let t=process.env.XDG_CACHE_HOME;if(t)return po.join(t,"yo");if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??po.join(Ul.homedir(),"AppData","Local");return po.join(n,"yo","cache")}return po.join(Ul.homedir(),".cache","yo")}function Zd(){return po.join(vh(),"deps")}var wB={...process.env,GIT_TERMINAL_PROMPT:"0"};function Th(e){return Zd()}function Eh(e){let t=em.createHash("sha256");return tm(t,e,""),`sha256-${t.digest("hex")}`}function tm(e,t,n){let r=n?$i.join(t,n):t,i=nr.readdirSync(r,{withFileTypes:!0});i.sort((o,a)=>$h(o.name,a.name));for(let o of i){let a=n?`${n}/${o.name}`:o.name;if(o.isDirectory()){if(o.name.startsWith("."))continue;e.update(`dir:${a}
10677
+ `),tm(e,t,a)}else if(o.isFile()){if(o.name===zl)continue;e.update(`file:${a}
10678
+ `);let s=nr.readFileSync($i.join(t,a));e.update(bh(s))}}}function $h(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n<r?-1:n>r?1:e<t?-1:e>t?1:0}var Jd=13,Ch=10;function bh(e){if(!e.includes(Jd))return e;let t=[];for(let n=0;n<e.length;n++)e[n]===Jd&&n+1<e.length&&e[n+1]===Ch||t.push(e[n]);return Buffer.from(t)}var zl=".yo-content-hash";function kh(e,t){nr.writeFileSync($i.join(e,zl),t+`
10679
+ `,"utf-8")}function wh(e,t,n){return $i.join(e,`${t}-${n.slice(0,12)}`)}function Fh(e,t,n){let r=wh(e,t,n.commit);if(!nr.existsSync(r))return{status:"missing_path",cachedPath:r};if(!n.hash)return{status:"missing_hash",cachedPath:r};let i=$i.join(r,zl),o;try{o=nr.readFileSync(i,"utf-8").trim()}catch{o=Eh(r),kh(r,o)}return o!==n.hash?{status:"hash_mismatch",cachedPath:r,actualHash:o}:{status:"ok",cachedPath:r,actualHash:o}}function Lh(e,t,n,r){return`Cached dependency "${e}" failed integrity check.
10662
10680
  Expected: ${t}
10663
10681
  Actual: ${n}
10664
10682
  Path: ${r}
10665
- Run 'yo fetch' to refetch this dependency.`}function tm(e,t,n=""){let r=Kd(e),i=Xd(r,t);if(!i||!i.commit)return;let o=vh(),a=wh(o,t,i);if(a.status!=="missing_path"){if(a.status==="missing_hash")throw new Error(`Dependency "${t}" is cached at "${a.cachedPath}" but its yo.lock entry is missing a content hash. Run 'yo fetch' to refresh yo.lock.`);if(a.status==="hash_mismatch")throw new Error(Fh(t,i.hash,a.actualHash??"<unknown>",a.cachedPath));return n?$i.join(a.cachedPath,n):a.cachedPath}}function nm({expr:e,env:t,context:n,stdPath:r}){if(!E(e,I.import,1))throw y({token:e.token,errorMessage:`Expected "import" with 1 argument, got:
10683
+ Run 'yo fetch' to refetch this dependency.`}function nm(e,t,n=""){let r=Xd(e),i=Qd(r,t);if(!i||!i.commit)return;let o=Th(),a=Fh(o,t,i);if(a.status!=="missing_path"){if(a.status==="missing_hash")throw new Error(`Dependency "${t}" is cached at "${a.cachedPath}" but its yo.lock entry is missing a content hash. Run 'yo fetch' to refresh yo.lock.`);if(a.status==="hash_mismatch")throw new Error(Lh(t,i.hash,a.actualHash??"<unknown>",a.cachedPath));return n?$i.join(a.cachedPath,n):a.cachedPath}}function rm({expr:e,env:t,context:n,stdPath:r}){if(!E(e,I.import,1))throw y({token:e.token,errorMessage:`Expected "import" with 1 argument, got:
10666
10684
  ${w(e)}`});let i=e.args[0],a=S({expr:i,env:t,context:{...n}}).$?.value;if(!Ve(a))throw y({token:i.token,errorMessage:`Expected comptime_string for module path, got:
10667
- ${w(i)}`});let s=a.value;if(s.endsWith("prelude.yo"))throw y({token:i.token,errorMessage:'Directly importing module with name "prelude.yo" is not allowed.'});if(s.startsWith("std/")?(s=Zt.relative(Zt.dirname(t.modulePath.replace(/^file:\/\//,"")),Zt.resolve(r,s.replace("std/","./"))),s.startsWith(".")||(s="./"+s)):s==="std"&&(s=Zt.relative(Zt.dirname(t.modulePath.replace(/^file:\/\//,"")),Zt.resolve(r,"./index.yo")),s.startsWith(".")||(s="./"+s)),!s.startsWith(".")){let c=Zf(s);if(c){let _=t.modulePath.replace(/^file:\/\//,"");s=Zt.relative(Zt.dirname(_),c),s.startsWith(".")||(s="./"+s)}}if(!s.startsWith(".")){let c=t.modulePath.replace(/^file:\/\//,""),_=Lh(c);if(_){let p=h=>{try{return tm(h,s)}catch(d){throw y({token:i.token,errorMessage:d instanceof Error?d.message:String(d)})}},m=Rl().findPathDependency(s),g;if(m?g=Zt.resolve(_,m.path):g=p(_),!g){let h=Qf();h&&h!==_&&(g=p(h))}if(g){let h=Ah(g,s);s=Zt.relative(Zt.dirname(c),h),s.startsWith(".")||(s="./"+s)}}if(!s.startsWith("."))throw y({token:i.token,errorMessage:`Module "${s}" not found. If this is a dependency, add it to build.yo and run 'yo fetch'.
10685
+ ${w(i)}`});let s=a.value;if(s.endsWith("prelude.yo"))throw y({token:i.token,errorMessage:'Directly importing module with name "prelude.yo" is not allowed.'});if(s.startsWith("std/")?(s=Zt.relative(Zt.dirname(t.modulePath.replace(/^file:\/\//,"")),Zt.resolve(r,s.replace("std/","./"))),s.startsWith(".")||(s="./"+s)):s==="std"&&(s=Zt.relative(Zt.dirname(t.modulePath.replace(/^file:\/\//,"")),Zt.resolve(r,"./index.yo")),s.startsWith(".")||(s="./"+s)),!s.startsWith(".")){let c=Jf(s);if(c){let _=t.modulePath.replace(/^file:\/\//,"");s=Zt.relative(Zt.dirname(_),c),s.startsWith(".")||(s="./"+s)}}if(!s.startsWith(".")){let c=t.modulePath.replace(/^file:\/\//,""),_=Ah(c);if(_){let p=h=>{try{return nm(h,s)}catch(d){throw y({token:i.token,errorMessage:d instanceof Error?d.message:String(d)})}},m=Rl().findPathDependency(s),g;if(m?g=Zt.resolve(_,m.path):g=p(_),!g){let h=Zf();h&&h!==_&&(g=p(h))}if(g){let h=Ih(g,s);s=Zt.relative(Zt.dirname(c),h),s.startsWith(".")||(s="./"+s)}}if(!s.startsWith("."))throw y({token:i.token,errorMessage:`Module "${s}" not found. If this is a dependency, add it to build.yo and run 'yo fetch'.
10668
10686
  ${w(e)}`})}let l="file://"+Zt.resolve(Zt.dirname(t.modulePath.replace(/^file:\/\//,"")),s);if(!Zt.extname(l)){let c=l.replace(/^file:\/\//,"")+".yo",_=Zt.join(l.replace(/^file:\/\//,""),"index.yo"),p=fo(c),f=fo(_);if(p&&f)throw y({token:i.token,errorMessage:`Ambiguous import "${s}": both "${s}.yo" and "${s}/index.yo" exist. Use an explicit path to resolve the ambiguity.`});if(p)l="file://"+c;else if(f)l="file://"+_;else throw y({token:i.token,errorMessage:`Module not found: tried "${"file://"+c}" and "${_}"`})}if(!n.loadModule)throw y({token:i.token,errorMessage:"Module loader is not provided in the context."});try{let{moduleValue:c}=n.loadModule(l);return e.$={env:t,type:c.type,value:c,pathCollection:[]},e}catch(c){throw y({token:i.token,errorMessage:`Failed to import module "${s}":
10669
- ${c instanceof yn||c instanceof Sn?c.toString():c instanceof Error?c.message:String(c)}`})}}function Lh(e){let t=Zt.dirname(e),n=Zt.parse(t).root;for(;t!==n;){if(fo(Zt.join(t,"yo.lock"))||fo(Zt.join(t,"build.yo")))return t;t=Zt.dirname(t)}}function Ah(e,t){let n=Zt.join(e,"index.yo"),r=Zt.join(e,t+".yo");return fo(n)?n:fo(r)?r:e}function Bl({lhsFunc:e,lhsFields:t,rhsFields:n,rhsValue:r,rhsType:i,lhs:o,env:a,isCompileTimeOnly:s,isDestructuringAtomVariable:l}){let u=!we(i),c=e.token.value;if(u&&c!=="_")throw y({token:e.token,errorMessage:`Expected "_" for non-tuple destructuring, got "${c}"`});if(it(i)&&t.length!==1)throw y({token:o.token,errorMessage:`Destructuring union type requires a single field, got ${t.length}`});if(t.length>n.length)throw y({token:o.token,errorMessage:`Too many fields in destructuring pattern. Expected at most ${n.length}, got ${t.length}`});let _={};for(let f=0;f<t.length;f++){let m=t[f],g=f,h,d=n[g],v,T,$,C;if(F(m)&&E(m,":",2)&&m.args[0].token.value==="..."&&m.args[1].token.value==="..."||z(m)&&m.token.value==="..."){if(it(i))throw y({token:m.token,errorMessage:`Cannot destructure union type with _, got ${A(i)}`});for(let L=0;L<n.length;L++){let b=n[L];if(_[b.label])continue;_[b.label]={label:b.label,variableName:b.label,type:b.type};let R=hn(r)||Cn(r)||We(r)||It(r)?r.fields[L]:void 0;if(!R&&s)throw y({token:m.token,errorMessage:`Destructuring field "${b.label}" is not defined in compile-time only context.`});let{env:N}=me({env:a,variable:{name:b.label,value:R?[an(R)]:void 0,type:b.type,isCompileTimeOnly:s,token:m.token,initializedAtToken:m.token,consumedAtToken:void 0,isCreatedFromDestructuringAtomVariable:l,isReassignable:!1,isOwningTheRcValue:!1}});a=N}m.$={env:a,type:i,value:r,pathCollection:[]};continue}else if(F(m)&&E(m,":",2)){let L=m.args[0],b=m.args[1];if(!z(L)||!je(L))throw y({token:L.token,errorMessage:`Expected identifier for label in destructuring pattern, got ${w(L)}`});$=L;let R=$.token.value,N=n.findIndex(D=>D.label===R);if(N===-1)throw y({token:m.token,errorMessage:`Label "${R}" being destructured not found.`});g=N,d=n[g];let B;if((hn(r)||Cn(r)||We(r)||It(r))&&(B=r.fields[g]),h=B,z(b)&&je(b))C=b,v=b.token.value,T=b.token;else throw y({token:b.token,errorMessage:`Nested destructuring is not supported:
10687
+ ${c instanceof yn||c instanceof Sn?c.toString():c instanceof Error?c.message:String(c)}`})}}function Ah(e){let t=Zt.dirname(e),n=Zt.parse(t).root;for(;t!==n;){if(fo(Zt.join(t,"yo.lock"))||fo(Zt.join(t,"build.yo")))return t;t=Zt.dirname(t)}}function Ih(e,t){let n=Zt.join(e,"index.yo"),r=Zt.join(e,t+".yo");return fo(n)?n:fo(r)?r:e}function Bl({lhsFunc:e,lhsFields:t,rhsFields:n,rhsValue:r,rhsType:i,lhs:o,env:a,isCompileTimeOnly:s,isDestructuringAtomVariable:l}){let u=!we(i),c=e.token.value;if(u&&c!=="_")throw y({token:e.token,errorMessage:`Expected "_" for non-tuple destructuring, got "${c}"`});if(it(i)&&t.length!==1)throw y({token:o.token,errorMessage:`Destructuring union type requires a single field, got ${t.length}`});if(t.length>n.length)throw y({token:o.token,errorMessage:`Too many fields in destructuring pattern. Expected at most ${n.length}, got ${t.length}`});let _={};for(let f=0;f<t.length;f++){let m=t[f],g=f,h,d=n[g],v,T,$,C;if(F(m)&&E(m,":",2)&&m.args[0].token.value==="..."&&m.args[1].token.value==="..."||z(m)&&m.token.value==="..."){if(it(i))throw y({token:m.token,errorMessage:`Cannot destructure union type with _, got ${A(i)}`});for(let L=0;L<n.length;L++){let b=n[L];if(_[b.label])continue;_[b.label]={label:b.label,variableName:b.label,type:b.type};let R=hn(r)||Cn(r)||We(r)||It(r)?r.fields[L]:void 0;if(!R&&s)throw y({token:m.token,errorMessage:`Destructuring field "${b.label}" is not defined in compile-time only context.`});let{env:N}=me({env:a,variable:{name:b.label,value:R?[an(R)]:void 0,type:b.type,isCompileTimeOnly:s,token:m.token,initializedAtToken:m.token,consumedAtToken:void 0,isCreatedFromDestructuringAtomVariable:l,isReassignable:!1,isOwningTheRcValue:!1}});a=N}m.$={env:a,type:i,value:r,pathCollection:[]};continue}else if(F(m)&&E(m,":",2)){let L=m.args[0],b=m.args[1];if(!z(L)||!je(L))throw y({token:L.token,errorMessage:`Expected identifier for label in destructuring pattern, got ${w(L)}`});$=L;let R=$.token.value,N=n.findIndex(D=>D.label===R);if(N===-1)throw y({token:m.token,errorMessage:`Label "${R}" being destructured not found.`});g=N,d=n[g];let B;if((hn(r)||Cn(r)||We(r)||It(r))&&(B=r.fields[g]),h=B,z(b)&&je(b))C=b,v=b.token.value,T=b.token;else throw y({token:b.token,errorMessage:`Nested destructuring is not supported:
10670
10688
 
10671
10689
  ${w(b)}`});if(_[d.label])throw y({token:m.token,errorMessage:`Label "${R}" being destructured already exists.`});_[d.label]={label:d.label,variableName:v,type:d.type}}else{if(F(m))throw y({token:m.token,errorMessage:`Nested destructuring is not supported:
10672
10690
 
10673
- ${w(m)}`});if(z(m)&&je(m)){if(it(i))throw y({token:m.token,errorMessage:`Cannot destructure union type with positional destructuring, got ${A(i)}`});if(_[d.label])throw y({token:m.token,errorMessage:`Label "${d.label}" being destructured already exists.`});_[d.label]={label:d.label,variableName:m.token.value,type:d.type},(hn(r)||Cn(r)||It(r)||We(r))&&(h=r.fields[g]),v=m.token.value,T=m.token}else throw y({token:m.token,errorMessage:`Unsupported destructuring pattern for: ${w(m)}`})}if(v&&T){if(!h&&s)throw y({token:m.token,errorMessage:`Destructuring field "${v}" is not defined in compile-time only context.`});let{env:L}=me({env:a,variable:{name:v,type:d.type,isCompileTimeOnly:s,value:h?[an(h)]:void 0,token:T,initializedAtToken:T,consumedAtToken:void 0,isCreatedFromDestructuringAtomVariable:l,isReassignable:!1,isOwningTheRcValue:!1}});a=L,m.$={env:a,type:d.type,value:h,pathCollection:[]},$&&($.$={env:a,type:d.type,value:h,pathCollection:[]}),C&&(C.$={env:a,type:d.type,value:h,pathCollection:[]})}}let p=[];for(let f in _){let m=_[f];p.push({label:m.label,type:m.type,variableName:m.variableName})}return{env:a,runtimeDestructurings:p}}function rm({lhs:e,rhs:t,env:n,isCompileTimeOnly:r,context:i}){if(!t.$?.type)throw y({token:t.token,errorMessage:`(1) Expected type for right-hand side, got ${w(t)}`});let o=t.$.type,a=t.$.value;if((ce(o)||it(o)||Te(o))&&F(e))return Bl({lhsFunc:e.func,lhsFields:e.args,rhsFields:o.fields,rhsValue:a,rhsType:o,lhs:e,env:n,context:{...i},isCompileTimeOnly:r,isDestructuringAtomVariable:z(t)});if(we(o)&&F(e)&&E(e,I.tuple))return Bl({lhsFunc:e.func,lhsFields:e.args,rhsFields:o.fields,rhsValue:a,rhsType:o,lhs:e,env:n,context:{...i},isCompileTimeOnly:r,isDestructuringAtomVariable:z(t)});if(ge(o)&&F(e)){let s=o.selectedVariantName;if(!s)throw y({token:t.token,errorMessage:`Expected enum variant name to be determined, got ${A(o)}`});let l=o.variants.find(u=>u.name===s);if(!l)throw y({token:t.token,errorMessage:`Expected enum variant "${s}" to be defined, got ${A(o)}`});if(!l.fields)throw y({token:t.token,errorMessage:`Cannot destructure enum variant "${s}" without fields, got ${A(o)}`});return Bl({lhsFunc:e.func,lhsFields:e.args,rhsFields:l.fields,rhsValue:a,rhsType:o,lhs:e,env:n,context:{...i},isCompileTimeOnly:r,isDestructuringAtomVariable:z(t)})}throw we(o)||ce(o)||it(o)||Te(o)?y({token:e.token,errorMessage:`Destructuring assignment not supported for the left-hand pattern:
10691
+ ${w(m)}`});if(z(m)&&je(m)){if(it(i))throw y({token:m.token,errorMessage:`Cannot destructure union type with positional destructuring, got ${A(i)}`});if(_[d.label])throw y({token:m.token,errorMessage:`Label "${d.label}" being destructured already exists.`});_[d.label]={label:d.label,variableName:m.token.value,type:d.type},(hn(r)||Cn(r)||It(r)||We(r))&&(h=r.fields[g]),v=m.token.value,T=m.token}else throw y({token:m.token,errorMessage:`Unsupported destructuring pattern for: ${w(m)}`})}if(v&&T){if(!h&&s)throw y({token:m.token,errorMessage:`Destructuring field "${v}" is not defined in compile-time only context.`});let{env:L}=me({env:a,variable:{name:v,type:d.type,isCompileTimeOnly:s,value:h?[an(h)]:void 0,token:T,initializedAtToken:T,consumedAtToken:void 0,isCreatedFromDestructuringAtomVariable:l,isReassignable:!1,isOwningTheRcValue:!1}});a=L,m.$={env:a,type:d.type,value:h,pathCollection:[]},$&&($.$={env:a,type:d.type,value:h,pathCollection:[]}),C&&(C.$={env:a,type:d.type,value:h,pathCollection:[]})}}let p=[];for(let f in _){let m=_[f];p.push({label:m.label,type:m.type,variableName:m.variableName})}return{env:a,runtimeDestructurings:p}}function im({lhs:e,rhs:t,env:n,isCompileTimeOnly:r,context:i}){if(!t.$?.type)throw y({token:t.token,errorMessage:`(1) Expected type for right-hand side, got ${w(t)}`});let o=t.$.type,a=t.$.value;if((ce(o)||it(o)||Te(o))&&F(e))return Bl({lhsFunc:e.func,lhsFields:e.args,rhsFields:o.fields,rhsValue:a,rhsType:o,lhs:e,env:n,context:{...i},isCompileTimeOnly:r,isDestructuringAtomVariable:z(t)});if(we(o)&&F(e)&&E(e,I.tuple))return Bl({lhsFunc:e.func,lhsFields:e.args,rhsFields:o.fields,rhsValue:a,rhsType:o,lhs:e,env:n,context:{...i},isCompileTimeOnly:r,isDestructuringAtomVariable:z(t)});if(ge(o)&&F(e)){let s=o.selectedVariantName;if(!s)throw y({token:t.token,errorMessage:`Expected enum variant name to be determined, got ${A(o)}`});let l=o.variants.find(u=>u.name===s);if(!l)throw y({token:t.token,errorMessage:`Expected enum variant "${s}" to be defined, got ${A(o)}`});if(!l.fields)throw y({token:t.token,errorMessage:`Cannot destructure enum variant "${s}" without fields, got ${A(o)}`});return Bl({lhsFunc:e.func,lhsFields:e.args,rhsFields:l.fields,rhsValue:a,rhsType:o,lhs:e,env:n,context:{...i},isCompileTimeOnly:r,isDestructuringAtomVariable:z(t)})}throw we(o)||ce(o)||it(o)||Te(o)?y({token:e.token,errorMessage:`Destructuring assignment not supported for the left-hand pattern:
10674
10692
 
10675
10693
  ${w(e)}`}):y({token:t.token,errorMessage:`Destructuring assignment not supported for the right-hand type:
10676
10694
 
10677
- ${A(o)}`})}function im({expr:e,env:t,context:n}){if(!E(e,":=",2)&&!E(e,"::",2))throw y({token:e.token,errorMessage:'Expected ":=" or "::" for initialization assignment.'});let r=E(e,"::")||n.forceCompileTimeBindings===!0,i=!E(e,"::");if(!r&&n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.isCompileTimeOnly)throw y({token:e.token,errorMessage:"Unexpected runtime variable declaration in a compile-time only function body."});let o=e.args[0],a=e.args[1],s=!1,l=o;if(F(o)&&E(o,I.given)){if(o.args.length!==1)throw y({token:o.token,errorMessage:`Expected exactly one argument for "given", got ${o.args.length}`});s=!0,l=o.args[0]}if(F(l)&&E(l,":"))throw y({token:l.token,errorMessage:`Unexpected use of ":" in type declaration with "${e.token.value}". Please consider using "=":
10695
+ ${A(o)}`})}function om({expr:e,env:t,context:n}){if(!E(e,":=",2)&&!E(e,"::",2))throw y({token:e.token,errorMessage:'Expected ":=" or "::" for initialization assignment.'});let r=E(e,"::")||n.forceCompileTimeBindings===!0,i=!E(e,"::");if(!r&&n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.isCompileTimeOnly)throw y({token:e.token,errorMessage:"Unexpected runtime variable declaration in a compile-time only function body."});let o=e.args[0],a=e.args[1],s=!1,l=o;if(F(o)&&E(o,I.given)){if(o.args.length!==1)throw y({token:o.token,errorMessage:`Expected exactly one argument for "given", got ${o.args.length}`});s=!0,l=o.args[0]}if(F(l)&&E(l,":"))throw y({token:l.token,errorMessage:`Unexpected use of ":" in type declaration with "${e.token.value}". Please consider using "=":
10678
10696
  (${w(l)}) = ${w(a)}`});if(a=S({expr:a,env:t,context:{...n,expectedType:void 0,isInsideGivenHandler:s?!0:n.isInsideGivenHandler}}),a.$?.env&&(t=a.$?.env),a.$?.type&&kr(a.$.type,a.token),nt(a.$?.controlFlow)&&Pl(a,a.$.controlFlow),Br(a),z(l)){if(ii(a,t),qt(a,{...n}),a.$?.env&&(t=a.$?.env),!je(l))throw y({token:l.token,errorMessage:`Invalid assignment to ${l.token.value}, expected identifier or operator`});let u=s||r,c=s?!1:i,_=a.$?.type;if(l.$?.type){try{let{expr:d,type:v,env:T}=xr({expr:a,type:l.$?.type,env:t,context:{...n}});a=d,_=v,t=T}catch(d){throw y({token:a.token,errorMessage:`(evaluateInitializationAssignment) Failed to synthesize type for expression: ${w(a)}
10679
10697
  ${d}`})}if(!Y({type:l.$.type,env:t},{type:_,env:t}))throw y({token:l.token,errorMessage:`Incompatible types:
10680
10698
  - Defined: ${A(l.$.type)}
@@ -10685,7 +10703,7 @@ Type:
10685
10703
  ${A(l.$.type)}`});if(u&&pr(l.$.type,t))throw y({token:e.token,errorMessage:`Expected ":=" instead of "::" for value type "${A(l.$.type)}" which can only be used at the runtime:
10686
10704
  ${w(e)}`});let p=a.$?.value;if(O(p)&&!p.value.typeName&&p.value!==n.SelfType?p.value.typeName=l.token.value:ne(p)&&!p.funcName?(p.funcName=l.token.value,p.funcId+=`_${l.token.value}`):(We(p)||Tt(p))&&!p.type.typeName&&p.type!==n.SelfType&&(p.type.typeName=l.token.value),s&&ne(p)&&(p.isModuleEffectMember=!0),!p&&u)throw y({token:l.token,errorMessage:`Expected compile-time value for "${l.token.value}".
10687
10705
  Got runtime value. Please consider using ":=" instead of "::":
10688
- ${w(a)}`});l.$={...l.$,env:t,type:l.$.type,value:u?p?an(p):K(l.$.type,{variableName:l.token.value,env:t,context:n}):void 0,pathCollection:[]};let f=l.$.type;x(f)&&_&&x(_)&&_.resolvedConcreteType&&(f={...f,resolvedConcreteType:_.resolvedConcreteType},l.$.type=f);let m=Oo(a,t,t.modulePath),g=m;m?.consumedAtToken&&(g=void 0);let{env:h}=me({env:t,variable:{name:l.token.value,type:f,isCompileTimeOnly:u,value:l.$.value?[l.$.value]:void 0,token:l.token,initializedAtToken:l.token,consumedAtToken:void 0,isOwningTheRcValue:Le(f),isOwningTheSameRcValueAs:g,isReassignable:!s,isImplicit:s}});return t=h,l.$.env=t,s&&(o.$={env:t,value:H,type:H.type,pathCollection:[]}),e.$={env:t,value:H,type:H.type,pathCollection:[],isCompileTimeOnlyAssignment:u},e}else{let u=s||r,{env:c,runtimeDestructurings:_}=rm({lhs:l,rhs:a,env:t,isCompileTimeOnly:s||r,context:{...n}});return t=c,e.$={env:t,value:H,type:H.type,pathCollection:[],runtimeDestructurings:_,isCompileTimeOnlyAssignment:u},e}}function Ih(e){return F(e)?E(e,"|",2):!1}function Gl(e){if(!Ih(e))return[e];let t=e,n=t.args[0],r=t.args[1];return[...Gl(n),...Gl(r)]}function Sh(e){return or(e)||ar(e)||jn(e)||cn(e)||vt(e)||Nt(e)||Et(e)}function om({expr:e,env:t,context:n}){if(!E(e,I.match))throw y({token:e.token,errorMessage:`Expected "match", got ${e.tag}`});let r=e.args;if(r.length<2)throw y({token:e.token,errorMessage:`Expected at least 2 arguments for "match", got ${r.length}`});let i=r[0],o=z(i)?S({expr:i,env:t,context:{...n,expectedType:void 0}}):ht({expr:i,env:t,context:{...n,expectedType:void 0},variablesToAdd:[]});if(!o.$||!o.$.variableName)throw y({token:i.token,errorMessage:`Failed to evaluate the match scrutinee expression: ${w(i)}`});t=o.$.env;let a=o.$.type,s=o.$.value,l,u;if(Ie(a)?(u=a.childType,l=a.tag):u=a,Sh(u))return Nh({expr:e,env:t,context:n,scrutineeExpr:o,scrutineeType:u,scrutineeValue:s});if(!ge(u))throw y({token:i.token,errorMessage:`Expected enum type or primitive type (integer, bool) for match expression, got ${a?A(a):"unknown type"}`});let c=u,_=r.slice(1),p=[],f,m=new Set,g=!1,h=!1,d=[],v=[];for(let $=0;$<_.length;$++){let C=_[$],L=t;if(!F(C)||!E(C,"=>",2))throw y({token:C.token,errorMessage:`Expected ":" for match pattern, got ${w(C)}`});let b=C.args[0],R=C.args[1];if(F(b)&&E(b,".",1)||dt(b,"_")){if(h)throw y({token:b.token,errorMessage:'Wildcard pattern "_" can only be used once and must be the last match arm in a "match" expression.'});let N;if(F(b)){if(N=b.args[0],!z(N))throw y({token:b.token,errorMessage:`Expected identifier for enum variant, got ${w(N)}`})}else h=!0,N=b;let B=N.token.value,D=c.variants.find(le=>le.name===B);if(!D&&B!=="_")throw y({token:b.token,errorMessage:`Enum variant "${B}" not found in ${A(c)}`});if(D&&D.fields&&D.fields.length>0)throw y({token:b.token,errorMessage:`Enum variant "${B}" has ${D.fields.length} field(s) and must be destructured. Use .${B}(...) instead of .${B}`});if(m.add(B),B!=="_"&&It(s)&&s.variantName!==B)continue;let V={...c,selectedVariantName:B==="_"?void 0:B};N.$={env:L,type:V,value:void 0,pathCollection:[]};let U=V;l&&l==="Ptr"&&(U=_i(V));let re=R;L=Pe(L),b.$={env:L,type:U,value:void 0,pathCollection:[],caseExecuted:!0};let j=ht({expr:re,env:L,context:{...n,isExecuting:It(s)&&s.variantName===B},variablesToAdd:[]});if(!j.$?.type)throw y({token:re.token,errorMessage:`Expected type for match result expression, got ${w(re)}`});let W=ct(j.$.env,!0);if(L=W,j.$={...j.$,env:W},n.expectedType&&!Y(n.expectedType,{type:j.$.type,env:j.$.env}))throw y({token:j.token,errorMessage:`Incompatible type with expected type:
10706
+ ${w(a)}`});l.$={...l.$,env:t,type:l.$.type,value:u?p?an(p):K(l.$.type,{variableName:l.token.value,env:t,context:n}):void 0,pathCollection:[]};let f=l.$.type;x(f)&&_&&x(_)&&_.resolvedConcreteType&&(f={...f,resolvedConcreteType:_.resolvedConcreteType},l.$.type=f);let m=Oo(a,t,t.modulePath),g=m;m?.consumedAtToken&&(g=void 0);let{env:h}=me({env:t,variable:{name:l.token.value,type:f,isCompileTimeOnly:u,value:l.$.value?[l.$.value]:void 0,token:l.token,initializedAtToken:l.token,consumedAtToken:void 0,isOwningTheRcValue:Le(f),isOwningTheSameRcValueAs:g,isReassignable:!s,isImplicit:s}});return t=h,l.$.env=t,s&&(o.$={env:t,value:H,type:H.type,pathCollection:[]}),e.$={env:t,value:H,type:H.type,pathCollection:[],isCompileTimeOnlyAssignment:u},e}else{let u=s||r,{env:c,runtimeDestructurings:_}=im({lhs:l,rhs:a,env:t,isCompileTimeOnly:s||r,context:{...n}});return t=c,e.$={env:t,value:H,type:H.type,pathCollection:[],runtimeDestructurings:_,isCompileTimeOnlyAssignment:u},e}}function Sh(e){return F(e)?E(e,"|",2):!1}function Gl(e){if(!Sh(e))return[e];let t=e,n=t.args[0],r=t.args[1];return[...Gl(n),...Gl(r)]}function Nh(e){return or(e)||ar(e)||jn(e)||cn(e)||vt(e)||Nt(e)||Et(e)}function am({expr:e,env:t,context:n}){if(!E(e,I.match))throw y({token:e.token,errorMessage:`Expected "match", got ${e.tag}`});let r=e.args;if(r.length<2)throw y({token:e.token,errorMessage:`Expected at least 2 arguments for "match", got ${r.length}`});let i=r[0],o=z(i)?S({expr:i,env:t,context:{...n,expectedType:void 0}}):ht({expr:i,env:t,context:{...n,expectedType:void 0},variablesToAdd:[]});if(!o.$||!o.$.variableName)throw y({token:i.token,errorMessage:`Failed to evaluate the match scrutinee expression: ${w(i)}`});t=o.$.env;let a=o.$.type,s=o.$.value,l,u;if(Ie(a)?(u=a.childType,l=a.tag):u=a,Nh(u))return Vh({expr:e,env:t,context:n,scrutineeExpr:o,scrutineeType:u,scrutineeValue:s});if(!ge(u))throw y({token:i.token,errorMessage:`Expected enum type or primitive type (integer, bool) for match expression, got ${a?A(a):"unknown type"}`});let c=u,_=r.slice(1),p=[],f,m=new Set,g=!1,h=!1,d=[],v=[];for(let $=0;$<_.length;$++){let C=_[$],L=t;if(!F(C)||!E(C,"=>",2))throw y({token:C.token,errorMessage:`Expected ":" for match pattern, got ${w(C)}`});let b=C.args[0],R=C.args[1];if(F(b)&&E(b,".",1)||dt(b,"_")){if(h)throw y({token:b.token,errorMessage:'Wildcard pattern "_" can only be used once and must be the last match arm in a "match" expression.'});let N;if(F(b)){if(N=b.args[0],!z(N))throw y({token:b.token,errorMessage:`Expected identifier for enum variant, got ${w(N)}`})}else h=!0,N=b;let B=N.token.value,D=c.variants.find(le=>le.name===B);if(!D&&B!=="_")throw y({token:b.token,errorMessage:`Enum variant "${B}" not found in ${A(c)}`});if(D&&D.fields&&D.fields.length>0)throw y({token:b.token,errorMessage:`Enum variant "${B}" has ${D.fields.length} field(s) and must be destructured. Use .${B}(...) instead of .${B}`});if(m.add(B),B!=="_"&&It(s)&&s.variantName!==B)continue;let V={...c,selectedVariantName:B==="_"?void 0:B};N.$={env:L,type:V,value:void 0,pathCollection:[]};let U=V;l&&l==="Ptr"&&(U=_i(V));let re=R;L=Pe(L),b.$={env:L,type:U,value:void 0,pathCollection:[],caseExecuted:!0};let j=ht({expr:re,env:L,context:{...n,isExecuting:It(s)&&s.variantName===B},variablesToAdd:[]});if(!j.$?.type)throw y({token:re.token,errorMessage:`Expected type for match result expression, got ${w(re)}`});let W=ct(j.$.env,!0);if(L=W,j.$={...j.$,env:W},n.expectedType&&!Y(n.expectedType,{type:j.$.type,env:j.$.env}))throw y({token:j.token,errorMessage:`Incompatible type with expected type:
10689
10707
  - Expected: ${A(n.expectedType.type)}
10690
10708
  - Actual : ${A(j.$.type)}`});if(s===void 0&&j.$&&(j.$.value=void 0),nt(j.$.controlFlow)?(d.push(j.$.controlFlow),et(j.$.controlFlow,"return")&&v.push(j),s&&!de(s)&&It(s)?e.$={env:j.$.env,type:n.expectedType?.type??j.$.type,value:j.$.value,pathCollection:j.$.pathCollection,controlFlow:j.$.controlFlow}:s===void 0&&(e.$={env:j.$.env,type:n.expectedType?.type??j.$.type,value:void 0,pathCollection:j.$.pathCollection,controlFlow:j.$.controlFlow})):g=!0,L=j.$.env,p.push(j),n.expectedType&&!Y(n.expectedType,{type:j.$.type,env:j.$.env}))throw y({token:j.token,errorMessage:`Incompatible type with expected type:
10691
10709
  - Expected: ${A(n.expectedType.type)}
@@ -10700,7 +10718,7 @@ Supported patterns:
10700
10718
  - _ (wildcard pattern)`})}let T=d.length>0?So(d):void 0;if(g||!nt(T)){if(g&&!f)throw y({token:e.token,errorMessage:"Failed to determine the type of value from the cond."});if(f||(f={type:H.type,env:t}),!m.has("_")){let L=c.variants.filter(b=>!m.has(b.name));if(L.length>0)throw y({token:e.token,errorMessage:`Match expression is not exhaustive. Missing cases for variants:
10701
10719
 
10702
10720
  - ${L.map(b=>b.name).join(`
10703
- - `)}`})}let $=p.filter(L=>L.$&&!et(L.$.controlFlow,"return")&&!et(L.$.controlFlow,"escape")),C;It(s)&&!de(s)&&$.length===1&&$[0].$?(t=$[0].$.env,C=$[0].$.value):It(s)&&$.length===1&&$[0].$?t=$[0].$.env:t=Gi(t,$),e.$={env:t,type:n.expectedType?.type??f.type,value:s===void 0?void 0:C!==void 0?C:K(f.type,{env:t,context:n}),pathCollection:[]},Ge(e,!0)}else{if(d.length===0)throw y({token:e.token,errorMessage:"No control flows found but expected some."});if(et(T,"return")){if(!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:e.token,errorMessage:"All cases in match are returning from function, but not evaluating in function body."});let $;if(v.length>0&&v[0].$?$=v[0].$.type:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?$=n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:n.expectedType&&($=n.expectedType.type),!$)throw y({token:e.token,errorMessage:"Failed to determine the return type for match statement."});e.$={env:t,type:$,value:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&Ao(n.isEvaluatingFunctionBodyOrAsyncBlock.type)?K($,{env:t,context:n}):void 0,pathCollection:[],controlFlow:T}}else if(et(T,"escape")){if(!n.enclosingFunctionReturnType)throw y({token:e.token,errorMessage:'All cases in match use "escape", but not inside a function with an enclosing function.'});let $=n.enclosingFunctionReturnType;e.$={env:t,type:$,value:void 0,pathCollection:[],controlFlow:T}}else if(et(T,"break")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are breaking from loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:T}}else if(et(T,"continue")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are continuing loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:T}}return e}return e}function Nh({expr:e,env:t,context:n,scrutineeExpr:r,scrutineeType:i,scrutineeValue:o}){let a=e.args.slice(1),s=[],l,u=new Set,c=!1,_=!1,p=[],f=[];for(let g=0;g<a.length;g++){let h=a[g],d=t;if(!F(h)||!E(h,"=>",2))throw y({token:h.token,errorMessage:`Expected "=>" for match pattern, got ${w(h)}`});let v=h.args[0],T=h.args[1];if(dt(v,"_")){if(_)throw y({token:v.token,errorMessage:'Wildcard pattern "_" can only be used once and must be the last match arm in a "match" expression.'});_=!0,v.$={env:d,type:i,value:void 0,pathCollection:[],caseExecuted:!0},d=Pe(d);let N=ht({expr:T,env:d,context:{...n,isExecuting:o!==void 0&&!de(o)},variablesToAdd:[]});if(!N.$?.type)throw y({token:T.token,errorMessage:`Expected type for match result expression, got ${w(T)}`});let B=ct(N.$.env,!0);if(d=B,N.$={...N.$,env:B},n.expectedType&&!Y(n.expectedType,{type:N.$.type,env:N.$.env}))throw y({token:N.token,errorMessage:`Incompatible type with expected type:
10721
+ - `)}`})}let $=p.filter(L=>L.$&&!et(L.$.controlFlow,"return")&&!et(L.$.controlFlow,"escape")),C;It(s)&&!de(s)&&$.length===1&&$[0].$?(t=$[0].$.env,C=$[0].$.value):It(s)&&$.length===1&&$[0].$?t=$[0].$.env:t=Gi(t,$),e.$={env:t,type:n.expectedType?.type??f.type,value:s===void 0?void 0:C!==void 0?C:K(f.type,{env:t,context:n}),pathCollection:[]},Ge(e,!0)}else{if(d.length===0)throw y({token:e.token,errorMessage:"No control flows found but expected some."});if(et(T,"return")){if(!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:e.token,errorMessage:"All cases in match are returning from function, but not evaluating in function body."});let $;if(v.length>0&&v[0].$?$=v[0].$.type:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?$=n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:n.expectedType&&($=n.expectedType.type),!$)throw y({token:e.token,errorMessage:"Failed to determine the return type for match statement."});e.$={env:t,type:$,value:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&Ao(n.isEvaluatingFunctionBodyOrAsyncBlock.type)?K($,{env:t,context:n}):void 0,pathCollection:[],controlFlow:T}}else if(et(T,"escape")){if(!n.enclosingFunctionReturnType)throw y({token:e.token,errorMessage:'All cases in match use "escape", but not inside a function with an enclosing function.'});let $=n.enclosingFunctionReturnType;e.$={env:t,type:$,value:void 0,pathCollection:[],controlFlow:T}}else if(et(T,"break")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are breaking from loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:T}}else if(et(T,"continue")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are continuing loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:T}}return e}return e}function Vh({expr:e,env:t,context:n,scrutineeExpr:r,scrutineeType:i,scrutineeValue:o}){let a=e.args.slice(1),s=[],l,u=new Set,c=!1,_=!1,p=[],f=[];for(let g=0;g<a.length;g++){let h=a[g],d=t;if(!F(h)||!E(h,"=>",2))throw y({token:h.token,errorMessage:`Expected "=>" for match pattern, got ${w(h)}`});let v=h.args[0],T=h.args[1];if(dt(v,"_")){if(_)throw y({token:v.token,errorMessage:'Wildcard pattern "_" can only be used once and must be the last match arm in a "match" expression.'});_=!0,v.$={env:d,type:i,value:void 0,pathCollection:[],caseExecuted:!0},d=Pe(d);let N=ht({expr:T,env:d,context:{...n,isExecuting:o!==void 0&&!de(o)},variablesToAdd:[]});if(!N.$?.type)throw y({token:T.token,errorMessage:`Expected type for match result expression, got ${w(T)}`});let B=ct(N.$.env,!0);if(d=B,N.$={...N.$,env:B},n.expectedType&&!Y(n.expectedType,{type:N.$.type,env:N.$.env}))throw y({token:N.token,errorMessage:`Incompatible type with expected type:
10704
10722
  - Expected: ${A(n.expectedType.type)}
10705
10723
  - Actual : ${A(N.$.type)}`});if(o===void 0&&N.$&&(N.$.value=void 0),nt(N.$.controlFlow))p.push(N.$.controlFlow),et(N.$.controlFlow,"return")&&f.push(N),o!==void 0&&!de(o)?e.$={env:N.$.env,type:n.expectedType?.type??N.$.type,value:N.$.value,pathCollection:N.$.pathCollection,controlFlow:N.$.controlFlow}:o===void 0&&(e.$={env:N.$.env,type:n.expectedType?.type??N.$.type,value:void 0,pathCollection:N.$.pathCollection,controlFlow:N.$.controlFlow});else if(c=!0,o!==void 0&&!de(o))return t=Gi(t,s.filter(D=>D.$&&!et(D.$.controlFlow,"return")&&!et(D.$.controlFlow,"escape"))),e.$={env:t,type:n.expectedType?.type??N.$.type,value:N.$.value,pathCollection:[],isPrimitiveMatch:!0},Ge(e,!0),e;if(d=N.$.env,s.push(N),!nt(N.$.controlFlow)){if(!l)l={type:N.$.type,env:d};else if(!Y({type:l.type,env:d},{type:N.$.type,env:t}))throw y({token:N.token,errorMessage:`Incompatible types in match branches:
10706
10724
  - Previous: ${A(l.type)}
@@ -10709,13 +10727,13 @@ Hint: Use "::" to define compile-time constants, e.g., "myConst :: 42"`});let V=
10709
10727
  - Expected: ${A(n.expectedType.type)}
10710
10728
  - Actual : ${A(b.$.type)}`});if(o===void 0&&b.$&&(b.$.value=void 0),nt(b.$.controlFlow)){if(p.push(b.$.controlFlow),et(b.$.controlFlow,"return")&&f.push(b),o!==void 0&&L)return e.$={env:b.$.env,type:n.expectedType?.type??b.$.type,value:b.$.value,pathCollection:b.$.pathCollection,controlFlow:b.$.controlFlow},e;o===void 0&&(e.$={env:b.$.env,type:n.expectedType?.type??b.$.type,value:void 0,pathCollection:b.$.pathCollection,controlFlow:b.$.controlFlow})}else if(c=!0,o!==void 0&&!de(o)&&L)return e.$={env:b.$.env,type:n.expectedType?.type??b.$.type,value:b.$.value,pathCollection:b.$.pathCollection,isPrimitiveMatch:!0},Ge(e,!0),e;if(d=b.$.env,s.push(b),!nt(b.$.controlFlow)){if(!l)l={type:b.$.type,env:d};else if(!Y({type:l.type,env:d},{type:b.$.type,env:t}))if(Y({type:yt({type:l.type,expectedType:void 0,expr:void 0,env:l.env}),env:l.env},{type:b.$.type,env:d}))l={type:b.$.type,env:d};else throw y({token:b.token,errorMessage:`Incompatible types in match branches:
10711
10729
  - Previous: ${A(l.type)}
10712
- - Current : ${A(b.$.type)}`})}}if(!_)if(cn(i)){let g=u.has("true"),h=u.has("false");if(!g||!h)throw y({token:e.token,errorMessage:`Match expression on bool is not exhaustive. Missing cases for: ${g?"":"true"}${!g&&!h?", ":""}${h?"":"false"}`})}else throw y({token:e.token,errorMessage:`Match expression on ${A(i)} requires a wildcard pattern "_" for exhaustiveness.`});let m=p.length>0?So(p):void 0;if(c||!nt(m)){if(c&&!l)throw y({token:e.token,errorMessage:"Failed to determine the type of value from the match."});l||(l={type:H.type,env:t});let g=s.filter(h=>h.$&&!et(h.$.controlFlow,"return")&&!et(h.$.controlFlow,"escape"));o!==void 0&&!de(o)&&g.length===1&&g[0].$?t=g[0].$.env:t=Gi(t,g),e.$={env:t,type:n.expectedType?.type??l.type,value:o===void 0?void 0:K(l.type,{env:t,context:n}),pathCollection:[],isPrimitiveMatch:!0},Ge(e,!0)}else{if(p.length===0)throw y({token:e.token,errorMessage:"No control flows found but expected some."});if(et(m,"return")){if(!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:e.token,errorMessage:"All cases in match are returning from function, but not evaluating in function body."});let g;if(f.length>0&&f[0].$?g=f[0].$.type:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?g=n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:n.expectedType&&(g=n.expectedType.type),!g)throw y({token:e.token,errorMessage:"Failed to determine the return type for match statement."});e.$={env:t,type:g,value:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&Ao(n.isEvaluatingFunctionBodyOrAsyncBlock.type)?K(g,{env:t,context:n}):void 0,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}else if(et(m,"escape")){if(!n.enclosingFunctionReturnType)throw y({token:e.token,errorMessage:'All cases in match use "escape", but not inside a function with an enclosing function.'});let g=n.enclosingFunctionReturnType;e.$={env:t,type:g,value:void 0,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}else if(et(m,"break")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are breaking from loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}else if(et(m,"continue")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are continuing loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}return e}return e}function am({expr:e,env:t,context:n}){let r=e.args[0];if(!r)throw y({token:e.token,errorMessage:`Expected "using" with 1 argument, got:
10730
+ - Current : ${A(b.$.type)}`})}}if(!_)if(cn(i)){let g=u.has("true"),h=u.has("false");if(!g||!h)throw y({token:e.token,errorMessage:`Match expression on bool is not exhaustive. Missing cases for: ${g?"":"true"}${!g&&!h?", ":""}${h?"":"false"}`})}else throw y({token:e.token,errorMessage:`Match expression on ${A(i)} requires a wildcard pattern "_" for exhaustiveness.`});let m=p.length>0?So(p):void 0;if(c||!nt(m)){if(c&&!l)throw y({token:e.token,errorMessage:"Failed to determine the type of value from the match."});l||(l={type:H.type,env:t});let g=s.filter(h=>h.$&&!et(h.$.controlFlow,"return")&&!et(h.$.controlFlow,"escape"));o!==void 0&&!de(o)&&g.length===1&&g[0].$?t=g[0].$.env:t=Gi(t,g),e.$={env:t,type:n.expectedType?.type??l.type,value:o===void 0?void 0:K(l.type,{env:t,context:n}),pathCollection:[],isPrimitiveMatch:!0},Ge(e,!0)}else{if(p.length===0)throw y({token:e.token,errorMessage:"No control flows found but expected some."});if(et(m,"return")){if(!n.isEvaluatingFunctionBodyOrAsyncBlock)throw y({token:e.token,errorMessage:"All cases in match are returning from function, but not evaluating in function body."});let g;if(f.length>0&&f[0].$?g=f[0].$.type:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"?g=n.isEvaluatingFunctionBodyOrAsyncBlock.type.return.type:n.expectedType&&(g=n.expectedType.type),!g)throw y({token:e.token,errorMessage:"Failed to determine the return type for match statement."});e.$={env:t,type:g,value:n.isEvaluatingFunctionBodyOrAsyncBlock.kind==="function-body"&&Ao(n.isEvaluatingFunctionBodyOrAsyncBlock.type)?K(g,{env:t,context:n}):void 0,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}else if(et(m,"escape")){if(!n.enclosingFunctionReturnType)throw y({token:e.token,errorMessage:'All cases in match use "escape", but not inside a function with an enclosing function.'});let g=n.enclosingFunctionReturnType;e.$={env:t,type:g,value:void 0,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}else if(et(m,"break")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are breaking from loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}else if(et(m,"continue")){if(!n.isEvaluatingLoopBody)throw y({token:e.token,errorMessage:"All cases in match are continuing loop, but not inside a loop."});e.$={env:t,type:H.type,value:H,pathCollection:[],controlFlow:m,isPrimitiveMatch:!0}}return e}return e}function sm({expr:e,env:t,context:n}){let r=e.args[0];if(!r)throw y({token:e.token,errorMessage:`Expected "using" with 1 argument, got:
10713
10731
  ${w(e)}`});{let l=r;for(;E(l,".")&&l.args.length>=1;)l=l.args[0];if(z(l)){let u=X(t,l.token.value),c=u[u.length-1];if(c?.isImplicit)throw y({token:r.token,errorMessage:`Cannot use "open" on implicit variable "${c.name}". Implicit variables must be passed via using() parameters.`})}}let i=S({expr:r,env:t,context:{...n}});if(!i.$)throw y({token:i.token,errorMessage:`Failed to evaluate the module argument:
10714
10732
  ${w(i)}`});let o=i.$.type,a=i.$.value,s;if(We(a)){let l=a,u=l.type;for(let c=0;c<u.fields.length;c++){let _=l.fields[c],p=u.fields[c],{env:f}=me({env:t,variable:{name:p.label,type:p.type,isCompileTimeOnly:!0,value:[_],token:p.exprs.labelExpr?.token??p.exprs.expr.token,initializedAtToken:p.exprs.labelExpr?.token??p.exprs.expr.token,consumedAtToken:void 0,isReassignable:!1,isOwningTheRcValue:!1}});t=f}}else if(ce(o)){let l=a,u=o;s=[];for(let c=0;c<u.fields.length;c++){let _;Cn(l)&&(_=l.fields[c]);let p=u.fields[c];try{let{env:f}=me({env:t,variable:{name:p.label,type:p.type,isCompileTimeOnly:!!_,value:_?[_]:void 0,token:p.exprs.labelExpr?.token??p.exprs.expr.token,initializedAtToken:p.exprs.labelExpr?.token??p.exprs.expr.token,consumedAtToken:void 0,isReassignable:!1,isOwningTheRcValue:!1}});t=f,s.push({label:p.label,variableName:p.label,type:p.type})}catch(f){throw lt([{token:r.token,errorMessage:`Failed to import struct field "${p.label}"`},...f instanceof yn?f.tokenAndErrorList:[{token:r.token,errorMessage:f instanceof Error?f.message:String(f)}]])}}}else throw y({token:r.token,errorMessage:`Expected module/struct for "${I.open}", got:
10715
- ${w(r)}`});return e.$={env:t,value:H,type:H.type,pathCollection:[],runtimeDestructurings:s},e}function sm({expr:e,env:t,context:n}){if(!E(e,"."))throw y({token:e.token,errorMessage:`Expected "." for property access, got:
10733
+ ${w(r)}`});return e.$={env:t,value:H,type:H.type,pathCollection:[],runtimeDestructurings:s},e}function lm({expr:e,env:t,context:n}){if(!E(e,"."))throw y({token:e.token,errorMessage:`Expected "." for property access, got:
10716
10734
  ${w(e)}`});if(E(e,".",1)){let s=e.args[0];if(!z(s)&&!je(s))throw y({token:s.token,errorMessage:`Expected identifier for enum variant access, got:
10717
10735
  ${w(s)}`});let l=n.expectedType?.type;if(!ge(l))throw y({token:e.token,errorMessage:"Failed to infer enum variant type."});let u=s.token.value,c=l,_=c.variants.find(f=>f.name===u);if(!_)throw y({token:s.token,errorMessage:`Enum variant "${u}" not found in enum`});let p={...c,selectedVariantName:u};if(!_.fields)e.$={env:t,type:p,value:Jr(p,u,[]),pathCollection:[]},s.$={env:t,type:p,pathCollection:[]};else{let f=ee(p);e.$={env:t,value:f,type:f.type,pathCollection:[]},s.$=e.$}return e}if(!E(e,".",2))throw y({token:e.token,errorMessage:`Expected "." with 2 arguments, got:
10718
- ${w(e)}`});let r=e.args[0],i=e.args[1];if(r=S({expr:r,env:t,context:{...n,expectedType:void 0}}),r.$?.env&&(t=r.$?.env),z(i)&&i.token.value==="*"){if(Ie(r.$?.type)){let s=r.$.type,l=s.childType;x(l)&&(l=Ot(t,l));let u=r.$?.value;if(wi(u)){let c=u.targetValue[0],_;return Un(c)?_=c.elements[u.targetIndex]:_=c,e.$={env:t,type:l,value:_,originType:s,isAccessingProperty:!0,pathCollection:[],sourceVariable:r.$.sourceVariable},e.$.ptrTargetValue=u.targetValue,e.$.ptrTargetIndex=u.targetIndex,i.$=e.$,e}if(de(u)){let c=K(l,{variableName:u.variableName?`${u.variableName}.*`:void 0,env:t,context:n});return e.$={env:t,type:l,value:c,originType:s,isAccessingProperty:!0,pathCollection:[]},i.$=e.$,e}return e.$={env:t,type:l,value:void 0,originType:s,isAccessingProperty:!0,pathCollection:[]},i.$=e.$,Ge(e,!1),e}if($t(r.$?.type)){let s=r.$.type,l=s.childType;return x(l)&&(l=Ot(t,l)),e.$={env:t,type:l,value:void 0,originType:s,isAccessingProperty:!0,pathCollection:[]},i.$=e.$,Ge(e,!1),e}}if(O(r.$?.value)){let s=r.$.value;if(ge(s.value)){if(!z(i))throw y({token:i.token,errorMessage:`Expected identifier for enum variant, got:
10736
+ ${w(e)}`});let r=e.args[0],i=e.args[1];if(r=S({expr:r,env:t,context:{...n,expectedType:void 0}}),r.$?.env&&(t=r.$?.env),z(i)&&i.token.value==="*"){if(Ie(r.$?.type)){let s=r.$.type,l=s.childType;x(l)&&(l=Ot(t,l));let u=r.$?.value;if(wi(u)){let c=u.targetValue[0],_;return Un(c)?_=c.elements[u.targetIndex]:_=c,e.$={env:t,type:l,value:_,originType:s,isAccessingProperty:!0,pathCollection:[],sourceVariable:r.$.sourceVariable},e.$.ptrTargetValue=u.targetValue,e.$.ptrTargetIndex=u.targetIndex,i.$=e.$,e}if(de(u)){let c=K(l,{variableName:u.variableName?`${u.variableName}.*`:void 0,env:t,context:n});return e.$={env:t,type:l,value:c,originType:s,isAccessingProperty:!0,pathCollection:[]},i.$=e.$,e}return e.$={env:t,type:l,value:void 0,originType:s,isAccessingProperty:!0,pathCollection:[]},i.$=e.$,Ge(e,!1),e}if(Ct(r.$?.type)){let s=r.$.type,l=s.childType;return x(l)&&(l=Ot(t,l)),e.$={env:t,type:l,value:void 0,originType:s,isAccessingProperty:!0,pathCollection:[]},i.$=e.$,Ge(e,!1),e}}if(O(r.$?.value)){let s=r.$.value;if(ge(s.value)){if(!z(i))throw y({token:i.token,errorMessage:`Expected identifier for enum variant, got:
10719
10737
  ${w(i)}`});{let p=i.token.value,f=s.value.trait.fields.find(m=>m.label===p);if(f)return e.$={env:t,type:f.type,value:f.assignedValue,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e}let l=i.token.value,u=s.value,c=u.variants.find(p=>p.name===l);if(!c){let p=Jn({concreteType:s.value,methodName:l,env:t});if(p.length===1){let f=p[0];return e.$={env:t,type:f.type,value:f.value,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e}if(p.length>1)return e.$=void 0,e;throw y({token:i.token,errorMessage:`Enum variant "${l}" not found in enum`})}let _={...u,selectedVariantName:l};if(!c.fields)e.$={env:t,type:_,value:Jr(_,l,[]),isAccessingProperty:!0,pathCollection:[]},i.$=e.$;else{let p=ee(_);e.$={env:t,type:p.type,value:p,isAccessingProperty:!0,pathCollection:[]},i.$=e.$}return e}else if(s.value.trait){if(!je(i))throw y({token:i.token,errorMessage:`Expected identifier for type method, got:
10720
10738
  ${w(i)}`});let l=i.token.value,u=s.value.trait.fields.findLast(c=>c.label===l);if(u){if(u.assignedValue){let c=u.assignedValue.type;return e.$={env:t,type:c,value:u.assignedValue,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e}if(u.unassignedSomeType){let c=ee(u.unassignedSomeType);return e.$={env:t,type:c.type,value:c,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e}return e.$={env:t,type:u.type,value:void 0,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e}else{for(let p of s.value.trait.fields)if(p.label===""&&p.assignedValue&&Tt(p.assignedValue)){let f=p.assignedValue,m=f.type,g=m.fields.findIndex(h=>h.label===l);if(g>=0){let h=m.fields[g],d=f.fields[g];if(G(h.type))continue;if(d)return e.$={env:t,type:d.type,value:d,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e;if(h.unassignedSomeType){let v=ee(h.unassignedSomeType);return e.$={env:t,type:v.type,value:v,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e}}}let c=Jn({concreteType:s.value,methodName:l,env:t});if(c.length===1){let p=c[0];return e.$={env:t,type:p.type,value:p.value,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e}let _=xa({concreteType:s.value,propertyName:l,env:t});return _?(e.$={env:t,type:_.type,value:_.value,pathCollection:[],isAccessingProperty:!0},i.$=e.$,e):(e.$=void 0,e)}}else if(Te(s.value)){if(!je(i))throw y({token:i.token,errorMessage:`Expected identifier for type method, got:
10721
10739
  ${w(i)}`});let l=i.token.value,c=s.value.fields.find(_=>_.label===l);return c?(e.$={env:t,type:c.type,value:c.assignedValue??K(c.type,{variableName:c.label,env:t,context:n}),pathCollection:[],isAccessingProperty:!0},i.$=e.$,e):(e.$=void 0,e)}else if(De(s.value)){if(!je(i))throw y({token:i.token,errorMessage:`Expected identifier for type method, got:
@@ -10723,19 +10741,19 @@ ${w(i)}`});let l=i.token.value,u=s.value;if(u.receiverType&&u.receiverType.trait
10723
10741
  ${w(i)}`});let c=s.length;if(u<0||u>=c)throw y({token:i.token,errorMessage:`Index out of bounds: ${u} for accessing field in:
10724
10742
  ${A(r.$?.type)}`});let _=s[u],p=r.$.originType||a,f=r.$.pathCollection&&r.$.pathCollection.length>0?r.$.pathCollection.map(m=>[...m,i.token.value]):[[r.$.variableName??"?",i.token.value]];if(e.$={env:t,type:_.type,originType:p,isAccessingProperty:!0,pathCollection:f},i.$=e.$,l){let m=[];(hn(l)||Cn(l))&&(m=l.fields),e.$.value=m?.[u]}return Ge(e,!1),e}else if(je(i)){let u=i.token.value;{let c=s.findIndex(m=>m.label===u);if(c<0){if(Te(r.$?.type))throw y({token:i.token,errorMessage:`Module field "${u}" not found in module type`});return e.$=void 0,e}let _=s[c],p=r.$?.originType||a,f=r.$.pathCollection&&r.$.pathCollection.length>0?r.$.pathCollection.map(m=>[...m,i.token.value]):[[r.$.variableName??"?",i.token.value]];if(e.$={env:t,type:_.type,originType:p,isAccessingProperty:!0,pathCollection:f},i.$=e.$,l)if(de(l))e.$.value=K(_.type,{env:t,context:n});else{let m=[];(hn(l)||Cn(l))&&(m=l.fields);let g=m?.[c];g||(g=K(_.type,{env:t,context:n})),e.$.value=g}return Ge(e,!1),e}}}}else if(Te(o)){let s=o.fields,l=r.$.value;if(z(i)){if(i.token.type==="integer")throw y({token:i.token,errorMessage:`Accessomg module field by index is not allowed, got:
10725
10743
  ${w(i)}`});if(je(i)){let u=i.token.value;{let c=s.findIndex(f=>f.label===u);if(c<0){if(Te(r.$?.type))throw y({token:i.token,errorMessage:`Module field "${u}" not found in module type`});return e.$=void 0,e}let _=s[c],p=r.$.pathCollection&&r.$.pathCollection.length>0?r.$.pathCollection.map(f=>[...f,i.token.value]):[[r.$.variableName??"?",i.token.value]];if(e.$={env:t,type:_.type,isAccessingProperty:!0,pathCollection:p},i.$=e.$,l)if(de(l))e.$.value=K(_.type,{env:t,context:n});else{let f=[];We(l)&&(f=l.fields);let m=f?.[c];m||(m=K(_.type,{env:t,context:n})),e.$.value=m}return e}}}}else if(ge(o)&&z(i)){if(!je(i))throw y({token:i.token,errorMessage:`Expected identifier for enum variant property, got:
10726
- ${w(i)}`});let s=i.token.value,l=o.variants.find(u=>u.name===o.selectedVariantName);if(l){let u=(l.fields??[]).findIndex(p=>p.label===s);if(u<0)return e.$=void 0,e;let c=(l.fields??[])[u];e.$={env:t,type:c.type,value:void 0,pathCollection:[[r.$.variableName??"?",i.token.value]],isAccessingProperty:!0};let _=r.$?.value;return _&&It(_)&&_.variantName===l.name&&(e.$.value=_.fields[u]),i.$=e.$,e}}return e.$=void 0,e}function lm({expr:e,env:t,context:n}){if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="function-body")throw y({token:e.token,errorMessage:`Expected a function type for recur, got:
10744
+ ${w(i)}`});let s=i.token.value,l=o.variants.find(u=>u.name===o.selectedVariantName);if(l){let u=(l.fields??[]).findIndex(p=>p.label===s);if(u<0)return e.$=void 0,e;let c=(l.fields??[])[u];e.$={env:t,type:c.type,value:void 0,pathCollection:[[r.$.variableName??"?",i.token.value]],isAccessingProperty:!0};let _=r.$?.value;return _&&It(_)&&_.variantName===l.name&&(e.$.value=_.fields[u]),i.$=e.$,e}}return e.$=void 0,e}function um({expr:e,env:t,context:n}){if(n.isEvaluatingFunctionBodyOrAsyncBlock?.kind!=="function-body")throw y({token:e.token,errorMessage:`Expected a function type for recur, got:
10727
10745
  ${w(e)}`});let r=n.isEvaluatingFunctionBodyOrAsyncBlock.type;if(!E(e,I.recur))throw y({token:e.token,errorMessage:`Expected recur, got:
10728
- ${w(e)}`});if(n.isAnalyzingCtfeCapability||n.isValidatingFunctionDefinition){let o=n.isEvaluatingFunctionBodyOrAsyncBlock.value,{returnType:a,runtimeArgExprsInOrder:s,callerEnv:l}=jr({functionValue:ne(o)?o:void 0,functionType:r,expr:e,functionCalleeExpr:e.func,argExprs:e.args,callerEnv:t,context:n,isMethodCall:!1,skipSpecialization:!0,skipCtfeExecution:!0});return t=ct(l),e.$={type:a,value:K(a,{variableName:"recur_result_"+qe(t.modulePath),env:t,context:n}),env:t,pathCollection:[],runtimeArgExprsInOrder:s},e}return Rn({expr:e,env:t,givenFunc:{type:r,value:n.isEvaluatingFunctionBodyOrAsyncBlock.value??void 0},context:{...n}})}function um({expr:e,env:t,context:n}){if(!E(e,I.runtime,1))throw y({token:e.token,errorMessage:`Expected runtime(expr), got:
10746
+ ${w(e)}`});if(n.isAnalyzingCtfeCapability||n.isValidatingFunctionDefinition){let o=n.isEvaluatingFunctionBodyOrAsyncBlock.value,{returnType:a,runtimeArgExprsInOrder:s,callerEnv:l}=jr({functionValue:ne(o)?o:void 0,functionType:r,expr:e,functionCalleeExpr:e.func,argExprs:e.args,callerEnv:t,context:n,isMethodCall:!1,skipSpecialization:!0,skipCtfeExecution:!0});return t=ct(l),e.$={type:a,value:K(a,{variableName:"recur_result_"+qe(t.modulePath),env:t,context:n}),env:t,pathCollection:[],runtimeArgExprsInOrder:s},e}return Rn({expr:e,env:t,givenFunc:{type:r,value:n.isEvaluatingFunctionBodyOrAsyncBlock.value??void 0},context:{...n}})}function cm({expr:e,env:t,context:n}){if(!E(e,I.runtime,1))throw y({token:e.token,errorMessage:`Expected runtime(expr), got:
10729
10747
  ${w(e)}`});if(n.isAnalyzingCtfeCapability)throw y({token:e.token,errorMessage:'Cannot use "runtime" during compile-time function evaluation analysis. The "runtime" keyword forces runtime evaluation and prevents CTFE.'});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(!i.$?.type)throw y({token:i.token,errorMessage:`Failed to evaluate runtime argument:
10730
- ${w(i)}`});let o=yt({type:i.$.type,expectedType:void 0,expr:i,env:i.$.env??t});return e.$={type:o,value:void 0,env:i.$.env??t,pathCollection:i.$.pathCollection??[]},e}function cm({expr:e,env:t,context:n}){he(e,"<:",2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$||!o.$.value||!O(o.$.value))throw y({token:r.token,errorMessage:"Expected type for left-hand side expression."});t=o.$.env;let a=o.$.value;if(n.isInsideWhereClause&&!x(a.value))throw y({token:r.token,errorMessage:`In a where clause, the left-hand side of <: must be a type parameter (SomeType), got: ${w(r)} of type ${A(a.value)}`});let s=[];if(F(i)&&E(i,I.tuple))for(let f of i.args)F(f)&&E(f,"!")&&f.args.length===1?s.push({expr:f.args[0],isNegated:!0}):s.push({expr:f,isNegated:!1});else F(i)&&E(i,"!")&&i.args.length===1?s.push({expr:i.args[0],isNegated:!0}):s.push({expr:i,isNegated:!1});let l=[];for(let{expr:f,isNegated:m}of s){let g=S({expr:f,env:t,context:{...n}});if(!g.$||!g.$.value||!O(g.$.value)||!De(g.$.value.value))throw y({token:f.token,errorMessage:"Expected trait type for right-hand side expression."});t=g.$.env;let h=g.$.value.value;if(h.receiverType)throw y({token:f.token,errorMessage:"Expected trait type already has a receiver type assigned."});if(m&&!n.isInsideWhereClause)throw y({token:f.token,errorMessage:"Negated trait constraints !(Trait) are only allowed in where clauses."});l.push({traitType:h,expr:f,isNegated:m})}if(n.isInsideWhereClause&&x(a.value)){let f=a.value;for(let{traitType:m,isNegated:g}of l){let h={...m,receiverType:f};t=er({env:t,someType:f,traitType:h,isNegated:g})}return e.$={env:t,value:a,type:a.type,pathCollection:[]},e}if(l.length>1)throw y({token:i.token,errorMessage:"Multiple trait constraints (tuple form) are only allowed in where clauses."});let{traitType:u}=l[0],c=a.value;if(!x(c)&&!St({targetType:c,traitType:u,env:t}))throw y({token:e.token,errorMessage:`Type "${A(c)}" does not implement trait "${u.typeName??A(u)}".`});let _={...u,receiverType:a.value},p=ee(_);return e.$={env:t,value:p,type:p.type,pathCollection:[]},e}function _m({expr:e,env:t,context:n}){if(!E(e,I.test))throw y({token:e.token,errorMessage:`Expected test, got ${e.tag}`});if(e.args.length!==2&&e.args.length!==3)throw y({token:e.token,errorMessage:`test expects 2 or 3 arguments (name, [using clause], body), got ${e.args.length}`});let r=e.args.length===3,i=e.args[0],o=r?e.args[1]:void 0,a=r?e.args[2]:e.args[1];if(o&&!E(o,I.using))throw y({token:o.token,errorMessage:`Expected using(...) clause as second argument, got: ${w(o)}`});let s=S({expr:i,env:t,context:{...n}});if(!s.$||!s.$.value)throw y({token:i.token,errorMessage:`Failed to evaluate test name: ${w(i)}`});if(t=s.$.env,!Ve(s.$.value))throw y({token:i.token,errorMessage:`Expected string for test name, got ${w(i)}`});if(r){let l=Ae(o);o.$={env:t,type:H.type,value:H,pathCollection:[],originalExpr:l};let u=Ae(a);a.$={env:t,type:H.type,value:H,pathCollection:[],originalExpr:u}}else{let l=Ae(a),u=S({expr:a,env:t,context:{...n,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"test-block",evaluationEnv:t}}});if(!u.$)throw y({token:a.token,errorMessage:`Failed to evaluate test body: ${w(a)}`});if(!pe(u.$.type))throw y({token:a.token,errorMessage:`Test body must have 'unit' type, got ${A(u.$.type)}`});u.$.originalExpr=l}return e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function pm({expr:e,env:t,context:n}){if(!E(e,k.typeof,1))throw y({token:e.token,errorMessage:`Expected "typeof" with 1 argument, got:
10748
+ ${w(i)}`});let o=yt({type:i.$.type,expectedType:void 0,expr:i,env:i.$.env??t});return e.$={type:o,value:void 0,env:i.$.env??t,pathCollection:i.$.pathCollection??[]},e}function _m({expr:e,env:t,context:n}){he(e,"<:",2);let r=e.args[0],i=e.args[1],o=S({expr:r,env:t,context:{...n}});if(!o.$||!o.$.value||!O(o.$.value))throw y({token:r.token,errorMessage:"Expected type for left-hand side expression."});t=o.$.env;let a=o.$.value;if(n.isInsideWhereClause&&!x(a.value))throw y({token:r.token,errorMessage:`In a where clause, the left-hand side of <: must be a type parameter (SomeType), got: ${w(r)} of type ${A(a.value)}`});let s=[];if(F(i)&&E(i,I.tuple))for(let f of i.args)F(f)&&E(f,"!")&&f.args.length===1?s.push({expr:f.args[0],isNegated:!0}):s.push({expr:f,isNegated:!1});else F(i)&&E(i,"!")&&i.args.length===1?s.push({expr:i.args[0],isNegated:!0}):s.push({expr:i,isNegated:!1});let l=[];for(let{expr:f,isNegated:m}of s){let g=S({expr:f,env:t,context:{...n}});if(!g.$||!g.$.value||!O(g.$.value)||!De(g.$.value.value))throw y({token:f.token,errorMessage:"Expected trait type for right-hand side expression."});t=g.$.env;let h=g.$.value.value;if(h.receiverType)throw y({token:f.token,errorMessage:"Expected trait type already has a receiver type assigned."});if(m&&!n.isInsideWhereClause)throw y({token:f.token,errorMessage:"Negated trait constraints !(Trait) are only allowed in where clauses."});l.push({traitType:h,expr:f,isNegated:m})}if(n.isInsideWhereClause&&x(a.value)){let f=a.value;for(let{traitType:m,isNegated:g}of l){let h={...m,receiverType:f};t=er({env:t,someType:f,traitType:h,isNegated:g})}return e.$={env:t,value:a,type:a.type,pathCollection:[]},e}if(l.length>1)throw y({token:i.token,errorMessage:"Multiple trait constraints (tuple form) are only allowed in where clauses."});let{traitType:u}=l[0],c=a.value;if(!x(c)&&!St({targetType:c,traitType:u,env:t}))throw y({token:e.token,errorMessage:`Type "${A(c)}" does not implement trait "${u.typeName??A(u)}".`});let _={...u,receiverType:a.value},p=ee(_);return e.$={env:t,value:p,type:p.type,pathCollection:[]},e}function pm({expr:e,env:t,context:n}){if(!E(e,I.test))throw y({token:e.token,errorMessage:`Expected test, got ${e.tag}`});if(e.args.length!==2&&e.args.length!==3)throw y({token:e.token,errorMessage:`test expects 2 or 3 arguments (name, [using clause], body), got ${e.args.length}`});let r=e.args.length===3,i=e.args[0],o=r?e.args[1]:void 0,a=r?e.args[2]:e.args[1];if(o&&!E(o,I.using))throw y({token:o.token,errorMessage:`Expected using(...) clause as second argument, got: ${w(o)}`});let s=S({expr:i,env:t,context:{...n}});if(!s.$||!s.$.value)throw y({token:i.token,errorMessage:`Failed to evaluate test name: ${w(i)}`});if(t=s.$.env,!Ve(s.$.value))throw y({token:i.token,errorMessage:`Expected string for test name, got ${w(i)}`});if(r){let l=Ae(o);o.$={env:t,type:H.type,value:H,pathCollection:[],originalExpr:l};let u=Ae(a);a.$={env:t,type:H.type,value:H,pathCollection:[],originalExpr:u}}else{let l=Ae(a),u=S({expr:a,env:t,context:{...n,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"test-block",evaluationEnv:t}}});if(!u.$)throw y({token:a.token,errorMessage:`Failed to evaluate test body: ${w(a)}`});if(!pe(u.$.type))throw y({token:a.token,errorMessage:`Test body must have 'unit' type, got ${A(u.$.type)}`});u.$.originalExpr=l}return e.$={env:t,type:H.type,value:H,pathCollection:[]},e}function fm({expr:e,env:t,context:n}){if(!E(e,k.typeof,1))throw y({token:e.token,errorMessage:`Expected "typeof" with 1 argument, got:
10731
10749
  ${w(e)}`});let r=e.args[0],i=S({expr:r,env:t,context:{...n}});if(i.$?.env&&(t=i.$.env),!i.$?.type)throw y({token:r.token,errorMessage:`Expected type for expression, got:
10732
- ${w(r)}`});let o=i.$.type,a=ee(o);return e.$={env:t,type:a.type,value:a,pathCollection:[]},e}var ql=(()=>{let e=process.env.YO_MAX_COMPTIME_LOOP_ITERATIONS;if(e!==void 0){let t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}return 1e4})();function fm(e,t){let n=et(t,"break")||et(t,"return")||et(t,"escape"),r=n||Hi(e);return{guaranteed:n,possible:r}}function Wl(e,t,n){let{possible:r}=fm(t,n);throw r?y({token:e.token,errorMessage:`Compile-time while loop exceeded the maximum iteration count (${ql}). The loop body contains a conditional \`break\`, \`return\`, or \`escape\`, but the loop did not terminate within the limit.
10750
+ ${w(r)}`});let o=i.$.type,a=ee(o);return e.$={env:t,type:a.type,value:a,pathCollection:[]},e}var ql=(()=>{let e=process.env.YO_MAX_COMPTIME_LOOP_ITERATIONS;if(e!==void 0){let t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}return 1e4})();function dm(e,t){let n=et(t,"break")||et(t,"return")||et(t,"escape"),r=n||Hi(e);return{guaranteed:n,possible:r}}function Wl(e,t,n){let{possible:r}=dm(t,n);throw r?y({token:e.token,errorMessage:`Compile-time while loop exceeded the maximum iteration count (${ql}). The loop body contains a conditional \`break\`, \`return\`, or \`escape\`, but the loop did not terminate within the limit.
10733
10751
  If this is an infinite runtime loop, use \`while runtime(true), { ... }\` instead.
10734
10752
  To increase the limit, set the YO_MAX_COMPTIME_LOOP_ITERATIONS environment variable.`}):y({token:e.token,errorMessage:"Infinite compile-time while loop detected. The condition is compile-time `true` but the loop body has no `break`, `return`, or `escape` to terminate it.\nIf you need an infinite runtime loop, use `while runtime(true), { ... }` instead of `while true, { ... }`.\nTo increase the limit, set the YO_MAX_COMPTIME_LOOP_ITERATIONS environment variable."})}function ns({expr:e,env:t,context:n,_comptimeIterationCount:r=0}){if(e.args.length!==2&&e.args.length!==3)throw y({token:e.token,errorMessage:`Expected 2 or 3 arguments for while loop, got ${e.args.length}`});let i=e.args[0],o,a;e.args.length===3?(o=e.args[1],a=e.args[2]):a=e.args[1];let s=ht({expr:i,env:t,context:{...n},variablesToAdd:[]});if(!s.$)throw y({token:i.token,errorMessage:`Failed to evaluate the condition expression:
10735
10753
  ${w(i)}`});if(!cn(s.$.type))throw y({token:i.token,errorMessage:`Expected bool type for condition expression, got:
10736
10754
  ${w(i)}`});let l=s.$.value,u=l!==void 0;if(Re(l)&&l.value===!1)return e.$={env:t,pathCollection:[],type:H.type,value:u?H:void 0},e;{let c=ht({expr:a,env:t,context:{...n,isEvaluatingLoopBody:{kind:"while",env:t}},variablesToAdd:[]});if(!c.$)throw y({token:a.token,errorMessage:`Failed to evaluate the body expression:
10737
10755
  ${w(a)}`});if(nt(c.$.controlFlow)){if(et(c.$.controlFlow,"return")||et(c.$.controlFlow,"escape"))if(Re(l)&&l.value===!0){let f={};et(c.$.controlFlow,"return")&&(f.return=!0),et(c.$.controlFlow,"escape")&&(f.escape=!0),e.$={env:c.$.env,pathCollection:c.$.pathCollection,type:c.$.type,value:c.$.value,controlFlow:f}}else e.$={env:t,pathCollection:[],type:H.type,value:u?H:void 0};else if(et(c.$.controlFlow,"break"))e.$={env:c.$.env,pathCollection:[],type:H.type,value:u?H:void 0};else if(et(c.$.controlFlow,"continue")){let f=c.$.env;if(o){let m=S({expr:o,env:f,context:{...n}});if(!m.$)throw y({token:o.token,errorMessage:`Failed to evaluate the step expression:
10738
- ${w(o)}`});f=m.$.env}if(Re(l))return ns({expr:e,env:f,context:{...n},_comptimeIterationCount:r+1});e.$={env:f,pathCollection:[],type:H.type,value:u?H:void 0}}return e}if(!Re(l)||l.value!==!0?!1:!!(dt(i,"true")||E(i,"begin")&&i.args.length===1&&dt(i.args[0],"true"))){let{guaranteed:f,possible:m}=fm(a,c.$.controlFlow);if(!f&&!m&&Wl(e,a,c.$.controlFlow),!f&&m)return e.$={env:c.$.env,pathCollection:[],type:H.type,value:void 0},e}if(!pe(c.$.type))throw y({token:a.token,errorMessage:`Expected the while loop body to return unit, but got:
10756
+ ${w(o)}`});f=m.$.env}if(Re(l))return ns({expr:e,env:f,context:{...n},_comptimeIterationCount:r+1});e.$={env:f,pathCollection:[],type:H.type,value:u?H:void 0}}return e}if(!Re(l)||l.value!==!0?!1:!!(dt(i,"true")||E(i,"begin")&&i.args.length===1&&dt(i.args[0],"true"))){let{guaranteed:f,possible:m}=dm(a,c.$.controlFlow);if(!f&&!m&&Wl(e,a,c.$.controlFlow),!f&&m)return e.$={env:c.$.env,pathCollection:[],type:H.type,value:void 0},e}if(!pe(c.$.type))throw y({token:a.token,errorMessage:`Expected the while loop body to return unit, but got:
10739
10757
  ${A(c.$.type)}`});let p=c.$.value===void 0;if(t=c.$.env,o){let f=S({expr:o,env:t,context:{...n}});if(!f.$)throw y({token:o.token,errorMessage:`Failed to evaluate the step expression:
10740
- ${w(o)}`});t=f.$.env}if(Re(l)&&l.value===!0&&p){let f=Ae(i),g=ht({expr:f,env:t,context:{...n},variablesToAdd:[]}).$?.value;if(Re(g)){let h=[a],d=t,v=g.value;for(let T=1;v&&T<ql;T++){let $=Ae(a),C=ht({expr:$,env:d,context:{...n,isEvaluatingLoopBody:{kind:"while",env:d}},variablesToAdd:[]});if(!C.$)break;if(h.push($),d=C.$.env,o){let N=Ae(o),B=S({expr:N,env:d,context:{...n}});if(!B.$)break;d=B.$.env}let L=Ae(i),R=ht({expr:L,env:d,context:{...n},variablesToAdd:[]}).$?.value;if(Re(R)&&R.value===!1)v=!1;else if(Re(R)&&R.value===!0)v=!0;else return e.$={env:d,pathCollection:[],type:H.type,value:void 0,comptimeUnrolledBodies:h},e}if(!v)return e.$={env:d,pathCollection:[],type:H.type,value:void 0,comptimeUnrolledBodies:h},e}Wl(e,a,c.$.controlFlow)}if(Re(l)&&l.value===!0){let f=r+1;return f>=ql&&Wl(e,a,c.$.controlFlow),ns({expr:e,env:t,context:{...n},_comptimeIterationCount:f})}else return e.$={env:t,pathCollection:[],type:H.type,value:u?H:void 0},e}}function dm(e){let t=process.env[e];return t==="1"||t?.toLowerCase()==="true"}var Vh=dm("YO_DEBUG_EVAL")||dm("YO_DEBUG_EVAL_PROFILE"),mm=globalThis,mo=mm.__yoEvalProfilerState??(mm.__yoEvalProfilerState={evalCount:0,evalStart:0});function Kr({expr:e,env:t,context:n}){if(Vh&&(mo.evalStart||(mo.evalStart=Date.now()),mo.evalCount++,mo.evalCount%1e5===0&&console.log(`[EVAL] ${mo.evalCount} calls, ${Date.now()-mo.evalStart}ms elapsed`)),z(e))switch(e.token.type){case"identifier":case"operator":return ts({expr:e,env:t,context:{...n},throwErrorOnUndefined:!0});case"integer":return Pd(e,t,{...n});case"float":return Rd(e,t,{...n});case"string":return Ud(e,t);case"char":return xd(e,t);case"bool":return Vd(e,t);default:throw y({token:e.token,errorMessage:`(1) Evaluating the expression (tag: ${e.tag}, token: ${e.token.type}) below is not implemented:
10741
- ${w(e)}`})}else if(E(e,":",2)){let{expr:r}=es({expr:e,env:t,context:n});return r}else{if(E(e,":=",2)||E(e,"::",2))return im({expr:e,env:t,context:n});if(E(e,"=",2))return Bd({expr:e,env:t,context:n});if(E(e,"->",2))return F(e.args[0])&&(E(e.args[0],I.fn)||E(e.args[0],I.unsafe_fn))?qa({expr:e,env:t,context:{...n,isUnsafeFunctionType:E(e.args[0],I.unsafe_fn)}}):F(e.args[0])&&E(e.args[0],I.Fn)?Ed({expr:e,env:t,context:{...n}}):Ja({expr:e,env:t,context:{...n}});if(E(e,"=>",2))return F(e.args[0])&&E(e.args[0],I.fn)?yd({expr:e,env:t,context:{...n}}):Ja({expr:e,env:t,context:{...n}});if(E(e,"=>>",2))return Ja({expr:e,env:t,context:{...n}});if(E(e,I.recur))return lm({expr:e,env:t,context:{...n}});if(E(e,I.runtime))return um({expr:e,env:t,context:{...n}});if(E(e,I.extern))return Yd({expr:e,env:t,context:{...n}});if(E(e,I.c_include))return Gd({expr:e,env:t,context:{...n}});if(E(e,I.test))return _m({expr:e,env:t,context:{...n}});if(E(e,I.cond))return Wd({expr:e,env:t,context:{...n}});if(E(e,I.match))return om({expr:e,env:t,context:{...n}});if(E(e,I.tuple))return zd({expr:e,env:t,context:{...n}});if(E(e,I.array))return Nd({expr:e,env:t,context:{...n}});if(E(e,I.comptime_list))return Dd({expr:e,env:t,context:{...n}});if(E(e,I.dyn))return Od({expr:e,env:t,context:{...n}});if(E(e,I.struct))return _o({expr:e,env:t,context:{...n}});if(E(e,I.object))return kd({expr:e,env:t,context:{...n}});if(E(e,I.newtype))return bd({expr:e,env:t,context:{...n}});if(E(e,I.enum))return Td({expr:e,env:t,context:{...n}});if(E(e,I.union))return Sd({expr:e,env:t,context:{...n}});if(E(e,"."))return sm({expr:e,env:t,context:{...n}});if(E(e,I.begin))return ht({expr:e,env:t,context:{...n},variablesToAdd:[]});if(E(e,I.module))return Cd({expr:e,env:t,context:{...n}});if(E(e,I.trait))return Ad({expr:e,env:t,context:{...n}});if(E(e,I.Impl))return Pf({expr:e,env:t,context:{...n}});if(E(e,I.impl))return Xu({expr:e,env:t,context:{...n}});if(E(e,k.typeof))return pm({expr:e,env:t,context:{...n}});if(E(e,k.sizeof))return nd({expr:e,env:t,context:{...n}});if(E(e,k.alignof))return Tp({expr:e,env:t,context:{...n}});if(E(e,k.typeid))return ud({expr:e,env:t,context:{...n}});if(E(e,k.downcast))return tf({expr:e,env:t,context:{...n}});if(E(e,k.rc))return td({expr:e,env:t,context:{...n}});if(E(e,"<:"))return cm({expr:e,env:t,context:{...n}});if(E(e,k.the))return rd({expr:e,env:t,context:{...n}});if(E(e,I.import))return nm({expr:e,env:t,context:{...n},stdPath:n.stdPath});if(E(e,I.open))return am({expr:e,env:t,context:{...n}});if(E(e,I.Ptr,1))return dd({expr:e,env:t,context:{...n}});if(E(e,I.Iso,1))return Cf({expr:e,env:t,context:{...n}});if(E(e,I.Arc,1))return cf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_address_of,1))return ed({expr:e,env:t,context:{...n}});if(E(e,I.Tuple))return Id({expr:e,env:t,context:{...n}});if(E(e,I.Array))return md({expr:e,env:t,context:{...n}});if(E(e,k.__yo_array_fill,2))return $p({expr:e,env:t,context:{...n}});if(E(e,I.Slice))return wd({expr:e,env:t,context:{...n}});if(E(e,I.ComptimeList))return gd({expr:e,env:t,context:{...n}});if(E(e,I.Future))return $d({expr:e,env:t,context:{...n}});if(E(e,I.Concrete))return hd({expr:e,env:t,context:{...n}});if(E(e,I.Dyn))return vd({expr:e,env:t,context:{...n}});if(E(e,k.comptime_expect_error))return kp({expr:e,env:t,context:{...n}});if(E(e,k.comptime_assert))return Cp({expr:e,env:t,context:{...n}});if(E(e,k.comptime_fn))return wp({expr:e,env:t,context:{...n}});if(E(e,k.comptime_print))return Mp({expr:e,env:t,context:{...n}});if(E(e,k.panic))return Bf({expr:e,env:t,context:{...n}});if(E(e,k.asm))return jf({expr:e,env:t,context:{...n}});if(E(e,k.global_asm))return Kf({expr:e,env:t,context:{...n}});if(E(e,k.macro_expand))return zf({expr:e,env:t,context:{...n}});if(E(e,I.op_and)||E(e,I.op_or))return Ep({expr:e,env:t,context:{...n}});if(E(e,I.escape))return qd({expr:e,env:t,context:{...n}});if(E(e,k.consume))return Rp({expr:e,env:t,context:{...n}});if(E(e,k.___drop))return Af({expr:e,env:t,context:{...n}});if(E(e,k.___dup))return If({expr:e,env:t,context:{...n}});if(E(e,k.__yo_decr_rc))return Pp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_incr_rc))return Up({expr:e,env:t,context:{...n}});if(E(e,k.__yo_decr_rc_atomic))return Bp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_incr_rc_atomic))return zp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_iso_extract))return jp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_iso_dispose))return Kp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_arc_dispose))return Xp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_drop_array_element))return Qp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dup_array_element))return Zp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_drop_tuple_element))return Jp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dup_tuple_element))return ef({expr:e,env:t,context:{...n}});if(E(e,k.__yo_rc_own))return Gp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dyn_drop))return Wp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dyn_dup))return qp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_sometype_drop))return Yp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_sometype_dup))return Hp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_gc_collect))return Of({expr:e,env:t,context:{...n}});if(E(e,I.quote))return Uf({expr:e,env:t,context:{...n}});if(E(e,I.gensym))return Rf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_is_atom))return Sf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_is_fn_call))return Nf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_get_callee))return Vf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_get_args))return xf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_to_string))return Df({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_eq))return Mf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_car))return Fp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_cdr))return Lp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_cons))return Ap({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_append))return Ip({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_length))return Sp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_element_type))return Np({expr:e,env:t,context:{...n}});if(F(e)&&e.func.tag==="Atom"&&typeof e.func.token.value=="string"&&(e.func.token.value.startsWith("__yo_comptime_u8_")||e.func.token.value.startsWith("__yo_comptime_i8_")||e.func.token.value.startsWith("__yo_comptime_u16_")||e.func.token.value.startsWith("__yo_comptime_i16_")||e.func.token.value.startsWith("__yo_comptime_u32_")||e.func.token.value.startsWith("__yo_comptime_i32_")||e.func.token.value.startsWith("__yo_comptime_u64_")||e.func.token.value.startsWith("__yo_comptime_i64_")||e.func.token.value.startsWith("__yo_comptime_usize_")||e.func.token.value.startsWith("__yo_comptime_isize_")||e.func.token.value.startsWith("__yo_comptime_f32_")||e.func.token.value.startsWith("__yo_comptime_f64_")||e.func.token.value.startsWith("__yo_comptime_int_")||e.func.token.value.startsWith("__yo_comptime_float_")))return Dp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_bool_and,2)||E(e,k.__yo_comptime_bool_or,2)||E(e,k.__yo_comptime_bool_eq,2)||E(e,k.__yo_comptime_bool_neq,2)||E(e,k.__yo_comptime_bool_not,1)||E(e,k.__yo_comptime_bool_to_comptime_string,1))return bp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_string_concat,2)||E(e,k.__yo_comptime_string_eq,2)||E(e,k.__yo_comptime_string_neq,2)||E(e,k.__yo_comptime_string_lt,2)||E(e,k.__yo_comptime_string_lte,2)||E(e,k.__yo_comptime_string_gt,2)||E(e,k.__yo_comptime_string_gte,2)||E(e,k.__yo_comptime_string_length,1)||E(e,k.__yo_comptime_string_to_upper,1)||E(e,k.__yo_comptime_string_to_lower,1)||E(e,k.__yo_comptime_string_slice))return Op({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_to_comptime_string,1))return id({expr:e,env:t,context:{...n}});if(E(e,k.__yo_are_types_compatible,2))return od({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_contains_rc_type,1))return ad({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_can_form_rc_cycle,1))return sd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_impls,2))return ld({expr:e,env:t,context:{...n}});if(E(e,k.__yo_var_print_info,1))return _d({expr:e,env:t,context:{...n}});if(E(e,k.__yo_var_is_owning_the_rc_value))return pd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_var_has_other_aliases))return fd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_process_platform)||E(e,k.__yo_process_arch))return Xf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_build_executable)||E(e,k.__yo_build_static_library)||E(e,k.__yo_build_shared_library)||E(e,k.__yo_build_test)||E(e,k.__yo_build_run)||E(e,k.__yo_build_step)||E(e,k.__yo_build_step_depend_on)||E(e,k.__yo_build_target_host)||E(e,k.__yo_build_target_parse)||E(e,k.__yo_build_dependency)||E(e,k.__yo_build_path_dependency)||E(e,k.__yo_build_system_library)||E(e,k.__yo_build_link)||E(e,k.__yo_build_link_system_library)||E(e,k.__yo_build_option)||E(e,k.__yo_build_dep_artifact)||E(e,k.__yo_build_module)||E(e,k.__yo_build_module_link)||E(e,k.__yo_build_add_import)||E(e,k.__yo_build_dep_module)){for(let r=0;r<e.args.length;r++)e.args[r]=Kr({expr:e.args[r],env:t,context:{...n}});return Jf({expr:e,env:t,context:{...n}})}else return E(e,I.while)?ns({expr:e,env:t,context:{...n}}):E(e,k.va_start)?cd({expr:e,env:t,context:{...n}}):Rn({expr:e,env:t,context:{...n}})}}function Dh(e){let t=e;for(;;){let n=ia.join(t,"std");if(xh(n))return n;let r=ia.dirname(t);if(r===t)break;t=r}return ia.join(__dirname,"../std")}var ym=class{constructor(t){this.modules=new Map;this.dependencies=new Map;this.dependents=new Map;this.allowPartialModule=t?.allowPartialModule??!1,this.stdPath=t?.stdPath??Dh(__dirname),this.codeGenratorC=new za,jl(Kr),hc(vp)}getRelativePath(t){let n=t.match(/\/std\/(.+)$/);if(n)return`std/${n[1]}`;let r=t.match(/\/tests\/(.+)$/);return r?`tests/${r[1]}`:null}isWorkspaceModule(t){return!t.includes("/extensions/")&&!t.includes("/.vscode/")}findExtensionDuplicates(t){if(!this.isWorkspaceModule(t))return[];let n=this.getRelativePath(t);if(!n)return[];let r=[];for(let[i]of this.modules)i!==t&&!this.isWorkspaceModule(i)&&this.getRelativePath(i)===n&&r.push(i);if(n.startsWith("std/"))for(let[i]of this.modules)!this.isWorkspaceModule(i)&&(i.endsWith("/std/prelude.yo")||i.endsWith("/prelude.yo"))&&!r.includes(i)&&r.push(i);return r}deleteModuleAndDependents(t){let n=this.getDependentModules(t);for(let r of n)zo(r),Uo(r),this.clearDependencies(r),ya(r),this.modules.delete(r);zo(t),Uo(t),this.clearDependencies(t),ya(t),this.modules.delete(t)}addDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n),this.dependents.has(n)||this.dependents.set(n,new Set),this.dependents.get(n).add(t)}getDependentModules(t){let n=new Set,r=[t];for(;r.length>0;){let i=r.pop(),o=this.dependents.get(i);if(o)for(let a of o)n.has(a)||(n.add(a),r.push(a))}return n}clearDependencies(t){let n=this.dependencies.get(t);if(n)for(let r of n){let i=this.dependents.get(r);i&&i.delete(t)}this.dependencies.delete(t)}resetAllState(){for(let t of this.modules.keys())zo(t),Uo(t),ya(t);this.modules.clear(),this.dependencies.clear(),this.dependents.clear(),el(),rc(),lu()}loadModule(t,n,r){if(!t.match(/^file:\/\//))throw new Error(`Invalid file protocol: ${t}. Only file:// is supported for now. `);r&&this.addDependency(r,t);let i=this.modules.get(t);if(i)return{moduleValue:i.moduleValue,moduleError:i.moduleError};let o=this.findExtensionDuplicates(t);for(let c of o)this.deleteModuleAndDependents(c);let a=t,s=new Go({modulePath:t,stdPath:this.stdPath,loadModule:c=>this.loadModule(c,void 0,a),inputString:n,allowPartialModule:this.allowPartialModule}),l=s.getModuleValue(),u=s.getModuleError();return this.modules.set(t,{moduleValue:l,moduleError:u,evaluator:s}),{moduleValue:l,moduleError:u}}deleteModule(t){if(!t.match(/^file:\/\//))throw new Error(`Invalid file protocol: ${t}. Only file:// is supported for now. `);let n=[t];if(this.isWorkspaceModule(t))for(let[i]of this.modules)!this.isWorkspaceModule(i)&&!n.includes(i)&&n.push(i);if(t.endsWith("/std/prelude.yo")||t.endsWith("/prelude.yo"))for(let[i]of this.modules)(i.endsWith("/std/prelude.yo")||i.endsWith("/prelude.yo"))&&i!==t&&!n.includes(i)&&n.push(i);for(let i of n)this.deleteModuleAndDependents(i)}compileModule(t,{emitC:n,debugGc:r,debugParallelism:i,debugAsyncAwait:o,allocator:a,isLibrary:s}={}){let{moduleValue:l,moduleError:u}=this.loadModule(t);if(u)throw u.toString();if(!this.modules.get(t))throw new Error(`Module data not found for ${t}`);this.codeGenratorC.compileModule(t,l,{debugGc:r,debugParallelism:i,debugAsyncAwait:o,allocator:a,isLibrary:s}),n&&console.log(this.codeGenratorC.print())}getGeneratedCode(){return this.codeGenratorC.print()}getExportedFunctionNames(){return this.codeGenratorC.getExportedFunctionNames()}get needsIntelAsmSyntax(){return this.codeGenratorC.needsIntelAsmSyntax}};export{Ci as Emitter,is as IdentifierRegex,ym as ModuleManager,rs as Operators,ae as PlaceholderToken,Rh as RAIIToken,jt as TokenType,yo as charIsOperator,el as clearAllGlobalImplState,Uo as clearGenericImplsFromModule,zo as clearImplsFromModule,f$ as debug,Hl as findMatchingBracketTokenIndex,Jt as generateExprFromCode,ir as stringIsOperator,Kl as tokenize};
10758
+ ${w(o)}`});t=f.$.env}if(Re(l)&&l.value===!0&&p){let f=Ae(i),g=ht({expr:f,env:t,context:{...n},variablesToAdd:[]}).$?.value;if(Re(g)){let h=[a],d=t,v=g.value;for(let T=1;v&&T<ql;T++){let $=Ae(a),C=ht({expr:$,env:d,context:{...n,isEvaluatingLoopBody:{kind:"while",env:d}},variablesToAdd:[]});if(!C.$)break;if(h.push($),d=C.$.env,o){let N=Ae(o),B=S({expr:N,env:d,context:{...n}});if(!B.$)break;d=B.$.env}let L=Ae(i),R=ht({expr:L,env:d,context:{...n},variablesToAdd:[]}).$?.value;if(Re(R)&&R.value===!1)v=!1;else if(Re(R)&&R.value===!0)v=!0;else return e.$={env:d,pathCollection:[],type:H.type,value:void 0,comptimeUnrolledBodies:h},e}if(!v)return e.$={env:d,pathCollection:[],type:H.type,value:void 0,comptimeUnrolledBodies:h},e}Wl(e,a,c.$.controlFlow)}if(Re(l)&&l.value===!0){let f=r+1;return f>=ql&&Wl(e,a,c.$.controlFlow),ns({expr:e,env:t,context:{...n},_comptimeIterationCount:f})}else return e.$={env:t,pathCollection:[],type:H.type,value:u?H:void 0},e}}function mm(e){let t=process.env[e];return t==="1"||t?.toLowerCase()==="true"}var xh=mm("YO_DEBUG_EVAL")||mm("YO_DEBUG_EVAL_PROFILE"),ym=globalThis,mo=ym.__yoEvalProfilerState??(ym.__yoEvalProfilerState={evalCount:0,evalStart:0});function Kr({expr:e,env:t,context:n}){if(xh&&(mo.evalStart||(mo.evalStart=Date.now()),mo.evalCount++,mo.evalCount%1e5===0&&console.log(`[EVAL] ${mo.evalCount} calls, ${Date.now()-mo.evalStart}ms elapsed`)),z(e))switch(e.token.type){case"identifier":case"operator":return ts({expr:e,env:t,context:{...n},throwErrorOnUndefined:!0});case"integer":return Ud(e,t,{...n});case"float":return Pd(e,t,{...n});case"string":return zd(e,t);case"char":return Dd(e,t);case"bool":return xd(e,t);default:throw y({token:e.token,errorMessage:`(1) Evaluating the expression (tag: ${e.tag}, token: ${e.token.type}) below is not implemented:
10759
+ ${w(e)}`})}else if(E(e,":",2)){let{expr:r}=es({expr:e,env:t,context:n});return r}else{if(E(e,":=",2)||E(e,"::",2))return om({expr:e,env:t,context:n});if(E(e,"=",2))return Gd({expr:e,env:t,context:n});if(E(e,"->",2))return F(e.args[0])&&(E(e.args[0],I.fn)||E(e.args[0],I.unsafe_fn))?qa({expr:e,env:t,context:{...n,isUnsafeFunctionType:E(e.args[0],I.unsafe_fn)}}):F(e.args[0])&&E(e.args[0],I.Fn)?$d({expr:e,env:t,context:{...n}}):Ja({expr:e,env:t,context:{...n}});if(E(e,"=>",2))return F(e.args[0])&&E(e.args[0],I.fn)?gd({expr:e,env:t,context:{...n}}):Ja({expr:e,env:t,context:{...n}});if(E(e,"=>>",2))return Ja({expr:e,env:t,context:{...n}});if(E(e,I.recur))return um({expr:e,env:t,context:{...n}});if(E(e,I.runtime))return cm({expr:e,env:t,context:{...n}});if(E(e,I.extern))return Hd({expr:e,env:t,context:{...n}});if(E(e,I.c_include))return Wd({expr:e,env:t,context:{...n}});if(E(e,I.test))return pm({expr:e,env:t,context:{...n}});if(E(e,I.cond))return qd({expr:e,env:t,context:{...n}});if(E(e,I.match))return am({expr:e,env:t,context:{...n}});if(E(e,I.tuple))return Bd({expr:e,env:t,context:{...n}});if(E(e,I.array))return Vd({expr:e,env:t,context:{...n}});if(E(e,I.comptime_list))return Md({expr:e,env:t,context:{...n}});if(E(e,I.dyn))return Rd({expr:e,env:t,context:{...n}});if(E(e,I.struct))return _o({expr:e,env:t,context:{...n}});if(E(e,I.object))return wd({expr:e,env:t,context:{...n}});if(E(e,I.newtype))return kd({expr:e,env:t,context:{...n}});if(E(e,I.enum))return Ed({expr:e,env:t,context:{...n}});if(E(e,I.union))return Nd({expr:e,env:t,context:{...n}});if(E(e,"."))return lm({expr:e,env:t,context:{...n}});if(E(e,I.begin))return ht({expr:e,env:t,context:{...n},variablesToAdd:[]});if(E(e,I.module))return bd({expr:e,env:t,context:{...n}});if(E(e,I.trait))return Id({expr:e,env:t,context:{...n}});if(E(e,I.Impl))return Uf({expr:e,env:t,context:{...n}});if(E(e,I.impl))return Xu({expr:e,env:t,context:{...n}});if(E(e,k.typeof))return fm({expr:e,env:t,context:{...n}});if(E(e,k.sizeof))return rd({expr:e,env:t,context:{...n}});if(E(e,k.alignof))return Ep({expr:e,env:t,context:{...n}});if(E(e,k.typeid))return cd({expr:e,env:t,context:{...n}});if(E(e,k.downcast))return nf({expr:e,env:t,context:{...n}});if(E(e,k.rc))return nd({expr:e,env:t,context:{...n}});if(E(e,"<:"))return _m({expr:e,env:t,context:{...n}});if(E(e,k.the))return id({expr:e,env:t,context:{...n}});if(E(e,I.import))return rm({expr:e,env:t,context:{...n},stdPath:n.stdPath});if(E(e,I.open))return sm({expr:e,env:t,context:{...n}});if(E(e,I.Ptr,1))return md({expr:e,env:t,context:{...n}});if(E(e,I.Iso,1))return bf({expr:e,env:t,context:{...n}});if(E(e,I.Arc,1))return _f({expr:e,env:t,context:{...n}});if(E(e,k.__yo_address_of,1))return td({expr:e,env:t,context:{...n}});if(E(e,I.Tuple))return Sd({expr:e,env:t,context:{...n}});if(E(e,I.Array))return yd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_array_fill,2))return Cp({expr:e,env:t,context:{...n}});if(E(e,I.Slice))return Fd({expr:e,env:t,context:{...n}});if(E(e,I.ComptimeList))return hd({expr:e,env:t,context:{...n}});if(E(e,I.Future))return Cd({expr:e,env:t,context:{...n}});if(E(e,I.Concrete))return vd({expr:e,env:t,context:{...n}});if(E(e,I.Dyn))return Td({expr:e,env:t,context:{...n}});if(E(e,k.comptime_expect_error))return wp({expr:e,env:t,context:{...n}});if(E(e,k.comptime_assert))return bp({expr:e,env:t,context:{...n}});if(E(e,k.comptime_fn))return Fp({expr:e,env:t,context:{...n}});if(E(e,k.comptime_print))return Op({expr:e,env:t,context:{...n}});if(E(e,k.panic))return Gf({expr:e,env:t,context:{...n}});if(E(e,k.asm))return Kf({expr:e,env:t,context:{...n}});if(E(e,k.global_asm))return Xf({expr:e,env:t,context:{...n}});if(E(e,k.macro_expand))return Bf({expr:e,env:t,context:{...n}});if(E(e,I.op_and)||E(e,I.op_or))return $p({expr:e,env:t,context:{...n}});if(E(e,I.escape))return Yd({expr:e,env:t,context:{...n}});if(E(e,k.consume))return Pp({expr:e,env:t,context:{...n}});if(E(e,k.___drop))return If({expr:e,env:t,context:{...n}});if(E(e,k.___dup))return Sf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_decr_rc))return Up({expr:e,env:t,context:{...n}});if(E(e,k.__yo_incr_rc))return zp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_decr_rc_atomic))return Gp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_incr_rc_atomic))return Bp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_iso_extract))return Kp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_iso_dispose))return Xp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_arc_dispose))return Qp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_drop_array_element))return Zp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dup_array_element))return Jp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_drop_tuple_element))return ef({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dup_tuple_element))return tf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_rc_own))return Wp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dyn_drop))return qp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_dyn_dup))return Yp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_sometype_drop))return Hp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_sometype_dup))return jp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_gc_collect))return Rf({expr:e,env:t,context:{...n}});if(E(e,I.quote))return zf({expr:e,env:t,context:{...n}});if(E(e,I.gensym))return Pf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_is_atom))return Nf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_is_fn_call))return Vf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_get_callee))return xf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_get_args))return Df({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_to_string))return Mf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_expr_eq))return Of({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_car))return Lp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_cdr))return Ap({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_cons))return Ip({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_append))return Sp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_length))return Np({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_list_element_type))return Vp({expr:e,env:t,context:{...n}});if(F(e)&&e.func.tag==="Atom"&&typeof e.func.token.value=="string"&&(e.func.token.value.startsWith("__yo_comptime_u8_")||e.func.token.value.startsWith("__yo_comptime_i8_")||e.func.token.value.startsWith("__yo_comptime_u16_")||e.func.token.value.startsWith("__yo_comptime_i16_")||e.func.token.value.startsWith("__yo_comptime_u32_")||e.func.token.value.startsWith("__yo_comptime_i32_")||e.func.token.value.startsWith("__yo_comptime_u64_")||e.func.token.value.startsWith("__yo_comptime_i64_")||e.func.token.value.startsWith("__yo_comptime_usize_")||e.func.token.value.startsWith("__yo_comptime_isize_")||e.func.token.value.startsWith("__yo_comptime_f32_")||e.func.token.value.startsWith("__yo_comptime_f64_")||e.func.token.value.startsWith("__yo_comptime_int_")||e.func.token.value.startsWith("__yo_comptime_float_")))return Mp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_bool_and,2)||E(e,k.__yo_comptime_bool_or,2)||E(e,k.__yo_comptime_bool_eq,2)||E(e,k.__yo_comptime_bool_neq,2)||E(e,k.__yo_comptime_bool_not,1)||E(e,k.__yo_comptime_bool_to_comptime_string,1))return kp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_comptime_string_concat,2)||E(e,k.__yo_comptime_string_eq,2)||E(e,k.__yo_comptime_string_neq,2)||E(e,k.__yo_comptime_string_lt,2)||E(e,k.__yo_comptime_string_lte,2)||E(e,k.__yo_comptime_string_gt,2)||E(e,k.__yo_comptime_string_gte,2)||E(e,k.__yo_comptime_string_length,1)||E(e,k.__yo_comptime_string_to_upper,1)||E(e,k.__yo_comptime_string_to_lower,1)||E(e,k.__yo_comptime_string_slice))return Rp({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_to_comptime_string,1))return od({expr:e,env:t,context:{...n}});if(E(e,k.__yo_are_types_compatible,2))return ad({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_contains_rc_type,1))return sd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_can_form_rc_cycle,1))return ld({expr:e,env:t,context:{...n}});if(E(e,k.__yo_type_impls,2))return ud({expr:e,env:t,context:{...n}});if(E(e,k.__yo_var_print_info,1))return pd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_var_is_owning_the_rc_value))return fd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_var_has_other_aliases))return dd({expr:e,env:t,context:{...n}});if(E(e,k.__yo_process_platform)||E(e,k.__yo_process_arch))return Qf({expr:e,env:t,context:{...n}});if(E(e,k.__yo_build_executable)||E(e,k.__yo_build_static_library)||E(e,k.__yo_build_shared_library)||E(e,k.__yo_build_test)||E(e,k.__yo_build_run)||E(e,k.__yo_build_step)||E(e,k.__yo_build_step_depend_on)||E(e,k.__yo_build_target_host)||E(e,k.__yo_build_target_parse)||E(e,k.__yo_build_dependency)||E(e,k.__yo_build_path_dependency)||E(e,k.__yo_build_system_library)||E(e,k.__yo_build_link)||E(e,k.__yo_build_link_system_library)||E(e,k.__yo_build_option)||E(e,k.__yo_build_dep_artifact)||E(e,k.__yo_build_module)||E(e,k.__yo_build_module_link)||E(e,k.__yo_build_add_import)||E(e,k.__yo_build_dep_module)){for(let r=0;r<e.args.length;r++)e.args[r]=Kr({expr:e.args[r],env:t,context:{...n}});return ed({expr:e,env:t,context:{...n}})}else return E(e,I.while)?ns({expr:e,env:t,context:{...n}}):E(e,k.va_start)?_d({expr:e,env:t,context:{...n}}):Rn({expr:e,env:t,context:{...n}})}}function Mh(e){let t=e;for(;;){let n=ia.join(t,"std");if(Dh(n))return n;let r=ia.dirname(t);if(r===t)break;t=r}return ia.join(__dirname,"../std")}var gm=class{constructor(t){this.modules=new Map;this.dependencies=new Map;this.dependents=new Map;this.allowPartialModule=t?.allowPartialModule??!1,this.stdPath=t?.stdPath??Mh(__dirname),this.codeGenratorC=new za,jl(Kr),hc(Tp)}getRelativePath(t){let n=t.match(/\/std\/(.+)$/);if(n)return`std/${n[1]}`;let r=t.match(/\/tests\/(.+)$/);return r?`tests/${r[1]}`:null}isWorkspaceModule(t){return!t.includes("/extensions/")&&!t.includes("/.vscode/")}findExtensionDuplicates(t){if(!this.isWorkspaceModule(t))return[];let n=this.getRelativePath(t);if(!n)return[];let r=[];for(let[i]of this.modules)i!==t&&!this.isWorkspaceModule(i)&&this.getRelativePath(i)===n&&r.push(i);if(n.startsWith("std/"))for(let[i]of this.modules)!this.isWorkspaceModule(i)&&(i.endsWith("/std/prelude.yo")||i.endsWith("/prelude.yo"))&&!r.includes(i)&&r.push(i);return r}deleteModuleAndDependents(t){let n=this.getDependentModules(t);for(let r of n)zo(r),Uo(r),this.clearDependencies(r),ya(r),this.modules.delete(r);zo(t),Uo(t),this.clearDependencies(t),ya(t),this.modules.delete(t)}addDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n),this.dependents.has(n)||this.dependents.set(n,new Set),this.dependents.get(n).add(t)}getDependentModules(t){let n=new Set,r=[t];for(;r.length>0;){let i=r.pop(),o=this.dependents.get(i);if(o)for(let a of o)n.has(a)||(n.add(a),r.push(a))}return n}clearDependencies(t){let n=this.dependencies.get(t);if(n)for(let r of n){let i=this.dependents.get(r);i&&i.delete(t)}this.dependencies.delete(t)}resetAllState(){for(let t of this.modules.keys())zo(t),Uo(t),ya(t);this.modules.clear(),this.dependencies.clear(),this.dependents.clear(),el(),rc(),lu()}loadModule(t,n,r){if(!t.match(/^file:\/\//))throw new Error(`Invalid file protocol: ${t}. Only file:// is supported for now. `);r&&this.addDependency(r,t);let i=this.modules.get(t);if(i)return{moduleValue:i.moduleValue,moduleError:i.moduleError};let o=this.findExtensionDuplicates(t);for(let c of o)this.deleteModuleAndDependents(c);let a=t,s=new Go({modulePath:t,stdPath:this.stdPath,loadModule:c=>this.loadModule(c,void 0,a),inputString:n,allowPartialModule:this.allowPartialModule}),l=s.getModuleValue(),u=s.getModuleError();return this.modules.set(t,{moduleValue:l,moduleError:u,evaluator:s}),{moduleValue:l,moduleError:u}}deleteModule(t){if(!t.match(/^file:\/\//))throw new Error(`Invalid file protocol: ${t}. Only file:// is supported for now. `);let n=[t];if(this.isWorkspaceModule(t))for(let[i]of this.modules)!this.isWorkspaceModule(i)&&!n.includes(i)&&n.push(i);if(t.endsWith("/std/prelude.yo")||t.endsWith("/prelude.yo"))for(let[i]of this.modules)(i.endsWith("/std/prelude.yo")||i.endsWith("/prelude.yo"))&&i!==t&&!n.includes(i)&&n.push(i);for(let i of n)this.deleteModuleAndDependents(i)}compileModule(t,{emitC:n,debugGc:r,debugParallelism:i,debugAsyncAwait:o,allocator:a,isLibrary:s}={}){let{moduleValue:l,moduleError:u}=this.loadModule(t);if(u)throw u.toString();if(!this.modules.get(t))throw new Error(`Module data not found for ${t}`);this.codeGenratorC.compileModule(t,l,{debugGc:r,debugParallelism:i,debugAsyncAwait:o,allocator:a,isLibrary:s}),n&&console.log(this.codeGenratorC.print())}getGeneratedCode(){return this.codeGenratorC.print()}getExportedFunctionNames(){return this.codeGenratorC.getExportedFunctionNames()}get needsIntelAsmSyntax(){return this.codeGenratorC.needsIntelAsmSyntax}};export{Ci as Emitter,is as IdentifierRegex,gm as ModuleManager,rs as Operators,ae as PlaceholderToken,Ph as RAIIToken,jt as TokenType,yo as charIsOperator,el as clearAllGlobalImplState,Uo as clearGenericImplsFromModule,zo as clearImplsFromModule,d$ as debug,Hl as findMatchingBracketTokenIndex,Jt as generateExprFromCode,ir as stringIsOperator,Kl as tokenize};