@shd101wyy/yo 0.1.7 → 0.1.8

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
@@ -185,14 +185,14 @@ This typically happens when a struct/enum/array/tuple contains fields with confl
185
185
 
186
186
  Consider restructuring the type to avoid mixing incompatible field types.`})}function ln(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=[ln(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=>ln(i,t,n))}}case"Struct":{let r=e;return{...r,fields:r.fields.map(i=>ln(i,t,n))}}case"Enum":{let r=e;return{...r,fields:r.fields.map(i=>ln(i,t,n))}}case"Array":{let r=e;return{...r,elements:r.elements.map(i=>ln(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=[ln(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=>ln(i,t,n))}}case"Module":{let r=e;return{...r,fields:r.fields.map(i=>i?ln(i,t,n):void 0)}}case"Trait":{let r=e;return{...r,fields:r.fields.map(i=>i?ln(i,t,n):void 0)}}default:return e}}function pl({modulePath:e,inputString:t}){return{functionDeclarationFrameLevel:-1,frames:[],modulePath:e,inputString:t}}function lt(){let e=pl({modulePath:"",inputString:""});return Re(e)}function fl(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=ln(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=ln(o.value[0],!1,t);return{...o,value:[s]}},i=o=>({...o,variables:o.variables.map(r),whereClauseConstraints:By(o.whereClauseConstraints)});return{...e,frames:e.frames.map(i)}}function By(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 sr({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 Un(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 _=u.value?.[0];P(_)&&M(_.value)&&_.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 _ of u.requiredTraits)i.has(_.id)||(i.add(_.id),n.push(_));for(let _ of u.negativeTraits)o.has(_.id)||(o.add(_.id),r.push(_))}if(a)return{requiredTraits:n,negativeTraits:r}}function y_(e){return`typeapp:${e.constructor.id}:${e.args.map(t=>t.id).join(",")}`}function g_({env:e,typeApp:t,traitType:n,isNegated:r}){let i=e.frames.length-1,o=e.frames[i];if(!o)return e;let a=y_(t),s=o.whereClauseConstraints.get(a);s||(s={someType:t.constructor,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 Gy(e,t){let n=y_(t),r=[],i=[],o=new Set,a=new Set,s=!1;for(let l of e.frames){let u=l.whereClauseConstraints.get(n);if(u){s=!0;for(let _ of u.requiredTraits)o.has(_.id)||(o.add(_.id),r.push(_));for(let _ of u.negativeTraits)a.has(_.id)||(a.add(_.id),i.push(_))}}if(s)return{requiredTraits:r,negativeTraits:i}}var h_=null;function v_(e){h_=e}function T_(){h_=null}var Wy="__yo_self";function me({env:e,variable:t,deltaFrame:n,variableId:r,addToBeginBlockFrame:i,allowVariableShadowing:o}){let a=e.frames.length-1+(n??0),s=st(e.modulePath,t.name);if(i){let d=jy(e);d>=0&&(a=d)}if(t.name!==Wy&&!s){let d=j(e,t.name);if(d.length>0&&!o){let h=d[d.length-1];throw _t([{token:t.token,errorMessage:`Failed to define variable "${t.name}":`},{token:h.token,errorMessage:`Variable "${t.name}" is already defined here (variable shadowing is not allowed):`}])}}let l=e.frames[a];if(!l)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 u=s?t.name:r??ci(e.modulePath,t.name),_={...t,frameLevel:a,id:u},c=s?Yy(l,_):qy({frame:l,variable:_}),p=e.frames.slice();return p[a]=c,{env:{functionDeclarationFrameLevel:e.functionDeclarationFrameLevel,frames:p,modulePath:e.modulePath,inputString:e.inputString},variable:_}}function qy({frame:e,variable:t}){if(t.name==="_")return e;if(e.variables.some(r=>r.name===t.name))throw _t([{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){return{id:e.id,variables:[...e.variables,t],isBeginBlockFrame:e.isBeginBlockFrame,whereClauseConstraints:e.whereClauseConstraints}}function Hy(e,t,n){let r=e.variables.filter(i=>i.name===t);return n?r.filter(n):r}function j(e,t,n){let r=[];for(let i=0;i<e.frames.length;i++){let o=e.frames[i],a=Hy(o,t,n);r.push(...a)}return n?r.filter(n):r}function hn(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 Xo(e,t){for(let n=e.frames.length-1;n>=0;n--)if(e.frames[n].variables.some(t))return n;return-1}function Re(e,t={id:ci(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=to(e),o=r.variables.filter(a=>!a.initializedAtToken);if(i.length>0)throw _t(i.map(a=>({token:a.token,errorMessage:`Variable "${a.name}" was not consumed. It is supposed to be consumed before going out of scope.
187
187
  Typeof "${a.name}": ${A(a.type)}`})));if(o.length>0)throw _t(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 Ge(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 E_(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 $_({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&&W(a.type));if(o&&W(o.type)){let a=o.assignedValue;ce(a)&&(a=X(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&&gt(a.assignedValue)){let s=a.assignedValue,l=s.type,u=l.fields.findIndex(_=>_.label===n&&W(_.type));if(u>=0){let _=l.fields[u];if(W(_.type)){let c=s.fields[u],p=_.type;ne(c)&&c.specializedType&&(p=c.specializedType),i.push({type:p,value:c})}}}if(i.length===0){let a=Bn({concreteType:r,methodName:n,env:e});i.push(...a)}return i}function dl({env:e,context:t,methodName:n,receiverType:r,isInfixOperatorCall:i}){let o=[],a=r;for(;Ce(a);)a=a.childType;function s(p,f){let d=p.fields.find(h=>h.label===n&&(W(h.type)||Ve(h.type)));if(d){let h;if(W(d.type)){if(ce(f))h=X(d.type,{variableName:d.label,env:e,context:t});else if(gt(f)){let g=p.fields.findIndex(y=>y.label===d.label);h=f.fields[g]}o.push({type:d.type,value:h})}else if($e(d.type)){let g=d.assignedValue;We(g)&&l(g)}}if(!d)for(let h of p.fields)Ve(h.type)&&h.assignedValue&&s(h.type,h.assignedValue)}function l(p){let f=p.type.fields.findIndex(d=>d.label==="Call");if(f>=0){let d=p.type.fields[f];if(d.assignedValue){let h=d.assignedValue;Cn(h)?h.fields.forEach(g=>{o.push({type:g.type,value:g})}):o.push({type:h.type,value:h})}}}function u(p){let f=[];for(let d of p)if(W(d.type)){if(d.type.parameters.length===0)continue;let g=d.type.parameters[0].type;if(!i&&Ce(g)){let v=g.childType,T=r;if((yt(r)||It(r)||pt(r))&&(T=ht({type:r,expectedType:void 0,expr:void 0,env:e})),Y({type:v,env:d.type.env},{type:T,env:e},!0)){f.push({type:d.type,value:d.value,needsPointerConversion:!0});continue}}if(de(g)){f.push(d);continue}if(de(g)&&!de(r)){f.push(d);continue}if(M(r)&&r.resolvedConcreteType&&!Fe(r)&&!de(g)&&Y({type:g,env:d.type.env},{type:r.resolvedConcreteType,env:e},!0)){f.push(d);continue}if(!de(g)&&de(r))continue;if(yt(r)||It(r)||pt(r)){let v=ht({type:r,expectedType:void 0,expr:void 0,env:e});if(Y({type:g,env:d.type.env},{type:v,env:e},!0)){f.push(d);continue}}if(Ie(r)&&d.value===void 0){if(d.type.parameters.length>0&&d.type.SelfType){let T=d.type.parameters[0];if(T){let $=T.type;if(!ft($)&&!Ie($)&&!Ce($))continue}}let v=d.type.return.type;if(yr(v,d.type.SelfType))continue}Y({type:g,env:d.type.env},{type:r,env:e},!0)&&f.push(d)}else f.push(d);return f}function _(p,f,d=new Set){if(d.has(p.id))return;d.add(p.id);let h=p.fields.find(g=>g.label===f&&W(g.type));if(h&&W(h.type)){let g=h.assignedValue;ce(g)&&(g=X(h.type,{variableName:h.label,env:e,context:t})),o.push({type:h.type,value:g});return}for(let g of p.fields)Ve(g.type)&&g.assignedValue&&s(g.type,g.assignedValue)}if(r!==a&&r.trait){let p=r.trait.fields.find(f=>f.label===n&&W(f.type));if(p&&W(p.type)){let f=p.assignedValue;ce(f)&&(f=X(p.type,{variableName:p.label,env:e,context:t})),o.push({type:p.type,value:f})}else _(r.trait,n);for(let f of r.trait.fields)if(f.label===""&&f.assignedValue&&gt(f.assignedValue)){let d=f.assignedValue,h=d.type,g=h.fields.findIndex(y=>y.label===n&&W(y.type));if(g>=0){let y=h.fields[g];if(W(y.type)){let v=d.fields[g],T=y.type;ne(v)&&v.specializedType&&(T=v.specializedType),o.push({type:T,value:v})}}}}if(o.length===0&&r!==a){let p=Bn({concreteType:r,methodName:n,env:e});o.push(...p)}let c=M(a)&&a.resolvedConcreteType&&!Fe(a);if(a.trait&&!Ie(a)&&!c){let p=a.trait.fields.find(f=>f.label===n&&(W(f.type)||$e(f.type)));if(p&&W(p.type)){let f=p.assignedValue;ce(f)&&(f=X(p.type,{variableName:p.label,env:e,context:t})),o.push({type:p.type,value:f})}else if(p&&$e(p.type)){let f=p.assignedValue;We(f)&&l(f)}else _(a.trait,n);for(let f of a.trait.fields)if(f.label===""&&f.assignedValue&&gt(f.assignedValue)){let d=f.assignedValue,h=d.type,g=h.fields.findIndex(y=>y.label===n&&W(y.type));if(g>=0){let y=h.fields[g];if(W(y.type)){let v=d.fields[g],T=y.type;ne(v)&&v.specializedType&&(T=v.specializedType),o.push({type:T,value:v})}}}if(o.length===0){let f=Bn({concreteType:a,methodName:n,env:e});o.push(...f)}}if(o.length===0&&Lr(a)){let p=Gy(e,a);if(p)for(let f of p.requiredTraits)_(f,n)}if(yt(a)||It(a)||pt(a)){let p=ht({type:a,expectedType:void 0,expr:void 0,env:e});if(p.trait){let f=p.trait.fields.find(d=>d.label===n&&W(d.type));if(f&&W(f.type)){let d=f.assignedValue;ce(d)&&(d=X(f.type,{variableName:f.label,env:e,context:t})),o.push({type:f.type,value:d})}else _(p.trait,n);for(let d of p.trait.fields)if(d.label===""&&d.assignedValue&&gt(d.assignedValue)){let h=d.assignedValue,g=h.type,y=g.fields.findIndex(v=>v.label===n&&W(v.type));if(y>=0){let v=g.fields[y];if(W(v.type)){let T=h.fields[y],$=v.type;ne(T)&&T.specializedType&&($=T.specializedType),o.push({type:$,value:T})}}}if(o.length===0){let d=Bn({concreteType:p,methodName:n,env:e});o.push(...d)}}}if(M(a)){if(a.resolvedConcreteType?.trait&&!Fe(a)){let p=a.resolvedConcreteType,f=p.trait,d=f?.fields.find(h=>h.label===n&&W(h.type));if(d&&W(d.type)){let h=d.assignedValue||X(d.type,{variableName:d.label,env:e,context:t});o.push({type:d.type,value:h})}if(o.length===0){for(let h of f?.fields??[])if(h.label===""&&h.assignedValue&&gt(h.assignedValue)){let g=h.assignedValue,y=g.type,v=y.fields.findIndex(T=>T.label===n&&W(T.type));if(v>=0){let T=y.fields[v];if(W(T.type)){let $=g.fields[v],C=T.type;ne($)&&$.specializedType&&(C=$.specializedType),o.push({type:C,value:$});break}}}}if(o.length===0){let h=Bn({concreteType:p,methodName:n,env:e});o.push(...h)}}if(!(o.length>0)){let p=[],f=new Set;for(let h of a.requiredTraits??[])f.has(h.traitType.id)||(f.add(h.traitType.id),p.push(h.traitType));let d=Un(e,a);if(d)for(let h of d.requiredTraits)f.has(h.id)||(f.add(h.id),p.push(h));if(M(a))for(let h=e.frames.length-1;h>=0;h--){let g=e.frames[h];for(let y of g.whereClauseConstraints.values())if(Y({type:y.someType,env:e},{type:a,env:e},!1))for(let v of y.requiredTraits)f.has(v.id)||(f.add(v.id),p.push(v))}for(let h of p){let g=h.fields.find(y=>y.label===n&&W(y.type));if(g&&W(g.type)){let y={...g.type,SelfType:a},v=!1;if(y.parameters.length>0&&Ce(y.parameters[0].type)){let $=y.parameters[0].type.childType;(M($)&&$.name==="Self"||Y({type:$,env:y.env},{type:r,env:e},!0))&&(v=!0)}let T=X(y,{variableName:g.label,env:e,context:t});o.push({type:y,value:T,needsPointerConversion:v})}}if(o.length===0){for(let h of a.trait.fields)if(h.label===""&&h.assignedValue&&P(h.assignedValue)&&Ve(h.assignedValue.value)){let y=h.assignedValue.value.fields.find(v=>v.label===n&&W(v.type));if(y&&W(y.type)){let v=X(y.type,{variableName:y.label,env:e,context:t});o.push({type:y.type,value:v})}}}}}if(Ie(a)){let p=a.trait.fields.find(d=>d.label===n&&(W(d.type)||Ve(d.type)));if(p&&W(p.type)){let d=p.assignedValue||X(p.type,{variableName:p.label,env:e,context:t});o.push({type:p.type,value:d})}let f=a.requiredTraits;for(let{traitType:d}of f){let h=d.fields.find(g=>g.label===n&&(W(g.type)||Ve(g.type)));h&&W(h.type)&&h.type.parameters.length>0&&(de(h.type.parameters[0].type)||de(r)||Y({type:h.type.parameters[0].type,env:h.type.env},{type:r,env:e},!0))&&o.push({type:h.type,value:void 0})}}return o.length>0,u(o)}function C_(e){let t=e.frames.map(n=>({...n,variables:n.variables.filter(r=>!r.isImplicit)}));return{...e,frames:t}}function Ga(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 to(e){return e.frames.length===0?[]:e.frames[e.frames.length-1].variables.filter(r=>{if(r.consumedAtToken||!r.isOwningTheRcValue||!Ne(r.type)||r.isModuleLevel)return!1;let i=r.type;return!(M(i)&&!i.resolvedConcreteType&&i.requiredTraits.length===0)}).reverse()}function jy(e){for(let t=e.frames.length-1;t>=0;t--)if(e.frames[t]?.isBeginBlockFrame)return t;return-1}var Qy=process.env.YO_SKIP_PRELUDE==="1"||process.env.YO_SKIP_PRELUDE==="true";function Zy(e,t){return e.some(n=>(n.type==="single_line_comment"||n.type==="multi_line_comment")&&n.value.includes(t))}var Qo=class{constructor({modulePath:t,stdPath:n,loadModule:r,inputString:i,allowPartialModule:o=!1,registerPartialModule:a}){if(this.modulePath=t,this.allowPartialModule=o,this.registerPartialModule=a,!this.modulePath.match(/^file:\/\//))throw new Error(`Invalid file protocol: ${this.modulePath}. Only file:// is supported for now. `);try{if(this.inputString=i??Ky(t.replace(/^file:\/\//,""),"utf-8"),this.parser=new Ii({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(s){throw new Error(`Failed to import module "${t}":
188
- ${s instanceof En||s instanceof Rn?s.toString():s instanceof Error?s.message:String(s)}`)}}getProgram(){return this.program}getTokens(){return this.tokens}evaluateProgram(t,n){let r=pl({modulePath:this.modulePath,inputString:this.inputString});if(!Zy(this.tokens,"@skip_prelude")&&!Qy){let l="file://"+Xy.join(t,"prelude.yo"),{moduleValue:u,moduleError:_}=n(l);if(_)throw _;if(u&&$e(u.type)){r=Re(r);for(let c=0;c<u.type.fields.length;c++){let p=u.type.fields[c],f=u.fields[c],{env:d}=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=d}}v_(r)}let{moduleValue:o,env:a,partialModuleError:s}=Ma({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,registerPartialModule:this.registerPartialModule});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 J$(...e){process.env.NODE_ENV!=="production"&&process.env.DEBUG&&console.log(...e)}import{existsSync as Tv}from"fs";import*as fa from"path";import*as A_ from"fs";function Jy(e){switch(e){case"x86_64":case"aarch64":return 64;case"x86":case"arm":case"wasm32":return 32}}var b_={darwin:"macos",linux:"linux",win32:"windows",freebsd:"freebsd"},k_={x64:"x86_64",arm64:"aarch64",ia32:"x86",arm:"arm"},Wa;function eg(){if(Wa)return Wa;let e=b_[process.platform];if(!e)throw new Error(`Unsupported host platform: ${process.platform}. Supported: ${Object.keys(b_).join(", ")}`);let t=k_[process.arch];if(!t)throw new Error(`Unsupported host architecture: ${process.arch}. Supported: ${Object.keys(k_).join(", ")}`);return Wa={platform:e,arch:t},Wa}function tg(){if(process.platform!=="linux")return"gnu";try{if(A_.readdirSync("/lib").some(n=>n.startsWith("ld-musl-")))return"musl"}catch{}return"gnu"}function I_(e){switch(e){case"linux":return tg();case"windows":return"msvc";case"wasi":case"emscripten":return"wasm";case"macos":case"freebsd":return}}function ng(e,t,n){return n?`${e}-${t}-${n}`:`${e}-${t}`}function S_(e,t,n){return{arch:e,os:t,abi:n,pointerSizeBits:Jy(e),triple:ng(e,t,n)}}function Kr(){let e=eg(),t=I_(e.platform);return S_(e.arch,e.platform,t)}var w_=new Set(["x86_64","aarch64","x86","arm","wasm32"]),F_=new Set(["linux","macos","windows","freebsd","wasi","emscripten"]),L_=new Set(["gnu","musl","msvc","none","wasm"]);function x_(e){let n=(e.startsWith("wasm-")?`wasm32-${e.slice(5)}`:e).split("-");if(n.length<2||n.length>3)throw new Error(`Invalid target triple "${e}". Expected format: <arch>-<os> or <arch>-<os>-<abi>. Example: x86_64-linux-gnu`);let r=n[0],i=n[1],o=n[2];if(!w_.has(r))throw new Error(`Unknown architecture "${r}" in target triple "${e}". Supported: ${[...w_].join(", ")}`);if(!F_.has(i))throw new Error(`Unknown OS "${i}" in target triple "${e}". Supported: ${[...F_].join(", ")}`);let a=r,s=i,l;if(o!==void 0)if(o==="none")l=void 0;else if(L_.has(o))l=o;else throw new Error(`Unknown ABI "${o}" in target triple "${e}". Supported: ${[...L_].join(", ")}`);else l=I_(s);return S_(a,s,l)}var ml;function Zo(){return ml||(ml=Kr()),ml}function Gt(e){return e.os==="windows"}function Ci(e){return e.os==="linux"}function Kn(e){return e.os==="macos"}function Xn(e){return e.arch==="wasm32"||e.os==="wasi"||e.os==="emscripten"}function N_(e){return e.os==="wasi"}function V_(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 D_(e){let t=Gt(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 Mr(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 On(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 bi=[...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_slice_ptr,...k.__yo_as,...k.__yo_getrandom,...k.__yo_arc4random_buf,...k.__yo_bcrypt_gen_random,...k.__yo_getentropy,...k.__yo_maybe_uninit_new,...k.__yo_maybe_uninit_as_ptr,...k.__yo_maybe_uninit_assume_init,...k.__yo_array_index,...k.__yo_slice_index,...k.__yo_array_index_range,...k.__yo_array_index_range_inclusive,...k.__yo_slice_index_range,...k.__yo_slice_index_range_inclusive,...k.__yo_noop,...k.__yo_return_self,...k.__yo_ms_sleep],M_=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 ie(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 z(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":for(let n of Object.values(t.types))if(wn(n.type)&&n.type.fields.length===1&&qe(n.type.fields[0].type))return n.cName;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=Kt(e);if(i)return z(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")&&pe(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(He(i)){let o=z(r,t),a=`Array_${ie(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_${ie(z(n.childType,t))}`;return t.sliceStructTypes.has(i)||t.sliceStructTypes.set(i,{childType:z(n.childType,t)}),i}case"SomeType":{let n=e;if(Fe(n)){if(n.resolvedConcreteType?.isExtern)return`${z(n.resolvedConcreteType,t)}*`;let r=t.types[n.id]?.cName;if(r)return`${r}*`;if(n.resolvedConcreteType&&M(n.resolvedConcreteType)&&Fe(n.resolvedConcreteType)){let o=n.resolvedConcreteType,a=t.types[o.id]?.cName;if(a)return`${a}*`}if(n.resolvedConcreteType&&pe(n.resolvedConcreteType)){let o=n.resolvedConcreteType.id;for(let[a,s]of Object.entries(t.types))if(M(s.type)&&Fe(s.type)&&s.type.resolvedConcreteType&&pe(s.type.resolvedConcreteType)&&s.type.resolvedConcreteType.id===o)return`${s.cName}*`}let i=Rt(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
+ ${s instanceof En||s instanceof Rn?s.toString():s instanceof Error?s.message:String(s)}`)}}getProgram(){return this.program}getTokens(){return this.tokens}evaluateProgram(t,n){let r=pl({modulePath:this.modulePath,inputString:this.inputString});if(!Zy(this.tokens,"@skip_prelude")&&!Qy){let l="file://"+Xy.join(t,"prelude.yo"),{moduleValue:u,moduleError:_}=n(l);if(_)throw _;if(u&&$e(u.type)){r=Re(r);for(let c=0;c<u.type.fields.length;c++){let p=u.type.fields[c],f=u.fields[c],{env:d}=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=d}}v_(r)}let{moduleValue:o,env:a,partialModuleError:s}=Ma({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,registerPartialModule:this.registerPartialModule});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 J$(...e){process.env.NODE_ENV!=="production"&&process.env.DEBUG&&console.log(...e)}import{existsSync as Tv}from"fs";import*as fa from"path";import*as A_ from"fs";function Jy(e){switch(e){case"x86_64":case"aarch64":return 64;case"x86":case"arm":case"wasm32":return 32}}var b_={darwin:"macos",linux:"linux",win32:"windows",freebsd:"freebsd"},k_={x64:"x86_64",arm64:"aarch64",ia32:"x86",arm:"arm"},Wa;function eg(){if(Wa)return Wa;let e=b_[process.platform];if(!e)throw new Error(`Unsupported host platform: ${process.platform}. Supported: ${Object.keys(b_).join(", ")}`);let t=k_[process.arch];if(!t)throw new Error(`Unsupported host architecture: ${process.arch}. Supported: ${Object.keys(k_).join(", ")}`);return Wa={platform:e,arch:t},Wa}function tg(){if(process.platform!=="linux")return"gnu";try{if(A_.readdirSync("/lib").some(n=>n.startsWith("ld-musl-")))return"musl"}catch{}return"gnu"}function I_(e){switch(e){case"linux":return tg();case"windows":return"msvc";case"wasi":case"emscripten":return"wasm";case"macos":case"freebsd":return}}function ng(e,t,n){return n?`${e}-${t}-${n}`:`${e}-${t}`}function S_(e,t,n){return{arch:e,os:t,abi:n,pointerSizeBits:Jy(e),triple:ng(e,t,n)}}function Kr(){let e=eg(),t=I_(e.platform);return S_(e.arch,e.platform,t)}var w_=new Set(["x86_64","aarch64","x86","arm","wasm32"]),F_=new Set(["linux","macos","windows","freebsd","wasi","emscripten"]),L_=new Set(["gnu","musl","msvc","none","wasm"]);function x_(e){let n=(e.startsWith("wasm-")?`wasm32-${e.slice(5)}`:e).split("-");if(n.length<2||n.length>3)throw new Error(`Invalid target triple "${e}". Expected format: <arch>-<os> or <arch>-<os>-<abi>. Example: x86_64-linux-gnu`);let r=n[0],i=n[1],o=n[2];if(!w_.has(r))throw new Error(`Unknown architecture "${r}" in target triple "${e}". Supported: ${[...w_].join(", ")}`);if(!F_.has(i))throw new Error(`Unknown OS "${i}" in target triple "${e}". Supported: ${[...F_].join(", ")}`);let a=r,s=i,l;if(o!==void 0)if(o==="none")l=void 0;else if(L_.has(o))l=o;else throw new Error(`Unknown ABI "${o}" in target triple "${e}". Supported: ${[...L_].join(", ")}`);else l=I_(s);return S_(a,s,l)}var ml;function Zo(){return ml||(ml=Kr()),ml}function Gt(e){return e.os==="windows"}function Ci(e){return e.os==="linux"}function Kn(e){return e.os==="macos"}function Xn(e){return e.arch==="wasm32"||e.os==="wasi"||e.os==="emscripten"}function N_(e){return e.os==="wasi"}function V_(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 D_(e){let t=Gt(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 Mr(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 On(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 bi=[...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_slice_ptr,...k.__yo_as,...k.__yo_getrandom,...k.__yo_arc4random_buf,...k.__yo_bcrypt_gen_random,...k.__yo_getentropy,...k.__yo_maybe_uninit_new,...k.__yo_maybe_uninit_as_ptr,...k.__yo_maybe_uninit_assume_init,...k.__yo_array_index,...k.__yo_slice_index,...k.__yo_array_index_range,...k.__yo_array_index_range_inclusive,...k.__yo_slice_index_range,...k.__yo_slice_index_range_inclusive,...k.__yo_noop,...k.__yo_return_self,...k.__yo_ms_sleep],M_=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 re(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 z(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":for(let n of Object.values(t.types))if(wn(n.type)&&n.type.fields.length===1&&qe(n.type.fields[0].type))return n.cName;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=Kt(e);if(i)return z(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")&&pe(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(He(i)){let o=z(r,t),a=`Array_${re(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_${re(z(n.childType,t))}`;return t.sliceStructTypes.has(i)||t.sliceStructTypes.set(i,{childType:z(n.childType,t)}),i}case"SomeType":{let n=e;if(Fe(n)){if(n.resolvedConcreteType?.isExtern)return`${z(n.resolvedConcreteType,t)}*`;let r=t.types[n.id]?.cName;if(r)return`${r}*`;if(n.resolvedConcreteType&&M(n.resolvedConcreteType)&&Fe(n.resolvedConcreteType)){let o=n.resolvedConcreteType,a=t.types[o.id]?.cName;if(a)return`${a}*`}if(n.resolvedConcreteType&&pe(n.resolvedConcreteType)){let o=n.resolvedConcreteType.id;for(let[a,s]of Object.entries(t.types))if(M(s.type)&&Fe(s.type)&&s.type.resolvedConcreteType&&pe(s.type.resolvedConcreteType)&&s.type.resolvedConcreteType.id===o)return`${s.cName}*`}let i=Rt(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.
189
189
  resolvedConcreteType: ${n.resolvedConcreteType?.id??"none"}
190
- registered type IDs: ${Object.keys(t.types).filter(o=>o.startsWith("sometype")).join(", ")}`)}return Ht(n)&&n.resolvedConcreteType||n.resolvedConcreteType?z(n.resolvedConcreteType,t):"void*"}case"Ptr":{let r=e.childType;if(qe(r)){let a=z(r.childType,t),s=`Slice_${ie(a)}`;return t.sliceStructTypes.has(s)||t.sliceStructTypes.set(s,{childType:a}),`${s}*`}let i=z(r,t);return ft(r)?`${i}*`:Te(r)&&Kt(r)?`${i}*`:`${i}*`}case"Iso":{let n=e,r=n.childType,i=z(r,t),o=i.replace(/\*/g,"").trim(),a=`Iso_${ie(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=z(r,t),o=i.replace(/\*/g,"").trim(),a=`Arc_${ie(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 ut(e,t,n){let r=ie(t);return`${z(e,n)} ${r}`}function Yt(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 Xr(e){return e.type.return.isCompileTimeOnly}function Cr(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],bi)?n=t.args[0].func.token.value:F(t)&&E(t,bi)&&(n=t.func.token.value),n&&k.__yo_as.includes(n)?null:n}function Kt(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(Ce(i)){if(n)return null;n=r}else return null}else return null;return t&&n&&n.fields?n.fields[0].type:null}function Vn(e){for(let t of e.variants)if(t.fields&&t.fields.length>0)return!1;return e.variants.length>0}function ve(e,t){if(!t)return ie(e);let n=j(t,e);if(n.length>0){let r=n[n.length-1];return ie(r.name,r.type.isExtern==="c")}return ie(e)}function qa(e){if(F(e)&&e.args.length>=1){let t=e.args[0];if(t&&B(t))return t.token.value}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&B(e.func.args[0])&&B(e.func.args[1])&&e.func.args[1].token.value===k.___dup[0])return e.func.args[0].token.value}function An(e){if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&B(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&B(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||!B(t)))return t.token.value}function Jo(e){if(e){if(Bt(e))return e;if(F(e)){let t=e;for(let n of t.args){let r=Jo(n);if(r)return r}}}}var yl;function O_(e){yl=e}function O(e,t,n){if(!yl)throw new Error("Internal Error: generateExpr function is not set.");return yl(e,t,n)}function Or(e,t,n){let r=M(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(!Ne(r))return"";if(ke(r)){let i=r.length;if(!He(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=Or(`(${e}).data[i]`,r.childType,n);return a&&o.emitLine(` ${a};`),o.emitLine("}"),""}if(xe(r)){let i=n.emitter;for(let o=0;o<r.fields.length;o++){let a=r.fields[o].type,s=M(a)&&a.resolvedConcreteType?a.resolvedConcreteType:a;if(Ne(s)){let l=Or(`(${e})._${o}`,a,n);l&&i.emitLine(`${l};`)}}return""}if(Ie(r))return`__yo_decr_rc((void*)(${e}).data)`;if(ft(r))return`__yo_decr_rc((void*)(${e}))`;if(Ft(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if(bt(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if(pe(r)||Te(r)){let i=br(r,n);if(i)return`${i}(${e})`}return""}function no(e,t,n){let r=M(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(ke(r)){let i=r.length;if(!He(i))return"/* Error: array has non-constant length */";let o=`temp_dup_${Pe("")}`,a=`i_${Pe("")}`,s=z(r,n),l=n.emitter;l.emitLine(`${s} ${o} = ${e};`),l.emitLine(`for (size_t ${a} = 0; ${a} < ${i.value}; ${a}++) {`);let u=no(`${o}.data[${a}]`,r.childType,n);return l.emitLine(` ${o}.data[${a}] = ${u};`),l.emitLine("}"),o}if(xe(r)){let i=n.emitter,o=`temp_dup_tuple_${Pe("")}`,a=z(r,n);i.emitLine(`${a} ${o} = ${e};`);for(let s=0;s<r.fields.length;s++){let l=r.fields[s].type,u=M(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(Ne(u)){let _=no(`${o}._${s}`,l,n);i.emitLine(`${o}._${s} = ${_};`)}}return o}if(Ie(r))return`((${z(r,n)}){ .data = __yo_incr_rc((void*)(${e}).data), .vtable = (${e}).vtable })`;if(ft(r))return`((${z(r,n)})__yo_incr_rc((void*)(${e})))`;if(Ft(r))return`((${z(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if(bt(r))return`((${z(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if(pe(r)||Te(r)){let i=Dn(r,n);if(i)return`${i}(${e})`}return e}function br(e,t){if(pe(e)||Te(e)||Ie(e)||M(e)||Ft(e)||bt(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 Dn(e,t){if(pe(e)||Te(e)||Ie(e)||M(e)||Ft(e)||bt(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 $t(e,t,n){let r=n.emitter;if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions){if(n.shortCircuitHandledDropVarNames){let a=An(i);if(a&&n.shortCircuitHandledDropVarNames.has(a)){n.shortCircuitHandledDropVarNames.delete(a);continue}}let o=O(i,t,n);o&&r.emitLine(`${t}${o};`)}}function ot(e,t,n){let r=n.emitter;if(e.$?.deferredDupExpressions){for(let i of e.$.deferredDupExpressions)if(F(i)){let o=O(i,t,n);o&&r.emitLine(`${t}${o};`)}}}function en(e,t,n){if(He(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(Be(e))return e.value?"true":"false";if(Le(e)){let r=n?.$?.convertedRuntimeType||n?.$?.type;if(r&&wn(r)&&r.fields.length===1){let i=r.fields[0].type;if(qe(i)){let o=z(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=z(r,t),o=JSON.stringify(e.value),a=Buffer.byteLength(e.value,"utf8");return`(${i}){ .data = (uint8_t*)${o}, .length = ${a} }`}if(!r||pt(r)){for(let i of Object.values(t.types))if(wn(i.type)&&i.type.fields.length===1&&qe(i.type.fields[0].type)){let o=JSON.stringify(e.value),a=Buffer.byteLength(e.value,"utf8");return`(${i.cName}){ .data = (uint8_t*)${o}, .length = ${a} }`}}return JSON.stringify(e.value)}else if(Nt(e)){let r=e.type,i=Kt(r);if(i){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 en(e.fields[0],t,{$:{type:i,convertedRuntimeType:i}})}if(Vn(r))return Yt(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=Yt(r,e.variantName,t);if(!e.fields||e.fields.length===0)return`(${a}){ .tag = ${s} }`;{let l=r.variants.find(_=>_.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[c];if(p&&!fe(p.type)){let f=ie(p.label),d=en(_,t);return`.${f} = ${d}`}return null}).filter(_=>_!==null);return u.length===0?`(${a}){ .tag = ${s} }`:`(${a}){ .tag = ${s}, .data = { .${e.variantName} = { ${u.join(", ")} } } }`}}else if(Cn(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
+ registered type IDs: ${Object.keys(t.types).filter(o=>o.startsWith("sometype")).join(", ")}`)}return Ht(n)&&n.resolvedConcreteType||n.resolvedConcreteType?z(n.resolvedConcreteType,t):"void*"}case"Ptr":{let r=e.childType;if(qe(r)){let a=z(r.childType,t),s=`Slice_${re(a)}`;return t.sliceStructTypes.has(s)||t.sliceStructTypes.set(s,{childType:a}),`${s}*`}let i=z(r,t);return ft(r)?`${i}*`:Te(r)&&Kt(r)?`${i}*`:`${i}*`}case"Iso":{let n=e,r=n.childType,i=z(r,t),o=i.replace(/\*/g,"").trim(),a=`Iso_${re(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=z(r,t),o=i.replace(/\*/g,"").trim(),a=`Arc_${re(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 ut(e,t,n){let r=re(t);return`${z(e,n)} ${r}`}function Yt(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 Xr(e){return e.type.return.isCompileTimeOnly}function Cr(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],bi)?n=t.args[0].func.token.value:F(t)&&E(t,bi)&&(n=t.func.token.value),n&&k.__yo_as.includes(n)?null:n}function Kt(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(Ce(i)){if(n)return null;n=r}else return null}else return null;return t&&n&&n.fields?n.fields[0].type:null}function Vn(e){for(let t of e.variants)if(t.fields&&t.fields.length>0)return!1;return e.variants.length>0}function ve(e,t){if(!t)return re(e);let n=j(t,e);if(n.length>0){let r=n[n.length-1];return re(r.name,r.type.isExtern==="c")}return re(e)}function qa(e){if(F(e)&&e.args.length>=1){let t=e.args[0];if(t&&B(t))return t.token.value}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&B(e.func.args[0])&&B(e.func.args[1])&&e.func.args[1].token.value===k.___dup[0])return e.func.args[0].token.value}function An(e){if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&B(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&B(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||!B(t)))return t.token.value}function Jo(e){if(e){if(Bt(e))return e;if(F(e)){let t=e;for(let n of t.args){let r=Jo(n);if(r)return r}}}}var yl;function O_(e){yl=e}function O(e,t,n){if(!yl)throw new Error("Internal Error: generateExpr function is not set.");return yl(e,t,n)}function Or(e,t,n){let r=M(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(!Ne(r))return"";if(ke(r)){let i=r.length;if(!He(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=Or(`(${e}).data[i]`,r.childType,n);return a&&o.emitLine(` ${a};`),o.emitLine("}"),""}if(xe(r)){let i=n.emitter;for(let o=0;o<r.fields.length;o++){let a=r.fields[o].type,s=M(a)&&a.resolvedConcreteType?a.resolvedConcreteType:a;if(Ne(s)){let l=Or(`(${e})._${o}`,a,n);l&&i.emitLine(`${l};`)}}return""}if(Ie(r))return`__yo_decr_rc((void*)(${e}).data)`;if(ft(r))return`__yo_decr_rc((void*)(${e}))`;if(Ft(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if(bt(r))return`__yo_decr_rc_atomic((void*)(${e}))`;if(pe(r)||Te(r)){let i=br(r,n);if(i)return`${i}(${e})`}return""}function no(e,t,n){let r=M(t)&&t.resolvedConcreteType?t.resolvedConcreteType:t;if(ke(r)){let i=r.length;if(!He(i))return"/* Error: array has non-constant length */";let o=`temp_dup_${Pe("")}`,a=`i_${Pe("")}`,s=z(r,n),l=n.emitter;l.emitLine(`${s} ${o} = ${e};`),l.emitLine(`for (size_t ${a} = 0; ${a} < ${i.value}; ${a}++) {`);let u=no(`${o}.data[${a}]`,r.childType,n);return l.emitLine(` ${o}.data[${a}] = ${u};`),l.emitLine("}"),o}if(xe(r)){let i=n.emitter,o=`temp_dup_tuple_${Pe("")}`,a=z(r,n);i.emitLine(`${a} ${o} = ${e};`);for(let s=0;s<r.fields.length;s++){let l=r.fields[s].type,u=M(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(Ne(u)){let _=no(`${o}._${s}`,l,n);i.emitLine(`${o}._${s} = ${_};`)}}return o}if(Ie(r))return`((${z(r,n)}){ .data = __yo_incr_rc((void*)(${e}).data), .vtable = (${e}).vtable })`;if(ft(r))return`((${z(r,n)})__yo_incr_rc((void*)(${e})))`;if(Ft(r))return`((${z(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if(bt(r))return`((${z(r,n)})__yo_incr_rc_atomic((void*)(${e})))`;if(pe(r)||Te(r)){let i=Dn(r,n);if(i)return`${i}(${e})`}return e}function br(e,t){if(pe(e)||Te(e)||Ie(e)||M(e)||Ft(e)||bt(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 Dn(e,t){if(pe(e)||Te(e)||Ie(e)||M(e)||Ft(e)||bt(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 $t(e,t,n){let r=n.emitter;if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions){if(n.shortCircuitHandledDropVarNames){let a=An(i);if(a&&n.shortCircuitHandledDropVarNames.has(a)){n.shortCircuitHandledDropVarNames.delete(a);continue}}let o=O(i,t,n);o&&r.emitLine(`${t}${o};`)}}function ot(e,t,n){let r=n.emitter;if(e.$?.deferredDupExpressions){for(let i of e.$.deferredDupExpressions)if(F(i)){let o=O(i,t,n);o&&r.emitLine(`${t}${o};`)}}}function en(e,t,n){if(He(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(Be(e))return e.value?"true":"false";if(Le(e)){let r=n?.$?.convertedRuntimeType||n?.$?.type;if(r&&wn(r)&&r.fields.length===1){let i=r.fields[0].type;if(qe(i)){let o=z(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=z(r,t),o=JSON.stringify(e.value),a=Buffer.byteLength(e.value,"utf8");return`(${i}){ .data = (uint8_t*)${o}, .length = ${a} }`}if(!r||pt(r)){for(let i of Object.values(t.types))if(wn(i.type)&&i.type.fields.length===1&&qe(i.type.fields[0].type)){let o=JSON.stringify(e.value),a=Buffer.byteLength(e.value,"utf8");return`(${i.cName}){ .data = (uint8_t*)${o}, .length = ${a} }`}}return JSON.stringify(e.value)}else if(Nt(e)){let r=e.type,i=Kt(r);if(i){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 en(e.fields[0],t,{$:{type:i,convertedRuntimeType:i}})}if(Vn(r))return Yt(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=Yt(r,e.variantName,t);if(!e.fields||e.fields.length===0)return`(${a}){ .tag = ${s} }`;{let l=r.variants.find(_=>_.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[c];if(p&&!fe(p.type)){let f=re(p.label),d=en(_,t);return`.${f} = ${d}`}return null}).filter(_=>_!==null);return u.length===0?`(${a}){ .tag = ${s} }`:`(${a}){ .tag = ${s}, .data = { .${e.variantName} = { ${u.join(", ")} } } }`}}else if(Cn(e)){let r=e.type,i=t.types[r.id]?.cName;if(!i)return`// Error: No C type name found for tuple ${A(r)}
191
191
  `;let o=e.fields.map((a,s)=>{let l=en(a,t);return`._${s} = ${l}`});return`(${i}){ ${o.join(", ")} }`}else if(sn(e)){let r=e.type;if(r&&pe(r)){let i=t.types[r.id]?.cName;if(!i)return`// Error: No C type name found for struct ${A(r)}
192
- `;if(r.isNewtype&&r.fields.length===1&&e.fields.length===1){let o=en(e.fields[0],t);return`((${i})(${o}))`}if(r.isReferenceSemantics){let o=e.fields.map(s=>en(s,t));return`${`__yo_new_${i}`}(${o.join(", ")})`}else{let o=e.fields.map((a,s)=>{let l=a,u=xe(r)?`_${s}`:ie(r.fields[s].label),_=en(l,t);return`.${u} = ${_}`});return`(${i}){ ${o.join(", ")} }`}}}else if(Sn(e)){let r=e.type,i=z(r,t),o=e.elements.map(a=>en(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}
193
- `}else if(P(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(xi(e)){let r=e.targetValue[0];if(r){let i=n?.$?.convertedRuntimeType||n?.$?.type;if(i&&Ce(i)){let o=i.childType,a=en(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 ro(e,t,n){if(e===t)return!0;if(e.tag==="FnCall"){if(n&&n(e))return!1;if(ro(e.func,t,n))return!0;for(let r of e.args)if(ro(r,t,n))return!0}return!1}function rg(e,t,n){for(let r=0;r<t.length;r++)if(ro(e,t[r].expr,n))return r;return-1}function R_(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=rg(l,t,i),_=n?.handleReturnStatements&&(vt(l,"return")||E(l,"return"));if(u!==-1){if(s.push(l),a.push(s),s=[],n?.handleSequentialSuspensions)for(let c=u+1;c<t.length&&ro(l,t[c].expr,i);c++)a.push([])}else if(_){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],_=l<t.length?t[l]:null;r.push({stateNumber:l,expressions:u,suspensionPoint:_})}return r}function hl(e,t){let r=R_(e,t,{shouldSkipBody:Bt,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 ig(e,t){return ro(e,t,Bt)}function P_(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&&ig(a,e.awaitPoint.expr),u=e.awaitPoint&&a.tag==="FnCall"&&(E(a,S.while)||E(a,S.cond)||E(a,S.match))&&pn(a);if((l||u)&&e.awaitPoint)so(a,e.awaitPoint,e.stateNumber,t,n);else if(s&&r){let _=O(a,t,n);_&&(i.emitLine(`${t}// Store final expression result`),i.emitLine(`${t}sm->result = ${_};`))}else{let _=O(a,t,n);!_||!a.$||st(a.$.env.modulePath,_)||i.emitLine(`${t}${_};`)}}}function so(e,t,n,r,i){let o=i.emitter;if(e.tag==="FnCall"&&gn(e)){let a=e.args[0];if(!a){o.emitLine(`${r}// Error: await without argument`);return}if(t.futureVariableId===void 0){let s=O(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"&&gn(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 _=O(l,r,i);o.emitLine(`${r}// Store Future for await (variable: ${u})`),o.emitLine(`${r}sm->await_future_${t.index} = ${_};`)}else o.emitLine(`${r}// Store Future for await (variable: ${u}) - future already in state machine`);return}if(s.tag==="FnCall"&&E(s,S.cond)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,_=j(a.$.env,u);_.length>0&&(l=_[_.length-1].id)}ea(s,t,r,i,l);return}if(s.tag==="FnCall"&&E(s,S.match)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,_=j(a.$.env,u);_.length>0&&(l=_[_.length-1].id)}ta(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,S.cond)){let l=O(a,r,i);ea(s,t,r,i,void 0,l||void 0);return}if(s.tag==="FnCall"&&E(s,S.match)){let l=O(a,r,i);ta(s,t,r,i,void 0,l||void 0);return}}}if(e.tag==="FnCall"&&E(e,S.cond)){ea(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,S.match)){ta(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,S.while)){vl(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 ea(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,S.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 g=0;g<s.length;g++){let y=s[g];if(y.tag==="FnCall"&&E(y,"=>")){let v=y.args[0];if(v&&!(Be(v.$?.value)&&v.$.value.value===!1)){u=g;break}}}let _=!1;if(u>=0){let g=s[u];if(g.tag==="FnCall"&&E(g,"=>")){let y=g.args[0];y&&Be(y.$?.value)&&y.$.value.value===!0&&(_=!0)}}if(_&&u>=0){let g=s[u],y=F(g)?g.args[1]:void 0;if(y)if(Qr(y)){let C=ao(y,t,n,r),L=r.asyncWhileLoopInfo?.get(t.index);if(L&&C.length>0){let V=r.asyncCondBranchInfo?.get(t.index)?.branches.some(I=>I.hasAwait&&I.remainingExprs&&I.remainingExprs.length>0)??!1;L.condBranchPostWhileExprs={branchIndex:u,condBranchFieldIndex:t.index,exprs:C,deferredDropExpressions:y.$?.deferredDropExpressions,skipCondBranchCheck:V},l.push({index:u,value:y,hasAwait:!0,remainingExprs:[],deferredDropExpressions:y.$?.deferredDropExpressions})}else l.push({index:u,value:y,hasAwait:!0,remainingExprs:C,deferredDropExpressions:y.$?.deferredDropExpressions})}else{if(io(e,y,r,i,o))oo(y,n,r);else if(F(y)&&E(y,S.begin)){let C=y.args;for(let L=0;L<C.length;L++){let b=C[L],V=O(b,n,r);if(V==="break"&&t.isInsideWhile)a.emitLine(`${n}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${n}goto while_loop_${t.index}_end;`);else{let I=V==="break"||V==="continue"||V?.includes("return");V&&(I||b.$&&!st(b.$.env.modulePath,V))&&a.emitLine(`${n}${V};`)}}if(y.$?.deferredDropExpressions)for(let L of y.$.deferredDropExpressions){let b=O(L,n,r);b&&a.emitLine(`${n}${b};`)}}else{let C=O(y,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||y.$&&!st(y.$.env.modulePath,C))&&a.emitLine(`${n}${C};`)}}l.push({index:u,value:y,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 c=!1,p=0,f=n;for(let g=0;g<s.length;g++){let y=s[g];if(y.tag!=="FnCall"||!E(y,"=>")){a.emitLine(`${f}// Error: Expected => pair in cond`);continue}let v=y.args[0],T=y.args[1];if(!v||!T){a.emitLine(`${f}// Error: Invalid pair in cond`);continue}if(Be(v.$?.value)&&v.$.value.value===!1)continue;c&&(a.emitLine(`${f}else {`),p++,f+=" ");let $=g===s.length-1&&v.tag==="Atom"&&v.token?.value==="true"?null:O(v,f,r);$?a.emitLine(`${f}if (${$}) {`):a.emitLine(`${f}{`),c=!0;let C=`${f} `;if(Qr(T)){a.emitLine(`${C}sm->cond_branch_${t.index} = ${g};`);let b=ao(T,t,C,r),V=r.asyncWhileLoopInfo?.get(t.index);if(V&&b.length>0){let U=r.asyncCondBranchInfo?.get(t.index)?.branches.some(D=>D.hasAwait&&D.remainingExprs&&D.remainingExprs.length>0)??!1;V.condBranchPostWhileExprs={branchIndex:g,condBranchFieldIndex:t.index,exprs:b,deferredDropExpressions:T.$?.deferredDropExpressions,skipCondBranchCheck:U},l.push({index:g,value:T,hasAwait:!0,remainingExprs:[],deferredDropExpressions:T.$?.deferredDropExpressions})}else l.push({index:g,value:T,hasAwait:!0,remainingExprs:b,deferredDropExpressions:T.$?.deferredDropExpressions})}else{if(io(e,T,r,i,o))oo(T,C,r);else if(F(T)&&E(T,S.begin)){let b=T.args;for(let V=0;V<b.length;V++){let I=b[V],U=O(I,C,r);if(U==="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=U==="break"||U==="continue"||U?.includes("return");U&&(D||I.$&&!st(I.$.env.modulePath,U))&&a.emitLine(`${C}${U};`)}}if(T.$?.deferredDropExpressions)for(let V of T.$.deferredDropExpressions){let I=O(V,C,r);I&&a.emitLine(`${C}${I};`)}}else{let b=O(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 V=b==="break"||b==="continue"||b?.includes("return");b&&(V||T.$&&!st(T.$.env.modulePath,b))&&a.emitLine(`${C}${b};`)}}l.push({index:g,value:T,hasAwait:!1})}a.emitLine(`${f}}`)}for(let g=0;g<p;g++)f=f.slice(0,-2),a.emitLine(`${f}}`);r.asyncCondBranchInfo||(r.asyncCondBranchInfo=new Map),(r.asyncCondBranchInfo.get(t.index)?.branches.some(g=>g.hasAwait&&g.remainingExprs&&g.remainingExprs.length>0)??!1)||r.asyncCondBranchInfo.set(t.index,{branches:l,targetVariableId:i,targetAssignmentCode:o})}function io(e,t,n,r,i){return!r&&!i&&n.asyncBodyReturnExpr!==void 0&&e===n.asyncBodyReturnExpr&&!!n.inAsyncStateMachine&&!z_(t)}function oo(e,t,n){let r=n.emitter,i=fe(e.$?.type);if(F(e)&&E(e,S.begin)){let o=e.args;for(let s=0;s<o.length-1;s++){let l=o[s],u=O(l,t,n);u&&l.$&&!st(l.$.env.modulePath,u)&&r.emitLine(`${t}${u};`)}let a=o[o.length-1];if(a&&!i){let s=O(a,t,n);s&&r.emitLine(`${t}sm->result = ${s};`)}if(e.$?.deferredDropExpressions)for(let s of e.$.deferredDropExpressions){let l=O(s,t,n);l&&r.emitLine(`${t}${l};`)}}else if(!i){let o=O(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=O(o,t,n);a&&a.includes("sm->")&&r.emitLine(`${t}${a};`)}Mr({emitter:r,indent:t,resultCode:void 0,debugLabel:n.currentFunctionName}),r.emitLine(`${t}return;`)}function Qr(e){if(e.tag==="FnCall"&&gn(e))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(Qr(t))return!0}return!1}function z_(e){if(vt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(z_(t))return!0}return!1}function ta(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,S.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=O(s,n,r),_=s.$?.type;if(!_){a.emitLine(`${n}// Error: match value has no type`);return}if(e.$?.isPrimitiveMatch){ag(e,l,u,t,n,r,i,o);return}if(!Te(_)){a.emitLine(`${n}// Error: match requires an enum type or primitive type`);return}let c=_,p=r.types[c.id]?.cName;if(!p){a.emitLine(`${n}// Error: enum type has no C name`);return}let f=Kt(c);if(f){let d=-1,h=-1,g;for(let y=0;y<l.length;y++){let v=l[y];if(F(v)&&E(v,"=>",2)){let T=v.args[0];if(T&&F(T)&&E(T,"."))d=y;else if(T&&F(T)){let $=T.func;$&&F($)&&E($,".")&&(h=y,T.args.length>0&&B(T.args[0])&&(g=T.args[0].token.value))}}}if(a.emitLine(`${n}if (${u} != NULL) {`),h>=0){let y=l[h];if(!F(y))a.emitLine(`${n} // Error: Expected => in case`);else{let v=y.args[1];if(g){let T=r,$=!1,C;if(T.stateMachineVariables){for(let[L,b]of T.stateMachineVariables)if(b.name===g){$=!0,C=L;break}}if($&&C){let L=an(C,"local",T.stateMachineFieldAliases);a.emitLine(`${n} sm->${L} = ${u};`)}else a.emitLine(`${n} ${z(f,r)} ${g} = ${u};`)}if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${h};`),Qr(v)){let T=ao(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:h,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(io(e,v,r,i,o))oo(v,n+" ",r);else{let T=O(v,n+" ",r);if(i){let $=ie(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!st(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}if(a.emitLine(`${n}} else {`),d>=0){let y=l[d];if(!F(y))a.emitLine(`${n} // Error: Expected => in case`);else{let v=y.args[1];if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${d};`),Qr(v)){let T=ao(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:d,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(io(e,v,r,i,o))oo(v,n+" ",r);else{let T=O(v,n+" ",r);if(i){let $=ie(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!st(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}a.emitLine(`${n}}`)}else{a.emitLine(`${n}switch (${u}.tag) {`);let d=!1;for(let h=0;h<l.length;h++){let g=l[h];if(!F(g)||!E(g,"=>",2))continue;let y=g.args[0],v=g.args[1],T=B(y)&&y.token.value==="_",$;if(!T){if(F(y)&&E(y,".",1))$=y.args[0].token.value;else if(F(y)){let C=y.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)d=!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} = ${h};`),F(y)&&y.args.length>=1){let C=y.func;if(C&&F(C)&&E(C,".")){let L=c.variants.find(b=>b.name===$);if(L&&L.fields)for(let b=0;b<Math.min(y.args.length,L.fields.length);b++){let V=y.args[b],I=L.fields[b];if(B(V)&&I){let U=V.token.value,D=ie(U),x=r,R=!1,Q;if(x.stateMachineVariables){for(let[H,oe]of x.stateMachineVariables)if(oe.name===U){R=!0,Q=H;break}}let J=ie(I.label,I.type.isExtern==="c"),G=`${u}.data.${$}.${J}`;if(R&&Q){let H=an(Q,"local",x.stateMachineFieldAliases);a.emitLine(`${n} sm->${H} = ${G};`)}else{let H=z(I.type,r);a.emitLine(`${n} ${H} ${D} = ${G};`)}}}}}if(Qr(v)){let C=ao(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:h,value:v,hasAwait:!0,remainingExprs:C,deferredDropExpressions:v.$?.deferredDropExpressions}),L.asyncCondBranchInfo.set(t.index,b)}}else if(io(e,v,r,i,o))oo(v,n+" ",r);else{let C=O(v,n+" ",r);if(i){let L=ie(`var_${i}`);C&&a.emitLine(`${n} sm->${L} = ${C};`)}else o?C&&a.emitLine(`${n} ${o} = ${C};`):C&&v.$&&!st(v.$.env.modulePath,C)&&a.emitLine(`${n} ${C};`)}a.emitLine(`${n} break;`),a.emitLine(`${n} }`)}d||a.emitLine(`${n} default: break;`),a.emitLine(`${n}}`)}}function og(e){return F(e)?E(e,"|",2):!1}function gl(e){if(!og(e))return[e];if(e.tag!=="FnCall")return[e];let t=e.args[0],n=e.args[1];return[...gl(t),...gl(n)]}function ag(e,t,n,r,i,o,a,s){let l=o.emitter,u=[];l.emitLine(`${i}switch (${n}) {`);for(let _=0;_<t.length;_++){let c=t[_];if(!F(c)||!E(c,"=>",2))continue;let p=c.args[0],f=c.args[1];if(vt(p,"_"))l.emitLine(`${i} default:`);else{let d=p.$?.primitivePatternValues;if(d&&d.length>0){for(let h of d)if(h!==void 0){let g=en(h,o);l.emitLine(`${i} case ${g}:`)}}else{let h=gl(p);for(let g of h){let y=g.$?.value;if(y!==void 0){let v=en(y,o);l.emitLine(`${i} case ${v}:`)}}}}if(l.emitLine(`${i} sm->cond_branch_${r.index} = ${_};`),Qr(f)){let d=ao(f,r,i+" ",o);u.push({index:_,value:f,hasAwait:!0,remainingExprs:d,deferredDropExpressions:f.$?.deferredDropExpressions})}else{if(io(e,f,o,a,s))oo(f,i+" ",o);else{let d=O(f,i+" ",o);if(a){let h=ie(`var_${a}`);d&&l.emitLine(`${i} sm->${h} = ${d};`)}else s?d&&l.emitLine(`${i} ${s} = ${d};`):d&&f.$&&!st(f.$.env.modulePath,d)&&l.emitLine(`${i} ${d};`)}u.push({index:_,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 ao(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"&&gn(u)){let _=u.args[0];if(_){let c=O(_,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${c};`)}}}else if(l.tag==="FnCall"&&gn(l)){let u=l.args[0];if(u)if(t.futureVariableId===void 0){let _=O(u,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${_};`)}else i.emitLine(`${n}// Await will use Future from sm->var_${t.futureVariableId}`)}else if(l.tag==="FnCall"&&E(l,S.cond)){let u=l===a[a.length-1],_=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),ea(l,t,n,r),r.asyncBodyReturnExpr=_}else if(l.tag==="FnCall"&&E(l,S.match)){let u=l===a[a.length-1],_=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),ta(l,t,n,r),r.asyncBodyReturnExpr=_}else l.tag==="FnCall"&&E(l,S.while)&&vl(l,t,n,r);else{let u=O(l,n,r);u&&l.$&&!st(l.$.env.modulePath,u)&&i.emitLine(`${n}${u};`)}}return o}function vl(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=lg(l),_;u?(_=r.asyncNextWhileLoopIndex??t.index+1,r.asyncNextWhileLoopIndex=_+1):_=t.index,i.emitLine(`${n}sm->while_loop_${_}_active = true;`),i.emitLine(`${n}while_loop_${_}_start:`);let c=O(a,n,r);i.emitLine(`${n}if (!(${c})) {`),i.emitLine(`${n} sm->while_loop_${_}_active = false;`),i.emitLine(`${n} goto while_loop_${_}_end;`),i.emitLine(`${n}}`);let p=sg(l,t,n,r,_);if(i.emitLine(`${n}while_loop_${_}_end:`),r.asyncWhileLoopInfo||(r.asyncWhileLoopInfo=new Map),u){let f=r.asyncWhileLoopInfo.get(t.index);f&&(f.outerWhileLoop={whileLoopIndex:_,conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}else r.asyncWhileLoopInfo.set(t.index,{conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}function sg(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 d=s[f];if(pn(d)){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,_=r.smWhileContinueInfo,c=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 d=s[f],h=O(d,n,r);h&&d.$&&!st(d.$.env.modulePath,h)&&o.emitLine(`${n}${h};`)}r.smWhileBreakInfo=u,r.smWhileContinueInfo=_,r.smWhileBodyDrops=c;let p=s[l];if(F(p)&&E(p,S.while)&&pn(p)){vl(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"&&gn(f)){let d=f.args[0];if(d){let h=O(d,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${h};`)}}}else if(p.tag==="FnCall"&&gn(p)){let f=p.args[0];if(f&&t.futureVariableId===void 0){let d=O(f,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${d};`)}}else if(F(p)&&E(p,S.cond)){ea(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,S.match)){ta(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 lg(e){let t=e.tag==="FnCall"&&E(e,"begin")?e.args:[e];for(let n of t)if(n.tag==="FnCall"&&E(n,S.while)&&pn(n))return!0;return!1}function ki(e,t,n){if(e)switch(e.tag){case"Atom":if(e.$&&e.token.type==="identifier"){let r=e.token.value,i=j(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(Bt(e)){if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)ki(r,t,n);break}ki(e.func,t,n);for(let r of e.args)ki(r,t,n);if(e.$?.deferredDropExpressions)for(let r of e.$.deferredDropExpressions)ki(r,t,n);if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)ki(r,t,n);break}}function Ya(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=hl(e,n);for(let c of a)(c.awaitPoint?.isInsideCond||c.awaitPoint?.isInsideWhile)&&o.add(c.stateNumber);let s=new Map;for(let c of a){let p=new Set;for(let f of c.expressions)ki(f,p,i);for(let f of p){let d=s.get(f);d||(d=new Set,s.set(f,d)),d.add(c.stateNumber)}}let l=-1;if(e.$?.deferredDropExpressions){let c=new Set;for(let p of e.$.deferredDropExpressions)ki(p,c,i);for(let p of c){let f=s.get(p);f||(f=new Set,s.set(p,f)),f.add(l)}}let u=new Set;for(let c of r){if(c.kind==="outer")continue;let p=s.get(c.id);if(!p)u.add(c.id);else if(p.size>1)u.add(c.id);else if(p.has(l))u.add(c.id);else{let f=p.values().next().value;o.has(f)&&u.add(c.id)}}let _=new Map;for(let c of n){if(c.futureVariableId!==void 0)continue;let p=c.expr;if(!F(p))continue;let f=p.args[0];if(!f)continue;let d=f.$?.variableName;if(!d)continue;let h=r.find(g=>g.kind==="local"&&(g.name===d||g.id===d));h&&(_.set(h.id,`await_future_${c.index}`),u.delete(h.id))}return{crossBoundaryIds:u,awaitFutureTempVarAliases:_,variableSegments:s}}function Ha(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)&&!Ne(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 d=[...f].filter(y=>y>=0);if(d.length===0)continue;let h=Math.min(...d),g=Math.max(...d);s.set(p.id,[h,g])}if(s.size<2)return o;let l=new Map;for(let[p]of s){let f=a.find(g=>g.id===p);if(!f)continue;let d=z(f.type,i),h=l.get(d);h||(h=[],l.set(d,h)),h.push(p)}let u=new Map,_=[],c=0;for(let[p,f]of l){if(f.length<2)continue;let d=new Map;for(let y of f)d.set(y,new Set);for(let y=0;y<f.length;y++)for(let v=y+1;v<f.length;v++){let[T,$]=s.get(f[y]),[C,L]=s.get(f[v]);T<=L&&C<=$&&(d.get(f[y]).add(f[v]),d.get(f[v]).add(f[y]))}let h=new Map;for(let y of f){let v=new Set;for(let $ of d.get(y))h.has($)&&v.add(h.get($));let T=0;for(;v.has(T);)T++;h.set(y,T)}let g=new Map;for(let[y,v]of h){let T=g.get(v);T||(T=[],g.set(v,T)),T.push(y)}for(let[,y]of g){if(y.length<2)continue;let v=`slot_${c}`,T=y.map($=>a.find(C=>C.id===$)?.name??$);for(let $ of y)u.set($,v);_.push({fieldName:v,cType:p,variableNames:T}),c++}}return{slotAliases:u,slots:_}}function El(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 na(e){return!e||!M(e)?!1:e.resolvedConcreteType&&M(e.resolvedConcreteType)&&e.resolvedConcreteType.isExtern?!0:e.requiredTraits.some(t=>da(t.traitType))}function an(e,t,n){if(t==="outer")return`__capture.${ie(e)}`;let r=n?.get(e);return r||ie(`var_${e}`)}function B_(e,t,n,r,i,o,a,s){let l=s.emitter,_=Rt(o).isFuture.outputType,c=fe(_);s.asyncCondBranchInfo=new Map,s.asyncWhileLoopInfo=new Map,s.asyncNextWhileLoopIndex=i.awaitPoints.length;let p=hl(e,i.awaitPoints),f=e.tag==="FnCall"&&E(e,"begin")?e.args:[e],d=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 h=[];for(let g=0;g<p.length;g++){let y=p[g];if(!y)continue;let v=y.stateNumber,T=g===p.length-1;if(l.emitLine(`
194
- state_${v}:`),l.emitLine(` case ${v}: { // State ${v}`),l.emitLine(` ASYNC_DEBUG("${t}: Entering state ${v}\\n");`),v>0&&i.awaitPoints[v-1]){let x=i.awaitPoints[v-1],R=El(x,i);x.isInsideCond&&l.emitLine(` if (sm->${R} != NULL) {`);let Q=fe(x.resultType)||M(x.resultType)&&!x.resultType.resolvedConcreteType;if(l.emitLine(" // Check if the awaited Future was aborted"),l.emitLine(` if (sm->${R}->state == -2) {`),l.emitLine(` __yo_decr_rc((void*)sm->${R});`),l.emitLine(` sm->${R} = NULL;`),On({emitter:l,indent:" ",debugLabel:t}),l.emitLine(" }"),x&&!Q){l.emitLine(` // Extract result from await ${v-1}`),l.emitLine(` int state_before_read = sm->${R}->state;`),l.emitLine(` ASYNC_DEBUG("${t}: Reading result from await ${v-1}, state=%d\\n", state_before_read);`);let G=!!x.isInsideCond,H;if(G?H=`sm->await_result_${v-1}`:x.targetVariableId&&(H=`sm->${an(x.targetVariableId,"local",s.stateMachineFieldAliases)}`),H)if(Ne(x.resultType)){let oe=Dn(x.resultType,s);oe?l.emitLine(` ${H} = ${oe}(sm->${R}->result);`):(l.emitLine(" /* Warning: No ___dup function found for result type, shallow copy may cause use-after-free */"),l.emitLine(` ${H} = sm->${R}->result;`))}else l.emitLine(` ${H} = sm->${R}->result;`);if(G&&x.targetVariableId){let oe=an(x.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(` sm->${oe} = sm->await_result_${v-1};`)}l.emitLine("")}if(!x.futureVariableId){let G=x.expr;if(G.tag==="FnCall"){let oe=G.args[0]?.$?.type;oe&&(M(oe)||Ie(oe))&&(l.emitLine(` if (sm->${R} != NULL) { __yo_decr_rc((void*)sm->${R}); sm->${R} = NULL; }`),l.emitLine(""))}}let J=s;if(x){let G=J.asyncCondBranchInfo?.get(x.index);if(G&&G.branches.some(oe=>oe.hasAwait)){let oe=G.condBranchFieldIndex??x.index,ge=oe===-1;l.emitLine(" // Execute remaining code from chosen cond branch"),ge||l.emitLine(` switch (sm->cond_branch_${oe}) {`);let q=y.awaitPoint?.isInsideCond??!1;for(let Z of G.branches)if(Z.hasAwait){if(ge||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,Ae=s.stateMachineVariables,De=s.variableIdRemapping,he=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Xe=J.asyncWhileLoopInfo?.get(x.index);s.pendingDeferredDrops=[...Z.deferredDropExpressions??[],...Xe?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let re=new Map;for(let be of i.capturedVariables)re.set(be.id,be);if(a)for(let be of a.fields)re.set(be.label,{id:be.label,name:be.label,type:be.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=re;let ee=!1,_e=[],le=G.targetAssignmentCode;for(let be=0;be<Z.remainingExprs.length;be++){let ae=Z.remainingExprs[be],ye=be===Z.remainingExprs.length-1;if(ee){_e.push(ae);continue}if(q&&pn(ae)){ee=!0,Tl(ae,y.awaitPoint,i," ",s);continue}let we=O(ae," ",s);!we||!ae.$||st(ae.$.env.modulePath,we)||(ye&&le?l.emitLine(` ${le} = ${we};`):l.emitLine(` ${we};`))}if(Z.remainingExprs.length===0&&le&&l.emitLine(` ${le} = sm->await_result_${x.index};`),ee&&y.awaitPoint){let be=y.awaitPoint.index;J.asyncCondBranchInfo||(J.asyncCondBranchInfo=new Map);let ae=J.asyncCondBranchInfo.get(be);if(ae)ae.chainedBranches||(ae.chainedBranches=[]),ae.chainedBranches.push({branches:[{index:Z.index,value:Z.value,hasAwait:_e.length>0||_e.some(ye=>pn(ye)),remainingExprs:_e,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:oe});else{let ye={branches:[{index:Z.index,value:Z.value,hasAwait:_e.length>0||_e.some(we=>pn(we)),remainingExprs:_e,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:oe};J.asyncCondBranchInfo.set(be,ye)}}else if(Z.deferredDropExpressions)for(let be of Z.deferredDropExpressions){let ae=O(be," ",s);ae&&ae.includes("sm->")&&l.emitLine(` ${ae};`)}s.inAsyncStateMachine=se,s.stateMachineVariables=Ae,s.variableIdRemapping=De,s.pendingDeferredDrops=he}ge||(l.emitLine(" break;"),l.emitLine(" }"))}if(ge||l.emitLine(" }"),G.chainedBranches){for(let Z of G.chainedBranches)for(let se of Z.branches)if(se.hasAwait&&se.remainingExprs&&se.remainingExprs.length>0){let Ae=s.inAsyncStateMachine,De=s.stateMachineVariables,he=s.variableIdRemapping,Xe=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let re=J.asyncWhileLoopInfo?.get(x.index);s.pendingDeferredDrops=[...se.deferredDropExpressions??[],...re?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let ee=new Map;for(let ae of i.capturedVariables)ee.set(ae.id,ae);if(a)for(let ae of a.fields)ee.set(ae.label,{id:ae.label,name:ae.label,type:ae.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ee;let _e=y.awaitPoint?.isInsideCond??!1,le=!1,be=[];for(let ae of se.remainingExprs){if(le){be.push(ae);continue}if(_e&&pn(ae)){le=!0,Tl(ae,y.awaitPoint,i," ",s);continue}let ye=O(ae," ",s);!ye||!ae.$||st(ae.$.env.modulePath,ye)||l.emitLine(` ${ye};`)}if(le&&y.awaitPoint){let ae=y.awaitPoint.index;J.asyncCondBranchInfo||(J.asyncCondBranchInfo=new Map);let ye=J.asyncCondBranchInfo.get(ae);ye?(ye.chainedBranches||(ye.chainedBranches=[]),ye.chainedBranches.push({branches:[{index:se.index,value:se.value,hasAwait:be.length>0||be.some(we=>pn(we)),remainingExprs:be,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})):J.asyncCondBranchInfo.set(ae,{branches:[{index:se.index,value:se.value,hasAwait:be.length>0||be.some(we=>pn(we)),remainingExprs:be,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})}else if(se.deferredDropExpressions)for(let ae of se.deferredDropExpressions){let ye=O(ae," ",s);ye&&ye.includes("sm->")&&l.emitLine(` ${ye};`)}s.inAsyncStateMachine=Ae,s.stateMachineVariables=De,s.variableIdRemapping=he,s.pendingDeferredDrops=Xe}}if(G.targetVariableId){let Z=an(G.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(" // Assign cond result to target variable"),l.emitLine(` sm->${Z} = sm->await_result_${x.index};`)}l.emitLine("")}x.isInsideCond&&l.emitLine(" }");let H=J.asyncWhileLoopInfo?.get(x.index);if(H){if(l.emitLine(" // Execute remaining code from while loop body and continue loop"),l.emitLine(` if (sm->while_loop_${x.index}_active) {`),H.bodyExprsAfterAwait&&H.bodyExprsAfterAwait.length>0){let he=s.inAsyncStateMachine,Xe=s.stateMachineVariables,re=s.variableIdRemapping,ee=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...H.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let _e=new Map;for(let ye of i.capturedVariables)_e.set(ye.id,ye);if(a)for(let ye of a.fields)_e.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=_e;let le=s.smWhileBreakInfo,be=s.smWhileContinueInfo,ae=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${x.index}`,activeIndex:x.index},s.smWhileContinueInfo={label:`while_loop_${x.index}_continue`},s.smWhileBodyDrops=[...H.bodyExpr.$?.deferredDropExpressions??[]];for(let ye of H.bodyExprsAfterAwait){let we=O(ye," ",s);!we||!ye.$||st(ye.$.env.modulePath,we)||l.emitLine(` ${we};`)}s.smWhileBreakInfo=le,s.smWhileContinueInfo=be,s.smWhileBodyDrops=ae,s.inAsyncStateMachine=he,s.stateMachineVariables=Xe,s.variableIdRemapping=re,s.pendingDeferredDrops=ee}l.emitLine(` while_loop_${x.index}_continue:`);{let he=H.bodyExpr.$?.deferredDropExpressions??[];if(he.length>0){let Xe=s.inAsyncStateMachine,re=s.stateMachineVariables,ee=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let _e=new Map;for(let le of i.capturedVariables)_e.set(le.id,le);if(a)for(let le of a.fields)_e.set(le.label,{id:le.label,name:le.label,type:le.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=_e;for(let le of he){let be=O(le," ",s);be&&be.includes("sm->")&&l.emitLine(` ${be};`)}s.inAsyncStateMachine=Xe,s.stateMachineVariables=re,s.variableIdRemapping=ee}}l.emitLine(` ASYNC_DEBUG("${t}: Re-evaluating while loop condition\\n");`);let oe=s.declaredTempVars;if(s.declaredTempVars=void 0,H.stepExpr){let he=s.inAsyncStateMachine,Xe=s.stateMachineVariables,re=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let ee=new Map;for(let le of i.capturedVariables)ee.set(le.id,le);if(a)for(let le of a.fields)ee.set(le.label,{id:le.label,name:le.label,type:le.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ee;let _e=O(H.stepExpr," ",s);_e&&l.emitLine(` ${_e};`),s.inAsyncStateMachine=he,s.stateMachineVariables=Xe,s.variableIdRemapping=re}let ge=s.inAsyncStateMachine,q=s.stateMachineVariables,Z=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let se=new Map;for(let he of i.capturedVariables)se.set(he.id,he);if(a)for(let he of a.fields)se.set(he.label,{id:he.label,name:he.label,type:he.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=se;let Ae=O(H.conditionExpr," ",s);s.inAsyncStateMachine=ge,s.stateMachineVariables=q,s.variableIdRemapping=Z,s.declaredTempVars=oe,l.emitLine(` if (!(${Ae})) {`),l.emitLine(` sm->while_loop_${x.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 De=x.index;if(l.emitLine(" // Loop back by transitioning to while loop state"),l.emitLine(` sm->state = ${De};`),l.emitLine(` goto while_loop_${De}_start;`),l.emitLine(" }"),l.emitLine(" }"),l.emitLine(""),l.emitLine(` after_while_loop_${x.index}:`),H.condBranchPostWhileExprs){let he=H.condBranchPostWhileExprs,Xe=he.condBranchFieldIndex,re=he.branchIndex;he.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} == ${re}) {`));let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping,be=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let ae=new Map;for(let Ue of i.capturedVariables)ae.set(Ue.id,Ue);if(a)for(let Ue of a.fields)ae.set(Ue.label,{id:Ue.label,name:Ue.label,type:Ue.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ae;let ye=y.awaitPoint!=null,we=!1,je=[];for(let Ue=0;Ue<he.exprs.length;Ue++){let Je=he.exprs[Ue];if(we){je.push(Je);continue}if(ye&&pn(Je)){we=!0,Tl(Je,y.awaitPoint,i," ",s);continue}let Lt=O(Je," ",s);!Lt||!Je.$||st(Je.$.env.modulePath,Lt)||l.emitLine(` ${Lt};`)}if(we&&y.awaitPoint){let Ue=y.awaitPoint.index;J.asyncCondBranchInfo||(J.asyncCondBranchInfo=new Map);let Je=he.skipCondBranchCheck?-1:he.condBranchFieldIndex,Lt=J.asyncCondBranchInfo.get(Ue);Lt?(Lt.chainedBranches||(Lt.chainedBranches=[]),Lt.chainedBranches.push({branches:[{index:he.branchIndex,value:he.exprs[0],hasAwait:je.length>0||je.some(At=>pn(At)),remainingExprs:je,deferredDropExpressions:he.deferredDropExpressions}],condBranchFieldIndex:Je})):J.asyncCondBranchInfo.set(Ue,{branches:[{index:he.branchIndex,value:he.exprs[0],hasAwait:je.length>0||je.some(At=>pn(At)),remainingExprs:je,deferredDropExpressions:he.deferredDropExpressions}],condBranchFieldIndex:Je})}if(!we&&he.deferredDropExpressions)for(let Ue of he.deferredDropExpressions){let Je=O(Ue," ",s);Je&&Je.includes("sm->")&&l.emitLine(` ${Je};`)}l.emitLine(" }"),s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le,s.pendingDeferredDrops=be}if(H.outerWhileLoop){let he=H.outerWhileLoop,Xe=he.whileLoopIndex;if(l.emitLine(" // Execute remaining code from outer while loop body"),l.emitLine(` if (sm->while_loop_${Xe}_active) {`),he.bodyExprsAfterAwait.length>0){let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping,be=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...he.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let ae=new Map;for(let Ue of i.capturedVariables)ae.set(Ue.id,Ue);if(a)for(let Ue of a.fields)ae.set(Ue.label,{id:Ue.label,name:Ue.label,type:Ue.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ae;let ye=s.smWhileBreakInfo,we=s.smWhileContinueInfo,je=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${Xe}`,activeIndex:Xe},s.smWhileContinueInfo={label:`while_loop_${Xe}_continue`},s.smWhileBodyDrops=[...he.bodyExpr.$?.deferredDropExpressions??[]];for(let Ue of he.bodyExprsAfterAwait){let Je=O(Ue," ",s);!Je||!Ue.$||st(Ue.$.env.modulePath,Je)||l.emitLine(` ${Je};`)}s.smWhileBreakInfo=ye,s.smWhileContinueInfo=we,s.smWhileBodyDrops=je,s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le,s.pendingDeferredDrops=be}l.emitLine(` while_loop_${Xe}_continue:`);{let ee=he.bodyExpr.$?.deferredDropExpressions??[];if(ee.length>0){let _e=s.inAsyncStateMachine,le=s.stateMachineVariables,be=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let ae=new Map;for(let ye of i.capturedVariables)ae.set(ye.id,ye);if(a)for(let ye of a.fields)ae.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ae;for(let ye of ee){let we=O(ye," ",s);we&&we.includes("sm->")&&l.emitLine(` ${we};`)}s.inAsyncStateMachine=_e,s.stateMachineVariables=le,s.variableIdRemapping=be}}let re=s.declaredTempVars;if(s.declaredTempVars=void 0,he.stepExpr){let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let be=new Map;for(let ye of i.capturedVariables)be.set(ye.id,ye);if(a)for(let ye of a.fields)be.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=be;let ae=O(he.stepExpr," ",s);ae&&l.emitLine(` ${ae};`),s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le}{let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let be=new Map;for(let ye of i.capturedVariables)be.set(ye.id,ye);if(a)for(let ye of a.fields)be.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=be;let ae=O(he.conditionExpr," ",s);s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le,l.emitLine(` if (!(${ae})) {`),l.emitLine(` sm->while_loop_${Xe}_active = false;`),l.emitLine(" } else {"),l.emitLine(` sm->state = ${x.index};`),l.emitLine(` goto while_loop_${Xe}_start;`),l.emitLine(" }")}s.declaredTempVars=re,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 x of i.capturedVariables)b.set(x.id,x);if(a)for(let x of a.fields)b.set(x.label,{id:x.label,name:x.label,type:x.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=b;let V=s.pendingDeferredDrops;s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let I=T&&!c&&y.expressions.length>0,U=y.expressions.length>0?y.expressions[y.expressions.length-1]:void 0,D=s.asyncBodyReturnExpr;if(!c&&U&&d&&U===d&&y.awaitPoint?s.asyncBodyReturnExpr=U:s.asyncBodyReturnExpr=void 0,P_(y," ",s,I),s.asyncBodyReturnExpr=D,s.pendingDeferredDrops=V,l.emitLine(""),y.awaitPoint){s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L;let x=v+1;{let R=El(y.awaitPoint,i),J=y.awaitPoint.expr.args?.[0],G=na(J?.$?.type),H=y.awaitPoint?.isInsideCond;H&&(l.emitLine(" // Only await if the cond branch with await was taken"),l.emitLine(` if (sm->${R} != NULL) {`));let oe=y.awaitPoint?.isInsideWhile,ge=oe?s.asyncWhileLoopInfo?.get(y.awaitPoint.index):void 0;if(oe&&ge){let q=y.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 = ${x};`),l.emitLine(""),l.emitLine(" // Check if future is ready"),l.emitLine(` int future_state = sm->${R}->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(""),G?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->${R}); // event loop reference`)),G||(l.emitLine(" if (future_state == 0) { // 0 = cold (not started)"),_g(y.awaitPoint.expr,`sm->${R}`," ",s),l.emitLine(" // Cold future \u2014 start it via stored resume function pointer"),l.emitLine(` sm->${R}->__yo_resume_fn((void*)sm->${R});`),l.emitLine(""),l.emitLine(" // Re-check: may have completed synchronously"),l.emitLine(` future_state = sm->${R}->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->${R}->continuation_fn = (void (*)(void*))${r};`),l.emitLine(` sm->${R}->continuation_sm = (void*)sm;`),l.emitLine(" return;"),oe&&ge){let q=y.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(" }")}H&&(l.emitLine(" } else {"),l.emitLine(" // Non-await cond branch was taken, skip directly to next state"),l.emitLine(` sm->state = ${x};`),l.emitLine(` goto state_${x};`),l.emitLine(" }"))}}else if(T){if(!y.expressions.some(R=>G_(R))){if(e.$?.deferredDropExpressions){let R=new Ai,Q=s.emitter;s.emitter=R;for(let G of e.$.deferredDropExpressions){let H=O(G,"",s);H&&R.emitLine(`${H};`)}s.emitter=Q;let J=R.print().trim();if(J){l.emitLine(" // Drop local variables before completion");for(let G of J.split(`
195
- `)){let H=G.trim();H&&(l.emitLine(` ${H}`),h.push(H))}l.emitLine("")}}l.emitLine(" // Final state - complete the Future"),Mr({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(""),h}function Tl(e,t,n,r,i){let o=i.emitter,a=El(t,n);if(e.tag==="FnCall"&&E(e,":=")){let s=e.args[1];if(s&&s.tag==="FnCall"&&gn(s)){let l=s.args[0];if(l){let u=O(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"&&gn(e)){let s=e.args[0];if(s){let l=O(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,S.cond)){so(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,S.match)){so(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,S.while)){so(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,S.begin)){so(e,t,0,r,i);return}o.emitLine(`${r}// Warning: unhandled await pattern in remaining expressions`)}function G_(e){if(vt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(G_(t))return!0}return!1}function ug(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;M(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),at(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function _g(e,t,n,r){let i=e.args?.[0];if(!i?.$?.type)return;let o=Rt(i.$.type);if(!o?.isFuture.effects?.length)return;let a=ug(o.isFuture.effects),s=r.emitter,l=e.args?.find(u=>F(u)&&E(u,S.using));if(l){let u=l.args;for(let _=0;_<a.length&&_<u.length;_++){let c=a[_],p=u[_];if(W(c.type)){if(c.type.forallParameters.length>0)continue;let f=O(p,n,r),d=c.label;s.emitLine(`${n}${t}->__capture.${d} = (void*)${f};`)}else $e(c.type)&&U_(c.type,t,n,p.$?.value,r,e)}}else for(let u of a)if(W(u.type)){if(u.type.forallParameters.length>0)continue;let _=cg(u.label,r,e);_&&s.emitLine(`${n}${t}->__capture.${u.label} = (void*)${_};`)}else $e(u.type)&&U_(u.type,t,n,void 0,r,e)}function U_(e,t,n,r,i,o){let a=i.emitter;for(let s of e.fields){if(!W(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),_=r.fields[u];if(_&&ne(_)){let c=i.functions[_.funcId];c&&(l=c.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 _=hn(u,c=>c.isImplicit===!0);for(let c=_.length-1;c>=0;c--){let p=_[c],f=p.value?.[p.value.length-1];if(f&&We(f)){let d=f.type.fields.findIndex(h=>h.label===s.label);if(d>=0){let h=f.fields[d];if(h&&ne(h)){let g=i.functions[h.funcId]?.cName;if(g){l=g;break}}}}}}}l&&a.emitLine(`${n}${t}->__capture.${s.label} = (void*)${l};`)}}function cg(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 pg=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 W_(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(pg.has(r))continue;$l(i,r,!0,e);continue}i.isExtern==="c"&&i.cInclude||r.startsWith("__atomic_")||r.startsWith("__sync_")||$l(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"),dg(e),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Closure constructors"),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Capture dispose functions"),mg(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&&Ct(i.specializedType??i.type).length===0&&[...i.type.implicitParameters,...i.type.parameters.filter(h=>h.isImplicit)].some(h=>W(h.type)))continue;let u=i.specializedType??i.type,_=Ct(u).length>0;if(!o&&i.isIoAsyncStateMachineClosure||!o&&!s&&!_&&!i.isModuleEffectMember&&(fr(i.type)&&!i.type.isClosure||i.specializedFunctionCaches?.length>0&&!i.type.isClosure||Xr(i)||Cr(i)||i.isIoAsyncStateMachineClosure))continue;let c=i.specializedType??i.type,p=!s&&!i.isModuleEffectMember&&(c.parameters.some(h=>de(h.type))||c.forallParameters.length>0),f=de(c.return.type),d=M(c.return.type)&&c.return.type.requiredTraits.length>0;p||f&&!d&&!i.isModuleEffectMember||$l(c,r,!1,e,i.isModuleEffectMember?void 0:i.body,i.specializedType&&Ct(c).length===0&&Ct(i.type).some(h=>h.fieldFunctionType.forallParameters&&h.fieldFunctionType.forallParameters.length>0)?i.type:void 0)}t.emitDeclarationLine("/// Closure vtable instances"),t.emitDeclarationLine("")}function Ct(e){let t=[],n=fg(e.implicitParameters);for(let r of n)$e(r.type)?q_(r.label,r.type,[],t):W(r.type)&&t.push({implicitLabel:r.label,fieldLabel:r.label,fieldPath:[r.label],fieldFunctionType:r.type,cParamName:ie(r.label)});return t}function q_(e,t,n,r){for(let i of t.fields)if(W(i.type)){let o=[...n,i.label],a=o.join("__");r.push({implicitLabel:e,fieldLabel:a,fieldPath:o,fieldFunctionType:i.type,cParamName:ie(`${e}__${a}`)})}else $e(i.type)&&q_(e,i.type,[...n,i.label],r)}function fg(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;M(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),at(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function kr(e,t,n,r,i){let o=r||z(e.return.type,n),a=e.parameters.filter(c=>!c.isCompileTimeOnly),s=[];e.isClosure&&s.push("void* closure_context");let l=a.map((c,p)=>{let f=ie(c.label||`param${p}`);if(W(c.type))return kr(c.type,"(*)",n).replace(" (*)(",` (*${f})(`);{let d;return M(c.type)&&Fe(c.type)?c.type.resolvedConcreteType?d=z(c.type.resolvedConcreteType,n)+"*":d=z(c.type,n):d=z(c.type,n),`${d} ${f}`}});s.push(...l);let u=Ct(i??e);for(let c of u)if(c.fieldFunctionType.forallParameters&&c.fieldFunctionType.forallParameters.length>0)s.push(`void* ${c.cParamName}`);else{let p=kr(c.fieldFunctionType,"(*)",n).replace(" (*)(",` (*${c.cParamName})(`);s.push(p)}let _=s.join(", ");return`${o} ${t}(${_})`}function $l(e,t,n,r,i,o){let a;if(i&&Fe(e.return.type)){let p=Jo(i);p?.$?.asyncStateMachineStructName?a=`${p.$.asyncStateMachineStructName}*`:i.$?.type&&M(i.$.type)&&Fe(i.$.type)&&(a=z(i.$.type,r))}if(i&&M(e.return.type)&&!Fe(e.return.type)&&i.$?.type&&(a=z(i.$.type,r)),!a&&i&&i.$?.type&&!Fe(e.return.type)){let p=z(e.return.type,r),f=z(i.$.type,r);p!==f&&(a=f)}let s=a?kr(e,t,r,a,o):kr(e,t,r,void 0,o),l=A(e),u=t==="__yo_user_main"||r.exportedFunctionLabels&&[...r.exportedFunctionLabels.values()].some(p=>ie(p)===t),_=!n&&!u&&(t.includes("___drop")||t.includes("___dup")||t.includes("___dispose")),c=n?"extern ":u?"":_?"static inline __attribute__((always_inline)) ":"static inline ";r.emitter.emitDeclarationLine(`${c}${s}; // ${l}`)}function dg(e){let t=e.emitter;t.emitDeclarationLine("static inline void __yo_decr_rc(void* ptr); // Decrement reference count"),t.emitDeclarationLine("static inline 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(pe(r)&&r.isReferenceSemantics){if(r.fields.some(l=>de(l.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(l=>{let u=z(l.type,e),_=ie(l.label);return`${u} ${_}`}).join(", ");t.emitDeclarationLine(`static ${i}* ${a}(${s}); // Constructor`)}}}function mg(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 Y_(e){let t=new Set;for(let n in e.functions){let{value:r,cName:i}=e.functions[n],o=r.specializedType;if(Xr(r)||!o||!Wn(r.type)||Wn(o))continue;let a=o.parameters.some(c=>de(c.type)),s=de(o.return.type);if(a||s||Ct(r.type).some(c=>c.fieldFunctionType.forallParameters&&c.fieldFunctionType.forallParameters.length>0)||t.has(n))continue;t.add(n);let _=i.includes("___drop")||i.includes("___dup")||i.includes("___dispose")?"static inline __attribute__((always_inline)) ":"static inline ";e.emitter.emitDeclarationLine(`${_}${kr(o,i,e)}; // specialized function: ${A(r.type)}`)}}function wr(e,t,n){let r=j(t,e);return r.length===0?!1:r[r.length-1].frameLevel<=n}function H_(e){return!!(e.$?.closureFunctionValue&&e.$?.type&&Ht(e.$.type))}function yg(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 d=qa(f);d&&l.set(d,f)}let u=e.fields.map(f=>{if(f.isEffectParam)return"NULL";let d,h=f.exprs.expr;if(h.$?.deferredDupExpressions?.length&&(d=h.$.deferredDupExpressions[0]),!d){let y=[f.label];B(h)&&y.push(h.token.value);for(let v of y){let T=l.get(v);if(T){d=T;break}}}if(d)return O(d,r,i);let g={tag:"Atom",token:h.token,$:h.$};return O(g,r,i)}),_=`(${s}){ ${u.map((f,d)=>{let h=e.fields[d];return h?`.${h.label} = ${f}`:`/* Error: missing field at index ${d} */`}).join(", ")} }`,c=n.token.position.row!==void 0?`${Date.now()}_${n.token.position.row}`:`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=`__capture_${t}_${c}`;return o?i.emitter.emitLine(`${r}${s} ${p} = ${_};`):(i.emitter.emitLine(`${r}${s}* ${p} = (${s}*)__yo_malloc(sizeof(${s}));`),i.emitter.emitLine(`${r}*${p} = ${_};`)),{captureTempVar:p,captureCName:s}}function j_(e,t,n){if(!e.$||!e.$.type||!e.$.closureFunctionValue)return"// Error: Missing closure metadata";let r=on(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=Ie(e.$.type),u;if(l){let d=n.types[e.$.type.id];if(!d)return"// Error: Dyn closure type not found in context";u=d.cName}let _=a&&pe(a)&&a.fields.length>0,c=z(i.return.type,n),p=i.parameters.map(d=>z(d.type,n)).join(", "),f=`(${c} (*)(void*${p?", "+p:""}))${s}`;if(_&&a&&pe(a)){let d=!l,h=yg(a,i.id,e,t,n,d);if(!h)return"// Error: Failed to allocate closure capture";let{captureTempVar:g}=h;if(l){let y=`__yo_create_${u}`,v=`__yo_dispose_${u}`;return`${y}(${g}, ${v}, ${f})`}else return n.implClosureCallMap.set(a.id,{functionCName:s,callTypeId:r.isFn.callType.id,callType:r.isFn.callType}),g}else if(l){let d=`__yo_create_${u}`,h=`__yo_dispose_${u}`;return`${d}(NULL, ${h}, ${f})`}else{if(e.$.type.tag==="SomeType"){let d=e.$.type;if(d.resolvedConcreteType)return n.implClosureCallMap.set(d.resolvedConcreteType.id,{functionCName:s,callTypeId:r.isFn.callType.id,callType:r.isFn.callType}),`(${z(d.resolvedConcreteType,n)}){}`}return"// Error: Impl(Fn(...)) without captures missing resolvedConcreteType"}}function Cl(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=O(a,t,n);s&&n.emitter.emitLine(`${t}${s};`)}}}function lo(e,t,n=""){let r=t;if(e.token.value==="continue"){if(r.currentContinueLabel)return Cl(r,n,t),`goto ${r.currentContinueLabel}`;if(r.currentLoopLabel)return Cl(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=O(s,n,t);l&&l.includes("sm->")&&a.emitLine(`${n}${l};`)}}if(r.smWhileContinueInfo.stepExpr){let a=t.emitter,s=O(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 Cl(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 _=O(u,n,t);_&&_.includes("sm->")&&l.emitLine(`${n}${_};`)}}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=Rt(s).isFuture.outputType,_=fe(u);if(e.$?.deferredDropExpressions)for(let p of e.$.deferredDropExpressions){let f=O(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=O(p,n,t);f&&f.includes("sm->")&&a.emitLine(`${n}${f};`)}}a.emitLine(`${n}// Early return - complete the result Future`);let c=_?void 0:`(${z(u,t)}){0}`;return Mr({emitter:a,indent:n,resultCode:c,debugLabel:t.currentFunctionName}),""}return"return"}if(e.$?.type&&fe(e.$.type))return"";if((r.inAsyncStateMachine||r.inEffectStateMachine)&&r.stateMachineVariables){let a=e.token.value;if(r.localShadowedVariables?.has(a))return ie(a);let s=!1;if(e.$?.env){let l=j(e.$.env,a);if(l.length>0){let u=l[l.length-1],_=u.isOwningTheSameRcValueAs?u.isOwningTheSameRcValueAs.id:u.id;r.variableIdRemapping?.has(_)&&(_=r.variableIdRemapping.get(_));let c=r.stateMachineVariables.get(_);if(c){let p=r.stateMachineFieldAliases?.get(_);if(p)return s=!0,`sm->${p}`;let f=c.kind==="outer"?`__capture.${a}`:`var_${c.id}`;return s=!0,`sm->${f}`}}}if(!s){for(let[l,u]of r.stateMachineVariables)if(u.name===a){let _=r.stateMachineFieldAliases?.get(l);if(_)return s=!0,`sm->${_}`;let c=u.kind==="outer"?`__capture.${a}`:`var_${l}`;return s=!0,`sm->${c}`}}if(e.$?.env){let l=j(e.$.env,a);if(l.length>0){let u=l[l.length-1];if(u.isOwningTheSameRcValueAs){let _=u.isOwningTheSameRcValueAs.name,c=u.isOwningTheSameRcValueAs.id;for(let[p,f]of r.stateMachineVariables)if(f.name===_||p===c)return`sm->${f.kind==="outer"?`__capture.${_}`:`var_${p}`}`}}}if(r.currentClosureCaptures&&r.currentClosureCaptures.includes(a)&&r.currentClosureCaptureFrameLevel!==void 0){let l=r.currentClosureCaptureTypeCName;return l?`((${l}*)closure_context)->${ve(a,e.$?.env)}`:`closure_context->${ve(a,e.$?.env)}`}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!ce(e.$.value)){let l=j(e.$.env,e.$.variableName);if(l.length>0&&l[l.length-1].isCompileTimeOnly)return en(e.$.value,t,e)}return ve(e.$.variableName,e.$.env)}}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!ce(e.$.value)){let a=j(e.$.env,e.$.variableName);if(a.length>0&&a[a.length-1].isCompileTimeOnly)return en(e.$.value,t,e)}if(!(r.currentClosureCaptures&&r.currentClosureCaptures.includes(e.token.value)&&e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0&&wr(e.token.value,e.$.env,r.currentClosureCaptureFrameLevel)))return ve(e.$.variableName,e.$?.env)}if(e.$?.value&&!ce(e.$.value))return en(e.$.value,t,e);let i=e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0?wr(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)->${ve(e.token.value,e.$?.env)}`:`closure_context->${ve(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=>W(l.type)&&l.type.isClosure&&l.type===a.value.type);if(s)return`((${`${s.cName}_capture`}*)closure_context->data)->${ve(e.token.value,e.$?.env)}`}}if(e.$?.env){let a=j(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(W(s.type)&&(ce(s.value?.[0])||s.value===void 0)){let l=Object.entries(t.functions).find(([u,_])=>_.value.funcName===e.token.value);if(l)return l[1].cName}}}return ve(e.token.value,e.$?.env)}function K_(e,t,n){let r;if(Bt(e)){let y=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;y&&ne(y)&&(r=y.body)}else r=e.args[0];if(!r)return"/* Error: async requires exactly 1 argument */";let i=e.$?.type;if(!i||!Fe(i))return"/* Error: async block must have Future type */";let o=Rt(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}`,_=`${a}_state_dispose`;n.types[i.id]={type:i,cName:s};let c=e.$?.awaitAnalysis;if(!c)throw new Error("Missing await analysis for async block. This should have been computed during evaluation.");let p=o.isFuture.outputType;if(M(p))if(p.resolvedConcreteType)p=p.resolvedConcreteType;else{let y=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(y&&ne(y)){let v=y.type?.return?.type;if(v&&M(v)&&v.resolvedConcreteType)p=v.resolvedConcreteType;else if(y.body?.$?.type){let T=y.body.$.type;M(T)&&T.resolvedConcreteType?p=T.resolvedConcreteType:M(T)||(p=T)}}}let f=z(p,n),d=n.emitter;if(d.emitDeclarationLine(`void ${_}(void* sm_ptr); // Dispose function for state machine`),d.emitDeclarationLine(""),d.emitDeclarationLine(`void ${l}(${s}* sm);`),d.emitDeclarationLine(""),e.$?.captureType){let g=e.$.captureType,y=Object.values(n.types).find(T=>T.type===g),v=y?y.cName:`async_capture_${g.id}`;d.emitDeclarationLine(`${s}* ${u}(${v} __capture);`)}else d.emitDeclarationLine(`${s}* ${u}();`);d.emitDeclarationLine(""),n.deferredAsyncBlocks||(n.deferredAsyncBlocks=[]),n.deferredAsyncBlocks.push({bodyExpr:r,asyncBlockId:a,structName:s,resumeFunctionName:l,constructorName:u,disposeFunctionName:_,futureType:i,futureModuleType:o,resultType:p,resultTypeCName:f,captureType:e.$?.captureType,analysis:c});let h=e.$?.captureType;if(h){let g=Object.values(n.types).find(I=>I.type===h),y=g?g.cName:`async_capture_${h.id}`,v=n,T=v.currentClosureCaptures!==void 0||v.inAsyncStateMachine!==void 0||v.inEffectStateMachine!==void 0,$=!1,C=h.fields.map(I=>{if(I.isEffectParam)return`.${I.label} = NULL`;let U;if(!T&&e.$?.deferredDupExpressions)for(let x of e.$.deferredDupExpressions){let R;if(F(x)&&(x.args.length>0&&B(x.args[0])?R=x.args[0].token.value:x.args.length===0&&F(x.func)&&E(x.func,".")&&x.func.args.length>=2&&B(x.func.args[0])&&(R=x.func.args[0].token.value)),R===I.label){U=x;break}}if(U)return $=!0,U.$?.variableName?(O(U,t,n),`.${I.label} = ${U.$.variableName}`):`.${I.label} = ${O(U,t,n)}`;let D={tag:"Atom",token:I.exprs.expr.token,$:I.exprs.expr.$};return`.${I.label} = ${lo(D,n)}`}).join(", "),L=`(${y}){${C}}`;if(!$){let I=Dn(h,n);I&&(L=`${I}(${L})`)}let b=e.$?.variableName||"async_result",V=`${u}(${L})`;if(b&&e.$?.type){let I=ut(e.$.type,b,n);return n.emitter.emitLine(`${t}${I} = ${V};`),b}else return V}else{let g=e.$?.variableName||"async_result",y=`${u}()`;if(g&&e.$?.type){let v=ut(e.$.type,g,n);return n.emitter.emitLine(`${t}${v} = ${y};`),g}else return y}}function X_(e,t){let n=t.emitter,{asyncBlockId:r,structName:i,resultType:o,resultTypeCName:a,captureType:s,analysis:l,crossBoundaryIds:u,awaitFutureTempVarAliases:_,overlappingSlotAliases:c,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)"),fe(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 g=Object.values(t.types).find(v=>v.type===s),y=g?g.cName:`async_capture_${s.id}`;n.emitDeclarationLine(" // Captured variables from outer scope"),n.emitDeclarationLine(` ${y} __capture;`),n.emitDeclarationLine("")}let f=l.capturedVariables.filter(g=>g.kind!=="outer");if(u&&(f=f.filter(g=>u.has(g.id)&&!_?.has(g.id)&&!c?.has(g.id))),f.length>0){n.emitDeclarationLine(" // Local variables");for(let g of f){let y=z(g.type,t),v=an(g.id,"local");n.emitDeclarationLine(` ${y} ${v}; // ${g.name}`)}n.emitDeclarationLine("")}if(p&&p.length>0){n.emitDeclarationLine(" // Overlapping storage slots (Phase 2)");for(let g of p)n.emitDeclarationLine(` ${g.cType} ${g.fieldName}; // shared: ${g.variableNames.join(", ")}`);n.emitDeclarationLine("")}if(l.awaitPoints.length>0){let g=[];for(let y of l.awaitPoints)if(!(fe(y.resultType)||M(y.resultType)&&!y.resultType.resolvedConcreteType)&&y.isInsideCond){let $=y.resultType;if(y.futureType){let L=Rt(y.futureType);L&&($=L.isFuture.outputType)}let C=z($,t);g.push(` ${C} await_result_${y.index};`)}if(g.length>0){n.emitDeclarationLine(" // Await result temporaries");for(let y of g)n.emitDeclarationLine(y);n.emitDeclarationLine("")}}if(l.awaitPoints.length>0){let g=l.awaitPoints.filter(y=>y.futureVariableId===void 0);if(g.length>0){n.emitDeclarationLine(" // Future references for awaits");for(let y of g){let v=y.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=z($,t);n.emitDeclarationLine(` ${C} await_future_${y.index};`)}n.emitDeclarationLine("")}}let d=l.awaitPoints.filter(g=>g.needsOwnCondBranchField);if(d.length>0){n.emitDeclarationLine(" // Branch tracking for cond expressions with await");for(let g of d)n.emitDeclarationLine(` int cond_branch_${g.index}; // Which branch was taken in cond with await ${g.index}`);n.emitDeclarationLine("")}let h=l.awaitPoints.filter(g=>g.isInsideWhile);if(h.length>0){n.emitDeclarationLine(" // Loop state tracking for while loops with await");let g=l.awaitPoints.length;for(let y of h){n.emitDeclarationLine(` _Bool while_loop_${y.index}_active; // Whether while loop ${y.index} should continue`);let v=(y.whileNestingDepth??1)-1;for(let T=0;T<v;T++)n.emitDeclarationLine(` _Bool while_loop_${g}_active; // Whether outer while loop ${g} should continue`),g++}n.emitDeclarationLine("")}n.emitDeclarationLine("};"),n.emitDeclarationLine("")}function gg(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=_=>{let c=r.get(_);c.has(l.structName)||(c.add(l.structName),i.set(l.structName,(i.get(l.structName)??0)+1))};for(let _ of l.analysis.capturedVariables){let c;try{c=z(_.type,e)}catch{continue}let p=n.get(c);p&&p.structName!==l.structName&&u(p.structName)}for(let _ of l.analysis.awaitPoints){if(_.futureVariableId!==void 0)continue;let c=_.expr;if(c.tag!=="FnCall")continue;let f=c.args[0]?.$?.type;if(!f)continue;let d;try{d=z(f,e)}catch{continue}let h=n.get(d);h&&h.structName!==l.structName&&u(h.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 _ of u){let c=(i.get(_)??0)-1;i.set(_,c),c===0&&o.push(_)}}let s=a.length===t.length?a.map(l=>n.get(l)).filter(Boolean):t;for(let l of s){let{crossBoundaryIds:u,awaitFutureTempVarAliases:_,variableSegments:c}=Ya(l.bodyExpr,l.analysis),{slotAliases:p,slots:f}=Ha(u,c,l.analysis.capturedVariables,_,e);X_({asyncBlockId:l.asyncBlockId,structName:l.structName,resultType:l.resultType,resultTypeCName:l.resultTypeCName,captureType:l.captureType,analysis:l.analysis,crossBoundaryIds:u,awaitFutureTempVarAliases:_,overlappingSlotAliases:p,overlappingSlots:f},e)}}function hg(e,t,n,r,i,o,a,s,l,u){let _=u.emitter;if(_.emitLine(`// Dispose function for async block ${e} state machine`),_.emitLine("// Called by __yo_decr_rc when refcount hits 0 - do NOT call __yo_free here"),_.emitLine(`void ${n}(void* sm_ptr) {`),_.emitLine(` ${t}* sm = (${t}*)sm_ptr;`),_.emitLine(` ASYNC_DEBUG("${n}: Disposing state machine\\n");`),_.emitLine(""),i&&Ne(i)){let c=Object.values(u.types).find(p=>p.type===i);if(!c)_.emitLine(" /* Error: capture struct type not found in context */");else{let p=c.cName,f=i.trait.fields.find(d=>d.label===k.___drop[0]);if(f&&f.assignedValue&&ne(f.assignedValue)){let d=u.functions[f.assignedValue.funcId]?.cName;d&&(_.emitLine(' ASYNC_DEBUG(" Dropping capture struct\\n");'),_.emitLine(` ${d}(sm->__capture);`))}else _.emitLine(` /* Warning: ___drop function not found for capture struct ${p} */`)}}if(_.emitLine(""),!fe(r)&&Ne(r)){let c=z(r,u);_.emitLine(" // Drop result field if it was set (state == -1 means completed)"),_.emitLine(" int final_state = sm->state;"),_.emitLine(" if (final_state == -1) {"),_.emitLine(' ASYNC_DEBUG(" Dropping result field\\n");');let p=br(r,u);p?_.emitLine(` ${p}(sm->result);`):_.emitLine(` /* Warning: No ___drop function found for result type ${c} */`),_.emitLine(" }")}_.emitLine("");{let c=[];for(let p of o.capturedVariables){if(p.kind!=="local"||!s.has(p.id)||l.has(p.id)||p.isOwningTheSameRcValueAs!==void 0)continue;let d=`sm->${an(p.id,"local")}`;if(Ie(p.type))c.push(` if ((${d}).data != NULL) { __yo_decr_rc((void*)(${d}).data); }`);else if(Ft(p.type)||bt(p.type))c.push(` if (${d} != NULL) { __yo_decr_rc_atomic((void*)${d}); }`);else if(ft(p.type)||M(p.type)&&un(p.type)){let h=br(p.type,u);h?c.push(` if (${d} != NULL) { ${h}(${d}); }`):c.push(` if (${d} != NULL) { __yo_decr_rc((void*)${d}); }`)}else if(Ne(p.type)){let h=br(p.type,u);h&&c.push(` ${h}(${d});`)}}if(c.length>0){_.emitLine(" // Drop local variables on escape (state == -2)"),_.emitLine(" if (sm->state == -2) {");for(let p of c)_.emitLine(p);_.emitLine(" }")}}_.emitLine(" // Memory freed by __yo_decr_rc after this function returns"),_.emitLine("}")}function vg(e,t,n,r,i,o,a,s,l,u){let _=u.emitter;if(l){let c=Object.values(u.types).find(f=>f.type===l),p=c?c.cName:`async_capture_${l.id}`;_.emitLine(`${t}* ${r}(${p} __capture) {`)}else _.emitLine(`${t}* ${r}() {`);if(_.emitLine(" // Allocate async block state machine (heap-backed, ref-counted)"),_.emitLine(` ${t}* sm = (${t}*)__yo_malloc(sizeof(${t}));`),_.emitLine(` memset(sm, 0, sizeof(${t}));`),_.emitLine(""),_.emitLine(" // Initialize reference counting header"),_.emitLine(" sm->header.ref_count = 1; // Caller owns initial reference"),_.emitLine(` GC_DEBUG("AsyncBlock ${t}: Created ptr=%p RC=1\\n", (void*)sm);`),u.needsCycleGC&&(_.emitLine(" sm->header.gc_flags = 0;"),_.emitLine(" sm->header.gc_mark = __YO_GC_UNMARKED;"),_.emitLine(" sm->header.gc_next = NULL;"),_.emitLine(" sm->header.gc_prev = NULL;")),u.needsCycleGC)_.emitLine(` sm->header.dispose_fn = (void(*)(void*))${i};`);else{u.disposeTypeIds||(u.disposeTypeIds=new Map,u.nextDisposeTypeId=1);let c=u.disposeTypeIds.get(i);c===void 0&&(c=u.nextDisposeTypeId,u.nextDisposeTypeId=c+1,u.disposeTypeIds.set(i,c)),_.emitLine(` sm->header.type_id = ${c};`)}u.needsCycleGC&&_.emitLine(" sm->header.traverse_fn = NULL; // TODO: Add traverse for cycle detection if needed"),_.emitLine(""),_.emitLine(" sm->state = 0;"),_.emitLine(" sm->continuation_fn = NULL;"),_.emitLine(" sm->continuation_sm = NULL;"),_.emitLine(""),l&&(_.emitLine(" // Initialize captured variables"),_.emitLine(" sm->__capture = __capture;"),_.emitLine("")),_.emitLine(" // Initialize result (will be set when async block completes)"),fe(a)?_.emitLine(" // Result is unit type, no initialization needed"):_.emitLine(` memset(&sm->result, 0, sizeof(${s}));`),_.emitLine(""),_.emitLine(` sm->__yo_resume_fn = (void(*)(void*))${n};`),_.emitLine(""),_.emitLine(" return sm;"),_.emitLine("}"),_.emitLine("")}function Q_(e){if(!e.deferredAsyncBlocks||e.deferredAsyncBlocks.length===0)return;let t=e.emitter;gg(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:_,futureType:c,resultType:p,resultTypeCName:f,captureType:d,analysis:h}=r,g=e.stateMachineVariables,y=e.currentEvidenceParams,v=new Map,{crossBoundaryIds:T,awaitFutureTempVarAliases:$,variableSegments:C}=Ya(o,h),{slotAliases:L}=Ha(T,C,h.capturedVariables,$,e),b=h.capturedVariables.filter(x=>x.kind==="outer"||T.has(x.id)||$.has(x.id)||L.has(x.id)),V={...h,capturedVariables:b};for(let x of b)v.set(x.id,x);if(d)for(let x of d.fields)v.set(x.label,{id:x.label,name:x.label,type:x.type,kind:"outer",isOwningTheSameRcValueAs:void 0});e.stateMachineVariables=v;let I=e.stateMachineFieldAliases,U=new Map($);for(let[x,R]of L)U.set(x,R);e.stateMachineFieldAliases=U;let D=B_(o,a,s,l,V,c,d,e);if(e.stateMachineVariables=g,e.currentEvidenceParams=y,e.stateMachineFieldAliases=I,t.emitLine(""),hg(a,s,_,p,d,V,D,T,$,e),t.emitLine(""),vg(a,s,l,u,_,c,p,f,d,e),t.emitLine(""),e.deferredAsyncBlocks.length>i){let x=e.deferredAsyncBlocks.slice(i);for(let R of x){let{crossBoundaryIds:Q,awaitFutureTempVarAliases:J,variableSegments:G}=Ya(R.bodyExpr,R.analysis),{slotAliases:H,slots:oe}=Ha(Q,G,R.analysis.capturedVariables,J,e);X_({asyncBlockId:R.asyncBlockId,structName:R.structName,resultType:R.resultType,resultTypeCName:R.resultTypeCName,captureType:R.captureType,analysis:R.analysis,crossBoundaryIds:Q,awaitFutureTempVarAliases:J,overlappingSlotAliases:H,overlappingSlots:oe},e)}}n++}}function Z_(e){for(let t in e.functions){let{value:n}=e.functions[t];n.body&&J_(n.body,e)}}var Tg=["__yo_poll_","__yo_fs_event_","__yo_async_"];function Eg(e){return Tg.some(t=>e.startsWith(t))}function J_(e,t){if(e&&F(e)){let n=e;if(Bt(e)){t.usesAsync=!0;let r=e.$?.type;if(r&&Fe(r)&&Rt(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(Bt(e)){let r=e.$?.type;if(r&&Fe(r)&&Rt(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"}`)}}(gn(e)||Na(e))&&(t.usesAsync=!0);{let r=n.func.$?.type;r&&"isExtern"in r&&r.isExtern==="yo"&&"externName"in r&&typeof r.externName=="string"&&Eg(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)J_(r,t)}}function ec(e,t,n){let r=e.$?.type;if(!r||!Fe(r))return"/* Error: io.async must return a Future type */";let i=Rt(r);if(!i)return"/* Error: Could not extract Future module type */";let o=i.isFuture.outputType;if(M(o))if(o.resolvedConcreteType)o=o.resolvedConcreteType;else{let V=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(V&&ne(V)){let I=V.type?.return?.type;if(I&&M(I)&&I.resolvedConcreteType)o=I.resolvedConcreteType;else if(V.body?.$?.type){let U=V.body.$.type;M(U)&&U.resolvedConcreteType?o=U.resolvedConcreteType:M(U)||(o=U)}}}let a=z(o,n),s=e.$?.asyncStateMachineStructName;if(!s)return"/* Error: Missing sync future struct name */";let l=`${s}_dispose`,u=`${s}_resume`,_=n.emitter,c=e.$?.runtimeArgExprsInOrder?.[0];if(!c?.$)return"/* Error: Missing closure argument for io.async */";let p=O(c,t,n),f=c.$.type,d,h;if(M(f)&&f.resolvedConcreteType){let b=f.resolvedConcreteType,V=n.implClosureCallMap.get(b.id);V&&(d=V.functionCName);let I=n.types[b.id];I&&(h=I.cName)}if(!d||!h)return"/* Error: no closure function or capture type for io.async sync path */";_.emitDeclarationLine(`struct ${s}_struct {`),_.emitDeclarationLine(" __yo_ref_header_t header;"),_.emitDeclarationLine(" int state;"),fe(o)?_.emitDeclarationLine(" uint8_t result;"):_.emitDeclarationLine(` ${a} result;`),_.emitDeclarationLine(" void (*continuation_fn)(void*);"),_.emitDeclarationLine(" void* continuation_sm;"),_.emitDeclarationLine(" void (*__yo_resume_fn)(void*);"),_.emitDeclarationLine(` ${h} __capture;`),_.emitDeclarationLine("};"),_.emitDeclarationLine("");let g="";for(let b in n.functions){let V=n.functions[b];if(V.cName===d){let I=Ct(V.value.type);I.length>0&&(g=", "+I.map(U=>`(void*)sm->__capture.${U.fieldPath.join(".")}`).join(", "));break}}_.emitDeclarationLine(`void ${u}(void* ptr) {`),_.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),fe(o)?_.emitDeclarationLine(` ${d}(&sm->__capture${g});`):_.emitDeclarationLine(` sm->result = ${d}(&sm->__capture${g});`),g&&(_.emitDeclarationLine(" if (__yo_effect_escaped) {"),_.emitDeclarationLine(" __yo_effect_escaped = 0;"),_.emitDeclarationLine(" sm->state = -2;"),_.emitDeclarationLine(" __yo_decr_rc(ptr);"),_.emitDeclarationLine(" return;"),_.emitDeclarationLine(" }")),_.emitDeclarationLine(" sm->state = -1;"),_.emitDeclarationLine(" void (*continuation)(void*) = sm->continuation_fn;"),_.emitDeclarationLine(" if (continuation) {"),_.emitDeclarationLine(" void* cont_sm = sm->continuation_sm;"),_.emitDeclarationLine(" continuation(cont_sm);"),_.emitDeclarationLine(" }"),_.emitDeclarationLine(" __yo_decr_rc(ptr);"),_.emitDeclarationLine("}"),_.emitDeclarationLine("");let y=c.$.captureType,v=y&&Ne(y)?br(y,n):void 0,T=y&&Ne(y)?Dn(y,n):void 0,$=br(o,n);_.emitDeclarationLine(`void ${l}(void* ptr) {`),(v||$)&&(_.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),v&&(_.emitDeclarationLine(" // Drop captured variables (future owns its references)"),_.emitDeclarationLine(` ${v}(sm->__capture);`)),$&&(_.emitDeclarationLine(" if (sm->state == -1) {"),_.emitDeclarationLine(` ${$}(sm->result);`),_.emitDeclarationLine(" }"))),_.emitDeclarationLine("}"),_.emitDeclarationLine("");let C=e.$?.variableName||"__io_async_result",L=ut(r,C,n);if(_.emitLine(`${t}${L} = (${s}*)__yo_malloc(sizeof(${s}));`),_.emitLine(`${t}memset(${C}, 0, sizeof(${s}));`),_.emitLine(`${t}${C}->header.ref_count = 1;`),n.needsCycleGC&&(_.emitLine(`${t}${C}->header.gc_flags = 0;`),_.emitLine(`${t}${C}->header.gc_mark = __YO_GC_UNMARKED;`),_.emitLine(`${t}${C}->header.gc_next = NULL;`),_.emitLine(`${t}${C}->header.gc_prev = NULL;`)),n.needsCycleGC)_.emitLine(`${t}${C}->header.dispose_fn = (void(*)(void*))${l};`);else{n.disposeTypeIds||(n.disposeTypeIds=new Map,n.nextDisposeTypeId=1);let b=n.disposeTypeIds.get(l);b===void 0&&(b=n.nextDisposeTypeId,n.nextDisposeTypeId=b+1,n.disposeTypeIds.set(l,b)),_.emitLine(`${t}${C}->header.type_id = ${b};`)}return n.needsCycleGC&&_.emitLine(`${t}${C}->header.traverse_fn = NULL;`),_.emitLine(`${t}${C}->__capture = ${p};`),T&&_.emitLine(`${t}${C}->__capture = ${T}(${C}->__capture);`),_.emitLine(`${t}${C}->state = 0;`),_.emitLine(`${t}${C}->__yo_resume_fn = ${u};`),_.emitLine(`${t}${C}->continuation_fn = NULL;`),_.emitLine(`${t}${C}->continuation_sm = NULL;`),C}function tc(e,t){for(let i=0;i<e.fields.length;i++){let o=e.fields[i];ne(o)&&(Rr(o.type,t),Zr(o.body,t))}if(t.moduleLevelInitExprs)for(let i of t.moduleLevelInitExprs)Zr(i,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(Rr(o.value.type,t),o.value.specializedType&&Rr(o.value.specializedType,t),Zr(o.value.body,t),o.value.calledComptimeFunctionCaches)for(let a of o.value.calledComptimeFunctionCaches)a.value&&a.value.type&&Pt(a.value.type,t),Zr(a.body,t)}}}function Rr(e,t){for(let n of e.parameters)Pt(n.type,t);for(let n of e.forallParameters)Pt(n.type,t);Pt(e.return.type,t)}function Zr(e,t){if(e.$&&e.$.type&&Pt(e.$.type,t),e.$&&e.$.value&&ne(e.$.value)){let n=e.$.value;n.isControlFunction?(Rr(n.type,t),zt(n.body,t)):t.functions[n.funcId]||n.type.parameters.map(o=>o.type).some(o=>M(o)&&Fe(o)&&!o.resolvedConcreteType)||(t.functions[n.funcId]={value:n,cName:ie(n.funcId)},Rr(n.type,t),zt(n.body,t))}if(e.$&&e.$.deferredDropExpressions&&e.$.deferredDropExpressions.length>0)for(let n of e.$.deferredDropExpressions)Zr(n,t);if(e.$&&e.$.macroExpansion&&Zr(e.$.macroExpansion,t),e.$&&e.$.runtimeDestructurings)for(let{type:n}of e.$.runtimeDestructurings)Pt(n,t);if(e.$&&e.$.captureType&&pe(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)Pt(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},Rr(i.type,t),zt(i.body,t))}}}switch(e.tag){case"FnCall":if(E(e,S.test))break;Zr(e.func,t);for(let n of e.args)Zr(n,t);break;case"Atom":e.$?.value&&P(e.$.value)&&Pt(e.$.value.value,t);break}}function Pt(e,t){if(!t.types[e.id]){if(M(e)&&Ht(e)){if(e.resolvedConcreteType){Pt(e.resolvedConcreteType,t);return}let n=on(e);n&&Pt(n,t);return}if(M(e)&&Fe(e)){let n=Rt(e);n&&Pt(n.isFuture.outputType,t);return}if(M(e)&&e.resolvedConcreteType){Pt(e.resolvedConcreteType,t);return}if(!de(e)){if(pe(e)||nt(e)||Te(e)||xe(e)||Ie(e)||$e(e)||Ve(e)||qe(e)||Ft(e)||bt(e)){let n=qe(e)?z(e,t):e.isExtern==="c"&&e.externName?e.externName:`__yo_${e.id}`;if(t.types[e.id]={type:e,cName:n},pe(e))for(let r of e.fields)Pt(r.type,t);if(Te(e)){for(let r of e.variants)if(r.fields)for(let i of r.fields)Pt(i.type,t)}if(nt(e))for(let r of e.fields)Pt(r.type,t);if(Ie(e)){let r=e;for(let i of r.requiredTraits)Pt(i.traitType,t)}if(Ft(e)){let r=e;Pt(r.childType,t),z(r,t)}if(bt(e)){let r=e;Pt(r.childType,t),z(r,t)}if(qe(e)&&Pt(e.childType,t),$e(e)||Ve(e)){for(let r of e.fields)Pt(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:ie(i.funcId)},Rr(i.type,t),zt(i.body,t))}else if(r.assignedValue&&(We(r.assignedValue)||gt(r.assignedValue))){let i=r.assignedValue;ra(i,t)}}}else if(ke(e)){let n=e,r=n.childType,i=n.length;if(He(i)){Pt(r,t);let o=z(r,t),a=`Array_${ie(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(Ce(e)){if(Pt(e.childType,t),qe(e.childType)){let r=e.childType.childType;Pt(r,t);let i=z(r,t),o=`Slice_${ie(i)}`;t.sliceStructTypes.has(o)||t.sliceStructTypes.set(o,{childType:i})}t.types[e.id]={type:e,cName:z(e,t)}}else M_.has(e.tag)&&(t.types[e.id]={type:e,cName:z(e,t)});e.trait&&Pt(e.trait,t)}}}function wi(e){if(e.$&&e.$.value&&ce(e.$.value)&&!(W(e.$.type)&&e.$.type.isExtern)){if(!fe(e.$.type))return!0}if(F(e)){if(wi(e.func))return!0;for(let t of e.args)if(!(t.$?.type&&fe(t.$.type))&&wi(t))return!0}if(e.$&&e.$.macroExpansion){if(e.$.type&&fe(e.$.type))return!1;if(wi(e.$.macroExpansion))return!0}if(e.$?.deferredDupExpressions){for(let t of e.$.deferredDupExpressions)if(wi(t))return!0}if(e.$?.deferredDropExpressions){for(let t of e.$.deferredDropExpressions)if(wi(t))return!0}return!1}function ra(e,t,n=!0){for(let r=0;r<e.fields.length;r++){let i=e.fields[r],o=e.type.fields[r];if(ne(i)){let a=o.label;if(a==="main")t.functions[i.funcId]={value:i,cName:"__yo_user_main"};else if(t.isLibrary)if(n&&t.currentModuleId&&i.funcId.startsWith(`fn_${t.currentModuleId}_`)){let l=ie(a);Object.values(t.functions).some(_=>_.cName===l)?t.functions[i.funcId]={value:i,cName:ie(i.funcId)}:(t.functions[i.funcId]={value:i,cName:l},t.exportedFunctionLabels||(t.exportedFunctionLabels=new Map),t.exportedFunctionLabels.set(i.funcId,a))}else t.functions[i.funcId]={value:i,cName:ie(i.funcId)};else t.functions[i.funcId]={value:i,cName:ie(i.funcId)};zt(i.body,t)}}}function nc(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:ie(r.funcId)},zt(r.body,t)):r&&We(r)&&nc(r,t)}}function zt(e,t){if(e.$?.value&&We(e.$.value)){let i=e.$.value;nc(i,t)}if(F(e)&&E(e,S.test)||F(e)&&E(e,k.comptime_expect_error))return;if(e.$&&e.$.macroExpansion&&zt(e.$.macroExpansion,t),e.$?.effectAnalysis){let i=e.$.effectAnalysis.handlerValue;i&&ne(i)&&zt(i.body,t)}if(e.$&&e.$.closureFunctionValue){let i=e.$.closureFunctionValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:ie(i.funcId)},zt(i.body,t))}if(e.$?.indexMethodValue&&ne(e.$.indexMethodValue)){let i=e.$.indexMethodValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:ie(i.funcId)},zt(i.body,t))}if(F(e)&&e.$&&e.$.dynCallTraitValues&&e.$.dynCallTraitValues.length>0){let i=e.$.type,o=e.args[0];if(Ie(i)&&o&&o.$?.type){let a=o.$.type,s=e.$.dynCallTraitValues;if(s.length>0&&(ft(a)||Fn(a))){let l=Fn(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(W(i)){if(ne(o)&&o.isControlFunction){zt(o.body,t);for(let a of e.args)zt(a,t);return}if(ne(o)){if(o.type.return.isCompileTimeOnly||ds(o)&&!o.specializedType)return;if(o.specializedType&&fr(o.specializedType)&&Ct(o.specializedType).length===0){zt(e.func,t);for(let s of e.args)zt(s,t);return}if(!t.functions[o.funcId]){let a=!1;if(wi(o.body)){let s=o.specializedType??o.type;if(a=s.implicitParameters.length>0&&(Ct(s).length>0||!fr(o.type)&&o.type.implicitParameters.length>0),!a)return}if(!a&&!(Ct(o.specializedType??o.type).length>0)&&(o.specializedType??o.type).parameters.map(_=>_.type).some(_=>M(_)&&Fe(_)&&!_.resolvedConcreteType))return;t.functions[o.funcId]={value:o,cName:ie(o.funcId)},zt(o.body,t)}}else if(i.isExtern==="c"){let a=i.externName?i.externName:B(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?ie(a):B(e.func)?ie(e.func.token.value):ie(i.id);t.externFunctions[i.id]={type:i,cName:s}}}}zt(e.func,t);for(let a of e.args)zt(a,t)}let n=e.$?.type,r=e.$?.value;if(W(n)){if(ne(r)&&r.isControlFunction){if(r.isModuleEffectMember=!0,t.functions[r.funcId]||(t.functions[r.funcId]={value:r,cName:ie(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:ie(o.funcId)},zt(o.body,t))}zt(r.body,t);return}if(ne(r)){if(ds(r)&&!r.specializedFunctionCaches||t.functions[r.funcId])return;if(wi(r.body))return;t.functions[r.funcId]={value:r,cName:ie(r.funcId)},zt(r.body,t)}}if(P(e.$?.value)&&Pt(e.$.value.value,t),e.$?.deferredDupExpressions)for(let i of e.$.deferredDupExpressions)zt(i,t);if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions)zt(i,t);if(e.$?.dynCallTraitValues)for(let i of e.$.dynCallTraitValues)ra(i,t,!1)}function rc(e){let t=k.dispose[0];for(let n in e.types){let{type:r}=e.types[n];if(!pe(r)||!r.isReferenceSemantics)continue;let i=Bn({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:ie(a.funcId)},Rr(a.type,e),zt(a.body,e)}}}function ic(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 oc(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=M(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=z(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;"),e.needsCycleGC&&(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;"));let l=`__yo_dispose_${a}`;if(e.needsCycleGC)t.emitLine(` box->header.dispose_fn = ${l};`);else{e.disposeTypeIds||(e.disposeTypeIds=new Map,e.nextDisposeTypeId=1);let c=e.disposeTypeIds.get(l);c===void 0&&(c=e.nextDisposeTypeId,e.nextDisposeTypeId=c+1,e.disposeTypeIds.set(l,c)),t.emitLine(` box->header.type_id = ${c};`)}e.needsCycleGC&&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 _=(M(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType).trait?.fields.find(c=>c.label===k.___drop[0]);if(_&&_.assignedValue&&ne(_.assignedValue)){let c=e.functions[_.assignedValue.funcId]?.cName;c&&t.emitLine(` ${c}(box->value);`)}t.emitLine("}"),t.emitLine("")}}function ac(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(!wt(a))continue;let s=a.isFn.callType,l=z(s.return.type,e),u=`__yo_wrap_${n}_call`,_=["void* self_ptr"];for(let c=0;c<s.parameters.length;c++){let p=s.parameters[c],f=z(p.type,e);_.push(`${f} arg${c+1}`)}if(t.emitDeclarationLine(`static ${l} ${u}(${_.join(", ")}) {`),Fn(i)){let c=e.types[i.id]?.cName||`unknown_${i.id}`,p=ie(i.fields[0].label);t.emitDeclarationLine(` ${c}* box = (${c}*)self_ptr;`);let f=i.fields[0].type,d=M(f)&&f.resolvedConcreteType?f.resolvedConcreteType:f,h=e.implClosureCallMap.get(d.id),g=(()=>{if(h)return h.functionCName;for(let[,v]of Object.entries(e.functions))if(v.value.closureInfo?.captureType?.id===d.id)return v.cName})(),y=[];if(g){y.push(`(void*)&box->${p}`);for(let v=0;v<s.parameters.length;v++)y.push(`arg${v+1}`);Ar(s.return.type)?t.emitDeclarationLine(` ${g}(${y.join(", ")});`):t.emitDeclarationLine(` return ${g}(${y.join(", ")});`)}else{y.push(`box->${p}.data`);for(let v=0;v<s.parameters.length;v++)y.push(`arg${v+1}`);Ar(s.return.type)?t.emitDeclarationLine(` box->${p}.call(${y.join(", ")});`):t.emitDeclarationLine(` return box->${p}.call(${y.join(", ")});`)}}else{t.emitDeclarationLine(" (void)self_ptr; /* Dyn(Fn): expected Box(...) data */");for(let c=0;c<s.parameters.length;c++)t.emitDeclarationLine(` (void)arg${c+1};`);Ar(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(wt(s))continue;let l=r.traitValues[a];if(!l){t.emitDeclarationLine(`/* Warning: Module value missing for module ${a} */`);continue}let _=l.type.fields;for(let c=0;c<_.length;c++){let p=_[c];if(p.label==="Self"||o.has(p.label))continue;let f=l.fields[c];if(!f||!ne(f)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function value */`);continue}let d=p.type;if(!W(d)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function type */`);continue}let h=f.funcId,g=e.functions[h]?.cName;if(!g){t.emitDeclarationLine(`/* Warning: Impl function for ${p.label} not found */`);continue}let y=`__yo_wrap_${n}_${p.label}`,v=z(d.return.type,e),T=["void* self_ptr"];for(let b=1;b<d.parameters.length;b++){let V=d.parameters[b],I=z(V.type,e);T.push(`${I} arg${b}`)}t.emitDeclarationLine(`static ${v} ${y}(${T.join(", ")}) {`);let $=d.parameters[0]?.type,C;if(Fn(i)){let b=e.types[i.id]?.cName||`unknown_${i.id}`,V=ie(i.fields[0].label);t.emitDeclarationLine(` ${b}* box = (${b}*)self_ptr;`),$&&Ce($)?C=`&box->${V}`:C=`box->${V}`}else{let b=z(r.concreteType,e);t.emitDeclarationLine(` ${b} concrete_value = (${b})self_ptr;`),$&&Ce($)?C="&concrete_value":C="concrete_value"}let L=[C];for(let b=1;b<d.parameters.length;b++)L.push(`arg${b}`);Ar(d.return.type)?t.emitDeclarationLine(` ${g}(${L.join(", ")});`):t.emitDeclarationLine(` return ${g}(${L.join(", ")});`),t.emitDeclarationLine("}"),t.emitDeclarationLine("")}}}}}function sc(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=M(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=M(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`,_=`__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)&${_},`);let c=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(wt(f)){let d=`__yo_wrap_${r}_call`;t.emitDeclarationLine(` .call = ${d},`),c.add("call");continue}for(let d of f.fields)if(d.label!=="Self"&&!p.has(d.label)&&!c.has(d.label)&&(c.add(d.label),W(d.type))){let h=d.type;if(h.parameters.length>0){let g=h.parameters[0];if(g&&g.label==="self"){let y=`__yo_wrap_${r}_${d.label}`;t.emitDeclarationLine(` .${ie(d.label)} = ${y},`)}}}}t.emitDeclarationLine("};"),t.emitDeclarationLine("")}}function lc(e,t){let r=Gt(t)?"__declspec(thread)":"_Thread_local";e.emitLine(`
192
+ `;if(r.isNewtype&&r.fields.length===1&&e.fields.length===1){let o=en(e.fields[0],t);return`((${i})(${o}))`}if(r.isReferenceSemantics){let o=e.fields.map(s=>en(s,t));return`${`__yo_new_${i}`}(${o.join(", ")})`}else{let o=e.fields.map((a,s)=>{let l=a,u=xe(r)?`_${s}`:re(r.fields[s].label),_=en(l,t);return`.${u} = ${_}`});return`(${i}){ ${o.join(", ")} }`}}}else if(Sn(e)){let r=e.type,i=z(r,t),o=e.elements.map(a=>en(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}
193
+ `}else if(P(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(xi(e)){let r=e.targetValue[0];if(r){let i=n?.$?.convertedRuntimeType||n?.$?.type;if(i&&Ce(i)){let o=i.childType,a=en(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 ro(e,t,n){if(e===t)return!0;if(e.tag==="FnCall"){if(n&&n(e))return!1;if(ro(e.func,t,n))return!0;for(let r of e.args)if(ro(r,t,n))return!0}return!1}function rg(e,t,n){for(let r=0;r<t.length;r++)if(ro(e,t[r].expr,n))return r;return-1}function R_(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=rg(l,t,i),_=n?.handleReturnStatements&&(vt(l,"return")||E(l,"return"));if(u!==-1){if(s.push(l),a.push(s),s=[],n?.handleSequentialSuspensions)for(let c=u+1;c<t.length&&ro(l,t[c].expr,i);c++)a.push([])}else if(_){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],_=l<t.length?t[l]:null;r.push({stateNumber:l,expressions:u,suspensionPoint:_})}return r}function hl(e,t){let r=R_(e,t,{shouldSkipBody:Bt,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 ig(e,t){return ro(e,t,Bt)}function P_(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&&ig(a,e.awaitPoint.expr),u=e.awaitPoint&&a.tag==="FnCall"&&(E(a,S.while)||E(a,S.cond)||E(a,S.match))&&pn(a);if((l||u)&&e.awaitPoint)so(a,e.awaitPoint,e.stateNumber,t,n);else if(s&&r){let _=O(a,t,n);_&&(i.emitLine(`${t}// Store final expression result`),i.emitLine(`${t}sm->result = ${_};`))}else{let _=O(a,t,n);!_||!a.$||st(a.$.env.modulePath,_)||i.emitLine(`${t}${_};`)}}}function so(e,t,n,r,i){let o=i.emitter;if(e.tag==="FnCall"&&gn(e)){let a=e.args[0];if(!a){o.emitLine(`${r}// Error: await without argument`);return}if(t.futureVariableId===void 0){let s=O(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"&&gn(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 _=O(l,r,i);o.emitLine(`${r}// Store Future for await (variable: ${u})`),o.emitLine(`${r}sm->await_future_${t.index} = ${_};`)}else o.emitLine(`${r}// Store Future for await (variable: ${u}) - future already in state machine`);return}if(s.tag==="FnCall"&&E(s,S.cond)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,_=j(a.$.env,u);_.length>0&&(l=_[_.length-1].id)}ea(s,t,r,i,l);return}if(s.tag==="FnCall"&&E(s,S.match)){let l;if(a.tag==="Atom"&&a.token.type==="identifier"&&a.$){let u=a.token.value,_=j(a.$.env,u);_.length>0&&(l=_[_.length-1].id)}ta(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,S.cond)){let l=O(a,r,i);ea(s,t,r,i,void 0,l||void 0);return}if(s.tag==="FnCall"&&E(s,S.match)){let l=O(a,r,i);ta(s,t,r,i,void 0,l||void 0);return}}}if(e.tag==="FnCall"&&E(e,S.cond)){ea(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,S.match)){ta(e,t,r,i);return}if(e.tag==="FnCall"&&E(e,S.while)){vl(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 ea(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,S.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 g=0;g<s.length;g++){let y=s[g];if(y.tag==="FnCall"&&E(y,"=>")){let v=y.args[0];if(v&&!(Be(v.$?.value)&&v.$.value.value===!1)){u=g;break}}}let _=!1;if(u>=0){let g=s[u];if(g.tag==="FnCall"&&E(g,"=>")){let y=g.args[0];y&&Be(y.$?.value)&&y.$.value.value===!0&&(_=!0)}}if(_&&u>=0){let g=s[u],y=F(g)?g.args[1]:void 0;if(y)if(Qr(y)){let C=ao(y,t,n,r),L=r.asyncWhileLoopInfo?.get(t.index);if(L&&C.length>0){let V=r.asyncCondBranchInfo?.get(t.index)?.branches.some(I=>I.hasAwait&&I.remainingExprs&&I.remainingExprs.length>0)??!1;L.condBranchPostWhileExprs={branchIndex:u,condBranchFieldIndex:t.index,exprs:C,deferredDropExpressions:y.$?.deferredDropExpressions,skipCondBranchCheck:V},l.push({index:u,value:y,hasAwait:!0,remainingExprs:[],deferredDropExpressions:y.$?.deferredDropExpressions})}else l.push({index:u,value:y,hasAwait:!0,remainingExprs:C,deferredDropExpressions:y.$?.deferredDropExpressions})}else{if(io(e,y,r,i,o))oo(y,n,r);else if(F(y)&&E(y,S.begin)){let C=y.args;for(let L=0;L<C.length;L++){let b=C[L],V=O(b,n,r);if(V==="break"&&t.isInsideWhile)a.emitLine(`${n}sm->while_loop_${t.index}_active = false;`),a.emitLine(`${n}goto while_loop_${t.index}_end;`);else{let I=V==="break"||V==="continue"||V?.includes("return");V&&(I||b.$&&!st(b.$.env.modulePath,V))&&a.emitLine(`${n}${V};`)}}if(y.$?.deferredDropExpressions)for(let L of y.$.deferredDropExpressions){let b=O(L,n,r);b&&a.emitLine(`${n}${b};`)}}else{let C=O(y,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||y.$&&!st(y.$.env.modulePath,C))&&a.emitLine(`${n}${C};`)}}l.push({index:u,value:y,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 c=!1,p=0,f=n;for(let g=0;g<s.length;g++){let y=s[g];if(y.tag!=="FnCall"||!E(y,"=>")){a.emitLine(`${f}// Error: Expected => pair in cond`);continue}let v=y.args[0],T=y.args[1];if(!v||!T){a.emitLine(`${f}// Error: Invalid pair in cond`);continue}if(Be(v.$?.value)&&v.$.value.value===!1)continue;c&&(a.emitLine(`${f}else {`),p++,f+=" ");let $=g===s.length-1&&v.tag==="Atom"&&v.token?.value==="true"?null:O(v,f,r);$?a.emitLine(`${f}if (${$}) {`):a.emitLine(`${f}{`),c=!0;let C=`${f} `;if(Qr(T)){a.emitLine(`${C}sm->cond_branch_${t.index} = ${g};`);let b=ao(T,t,C,r),V=r.asyncWhileLoopInfo?.get(t.index);if(V&&b.length>0){let U=r.asyncCondBranchInfo?.get(t.index)?.branches.some(D=>D.hasAwait&&D.remainingExprs&&D.remainingExprs.length>0)??!1;V.condBranchPostWhileExprs={branchIndex:g,condBranchFieldIndex:t.index,exprs:b,deferredDropExpressions:T.$?.deferredDropExpressions,skipCondBranchCheck:U},l.push({index:g,value:T,hasAwait:!0,remainingExprs:[],deferredDropExpressions:T.$?.deferredDropExpressions})}else l.push({index:g,value:T,hasAwait:!0,remainingExprs:b,deferredDropExpressions:T.$?.deferredDropExpressions})}else{if(io(e,T,r,i,o))oo(T,C,r);else if(F(T)&&E(T,S.begin)){let b=T.args;for(let V=0;V<b.length;V++){let I=b[V],U=O(I,C,r);if(U==="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=U==="break"||U==="continue"||U?.includes("return");U&&(D||I.$&&!st(I.$.env.modulePath,U))&&a.emitLine(`${C}${U};`)}}if(T.$?.deferredDropExpressions)for(let V of T.$.deferredDropExpressions){let I=O(V,C,r);I&&a.emitLine(`${C}${I};`)}}else{let b=O(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 V=b==="break"||b==="continue"||b?.includes("return");b&&(V||T.$&&!st(T.$.env.modulePath,b))&&a.emitLine(`${C}${b};`)}}l.push({index:g,value:T,hasAwait:!1})}a.emitLine(`${f}}`)}for(let g=0;g<p;g++)f=f.slice(0,-2),a.emitLine(`${f}}`);r.asyncCondBranchInfo||(r.asyncCondBranchInfo=new Map),(r.asyncCondBranchInfo.get(t.index)?.branches.some(g=>g.hasAwait&&g.remainingExprs&&g.remainingExprs.length>0)??!1)||r.asyncCondBranchInfo.set(t.index,{branches:l,targetVariableId:i,targetAssignmentCode:o})}function io(e,t,n,r,i){return!r&&!i&&n.asyncBodyReturnExpr!==void 0&&e===n.asyncBodyReturnExpr&&!!n.inAsyncStateMachine&&!z_(t)}function oo(e,t,n){let r=n.emitter,i=fe(e.$?.type);if(F(e)&&E(e,S.begin)){let o=e.args;for(let s=0;s<o.length-1;s++){let l=o[s],u=O(l,t,n);u&&l.$&&!st(l.$.env.modulePath,u)&&r.emitLine(`${t}${u};`)}let a=o[o.length-1];if(a&&!i){let s=O(a,t,n);s&&r.emitLine(`${t}sm->result = ${s};`)}if(e.$?.deferredDropExpressions)for(let s of e.$.deferredDropExpressions){let l=O(s,t,n);l&&r.emitLine(`${t}${l};`)}}else if(!i){let o=O(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=O(o,t,n);a&&a.includes("sm->")&&r.emitLine(`${t}${a};`)}Mr({emitter:r,indent:t,resultCode:void 0,debugLabel:n.currentFunctionName}),r.emitLine(`${t}return;`)}function Qr(e){if(e.tag==="FnCall"&&gn(e))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(Qr(t))return!0}return!1}function z_(e){if(vt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(z_(t))return!0}return!1}function ta(e,t,n,r,i,o){let a=r.emitter;if(e.tag!=="FnCall"||!E(e,S.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=O(s,n,r),_=s.$?.type;if(!_){a.emitLine(`${n}// Error: match value has no type`);return}if(e.$?.isPrimitiveMatch){ag(e,l,u,t,n,r,i,o);return}if(!Te(_)){a.emitLine(`${n}// Error: match requires an enum type or primitive type`);return}let c=_,p=r.types[c.id]?.cName;if(!p){a.emitLine(`${n}// Error: enum type has no C name`);return}let f=Kt(c);if(f){let d=-1,h=-1,g;for(let y=0;y<l.length;y++){let v=l[y];if(F(v)&&E(v,"=>",2)){let T=v.args[0];if(T&&F(T)&&E(T,"."))d=y;else if(T&&F(T)){let $=T.func;$&&F($)&&E($,".")&&(h=y,T.args.length>0&&B(T.args[0])&&(g=T.args[0].token.value))}}}if(a.emitLine(`${n}if (${u} != NULL) {`),h>=0){let y=l[h];if(!F(y))a.emitLine(`${n} // Error: Expected => in case`);else{let v=y.args[1];if(g){let T=r,$=!1,C;if(T.stateMachineVariables){for(let[L,b]of T.stateMachineVariables)if(b.name===g){$=!0,C=L;break}}if($&&C){let L=an(C,"local",T.stateMachineFieldAliases);a.emitLine(`${n} sm->${L} = ${u};`)}else a.emitLine(`${n} ${z(f,r)} ${g} = ${u};`)}if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${h};`),Qr(v)){let T=ao(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:h,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(io(e,v,r,i,o))oo(v,n+" ",r);else{let T=O(v,n+" ",r);if(i){let $=re(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!st(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}if(a.emitLine(`${n}} else {`),d>=0){let y=l[d];if(!F(y))a.emitLine(`${n} // Error: Expected => in case`);else{let v=y.args[1];if(a.emitLine(`${n} sm->cond_branch_${t.index} = ${d};`),Qr(v)){let T=ao(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:d,value:v,hasAwait:!0,remainingExprs:T,deferredDropExpressions:v.$?.deferredDropExpressions}),$.asyncCondBranchInfo.set(t.index,C)}}else if(io(e,v,r,i,o))oo(v,n+" ",r);else{let T=O(v,n+" ",r);if(i){let $=re(`var_${i}`);T&&a.emitLine(`${n} sm->${$} = ${T};`)}else o?T&&a.emitLine(`${n} ${o} = ${T};`):T&&v.$&&!st(v.$.env.modulePath,T)&&a.emitLine(`${n} ${T};`)}}}a.emitLine(`${n}}`)}else{a.emitLine(`${n}switch (${u}.tag) {`);let d=!1;for(let h=0;h<l.length;h++){let g=l[h];if(!F(g)||!E(g,"=>",2))continue;let y=g.args[0],v=g.args[1],T=B(y)&&y.token.value==="_",$;if(!T){if(F(y)&&E(y,".",1))$=y.args[0].token.value;else if(F(y)){let C=y.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)d=!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} = ${h};`),F(y)&&y.args.length>=1){let C=y.func;if(C&&F(C)&&E(C,".")){let L=c.variants.find(b=>b.name===$);if(L&&L.fields)for(let b=0;b<Math.min(y.args.length,L.fields.length);b++){let V=y.args[b],I=L.fields[b];if(B(V)&&I){let U=V.token.value,D=re(U),x=r,R=!1,Q;if(x.stateMachineVariables){for(let[H,oe]of x.stateMachineVariables)if(oe.name===U){R=!0,Q=H;break}}let J=re(I.label,I.type.isExtern==="c"),G=`${u}.data.${$}.${J}`;if(R&&Q){let H=an(Q,"local",x.stateMachineFieldAliases);a.emitLine(`${n} sm->${H} = ${G};`)}else{let H=z(I.type,r);a.emitLine(`${n} ${H} ${D} = ${G};`)}}}}}if(Qr(v)){let C=ao(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:h,value:v,hasAwait:!0,remainingExprs:C,deferredDropExpressions:v.$?.deferredDropExpressions}),L.asyncCondBranchInfo.set(t.index,b)}}else if(io(e,v,r,i,o))oo(v,n+" ",r);else{let C=O(v,n+" ",r);if(i){let L=re(`var_${i}`);C&&a.emitLine(`${n} sm->${L} = ${C};`)}else o?C&&a.emitLine(`${n} ${o} = ${C};`):C&&v.$&&!st(v.$.env.modulePath,C)&&a.emitLine(`${n} ${C};`)}a.emitLine(`${n} break;`),a.emitLine(`${n} }`)}d||a.emitLine(`${n} default: break;`),a.emitLine(`${n}}`)}}function og(e){return F(e)?E(e,"|",2):!1}function gl(e){if(!og(e))return[e];if(e.tag!=="FnCall")return[e];let t=e.args[0],n=e.args[1];return[...gl(t),...gl(n)]}function ag(e,t,n,r,i,o,a,s){let l=o.emitter,u=[];l.emitLine(`${i}switch (${n}) {`);for(let _=0;_<t.length;_++){let c=t[_];if(!F(c)||!E(c,"=>",2))continue;let p=c.args[0],f=c.args[1];if(vt(p,"_"))l.emitLine(`${i} default:`);else{let d=p.$?.primitivePatternValues;if(d&&d.length>0){for(let h of d)if(h!==void 0){let g=en(h,o);l.emitLine(`${i} case ${g}:`)}}else{let h=gl(p);for(let g of h){let y=g.$?.value;if(y!==void 0){let v=en(y,o);l.emitLine(`${i} case ${v}:`)}}}}if(l.emitLine(`${i} sm->cond_branch_${r.index} = ${_};`),Qr(f)){let d=ao(f,r,i+" ",o);u.push({index:_,value:f,hasAwait:!0,remainingExprs:d,deferredDropExpressions:f.$?.deferredDropExpressions})}else{if(io(e,f,o,a,s))oo(f,i+" ",o);else{let d=O(f,i+" ",o);if(a){let h=re(`var_${a}`);d&&l.emitLine(`${i} sm->${h} = ${d};`)}else s?d&&l.emitLine(`${i} ${s} = ${d};`):d&&f.$&&!st(f.$.env.modulePath,d)&&l.emitLine(`${i} ${d};`)}u.push({index:_,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 ao(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"&&gn(u)){let _=u.args[0];if(_){let c=O(_,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${c};`)}}}else if(l.tag==="FnCall"&&gn(l)){let u=l.args[0];if(u)if(t.futureVariableId===void 0){let _=O(u,n,r);i.emitLine(`${n}// Store Future for await ${t.index} (cond branch)`),i.emitLine(`${n}sm->await_future_${t.index} = ${_};`)}else i.emitLine(`${n}// Await will use Future from sm->var_${t.futureVariableId}`)}else if(l.tag==="FnCall"&&E(l,S.cond)){let u=l===a[a.length-1],_=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),ea(l,t,n,r),r.asyncBodyReturnExpr=_}else if(l.tag==="FnCall"&&E(l,S.match)){let u=l===a[a.length-1],_=r.asyncBodyReturnExpr;u&&r.asyncBodyReturnExpr!==void 0&&(r.asyncBodyReturnExpr=l),ta(l,t,n,r),r.asyncBodyReturnExpr=_}else l.tag==="FnCall"&&E(l,S.while)&&vl(l,t,n,r);else{let u=O(l,n,r);u&&l.$&&!st(l.$.env.modulePath,u)&&i.emitLine(`${n}${u};`)}}return o}function vl(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=lg(l),_;u?(_=r.asyncNextWhileLoopIndex??t.index+1,r.asyncNextWhileLoopIndex=_+1):_=t.index,i.emitLine(`${n}sm->while_loop_${_}_active = true;`),i.emitLine(`${n}while_loop_${_}_start:`);let c=O(a,n,r);i.emitLine(`${n}if (!(${c})) {`),i.emitLine(`${n} sm->while_loop_${_}_active = false;`),i.emitLine(`${n} goto while_loop_${_}_end;`),i.emitLine(`${n}}`);let p=sg(l,t,n,r,_);if(i.emitLine(`${n}while_loop_${_}_end:`),r.asyncWhileLoopInfo||(r.asyncWhileLoopInfo=new Map),u){let f=r.asyncWhileLoopInfo.get(t.index);f&&(f.outerWhileLoop={whileLoopIndex:_,conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}else r.asyncWhileLoopInfo.set(t.index,{conditionExpr:a,stepExpr:s,bodyExpr:l,bodyExprsAfterAwait:p})}function sg(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 d=s[f];if(pn(d)){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,_=r.smWhileContinueInfo,c=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 d=s[f],h=O(d,n,r);h&&d.$&&!st(d.$.env.modulePath,h)&&o.emitLine(`${n}${h};`)}r.smWhileBreakInfo=u,r.smWhileContinueInfo=_,r.smWhileBodyDrops=c;let p=s[l];if(F(p)&&E(p,S.while)&&pn(p)){vl(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"&&gn(f)){let d=f.args[0];if(d){let h=O(d,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${h};`)}}}else if(p.tag==="FnCall"&&gn(p)){let f=p.args[0];if(f&&t.futureVariableId===void 0){let d=O(f,n,r);o.emitLine(`${n}// Store Future for await ${t.index} (while loop body)`),o.emitLine(`${n}sm->await_future_${t.index} = ${d};`)}}else if(F(p)&&E(p,S.cond)){ea(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,S.match)){ta(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 lg(e){let t=e.tag==="FnCall"&&E(e,"begin")?e.args:[e];for(let n of t)if(n.tag==="FnCall"&&E(n,S.while)&&pn(n))return!0;return!1}function ki(e,t,n){if(e)switch(e.tag){case"Atom":if(e.$&&e.token.type==="identifier"){let r=e.token.value,i=j(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(Bt(e)){if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)ki(r,t,n);break}ki(e.func,t,n);for(let r of e.args)ki(r,t,n);if(e.$?.deferredDropExpressions)for(let r of e.$.deferredDropExpressions)ki(r,t,n);if(e.$?.deferredDupExpressions)for(let r of e.$.deferredDupExpressions)ki(r,t,n);break}}function Ya(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=hl(e,n);for(let c of a)(c.awaitPoint?.isInsideCond||c.awaitPoint?.isInsideWhile)&&o.add(c.stateNumber);let s=new Map;for(let c of a){let p=new Set;for(let f of c.expressions)ki(f,p,i);for(let f of p){let d=s.get(f);d||(d=new Set,s.set(f,d)),d.add(c.stateNumber)}}let l=-1;if(e.$?.deferredDropExpressions){let c=new Set;for(let p of e.$.deferredDropExpressions)ki(p,c,i);for(let p of c){let f=s.get(p);f||(f=new Set,s.set(p,f)),f.add(l)}}let u=new Set;for(let c of r){if(c.kind==="outer")continue;let p=s.get(c.id);if(!p)u.add(c.id);else if(p.size>1)u.add(c.id);else if(p.has(l))u.add(c.id);else{let f=p.values().next().value;o.has(f)&&u.add(c.id)}}let _=new Map;for(let c of n){if(c.futureVariableId!==void 0)continue;let p=c.expr;if(!F(p))continue;let f=p.args[0];if(!f)continue;let d=f.$?.variableName;if(!d)continue;let h=r.find(g=>g.kind==="local"&&(g.name===d||g.id===d));h&&(_.set(h.id,`await_future_${c.index}`),u.delete(h.id))}return{crossBoundaryIds:u,awaitFutureTempVarAliases:_,variableSegments:s}}function Ha(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)&&!Ne(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 d=[...f].filter(y=>y>=0);if(d.length===0)continue;let h=Math.min(...d),g=Math.max(...d);s.set(p.id,[h,g])}if(s.size<2)return o;let l=new Map;for(let[p]of s){let f=a.find(g=>g.id===p);if(!f)continue;let d=z(f.type,i),h=l.get(d);h||(h=[],l.set(d,h)),h.push(p)}let u=new Map,_=[],c=0;for(let[p,f]of l){if(f.length<2)continue;let d=new Map;for(let y of f)d.set(y,new Set);for(let y=0;y<f.length;y++)for(let v=y+1;v<f.length;v++){let[T,$]=s.get(f[y]),[C,L]=s.get(f[v]);T<=L&&C<=$&&(d.get(f[y]).add(f[v]),d.get(f[v]).add(f[y]))}let h=new Map;for(let y of f){let v=new Set;for(let $ of d.get(y))h.has($)&&v.add(h.get($));let T=0;for(;v.has(T);)T++;h.set(y,T)}let g=new Map;for(let[y,v]of h){let T=g.get(v);T||(T=[],g.set(v,T)),T.push(y)}for(let[,y]of g){if(y.length<2)continue;let v=`slot_${c}`,T=y.map($=>a.find(C=>C.id===$)?.name??$);for(let $ of y)u.set($,v);_.push({fieldName:v,cType:p,variableNames:T}),c++}}return{slotAliases:u,slots:_}}function El(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 na(e){return!e||!M(e)?!1:e.resolvedConcreteType&&M(e.resolvedConcreteType)&&e.resolvedConcreteType.isExtern?!0:e.requiredTraits.some(t=>da(t.traitType))}function an(e,t,n){if(t==="outer")return`__capture.${re(e)}`;let r=n?.get(e);return r||re(`var_${e}`)}function B_(e,t,n,r,i,o,a,s){let l=s.emitter,_=Rt(o).isFuture.outputType,c=fe(_);s.asyncCondBranchInfo=new Map,s.asyncWhileLoopInfo=new Map,s.asyncNextWhileLoopIndex=i.awaitPoints.length;let p=hl(e,i.awaitPoints),f=e.tag==="FnCall"&&E(e,"begin")?e.args:[e],d=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 h=[];for(let g=0;g<p.length;g++){let y=p[g];if(!y)continue;let v=y.stateNumber,T=g===p.length-1;if(l.emitLine(`
194
+ state_${v}:`),l.emitLine(` case ${v}: { // State ${v}`),l.emitLine(` ASYNC_DEBUG("${t}: Entering state ${v}\\n");`),v>0&&i.awaitPoints[v-1]){let x=i.awaitPoints[v-1],R=El(x,i);x.isInsideCond&&l.emitLine(` if (sm->${R} != NULL) {`);let Q=fe(x.resultType)||M(x.resultType)&&!x.resultType.resolvedConcreteType;if(l.emitLine(" // Check if the awaited Future was aborted"),l.emitLine(` if (sm->${R}->state == -2) {`),l.emitLine(` __yo_decr_rc((void*)sm->${R});`),l.emitLine(` sm->${R} = NULL;`),On({emitter:l,indent:" ",debugLabel:t}),l.emitLine(" }"),x&&!Q){l.emitLine(` // Extract result from await ${v-1}`),l.emitLine(` int state_before_read = sm->${R}->state;`),l.emitLine(` ASYNC_DEBUG("${t}: Reading result from await ${v-1}, state=%d\\n", state_before_read);`);let G=!!x.isInsideCond,H;if(G?H=`sm->await_result_${v-1}`:x.targetVariableId&&(H=`sm->${an(x.targetVariableId,"local",s.stateMachineFieldAliases)}`),H)if(Ne(x.resultType)){let oe=Dn(x.resultType,s);oe?l.emitLine(` ${H} = ${oe}(sm->${R}->result);`):(l.emitLine(" /* Warning: No ___dup function found for result type, shallow copy may cause use-after-free */"),l.emitLine(` ${H} = sm->${R}->result;`))}else l.emitLine(` ${H} = sm->${R}->result;`);if(G&&x.targetVariableId){let oe=an(x.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(` sm->${oe} = sm->await_result_${v-1};`)}l.emitLine("")}if(!x.futureVariableId){let G=x.expr;if(G.tag==="FnCall"){let oe=G.args[0]?.$?.type;oe&&(M(oe)||Ie(oe))&&(l.emitLine(` if (sm->${R} != NULL) { __yo_decr_rc((void*)sm->${R}); sm->${R} = NULL; }`),l.emitLine(""))}}let J=s;if(x){let G=J.asyncCondBranchInfo?.get(x.index);if(G&&G.branches.some(oe=>oe.hasAwait)){let oe=G.condBranchFieldIndex??x.index,ge=oe===-1;l.emitLine(" // Execute remaining code from chosen cond branch"),ge||l.emitLine(` switch (sm->cond_branch_${oe}) {`);let q=y.awaitPoint?.isInsideCond??!1;for(let Z of G.branches)if(Z.hasAwait){if(ge||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,Ae=s.stateMachineVariables,De=s.variableIdRemapping,he=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let Xe=J.asyncWhileLoopInfo?.get(x.index);s.pendingDeferredDrops=[...Z.deferredDropExpressions??[],...Xe?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let ie=new Map;for(let be of i.capturedVariables)ie.set(be.id,be);if(a)for(let be of a.fields)ie.set(be.label,{id:be.label,name:be.label,type:be.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ie;let ee=!1,_e=[],le=G.targetAssignmentCode;for(let be=0;be<Z.remainingExprs.length;be++){let ae=Z.remainingExprs[be],ye=be===Z.remainingExprs.length-1;if(ee){_e.push(ae);continue}if(q&&pn(ae)){ee=!0,Tl(ae,y.awaitPoint,i," ",s);continue}let we=O(ae," ",s);!we||!ae.$||st(ae.$.env.modulePath,we)||(ye&&le?l.emitLine(` ${le} = ${we};`):l.emitLine(` ${we};`))}if(Z.remainingExprs.length===0&&le&&l.emitLine(` ${le} = sm->await_result_${x.index};`),ee&&y.awaitPoint){let be=y.awaitPoint.index;J.asyncCondBranchInfo||(J.asyncCondBranchInfo=new Map);let ae=J.asyncCondBranchInfo.get(be);if(ae)ae.chainedBranches||(ae.chainedBranches=[]),ae.chainedBranches.push({branches:[{index:Z.index,value:Z.value,hasAwait:_e.length>0||_e.some(ye=>pn(ye)),remainingExprs:_e,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:oe});else{let ye={branches:[{index:Z.index,value:Z.value,hasAwait:_e.length>0||_e.some(we=>pn(we)),remainingExprs:_e,deferredDropExpressions:Z.deferredDropExpressions}],condBranchFieldIndex:oe};J.asyncCondBranchInfo.set(be,ye)}}else if(Z.deferredDropExpressions)for(let be of Z.deferredDropExpressions){let ae=O(be," ",s);ae&&ae.includes("sm->")&&l.emitLine(` ${ae};`)}s.inAsyncStateMachine=se,s.stateMachineVariables=Ae,s.variableIdRemapping=De,s.pendingDeferredDrops=he}ge||(l.emitLine(" break;"),l.emitLine(" }"))}if(ge||l.emitLine(" }"),G.chainedBranches){for(let Z of G.chainedBranches)for(let se of Z.branches)if(se.hasAwait&&se.remainingExprs&&se.remainingExprs.length>0){let Ae=s.inAsyncStateMachine,De=s.stateMachineVariables,he=s.variableIdRemapping,Xe=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let ie=J.asyncWhileLoopInfo?.get(x.index);s.pendingDeferredDrops=[...se.deferredDropExpressions??[],...ie?.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let ee=new Map;for(let ae of i.capturedVariables)ee.set(ae.id,ae);if(a)for(let ae of a.fields)ee.set(ae.label,{id:ae.label,name:ae.label,type:ae.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ee;let _e=y.awaitPoint?.isInsideCond??!1,le=!1,be=[];for(let ae of se.remainingExprs){if(le){be.push(ae);continue}if(_e&&pn(ae)){le=!0,Tl(ae,y.awaitPoint,i," ",s);continue}let ye=O(ae," ",s);!ye||!ae.$||st(ae.$.env.modulePath,ye)||l.emitLine(` ${ye};`)}if(le&&y.awaitPoint){let ae=y.awaitPoint.index;J.asyncCondBranchInfo||(J.asyncCondBranchInfo=new Map);let ye=J.asyncCondBranchInfo.get(ae);ye?(ye.chainedBranches||(ye.chainedBranches=[]),ye.chainedBranches.push({branches:[{index:se.index,value:se.value,hasAwait:be.length>0||be.some(we=>pn(we)),remainingExprs:be,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})):J.asyncCondBranchInfo.set(ae,{branches:[{index:se.index,value:se.value,hasAwait:be.length>0||be.some(we=>pn(we)),remainingExprs:be,deferredDropExpressions:se.deferredDropExpressions}],condBranchFieldIndex:Z.condBranchFieldIndex})}else if(se.deferredDropExpressions)for(let ae of se.deferredDropExpressions){let ye=O(ae," ",s);ye&&ye.includes("sm->")&&l.emitLine(` ${ye};`)}s.inAsyncStateMachine=Ae,s.stateMachineVariables=De,s.variableIdRemapping=he,s.pendingDeferredDrops=Xe}}if(G.targetVariableId){let Z=an(G.targetVariableId,"local",s.stateMachineFieldAliases);l.emitLine(" // Assign cond result to target variable"),l.emitLine(` sm->${Z} = sm->await_result_${x.index};`)}l.emitLine("")}x.isInsideCond&&l.emitLine(" }");let H=J.asyncWhileLoopInfo?.get(x.index);if(H){if(l.emitLine(" // Execute remaining code from while loop body and continue loop"),l.emitLine(` if (sm->while_loop_${x.index}_active) {`),H.bodyExprsAfterAwait&&H.bodyExprsAfterAwait.length>0){let he=s.inAsyncStateMachine,Xe=s.stateMachineVariables,ie=s.variableIdRemapping,ee=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...H.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let _e=new Map;for(let ye of i.capturedVariables)_e.set(ye.id,ye);if(a)for(let ye of a.fields)_e.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=_e;let le=s.smWhileBreakInfo,be=s.smWhileContinueInfo,ae=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${x.index}`,activeIndex:x.index},s.smWhileContinueInfo={label:`while_loop_${x.index}_continue`},s.smWhileBodyDrops=[...H.bodyExpr.$?.deferredDropExpressions??[]];for(let ye of H.bodyExprsAfterAwait){let we=O(ye," ",s);!we||!ye.$||st(ye.$.env.modulePath,we)||l.emitLine(` ${we};`)}s.smWhileBreakInfo=le,s.smWhileContinueInfo=be,s.smWhileBodyDrops=ae,s.inAsyncStateMachine=he,s.stateMachineVariables=Xe,s.variableIdRemapping=ie,s.pendingDeferredDrops=ee}l.emitLine(` while_loop_${x.index}_continue:`);{let he=H.bodyExpr.$?.deferredDropExpressions??[];if(he.length>0){let Xe=s.inAsyncStateMachine,ie=s.stateMachineVariables,ee=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let _e=new Map;for(let le of i.capturedVariables)_e.set(le.id,le);if(a)for(let le of a.fields)_e.set(le.label,{id:le.label,name:le.label,type:le.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=_e;for(let le of he){let be=O(le," ",s);be&&be.includes("sm->")&&l.emitLine(` ${be};`)}s.inAsyncStateMachine=Xe,s.stateMachineVariables=ie,s.variableIdRemapping=ee}}l.emitLine(` ASYNC_DEBUG("${t}: Re-evaluating while loop condition\\n");`);let oe=s.declaredTempVars;if(s.declaredTempVars=void 0,H.stepExpr){let he=s.inAsyncStateMachine,Xe=s.stateMachineVariables,ie=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let ee=new Map;for(let le of i.capturedVariables)ee.set(le.id,le);if(a)for(let le of a.fields)ee.set(le.label,{id:le.label,name:le.label,type:le.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ee;let _e=O(H.stepExpr," ",s);_e&&l.emitLine(` ${_e};`),s.inAsyncStateMachine=he,s.stateMachineVariables=Xe,s.variableIdRemapping=ie}let ge=s.inAsyncStateMachine,q=s.stateMachineVariables,Z=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let se=new Map;for(let he of i.capturedVariables)se.set(he.id,he);if(a)for(let he of a.fields)se.set(he.label,{id:he.label,name:he.label,type:he.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=se;let Ae=O(H.conditionExpr," ",s);s.inAsyncStateMachine=ge,s.stateMachineVariables=q,s.variableIdRemapping=Z,s.declaredTempVars=oe,l.emitLine(` if (!(${Ae})) {`),l.emitLine(` sm->while_loop_${x.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 De=x.index;if(l.emitLine(" // Loop back by transitioning to while loop state"),l.emitLine(` sm->state = ${De};`),l.emitLine(` goto while_loop_${De}_start;`),l.emitLine(" }"),l.emitLine(" }"),l.emitLine(""),l.emitLine(` after_while_loop_${x.index}:`),H.condBranchPostWhileExprs){let he=H.condBranchPostWhileExprs,Xe=he.condBranchFieldIndex,ie=he.branchIndex;he.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} == ${ie}) {`));let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping,be=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let ae=new Map;for(let Ue of i.capturedVariables)ae.set(Ue.id,Ue);if(a)for(let Ue of a.fields)ae.set(Ue.label,{id:Ue.label,name:Ue.label,type:Ue.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ae;let ye=y.awaitPoint!=null,we=!1,je=[];for(let Ue=0;Ue<he.exprs.length;Ue++){let Je=he.exprs[Ue];if(we){je.push(Je);continue}if(ye&&pn(Je)){we=!0,Tl(Je,y.awaitPoint,i," ",s);continue}let Lt=O(Je," ",s);!Lt||!Je.$||st(Je.$.env.modulePath,Lt)||l.emitLine(` ${Lt};`)}if(we&&y.awaitPoint){let Ue=y.awaitPoint.index;J.asyncCondBranchInfo||(J.asyncCondBranchInfo=new Map);let Je=he.skipCondBranchCheck?-1:he.condBranchFieldIndex,Lt=J.asyncCondBranchInfo.get(Ue);Lt?(Lt.chainedBranches||(Lt.chainedBranches=[]),Lt.chainedBranches.push({branches:[{index:he.branchIndex,value:he.exprs[0],hasAwait:je.length>0||je.some(At=>pn(At)),remainingExprs:je,deferredDropExpressions:he.deferredDropExpressions}],condBranchFieldIndex:Je})):J.asyncCondBranchInfo.set(Ue,{branches:[{index:he.branchIndex,value:he.exprs[0],hasAwait:je.length>0||je.some(At=>pn(At)),remainingExprs:je,deferredDropExpressions:he.deferredDropExpressions}],condBranchFieldIndex:Je})}if(!we&&he.deferredDropExpressions)for(let Ue of he.deferredDropExpressions){let Je=O(Ue," ",s);Je&&Je.includes("sm->")&&l.emitLine(` ${Je};`)}l.emitLine(" }"),s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le,s.pendingDeferredDrops=be}if(H.outerWhileLoop){let he=H.outerWhileLoop,Xe=he.whileLoopIndex;if(l.emitLine(" // Execute remaining code from outer while loop body"),l.emitLine(` if (sm->while_loop_${Xe}_active) {`),he.bodyExprsAfterAwait.length>0){let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping,be=s.pendingDeferredDrops;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping,s.pendingDeferredDrops=[...he.bodyExpr.$?.deferredDropExpressions??[],...e.$?.deferredDropExpressions??[]];let ae=new Map;for(let Ue of i.capturedVariables)ae.set(Ue.id,Ue);if(a)for(let Ue of a.fields)ae.set(Ue.label,{id:Ue.label,name:Ue.label,type:Ue.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ae;let ye=s.smWhileBreakInfo,we=s.smWhileContinueInfo,je=s.smWhileBodyDrops;s.smWhileBreakInfo={label:`after_while_loop_${Xe}`,activeIndex:Xe},s.smWhileContinueInfo={label:`while_loop_${Xe}_continue`},s.smWhileBodyDrops=[...he.bodyExpr.$?.deferredDropExpressions??[]];for(let Ue of he.bodyExprsAfterAwait){let Je=O(Ue," ",s);!Je||!Ue.$||st(Ue.$.env.modulePath,Je)||l.emitLine(` ${Je};`)}s.smWhileBreakInfo=ye,s.smWhileContinueInfo=we,s.smWhileBodyDrops=je,s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le,s.pendingDeferredDrops=be}l.emitLine(` while_loop_${Xe}_continue:`);{let ee=he.bodyExpr.$?.deferredDropExpressions??[];if(ee.length>0){let _e=s.inAsyncStateMachine,le=s.stateMachineVariables,be=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let ae=new Map;for(let ye of i.capturedVariables)ae.set(ye.id,ye);if(a)for(let ye of a.fields)ae.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=ae;for(let ye of ee){let we=O(ye," ",s);we&&we.includes("sm->")&&l.emitLine(` ${we};`)}s.inAsyncStateMachine=_e,s.stateMachineVariables=le,s.variableIdRemapping=be}}let ie=s.declaredTempVars;if(s.declaredTempVars=void 0,he.stepExpr){let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let be=new Map;for(let ye of i.capturedVariables)be.set(ye.id,ye);if(a)for(let ye of a.fields)be.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=be;let ae=O(he.stepExpr," ",s);ae&&l.emitLine(` ${ae};`),s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le}{let ee=s.inAsyncStateMachine,_e=s.stateMachineVariables,le=s.variableIdRemapping;s.inAsyncStateMachine={futureType:o},s.variableIdRemapping=i.variableIdRemapping;let be=new Map;for(let ye of i.capturedVariables)be.set(ye.id,ye);if(a)for(let ye of a.fields)be.set(ye.label,{id:ye.label,name:ye.label,type:ye.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=be;let ae=O(he.conditionExpr," ",s);s.inAsyncStateMachine=ee,s.stateMachineVariables=_e,s.variableIdRemapping=le,l.emitLine(` if (!(${ae})) {`),l.emitLine(` sm->while_loop_${Xe}_active = false;`),l.emitLine(" } else {"),l.emitLine(` sm->state = ${x.index};`),l.emitLine(` goto while_loop_${Xe}_start;`),l.emitLine(" }")}s.declaredTempVars=ie,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 x of i.capturedVariables)b.set(x.id,x);if(a)for(let x of a.fields)b.set(x.label,{id:x.label,name:x.label,type:x.type,kind:"outer",isOwningTheSameRcValueAs:void 0});s.stateMachineVariables=b;let V=s.pendingDeferredDrops;s.pendingDeferredDrops=[...e.$?.deferredDropExpressions??[]];let I=T&&!c&&y.expressions.length>0,U=y.expressions.length>0?y.expressions[y.expressions.length-1]:void 0,D=s.asyncBodyReturnExpr;if(!c&&U&&d&&U===d&&y.awaitPoint?s.asyncBodyReturnExpr=U:s.asyncBodyReturnExpr=void 0,P_(y," ",s,I),s.asyncBodyReturnExpr=D,s.pendingDeferredDrops=V,l.emitLine(""),y.awaitPoint){s.inAsyncStateMachine=$,s.stateMachineVariables=C,s.variableIdRemapping=L;let x=v+1;{let R=El(y.awaitPoint,i),J=y.awaitPoint.expr.args?.[0],G=na(J?.$?.type),H=y.awaitPoint?.isInsideCond;H&&(l.emitLine(" // Only await if the cond branch with await was taken"),l.emitLine(` if (sm->${R} != NULL) {`));let oe=y.awaitPoint?.isInsideWhile,ge=oe?s.asyncWhileLoopInfo?.get(y.awaitPoint.index):void 0;if(oe&&ge){let q=y.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 = ${x};`),l.emitLine(""),l.emitLine(" // Check if future is ready"),l.emitLine(` int future_state = sm->${R}->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(""),G?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->${R}); // event loop reference`)),G||(l.emitLine(" if (future_state == 0) { // 0 = cold (not started)"),_g(y.awaitPoint.expr,`sm->${R}`," ",s),l.emitLine(" // Cold future \u2014 start it via stored resume function pointer"),l.emitLine(` sm->${R}->__yo_resume_fn((void*)sm->${R});`),l.emitLine(""),l.emitLine(" // Re-check: may have completed synchronously"),l.emitLine(` future_state = sm->${R}->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->${R}->continuation_fn = (void (*)(void*))${r};`),l.emitLine(` sm->${R}->continuation_sm = (void*)sm;`),l.emitLine(" return;"),oe&&ge){let q=y.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(" }")}H&&(l.emitLine(" } else {"),l.emitLine(" // Non-await cond branch was taken, skip directly to next state"),l.emitLine(` sm->state = ${x};`),l.emitLine(` goto state_${x};`),l.emitLine(" }"))}}else if(T){if(!y.expressions.some(R=>G_(R))){if(e.$?.deferredDropExpressions){let R=new Ai,Q=s.emitter;s.emitter=R;for(let G of e.$.deferredDropExpressions){let H=O(G,"",s);H&&R.emitLine(`${H};`)}s.emitter=Q;let J=R.print().trim();if(J){l.emitLine(" // Drop local variables before completion");for(let G of J.split(`
195
+ `)){let H=G.trim();H&&(l.emitLine(` ${H}`),h.push(H))}l.emitLine("")}}l.emitLine(" // Final state - complete the Future"),Mr({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(""),h}function Tl(e,t,n,r,i){let o=i.emitter,a=El(t,n);if(e.tag==="FnCall"&&E(e,":=")){let s=e.args[1];if(s&&s.tag==="FnCall"&&gn(s)){let l=s.args[0];if(l){let u=O(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"&&gn(e)){let s=e.args[0];if(s){let l=O(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,S.cond)){so(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,S.match)){so(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,S.while)){so(e,t,0,r,i);return}if(e.tag==="FnCall"&&E(e,S.begin)){so(e,t,0,r,i);return}o.emitLine(`${r}// Warning: unhandled await pattern in remaining expressions`)}function G_(e){if(vt(e,"return")||E(e,"return"))return!0;if(e.tag==="FnCall"){for(let t of e.args)if(G_(t))return!0}return!1}function ug(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;M(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),at(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function _g(e,t,n,r){let i=e.args?.[0];if(!i?.$?.type)return;let o=Rt(i.$.type);if(!o?.isFuture.effects?.length)return;let a=ug(o.isFuture.effects),s=r.emitter,l=e.args?.find(u=>F(u)&&E(u,S.using));if(l){let u=l.args;for(let _=0;_<a.length&&_<u.length;_++){let c=a[_],p=u[_];if(W(c.type)){if(c.type.forallParameters.length>0)continue;let f=O(p,n,r),d=c.label;s.emitLine(`${n}${t}->__capture.${d} = (void*)${f};`)}else $e(c.type)&&U_(c.type,t,n,p.$?.value,r,e)}}else for(let u of a)if(W(u.type)){if(u.type.forallParameters.length>0)continue;let _=cg(u.label,r,e);_&&s.emitLine(`${n}${t}->__capture.${u.label} = (void*)${_};`)}else $e(u.type)&&U_(u.type,t,n,void 0,r,e)}function U_(e,t,n,r,i,o){let a=i.emitter;for(let s of e.fields){if(!W(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),_=r.fields[u];if(_&&ne(_)){let c=i.functions[_.funcId];c&&(l=c.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 _=hn(u,c=>c.isImplicit===!0);for(let c=_.length-1;c>=0;c--){let p=_[c],f=p.value?.[p.value.length-1];if(f&&We(f)){let d=f.type.fields.findIndex(h=>h.label===s.label);if(d>=0){let h=f.fields[d];if(h&&ne(h)){let g=i.functions[h.funcId]?.cName;if(g){l=g;break}}}}}}}l&&a.emitLine(`${n}${t}->__capture.${s.label} = (void*)${l};`)}}function cg(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 pg=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 W_(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(pg.has(r))continue;$l(i,r,!0,e);continue}i.isExtern==="c"&&i.cInclude||r.startsWith("__atomic_")||r.startsWith("__sync_")||$l(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"),dg(e),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Closure constructors"),t.emitDeclarationLine(""),t.emitDeclarationLine("/// Capture dispose functions"),mg(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&&Ct(i.specializedType??i.type).length===0&&[...i.type.implicitParameters,...i.type.parameters.filter(h=>h.isImplicit)].some(h=>W(h.type)))continue;let u=i.specializedType??i.type,_=Ct(u).length>0;if(!o&&i.isIoAsyncStateMachineClosure||!o&&!s&&!_&&!i.isModuleEffectMember&&(fr(i.type)&&!i.type.isClosure||i.specializedFunctionCaches?.length>0&&!i.type.isClosure||Xr(i)||Cr(i)||i.isIoAsyncStateMachineClosure))continue;let c=i.specializedType??i.type,p=!s&&!i.isModuleEffectMember&&(c.parameters.some(h=>de(h.type))||c.forallParameters.length>0),f=de(c.return.type),d=M(c.return.type)&&c.return.type.requiredTraits.length>0;p||f&&!d&&!i.isModuleEffectMember||$l(c,r,!1,e,i.isModuleEffectMember?void 0:i.body,i.specializedType&&Ct(c).length===0&&Ct(i.type).some(h=>h.fieldFunctionType.forallParameters&&h.fieldFunctionType.forallParameters.length>0)?i.type:void 0)}t.emitDeclarationLine("/// Closure vtable instances"),t.emitDeclarationLine("")}function Ct(e){let t=[],n=fg(e.implicitParameters);for(let r of n)$e(r.type)?q_(r.label,r.type,[],t):W(r.type)&&t.push({implicitLabel:r.label,fieldLabel:r.label,fieldPath:[r.label],fieldFunctionType:r.type,cParamName:re(r.label)});return t}function q_(e,t,n,r){for(let i of t.fields)if(W(i.type)){let o=[...n,i.label],a=o.join("__");r.push({implicitLabel:e,fieldLabel:a,fieldPath:o,fieldFunctionType:i.type,cParamName:re(`${e}__${a}`)})}else $e(i.type)&&q_(e,i.type,[...n,i.label],r)}function fg(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;M(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),at(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function kr(e,t,n,r,i){let o=r||z(e.return.type,n),a=e.parameters.filter(c=>!c.isCompileTimeOnly),s=[];e.isClosure&&s.push("void* closure_context");let l=a.map((c,p)=>{let f=re(c.label||`param${p}`);if(W(c.type))return kr(c.type,"(*)",n).replace(" (*)(",` (*${f})(`);{let d;return M(c.type)&&Fe(c.type)?c.type.resolvedConcreteType?d=z(c.type.resolvedConcreteType,n)+"*":d=z(c.type,n):d=z(c.type,n),`${d} ${f}`}});s.push(...l);let u=Ct(i??e);for(let c of u)if(c.fieldFunctionType.forallParameters&&c.fieldFunctionType.forallParameters.length>0)s.push(`void* ${c.cParamName}`);else{let p=kr(c.fieldFunctionType,"(*)",n).replace(" (*)(",` (*${c.cParamName})(`);s.push(p)}let _=s.join(", ");return`${o} ${t}(${_})`}function $l(e,t,n,r,i,o){let a;if(i&&Fe(e.return.type)){let p=Jo(i);p?.$?.asyncStateMachineStructName?a=`${p.$.asyncStateMachineStructName}*`:i.$?.type&&M(i.$.type)&&Fe(i.$.type)&&(a=z(i.$.type,r))}if(i&&M(e.return.type)&&!Fe(e.return.type)&&i.$?.type&&(a=z(i.$.type,r)),!a&&i&&i.$?.type&&!Fe(e.return.type)){let p=z(e.return.type,r),f=z(i.$.type,r);p!==f&&(a=f)}let s=a?kr(e,t,r,a,o):kr(e,t,r,void 0,o),l=A(e),u=t==="__yo_user_main"||r.exportedFunctionLabels&&[...r.exportedFunctionLabels.values()].some(p=>re(p)===t),_=!n&&!u&&(t.includes("___drop")||t.includes("___dup")||t.includes("___dispose")),c=n?"extern ":u?"":_?"static inline __attribute__((always_inline)) ":"static inline ";r.emitter.emitDeclarationLine(`${c}${s}; // ${l}`)}function dg(e){let t=e.emitter;t.emitDeclarationLine("static inline void __yo_decr_rc(void* ptr); // Decrement reference count"),t.emitDeclarationLine("static inline 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(pe(r)&&r.isReferenceSemantics){if(r.fields.some(l=>de(l.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(l=>{let u=z(l.type,e),_=re(l.label);return`${u} ${_}`}).join(", ");t.emitDeclarationLine(`static ${i}* ${a}(${s}); // Constructor`)}}}function mg(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 Y_(e){let t=new Set;for(let n in e.functions){let{value:r,cName:i}=e.functions[n],o=r.specializedType;if(Xr(r)||!o||!Wn(r.type)||Wn(o))continue;let a=o.parameters.some(c=>de(c.type)),s=de(o.return.type);if(a||s||Ct(r.type).some(c=>c.fieldFunctionType.forallParameters&&c.fieldFunctionType.forallParameters.length>0)||t.has(n))continue;t.add(n);let _=i.includes("___drop")||i.includes("___dup")||i.includes("___dispose")?"static inline __attribute__((always_inline)) ":"static inline ";e.emitter.emitDeclarationLine(`${_}${kr(o,i,e)}; // specialized function: ${A(r.type)}`)}}function wr(e,t,n){let r=j(t,e);return r.length===0?!1:r[r.length-1].frameLevel<=n}function H_(e){return!!(e.$?.closureFunctionValue&&e.$?.type&&Ht(e.$.type))}function yg(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 d=qa(f);d&&l.set(d,f)}let u=e.fields.map(f=>{if(f.isEffectParam)return"NULL";let d,h=f.exprs.expr;if(h.$?.deferredDupExpressions?.length&&(d=h.$.deferredDupExpressions[0]),!d){let y=[f.label];B(h)&&y.push(h.token.value);for(let v of y){let T=l.get(v);if(T){d=T;break}}}if(d)return O(d,r,i);let g={tag:"Atom",token:h.token,$:h.$};return O(g,r,i)}),_=`(${s}){ ${u.map((f,d)=>{let h=e.fields[d];return h?`.${h.label} = ${f}`:`/* Error: missing field at index ${d} */`}).join(", ")} }`,c=n.token.position.row!==void 0?`${Date.now()}_${n.token.position.row}`:`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=`__capture_${t}_${c}`;return o?i.emitter.emitLine(`${r}${s} ${p} = ${_};`):(i.emitter.emitLine(`${r}${s}* ${p} = (${s}*)__yo_malloc(sizeof(${s}));`),i.emitter.emitLine(`${r}*${p} = ${_};`)),{captureTempVar:p,captureCName:s}}function j_(e,t,n){if(!e.$||!e.$.type||!e.$.closureFunctionValue)return"// Error: Missing closure metadata";let r=on(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=Ie(e.$.type),u;if(l){let d=n.types[e.$.type.id];if(!d)return"// Error: Dyn closure type not found in context";u=d.cName}let _=a&&pe(a)&&a.fields.length>0,c=z(i.return.type,n),p=i.parameters.map(d=>z(d.type,n)).join(", "),f=`(${c} (*)(void*${p?", "+p:""}))${s}`;if(_&&a&&pe(a)){let d=!l,h=yg(a,i.id,e,t,n,d);if(!h)return"// Error: Failed to allocate closure capture";let{captureTempVar:g}=h;if(l){let y=`__yo_create_${u}`,v=`__yo_dispose_${u}`;return`${y}(${g}, ${v}, ${f})`}else return n.implClosureCallMap.set(a.id,{functionCName:s,callTypeId:r.isFn.callType.id,callType:r.isFn.callType}),g}else if(l){let d=`__yo_create_${u}`,h=`__yo_dispose_${u}`;return`${d}(NULL, ${h}, ${f})`}else{if(e.$.type.tag==="SomeType"){let d=e.$.type;if(d.resolvedConcreteType)return n.implClosureCallMap.set(d.resolvedConcreteType.id,{functionCName:s,callTypeId:r.isFn.callType.id,callType:r.isFn.callType}),`(${z(d.resolvedConcreteType,n)}){}`}return"// Error: Impl(Fn(...)) without captures missing resolvedConcreteType"}}function Cl(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=O(a,t,n);s&&n.emitter.emitLine(`${t}${s};`)}}}function lo(e,t,n=""){let r=t;if(e.token.value==="continue"){if(r.currentContinueLabel)return Cl(r,n,t),`goto ${r.currentContinueLabel}`;if(r.currentLoopLabel)return Cl(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=O(s,n,t);l&&l.includes("sm->")&&a.emitLine(`${n}${l};`)}}if(r.smWhileContinueInfo.stepExpr){let a=t.emitter,s=O(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 Cl(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 _=O(u,n,t);_&&_.includes("sm->")&&l.emitLine(`${n}${_};`)}}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=Rt(s).isFuture.outputType,_=fe(u);if(e.$?.deferredDropExpressions)for(let p of e.$.deferredDropExpressions){let f=O(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=O(p,n,t);f&&f.includes("sm->")&&a.emitLine(`${n}${f};`)}}a.emitLine(`${n}// Early return - complete the result Future`);let c=_?void 0:`(${z(u,t)}){0}`;return Mr({emitter:a,indent:n,resultCode:c,debugLabel:t.currentFunctionName}),""}return"return"}if(e.$?.type&&fe(e.$.type))return"";if((r.inAsyncStateMachine||r.inEffectStateMachine)&&r.stateMachineVariables){let a=e.token.value;if(r.localShadowedVariables?.has(a))return re(a);let s=!1;if(e.$?.env){let l=j(e.$.env,a);if(l.length>0){let u=l[l.length-1],_=u.isOwningTheSameRcValueAs?u.isOwningTheSameRcValueAs.id:u.id;r.variableIdRemapping?.has(_)&&(_=r.variableIdRemapping.get(_));let c=r.stateMachineVariables.get(_);if(c){let p=r.stateMachineFieldAliases?.get(_);if(p)return s=!0,`sm->${p}`;let f=c.kind==="outer"?`__capture.${a}`:`var_${c.id}`;return s=!0,`sm->${f}`}}}if(!s){for(let[l,u]of r.stateMachineVariables)if(u.name===a){let _=r.stateMachineFieldAliases?.get(l);if(_)return s=!0,`sm->${_}`;let c=u.kind==="outer"?`__capture.${a}`:`var_${l}`;return s=!0,`sm->${c}`}}if(e.$?.env){let l=j(e.$.env,a);if(l.length>0){let u=l[l.length-1];if(u.isOwningTheSameRcValueAs){let _=u.isOwningTheSameRcValueAs.name,c=u.isOwningTheSameRcValueAs.id;for(let[p,f]of r.stateMachineVariables)if(f.name===_||p===c)return`sm->${f.kind==="outer"?`__capture.${_}`:`var_${p}`}`}}}if(r.currentClosureCaptures&&r.currentClosureCaptures.includes(a)&&r.currentClosureCaptureFrameLevel!==void 0){let l=r.currentClosureCaptureTypeCName;return l?`((${l}*)closure_context)->${ve(a,e.$?.env)}`:`closure_context->${ve(a,e.$?.env)}`}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!ce(e.$.value)){let l=j(e.$.env,e.$.variableName);if(l.length>0&&l[l.length-1].isCompileTimeOnly)return en(e.$.value,t,e)}return ve(e.$.variableName,e.$.env)}}if(e.$?.variableName){if(e.$?.env&&e.$?.value&&!ce(e.$.value)){let a=j(e.$.env,e.$.variableName);if(a.length>0&&a[a.length-1].isCompileTimeOnly)return en(e.$.value,t,e)}if(!(r.currentClosureCaptures&&r.currentClosureCaptures.includes(e.token.value)&&e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0&&wr(e.token.value,e.$.env,r.currentClosureCaptureFrameLevel)))return ve(e.$.variableName,e.$?.env)}if(e.$?.value&&!ce(e.$.value))return en(e.$.value,t,e);let i=e.$?.env&&r.currentClosureCaptureFrameLevel!==void 0?wr(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)->${ve(e.token.value,e.$?.env)}`:`closure_context->${ve(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=>W(l.type)&&l.type.isClosure&&l.type===a.value.type);if(s)return`((${`${s.cName}_capture`}*)closure_context->data)->${ve(e.token.value,e.$?.env)}`}}if(e.$?.env){let a=j(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(W(s.type)&&(ce(s.value?.[0])||s.value===void 0)){let l=Object.entries(t.functions).find(([u,_])=>_.value.funcName===e.token.value);if(l)return l[1].cName}}}return ve(e.token.value,e.$?.env)}function K_(e,t,n){let r;if(Bt(e)){let y=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;y&&ne(y)&&(r=y.body)}else r=e.args[0];if(!r)return"/* Error: async requires exactly 1 argument */";let i=e.$?.type;if(!i||!Fe(i))return"/* Error: async block must have Future type */";let o=Rt(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}`,_=`${a}_state_dispose`;n.types[i.id]={type:i,cName:s};let c=e.$?.awaitAnalysis;if(!c)throw new Error("Missing await analysis for async block. This should have been computed during evaluation.");let p=o.isFuture.outputType;if(M(p))if(p.resolvedConcreteType)p=p.resolvedConcreteType;else{let y=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(y&&ne(y)){let v=y.type?.return?.type;if(v&&M(v)&&v.resolvedConcreteType)p=v.resolvedConcreteType;else if(y.body?.$?.type){let T=y.body.$.type;M(T)&&T.resolvedConcreteType?p=T.resolvedConcreteType:M(T)||(p=T)}}}let f=z(p,n),d=n.emitter;if(d.emitDeclarationLine(`void ${_}(void* sm_ptr); // Dispose function for state machine`),d.emitDeclarationLine(""),d.emitDeclarationLine(`void ${l}(${s}* sm);`),d.emitDeclarationLine(""),e.$?.captureType){let g=e.$.captureType,y=Object.values(n.types).find(T=>T.type===g),v=y?y.cName:`async_capture_${g.id}`;d.emitDeclarationLine(`${s}* ${u}(${v} __capture);`)}else d.emitDeclarationLine(`${s}* ${u}();`);d.emitDeclarationLine(""),n.deferredAsyncBlocks||(n.deferredAsyncBlocks=[]),n.deferredAsyncBlocks.push({bodyExpr:r,asyncBlockId:a,structName:s,resumeFunctionName:l,constructorName:u,disposeFunctionName:_,futureType:i,futureModuleType:o,resultType:p,resultTypeCName:f,captureType:e.$?.captureType,analysis:c});let h=e.$?.captureType;if(h){let g=Object.values(n.types).find(I=>I.type===h),y=g?g.cName:`async_capture_${h.id}`,v=n,T=v.currentClosureCaptures!==void 0||v.inAsyncStateMachine!==void 0||v.inEffectStateMachine!==void 0,$=!1,C=h.fields.map(I=>{if(I.isEffectParam)return`.${I.label} = NULL`;let U;if(!T&&e.$?.deferredDupExpressions)for(let x of e.$.deferredDupExpressions){let R;if(F(x)&&(x.args.length>0&&B(x.args[0])?R=x.args[0].token.value:x.args.length===0&&F(x.func)&&E(x.func,".")&&x.func.args.length>=2&&B(x.func.args[0])&&(R=x.func.args[0].token.value)),R===I.label){U=x;break}}if(U)return $=!0,U.$?.variableName?(O(U,t,n),`.${I.label} = ${U.$.variableName}`):`.${I.label} = ${O(U,t,n)}`;let D={tag:"Atom",token:I.exprs.expr.token,$:I.exprs.expr.$};return`.${I.label} = ${lo(D,n)}`}).join(", "),L=`(${y}){${C}}`;if(!$){let I=Dn(h,n);I&&(L=`${I}(${L})`)}let b=e.$?.variableName||"async_result",V=`${u}(${L})`;if(b&&e.$?.type){let I=ut(e.$.type,b,n);return n.emitter.emitLine(`${t}${I} = ${V};`),b}else return V}else{let g=e.$?.variableName||"async_result",y=`${u}()`;if(g&&e.$?.type){let v=ut(e.$.type,g,n);return n.emitter.emitLine(`${t}${v} = ${y};`),g}else return y}}function X_(e,t){let n=t.emitter,{asyncBlockId:r,structName:i,resultType:o,resultTypeCName:a,captureType:s,analysis:l,crossBoundaryIds:u,awaitFutureTempVarAliases:_,overlappingSlotAliases:c,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)"),fe(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 g=Object.values(t.types).find(v=>v.type===s),y=g?g.cName:`async_capture_${s.id}`;n.emitDeclarationLine(" // Captured variables from outer scope"),n.emitDeclarationLine(` ${y} __capture;`),n.emitDeclarationLine("")}let f=l.capturedVariables.filter(g=>g.kind!=="outer");if(u&&(f=f.filter(g=>u.has(g.id)&&!_?.has(g.id)&&!c?.has(g.id))),f.length>0){n.emitDeclarationLine(" // Local variables");for(let g of f){let y=z(g.type,t),v=an(g.id,"local");n.emitDeclarationLine(` ${y} ${v}; // ${g.name}`)}n.emitDeclarationLine("")}if(p&&p.length>0){n.emitDeclarationLine(" // Overlapping storage slots (Phase 2)");for(let g of p)n.emitDeclarationLine(` ${g.cType} ${g.fieldName}; // shared: ${g.variableNames.join(", ")}`);n.emitDeclarationLine("")}if(l.awaitPoints.length>0){let g=[];for(let y of l.awaitPoints)if(!(fe(y.resultType)||M(y.resultType)&&!y.resultType.resolvedConcreteType)&&y.isInsideCond){let $=y.resultType;if(y.futureType){let L=Rt(y.futureType);L&&($=L.isFuture.outputType)}let C=z($,t);g.push(` ${C} await_result_${y.index};`)}if(g.length>0){n.emitDeclarationLine(" // Await result temporaries");for(let y of g)n.emitDeclarationLine(y);n.emitDeclarationLine("")}}if(l.awaitPoints.length>0){let g=l.awaitPoints.filter(y=>y.futureVariableId===void 0);if(g.length>0){n.emitDeclarationLine(" // Future references for awaits");for(let y of g){let v=y.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=z($,t);n.emitDeclarationLine(` ${C} await_future_${y.index};`)}n.emitDeclarationLine("")}}let d=l.awaitPoints.filter(g=>g.needsOwnCondBranchField);if(d.length>0){n.emitDeclarationLine(" // Branch tracking for cond expressions with await");for(let g of d)n.emitDeclarationLine(` int cond_branch_${g.index}; // Which branch was taken in cond with await ${g.index}`);n.emitDeclarationLine("")}let h=l.awaitPoints.filter(g=>g.isInsideWhile);if(h.length>0){n.emitDeclarationLine(" // Loop state tracking for while loops with await");let g=l.awaitPoints.length;for(let y of h){n.emitDeclarationLine(` _Bool while_loop_${y.index}_active; // Whether while loop ${y.index} should continue`);let v=(y.whileNestingDepth??1)-1;for(let T=0;T<v;T++)n.emitDeclarationLine(` _Bool while_loop_${g}_active; // Whether outer while loop ${g} should continue`),g++}n.emitDeclarationLine("")}n.emitDeclarationLine("};"),n.emitDeclarationLine("")}function gg(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=_=>{let c=r.get(_);c.has(l.structName)||(c.add(l.structName),i.set(l.structName,(i.get(l.structName)??0)+1))};for(let _ of l.analysis.capturedVariables){let c;try{c=z(_.type,e)}catch{continue}let p=n.get(c);p&&p.structName!==l.structName&&u(p.structName)}for(let _ of l.analysis.awaitPoints){if(_.futureVariableId!==void 0)continue;let c=_.expr;if(c.tag!=="FnCall")continue;let f=c.args[0]?.$?.type;if(!f)continue;let d;try{d=z(f,e)}catch{continue}let h=n.get(d);h&&h.structName!==l.structName&&u(h.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 _ of u){let c=(i.get(_)??0)-1;i.set(_,c),c===0&&o.push(_)}}let s=a.length===t.length?a.map(l=>n.get(l)).filter(Boolean):t;for(let l of s){let{crossBoundaryIds:u,awaitFutureTempVarAliases:_,variableSegments:c}=Ya(l.bodyExpr,l.analysis),{slotAliases:p,slots:f}=Ha(u,c,l.analysis.capturedVariables,_,e);X_({asyncBlockId:l.asyncBlockId,structName:l.structName,resultType:l.resultType,resultTypeCName:l.resultTypeCName,captureType:l.captureType,analysis:l.analysis,crossBoundaryIds:u,awaitFutureTempVarAliases:_,overlappingSlotAliases:p,overlappingSlots:f},e)}}function hg(e,t,n,r,i,o,a,s,l,u){let _=u.emitter;if(_.emitLine(`// Dispose function for async block ${e} state machine`),_.emitLine("// Called by __yo_decr_rc when refcount hits 0 - do NOT call __yo_free here"),_.emitLine(`void ${n}(void* sm_ptr) {`),_.emitLine(` ${t}* sm = (${t}*)sm_ptr;`),_.emitLine(` ASYNC_DEBUG("${n}: Disposing state machine\\n");`),_.emitLine(""),i&&Ne(i)){let c=Object.values(u.types).find(p=>p.type===i);if(!c)_.emitLine(" /* Error: capture struct type not found in context */");else{let p=c.cName,f=i.trait.fields.find(d=>d.label===k.___drop[0]);if(f&&f.assignedValue&&ne(f.assignedValue)){let d=u.functions[f.assignedValue.funcId]?.cName;d&&(_.emitLine(' ASYNC_DEBUG(" Dropping capture struct\\n");'),_.emitLine(` ${d}(sm->__capture);`))}else _.emitLine(` /* Warning: ___drop function not found for capture struct ${p} */`)}}if(_.emitLine(""),!fe(r)&&Ne(r)){let c=z(r,u);_.emitLine(" // Drop result field if it was set (state == -1 means completed)"),_.emitLine(" int final_state = sm->state;"),_.emitLine(" if (final_state == -1) {"),_.emitLine(' ASYNC_DEBUG(" Dropping result field\\n");');let p=br(r,u);p?_.emitLine(` ${p}(sm->result);`):_.emitLine(` /* Warning: No ___drop function found for result type ${c} */`),_.emitLine(" }")}_.emitLine("");{let c=[];for(let p of o.capturedVariables){if(p.kind!=="local"||!s.has(p.id)||l.has(p.id)||p.isOwningTheSameRcValueAs!==void 0)continue;let d=`sm->${an(p.id,"local")}`;if(Ie(p.type))c.push(` if ((${d}).data != NULL) { __yo_decr_rc((void*)(${d}).data); }`);else if(Ft(p.type)||bt(p.type))c.push(` if (${d} != NULL) { __yo_decr_rc_atomic((void*)${d}); }`);else if(ft(p.type)||M(p.type)&&un(p.type)){let h=br(p.type,u);h?c.push(` if (${d} != NULL) { ${h}(${d}); }`):c.push(` if (${d} != NULL) { __yo_decr_rc((void*)${d}); }`)}else if(Ne(p.type)){let h=br(p.type,u);h&&c.push(` ${h}(${d});`)}}if(c.length>0){_.emitLine(" // Drop local variables on escape (state == -2)"),_.emitLine(" if (sm->state == -2) {");for(let p of c)_.emitLine(p);_.emitLine(" }")}}_.emitLine(" // Memory freed by __yo_decr_rc after this function returns"),_.emitLine("}")}function vg(e,t,n,r,i,o,a,s,l,u){let _=u.emitter;if(l){let c=Object.values(u.types).find(f=>f.type===l),p=c?c.cName:`async_capture_${l.id}`;_.emitLine(`${t}* ${r}(${p} __capture) {`)}else _.emitLine(`${t}* ${r}() {`);if(_.emitLine(" // Allocate async block state machine (heap-backed, ref-counted)"),_.emitLine(` ${t}* sm = (${t}*)__yo_malloc(sizeof(${t}));`),_.emitLine(` memset(sm, 0, sizeof(${t}));`),_.emitLine(""),_.emitLine(" // Initialize reference counting header"),_.emitLine(" sm->header.ref_count = 1; // Caller owns initial reference"),_.emitLine(` GC_DEBUG("AsyncBlock ${t}: Created ptr=%p RC=1\\n", (void*)sm);`),u.needsCycleGC&&(_.emitLine(" sm->header.gc_flags = 0;"),_.emitLine(" sm->header.gc_mark = __YO_GC_UNMARKED;"),_.emitLine(" sm->header.gc_next = NULL;"),_.emitLine(" sm->header.gc_prev = NULL;")),u.needsCycleGC)_.emitLine(` sm->header.dispose_fn = (void(*)(void*))${i};`);else{u.disposeTypeIds||(u.disposeTypeIds=new Map,u.nextDisposeTypeId=1);let c=u.disposeTypeIds.get(i);c===void 0&&(c=u.nextDisposeTypeId,u.nextDisposeTypeId=c+1,u.disposeTypeIds.set(i,c)),_.emitLine(` sm->header.type_id = ${c};`)}u.needsCycleGC&&_.emitLine(" sm->header.traverse_fn = NULL; // TODO: Add traverse for cycle detection if needed"),_.emitLine(""),_.emitLine(" sm->state = 0;"),_.emitLine(" sm->continuation_fn = NULL;"),_.emitLine(" sm->continuation_sm = NULL;"),_.emitLine(""),l&&(_.emitLine(" // Initialize captured variables"),_.emitLine(" sm->__capture = __capture;"),_.emitLine("")),_.emitLine(" // Initialize result (will be set when async block completes)"),fe(a)?_.emitLine(" // Result is unit type, no initialization needed"):_.emitLine(` memset(&sm->result, 0, sizeof(${s}));`),_.emitLine(""),_.emitLine(` sm->__yo_resume_fn = (void(*)(void*))${n};`),_.emitLine(""),_.emitLine(" return sm;"),_.emitLine("}"),_.emitLine("")}function Q_(e){if(!e.deferredAsyncBlocks||e.deferredAsyncBlocks.length===0)return;let t=e.emitter;gg(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:_,futureType:c,resultType:p,resultTypeCName:f,captureType:d,analysis:h}=r,g=e.stateMachineVariables,y=e.currentEvidenceParams,v=new Map,{crossBoundaryIds:T,awaitFutureTempVarAliases:$,variableSegments:C}=Ya(o,h),{slotAliases:L}=Ha(T,C,h.capturedVariables,$,e),b=h.capturedVariables.filter(x=>x.kind==="outer"||T.has(x.id)||$.has(x.id)||L.has(x.id)),V={...h,capturedVariables:b};for(let x of b)v.set(x.id,x);if(d)for(let x of d.fields)v.set(x.label,{id:x.label,name:x.label,type:x.type,kind:"outer",isOwningTheSameRcValueAs:void 0});e.stateMachineVariables=v;let I=e.stateMachineFieldAliases,U=new Map($);for(let[x,R]of L)U.set(x,R);e.stateMachineFieldAliases=U;let D=B_(o,a,s,l,V,c,d,e);if(e.stateMachineVariables=g,e.currentEvidenceParams=y,e.stateMachineFieldAliases=I,t.emitLine(""),hg(a,s,_,p,d,V,D,T,$,e),t.emitLine(""),vg(a,s,l,u,_,c,p,f,d,e),t.emitLine(""),e.deferredAsyncBlocks.length>i){let x=e.deferredAsyncBlocks.slice(i);for(let R of x){let{crossBoundaryIds:Q,awaitFutureTempVarAliases:J,variableSegments:G}=Ya(R.bodyExpr,R.analysis),{slotAliases:H,slots:oe}=Ha(Q,G,R.analysis.capturedVariables,J,e);X_({asyncBlockId:R.asyncBlockId,structName:R.structName,resultType:R.resultType,resultTypeCName:R.resultTypeCName,captureType:R.captureType,analysis:R.analysis,crossBoundaryIds:Q,awaitFutureTempVarAliases:J,overlappingSlotAliases:H,overlappingSlots:oe},e)}}n++}}function Z_(e){for(let t in e.functions){let{value:n}=e.functions[t];n.body&&J_(n.body,e)}}var Tg=["__yo_poll_","__yo_fs_event_","__yo_async_"];function Eg(e){return Tg.some(t=>e.startsWith(t))}function J_(e,t){if(e&&F(e)){let n=e;if(Bt(e)){t.usesAsync=!0;let r=e.$?.type;if(r&&Fe(r)&&Rt(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(Bt(e)){let r=e.$?.type;if(r&&Fe(r)&&Rt(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"}`)}}(gn(e)||Na(e))&&(t.usesAsync=!0);{let r=n.func.$?.type;r&&"isExtern"in r&&r.isExtern==="yo"&&"externName"in r&&typeof r.externName=="string"&&Eg(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)J_(r,t)}}function ec(e,t,n){let r=e.$?.type;if(!r||!Fe(r))return"/* Error: io.async must return a Future type */";let i=Rt(r);if(!i)return"/* Error: Could not extract Future module type */";let o=i.isFuture.outputType;if(M(o))if(o.resolvedConcreteType)o=o.resolvedConcreteType;else{let V=e.$?.runtimeArgExprsInOrder?.[0]?.$?.closureFunctionValue;if(V&&ne(V)){let I=V.type?.return?.type;if(I&&M(I)&&I.resolvedConcreteType)o=I.resolvedConcreteType;else if(V.body?.$?.type){let U=V.body.$.type;M(U)&&U.resolvedConcreteType?o=U.resolvedConcreteType:M(U)||(o=U)}}}let a=z(o,n),s=e.$?.asyncStateMachineStructName;if(!s)return"/* Error: Missing sync future struct name */";let l=`${s}_dispose`,u=`${s}_resume`,_=n.emitter,c=e.$?.runtimeArgExprsInOrder?.[0];if(!c?.$)return"/* Error: Missing closure argument for io.async */";let p=O(c,t,n),f=c.$.type,d,h;if(M(f)&&f.resolvedConcreteType){let b=f.resolvedConcreteType,V=n.implClosureCallMap.get(b.id);V&&(d=V.functionCName);let I=n.types[b.id];I&&(h=I.cName)}if(!d||!h)return"/* Error: no closure function or capture type for io.async sync path */";_.emitDeclarationLine(`struct ${s}_struct {`),_.emitDeclarationLine(" __yo_ref_header_t header;"),_.emitDeclarationLine(" int state;"),fe(o)?_.emitDeclarationLine(" uint8_t result;"):_.emitDeclarationLine(` ${a} result;`),_.emitDeclarationLine(" void (*continuation_fn)(void*);"),_.emitDeclarationLine(" void* continuation_sm;"),_.emitDeclarationLine(" void (*__yo_resume_fn)(void*);"),_.emitDeclarationLine(` ${h} __capture;`),_.emitDeclarationLine("};"),_.emitDeclarationLine("");let g="";for(let b in n.functions){let V=n.functions[b];if(V.cName===d){let I=Ct(V.value.type);I.length>0&&(g=", "+I.map(U=>`(void*)sm->__capture.${U.fieldPath.join(".")}`).join(", "));break}}_.emitDeclarationLine(`void ${u}(void* ptr) {`),_.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),fe(o)?_.emitDeclarationLine(` ${d}(&sm->__capture${g});`):_.emitDeclarationLine(` sm->result = ${d}(&sm->__capture${g});`),g&&(_.emitDeclarationLine(" if (__yo_effect_escaped) {"),_.emitDeclarationLine(" __yo_effect_escaped = 0;"),_.emitDeclarationLine(" sm->state = -2;"),_.emitDeclarationLine(" __yo_decr_rc(ptr);"),_.emitDeclarationLine(" return;"),_.emitDeclarationLine(" }")),_.emitDeclarationLine(" sm->state = -1;"),_.emitDeclarationLine(" void (*continuation)(void*) = sm->continuation_fn;"),_.emitDeclarationLine(" if (continuation) {"),_.emitDeclarationLine(" void* cont_sm = sm->continuation_sm;"),_.emitDeclarationLine(" continuation(cont_sm);"),_.emitDeclarationLine(" }"),_.emitDeclarationLine(" __yo_decr_rc(ptr);"),_.emitDeclarationLine("}"),_.emitDeclarationLine("");let y=c.$.captureType,v=y&&Ne(y)?br(y,n):void 0,T=y&&Ne(y)?Dn(y,n):void 0,$=br(o,n);_.emitDeclarationLine(`void ${l}(void* ptr) {`),(v||$)&&(_.emitDeclarationLine(` ${s}* sm = (${s}*)ptr;`),v&&(_.emitDeclarationLine(" // Drop captured variables (future owns its references)"),_.emitDeclarationLine(` ${v}(sm->__capture);`)),$&&(_.emitDeclarationLine(" if (sm->state == -1) {"),_.emitDeclarationLine(` ${$}(sm->result);`),_.emitDeclarationLine(" }"))),_.emitDeclarationLine("}"),_.emitDeclarationLine("");let C=e.$?.variableName||"__io_async_result",L=ut(r,C,n);if(_.emitLine(`${t}${L} = (${s}*)__yo_malloc(sizeof(${s}));`),_.emitLine(`${t}memset(${C}, 0, sizeof(${s}));`),_.emitLine(`${t}${C}->header.ref_count = 1;`),n.needsCycleGC&&(_.emitLine(`${t}${C}->header.gc_flags = 0;`),_.emitLine(`${t}${C}->header.gc_mark = __YO_GC_UNMARKED;`),_.emitLine(`${t}${C}->header.gc_next = NULL;`),_.emitLine(`${t}${C}->header.gc_prev = NULL;`)),n.needsCycleGC)_.emitLine(`${t}${C}->header.dispose_fn = (void(*)(void*))${l};`);else{n.disposeTypeIds||(n.disposeTypeIds=new Map,n.nextDisposeTypeId=1);let b=n.disposeTypeIds.get(l);b===void 0&&(b=n.nextDisposeTypeId,n.nextDisposeTypeId=b+1,n.disposeTypeIds.set(l,b)),_.emitLine(`${t}${C}->header.type_id = ${b};`)}return n.needsCycleGC&&_.emitLine(`${t}${C}->header.traverse_fn = NULL;`),_.emitLine(`${t}${C}->__capture = ${p};`),T&&_.emitLine(`${t}${C}->__capture = ${T}(${C}->__capture);`),_.emitLine(`${t}${C}->state = 0;`),_.emitLine(`${t}${C}->__yo_resume_fn = ${u};`),_.emitLine(`${t}${C}->continuation_fn = NULL;`),_.emitLine(`${t}${C}->continuation_sm = NULL;`),C}function tc(e,t){for(let i=0;i<e.fields.length;i++){let o=e.fields[i];ne(o)&&(Rr(o.type,t),Zr(o.body,t))}if(t.moduleLevelInitExprs)for(let i of t.moduleLevelInitExprs)Zr(i,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(Rr(o.value.type,t),o.value.specializedType&&Rr(o.value.specializedType,t),Zr(o.value.body,t),o.value.calledComptimeFunctionCaches)for(let a of o.value.calledComptimeFunctionCaches)a.value&&a.value.type&&Pt(a.value.type,t),Zr(a.body,t)}}}function Rr(e,t){for(let n of e.parameters)Pt(n.type,t);for(let n of e.forallParameters)Pt(n.type,t);Pt(e.return.type,t)}function Zr(e,t){if(e.$&&e.$.type&&Pt(e.$.type,t),e.$&&e.$.value&&ne(e.$.value)){let n=e.$.value;n.isControlFunction?(Rr(n.type,t),zt(n.body,t)):t.functions[n.funcId]||n.type.parameters.map(o=>o.type).some(o=>M(o)&&Fe(o)&&!o.resolvedConcreteType)||(t.functions[n.funcId]={value:n,cName:re(n.funcId)},Rr(n.type,t),zt(n.body,t))}if(e.$&&e.$.deferredDropExpressions&&e.$.deferredDropExpressions.length>0)for(let n of e.$.deferredDropExpressions)Zr(n,t);if(e.$&&e.$.macroExpansion&&Zr(e.$.macroExpansion,t),e.$&&e.$.runtimeDestructurings)for(let{type:n}of e.$.runtimeDestructurings)Pt(n,t);if(e.$&&e.$.captureType&&pe(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)Pt(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},Rr(i.type,t),zt(i.body,t))}}}switch(e.tag){case"FnCall":if(E(e,S.test))break;Zr(e.func,t);for(let n of e.args)Zr(n,t);break;case"Atom":e.$?.value&&P(e.$.value)&&Pt(e.$.value.value,t);break}}function Pt(e,t){if(!t.types[e.id]){if(M(e)&&Ht(e)){if(e.resolvedConcreteType){Pt(e.resolvedConcreteType,t);return}let n=on(e);n&&Pt(n,t);return}if(M(e)&&Fe(e)){let n=Rt(e);n&&Pt(n.isFuture.outputType,t);return}if(M(e)&&e.resolvedConcreteType){Pt(e.resolvedConcreteType,t);return}if(!de(e)){if(pe(e)||nt(e)||Te(e)||xe(e)||Ie(e)||$e(e)||Ve(e)||qe(e)||Ft(e)||bt(e)){let n=qe(e)?z(e,t):e.isExtern==="c"&&e.externName?e.externName:`__yo_${e.id}`;if(t.types[e.id]={type:e,cName:n},pe(e))for(let r of e.fields)Pt(r.type,t);if(Te(e)){for(let r of e.variants)if(r.fields)for(let i of r.fields)Pt(i.type,t)}if(nt(e))for(let r of e.fields)Pt(r.type,t);if(Ie(e)){let r=e;for(let i of r.requiredTraits)Pt(i.traitType,t)}if(Ft(e)){let r=e;Pt(r.childType,t),z(r,t)}if(bt(e)){let r=e;Pt(r.childType,t),z(r,t)}if(qe(e)&&Pt(e.childType,t),$e(e)||Ve(e)){for(let r of e.fields)Pt(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:re(i.funcId)},Rr(i.type,t),zt(i.body,t))}else if(r.assignedValue&&(We(r.assignedValue)||gt(r.assignedValue))){let i=r.assignedValue;ra(i,t,!1)}}}else if(ke(e)){let n=e,r=n.childType,i=n.length;if(He(i)){Pt(r,t);let o=z(r,t),a=`Array_${re(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(Ce(e)){if(Pt(e.childType,t),qe(e.childType)){let r=e.childType.childType;Pt(r,t);let i=z(r,t),o=`Slice_${re(i)}`;t.sliceStructTypes.has(o)||t.sliceStructTypes.set(o,{childType:i})}t.types[e.id]={type:e,cName:z(e,t)}}else M_.has(e.tag)&&(t.types[e.id]={type:e,cName:z(e,t)});e.trait&&Pt(e.trait,t)}}}function wi(e){if(e.$&&e.$.value&&ce(e.$.value)&&!(W(e.$.type)&&e.$.type.isExtern)){if(!fe(e.$.type))return!0}if(F(e)){if(wi(e.func))return!0;for(let t of e.args)if(!(t.$?.type&&fe(t.$.type))&&wi(t))return!0}if(e.$&&e.$.macroExpansion){if(e.$.type&&fe(e.$.type))return!1;if(wi(e.$.macroExpansion))return!0}if(e.$?.deferredDupExpressions){for(let t of e.$.deferredDupExpressions)if(wi(t))return!0}if(e.$?.deferredDropExpressions){for(let t of e.$.deferredDropExpressions)if(wi(t))return!0}return!1}function ra(e,t,n=!0){for(let r=0;r<e.fields.length;r++){let i=e.fields[r],o=e.type.fields[r];if(ne(i)){let a=o.label;if(a==="main")t.functions[i.funcId]={value:i,cName:"__yo_user_main"};else if(t.isLibrary)if(n&&t.currentModuleId&&i.funcId.startsWith(`fn_${t.currentModuleId}_`)){let l=re(a);Object.values(t.functions).some(_=>_.cName===l)?t.functions[i.funcId]={value:i,cName:re(i.funcId)}:(t.functions[i.funcId]={value:i,cName:l},t.exportedFunctionLabels||(t.exportedFunctionLabels=new Map),t.exportedFunctionLabels.set(i.funcId,a))}else t.functions[i.funcId]={value:i,cName:re(i.funcId)};else if(n&&t.currentModuleId&&i.funcId.startsWith(`fn_${t.currentModuleId}_`)){let l=re(a);Object.values(t.functions).some(_=>_.cName===l)?t.functions[i.funcId]={value:i,cName:re(i.funcId)}:(t.functions[i.funcId]={value:i,cName:l},t.exportedFunctionLabels||(t.exportedFunctionLabels=new Map),t.exportedFunctionLabels.set(i.funcId,a))}else t.functions[i.funcId]={value:i,cName:re(i.funcId)};zt(i.body,t)}}}function nc(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:re(r.funcId)},zt(r.body,t)):r&&We(r)&&nc(r,t)}}function zt(e,t){if(e.$?.value&&We(e.$.value)){let i=e.$.value;nc(i,t)}if(F(e)&&E(e,S.test)||F(e)&&E(e,k.comptime_expect_error))return;if(e.$&&e.$.macroExpansion&&zt(e.$.macroExpansion,t),e.$?.effectAnalysis){let i=e.$.effectAnalysis.handlerValue;i&&ne(i)&&zt(i.body,t)}if(e.$&&e.$.closureFunctionValue){let i=e.$.closureFunctionValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:re(i.funcId)},zt(i.body,t))}if(e.$?.indexMethodValue&&ne(e.$.indexMethodValue)){let i=e.$.indexMethodValue;t.functions[i.funcId]||(t.functions[i.funcId]={value:i,cName:re(i.funcId)},zt(i.body,t))}if(F(e)&&e.$&&e.$.dynCallTraitValues&&e.$.dynCallTraitValues.length>0){let i=e.$.type,o=e.args[0];if(Ie(i)&&o&&o.$?.type){let a=o.$.type,s=e.$.dynCallTraitValues;if(s.length>0&&(ft(a)||Fn(a))){let l=Fn(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(W(i)){if(ne(o)&&o.isControlFunction){zt(o.body,t);for(let a of e.args)zt(a,t);return}if(ne(o)){if(o.type.return.isCompileTimeOnly||ds(o)&&!o.specializedType)return;if(o.specializedType&&fr(o.specializedType)&&Ct(o.specializedType).length===0){zt(e.func,t);for(let s of e.args)zt(s,t);return}if(!t.functions[o.funcId]){let a=!1;if(wi(o.body)){let s=o.specializedType??o.type;if(a=s.implicitParameters.length>0&&(Ct(s).length>0||!fr(o.type)&&o.type.implicitParameters.length>0),!a)return}if(!a&&!(Ct(o.specializedType??o.type).length>0)&&(o.specializedType??o.type).parameters.map(_=>_.type).some(_=>M(_)&&Fe(_)&&!_.resolvedConcreteType))return;t.functions[o.funcId]={value:o,cName:re(o.funcId)},zt(o.body,t)}}else if(i.isExtern==="c"){let a=i.externName?i.externName:B(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?re(a):B(e.func)?re(e.func.token.value):re(i.id);t.externFunctions[i.id]={type:i,cName:s}}}}zt(e.func,t);for(let a of e.args)zt(a,t)}let n=e.$?.type,r=e.$?.value;if(W(n)){if(ne(r)&&r.isControlFunction){if(r.isModuleEffectMember=!0,t.functions[r.funcId]||(t.functions[r.funcId]={value:r,cName:re(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:re(o.funcId)},zt(o.body,t))}zt(r.body,t);return}if(ne(r)){if(ds(r)&&!r.specializedFunctionCaches||t.functions[r.funcId])return;if(wi(r.body))return;t.functions[r.funcId]={value:r,cName:re(r.funcId)},zt(r.body,t)}}if(P(e.$?.value)&&Pt(e.$.value.value,t),e.$?.deferredDupExpressions)for(let i of e.$.deferredDupExpressions)zt(i,t);if(e.$?.deferredDropExpressions)for(let i of e.$.deferredDropExpressions)zt(i,t);if(e.$?.dynCallTraitValues)for(let i of e.$.dynCallTraitValues)ra(i,t,!1)}function rc(e){let t=k.dispose[0];for(let n in e.types){let{type:r}=e.types[n];if(!pe(r)||!r.isReferenceSemantics)continue;let i=Bn({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:re(a.funcId)},Rr(a.type,e),zt(a.body,e)}}}function ic(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 oc(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=M(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=z(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;"),e.needsCycleGC&&(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;"));let l=`__yo_dispose_${a}`;if(e.needsCycleGC)t.emitLine(` box->header.dispose_fn = ${l};`);else{e.disposeTypeIds||(e.disposeTypeIds=new Map,e.nextDisposeTypeId=1);let c=e.disposeTypeIds.get(l);c===void 0&&(c=e.nextDisposeTypeId,e.nextDisposeTypeId=c+1,e.disposeTypeIds.set(l,c)),t.emitLine(` box->header.type_id = ${c};`)}e.needsCycleGC&&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 _=(M(r.concreteType)&&r.concreteType.resolvedConcreteType?r.concreteType.resolvedConcreteType:r.concreteType).trait?.fields.find(c=>c.label===k.___drop[0]);if(_&&_.assignedValue&&ne(_.assignedValue)){let c=e.functions[_.assignedValue.funcId]?.cName;c&&t.emitLine(` ${c}(box->value);`)}t.emitLine("}"),t.emitLine("")}}function ac(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(!wt(a))continue;let s=a.isFn.callType,l=z(s.return.type,e),u=`__yo_wrap_${n}_call`,_=["void* self_ptr"];for(let c=0;c<s.parameters.length;c++){let p=s.parameters[c],f=z(p.type,e);_.push(`${f} arg${c+1}`)}if(t.emitDeclarationLine(`static ${l} ${u}(${_.join(", ")}) {`),Fn(i)){let c=e.types[i.id]?.cName||`unknown_${i.id}`,p=re(i.fields[0].label);t.emitDeclarationLine(` ${c}* box = (${c}*)self_ptr;`);let f=i.fields[0].type,d=M(f)&&f.resolvedConcreteType?f.resolvedConcreteType:f,h=e.implClosureCallMap.get(d.id),g=(()=>{if(h)return h.functionCName;for(let[,v]of Object.entries(e.functions))if(v.value.closureInfo?.captureType?.id===d.id)return v.cName})(),y=[];if(g){y.push(`(void*)&box->${p}`);for(let v=0;v<s.parameters.length;v++)y.push(`arg${v+1}`);Ar(s.return.type)?t.emitDeclarationLine(` ${g}(${y.join(", ")});`):t.emitDeclarationLine(` return ${g}(${y.join(", ")});`)}else{y.push(`box->${p}.data`);for(let v=0;v<s.parameters.length;v++)y.push(`arg${v+1}`);Ar(s.return.type)?t.emitDeclarationLine(` box->${p}.call(${y.join(", ")});`):t.emitDeclarationLine(` return box->${p}.call(${y.join(", ")});`)}}else{t.emitDeclarationLine(" (void)self_ptr; /* Dyn(Fn): expected Box(...) data */");for(let c=0;c<s.parameters.length;c++)t.emitDeclarationLine(` (void)arg${c+1};`);Ar(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(wt(s))continue;let l=r.traitValues[a];if(!l){t.emitDeclarationLine(`/* Warning: Module value missing for module ${a} */`);continue}let _=l.type.fields;for(let c=0;c<_.length;c++){let p=_[c];if(p.label==="Self"||o.has(p.label))continue;let f=l.fields[c];if(!f||!ne(f)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function value */`);continue}let d=p.type;if(!W(d)){t.emitDeclarationLine(`/* Warning: Module field ${p.label} is not a function type */`);continue}let h=f.funcId,g=e.functions[h]?.cName;if(!g){t.emitDeclarationLine(`/* Warning: Impl function for ${p.label} not found */`);continue}let y=`__yo_wrap_${n}_${p.label}`,v=z(d.return.type,e),T=["void* self_ptr"];for(let b=1;b<d.parameters.length;b++){let V=d.parameters[b],I=z(V.type,e);T.push(`${I} arg${b}`)}t.emitDeclarationLine(`static ${v} ${y}(${T.join(", ")}) {`);let $=d.parameters[0]?.type,C;if(Fn(i)){let b=e.types[i.id]?.cName||`unknown_${i.id}`,V=re(i.fields[0].label);t.emitDeclarationLine(` ${b}* box = (${b}*)self_ptr;`),$&&Ce($)?C=`&box->${V}`:C=`box->${V}`}else{let b=z(r.concreteType,e);t.emitDeclarationLine(` ${b} concrete_value = (${b})self_ptr;`),$&&Ce($)?C="&concrete_value":C="concrete_value"}let L=[C];for(let b=1;b<d.parameters.length;b++)L.push(`arg${b}`);Ar(d.return.type)?t.emitDeclarationLine(` ${g}(${L.join(", ")});`):t.emitDeclarationLine(` return ${g}(${L.join(", ")});`),t.emitDeclarationLine("}"),t.emitDeclarationLine("")}}}}}function sc(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=M(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=M(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`,_=`__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)&${_},`);let c=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(wt(f)){let d=`__yo_wrap_${r}_call`;t.emitDeclarationLine(` .call = ${d},`),c.add("call");continue}for(let d of f.fields)if(d.label!=="Self"&&!p.has(d.label)&&!c.has(d.label)&&(c.add(d.label),W(d.type))){let h=d.type;if(h.parameters.length>0){let g=h.parameters[0];if(g&&g.label==="self"){let y=`__yo_wrap_${r}_${d.label}`;t.emitDeclarationLine(` .${re(d.label)} = ${y},`)}}}}t.emitDeclarationLine("};"),t.emitDeclarationLine("")}}function lc(e,t){let r=Gt(t)?"__declspec(thread)":"_Thread_local";e.emitLine(`
196
196
  // ============================================================================
197
197
  // Async/Await Runtime - Per-Thread Cooperative Scheduler
198
198
  // ============================================================================
@@ -9944,7 +9944,7 @@ ${o?` {
9944
9944
 
9945
9945
  return count;
9946
9946
  }
9947
- `))}function vc(e,t,n,r){lc(e,t),Ci(t)?pc(e):Kn(t)?_c(e):Gt(t)?dc(e):Xn(t)&&yc(e,t),Xn(t)||hc(e,t,r)}function $g(e,t,n,r){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){ot(e,n,r);let i=e.$.deferredDupExpressions[0];if(F(i)&&i.$?.variableName)return ve(i.$.variableName,i.$.env)}return t}function Cg(e,t,n){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){if(e.$?.variableName){let i=e.$.variableName;e.$.variableName=void 0;let o=O(e,t,n);e.$.variableName=i;let a=z(e.$.type,n),s=ie(i);s!==o&&n.emitter.emitLine(`${t}${a} ${s} = ${o};`)}else{let i=O(e,t,n);n.emitter.emitLine(`${t}${i};`)}ot(e,t,n);let r=e.$.deferredDupExpressions[0];if(F(r)&&r.$?.variableName)return ve(r.$.variableName,r.$.env)}return O(e,t,n)}function bg(e){if(F(e)&&E(e,k.___drop)&&e.args.length>=1){let t=e.args[0];if(t&&B(t))return ve(t.token.value,t.$?.env)}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&B(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&B(e.func.args[0])){let t=e.func.args[0];return ve(t.token.value,t.$?.env)}}function fn(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 _=An(u);_&&a.add(_)}let s=t.effectSmConsumedArgCNames,l=n.$?.env&&!o?t.pendingDeferredDrops.filter(u=>{let _=An(u);return!_||a.has(_)?!1:j(n.$.env,_).length>0}):t.pendingDeferredDrops.filter(u=>{let _=An(u);if(!_||a.has(_))return!1;if(s&&s.size>0){let c=bg(u);if(c&&s.has(c))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 _ of l){let c=O(_,e,t);c&&t.emitter.emitLine(`${e}${c};`)}}}}function Qn(e,t,n,r=!1){if(!t.consumedVarPendingDrops||t.consumedVarPendingDrops.length===0)return;let i=n.$?.env&&!r?t.consumedVarPendingDrops.filter(o=>{let a=An(o);return a?j(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=O(o,e,t);a&&t.emitter.emitLine(`${e}${a};`)}}}function Tc(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=O(a,t,n);s&&n.emitter.emitLine(`${t}${o.directReturnVar} = ${s};`)}}return fn(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&&!fe(e.$.type))return"// Error: return expression missing temporary variable name";let o,a=!1;if(r.inAsyncStateMachine&&i.$?.variableName){let c=i.$.variableName;i.$.variableName=void 0,o=O(i,t,n),i.$.variableName=c,a=!0}else if(i.$?.variableName&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){let c=i.$.variableName;i.$.variableName=void 0;let p=O(i,t,n);i.$.variableName=c;let f=z(i.$.type,n),d=ve(c,i.$.env);d!==p&&n.emitter.emitLine(`${t}${f} ${d} = ${p};`),o=d}else o=O(i,t,n);let s=!1;if(i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,r);let c=i.$.deferredDupExpressions[0];F(c)&&c.$?.variableName&&(o=ve(c.$.variableName,c.$.env),s=!0)}let l=z(e.$.type,n),u=e.$.variableName?ve(e.$.variableName,e.$.env):void 0;if(!s&&!fe(e.$.type)&&u&&u!==o&&n.emitter.emitLine(`${t}${l} ${u} = ${o};`),e.$.deferredDropExpressions&&$t(e,t,n),r.inAsyncStateMachine){let c=r.inAsyncStateMachine.futureType,f=Rt(c).isFuture.outputType,d=fe(f);fn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future`);let h;return d||(h=e.$.variableName&&a?e.$.variableName:e.$.variableName||o),Mr({emitter:n.emitter,indent:t,resultCode:h,debugLabel:n.currentFunctionName}),""}return fn(t,r,e),fe(e.$.type)?"return":`return ${s?o:u??o}`}else{if(e.$?.deferredDropExpressions&&$t(e,t,n),r.inAsyncStateMachine){let o=r.inAsyncStateMachine.futureType,s=Rt(o).isFuture.outputType,l=fe(s);fn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future (early unit return)`);let u=l?void 0:`(${z(s,n)}){0}`;return Mr({emitter:n.emitter,indent:t,resultCode:u,debugLabel:n.currentFunctionName}),""}return fn(t,r,e),"return"}}function Ec(e,t,n){let r=n;switch(e.tag){case"Atom":{let i=lo(e,n),o=$g(e,i,t,r);n.emitter.emitLine(`${t}return ${o};`);break}case"FnCall":{if(E(e,S.return)){let i=O(e,t,n);n.emitter.emitLine(`${t}${i};`)}else{let i=Cg(e,t,r);n.emitter.emitLine(`${t}return ${i};`)}break}}}function $c(e,t,n,r){let i=Gt(n),o=Ci(n),a=Kn(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) {",_=i?"return 0;":"return NULL;",c=i?"SwitchToThread();":"sched_yield();",p=i?`static __YO_THREAD_SYNC_TYPE __yo_worker_pool_mutex; // Pool-level mutex (initialized in __yo_worker_init_mutex)
9947
+ `))}function vc(e,t,n,r){lc(e,t),Ci(t)?pc(e):Kn(t)?_c(e):Gt(t)?dc(e):Xn(t)&&yc(e,t),Xn(t)||hc(e,t,r)}function $g(e,t,n,r){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){ot(e,n,r);let i=e.$.deferredDupExpressions[0];if(F(i)&&i.$?.variableName)return ve(i.$.variableName,i.$.env)}return t}function Cg(e,t,n){if(e.$?.deferredDupExpressions&&e.$.deferredDupExpressions.length>0){if(e.$?.variableName){let i=e.$.variableName;e.$.variableName=void 0;let o=O(e,t,n);e.$.variableName=i;let a=z(e.$.type,n),s=re(i);s!==o&&n.emitter.emitLine(`${t}${a} ${s} = ${o};`)}else{let i=O(e,t,n);n.emitter.emitLine(`${t}${i};`)}ot(e,t,n);let r=e.$.deferredDupExpressions[0];if(F(r)&&r.$?.variableName)return ve(r.$.variableName,r.$.env)}return O(e,t,n)}function bg(e){if(F(e)&&E(e,k.___drop)&&e.args.length>=1){let t=e.args[0];if(t&&B(t))return ve(t.token.value,t.$?.env)}if(F(e)&&e.args.length===0&&F(e.func)&&E(e.func,".",2)&&B(e.func.args[1])&&e.func.args[1].token.value===k.___drop[0]&&B(e.func.args[0])){let t=e.func.args[0];return ve(t.token.value,t.$?.env)}}function fn(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 _=An(u);_&&a.add(_)}let s=t.effectSmConsumedArgCNames,l=n.$?.env&&!o?t.pendingDeferredDrops.filter(u=>{let _=An(u);return!_||a.has(_)?!1:j(n.$.env,_).length>0}):t.pendingDeferredDrops.filter(u=>{let _=An(u);if(!_||a.has(_))return!1;if(s&&s.size>0){let c=bg(u);if(c&&s.has(c))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 _ of l){let c=O(_,e,t);c&&t.emitter.emitLine(`${e}${c};`)}}}}function Qn(e,t,n,r=!1){if(!t.consumedVarPendingDrops||t.consumedVarPendingDrops.length===0)return;let i=n.$?.env&&!r?t.consumedVarPendingDrops.filter(o=>{let a=An(o);return a?j(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=O(o,e,t);a&&t.emitter.emitLine(`${e}${a};`)}}}function Tc(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=O(a,t,n);s&&n.emitter.emitLine(`${t}${o.directReturnVar} = ${s};`)}}return fn(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&&!fe(e.$.type))return"// Error: return expression missing temporary variable name";let o,a=!1;if(r.inAsyncStateMachine&&i.$?.variableName){let c=i.$.variableName;i.$.variableName=void 0,o=O(i,t,n),i.$.variableName=c,a=!0}else if(i.$?.variableName&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){let c=i.$.variableName;i.$.variableName=void 0;let p=O(i,t,n);i.$.variableName=c;let f=z(i.$.type,n),d=ve(c,i.$.env);d!==p&&n.emitter.emitLine(`${t}${f} ${d} = ${p};`),o=d}else o=O(i,t,n);let s=!1;if(i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,r);let c=i.$.deferredDupExpressions[0];F(c)&&c.$?.variableName&&(o=ve(c.$.variableName,c.$.env),s=!0)}let l=z(e.$.type,n),u=e.$.variableName?ve(e.$.variableName,e.$.env):void 0;if(!s&&!fe(e.$.type)&&u&&u!==o&&n.emitter.emitLine(`${t}${l} ${u} = ${o};`),e.$.deferredDropExpressions&&$t(e,t,n),r.inAsyncStateMachine){let c=r.inAsyncStateMachine.futureType,f=Rt(c).isFuture.outputType,d=fe(f);fn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future`);let h;return d||(h=e.$.variableName&&a?e.$.variableName:e.$.variableName||o),Mr({emitter:n.emitter,indent:t,resultCode:h,debugLabel:n.currentFunctionName}),""}return fn(t,r,e),fe(e.$.type)?"return":`return ${s?o:u??o}`}else{if(e.$?.deferredDropExpressions&&$t(e,t,n),r.inAsyncStateMachine){let o=r.inAsyncStateMachine.futureType,s=Rt(o).isFuture.outputType,l=fe(s);fn(t,r,e,!0),n.emitter.emitLine(`${t}// Final state - complete the result Future (early unit return)`);let u=l?void 0:`(${z(s,n)}){0}`;return Mr({emitter:n.emitter,indent:t,resultCode:u,debugLabel:n.currentFunctionName}),""}return fn(t,r,e),"return"}}function Ec(e,t,n){let r=n;switch(e.tag){case"Atom":{let i=lo(e,n),o=$g(e,i,t,r);n.emitter.emitLine(`${t}return ${o};`);break}case"FnCall":{if(E(e,S.return)){let i=O(e,t,n);n.emitter.emitLine(`${t}${i};`)}else{let i=Cg(e,t,r);n.emitter.emitLine(`${t}return ${i};`)}break}}}function $c(e,t,n,r){let i=Gt(n),o=Ci(n),a=Kn(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) {",_=i?"return 0;":"return NULL;",c=i?"SwitchToThread();":"sched_yield();",p=i?`static __YO_THREAD_SYNC_TYPE __yo_worker_pool_mutex; // Pool-level mutex (initialized in __yo_worker_init_mutex)
9948
9948
  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?`
9949
9949
  // Initialize the worker pool mutex on Windows (must be called before any use)
9950
9950
  static void __yo_worker_init_mutex(void) {
@@ -10326,7 +10326,7 @@ static void __yo_worker_spawn(__yo_thread_fn fn, void* closure) {
10326
10326
  __yo_cond_signal(&worker->cond);
10327
10327
  __yo_mutex_unlock(&worker->mutex);
10328
10328
  }
10329
- `)}function bl(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 kl(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(wt(s)){let l=s.isFn.callType,u=z(l.return.type,n),_=l.parameters.map(c=>{let p=z(c.type,n),f=ie(c.label);return`${p} ${f}`}).join(", ");r.emitDeclarationLine(` ${u} (*call)(void* self${_?", "+_:""}); // 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=ie(l.label);if(W(l.type)){let _=l.type;if(_.parameters.length>0){let c=_.parameters[0];if(c&&c.label==="self"){let p=z(_.return.type,n),f=_.parameters.map((d,h)=>{if(h===0)return"void* self";{let g=z(d.type,n),y=ie(d.label);return`${g} ${y}`}}).join(", ");r.emitDeclarationLine(` ${p} (*${u})(${f}); // Method pointer for ${l.label}`)}}}else{let _=z(l.type,n);r.emitDeclarationLine(` ${_} ${u}; // Non-function member ${l.label}`)}}}r.emitDeclarationLine(`} ${i};`),r.emitDeclarationLine("")}function wl(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=M(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=z(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 Cc(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
10329
+ `)}function bl(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 kl(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(wt(s)){let l=s.isFn.callType,u=z(l.return.type,n),_=l.parameters.map(c=>{let p=z(c.type,n),f=re(c.label);return`${p} ${f}`}).join(", ");r.emitDeclarationLine(` ${u} (*call)(void* self${_?", "+_:""}); // 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=re(l.label);if(W(l.type)){let _=l.type;if(_.parameters.length>0){let c=_.parameters[0];if(c&&c.label==="self"){let p=z(_.return.type,n),f=_.parameters.map((d,h)=>{if(h===0)return"void* self";{let g=z(d.type,n),y=re(d.label);return`${g} ${y}`}}).join(", ");r.emitDeclarationLine(` ${p} (*${u})(${f}); // Method pointer for ${l.label}`)}}}else{let _=z(l.type,n);r.emitDeclarationLine(` ${_} ${u}; // Non-function member ${l.label}`)}}}r.emitDeclarationLine(`} ${i};`),r.emitDeclarationLine("")}function wl(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=M(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=z(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 Cc(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
10330
10330
  // Based on QuickJS trial deletion algorithm
10331
10331
  // See CYCLE_COLLECTION.md for design details
10332
10332
 
@@ -10554,7 +10554,7 @@ void __yo_arc_dispose_${n}(${n} arc) {
10554
10554
  }`),t.emitLine(`
10555
10555
  static void __yo_dispose_arc_${n}(void* ptr) {
10556
10556
  __yo_arc_dispose_${n}((${n})ptr);
10557
- }`),r.disposeGenerated=!0}}}function Ag(e,t,n){let r=n.emitter;if(e.isNewtype&&e.fields.length===1){let i=e.fields[0].type,o=z(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=z(i.type,n),a=ie(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=z(i.type,n),a=ie(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine("};")}r.emitDeclarationLine("")}function Ig(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=z(o.type,n),s=`_${i}`;r.emitDeclarationLine(` ${a} ${s};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function Sg(e,t,n){let r=n.emitter;r.emitDeclarationLine(`typedef union { // ${e.typeName} : ${A(e)}`);for(let i of e.fields){let o=z(i.type,n),a=ie(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function Fl(e,t,n){let r=n.emitter,i=Kt(e);if(i){let l=z(i,n);r.emitDeclarationLine(`typedef ${l} ${t}; // ${e.typeName} : ${A(e)} (optimized as nullable pointer)`),r.emitDeclarationLine("");return}if(Vn(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 _=Yt(e,u.name,n),c=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${_} = ${p}${c}`)}}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 _=Yt(e,u.name,n),c=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${_} = ${p}${c}`)}}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(_=>!fe(_.type));if(u.length>0){let _=l.name;r.emitDeclarationLine(" struct {");for(let c of u){let p=z(c.type,n),f=ie(c.label);r.emitDeclarationLine(` ${p} ${f};`)}r.emitDeclarationLine(` } ${_};`)}}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 xg(e,t){let n=Mn(t,"Dispose");if(!n)return;let r={...n,receiverType:e};if(e.trait)for(let o of e.trait.fields){if(!o.assignedValue||!gt(o.assignedValue))continue;let a=o.assignedValue,s=a.type;if(Y({type:r,env:t},{type:s,env:t}))return a}let i=za({concreteType:e,traitType:n,env:t});if(i)return i.traitValue}function Ng(e,t,n){let r=xg(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,_=u.specializedType??u.type;if(u.funcName===k.dispose[0]&&_.SelfType&&Y({type:_.SelfType,env:t},{type:e,env:t}))return l.cName}}function bc(e){e.emitter.emitLine("// Function implementations"),gc(e.emitter,e.targetInfo),e.usesAsync&&vc(e.emitter,e.targetInfo,e.debugAsyncAwait,{needsCycleGC:e.needsCycleGC??!1,registerDisposeTypeId:t=>{e.disposeTypeIds||(e.disposeTypeIds=new Map,e.nextDisposeTypeId=1);let n=e.disposeTypeIds.get(t);return n===void 0&&(n=e.nextDisposeTypeId,e.nextDisposeTypeId=n+1,e.disposeTypeIds.set(t,n)),n}}),e.usesParallelism&&$c(e.emitter,e.debugParallelism,e.targetInfo,e.usesAsync??!1),Dg(e),Pg(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&&Ct(n.specializedType??n.type).length===0&&[...n.type.implicitParameters,...n.type.parameters.filter(y=>y.isImplicit)].some(y=>W(y.type)))continue;let l=n.specializedType&&!Wn(n.type),u=n.specializedType??n.type,_=Ct(u).length>0,c=n.type.parameters.some(y=>y.isCompileTimeOnly);if(!i&&(!n.isModuleEffectMember||c)&&!n.specializedType&&(n.specializedFunctionCaches?.length??0)===0&&(fr(n.type)||Xr(n))||!i&&n.isIoAsyncStateMachineClosure||!i&&!a&&!_&&!n.isModuleEffectMember&&(fr(n.type)&&!n.type.isClosure||n.specializedFunctionCaches?.length>0&&!n.type.isClosure||n.specializedType&&!l||Xr(n)||Cr(n)||n.isIoAsyncStateMachineClosure))continue;let p=n.specializedType??n.type,f=!a&&!n.isModuleEffectMember&&(p.parameters.some(y=>de(y.type))||p.forallParameters.length>0),d=de(p.return.type),h=M(p.return.type)&&p.return.type.requiredTraits.length>0;if(f||d&&!h&&!n.isModuleEffectMember)continue;let g=n.body?.$?.effectAnalysis;g&&g.hasEffects,Ac(n,r,e)}Ll(e)}function kc(e){let t=e.emitter,n=[];if(!e.moduleLevelInitExprs||e.moduleLevelInitExprs.length===0)return n;for(let r of e.moduleLevelInitExprs){if(!F(r)||r.args.length<2)continue;let i=r.args[0],o=r.args[1],a;if(B(i)&&i.$?.type)a=i;else if(F(i)&&E(i,":",2)){let _=i.args[0];B(_)&&_.$?.type&&(a=_)}if(!a||!a.$?.type)continue;let s=a.$?.variableName??a.token.value,l=ve(s,a.$.env),u=z(a.$.type,e);t.emitDeclarationLine(`static ${u} ${l}; // module-level mutable variable`),n.push({cVarName:l,cTypeStr:u,rhs:o})}return n}function wc(e,t){if(t.length===0)return;let n=e.emitter;n.emitLine(`
10557
+ }`),r.disposeGenerated=!0}}}function Ag(e,t,n){let r=n.emitter;if(e.isNewtype&&e.fields.length===1){let i=e.fields[0].type,o=z(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=z(i.type,n),a=re(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=z(i.type,n),a=re(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine("};")}r.emitDeclarationLine("")}function Ig(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=z(o.type,n),s=`_${i}`;r.emitDeclarationLine(` ${a} ${s};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function Sg(e,t,n){let r=n.emitter;r.emitDeclarationLine(`typedef union { // ${e.typeName} : ${A(e)}`);for(let i of e.fields){let o=z(i.type,n),a=re(i.label);r.emitDeclarationLine(` ${o} ${a};`)}r.emitDeclarationLine(`} ${t};`),r.emitDeclarationLine("")}function Fl(e,t,n){let r=n.emitter,i=Kt(e);if(i){let l=z(i,n);r.emitDeclarationLine(`typedef ${l} ${t}; // ${e.typeName} : ${A(e)} (optimized as nullable pointer)`),r.emitDeclarationLine("");return}if(Vn(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 _=Yt(e,u.name,n),c=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${_} = ${p}${c}`)}}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 _=Yt(e,u.name,n),c=l<e.variants.length-1?",":"",p=u.discriminant??BigInt(l);r.emitDeclarationLine(` ${_} = ${p}${c}`)}}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(_=>!fe(_.type));if(u.length>0){let _=l.name;r.emitDeclarationLine(" struct {");for(let c of u){let p=z(c.type,n),f=re(c.label);r.emitDeclarationLine(` ${p} ${f};`)}r.emitDeclarationLine(` } ${_};`)}}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 xg(e,t){let n=Mn(t,"Dispose");if(!n)return;let r={...n,receiverType:e};if(e.trait)for(let o of e.trait.fields){if(!o.assignedValue||!gt(o.assignedValue))continue;let a=o.assignedValue,s=a.type;if(Y({type:r,env:t},{type:s,env:t}))return a}let i=za({concreteType:e,traitType:n,env:t});if(i)return i.traitValue}function Ng(e,t,n){let r=xg(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,_=u.specializedType??u.type;if(u.funcName===k.dispose[0]&&_.SelfType&&Y({type:_.SelfType,env:t},{type:e,env:t}))return l.cName}}function bc(e){e.emitter.emitLine("// Function implementations"),gc(e.emitter,e.targetInfo),e.usesAsync&&vc(e.emitter,e.targetInfo,e.debugAsyncAwait,{needsCycleGC:e.needsCycleGC??!1,registerDisposeTypeId:t=>{e.disposeTypeIds||(e.disposeTypeIds=new Map,e.nextDisposeTypeId=1);let n=e.disposeTypeIds.get(t);return n===void 0&&(n=e.nextDisposeTypeId,e.nextDisposeTypeId=n+1,e.disposeTypeIds.set(t,n)),n}}),e.usesParallelism&&$c(e.emitter,e.debugParallelism,e.targetInfo,e.usesAsync??!1),Dg(e),Pg(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&&Ct(n.specializedType??n.type).length===0&&[...n.type.implicitParameters,...n.type.parameters.filter(y=>y.isImplicit)].some(y=>W(y.type)))continue;let l=n.specializedType&&!Wn(n.type),u=n.specializedType??n.type,_=Ct(u).length>0,c=n.type.parameters.some(y=>y.isCompileTimeOnly);if(!i&&(!n.isModuleEffectMember||c)&&!n.specializedType&&(n.specializedFunctionCaches?.length??0)===0&&(fr(n.type)||Xr(n))||!i&&n.isIoAsyncStateMachineClosure||!i&&!a&&!_&&!n.isModuleEffectMember&&(fr(n.type)&&!n.type.isClosure||n.specializedFunctionCaches?.length>0&&!n.type.isClosure||n.specializedType&&!l||Xr(n)||Cr(n)||n.isIoAsyncStateMachineClosure))continue;let p=n.specializedType??n.type,f=!a&&!n.isModuleEffectMember&&(p.parameters.some(y=>de(y.type))||p.forallParameters.length>0),d=de(p.return.type),h=M(p.return.type)&&p.return.type.requiredTraits.length>0;if(f||d&&!h&&!n.isModuleEffectMember)continue;let g=n.body?.$?.effectAnalysis;g&&g.hasEffects,Ac(n,r,e)}Ll(e)}function kc(e){let t=e.emitter,n=[];if(!e.moduleLevelInitExprs||e.moduleLevelInitExprs.length===0)return n;for(let r of e.moduleLevelInitExprs){if(!F(r)||r.args.length<2)continue;let i=r.args[0],o=r.args[1],a;if(B(i)&&i.$?.type)a=i;else if(F(i)&&E(i,":",2)){let _=i.args[0];B(_)&&_.$?.type&&(a=_)}if(!a||!a.$?.type)continue;let s=a.$?.variableName??a.token.value,l=ve(s,a.$.env),u=z(a.$.type,e);t.emitDeclarationLine(`static ${u} ${l}; // module-level mutable variable`),n.push({cVarName:l,cTypeStr:u,rhs:o})}return n}function wc(e,t){if(t.length===0)return;let n=e.emitter;n.emitLine(`
10558
10558
  // Library initialization - call before using library functions
10559
10559
  void __yo_module_init(void) {`),n.emitLine(" // Initialize module-level mutable variables");for(let{cVarName:r,rhs:i}of t){let o=O(i," ",e);n.emitLine(` ${r} = ${o};`)}n.emitLine(`}
10560
10560
  `)}function Fc(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(!fe(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=Ct(r.type).map(()=>"NULL").join(", "),l=s?`(${s})`:"()",u=e.usesAsync?`
@@ -10573,7 +10573,7 @@ int main(int argc, char** argv) {
10573
10573
  ${_}
10574
10574
  return 0;
10575
10575
  }
10576
- `)}}function Lc(e){for(let t in e.functions){let{value:n}=e.functions[t];if(Xr(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(c=>c.isCompileTimeOnly),l=a.parameters.some(c=>!c.isCompileTimeOnly&&M(c.type)&&!Fe(c.type));if(s||l)continue;let u=n.specializedType.parameters.some(c=>de(c.type)),_=de(n.specializedType.return.type);if(u||_)continue}let i=Ct(n.specializedType??n.type);if(i.length===0&&n.specializedType){let a=Ct(n.type);a.some(s=>s.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0)&&(i=a)}i.length>0}}function Ac(e,t,n){let r=n.emitter,i=t,o=e.specializedType??e.type,a;if(e.body&&Fe(o.return.type)){let b=Jo(e.body);b?.$?.asyncStateMachineStructName?a=`${b.$.asyncStateMachineStructName}*`:e.body.$?.type&&M(e.body.$.type)&&Fe(e.body.$.type)&&(a=z(e.body.$.type,n))}e.body&&M(o.return.type)&&!Fe(o.return.type)&&!e.specializedType&&!e.isModuleEffectMember&&e.body.$?.type&&(a=z(e.body.$.type,n));let s=e.specializedType&&Ct(o).length===0&&Ct(e.type).some(b=>b.fieldFunctionType.forallParameters&&b.fieldFunctionType.forallParameters.length>0)?e.type:void 0,l=a?kr(o,t,n,a,s):kr(o,t,n,void 0,s),u=t==="__yo_user_main"||n.exportedFunctionLabels?.has(e.funcId),_=!u&&(t.includes("___drop")||t.includes("___dup")||t.includes("___dispose")),c=u?"":_?"static inline __attribute__((always_inline)) ":"static inline ";r.emitLine(`${c}${l} {`);let p=n.currentFunctionName,f=n.currentFunctionType;n.currentFunctionName=i,n.currentFunctionType=o;let d=n.isModuleEffectMemberFunction,h=n.overrideReturnTypeStr;e.isModuleEffectMember&&(n.isModuleEffectMemberFunction=!0),n.overrideReturnTypeStr=a;let g=n.currentEvidenceParams,y=Ct(o);if(y.length===0&&e.specializedType){let b=Ct(e.type);b.some(V=>V.fieldFunctionType.forallParameters&&V.fieldFunctionType.forallParameters.length>0)&&(y=b)}if(y.length>0){let b=new Map;for(let V of y)b.set(`${V.implicitLabel}.${V.fieldLabel}`,V);n.currentEvidenceParams=b}let v=n.currentClosureCaptures,T=n.currentClosureCaptureFrameLevel,$=n.currentClosureType,C=n.currentClosureCaptureTypeCName;if(o.isClosure){let b=e.closureInfo;if(b){let V=b.closureType.isFn,I=b.captureType;if(n.currentClosureType=V.callType,I&&pe(I)&&I.fields.length>0){let U=I.fields.map(x=>x.label);n.currentClosureCaptures=U,n.currentClosureCaptureFrameLevel=e.frameLevel;let D=n.types[I.id]?.cName;D&&(n.currentClosureCaptureTypeCName=D)}}}if(e.funcName===k.___dispose[0]&&o.SelfType){let b=Ng(o.SelfType,e.type.env,n);if(b){let V=o.parameters[0]?.label==="__yo_self"?"__yo_self":o.parameters[0]?.label??"__yo_self";r.emitLine(` ${b}(${V}); // Call user's dispose method`)}}Vg(e.body,o," ",n),n.currentFunctionName=p,n.currentFunctionType=f,n.isModuleEffectMemberFunction=d,n.overrideReturnTypeStr=h,n.currentEvidenceParams=g,n.currentClosureCaptures=v,n.currentClosureCaptureFrameLevel=T,n.currentClosureType=$,n.currentClosureCaptureTypeCName=C,r.emitLine("}")}function Vg(e,t,n,r){let i=r.emitter;if(F(e)&&E(e,S.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,S.return)&&(a=!0);let u=O(l,n,r);if(u&&(!l.$||!st(l.$.env.modulePath,u))&&i.emitLine(`${n}${u};`),a)break;if(it(l.$?.controlFlow)){a=!0;break}}if(!a&&o.length>0){let s=o[o.length-1];if(Fe(t.return.type)&&s){let u=Bt(s),_=s.$?.type,c=_&&Fe(_);if(u||c){let p=O(s,n,r);if(e.$?.deferredDropExpressions&&e.$.deferredDropExpressions.length>0&&_){let f=z(_,r),d=`_yo_async_return_${Math.random().toString(36).substr(2,9)}`;i.emitLine(`${n}${f} ${d} = ${p};`),$t(e,n,r),i.emitLine(`${n}return ${d};`)}else i.emitLine(`${n}return ${p};`);return}}else if(s&&fe(t.return.type)){let u=O(s,n,r);u&&i.emitLine(`${n}${u};`),$t(e,n,r)}else if(s){let u=it(s.$?.controlFlow),_=fe(s.$?.type)||F(s)&&E(s,S.tuple)&&s.args.length===0,c=o.length>1?o[o.length-2]:null,p=it(c?.$?.controlFlow);if(!(_&&p))if(u){let f=O(s,n,r);f&&i.emitLine(`${n}${f};`)}else{if(s.$?.deferredDupExpressions&&s.$.deferredDupExpressions.length>0){if(s.$?.variableName){let h=z(t.return.type,r),g=ve(s.$.variableName,s.$.env),y=O(s,n,r);g!==y&&i.emitLine(`${n}${h} ${g} = ${y};`)}ot(s,n,r);let d=s.$.deferredDupExpressions[0];if(F(d)&&d.$?.variableName){let h=ie(d.$.variableName);$t(e,n,r),i.emitLine(`${n}return ${h};`);return}}let f=O(s,n,r);$t(e,n,r),f&&i.emitLine(`${n}return ${f};`)}}}else if(a&&o.length>0){let s=o[o.length-1];s&&fe(s.$?.type)}}else if($t(e,n,r),fe(t.return.type)){let o=O(e,n,r);o&&i.emitLine(`${n}${o};`)}else Ec(e,n,r)}function Ic(e){for(let t in e.functions){let{value:n,cName:r}=e.functions[t];if(Xr(n)||!n.specializedType||!Wn(n.type))continue;let i=n.specializedType,o=i.forallParameters.length>0||i.parameters.some(c=>c.isCompileTimeOnly),a=i.parameters.some(c=>!c.isCompileTimeOnly&&M(c.type)&&!Fe(c.type));if(o||a)continue;let s=n.specializedType.parameters.some(c=>de(c.type)),l=de(n.specializedType.return.type);if(s||l)continue;let u=n.body?.$?.effectAnalysis;u&&u.hasEffects||n.isModuleEffectMember||Ct(n.specializedType??n.type).length>0||Ac(n,r,e)}}function Dg(e){e.needsCycleGC?Og(e):Mg(e)}function Mg(e){let t=e.emitter;t.emitDeclarationLine("static void __yo_dispose_dispatch(void* ptr); // Type-tag based dispose dispatch"),t.emitLine(`// Lightweight reference counting \u2014 no cycle detection needed
10576
+ `)}}function Lc(e){for(let t in e.functions){let{value:n}=e.functions[t];if(Xr(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(c=>c.isCompileTimeOnly),l=a.parameters.some(c=>!c.isCompileTimeOnly&&M(c.type)&&!Fe(c.type));if(s||l)continue;let u=n.specializedType.parameters.some(c=>de(c.type)),_=de(n.specializedType.return.type);if(u||_)continue}let i=Ct(n.specializedType??n.type);if(i.length===0&&n.specializedType){let a=Ct(n.type);a.some(s=>s.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0)&&(i=a)}i.length>0}}function Ac(e,t,n){let r=n.emitter,i=t,o=e.specializedType??e.type,a;if(e.body&&Fe(o.return.type)){let b=Jo(e.body);b?.$?.asyncStateMachineStructName?a=`${b.$.asyncStateMachineStructName}*`:e.body.$?.type&&M(e.body.$.type)&&Fe(e.body.$.type)&&(a=z(e.body.$.type,n))}e.body&&M(o.return.type)&&!Fe(o.return.type)&&!e.specializedType&&!e.isModuleEffectMember&&e.body.$?.type&&(a=z(e.body.$.type,n));let s=e.specializedType&&Ct(o).length===0&&Ct(e.type).some(b=>b.fieldFunctionType.forallParameters&&b.fieldFunctionType.forallParameters.length>0)?e.type:void 0,l=a?kr(o,t,n,a,s):kr(o,t,n,void 0,s),u=t==="__yo_user_main"||n.exportedFunctionLabels?.has(e.funcId),_=!u&&(t.includes("___drop")||t.includes("___dup")||t.includes("___dispose")),c=u?"":_?"static inline __attribute__((always_inline)) ":"static inline ";r.emitLine(`${c}${l} {`);let p=n.currentFunctionName,f=n.currentFunctionType;n.currentFunctionName=i,n.currentFunctionType=o;let d=n.isModuleEffectMemberFunction,h=n.overrideReturnTypeStr;e.isModuleEffectMember&&(n.isModuleEffectMemberFunction=!0),n.overrideReturnTypeStr=a;let g=n.currentEvidenceParams,y=Ct(o);if(y.length===0&&e.specializedType){let b=Ct(e.type);b.some(V=>V.fieldFunctionType.forallParameters&&V.fieldFunctionType.forallParameters.length>0)&&(y=b)}if(y.length>0){let b=new Map;for(let V of y)b.set(`${V.implicitLabel}.${V.fieldLabel}`,V);n.currentEvidenceParams=b}let v=n.currentClosureCaptures,T=n.currentClosureCaptureFrameLevel,$=n.currentClosureType,C=n.currentClosureCaptureTypeCName;if(o.isClosure){let b=e.closureInfo;if(b){let V=b.closureType.isFn,I=b.captureType;if(n.currentClosureType=V.callType,I&&pe(I)&&I.fields.length>0){let U=I.fields.map(x=>x.label);n.currentClosureCaptures=U,n.currentClosureCaptureFrameLevel=e.frameLevel;let D=n.types[I.id]?.cName;D&&(n.currentClosureCaptureTypeCName=D)}}}if(e.funcName===k.___dispose[0]&&o.SelfType){let b=Ng(o.SelfType,e.type.env,n);if(b){let V=o.parameters[0]?.label==="__yo_self"?"__yo_self":o.parameters[0]?.label??"__yo_self";r.emitLine(` ${b}(${V}); // Call user's dispose method`)}}Vg(e.body,o," ",n),n.currentFunctionName=p,n.currentFunctionType=f,n.isModuleEffectMemberFunction=d,n.overrideReturnTypeStr=h,n.currentEvidenceParams=g,n.currentClosureCaptures=v,n.currentClosureCaptureFrameLevel=T,n.currentClosureType=$,n.currentClosureCaptureTypeCName=C,r.emitLine("}")}function Vg(e,t,n,r){let i=r.emitter;if(F(e)&&E(e,S.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,S.return)&&(a=!0);let u=O(l,n,r);if(u&&(!l.$||!st(l.$.env.modulePath,u))&&i.emitLine(`${n}${u};`),a)break;if(it(l.$?.controlFlow)){a=!0;break}}if(!a&&o.length>0){let s=o[o.length-1];if(Fe(t.return.type)&&s){let u=Bt(s),_=s.$?.type,c=_&&Fe(_);if(u||c){let p=O(s,n,r);if(e.$?.deferredDropExpressions&&e.$.deferredDropExpressions.length>0&&_){let f=z(_,r),d=`_yo_async_return_${Math.random().toString(36).substr(2,9)}`;i.emitLine(`${n}${f} ${d} = ${p};`),$t(e,n,r),i.emitLine(`${n}return ${d};`)}else i.emitLine(`${n}return ${p};`);return}}else if(s&&fe(t.return.type)){let u=O(s,n,r);u&&i.emitLine(`${n}${u};`),$t(e,n,r)}else if(s){let u=it(s.$?.controlFlow),_=fe(s.$?.type)||F(s)&&E(s,S.tuple)&&s.args.length===0,c=o.length>1?o[o.length-2]:null,p=it(c?.$?.controlFlow);if(!(_&&p))if(u){let f=O(s,n,r);f&&i.emitLine(`${n}${f};`)}else{if(s.$?.deferredDupExpressions&&s.$.deferredDupExpressions.length>0){if(s.$?.variableName){let h=z(t.return.type,r),g=ve(s.$.variableName,s.$.env),y=O(s,n,r);g!==y&&i.emitLine(`${n}${h} ${g} = ${y};`)}ot(s,n,r);let d=s.$.deferredDupExpressions[0];if(F(d)&&d.$?.variableName){let h=re(d.$.variableName);$t(e,n,r),i.emitLine(`${n}return ${h};`);return}}let f=O(s,n,r);$t(e,n,r),f&&i.emitLine(`${n}return ${f};`)}}}else if(a&&o.length>0){let s=o[o.length-1];s&&fe(s.$?.type)}}else if($t(e,n,r),fe(t.return.type)){let o=O(e,n,r);o&&i.emitLine(`${n}${o};`)}else Ec(e,n,r)}function Ic(e){for(let t in e.functions){let{value:n,cName:r}=e.functions[t];if(Xr(n)||!n.specializedType||!Wn(n.type))continue;let i=n.specializedType,o=i.forallParameters.length>0||i.parameters.some(c=>c.isCompileTimeOnly),a=i.parameters.some(c=>!c.isCompileTimeOnly&&M(c.type)&&!Fe(c.type));if(o||a)continue;let s=n.specializedType.parameters.some(c=>de(c.type)),l=de(n.specializedType.return.type);if(s||l)continue;let u=n.body?.$?.effectAnalysis;u&&u.hasEffects||n.isModuleEffectMember||Ct(n.specializedType??n.type).length>0||Ac(n,r,e)}}function Dg(e){e.needsCycleGC?Og(e):Mg(e)}function Mg(e){let t=e.emitter;t.emitDeclarationLine("static void __yo_dispose_dispatch(void* ptr); // Type-tag based dispose dispatch"),t.emitLine(`// Lightweight reference counting \u2014 no cycle detection needed
10577
10577
  // Uses type_id dispatch instead of function pointer for dispose
10578
10578
  // (WASM: br_table ~2 cycles vs call_indirect ~20+ cycles)
10579
10579
  static inline void __yo_decr_rc(void* ptr) {
@@ -11055,7 +11055,7 @@ static void __yo_init_process_cleanup(void) {
11055
11055
  if (cleanup_initialized) return;
11056
11056
  cleanup_initialized = true;
11057
11057
  atexit(__yo_process_cleanup);
11058
- }`}`)}function Rg(e){let t=e.emitter;for(let n in e.types){let{type:r,cName:i}=e.types[n];if(pe(r)&&r.isReferenceSemantics){if(r.fields.some(s=>de(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=ie(s.label),u=s.type;if(pe(u)&&u.isReferenceSemantics)t.emitLine(` if (obj->${l}) {`),t.emitLine(` visit(obj->${l});`),t.emitLine(" }");else if(Te(u)){let _=u;if(!Kt(_)){if(!Vn(_)){t.emitLine(` switch (obj->${l}.tag) {`);for(let p of _.variants||[])if(p.fields&&p.fields.length>0){let f=p.fields.filter(d=>pe(d.type)&&d.type.isReferenceSemantics);if(f.length>0){let d=Yt(_,p.name,e);t.emitLine(` case ${d}:`);for(let h of f)t.emitLine(` if (obj->${l}.data.${p.name}.${ie(h.label)}) {`),t.emitLine(` visit(obj->${l}.data.${p.name}.${ie(h.label)});`),t.emitLine(" }");t.emitLine(" break;")}}t.emitLine(" }")}}}}t.emitLine("}"),t.emitLine("")}}}function Pg(e){let t=e.emitter;e.needsCycleGC&&Rg(e);for(let n in e.types){let{type:r,cName:i}=e.types[n];if(pe(r)&&r.isReferenceSemantics){if(r.fields.some(u=>de(u.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(u=>{let _=z(u.type,e),c=ie(u.label);return`${_} ${c}`}).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"),e.needsCycleGC&&(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(u=>u.label===k.___dispose[0]&&u.assignedValue&&ne(u.assignedValue));if(l&&ne(l.assignedValue)){let u=l.assignedValue,_=e.functions[u.funcId]?.cName||u.funcId;if(e.needsCycleGC)t.emitLine(` obj->header.dispose_fn = (void(*)(void*))${_};`);else{e.disposeTypeIds||(e.disposeTypeIds=new Map,e.nextDisposeTypeId=1);let c=e.disposeTypeIds.get(_);c===void 0&&(c=e.nextDisposeTypeId,e.nextDisposeTypeId=c+1,e.disposeTypeIds.set(_,c)),t.emitLine(` obj->header.type_id = ${c};`)}}else e.needsCycleGC?t.emitLine(" obj->header.dispose_fn = NULL;"):t.emitLine(" obj->header.type_id = 0;");if(e.needsCycleGC){let u=`__yo_traverse_${i}`;t.emitLine(` obj->header.traverse_fn = ${u};`)}r.fields.forEach(u=>{let _=ie(u.label);t.emitLine(` obj->${_} = ${_};`)}),e.needsCycleGC&&rr(r,new Set,r.env)&&t.emitLine(" __yo_gc_register(obj);"),t.emitLine(" return obj;"),t.emitLine("}"),t.emitLine("")}}}function Sc(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(_=>_.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 xc(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=M(n.concreteType)&&n.concreteType.resolvedConcreteType?n.concreteType.resolvedConcreteType:n.concreteType,a=`${(()=>{let s=e.types[i.id]?.cName;if(s)return s;let l=on(i);return(l?e.types[l.id]?.cName:void 0)||`unknown_${i.id}`})()}_${r}`;t.set(a,n)}e.dynImpls=t}var ja=class{constructor(){this.exportedFunctionNames=new Set;this._needsIntelAsmSyntax=!1;this._usesParallelism=!1;this.emitter=new Ai}compileModule(t,n,r={}){this.emitter.emitDeclarationLine(`
11058
+ }`}`)}function Rg(e){let t=e.emitter;for(let n in e.types){let{type:r,cName:i}=e.types[n];if(pe(r)&&r.isReferenceSemantics){if(r.fields.some(s=>de(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=re(s.label),u=s.type;if(pe(u)&&u.isReferenceSemantics)t.emitLine(` if (obj->${l}) {`),t.emitLine(` visit(obj->${l});`),t.emitLine(" }");else if(Te(u)){let _=u;if(!Kt(_)){if(!Vn(_)){t.emitLine(` switch (obj->${l}.tag) {`);for(let p of _.variants||[])if(p.fields&&p.fields.length>0){let f=p.fields.filter(d=>pe(d.type)&&d.type.isReferenceSemantics);if(f.length>0){let d=Yt(_,p.name,e);t.emitLine(` case ${d}:`);for(let h of f)t.emitLine(` if (obj->${l}.data.${p.name}.${re(h.label)}) {`),t.emitLine(` visit(obj->${l}.data.${p.name}.${re(h.label)});`),t.emitLine(" }");t.emitLine(" break;")}}t.emitLine(" }")}}}}t.emitLine("}"),t.emitLine("")}}}function Pg(e){let t=e.emitter;e.needsCycleGC&&Rg(e);for(let n in e.types){let{type:r,cName:i}=e.types[n];if(pe(r)&&r.isReferenceSemantics){if(r.fields.some(u=>de(u.type)))continue;let a=`__yo_new_${i}`,s=r.fields.map(u=>{let _=z(u.type,e),c=re(u.label);return`${_} ${c}`}).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"),e.needsCycleGC&&(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(u=>u.label===k.___dispose[0]&&u.assignedValue&&ne(u.assignedValue));if(l&&ne(l.assignedValue)){let u=l.assignedValue,_=e.functions[u.funcId]?.cName||u.funcId;if(e.needsCycleGC)t.emitLine(` obj->header.dispose_fn = (void(*)(void*))${_};`);else{e.disposeTypeIds||(e.disposeTypeIds=new Map,e.nextDisposeTypeId=1);let c=e.disposeTypeIds.get(_);c===void 0&&(c=e.nextDisposeTypeId,e.nextDisposeTypeId=c+1,e.disposeTypeIds.set(_,c)),t.emitLine(` obj->header.type_id = ${c};`)}}else e.needsCycleGC?t.emitLine(" obj->header.dispose_fn = NULL;"):t.emitLine(" obj->header.type_id = 0;");if(e.needsCycleGC){let u=`__yo_traverse_${i}`;t.emitLine(` obj->header.traverse_fn = ${u};`)}r.fields.forEach(u=>{let _=re(u.label);t.emitLine(` obj->${_} = ${_};`)}),e.needsCycleGC&&rr(r,new Set,r.env)&&t.emitLine(" __yo_gc_register(obj);"),t.emitLine(" return obj;"),t.emitLine("}"),t.emitLine("")}}}function Sc(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(_=>_.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 xc(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=M(n.concreteType)&&n.concreteType.resolvedConcreteType?n.concreteType.resolvedConcreteType:n.concreteType,a=`${(()=>{let s=e.types[i.id]?.cName;if(s)return s;let l=on(i);return(l?e.types[l.id]?.cName:void 0)||`unknown_${i.id}`})()}_${r}`;t.set(a,n)}e.dynImpls=t}var ja=class{constructor(){this.exportedFunctionNames=new Set;this._needsIntelAsmSyntax=!1;this._usesParallelism=!1;this.emitter=new Ai}compileModule(t,n,r={}){this.emitter.emitDeclarationLine(`
11059
11059
  // Module ${t}`),this.emitter.emitDeclarationLine(`// Module ID: ${Hi(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:Zo(),deferredAsyncBlocks:[],allocator:r.allocator??"libc",isLibrary:r.isLibrary??!1,currentModuleId:Hi(t),moduleLevelInitExprs:r.allModuleLevelInitExprs??n.moduleLevelInitExprs};if(ra(n,i),i.moduleLevelInitExprs)for(let a of i.moduleLevelInitExprs)zt(a,i);if(tc(n,i),r.isLibrary&&i.exportedFunctionLabels)for(let[a]of i.exportedFunctionLabels){let s=i.functions[a];s&&this.exportedFunctionNames.add(s.cName)}rc(i),V_(i),D_(i),this.emitter.emitDeclarationLine(`
11060
11060
  // Future state enum - shared by all Future types
11061
11061
  typedef enum {
@@ -11076,16 +11076,16 @@ static void __yo_dispose_dispatch(void* ptr) {
11076
11076
  }
11077
11077
  }`)}else i.needsCycleGC||this.emitter.emitLine("static void __yo_dispose_dispatch(void* ptr) { (void)ptr; }");i.needsIntelAsmSyntax&&(this._needsIntelAsmSyntax=!0),i.usesParallelism&&(this._usesParallelism=!0)}print(){return this.emitter.print()}getExportedFunctionNames(){return this.exportedFunctionNames}get needsIntelAsmSyntax(){return this._needsIntelAsmSyntax}get usesParallelism(){return this._usesParallelism}};var Nc=0;function Ka(e){if(e.$?.variableName)return!0;if(e.$?.value!==void 0)return!1;if(F(e)){for(let t of e.args)if(Ka(t))return!0;if(e.func&&Ka(e.func))return!0}return!1}function ia(e,t){if(F(e)){e.$?.variableName&&t.add(e.$.variableName);let n=e.func,r=n.tag==="Atom"&&(n.token.value==="&&"||n.token.value==="||");if(r)e.args.length>0&&ia(e.args[0],t);else for(let i of e.args)ia(i,t);e.func&&!r&&ia(e.func,t)}}function Vc(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=An(o);if(a&&e.has(a)){let s=O(o,t,n);s&&n.emitter.emitLine(`${t}${s};`),r.shortCircuitHandledDropVarNames.add(a)}}}}function Dc(e,t,n){if(e.args.length===0)return"true";if(e.args.length===1)return O(e.args[0],t,n);let r=[];for(let l of e.args){let u=l.$?.value;if(Be(u)){if(u.value===!1)return"false";continue}r.push(l)}if(r.length===0)return"true";if(r.length===1)return O(r[0],t,n);if(!r.slice(1).some(l=>Ka(l)))return`(${r.map(u=>O(u,t,n)).join(" && ")})`;let o=`__yo_sc_${Nc++}`;n.emitter.emitLine(`${t}bool ${o} = false;`);let a=t,s=r.length-1;for(let l=0;l<r.length;l++){let u=O(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],_=new Set;ia(u,_),Vc(_,a,n),a=a.slice(2),n.emitter.emitLine(`${a}}`)}return o}function Mc(e,t,n){if(e.args.length===0)return"false";if(e.args.length===1)return O(e.args[0],t,n);let r=[];for(let l of e.args){let u=l.$?.value;if(Be(u)){if(u.value===!0)return"true";continue}r.push(l)}if(r.length===0)return"false";if(r.length===1)return O(r[0],t,n);if(!r.slice(1).some(l=>Ka(l)))return`(${r.map(u=>O(u,t,n)).join(" || ")})`;let o=`__yo_sc_${Nc++}`;n.emitter.emitLine(`${t}bool ${o} = true;`);let a=t,s=r.length-1;for(let l=0;l<r.length;l++){let u=O(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],_=new Set;ia(u,_),Vc(_,a,n),a=a.slice(2),n.emitter.emitLine(`${a}}`)}return o}function Oc(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_arc_dispose requires exactly 1 argument";let i=O(r,t,n),o=r.$?.type;return!o||!bt(o)?"// Error: __yo_arc_dispose requires an Arc type":`__yo_arc_dispose_${z(o,n)}(${i})`}function Al(e){let t=e.func.$?.value;return P(t)&&bt(t.value)&&e.args.length===1}function Rc(e,t,n){if(!Al(e))return"/* Error: generateArcTypeCall called on non-Arc type call */";let i=(e.func.$?.value).value,o=i.childType,a=e.args[0],s=O(a,t,n),l=z(i,n),u=z(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 Pc(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 _=O(u,t,n);if(u.$?.deferredDupExpressions&&u.$.deferredDupExpressions.length>0){ot(u,t,a);let c=u.$.deferredDupExpressions[0];if(F(c)&&c.$?.variableName)return ve(c.$.variableName,c.$.env)}return _}).join(", "),l=z(i,n);if(o&&e.$?.type){let u=`(${l}){ .data = { ${s} } }`,_=ut(e.$.type,o,n);return n.emitter.emitLine(`${t}${_} = ${u};`),o}else return`(${l}){ .data = { ${s} } }`}}function zc(e,t,n){let r=n.emitter,i=e.args[0],o=e.args[1],a=i.$?.value;if(!a||!P(a)||!ke(a.value))return"/* ERROR: __yo_array_fill first argument must be an ArrayType */";let s=a.value,l=s.length;if(!He(l))return"/* ERROR: __yo_array_fill requires compile-time known array length */";let u=z(s,n),_=O(o,t,n),c=e.$?.variableName||`temp_array_${Date.now()}`,p=`i_${Pe(e.$?.env.modulePath??"")}`;return r.emitLine(`${t}${u} ${c};`),r.emitLine(`${t}for (int ${p} = 0; ${p} < ${l.value}; ${p}++) {`),r.emitLine(`${t} ${c}.data[${p}] = ${_};`),r.emitLine(`${t}}`),c}function Uc(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]),o&&B(r)&&r.$?.env){let l=r.token.value,u=j(r.$.env,l);if(u.length>0&&u[u.length-1].isModuleLevel)return""}if(F(r)&&E(r,S.comptime)||F(r)&&E(r,S.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 _=j(r.$.env,u);if(_.length>0&&_[_.length-1].isCompileTimeOnly)return""}}}if(B(r)&&r.$?.env){let l=r.token.value,u=j(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)}
11078
11078
  `;let a=O(r,t,n),s=!1;if(e.$?.variableName){let l=e.$.variableName,u=n;if((u.inAsyncStateMachine||u.inEffectStateMachine)&&a.startsWith("sm->")){let c=u.stateMachineVariables?.get(l);if(!c&&u.stateMachineVariables){for(let[,p]of u.stateMachineVariables)if(p.name===l){c=p;break}}if(c&&c.kind!=="outer"){let p=`var_${c.id}`;fe(r.$.type)||n.emitter.emitLine(`${t}sm->${p} = ${a}; // Save old value for deferred drop`)}else s=!0}else{let c=ut(r.$.type,l,n);ke(r.$.type)?n.emitter.emitLine(`${t}${c} = ${a}; // Save old value for later use`):fe(r.$.type)||n.emitter.emitLine(`${t}${c} = ${a}; // Save old value for later use`)}}if(ke(r.$.type)){let l=O(i,t,n),u=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Ht(i.$.type),_=n,c=l;if(!u&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){if(i.$?.variableName&&i.$?.type){let f=ve(i.$.variableName,i.$.env);if(f!==l.trim()){let d=i.$.convertedRuntimeType||i.$.type,h=z(d,n);n.emitter.emitLine(`${t}${h} ${f} = ${l};`)}}ot(i,t,_);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(c=ve(p.$.variableName,p.$.env))}if(o){let p=ut(r.$.type,O(r,t,n),n);n.emitter.emitLine(`${t}${p} = ${c};`)}else n.emitter.emitLine(`${t}${a} = ${c};`)}else{let l=O(i,t,n),u=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Ht(i.$.type),_=n,c=l;if(!u&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){if(i.$?.variableName&&i.$?.type){let f=ve(i.$.variableName,i.$.env);if(f!==l.trim()){let d=i.$.convertedRuntimeType||i.$.type,h=z(d,n);n.emitter.emitLine(`${t}${h} ${f} = ${l};`)}}ot(i,t,_);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(c=ve(p.$.variableName,p.$.env))}if(!fe(r.$.type)){let p=r.$.type,f=i.$?.type,d,h=st(i.$.env.modulePath,c.trim());h&&n.tempVarAsyncStructNames&&(d=n.tempVarAsyncStructNames.get(c.trim()));let g=o&&f&&Fe(p)&&Fe(f),y;h&&g?d?y=`${d}*`:y=z(f,n):g&&d?y=`${d}*`:y=z(g?f:p,n);let v=(_.inAsyncStateMachine||_.inEffectStateMachine)&&a.startsWith("sm->");n.emitter.emitLine(`${t}${o&&!v?y+" ":""}${a} = ${c};`)}}return s?"":e.$?.variableName??""}function Gc(e,t,n){let r=e.args[0];if(!r)return"// Error: await requires exactly 1 argument";let i=r.$?.type;if(!i||!Fe(i))return"// Error: await argument must be a Future type";let o=Rt(i);if(!o)return"// Error: could not extract Future module from type";let a=n;if(a.inAsyncStateMachine||a.inEffectStateMachine)return"";if(gn(e)){let s=O(r,t,n),l=z(i,n),u=o.isFuture.outputType;M(u)&&(u.resolvedConcreteType?u=u.resolvedConcreteType:e.$?.type&&!M(e.$.type)?u=e.$.type:e.$?.type&&M(e.$.type)&&e.$.type.resolvedConcreteType&&(u=e.$.type.resolvedConcreteType));let _=a.emitter,c=fe(u)||M(u)&&fe(e.$?.type??u),p=e.$?.variableName?`__sync_future_${e.$.variableName}`:"__sync_future",f=e.$?.variableName?`__pre_await_state_${e.$.variableName}`:"__pre_await_state";_.emitLine(`${t}// Synchronous await (io.await outside state machine)`),_.emitLine(`${t}${l} ${p} = ${s};`),_.emitLine(`${t}int ${f} = ${p}->state;`),na(r.$?.type)||(_.emitLine(`${t}if (${f} == 0 && ${p}->__yo_resume_fn) {`),Ug(e,p,t,n),_.emitLine(`${t} __yo_incr_rc((void*)${p}); // event loop reference`),_.emitLine(`${t} ${p}->__yo_resume_fn((void*)${p});`),_.emitLine(`${t}}`)),_.emitLine(`${t}{`),_.emitLine(`${t} int __await_state = ${p}->state;`),_.emitLine(`${t} while (__await_state != -1 && __await_state != -2) {`),_.emitLine(`${t} __yo_async_poll_step();`),_.emitLine(`${t} __await_state = ${p}->state;`),_.emitLine(`${t} }`),_.emitLine(`${t} if (__await_state == -2) {`);let h=Rt(i),g=h?.isFuture.effects?.some(y=>W(y.type)||$e(y.type)||y.isEffectRowSpread)??!1;if(g){_.emitLine(`${t} if (${f} == -2) {`),_.emitLine(`${t} fprintf(stderr, "panic: attempted to await an aborted Future\\n");`),_.emitLine(`${t} abort();`),_.emitLine(`${t} }`);let y=a.pendingDeferredDrops;if(y){let $=e.$?.variableName;a.pendingDeferredDrops=y.filter(C=>An(C)!==$)}fn(t+" ",a,e),a.pendingDeferredDrops=y;let v=zg(h,a),T=a.currentFunctionType?.return?.type;if(v)if(_.emitLine(`${t} __yo_effect_escaped = 0;`),T&&!fe(T)){let $=z(T,n);$!=="void"?(_.emitLine(`${t} ${$} _esc_result;`),_.emitLine(`${t} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${$}));`),_.emitLine(`${t} return _esc_result;`)):_.emitLine(`${t} return;`)}else _.emitLine(`${t} return;`);else if(_.emitLine(`${t} __yo_effect_escaped = 1;`),T&&!fe(T)){let $=z(T,n);_.emitLine(`${t} return (${$}){0};`)}else _.emitLine(`${t} return;`)}else _.emitLine(`${t} fprintf(stderr, "panic: attempted to await an aborted Future\\n");`),_.emitLine(`${t} abort();`);if(_.emitLine(`${t} }`),_.emitLine(`${t}}`),c)return"";{let y=e.$?.variableName||"__sync_await_result",v=z(u,n),T=ut(u,y,n);if(g){if(_.emitLine(`${t}${T};`),_.emitLine(`${t}if (${p}->state == -1) {`),Ne(u)){let $=Dn(u,n);$?_.emitLine(`${t} ${y} = ${$}(${p}->result);`):_.emitLine(`${t} ${y} = ${p}->result;`)}else _.emitLine(`${t} ${y} = ${p}->result;`);_.emitLine(`${t}} else {`),_.emitLine(`${t} ${y} = (${v}){0};`),_.emitLine(`${t}}`)}else if(Ne(u)){let $=Dn(u,n);$?_.emitLine(`${t}${T} = ${$}(${p}->result);`):_.emitLine(`${t}${T} = ${p}->result;`)}else _.emitLine(`${t}${T} = ${p}->result;`);return y}}return"// Error: await should only be used inside async blocks"}function Wc(e,t,n){let r=e.args[0];if(!r)return"// Error: io.state requires exactly 1 argument";let i=r.$?.type;if(!i||!Fe(i))return"// Error: io.state argument must be a Future type";let a=n.emitter,s=O(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 qc(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=O(o,t,n),s=e.$?.type;if(!s||!Te(s))return"// Error: JoinHandle.await return type must be Option(T)";let l=z(s,n),_=s.variants.find(C=>C.name==="Some")?.fields?.[0]?.type,c=!_||fe(_),p=c?"uint8_t":_?z(_,n):"uint8_t",f=Yt(s,"Some",n),d=Yt(s,"None",n),h=e.$?.variableName||"jh",g=`__jh_future_${h}`,y=`__jh_header_${h}`,v=e.$?.variableName||"__jh_result",T=`__yo_jh_header_${h}`;i.emitLine(`${t}// JoinHandle.await \u2014 poll spawned task, return Option(T)`);let $=ut(s,v,n);if(i.emitLine(`${t}${$};`),i.emitLine(`${t}{`),i.emitLine(`${t} void* ${g} = ${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}* ${y} = (struct ${T}*)${g};`),i.emitLine(`${t} int __jh_state = ${y}->state;`),i.emitLine(`${t} while (__jh_state != -1 && __jh_state != -2) {`),i.emitLine(`${t} __yo_async_poll_step();`),i.emitLine(`${t} __jh_state = ${y}->state;`),i.emitLine(`${t} }`),i.emitLine(`${t} if (__jh_state == -1) {`),c)i.emitLine(`${t} ${v} = (${l}){ .tag = ${f} };`);else if(_&&Ne(_)){let C=Dn(_,n);C?i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${C}(${y}->result) } } };`):i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${y}->result } } };`)}else i.emitLine(`${t} ${v} = (${l}){ .tag = ${f}, .data = { .Some = { .value = ${y}->result } } };`);return i.emitLine(`${t} } else {`),i.emitLine(`${t} __yo_effect_escaped = 0;`),i.emitLine(`${t} ${v} = (${l}){ .tag = ${d} };`),i.emitLine(`${t} }`),i.emitLine(`${t}}`),v}function zg(e,t){let n=e.isFuture.effects;if(!n?.length)return!1;let r=Yc(n),i=t.currentEvidenceParams;for(let o of r)if(W(o.type)){let a=`${o.label}.${o.label}`;if(!i?.has(a))return!0}else if($e(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 Yc(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;M(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),at(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function Ug(e,t,n,r){let i=e.args[0];if(!i?.$?.type)return;let o=Rt(i.$.type);if(!o?.isFuture.effects?.length)return;let a=Yc(o.isFuture.effects),s=r,l=s.emitter,u=e.args.find(_=>F(_)&&E(_,S.using));if(u){let _=u.args;for(let c=0;c<a.length&&c<_.length;c++){let p=a[c],f=_[c];if(W(p.type)){let d=O(f,n,r),h=p.label;l.emitLine(`${n} ${t}->__capture.${h} = (void*)${d};`)}else $e(p.type)&&Bc(p.type,t,n,f.$?.value,s,e)}}else for(let _ of a)if(W(_.type)){let c=Gg(_.label,s,e);c&&l.emitLine(`${n} ${t}->__capture.${_.label} = (void*)${c};`)}else $e(_.type)&&Bc(_.type,t,n,void 0,s,e)}function Bc(e,t,n,r,i,o){let a=i.emitter;for(let s of e.fields){if(!W(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),_=r.fields[u];if(_&&ne(_)){let c=i.functions[_.funcId];c&&(l=c.cName)}}if(!l&&i.currentEvidenceParams){for(let u of i.currentEvidenceParams.values())if(u.fieldLabel===s.label){l=u.cParamName;break}}l||(l=Bg(s.label,e,i,o)),l&&a.emitLine(`${n} ${t}->__capture.${s.label} = (void*)${l};`)}}function Bg(e,t,n,r){let i=r.$?.env??r.func.$?.env;if(!i)return;let o=hn(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(_=>_.label===e);if(u>=0){let _=l.fields[u];if(_&&ne(_)){let c=n.functions[_.funcId]?.cName;if(c)return c}}}}}function Gg(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 Hc(e,t,n){let r=e.$?.variableName,i=e.$?.type,o=n;if(r&&i){!fe(i)&&!it(e.$?.controlFlow)&&n.emitter.emitLine(`${t}${z(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=!fe(i)&&!it(e.$?.controlFlow);for(let p=0;p<e.args.length;p++){let f=e.args[p],d=O(f,t+" ",n);_.push(d);let h=p===e.args.length-1;d&&!(h&&c)&&(f.$&&st(f.$.env.modulePath,d)||n.emitter.emitLine(`${t} ${d};`))}if(c){let p=e.args[e.args.length-1],f=_[_.length-1];if(p.$?.deferredDupExpressions&&p.$.deferredDupExpressions.length>0){if(p.$?.variableName){let h=p.$.variableName;p.$.variableName=void 0;let g=O(p,t+" ",n);p.$.variableName=h;let y=z(p.$.type,n),v=ve(h,p.$.env);v!==g&&n.emitter.emitLine(`${t} ${y} ${v} = ${g};`),f=v}ot(p,t+" ",n);let d=p.$.deferredDupExpressions[0];F(d)&&d.$?.variableName&&(f=ve(d.$.variableName,d.$.env))}n.emitter.emitLine(`${t} ${r} = ${f};`)}if(e.$?.deferredDropExpressions)for(let p of e.$.deferredDropExpressions){if(o.shortCircuitHandledDropVarNames){let d=An(p);if(d&&o.shortCircuitHandledDropVarNames.has(d)){o.shortCircuitHandledDropVarNames.delete(d);continue}}let f=O(p,t+" ",n);f&&n.emitter.emitLine(`${t} ${f};`)}return n.emitter.emitLine(`${t}} // end begin block`),o.pendingDeferredDrops=a,o.consumedVarPendingDrops=l,fe(i)||it(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(c=>O(c,t+" ",n)).forEach(c=>{c&&n.emitter.emitLine(`${t} ${c};`)}),e.$?.deferredDropExpressions)for(let c of e.$.deferredDropExpressions){if(o.shortCircuitHandledDropVarNames){let f=An(c);if(f&&o.shortCircuitHandledDropVarNames.has(f)){o.shortCircuitHandledDropVarNames.delete(f);continue}}let p=O(c,t+" ",n);p&&n.emitter.emitLine(`${t} ${p};`)}return n.emitter.emitLine(`${t}} // end begin block`),o.pendingDeferredDrops=a,o.consumedVarPendingDrops=l,""}}function jc(e,t,n){let r=e.args[0];if(F(r)&&E(r,S.comptime,1)||F(r)&&E(r,S.given,1))return"";if(!r.$?.type)return`// Error: No type information for left-hand side ${w(r)}
11079
- `;let i=r.token.value,o=ut(r.$.type,i,n);return n.emitter.emitLine(`${t}${o};`),""}function Kc(e,t,n){if(e.$){let r=e.$.variableName,i=e.$.type,o=i&&fe(i),a=-1;for(let c=0;c<e.args.length;c++){let p=e.args[c];if(F(p)&&E(p,"=>",2)){let f=p.args[0];if(f&&!(Be(f.$?.value)&&f.$.value.value===!1)){a=c;break}}}let s=!1;if(a>=0){let c=e.args[a];if(c&&F(c)&&E(c,"=>",2)){let p=c.args[0];p&&Be(p.$?.value)&&p.$.value.value===!0&&(s=!0)}}if(!o&&r&&!s){let c=z(i,n);n.emitter.emitLine(`${t}${c} ${r};`)}if(s&&a>=0){let c=e.args[a];if(c&&F(c)&&E(c,"=>",2)){let p=c.args[1];if(p){let f=O(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,_=!1;for(let c=0;c<e.args.length;c++){let p=e.args[c];if(F(p)&&E(p,"=>",2)){let f=p.args[0],d=p.args[1];if(f&&d){if(Be(f.$?.value)&&f.$.value.value===!1)continue;if(_){if(n.emitter.emitLine(`${l}else {`),u++,l+=" ",!(Be(f.$?.value)&&f.$.value.value===!0)){let T=O(f,l,n);n.emitter.emitLine(`${l}if (${T}) {`)}}else{if(Be(f.$?.value)&&f.$.value.value===!0)n.emitter.emitLine(`${l}{`);else{let v=O(f,l,n);n.emitter.emitLine(`${l}if (${v}) {`)}_=!0}let h=Be(f.$?.value)&&f.$.value.value===!0,g=_&&h?l:l+" ";if(F(d)&&E(d,S.begin)){let v=d.args,T=n,$=T.pendingDeferredDrops,C=d.$?.deferredDropExpressions??[];T.pendingDeferredDrops=[...C,...$??[]];let L=T.consumedVarPendingDrops,b=d.$?.consumedVariableDropExpressions??[];T.consumedVarPendingDrops=[...b,...L??[]];for(let V=0;V<v.length-1;V++){let I=v[V],U=O(I,g,n);if(U&&I.$&&!st(I.$.env.modulePath,U)&&n.emitter.emitLine(`${g}${U};`),it(I.$?.controlFlow))break}if(v.length>0){let V=v[v.length-1];if(V.$?.deferredDupExpressions){if(V.$?.variableName){let U=V.$.variableName;V.$.variableName=void 0;let D=O(V,g,n);V.$.variableName=U;let x=z(V.$.type,n),R=ve(U,V.$.env);R!==D&&n.emitter.emitLine(`${g}${x} ${R} = ${D};`)}ot(V,g,n);let I=V.$.deferredDupExpressions[0];if(F(I)&&I.$?.variableName){let U=ve(I.$.variableName,I.$.env);r&&!o&&n.emitter.emitLine(`${g}${r} = ${U};`)}else{let U=O(V,g,n);U&&r&&!o&&n.emitter.emitLine(`${g}${r} = ${U};`)}}else{let I=O(V,g,n);I&&(I==="continue"||I==="break"||I.startsWith("goto")||F(V)&&E(V,S.return)||I.includes("return")?n.emitter.emitLine(`${g}${I};`):r&&!o&&n.emitter.emitLine(`${g}${r} = ${I};`))}}d.$?.deferredDropExpressions&&$t(d,g,n),T.pendingDeferredDrops=$,T.consumedVarPendingDrops=L}else if(d.$?.deferredDupExpressions&&d.$.deferredDupExpressions.length>0){if(d.$?.variableName){let T=d.$.variableName;d.$.variableName=void 0;let $=O(d,g,n);d.$.variableName=T;let C=z(d.$.type,n),L=ve(T,d.$.env);L!==$&&n.emitter.emitLine(`${g}${C} ${L} = ${$};`)}ot(d,g,n);let v=d.$.deferredDupExpressions[0];if(F(v)&&v.$?.variableName){let T=ve(v.$.variableName,v.$.env);r&&!o&&n.emitter.emitLine(`${g}${r} = ${T};`)}else{let T=O(d,g,n);T&&r&&!o&&n.emitter.emitLine(`${g}${r} = ${T};`)}}else{let v=O(d,g,n);v==="continue"||v==="break"||v.startsWith("goto")||F(d)&&E(d,S.return)||v.includes("return")?n.emitter.emitLine(`${g}${v};`):v===""||!v||r&&(o||n.emitter.emitLine(`${g}${r} = ${v};`))}!(_&&h)&&n.emitter.emitLine(`${l}}`)}}}for(let c=0;c<u;c++)l=l.slice(0,-2),n.emitter.emitLine(`${l}}`);return o?"":r??""}return'/* "cond" expression is not evaluated */'}function Xc(e,t,n){let r=e.args[0];return O(r,t,n)}function Qc(e,t,n){let r=e.args[0],i=r.$?.type;if(!i||!Ie(i))throw new Error("downcast codegen: expected Dyn type as first argument");let o=O(r,t,n),s=e.args[1].$?.value;if(!s||!P(s))throw new Error("downcast codegen: expected TypeValue as second argument");let l=s.value,u=z(l,n),_=n.types[l.id]?.cName||u,c=`__yo_typeid_${ie(_)}`;n.typeIdStatics||(n.typeIdStatics=new Map),n.typeIdStatics.has(l.id)||(n.typeIdStatics.set(l.id,c),n.emitter.emitDeclarationLine(`static const char ${c} = 0;`)),n.cIncludes.add("<stdint.h>");let p=`${o}.vtable->__yo_type_id == (uintptr_t)&${c}`,f,d=!1,h="",g="";for(let[,V]of n.dynImpls){if(V.dynType.id!==i.id)continue;if((M(V.concreteType)&&V.concreteType.resolvedConcreteType?V.concreteType.resolvedConcreteType:V.concreteType).id===l.id&&Fn(V.dataType)){d=!0,h=n.types[V.dataType.id]?.cName||`unknown_box_${V.dataType.id}`,g=ie(V.dataType.fields[0].label);break}}if(d){let V=`((${h}*)${o}.data)->${g}`,I=Dn(l,n);if(ft(l))f=`((${u})__yo_incr_rc((void*)${V}))`;else if(I)f=`${I}((${u})${V})`;else{let U=!1,D=l;for(;wn(D)&&D.fields.length===1;)D=D.fields[0].type;U=ft(D),U?f=`((${u})__yo_incr_rc((void*)${V}))`:f=`((${u})${V})`}}else f=`((${u})__yo_incr_rc((void*)${o}.data))`;let y=e.$?.type;if(!y||!Te(y))throw new Error("downcast codegen: expected Option enum as result type");if(Kt(y))return`((${p}) ? ${f} : NULL)`;let T=z(y,n),$=Yt(y,"Some",n),C=Yt(y,"None",n),L=`(${T}){ .tag = ${$}, .data = { .Some = { .value = ${f} } } }`,b=`(${T}){ .tag = ${C} }`;return`((${p}) ? ${L} : ${b})`}function Zc(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(!Ie(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(!ft(o)&&!Fn(o))return"/* Error: dyn() requires an object type (use box() for value types) */";let s=Fn(o)?o.fields[0].type:o,l=M(s)&&s.resolvedConcreteType?s.resolvedConcreteType:s,u=n.types[i.id]?.cName||`__yo_dyn_${i.id}`,c=`${(()=>{let y=n.types[l.id]?.cName;if(y)return y;let v=on(l);return(v?n.types[v.id]?.cName:void 0)||`unknown_${l.id}`})()}_${u}`;n.dynImpls.set(c,{dynType:i,concreteType:s,dataType:o,traitValues:a});let p=O(r,t,n);if(r.$?.variableName&&p!==r.$.variableName){let y=ut(r.$.type,r.$.variableName,n);n.emitter.emitLine(`${t}${y} = ${p};`),p=r.$.variableName}if(r.$?.deferredDupExpressions&&r.$.deferredDupExpressions.length>0){ot(r,t,n);let y=r.$.deferredDupExpressions[0];F(y)&&y.$?.variableName&&(p=ve(y.$.variableName,y.$.env))}let f=e.$?.variableName;if(!f)return"/* Error: dyn() expression missing temp variable name */";let d=n,h;if(d.inAsyncStateMachine&&d.stateMachineVariables){for(let[,y]of d.stateMachineVariables)if(y.kind==="local"&&y.id===f){h=`sm->${an(y.id,"local",d.stateMachineFieldAliases)}`;break}}let g=`__yo_vtable_${c}`;return h?(n.emitter.emitLine(`${t}${h} = (${u}){`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${g}`),n.emitter.emitLine(`${t}};`),h):(n.emitter.emitLine(`${t}${u} ${f} = {`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${g}`),n.emitter.emitLine(`${t}};`),f)}function Jc(e,t,n){return e.args.length!==0?"// Error: __yo_gc_collect requires exactly 0 arguments":"__yo_gc_collect()"}function ep(e,t,n){let r=e.args[0],i=e.args[1],o=n;if(F(r)&&E(r,S.comptime,1)||F(r)&&E(r,S.given,1))return"";if((o.inAsyncStateMachine||o.inEffectStateMachine)&&B(r)&&B(i)){let a=r.token.value,s=i.token.value,l=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(_=>_.name===a),u=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(_=>_.name===s);if(a===s&&(l||u))return""}if(e.$?.runtimeDestructurings){let a=e.$.runtimeDestructurings,s=O(i,t,n),l=i.$?.type;return a.forEach(({label:u,type:_,variableName:c})=>{if(c==="_")return;let p=ie(c,_.isExtern==="c"),f=ut(_,p,n);if(l&&pe(l)&&l.isNewtype&&l.fields.length===1){let g=l.fields[0];if(g&&g.label===u){n.emitter.emitLine(`${t}${f} = ${s}; // Destructuring ${u} (newtype)`);return}}let d=u.match(/^\d+$/)?`_${u}`:ie(u,_.isExtern==="c");if(l&&xe(l)&&!u.match(/^\d+$/)){let g=l.fields.findIndex(y=>y.label===u);d=g>=0?`_${g}`:d}let h=l&&ft(l)?"->":".";n.emitter.emitLine(`${t}${f} = ${s}${h}${d}; // Destructuring ${u}`)}),""}if(B(r)){let a=r.$?.variableName??r.token.value;if(!r.$?.type)return`// Error: No type information for variable ${a}
11080
- `;if(r.$?.env){let u=j(r.$.env,a);if(u.length>0&&u[u.length-1].isCompileTimeOnly||u.length>0&&u[u.length-1].isModuleLevel)return""}let s=!1,l;if((o.inAsyncStateMachine||o.inEffectStateMachine)&&o.stateMachineVariables&&r.$?.env){let u=j(r.$.env,a);if(u.length>0){let _=u[u.length-1],c=_.isOwningTheSameRcValueAs?_.isOwningTheSameRcValueAs.id:_.id;o.stateMachineVariables.has(c)&&(s=!0,l=c)}}if(ke(r.$.type))if(F(i)&&E(i,S.array)){let u=O(i,t,n);if(s&&l){let _=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${_} = ${u};`)}else if(!fe(r.$.type)){let _=ut(r.$.type,a,n);n.emitter.emitLine(`${t}${_} = ${u};`)}}else{let u;if(i.$?.variableName){let _=ve(i.$.variableName,i.$.env),c=O(i,t,n);if(!s){let p=ut(i.$.type,_,n);_!==c&&n.emitter.emitLine(`${t}${p} = ${c};`)}u=_}else u=O(i,t,n);if(s&&l){let _=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${_} = ${u};`)}else if(!fe(r.$.type)){let _=ut(r.$.type,a,n);n.emitter.emitLine(`${t}${_} = ${u};`)}}else{let u,_=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Ht(i.$.type),c=F(i)&&Bt(i);if(i.$?.variableName){let p=ve(i.$.variableName,i.$.env),f=ve(a,r.$.env);if(p===f){if(u=O(i,t,n),!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let d=i.$.deferredDupExpressions[0];F(d)&&d.$?.variableName&&(u=ve(d.$.variableName,d.$.env))}}else if(B(i)&&p===ve(i.token.value,i.$.env)){if(u=O(i,t,n),!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let d=i.$.deferredDupExpressions[0];F(d)&&d.$?.variableName&&(u=ve(d.$.variableName,d.$.env))}}else if(B(i)&&o.currentClosureCaptures&&o.currentClosureCaptures.includes(i.token.value)&&i.$?.env&&o.currentClosureCaptureFrameLevel!==void 0&&wr(i.token.value,i.$.env,o.currentClosureCaptureFrameLevel)){let d=o.currentClosureType;if(d&&d.isClosure){let h=Object.values(o.types).find(g=>g.type===d);h?u=`((${`${h.cName}_capture`}*)closure_context->data)->${ve(i.token.value,i.$.env)}`:u=`closure_context->${ve(i.token.value,i.$.env)}`}else u=`closure_context->${ve(i.token.value,i.$.env)}`}else{let d=O(i,t,n);if(d.trim()!==p){let h=i.$.convertedRuntimeType||i.$.type,g=ut(h,p,n);n.emitter.emitLine(`${t}${g} = ${d};`)}if(!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let h=i.$.deferredDupExpressions[0];F(h)&&h.$?.variableName?u=ve(h.$.variableName,h.$.env):u=p}else u=p}}else if(u=O(i,t,n),!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(u=ve(p.$.variableName,p.$.env))}if(qe(r.$.type)){let p=r.$.type;if(s&&l){let f=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${f} = ${u};`)}else if(!fe(p)){let f=ut(p,a,n);n.emitter.emitLine(`${t}${f} = ${u};`)}}else if(s&&l){let p=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${p} = ${u};`)}else{let p=st(i.$.env.modulePath,u.trim()),f;if(p&&n.tempVarAsyncStructNames){let d=n.tempVarAsyncStructNames.get(u.trim());d?f=`${d}*`:f=z(r.$.type,n)}else f=z(r.$.type,n);fe(r.$.type)||n.emitter.emitLine(`${t}${f} ${ve(a,r.$.env)} = ${u};`)}}return""}}var Wg=0;function oa(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 Gt(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=z(n.$.type,r),a=n.args[0]?.$?.type;return a&&Te(a)&&!Vn(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_ptr.includes(e))return`(${t[0]}.data)`;if(k.__yo_slice_new.includes(e)&&n.$?.type)return`(${z(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_getentropy.includes(e))return`getentropy(${t[0]}, ${t[1]})`;if(k.__yo_maybe_uninit_new.includes(e)&&n.$?.type){let o=z(n.$.type,r),a=`__yo_uninit_${Wg++}`;return r.emitter.emitLine(`${i}${o} ${a};`),a}else return k.__yo_maybe_uninit_as_ptr.includes(e)&&n.$?.type?`((${z(n.$.type,r)})(${t[0]}))`:k.__yo_maybe_uninit_assume_init.includes(e)?`(${t[0]})`:k.__yo_array_index.includes(e)?`(&((${t[0]})->data[${t[1]}]))`:k.__yo_slice_index.includes(e)?`(&((${t[0]})->data[${t[1]}]))`:k.__yo_array_index_range.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start })`:k.__yo_array_index_range_inclusive.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start + 1 })`:k.__yo_slice_index_range.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start })`:k.__yo_slice_index_range_inclusive.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start + 1 })`:`/* Unhandled operator ${e} */`}}function tp(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_extract requires exactly 1 argument";let i=O(r,t,n),o=r.$?.type;if(!o||!Ft(o))return"// Error: __yo_iso_extract requires an Iso type";let a=z(o,n),s=e.$?.type;if(s&&n.isoTypes?.has(a)){let _=n.isoTypes.get(a);_.optionTypeCName||(_.optionTypeCName=z(s,n))}let l=`__yo_iso_extract_${a}(${i})`,u=e.$?.variableName;return u&&s?(n.emitter.emitLine(`${t}${z(s,n)} ${u} = ${l};`),u):l}function np(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_dispose requires exactly 1 argument";let i=O(r,t,n),o=r.$?.type;return!o||!Ft(o)?"// Error: __yo_iso_dispose requires an Iso type":`__yo_iso_dispose_${z(o,n)}(${i})`}function Il(e){let t=e.func.$?.value;return P(t)&&Ft(t.value)&&e.args.length===1}function rp(e,t,n){if(!Il(e))return"/* Error: generateIsoTypeCall called on non-Iso type call */";let i=(e.func.$?.value).value,o=i.childType,a=e.args[0],s=O(a,t,n),l=z(i,n),u=z(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 Pr(e){return e===""||e==="break"||e==="continue"||e.startsWith("goto")||e.includes("return")}function zr(e,t,n){if(F(e)&&E(e,S.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 _=0;_<r.length-1;_++){let c=r[_],p=O(c,t,n);if(p&&n.emitter.emitLine(`${t}${p};`),it(c.$?.controlFlow))break}let u="";if(r.length>0){let _=r[r.length-1];if(_.$?.deferredDupExpressions&&_.$.deferredDupExpressions.length>0){if(_.$?.variableName){let p=_.$.variableName;_.$.variableName=void 0;let f=O(_,t,n);_.$.variableName=p;let d=z(_.$.type,n),h=ve(p,_.$.env);h!==f&&n.emitter.emitLine(`${t}${d} ${h} = ${f};`)}ot(_,t,n);let c=_.$.deferredDupExpressions[0];F(c)&&c.$?.variableName?u=ve(c.$.variableName,c.$.env):u=O(_,t,n)}else u=O(_,t,n)}return e.$?.deferredDropExpressions&&$t(e,t,n),i.pendingDeferredDrops=o,i.consumedVarPendingDrops=s,u}else return e.$?.deferredDupExpressions&&ot(e,t,n),O(e,t,n)}function op(e,t,n){if(!e.$)return'/* "match" expression is not evaluated */';let r=e.$.variableName,i=e.$.type,o=i&&fe(i);if(!o&&r){let h=z(i,n);n.emitter.emitLine(`${t}${h} ${r};`)}let a=O(e.args[0],t,n),s=e.args[0].$?.type;if(!s)return'// Error: "match" expression requires a valid type';if(e.$.isPrimitiveMatch)return Yg(e,t,n,a,s,r,o);let l,u;if(Ce(s)?(u=s.childType,l=s.tag):ft(s)?(u=s,l="ref_semantics"):u=s,!Te(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 c=Kt(u);if(c){let h=e.args.slice(1),g=null,y=null;for(let v of h)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,"."))g={caseBody:$};else{let C=T.func;if(C&&F(C)&&E(C,".")){let L=C.args[0];if(L&&B(L)){let b=L.token.value;y={caseBody:$,variantName:b,casePattern:T}}}}}if(n.emitter.emitLine(`${t}if (${l&&l!=="ref_semantics"?"*":""}${a} != NULL) {`),y){let v;if(F(y.casePattern)&&y.casePattern.args.length>0){let L=y.casePattern.args[0];if(L&&B(L)){v=ie(L.token.value);let b=c;n.emitter.emitLine(`${t} ${z(b,n)} ${v} = ${a};`)}}let T=n;v&&(T.inAsyncStateMachine||T.inEffectStateMachine)&&(T.localShadowedVariables||(T.localShadowedVariables=new Set),T.localShadowedVariables.add(v));let $=zr(y.caseBody,t+" ",n);v&&T.localShadowedVariables&&T.localShadowedVariables.delete(v);let C=Pr($);if(!o&&r&&!C){let L=$||a;n.emitter.emitLine(`${t} ${r} = ${L};`)}else $&&$!==""&&n.emitter.emitLine(`${t} ${$};`)}if(n.emitter.emitLine(`${t}} else {`),g){let v=zr(g.caseBody,t+" ",n),T=Pr(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(Vn(u)){n.emitter.emitLine(`${t}switch (${l&&l!=="ref_semantics"?"*":""}${a}) {`);let h=n.insideMatch;n.insideMatch=!0;let g=e.args.slice(1);for(let y=0;y<g.length;y++){let v=g[y];if(F(v)&&E(v,"=>",2)){if(!v.args[0]?.$?.caseExecuted)continue;let T=v.args[0],$=v.args[1];if(T&&$&&B(T)&&T.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let C=zr($,t+" ",n);!o&&r&&C&&!Pr(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=Yt(u,C,n);n.emitter.emitLine(`${t}case ${L}: {`);let b=zr($,t+" ",n);!o&&r&&b&&!Pr(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=h,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 d=e.args.slice(1);for(let h=0;h<d.length;h++){let g=d[h];if(F(g)&&E(g,"=>",2)){if(!g.args[0]?.$?.caseExecuted)continue;let y=g.args[0],v=g.args[1];if(y&&v&&B(y)&&y.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let T=zr(v,t+" ",n);!o&&r&&T&&!Pr(T)?n.emitter.emitLine(`${t} ${r} = ${T};`):T&&n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(y&&v&&F(y)&&y.func.tag==="Atom"&&y.func.token.value==="."&&y.args.length>=1){let T=y.args[0].token.value,$=Yt(u,T,n);if(n.emitter.emitLine(`${t}case ${$}: {`),y.args.length>1){let L=u.variants.find(b=>b.name===T);if(L&&L.fields){let b=y.args.slice(1);if(b.some(I=>F(I)&&E(I,":",2))){for(let I of b)if(F(I)&&E(I,":",2)){let U=I.args[0],D=I.args[1];if(!B(U))continue;let x=U.token.value,R=L.fields.find(Q=>Q.label===x);if(!R||fe(R.type))continue;if(B(D)){let Q=D.token.value;if(Q!=="_"){let J=ie(Q),G=ie(x),H=z(R.type,n),oe=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${H} ${J} = ${a}${oe}data.${T}.${G};`);let ge=n;if((ge?.inAsyncStateMachine||ge?.inEffectStateMachine)&&ge.stateMachineVariables){let q;if(D.$?.env){let Z=j(D.$.env,Q);Z.length>0&&(q=Z[Z.length-1].id)}if(q&&ge.stateMachineVariables.has(q)){let Z=an(q,"local",ge.stateMachineFieldAliases);n.emitter.emitLine(`${t} sm->${Z} = ${J};`)}}}}}}else for(let I=0;I<b.length&&I<L.fields.length;I++){let U=b[I],D=L.fields[I];if(B(U)&&D){if(fe(D.type))continue;let x=U.token.value;if(x!=="_"){let R=ie(x),Q=ie(D.label),J=z(D.type,n),G=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${J} ${R} = ${a}${G}data.${T}.${Q};`);let H=n;if((H?.inAsyncStateMachine||H?.inEffectStateMachine)&&H.stateMachineVariables){let oe;if(U.$?.env){let ge=j(U.$.env,x);ge.length>0&&(oe=ge[ge.length-1].id)}oe&&H.stateMachineVariables.has(oe)&&n.emitter.emitLine(`${t} sm->${an(oe,"local",H.stateMachineFieldAliases)} = ${R};`)}}}}}}if(F(v)&&E(v,"=>",2)){let L=v.args[0];n.emitter.emitLine(`${t} ${z(s,n)} ${ie(L.token.value)} = ${a};`),v=v.args[1]}let C=zr(v,t+" ",n);!o&&r&&C&&!Pr(C)?n.emitter.emitLine(`${t} ${r} = ${C};`):C&&n.emitter.emitLine(`${t} ${C};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(y&&v&&F(y)&&F(y.func)&&y.func.func.tag==="Atom"&&y.func.func.token.value==="."&&y.func.args.length===1){let T=y.func.args[0].token.value,$=Yt(u,T,n),C=y.args;n.emitter.emitLine(`${t}case ${$}: {`);let L=u.variants.find(V=>V.name===T);if(L&&L.fields&&C.length>0)if(C.some(I=>F(I)&&E(I,":",2))){for(let I of C)if(F(I)&&E(I,":",2)){let U=I.args[0],D=I.args[1];if(!B(U))continue;let x=U.token.value,R=L.fields.find(Q=>Q.label===x);if(!R)continue;if(B(D)){let Q=D.token.value;if(Q!=="_"){let J=ie(Q);if(fe(R.type))n.emitter.emitLine(`${t} // ${J} is unit type (no value)`);else{let G=ie(x),H=z(R.type,n),oe=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${H} ${J} = ${a}${oe}data.${T}.${G};`);let ge=n;if((ge?.inAsyncStateMachine||ge?.inEffectStateMachine)&&ge.stateMachineVariables){let q;if(D.$?.env){let Z=j(D.$.env,J);Z.length>0&&(q=Z[Z.length-1].id)}q&&ge.stateMachineVariables.has(q)&&n.emitter.emitLine(`${t} sm->${an(q,"local",ge.stateMachineFieldAliases)} = ${J};`)}}}}}}else for(let I=0;I<Math.min(C.length,L.fields.length);I++){let U=C[I],D=L.fields[I];if(U.tag==="Atom"&&D){let x=U.token.value;if(x!=="_"){let R=ie(x);if(fe(D.type))n.emitter.emitLine(`${t} // ${R} is unit type (no value)`);else{let Q=ie(D.label),J=z(D.type,n),G=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${J} ${R} = ${a}${G}data.${T}.${Q};`);let H=n;if((H?.inAsyncStateMachine||H?.inEffectStateMachine)&&H.stateMachineVariables){let oe;if(U.$?.env){let ge=j(U.$.env,x);ge.length>0&&(oe=ge[ge.length-1].id)}oe&&H.stateMachineVariables.has(oe)&&n.emitter.emitLine(`${t} sm->${an(oe,"local",H.stateMachineFieldAliases)} = ${R};`)}}}}}if(F(v)&&E(v,"=>",2)){let V=v.args[0];n.emitter.emitLine(`${t} ${z(s,n)} ${ie(V.token.value)} = ${a};`),v=v.args[1]}let b=zr(v,t+" ",n);!o&&r&&b&&!Pr(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&&$t(e,t,n),o?"":r??""}function qg(e){return F(e)?E(e,"|",2):!1}function Sl(e){if(!qg(e))return[e];let t=e,n=t.args[0],r=t.args[1];return[...Sl(n),...Sl(r)]}function ip(e){if(e!==void 0){if(He(e))return String(e.value);if(Be(e))return e.value?"true":"false"}}function Yg(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 _=l[u];if(F(_)&&E(_,"=>",2)){if(!_.args[0]?.$?.caseExecuted)continue;let c=_.args[0],p=_.args[1];if(!c||!p)continue;if(B(c)&&c.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let g=zr(p,t+" ",n);!a&&o&&g&&!Pr(g)?n.emitter.emitLine(`${t} ${o} = ${g};`):g&&n.emitter.emitLine(`${t} ${g};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`);continue}let f=Sl(c),d=c.$?.primitivePatternValues;if(d&&d.length>0)for(let g of d){let y=ip(g);y!==void 0&&n.emitter.emitLine(`${t}case ${y}:`)}else for(let g of f){let y=g.$?.value,v=ip(y);v!==void 0&&n.emitter.emitLine(`${t}case ${v}:`)}n.emitter.emitLine(`${t}{`);let h=zr(p,t+" ",n);!a&&o&&h&&!Pr(h)?n.emitter.emitLine(`${t} ${o} = ${h};`):h&&n.emitter.emitLine(`${t} ${h};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}return n.insideMatch=s,n.emitter.emitLine(`${t}}`),e.$?.deferredDropExpressions&&$t(e,t,n),a?"":o??""}function ap(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(pe(i)&&o===void 0){let a=O(r,t,n),s=e.$.runtimeDestructurings;for(let l of s){let u=z(l.type,n),_=ie(l.variableName),c=ie(l.label);n.emitter.emitLine(`${t}${u} ${_} = ${a}.${c};`)}}}return""}function sp(e,t,n,r){if(!t.callType)return e;let i=Ct(t.callType);if(i.length===0)return e;let o=i.map(()=>"NULL").join(", "),s=`__yo_spawn_wrapper_${Pe(r)}`;return n.emitter.emitDeclarationLine(`
11079
+ `;let i=r.token.value,o=ut(r.$.type,i,n);return n.emitter.emitLine(`${t}${o};`),""}function Kc(e,t,n){if(e.$){let r=e.$.variableName,i=e.$.type,o=i&&fe(i),a=-1;for(let c=0;c<e.args.length;c++){let p=e.args[c];if(F(p)&&E(p,"=>",2)){let f=p.args[0];if(f&&!(Be(f.$?.value)&&f.$.value.value===!1)){a=c;break}}}let s=!1;if(a>=0){let c=e.args[a];if(c&&F(c)&&E(c,"=>",2)){let p=c.args[0];p&&Be(p.$?.value)&&p.$.value.value===!0&&(s=!0)}}if(!o&&r&&!s){let c=z(i,n);n.emitter.emitLine(`${t}${c} ${r};`)}if(s&&a>=0){let c=e.args[a];if(c&&F(c)&&E(c,"=>",2)){let p=c.args[1];if(p){let f=O(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,_=!1;for(let c=0;c<e.args.length;c++){let p=e.args[c];if(F(p)&&E(p,"=>",2)){let f=p.args[0],d=p.args[1];if(f&&d){if(Be(f.$?.value)&&f.$.value.value===!1)continue;if(_){if(n.emitter.emitLine(`${l}else {`),u++,l+=" ",!(Be(f.$?.value)&&f.$.value.value===!0)){let T=O(f,l,n);n.emitter.emitLine(`${l}if (${T}) {`)}}else{if(Be(f.$?.value)&&f.$.value.value===!0)n.emitter.emitLine(`${l}{`);else{let v=O(f,l,n);n.emitter.emitLine(`${l}if (${v}) {`)}_=!0}let h=Be(f.$?.value)&&f.$.value.value===!0,g=_&&h?l:l+" ";if(F(d)&&E(d,S.begin)){let v=d.args,T=n,$=T.pendingDeferredDrops,C=d.$?.deferredDropExpressions??[];T.pendingDeferredDrops=[...C,...$??[]];let L=T.consumedVarPendingDrops,b=d.$?.consumedVariableDropExpressions??[];T.consumedVarPendingDrops=[...b,...L??[]];for(let V=0;V<v.length-1;V++){let I=v[V],U=O(I,g,n);if(U&&I.$&&!st(I.$.env.modulePath,U)&&n.emitter.emitLine(`${g}${U};`),it(I.$?.controlFlow))break}if(v.length>0){let V=v[v.length-1];if(V.$?.deferredDupExpressions){if(V.$?.variableName){let U=V.$.variableName;V.$.variableName=void 0;let D=O(V,g,n);V.$.variableName=U;let x=z(V.$.type,n),R=ve(U,V.$.env);R!==D&&n.emitter.emitLine(`${g}${x} ${R} = ${D};`)}ot(V,g,n);let I=V.$.deferredDupExpressions[0];if(F(I)&&I.$?.variableName){let U=ve(I.$.variableName,I.$.env);r&&!o&&n.emitter.emitLine(`${g}${r} = ${U};`)}else{let U=O(V,g,n);U&&r&&!o&&n.emitter.emitLine(`${g}${r} = ${U};`)}}else{let I=O(V,g,n);I&&(I==="continue"||I==="break"||I.startsWith("goto")||F(V)&&E(V,S.return)||I.includes("return")?n.emitter.emitLine(`${g}${I};`):r&&!o&&n.emitter.emitLine(`${g}${r} = ${I};`))}}d.$?.deferredDropExpressions&&$t(d,g,n),T.pendingDeferredDrops=$,T.consumedVarPendingDrops=L}else if(d.$?.deferredDupExpressions&&d.$.deferredDupExpressions.length>0){if(d.$?.variableName){let T=d.$.variableName;d.$.variableName=void 0;let $=O(d,g,n);d.$.variableName=T;let C=z(d.$.type,n),L=ve(T,d.$.env);L!==$&&n.emitter.emitLine(`${g}${C} ${L} = ${$};`)}ot(d,g,n);let v=d.$.deferredDupExpressions[0];if(F(v)&&v.$?.variableName){let T=ve(v.$.variableName,v.$.env);r&&!o&&n.emitter.emitLine(`${g}${r} = ${T};`)}else{let T=O(d,g,n);T&&r&&!o&&n.emitter.emitLine(`${g}${r} = ${T};`)}}else{let v=O(d,g,n);v==="continue"||v==="break"||v.startsWith("goto")||F(d)&&E(d,S.return)||v.includes("return")?n.emitter.emitLine(`${g}${v};`):v===""||!v||r&&(o||n.emitter.emitLine(`${g}${r} = ${v};`))}!(_&&h)&&n.emitter.emitLine(`${l}}`)}}}for(let c=0;c<u;c++)l=l.slice(0,-2),n.emitter.emitLine(`${l}}`);return o?"":r??""}return'/* "cond" expression is not evaluated */'}function Xc(e,t,n){let r=e.args[0];return O(r,t,n)}function Qc(e,t,n){let r=e.args[0],i=r.$?.type;if(!i||!Ie(i))throw new Error("downcast codegen: expected Dyn type as first argument");let o=O(r,t,n),s=e.args[1].$?.value;if(!s||!P(s))throw new Error("downcast codegen: expected TypeValue as second argument");let l=s.value,u=z(l,n),_=n.types[l.id]?.cName||u,c=`__yo_typeid_${re(_)}`;n.typeIdStatics||(n.typeIdStatics=new Map),n.typeIdStatics.has(l.id)||(n.typeIdStatics.set(l.id,c),n.emitter.emitDeclarationLine(`static const char ${c} = 0;`)),n.cIncludes.add("<stdint.h>");let p=`${o}.vtable->__yo_type_id == (uintptr_t)&${c}`,f,d=!1,h="",g="";for(let[,V]of n.dynImpls){if(V.dynType.id!==i.id)continue;if((M(V.concreteType)&&V.concreteType.resolvedConcreteType?V.concreteType.resolvedConcreteType:V.concreteType).id===l.id&&Fn(V.dataType)){d=!0,h=n.types[V.dataType.id]?.cName||`unknown_box_${V.dataType.id}`,g=re(V.dataType.fields[0].label);break}}if(d){let V=`((${h}*)${o}.data)->${g}`,I=Dn(l,n);if(ft(l))f=`((${u})__yo_incr_rc((void*)${V}))`;else if(I)f=`${I}((${u})${V})`;else{let U=!1,D=l;for(;wn(D)&&D.fields.length===1;)D=D.fields[0].type;U=ft(D),U?f=`((${u})__yo_incr_rc((void*)${V}))`:f=`((${u})${V})`}}else f=`((${u})__yo_incr_rc((void*)${o}.data))`;let y=e.$?.type;if(!y||!Te(y))throw new Error("downcast codegen: expected Option enum as result type");if(Kt(y))return`((${p}) ? ${f} : NULL)`;let T=z(y,n),$=Yt(y,"Some",n),C=Yt(y,"None",n),L=`(${T}){ .tag = ${$}, .data = { .Some = { .value = ${f} } } }`,b=`(${T}){ .tag = ${C} }`;return`((${p}) ? ${L} : ${b})`}function Zc(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(!Ie(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(!ft(o)&&!Fn(o))return"/* Error: dyn() requires an object type (use box() for value types) */";let s=Fn(o)?o.fields[0].type:o,l=M(s)&&s.resolvedConcreteType?s.resolvedConcreteType:s,u=n.types[i.id]?.cName||`__yo_dyn_${i.id}`,c=`${(()=>{let y=n.types[l.id]?.cName;if(y)return y;let v=on(l);return(v?n.types[v.id]?.cName:void 0)||`unknown_${l.id}`})()}_${u}`;n.dynImpls.set(c,{dynType:i,concreteType:s,dataType:o,traitValues:a});let p=O(r,t,n);if(r.$?.variableName&&p!==r.$.variableName){let y=ut(r.$.type,r.$.variableName,n);n.emitter.emitLine(`${t}${y} = ${p};`),p=r.$.variableName}if(r.$?.deferredDupExpressions&&r.$.deferredDupExpressions.length>0){ot(r,t,n);let y=r.$.deferredDupExpressions[0];F(y)&&y.$?.variableName&&(p=ve(y.$.variableName,y.$.env))}let f=e.$?.variableName;if(!f)return"/* Error: dyn() expression missing temp variable name */";let d=n,h;if(d.inAsyncStateMachine&&d.stateMachineVariables){for(let[,y]of d.stateMachineVariables)if(y.kind==="local"&&y.id===f){h=`sm->${an(y.id,"local",d.stateMachineFieldAliases)}`;break}}let g=`__yo_vtable_${c}`;return h?(n.emitter.emitLine(`${t}${h} = (${u}){`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${g}`),n.emitter.emitLine(`${t}};`),h):(n.emitter.emitLine(`${t}${u} ${f} = {`),n.emitter.emitLine(`${t} .data = ${p},`),n.emitter.emitLine(`${t} .vtable = &${g}`),n.emitter.emitLine(`${t}};`),f)}function Jc(e,t,n){return e.args.length!==0?"// Error: __yo_gc_collect requires exactly 0 arguments":"__yo_gc_collect()"}function ep(e,t,n){let r=e.args[0],i=e.args[1],o=n;if(F(r)&&E(r,S.comptime,1)||F(r)&&E(r,S.given,1))return"";if((o.inAsyncStateMachine||o.inEffectStateMachine)&&B(r)&&B(i)){let a=r.token.value,s=i.token.value,l=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(_=>_.name===a),u=o.stateMachineVariables&&Array.from(o.stateMachineVariables.values()).some(_=>_.name===s);if(a===s&&(l||u))return""}if(e.$?.runtimeDestructurings){let a=e.$.runtimeDestructurings,s=O(i,t,n),l=i.$?.type;return a.forEach(({label:u,type:_,variableName:c})=>{if(c==="_")return;let p=re(c,_.isExtern==="c"),f=ut(_,p,n);if(l&&pe(l)&&l.isNewtype&&l.fields.length===1){let g=l.fields[0];if(g&&g.label===u){n.emitter.emitLine(`${t}${f} = ${s}; // Destructuring ${u} (newtype)`);return}}let d=u.match(/^\d+$/)?`_${u}`:re(u,_.isExtern==="c");if(l&&xe(l)&&!u.match(/^\d+$/)){let g=l.fields.findIndex(y=>y.label===u);d=g>=0?`_${g}`:d}let h=l&&ft(l)?"->":".";n.emitter.emitLine(`${t}${f} = ${s}${h}${d}; // Destructuring ${u}`)}),""}if(B(r)){let a=r.$?.variableName??r.token.value;if(!r.$?.type)return`// Error: No type information for variable ${a}
11080
+ `;if(r.$?.env){let u=j(r.$.env,a);if(u.length>0&&u[u.length-1].isCompileTimeOnly||u.length>0&&u[u.length-1].isModuleLevel)return""}let s=!1,l;if((o.inAsyncStateMachine||o.inEffectStateMachine)&&o.stateMachineVariables&&r.$?.env){let u=j(r.$.env,a);if(u.length>0){let _=u[u.length-1],c=_.isOwningTheSameRcValueAs?_.isOwningTheSameRcValueAs.id:_.id;o.stateMachineVariables.has(c)&&(s=!0,l=c)}}if(ke(r.$.type))if(F(i)&&E(i,S.array)){let u=O(i,t,n);if(s&&l){let _=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${_} = ${u};`)}else if(!fe(r.$.type)){let _=ut(r.$.type,a,n);n.emitter.emitLine(`${t}${_} = ${u};`)}}else{let u;if(i.$?.variableName){let _=ve(i.$.variableName,i.$.env),c=O(i,t,n);if(!s){let p=ut(i.$.type,_,n);_!==c&&n.emitter.emitLine(`${t}${p} = ${c};`)}u=_}else u=O(i,t,n);if(s&&l){let _=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${_} = ${u};`)}else if(!fe(r.$.type)){let _=ut(r.$.type,a,n);n.emitter.emitLine(`${t}${_} = ${u};`)}}else{let u,_=F(i)&&i.$?.closureFunctionValue&&i.$?.type&&Ht(i.$.type),c=F(i)&&Bt(i);if(i.$?.variableName){let p=ve(i.$.variableName,i.$.env),f=ve(a,r.$.env);if(p===f){if(u=O(i,t,n),!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let d=i.$.deferredDupExpressions[0];F(d)&&d.$?.variableName&&(u=ve(d.$.variableName,d.$.env))}}else if(B(i)&&p===ve(i.token.value,i.$.env)){if(u=O(i,t,n),!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let d=i.$.deferredDupExpressions[0];F(d)&&d.$?.variableName&&(u=ve(d.$.variableName,d.$.env))}}else if(B(i)&&o.currentClosureCaptures&&o.currentClosureCaptures.includes(i.token.value)&&i.$?.env&&o.currentClosureCaptureFrameLevel!==void 0&&wr(i.token.value,i.$.env,o.currentClosureCaptureFrameLevel)){let d=o.currentClosureType;if(d&&d.isClosure){let h=Object.values(o.types).find(g=>g.type===d);h?u=`((${`${h.cName}_capture`}*)closure_context->data)->${ve(i.token.value,i.$.env)}`:u=`closure_context->${ve(i.token.value,i.$.env)}`}else u=`closure_context->${ve(i.token.value,i.$.env)}`}else{let d=O(i,t,n);if(d.trim()!==p){let h=i.$.convertedRuntimeType||i.$.type,g=ut(h,p,n);n.emitter.emitLine(`${t}${g} = ${d};`)}if(!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let h=i.$.deferredDupExpressions[0];F(h)&&h.$?.variableName?u=ve(h.$.variableName,h.$.env):u=p}else u=p}}else if(u=O(i,t,n),!_&&!c&&i.$?.deferredDupExpressions&&i.$.deferredDupExpressions.length>0){ot(i,t,o);let p=i.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(u=ve(p.$.variableName,p.$.env))}if(qe(r.$.type)){let p=r.$.type;if(s&&l){let f=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${f} = ${u};`)}else if(!fe(p)){let f=ut(p,a,n);n.emitter.emitLine(`${t}${f} = ${u};`)}}else if(s&&l){let p=an(l,"local",o.stateMachineFieldAliases);n.emitter.emitLine(`${t}sm->${p} = ${u};`)}else{let p=st(i.$.env.modulePath,u.trim()),f;if(p&&n.tempVarAsyncStructNames){let d=n.tempVarAsyncStructNames.get(u.trim());d?f=`${d}*`:f=z(r.$.type,n)}else f=z(r.$.type,n);fe(r.$.type)||n.emitter.emitLine(`${t}${f} ${ve(a,r.$.env)} = ${u};`)}}return""}}var Wg=0;function oa(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 Gt(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=z(n.$.type,r),a=n.args[0]?.$?.type;return a&&Te(a)&&!Vn(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_ptr.includes(e))return`(${t[0]}.data)`;if(k.__yo_slice_new.includes(e)&&n.$?.type)return`(${z(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_getentropy.includes(e))return`getentropy(${t[0]}, ${t[1]})`;if(k.__yo_maybe_uninit_new.includes(e)&&n.$?.type){let o=z(n.$.type,r),a=`__yo_uninit_${Wg++}`;return r.emitter.emitLine(`${i}${o} ${a};`),a}else return k.__yo_maybe_uninit_as_ptr.includes(e)&&n.$?.type?`((${z(n.$.type,r)})(${t[0]}))`:k.__yo_maybe_uninit_assume_init.includes(e)?`(${t[0]})`:k.__yo_array_index.includes(e)?`(&((${t[0]})->data[${t[1]}]))`:k.__yo_slice_index.includes(e)?`(&((${t[0]})->data[${t[1]}]))`:k.__yo_array_index_range.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start })`:k.__yo_array_index_range_inclusive.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start + 1 })`:k.__yo_slice_index_range.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start })`:k.__yo_slice_index_range_inclusive.includes(e)&&n.$?.type&&Ce(n.$.type)?`(&(${z(n.$.type.childType,r)}){ .data = &((${t[0]})->data[(${t[1]}).start]), .length = (${t[1]}).end - (${t[1]}).start + 1 })`:`/* Unhandled operator ${e} */`}}function tp(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_extract requires exactly 1 argument";let i=O(r,t,n),o=r.$?.type;if(!o||!Ft(o))return"// Error: __yo_iso_extract requires an Iso type";let a=z(o,n),s=e.$?.type;if(s&&n.isoTypes?.has(a)){let _=n.isoTypes.get(a);_.optionTypeCName||(_.optionTypeCName=z(s,n))}let l=`__yo_iso_extract_${a}(${i})`,u=e.$?.variableName;return u&&s?(n.emitter.emitLine(`${t}${z(s,n)} ${u} = ${l};`),u):l}function np(e,t,n){let r=e.args[0];if(!r)return"// Error: __yo_iso_dispose requires exactly 1 argument";let i=O(r,t,n),o=r.$?.type;return!o||!Ft(o)?"// Error: __yo_iso_dispose requires an Iso type":`__yo_iso_dispose_${z(o,n)}(${i})`}function Il(e){let t=e.func.$?.value;return P(t)&&Ft(t.value)&&e.args.length===1}function rp(e,t,n){if(!Il(e))return"/* Error: generateIsoTypeCall called on non-Iso type call */";let i=(e.func.$?.value).value,o=i.childType,a=e.args[0],s=O(a,t,n),l=z(i,n),u=z(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 Pr(e){return e===""||e==="break"||e==="continue"||e.startsWith("goto")||e.includes("return")}function zr(e,t,n){if(F(e)&&E(e,S.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 _=0;_<r.length-1;_++){let c=r[_],p=O(c,t,n);if(p&&n.emitter.emitLine(`${t}${p};`),it(c.$?.controlFlow))break}let u="";if(r.length>0){let _=r[r.length-1];if(_.$?.deferredDupExpressions&&_.$.deferredDupExpressions.length>0){if(_.$?.variableName){let p=_.$.variableName;_.$.variableName=void 0;let f=O(_,t,n);_.$.variableName=p;let d=z(_.$.type,n),h=ve(p,_.$.env);h!==f&&n.emitter.emitLine(`${t}${d} ${h} = ${f};`)}ot(_,t,n);let c=_.$.deferredDupExpressions[0];F(c)&&c.$?.variableName?u=ve(c.$.variableName,c.$.env):u=O(_,t,n)}else u=O(_,t,n)}return e.$?.deferredDropExpressions&&$t(e,t,n),i.pendingDeferredDrops=o,i.consumedVarPendingDrops=s,u}else return e.$?.deferredDupExpressions&&ot(e,t,n),O(e,t,n)}function op(e,t,n){if(!e.$)return'/* "match" expression is not evaluated */';let r=e.$.variableName,i=e.$.type,o=i&&fe(i);if(!o&&r){let h=z(i,n);n.emitter.emitLine(`${t}${h} ${r};`)}let a=O(e.args[0],t,n),s=e.args[0].$?.type;if(!s)return'// Error: "match" expression requires a valid type';if(e.$.isPrimitiveMatch)return Yg(e,t,n,a,s,r,o);let l,u;if(Ce(s)?(u=s.childType,l=s.tag):ft(s)?(u=s,l="ref_semantics"):u=s,!Te(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 c=Kt(u);if(c){let h=e.args.slice(1),g=null,y=null;for(let v of h)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,"."))g={caseBody:$};else{let C=T.func;if(C&&F(C)&&E(C,".")){let L=C.args[0];if(L&&B(L)){let b=L.token.value;y={caseBody:$,variantName:b,casePattern:T}}}}}if(n.emitter.emitLine(`${t}if (${l&&l!=="ref_semantics"?"*":""}${a} != NULL) {`),y){let v;if(F(y.casePattern)&&y.casePattern.args.length>0){let L=y.casePattern.args[0];if(L&&B(L)){v=re(L.token.value);let b=c;n.emitter.emitLine(`${t} ${z(b,n)} ${v} = ${a};`)}}let T=n;v&&(T.inAsyncStateMachine||T.inEffectStateMachine)&&(T.localShadowedVariables||(T.localShadowedVariables=new Set),T.localShadowedVariables.add(v));let $=zr(y.caseBody,t+" ",n);v&&T.localShadowedVariables&&T.localShadowedVariables.delete(v);let C=Pr($);if(!o&&r&&!C){let L=$||a;n.emitter.emitLine(`${t} ${r} = ${L};`)}else $&&$!==""&&n.emitter.emitLine(`${t} ${$};`)}if(n.emitter.emitLine(`${t}} else {`),g){let v=zr(g.caseBody,t+" ",n),T=Pr(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(Vn(u)){n.emitter.emitLine(`${t}switch (${l&&l!=="ref_semantics"?"*":""}${a}) {`);let h=n.insideMatch;n.insideMatch=!0;let g=e.args.slice(1);for(let y=0;y<g.length;y++){let v=g[y];if(F(v)&&E(v,"=>",2)){if(!v.args[0]?.$?.caseExecuted)continue;let T=v.args[0],$=v.args[1];if(T&&$&&B(T)&&T.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let C=zr($,t+" ",n);!o&&r&&C&&!Pr(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=Yt(u,C,n);n.emitter.emitLine(`${t}case ${L}: {`);let b=zr($,t+" ",n);!o&&r&&b&&!Pr(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=h,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 d=e.args.slice(1);for(let h=0;h<d.length;h++){let g=d[h];if(F(g)&&E(g,"=>",2)){if(!g.args[0]?.$?.caseExecuted)continue;let y=g.args[0],v=g.args[1];if(y&&v&&B(y)&&y.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let T=zr(v,t+" ",n);!o&&r&&T&&!Pr(T)?n.emitter.emitLine(`${t} ${r} = ${T};`):T&&n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(y&&v&&F(y)&&y.func.tag==="Atom"&&y.func.token.value==="."&&y.args.length>=1){let T=y.args[0].token.value,$=Yt(u,T,n);if(n.emitter.emitLine(`${t}case ${$}: {`),y.args.length>1){let L=u.variants.find(b=>b.name===T);if(L&&L.fields){let b=y.args.slice(1);if(b.some(I=>F(I)&&E(I,":",2))){for(let I of b)if(F(I)&&E(I,":",2)){let U=I.args[0],D=I.args[1];if(!B(U))continue;let x=U.token.value,R=L.fields.find(Q=>Q.label===x);if(!R||fe(R.type))continue;if(B(D)){let Q=D.token.value;if(Q!=="_"){let J=re(Q),G=re(x),H=z(R.type,n),oe=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${H} ${J} = ${a}${oe}data.${T}.${G};`);let ge=n;if((ge?.inAsyncStateMachine||ge?.inEffectStateMachine)&&ge.stateMachineVariables){let q;if(D.$?.env){let Z=j(D.$.env,Q);Z.length>0&&(q=Z[Z.length-1].id)}if(q&&ge.stateMachineVariables.has(q)){let Z=an(q,"local",ge.stateMachineFieldAliases);n.emitter.emitLine(`${t} sm->${Z} = ${J};`)}}}}}}else for(let I=0;I<b.length&&I<L.fields.length;I++){let U=b[I],D=L.fields[I];if(B(U)&&D){if(fe(D.type))continue;let x=U.token.value;if(x!=="_"){let R=re(x),Q=re(D.label),J=z(D.type,n),G=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${J} ${R} = ${a}${G}data.${T}.${Q};`);let H=n;if((H?.inAsyncStateMachine||H?.inEffectStateMachine)&&H.stateMachineVariables){let oe;if(U.$?.env){let ge=j(U.$.env,x);ge.length>0&&(oe=ge[ge.length-1].id)}oe&&H.stateMachineVariables.has(oe)&&n.emitter.emitLine(`${t} sm->${an(oe,"local",H.stateMachineFieldAliases)} = ${R};`)}}}}}}if(F(v)&&E(v,"=>",2)){let L=v.args[0];n.emitter.emitLine(`${t} ${z(s,n)} ${re(L.token.value)} = ${a};`),v=v.args[1]}let C=zr(v,t+" ",n);!o&&r&&C&&!Pr(C)?n.emitter.emitLine(`${t} ${r} = ${C};`):C&&n.emitter.emitLine(`${t} ${C};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}else if(y&&v&&F(y)&&F(y.func)&&y.func.func.tag==="Atom"&&y.func.func.token.value==="."&&y.func.args.length===1){let T=y.func.args[0].token.value,$=Yt(u,T,n),C=y.args;n.emitter.emitLine(`${t}case ${$}: {`);let L=u.variants.find(V=>V.name===T);if(L&&L.fields&&C.length>0)if(C.some(I=>F(I)&&E(I,":",2))){for(let I of C)if(F(I)&&E(I,":",2)){let U=I.args[0],D=I.args[1];if(!B(U))continue;let x=U.token.value,R=L.fields.find(Q=>Q.label===x);if(!R)continue;if(B(D)){let Q=D.token.value;if(Q!=="_"){let J=re(Q);if(fe(R.type))n.emitter.emitLine(`${t} // ${J} is unit type (no value)`);else{let G=re(x),H=z(R.type,n),oe=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${H} ${J} = ${a}${oe}data.${T}.${G};`);let ge=n;if((ge?.inAsyncStateMachine||ge?.inEffectStateMachine)&&ge.stateMachineVariables){let q;if(D.$?.env){let Z=j(D.$.env,J);Z.length>0&&(q=Z[Z.length-1].id)}q&&ge.stateMachineVariables.has(q)&&n.emitter.emitLine(`${t} sm->${an(q,"local",ge.stateMachineFieldAliases)} = ${J};`)}}}}}}else for(let I=0;I<Math.min(C.length,L.fields.length);I++){let U=C[I],D=L.fields[I];if(U.tag==="Atom"&&D){let x=U.token.value;if(x!=="_"){let R=re(x);if(fe(D.type))n.emitter.emitLine(`${t} // ${R} is unit type (no value)`);else{let Q=re(D.label),J=z(D.type,n),G=l==="ref_semantics"||l?"->":".";n.emitter.emitLine(`${t} ${J} ${R} = ${a}${G}data.${T}.${Q};`);let H=n;if((H?.inAsyncStateMachine||H?.inEffectStateMachine)&&H.stateMachineVariables){let oe;if(U.$?.env){let ge=j(U.$.env,x);ge.length>0&&(oe=ge[ge.length-1].id)}oe&&H.stateMachineVariables.has(oe)&&n.emitter.emitLine(`${t} sm->${an(oe,"local",H.stateMachineFieldAliases)} = ${R};`)}}}}}if(F(v)&&E(v,"=>",2)){let V=v.args[0];n.emitter.emitLine(`${t} ${z(s,n)} ${re(V.token.value)} = ${a};`),v=v.args[1]}let b=zr(v,t+" ",n);!o&&r&&b&&!Pr(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&&$t(e,t,n),o?"":r??""}function qg(e){return F(e)?E(e,"|",2):!1}function Sl(e){if(!qg(e))return[e];let t=e,n=t.args[0],r=t.args[1];return[...Sl(n),...Sl(r)]}function ip(e){if(e!==void 0){if(He(e))return String(e.value);if(Be(e))return e.value?"true":"false"}}function Yg(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 _=l[u];if(F(_)&&E(_,"=>",2)){if(!_.args[0]?.$?.caseExecuted)continue;let c=_.args[0],p=_.args[1];if(!c||!p)continue;if(B(c)&&c.token.value==="_"){n.emitter.emitLine(`${t}default: {`);let g=zr(p,t+" ",n);!a&&o&&g&&!Pr(g)?n.emitter.emitLine(`${t} ${o} = ${g};`):g&&n.emitter.emitLine(`${t} ${g};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`);continue}let f=Sl(c),d=c.$?.primitivePatternValues;if(d&&d.length>0)for(let g of d){let y=ip(g);y!==void 0&&n.emitter.emitLine(`${t}case ${y}:`)}else for(let g of f){let y=g.$?.value,v=ip(y);v!==void 0&&n.emitter.emitLine(`${t}case ${v}:`)}n.emitter.emitLine(`${t}{`);let h=zr(p,t+" ",n);!a&&o&&h&&!Pr(h)?n.emitter.emitLine(`${t} ${o} = ${h};`):h&&n.emitter.emitLine(`${t} ${h};`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t}}`)}}return n.insideMatch=s,n.emitter.emitLine(`${t}}`),e.$?.deferredDropExpressions&&$t(e,t,n),a?"":o??""}function ap(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(pe(i)&&o===void 0){let a=O(r,t,n),s=e.$.runtimeDestructurings;for(let l of s){let u=z(l.type,n),_=re(l.variableName),c=re(l.label);n.emitter.emitLine(`${t}${u} ${_} = ${a}.${c};`)}}}return""}function sp(e,t,n,r){if(!t.callType)return e;let i=Ct(t.callType);if(i.length===0)return e;let o=i.map(()=>"NULL").join(", "),s=`__yo_spawn_wrapper_${Pe(r)}`;return n.emitter.emitDeclarationLine(`
11081
11081
  // Spawn wrapper: bridges __yo_thread_fn to closure with evidence params
11082
11082
  static void ${s}(void* closure) {
11083
11083
  ${e}(closure, ${o});
11084
11084
  }
11085
- `),s}function lp(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(M(o)){let g=o;g.resolvedConcreteType&&(a=g.resolvedConcreteType.id,s=g.resolvedConcreteType)}else pe(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,_=z(s,n),c=sp(u,l,n,e.$?.env.modulePath??""),p=O(i,t,n),f=i.$?.variableName?ve(i.$.variableName,i.$.env):p,d=`_thread_closure_data_${Pe(e.$?.env.modulePath??"")}`;n.emitter.emitLine(`${t}${_}* ${d} = (${_}*)__yo_malloc(sizeof(${_}));`),n.emitter.emitLine(`${t}*${d} = ${f};`);let h=e.$?.variableName;return h?(n.emitter.emitLine(`${t}__yo_thread_t ${h} = __yo_thread_spawn(${c}, ${d});`),h):`__yo_thread_spawn(${c}, ${d})`}function up(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(M(o)){let h=o;h.resolvedConcreteType&&(a=h.resolvedConcreteType.id,s=h.resolvedConcreteType)}else pe(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,_=z(s,n),c=sp(u,l,n,e.$?.env.modulePath??""),p=O(i,t,n),f=i.$?.variableName?ve(i.$.variableName,i.$.env):p,d=`_worker_closure_data_${Pe(e.$?.env.modulePath??"")}`;return n.emitter.emitLine(`${t}${_}* ${d} = (${_}*)__yo_malloc(sizeof(${_}));`),n.emitter.emitLine(`${t}*${d} = ${f};`),n.emitter.emitLine(`${t}__yo_worker_spawn(${c}, ${d});`),""}function _p(e,t,n){let r=e.args[0];return r?`__yo_thread_set_maximum_threads(${O(r,t,n)})`:"// Error: __yo_thread_set_maximum_threads requires exactly 1 argument"}function cp(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 In(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&&Fe(i.type))return;let o=`var_${i.id}`,a=ie(e);n.emitter.emitLine(`${t}sm->${o} = ${a};`)}}function dp(e,t,n){if(e.$?.value!==void 0&&!ce(e.$.value))return e.$?.deferredDropExpressions&&$t(e,t,n),fe(e.$.type)?"":en(e.$.value,n,e);let r=e.func.$?.value,i=e.func.$?.type??(ne(r)?r.specializedType??r.type:void 0);if(W(i)){let o=e.$?.runtimeArgExprsInOrder;if(o){let a=!1;if(F(e.func)&&E(e.func,".",2)){let _=e.func.args[0]?.$?.type;_&&Ie(_)&&(a=!0)}let s=o.map((u,_)=>{if(u.$?.variableName&&u.$?.type){let c=n,p=c.currentClosureCaptures&&c.currentClosureCaptures.includes(u.$.variableName)&&B(u)&&u.$.env&&c.currentClosureCaptureFrameLevel!==void 0&&wr(u.token.value,u.$.env,c.currentClosureCaptureFrameLevel),f=O(u,t,n),d=!1;if(B(u)&&u.$.env&&u.$.variableName){let v=j(u.$.env,u.$.variableName);v.length>0&&v[v.length-1].isCompileTimeOnly&&(d=!0)}let h=(c.inAsyncStateMachine||c.inEffectStateMachine)&&f.startsWith("sm->"),g=!1;if(f&&f!==u.$.variableName&&!p&&!h&&!d){let v=ve(u.$.variableName,u.$.env);if(f!==v){let T=u.$.convertedRuntimeType||u.$.type,$=ut(T,u.$.variableName,n);n.emitter.emitLine(`${t}${$} = ${f};`),g=!0,In(u.$.variableName,t,n)}}let y=g?u.$.variableName:f;if(u.$?.deferredDupExpressions&&u.$.deferredDupExpressions.length>0){let v=new Set;u.$?.variableName&&v.add(ve(u.$.variableName,u.$.env)),f&&v.add(f),B(u)&&v.add(ve(u.token.value,u.$.env));let T=u.$.deferredDupExpressions.find($=>{let C=qa($);return C?v.has(ve(C,$.$?.env)):!1});T&&(ot(u,t,c),F(T)&&T.$?.variableName&&(y=ve(T.$.variableName,T.$.env)))}if(a&&_===0){if(F(e.func)&&E(e.func,".",2)){let $=e.func.args[0]?.$?.type,C=e.func.args[1];if(B(C)&&Ie($)){let L=C.token.value;if($.trait.fields.find(V=>V.label===L))return h?f:ie(y,u.$.type.isExtern==="c")}}let v=u.$?.type;return v&&Ce(v)?h?`${f}->data`:`${ie(y,u.$.type.isExtern==="c")}->data`:h?`(${f}).data`:`(${ie(y,u.$.type.isExtern==="c")}).data`}else return p||h||d?f:ie(y,u.$.type.isExtern==="c")}else if(a&&_===0){let c=O(u,t,n);if(F(e.func)&&E(e.func,".",2)){let d=e.func.args[0]?.$?.type,h=e.func.args[1];if(B(h)&&Ie(d)){let g=h.token.value;if(d.trait.fields.find(v=>v.label===g))return c}}let p=u.$?.type;return p&&Ce(p)?`(${c})->data`:`(${c}).data`}else return O(u,t,n)}),l=s.join(", ");if(i.isExtern==="yo"&&i.externName){let u=i.externName;return bi.includes(u)?oa(u,s,e,n,t):u==="__yo_thread_spawn"?lp(e,t,n):u==="__yo_worker_spawn"?up(e,t,n):fe(i.return.type)?(n.emitter.emitLine(`${t}${u}(${l});`),e.$?.deferredDropExpressions&&$t(e,t,n),""):`${u}(${l})`}{let u=n;if(u.currentEvidenceParams?.size){let _=e.func.token?.value,c;if(_==="."&&F(e.func)&&E(e.func,".",2)){let p=e.func.args[1];p&&B(p)&&(_=p.token.value);let f=e.func.args[0];if(f&&B(f))c=f.token.value;else if(f&&F(f)&&E(f,".",2)){let d=f.args[0];d&&B(d)&&(c=d.token.value)}}if(_&&_!=="."){for(let p of u.currentEvidenceParams.values())if(p.fieldLabel===_||p.implicitLabel===_||p.fieldPath[p.fieldPath.length-1]===_){if(c&&c!==p.implicitLabel)continue;return fp(p.cParamName,i,s,o,e,t,u,p)}}}}if(ne(r)){let u=Cr(r);if(u)return oa(u,s,e,n,t);let _=r.specializedType??r.type,c=n;if(c.currentEvidenceParams&&r.isModuleEffectMember){let f,d=e.func.$?.env??e.$?.env;if(d)for(let h of c.currentEvidenceParams.values()){let g=j(d,h.implicitLabel),v=g[g.length-1]?.value?.[0];if(v&&We(v)){let T=v,$=!0;for(let C=0;C<h.fieldPath.length-1;C++){let L=h.fieldPath[C],b=T.type.fields.findIndex(V=>V.label===L);if(b>=0&&T.fields[b]&&We(T.fields[b]))T=T.fields[b];else{$=!1;break}}if($){let C=h.fieldPath[h.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=h;break}}}}}if(f){let h=f.cParamName;return fp(h,_,s,o,e,t,c,f)}}let p=n.functions[r.funcId]?.cName;if(p){let f=r.specializedType??r.type,d=Ct(f);if(d.length===0&&r.specializedType){let y=Ct(r.type);y.length>0&&y.some(v=>v.fieldFunctionType.forallParameters&&v.fieldFunctionType.forallParameters.length>0)&&(d=y)}if(d.length>0){let{args:y,isHandlerInstallation:v}=xl(d,r,e,n);if(y.length>0){let T=l?`${l}, ${y.join(", ")}`:y.join(", ");return Nl(p,T,_,e,o,t,n,v)}}let h=r.isControlFunction||r.isModuleEffectMember||r.body?.$?.effectAnalysis?.hasEffects,g=!1;if(h){if(r.isControlFunction||r.isModuleEffectMember){let y=e.func?.$?.env??e.$?.env;if(y){let v=Xo(y,T=>T.isImplicit===!0&&ne(T.value?.[0])&&T.value[0].funcId===r.funcId);v>=0&&v>y.functionDeclarationFrameLevel&&y.frames[v]?.isBeginBlockFrame&&(g=!0)}}else if(r.specializedType){let y=Ct(r.type);if(y.length>0){let v=e.func?.$?.env??e.$?.env;if(v)for(let T of y){let $=Xo(v,C=>C.isImplicit===!0&&(C.name===T.implicitLabel||C.name===T.fieldLabel));if($>=0&&$>v.functionDeclarationFrameLevel&&v.frames[$]?.isBeginBlockFrame){g=!0;break}}}}}if(fe(_.return.type))return n.emitter.emitLine(`${t}${p}(${l});`),e.$?.deferredDropExpressions&&$t(e,t,n),h&&pp(t,n,g,e),"";{let y=e.$?.variableName;if(y){let v=r.specializedType?.return.type??_.return.type,T=e.$?.type,$=T&&Fe(T),C=v&&Fe(v),L;if($&&C){let V=r.body;if(V&&E(V,"begin")){let I=V.args;if(I.length>0){let U=I[I.length-1];Bt(U)&&(V=U)}}if(V&&Bt(V)&&V.$?.asyncStateMachineStructName){let I=V.$.asyncStateMachineStructName;L=`${I}*`,n.tempVarAsyncStructNames||(n.tempVarAsyncStructNames=new Map),n.tempVarAsyncStructNames.set(y,I)}else T&&M(T)&&T.resolvedConcreteType?L=z(T,n):L=z(v,n)}else L=z(v??T,n);let b=n;return b.declaredTempVars||(b.declaredTempVars=new Set),b.declaredTempVars.has(y)||(b.declaredTempVars.add(y),n.emitter.emitLine(`${t}${L} ${y} = ${p}(${l});`)),In(y,t,n),e.$?.deferredDropExpressions&&$t(e,t,n),h&&pp(t,n,g,e),y}else return`// Error: Regular function call returns ${z(r.specializedType?.return.type??_.return.type,n)} but no temp variable assigned`}}}else{let u=n.externFunctions[i.id];if(u){let _=u.cName;return e.$?.deferredDropExpressions&&$t(e,t,n),`${_}(${l})`}else{let _=O(e.func,t,n);if(r&&W(r.type)){let y=Ct(r.type);if(y.length>0){let{args:v,isHandlerInstallation:T}=xl(y,r,e,n);if(v.length>0){let $=l?`${l}, ${v.join(", ")}`:v.join(", ");return Nl(_,$,i,e,o,t,n,T)}}}let c=e.$?.type??i.return.type,p=z(c,n),f=i.parameters.filter(y=>!y.isCompileTimeOnly).map(y=>z(y.type,n)),d=`((${p} (*)(${f.join(", ")}))${_})`,h=n,g=_.includes("__capture.")&&!!h.inAsyncStateMachine;if(g&&n.emitter.emitLine(`${t}__yo_effect_escaped = 0;`),fe(i.return.type)||fe(c)){if(n.emitter.emitLine(`${t}${d}(${l});`),e.$?.deferredDropExpressions&&$t(e,t,n),g){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let y of o)if(y.$?.variableName&&y.$?.type&&Ne(y.$.type)){let v=cp(ie(y.$.variableName),n),T=Or(v,y.$.type,n);T&&(n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} memset(&${v}, 0, sizeof(${v}));`))}}On({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return""}else{let y=e.$?.variableName;if(y){let v=i.return.type,T=e.$?.type,$=T&&v&&Fe(T)&&Fe(v)?v:T??v,C=n;if(C.declaredTempVars||(C.declaredTempVars=new Set),C.declaredTempVars.has(y)||(C.declaredTempVars.add(y),n.emitter.emitLine(`${t}${z($,n)} ${y} = ${d}(${l});`)),In(y,t,n),e.$?.deferredDropExpressions&&$t(e,t,n),g){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let L of o)if(L.$?.variableName&&L.$?.type&&Ne(L.$.type)){let b=cp(ie(L.$.variableName),n),V=Or(b,L.$.type,n);V&&(n.emitter.emitLine(`${t} ${V};`),n.emitter.emitLine(`${t} memset(&${b}, 0, sizeof(${b}));`))}}On({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return y}else return`// Error: Function parameter call returns ${z(i.return.type,n)} but no temp variable assigned`}}}}}else if(i&&Ht(i)){let o=i,a=on(o),s=Ie(o);{let l=a.isFn.callType,u=e.$?.runtimeArgExprsInOrder;if(u){let _=n;for(let h of u)if(h.$?.variableName&&h.$?.type){let g=_.currentClosureCaptures&&_.currentClosureCaptures.includes(h.$.variableName)&&B(h)&&h.$.env&&_.currentClosureCaptureFrameLevel!==void 0&&wr(h.token.value,h.$.env,_.currentClosureCaptureFrameLevel),y=O(h,t,n),v=!1;if(B(h)&&h.$.env&&h.$.variableName){let $=j(h.$.env,h.$.variableName);$.length>0&&$[$.length-1].isCompileTimeOnly&&(v=!0)}let T=(_.inAsyncStateMachine||_.inEffectStateMachine)&&y.startsWith("sm->");if(y&&y!==h.$.variableName&&!g&&!T&&!v){let $=h.$.convertedRuntimeType||h.$.type,C=ut($,h.$.variableName,n);n.emitter.emitLine(`${t}${C} = ${y};`),In(h.$.variableName,t,n)}}let c=O(e.func,t,n),p=u.map(h=>{if(h.$?.variableName&&h.$?.type){if(_.currentClosureCaptures&&_.currentClosureCaptures.includes(h.$.variableName)&&B(h)&&h.$.env&&_.currentClosureCaptureFrameLevel!==void 0&&wr(h.token.value,h.$.env,_.currentClosureCaptureFrameLevel))return O(h,t,n);{let y=ve(h.$.variableName,h.$.env),v=(_.inAsyncStateMachine||_.inEffectStateMachine)&&y.startsWith("sm->"),T=y;if(h.$?.deferredDupExpressions&&h.$.deferredDupExpressions.length>0){ot(h,t,_);let $=h.$.deferredDupExpressions[0];F($)&&$.$?.variableName&&(T=ve($.$.variableName,$.$.env))}return v?y:T}}else return O(h,t,n)}),f;if(s){let h=[`(${c}).data`,...p];f=`(${c}).vtable->call(${h.join(", ")})`}else{let h;if(M(o)){let y=o;y.resolvedConcreteType&&(h=y.resolvedConcreteType.id)}let g=h?n.implClosureCallMap.get(h):void 0;if(g){let y=Ct(l);if(y.length>0){let{args:T,isHandlerInstallation:$}=xl(y,{},e,_);if(T.length>0){let C=[`&(${c})`,...p,...T];return Nl(g.functionCName,C.join(", "),l,e,u,t,_,$)}}let v=[`&(${c})`,...p];f=`${g.functionCName}(${v.join(", ")})`}else{let y=[`(${c}).data`,...p];f=`(${c}).call(${y.join(", ")})`}}let d=l.return.type;if(fe(d))return n.emitter.emitLine(`${t}${f};`),e.$?.deferredDropExpressions&&$t(e,t,n),"";{let h=e.$?.variableName;return h?(n.emitter.emitLine(`${t}${z(d,n)} ${h} = ${f};`),In(h,t,n),e.$?.deferredDropExpressions&&$t(e,t,n),h):`// Error: Closure call returns ${z(d,n)} but no temp variable assigned`}}else return"// Error: No runtime args found for closure call"}}else if(P(r))if(pe(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=o.fields.map(_=>_.label),u=e.$?.variableName;if(a&&s&&l.length===a.length){if(o.isNewtype&&o.fields.length===1){let _=a[0],c=O(_,t,n),p=c;if(_.$?.deferredDupExpressions&&_.$.deferredDupExpressions.length>0){let d=n;if(_.$?.variableName&&_.$?.type){let g=ve(_.$.variableName,_.$.env);if(c!==g){let y=_.$.type,v=z(y,n);n.emitter.emitLine(`${t}${v} ${g} = ${c};`)}}ot(_,t,d);let h=_.$.deferredDupExpressions[0];F(h)&&h.$?.variableName&&(p=ve(h.$.variableName,h.$.env))}let f=`((${s})(${p}))`;if(u&&e.$?.type){let d=ut(e.$.type,u,n);return n.emitter.emitLine(`${t}${d} = ${f};`),In(u,t,n),u}else return f}if(o.isReferenceSemantics){let _=n,c=a.map(d=>{let h=O(d,t,n);if(d.$?.deferredDupExpressions&&d.$.deferredDupExpressions.length>0){if(d.$?.variableName&&d.$?.type){let y=ve(d.$.variableName,d.$.env);if(h!==y){let v=d.$.type,T=z(v,n);n.emitter.emitLine(`${t}${T} ${y} = ${h};`)}}ot(d,t,_);let g=d.$.deferredDupExpressions[0];if(F(g)&&g.$?.variableName)return ve(g.$.variableName,g.$.env)}return h}).join(", "),f=`${`__yo_new_${s}`}(${c})`;if(u&&e.$?.type){let d=ut(e.$.type,u,n);return n.emitter.emitLine(`${t}${d} = ${f};`),In(u,t,n),u}else return f}else{let _=n,c=a.map((f,d)=>{let h=O(f,t,n),g=xe(o)?`_${d}`:ie(l[d],o.isExtern==="c"),y=h;if(f.$?.deferredDupExpressions&&f.$.deferredDupExpressions.length>0){if(f.$?.variableName&&f.$?.type){let T=ve(f.$.variableName,f.$.env),$=f.$.type,C=z($,n);h!==T&&n.emitter.emitLine(`${t}${C} ${T} = ${h};`)}ot(f,t,_);let v=f.$.deferredDupExpressions[0];F(v)&&v.$?.variableName&&(y=ve(v.$.variableName,v.$.env))}return`.${g} = `+y}).join(", "),p=`(${s}){ ${c} }`;if(u&&e.$?.type){let f=ut(e.$.type,u,n);return n.emitter.emitLine(`${t}${f} = ${p};`),In(u,t,n),u}else return p}}}else{if(Ht(r.value))return"// Error: Closure construction should have been handled by closureFunctionValue check at top of generateFuncCall";if(nt(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&&B(s)&&l){let _=n,c=s.token.value,p=ve(c,s.$?.env),d=O(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){ot(l,t,_);let g=l.$.deferredDupExpressions[0];F(g)&&g.$?.variableName&&(d=ve(g.$.variableName,g.$.env))}let h=`(${u}){ .${p} = ${d} }`;if(o&&e.$?.type){let g=ut(e.$.type,o,n);return n.emitter.emitLine(`${t}${g} = ${h};`),In(o,t,n),o}else return h}}}else if(Te(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=e.$?.variableName;if(o.selectedVariantName&&a&&s){if(Kt(o)){let f=o.selectedVariantName,d=o.variants.find(h=>h.name===f);if(d){if(!d.fields||d.fields.length===0){let h="NULL";if(l&&e.$?.type){let g=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${g} = ${h};`),In(l,t,n),l}else return h}else if(d.fields.length===1){let h=O(a[0],t,n);if(l&&e.$?.type){let g=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${g} = ${h};`),In(l,t,n),l}else return h}}}if(Vn(o)){let f=o.selectedVariantName,d=Yt(o,f,n);if(l&&e.$?.type){let h=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${h} = ${d};`),In(l,t,n),l}else return d}let c=o.selectedVariantName,p=o.variants.find(f=>f.name===c);if(p){let f=p.fields?.filter(y=>!fe(y.type))||[],d=n,h=a.map((y,v)=>{if(p.fields){let T=p.fields[v];if(T&&!fe(T.type)){let $=O(y,t,n),C=ve(T.label,y.$?.env),L=$;if(y.$?.variableName&&y.$?.type){let b=d.currentClosureCaptures&&d.currentClosureCaptures.includes(y.$.variableName)&&B(y)&&y.$.env&&d.currentClosureCaptureFrameLevel!==void 0&&wr(y.token.value,y.$.env,d.currentClosureCaptureFrameLevel),V=(d.inAsyncStateMachine||d.inEffectStateMachine)&&$.startsWith("sm->"),I=!1;if(B(y)&&y.$.env&&y.$.variableName){let D=j(y.$.env,y.$.variableName);D.length>0&&D[D.length-1].isCompileTimeOnly&&(I=!0)}let U=!1;if($&&$!==y.$.variableName&&!b&&!V&&!I){let D=ve(y.$.variableName,y.$.env);if($!==D){let x=ut(y.$.type,y.$.variableName,n);n.emitter.emitLine(`${t}${x} = ${$};`),U=!0,In(y.$.variableName,t,n)}}U&&(L=ve(y.$.variableName,y.$.env))}if(y.$?.deferredDupExpressions&&y.$.deferredDupExpressions.length>0){ot(y,t,d);let b=y.$.deferredDupExpressions[0];F(b)&&b.$?.variableName&&(L=ve(b.$.variableName,b.$.env))}return`.${C} = `+L}return""}else return""}).filter(y=>y).join(", "),g=f.length>0?`(${s}){ .tag = ${Yt(o,c,n)}, .data = { .${c} = { ${h} } } }`:`(${s}){ .tag = ${Yt(o,c,n)} }`;if(l&&e.$?.type){let y=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${y} = ${g};`),In(l,t,n),l}else return g}}}}else if(ke(i)){let o=e.args[0];if(o&&F(o)&&(E(o,"..")||E(o,"..="))){let l=E(o,"..="),u=O(e.func,t,n),_=O(o.args[0],t,n),c=O(o.args[1],t,n),p=`Slice_${ie(z(i.childType,n))}`;return n.sliceStructTypes.has(p)||n.sliceStructTypes.set(p,{childType:z(i.childType,n)}),l?`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) + 1 }`:`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) }`}let a=O(e.func,t,n),s=O(o,t,n);return`${a}.data[${s}]`}else if(qe(i)){let o=e.args[0];if(o&&F(o)&&(E(o,"..")||E(o,"..="))){let l=E(o,"..="),u=O(e.func,t,n),_=O(o.args[0],t,n),c=O(o.args[1],t,n),p=`Slice_${ie(z(i.childType,n))}`;return n.sliceStructTypes.has(p)||n.sliceStructTypes.set(p,{childType:z(i.childType,n)}),l?`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) + 1 }`:`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) }`}let a=O(e.func,t,n),s=O(o,t,n);return`${a}.data[${s}]`}else if(i&&Ce(i)&&qe(i.childType)){let o=O(e.func,t,n),a=O(e.args[0],t,n);return`${o}.data[${a}]`}}function pp(e,t,n,r){let i=t.emitter;if(i.emitLine(`${e}if (__yo_effect_escaped) {`),t.inAsyncStateMachine||(fn(e+" ",t,r,!1,!0,!1),Qn(e+" ",t,r)),t.inAsyncStateMachine)n&&i.emitLine(`${e} __yo_effect_escaped = 0;`),On({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&&!fe(o)){let a=z(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&&!fe(o)){let a=z(o,t);a!=="void"?i.emitLine(`${e} return (${a}){0};`):i.emitLine(`${e} return;`)}else i.emitLine(`${e} return;`)}i.emitLine(`${e}}`)}function fp(e,t,n,r,i,o,a,s){let l=n.join(", "),u=t.return.type,_=a.emitter,c,p=!1;if(s?.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0){let f=s.fieldFunctionType.return.type;p=M(f);let d=p?"void":i.$?.type?z(i.$.type,a):z(u,a),h=[],y=s.fieldFunctionType.parameters.filter(T=>!T.isCompileTimeOnly);for(let T=0;T<y.length;T++){let $=y[T].type,C=M($)&&r?.[T]?.$?.type?r[T].$.type:$,L=W(C)?kr(C,"(*)",a):z(C,a);h.push(L)}let v=h.join(", ");c=`((${d} (*)(${v}))${e})`}else c=e;if(fe(u)){if(_.emitLine(`${o}${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let f=a.currentFunctionType?.return.type;if(f&&!fe(f)){let d=z(f,a);d!=="void"?_.emitLine(`${o} return (${d}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),""}else{let f=i.$?.variableName;if(f){let d=s?.fieldFunctionType.forallParameters?.length&&i.$?.type?i.$.type:u,h=z(d,a);if(h==="void"||fe(d)){if(_.emitLine(`${o}${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!fe(g)){let y=z(g,a);y!=="void"?_.emitLine(`${o} return (${y}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),""}if(p){if(_.emitLine(`${o}${h} ${f} = (${h}){0};`),_.emitLine(`${o}${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!fe(g)){let y=z(g,a);y!=="void"?_.emitLine(`${o} return (${y}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),In(f,o,a),f}if(_.emitLine(`${o}${h} ${f} = ${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!fe(g)){let y=z(g,a);y!=="void"?_.emitLine(`${o} return (${y}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),f}else return`${c}(${l})`}}function xl(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 _=r.currentEvidenceParams.get(l);_&&(i.push(_.cParamName),u=!0)}if(!u){if(o){if(o.effectHandlerInfos)for(let _ of o.effectHandlerInfos){if(_.effectParameterName!==s.fieldLabel&&_.effectParameterName!==s.implicitLabel)continue;let c=_.handlerValue;if(c&&ne(c)){if(c.specializedFunctionCaches?.length){let f=c.specializedFunctionCaches[0].specializedFunction,d=r.functions[f.funcId]?.cName;if(d){i.push(`(void*)${d}`),u=!0,a=!0;break}}let p=r.functions[c.funcId]?.cName;if(p){i.push(p),u=!0,a=!0;break}}}if(!u&&o.handlerValue&&e.length===1){let _=o.handlerValue;if(_&&ne(_)){if(_.specializedFunctionCaches?.length){let c=_.specializedFunctionCaches[0].specializedFunction,p=r.functions[c.funcId]?.cName;p&&(i.push(`(void*)${p}`),u=!0,a=!0)}if(!u){let c=r.functions[_.funcId]?.cName;c&&(i.push(c),u=!0,a=!0)}}}}if(!u){let _=n.func.$?.env??n.$?.env;if(_){let c=j(_,s.implicitLabel),p=hn(_,y=>y.isImplicit===!0&&W(y.type)&&W(s.fieldFunctionType)&&y.type===s.fieldFunctionType),f=c[c.length-1],d=p[p.length-1],g=(d&&d!==f?d:f??d)?.value?.[0];if(g&&We(g)){let y=g,v=!0;for(let T=0;T<s.fieldPath.length-1;T++){let $=s.fieldPath[T],C=y.type.fields.findIndex(L=>L.label===$);if(C>=0&&y.fields[C]&&We(y.fields[C]))y=y.fields[C];else{v=!1;break}}if(v){let T=s.fieldPath[s.fieldPath.length-1],$=y.type.fields.findIndex(C=>C.label===T);if($>=0){let C=y.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(g&&ne(g)){if(g.specializedFunctionCaches?.length){let y=g.specializedFunctionCaches[0].specializedFunction,v=r.functions[y.funcId]?.cName;v&&(i.push(`(void*)${v}`),u=!0)}if(!u){let y=r.functions[g.funcId]?.cName;y&&(i.push(y),u=!0)}}u&&(a=!0)}}if(!u&&r.stateMachineVariables){let _=s.fieldPath[s.fieldPath.length-1];for(let[,c]of r.stateMachineVariables)if(c.name===_&&c.kind==="outer"){i.push(`sm->__capture.${_}`),u=!0;break}}if(!u)break}}return{args:i,isHandlerInstallation:a}}function Nl(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;`),fe(u)){if(l.emitLine(`${o}${e}(${t});`),r.$?.deferredDropExpressions&&$t(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,r,!1,!0,!1),Qn(o+" ",a,r)),a.inAsyncStateMachine)On({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let _=a.currentFunctionType?.return.type;if(s&&l.emitLine(`${o} __yo_effect_escaped = 0;`),_&&!fe(_))if(s){let c=z(_,a);c!=="void"?(l.emitLine(`${o} ${c} _esc_result;`),l.emitLine(`${o} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${c}));`),l.emitLine(`${o} return _esc_result;`)):l.emitLine(`${o} return;`)}else{let c=z(_,a);c!=="void"?l.emitLine(`${o} return (${c}){0};`):l.emitLine(`${o} return;`)}else l.emitLine(`${o} return;`)}return l.emitLine(`${o}}`),""}else{let _=r.$?.variableName;if(_){let c=z(u,a);if(l.emitLine(`${o}${c} ${_} = ${e}(${t});`),In(_,o,a),r.$?.deferredDropExpressions&&$t(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,r,!1,!0,!1),Qn(o+" ",a,r)),a.inAsyncStateMachine)On({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let p=a.currentFunctionType?.return.type;if(s&&p&&!fe(p)){let f=z(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&&!fe(p)){let f=z(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}}`),_}else return`${e}(${t})`}}function mp(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&&Le(a.$.value)){let s=a.$.value.value;r.emitLine(`${t}fprintf(stderr, "%s\\n", ${JSON.stringify(s)});`),r.emitLine(`${t}abort();`)}else{let s=O(a,t,n),l=a.$?.type;l&&pe(l)&&wn(l)&&l.typeName==="str"?r.emitLine(`${t}fprintf(stderr, "%.*s\\n", (int)${s}.length, ${s}.data);`):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`(*((${z(i,n)}*)NULL))`}var Hg={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"}},jg={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"},Kg={e:"k",x:"w",l:"b",h:"h",w:"w"};function Xg(e,t){if(!e)return"r";if(e.startsWith("raw:"))return e.slice(4);let n=jg[e];if(n)return n;let r=Hg[e];return r?r[t]??r.x86_64??"r":e}function Qg(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?Kg[l]??l:void 0,_=parseInt(s,10);isNaN(_)?u?n+=`%${u}[${s}]`:n+=`%[${s}]`:u?n+=`%${u}${_}`:n+=`%${_}`,r=i+1}else e[r]==="}"&&r+1<e.length&&e[r+1]==="}"?(n+="}",r+=2):(n+=e[r],r++);return n}function Zg(e,t,n,r){let i=e.args,o=n.targetInfo.arch;if(r==="const_val"){let y,v=0;i.length===2&&i[0].$?.value&&Le(i[0].$.value)&&(y=i[0].$.value.value,v=1);let T=O(i[v],t,n);return{kind:"const_val",name:y,constraint:"",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}if(r==="sym"){let y,v=0;i.length===2&&i[0].$?.value&&Le(i[0].$.value)&&(y=i[0].$.value.value,v=1);let T=O(i[v],t,n);return{kind:"sym",name:y,constraint:"i",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}let a,s=0;if(i.length>=2){let y=i[0];y.$?.value&&Le(y.$.value)&&!(y.tag==="Atom"&&yp(y.token.value))&&(a=y.$.value.value,s=1)}let l=s<i.length-1,u,_;l?(u=Jg(i[s],t,n),_=s+1):(a!==void 0&&(u=a),_=s);let c=Xg(u,o),p=i[_];if(p.tag==="Atom"&&p.token.value==="_")return{kind:r,name:a,constraint:c,cExpr:"",cType:"int32_t",isDiscarded:!0,isVariableTarget:!1};if(p.$?.value&&P(p.$.value)){let y=p.$.value.value,v=z(y,n);return{kind:r,name:a,constraint:c,cExpr:"",cType:v,isDiscarded:!1,isVariableTarget:!1}}let f=O(p,t,n),d=z(p.$?.type,n),g=(r==="out"||r==="lateout")&&p.tag==="Atom";return{kind:r,name:a,constraint:c,cExpr:f,cType:d,isDiscarded:!1,isVariableTarget:g}}function yp(e){return["reg","reg_byte","reg_abcd","xmm_reg","ymm_reg","imm","mem"].includes(e)}function Jg(e,t,n){if(e.tag==="Atom"&&yp(e.token.value))return e.token.value;if(e.$?.value&&Le(e.$.value))return e.$.value.value;if(E(e,"raw",1)){let r=e;if(r.args[0].$?.value&&Le(r.args[0].$.value))return`raw:${r.args[0].$.value.value}`}return"r"}function eh(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&&Le(i.$.value)?n.push(i.$.value.value):i.tag==="Atom"&&n.push(i.token.value);return n}function th(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 Vl=0;function gp(e,t,n){let r=n.emitter,i=e.$?.type;if(!i)return"/* Error: asm() missing type information */";if(Xn(n.targetInfo))return r.emitLine(`${t}/* Error: inline assembly is not supported on WebAssembly */`),r.emitLine(`${t}abort();`),`(*((${z(i,n)}*)NULL))`;let o=[],a=0;for(;a<e.args.length;){let D=e.args[a];if(F(D))break;if(D.$?.value&&Le(D.$.value))o.push(D.$.value.value),a++;else break}let s=o.join(`
11086
- `),l=[],u=[],_={isVolatile:!0,intelSyntax:!1,noreturn:!1,pure:!1};for(;a<e.args.length;){let D=e.args[a];if(!F(D)){a++;continue}let x=D.func.tag==="Atom"?D.func.token.value:void 0;if(!x){a++;continue}["in","out","inout","lateout","inlateout","const_val","sym"].includes(x)?l.push(Zg(D,t,n,x)):x==="clobber"||x==="clobber_abi"?u.push(...eh(D,n)):x==="asm_options"&&(_=th(D)),a++}let c=new Map;for(let D=0;D<l.length;D++)l[D].name&&c.set(l[D].name,D);let p=s;for(let D=0;D<l.length;D++){let x=l[D];x.kind==="const_val"&&(x.name&&(p=p.replace(new RegExp(`\\{${x.name}(?::[^}]*)?\\}`,"g"),x.cExpr)),p=p.replace(new RegExp(`\\{${D}(?::[^}]*)?\\}`,"g"),x.cExpr))}let f=Qg(p,c),d=[],h=[],g=[];for(let D=0;D<l.length;D++){let x=l[D];if(x.isDiscarded){let R=`__asm_discard_${Vl++}`;g.push({varName:R,cType:x.cType,operandIdx:D}),r.emitLine(`${t}${x.cType} ${R};`)}else if(x.kind==="out"||x.kind==="lateout"){if(!x.isVariableTarget){if(x.cType){let R=`__asm_out_${Vl++}`;d.push({varName:R,cType:x.cType,operandIdx:D}),r.emitLine(`${t}${x.cType} ${R};`)}}}else if(x.kind==="inout"||x.kind==="inlateout"){let R=`__asm_inout_${Vl++}`;h.push({varName:R,cType:x.cType,initExpr:x.cExpr,operandIdx:D}),r.emitLine(`${t}${x.cType} ${R} = ${x.cExpr};`)}}let y=_.isVolatile?" __volatile__":"",v=f;_.intelSyntax&&(n.needsIntelAsmSyntax=!0);let T=JSON.stringify(v),$=[];for(let D=0;D<l.length;D++){let x=l[D];if(x.kind==="in"||x.kind==="const_val"||x.kind==="sym")continue;let R;x.kind==="out"||x.kind==="lateout"?R=x.kind==="lateout"?"=&":"=":R=x.kind==="inlateout"?"+&":"+";let Q=`${R}${x.constraint}`,J=x.name?`[${x.name}] `:"",G;x.isDiscarded?G=g.find(oe=>oe.operandIdx===D).varName:x.isVariableTarget?G=x.cExpr:x.kind==="out"||x.kind==="lateout"?G=d.find(oe=>oe.operandIdx===D).varName:G=h.find(oe=>oe.operandIdx===D).varName,$.push(`${J}"${Q}" (${G})`)}let C=[];for(let D=0;D<l.length;D++){let x=l[D];if(x.kind!=="in"&&x.kind!=="sym")continue;let R=x.constraint,Q=x.name?`[${x.name}] `:"";C.push(`${Q}"${R}" (${x.cExpr})`)}let L=u.map(D=>`"${D}"`),b=$.join(", "),V=C.join(", "),I=L.join(", ");if(r.emitLine(`${t}__asm__${y} (`),r.emitLine(`${t} ${T}`),r.emitLine(`${t} : ${b}`),r.emitLine(`${t} : ${V}`),r.emitLine(`${t} : ${I}`),r.emitLine(`${t});`),_.noreturn)return r.emitLine(`${t}__builtin_unreachable();`),`(*((${z(i,n)}*)NULL))`;if(fe(i))return"";let U=[];for(let D=0;D<l.length;D++){let x=l[D];if(!(x.isDiscarded||x.isVariableTarget)&&!(x.kind==="in"||x.kind==="const_val"||x.kind==="sym"))if(x.kind==="out"||x.kind==="lateout"){let R=d.find(Q=>Q.operandIdx===D);R&&U.push(R.varName)}else{let R=h.find(Q=>Q.operandIdx===D);R&&U.push(R.varName)}}if(U.length===1)return U[0];if(U.length>1){let D=z(i,n),x=U.map((R,Q)=>`._${Q} = ${R}`).join(", ");return`((${D}){ ${x} })`}return""}function hp(e,t,n){if(Xn(n.targetInfo))return"/* global_asm skipped: not supported on this target */";let r=e.args[0];if(r.$?.value&&Le(r.$.value)){let i=r.$.value.value;n.emitter.emitDeclarationLine(`__asm__(${JSON.stringify(i)});`)}return""}function vp(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=O(r,t,n),a=r.$?.type,s=r.$?.value;if(B(i)){let l=i.token.value,u=n;if(u.currentEvidenceParams&&B(r)){let c=`${r.token.value}.${l}`,p=u.currentEvidenceParams.get(c);if(p)return p.cParamName}if(e.$?.value&&ne(e.$.value)){let _=e.$.value;return n.functions[_.funcId]?.cName||_.funcId}if(!e.$?.value&&(k.___dispose.includes(l)||k.___drop.includes(l)||k.___dup.includes(l))&&a){let _=null;if((pe(a)||Te(a))&&(_=a.trait),_){let c=_.fields.find(p=>p.label===l&&p.assignedValue&&ne(p.assignedValue));if(c&&ne(c.assignedValue)){let p=c.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($e(a)||We(s)){let _=e.$?.value;if(_){if(ce(_)){if(_.variableName)return ve(_.variableName,e.$?.env);if((u.inAsyncStateMachine||u.inEffectStateMachine)&&u.stateMachineVariables){for(let[,c]of u.stateMachineVariables)if(c.name===l&&c.kind==="outer")return`sm->__capture.${l}`}}else if(!We(_))return en(_,n,e)}return ve(l,e.$?.env)}if(wn(a)&&a.fields.length===1){let _=a.fields[0];if(_&&_.label===l)return o}if(Te(a)){let _=a;if(Kt(_))return o;for(let p of _.variants)if(p.fields){for(let f of p.fields)if(f.label===l){let d=p.name;return`${o}.data.${d}.${ie(l)}`}}return`/* ERROR: field ${l} not found in enum ${_.typeName} */`}else if(P(s)&&Te(s.value)){let _=s.value,c=_.variants.find(f=>f.name===l),p=n.types[_.id]?.cName;if(c&&!c.fields&&p){let f=Yt(_,c.name,n);return`(${p}){ .tag = ${f}, .data = { } }`}}else{if(bt(a)&&l==="*")return`${o}->value`;if(Ce(a)){if(l==="*")return`(*${o})`;if(qe(a.childType))return`${o}->${ie(l)}`;{let _=0,c=a;for(;Ce(c);)_++,c=c.childType;if(_>0&&pe(c)&&c.isReferenceSemantics&&_++,wn(c)&&c.fields.length===1){let p=c.fields[0];if(p&&p.label===l)return _===1?`(*${o})`:`${"*".repeat(_)}(${o})`}return _>0?_===1?`${o}->${ie(l)}`:`${`(${"*".repeat(_-1)}${o})`}->${ie(l)}`:`${o}.${ie(l)}`}}else if(xe(a)){if(l.match(/^\d+$/))return`${o}._${l}`;{let _=a.fields.findIndex(c=>c.label===l);return`${o}._${_}`}}else return Ie(a)?`${o}.vtable->${ie(l)}`:ft(a)?`${o}->${ie(l)}`:`${o}.${ie(l)}`}}return"/* ERROR: field name must be an identifier */"}var nh=0;function Tp(e,t,n){if(!e.$?.type)return`// Error: No type information for pointer/reference expression ${w(e)}
11087
- `;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,"..")||E(u,"..="))){let _=E(u,"..="),c=O(i.func,t,n),p=O(u.args[0],t,n),f=O(u.args[1],t,n),d=`Slice_${ie(z(l.childType,n))}`;return n.sliceStructTypes.has(d)||n.sliceStructTypes.set(d,{childType:z(l.childType,n)}),_?`(${d}){ .data = &${c}.data[${p}], .length = (${f}) - (${p}) + 1 }`:`(${d}){ .data = &${c}.data[${p}], .length = (${f}) - (${p}) }`}}else if(l&&(qe(l)||Ce(l)&&qe(l.childType))){let u=qe(l)?l:l.childType,_=i.args[0];if(_&&F(_)&&(E(_,"..")||E(_,"..="))){let c=E(_,"..="),p=O(i.func,t,n),f=O(_.args[0],t,n),d=O(_.args[1],t,n),h=`Slice_${ie(z(u.childType,n))}`;return n.sliceStructTypes.has(h)||n.sliceStructTypes.set(h,{childType:z(u.childType,n)}),c?`(${h}){ .data = &${p}.data[${f}], .length = (${d}) - (${f}) + 1 }`:`(${h}){ .data = &${p}.data[${f}], .length = (${d}) - (${f}) }`}}}let o=i.$?.value,a=i.$?.type;if(o!==void 0&&a){if(He(o)||Be(o)){let l=O(i,t,n);return`(&(${z(a,n)}){${l}})`}if(Le(o)&&i.$?.convertedRuntimeType)return`(&${O(i,t,n)})`}if(e.$?.isIndexTraitAddressOf&&F(i)&&i.$?.indexMethodValue){let l=i.$.indexMethodValue;if(ne(l)){let u=i.func,_=O(u,t,n);if(F(u)&&!B(u)&&!E(u,".")&&u.$?.type&&!(u.$?.variableName&&_===ve(u.$.variableName,u.$.env))){let g=z(u.$.type,n),y=`__yo_ptr_idx_tmp_${nh++}`;n.emitter.emitLine(`${t}${g} ${y} = ${_};`),_=y}let c=i.args[0],p=c?O(c,t,n):"0",f=Cr(l);if(f&&(k.__yo_array_index.includes(f)||k.__yo_slice_index.includes(f)))return`(&((&${_})->data[${p}]))`;let d=n.functions[l.funcId]?.cName;if(d)return`${d}(&${_}, ${p})`}}return`(&${O(i,t,n)})`}function Ep(e,t,n){let r=e.args[0];return r?`__yo_decr_rc(${O(r,t,n)})`:"// Error: __yo_decr_rc requires exactly 1 argument"}function $p(e,t,n){let r=e.args[0];return r?`__yo_incr_rc(${O(r,t,n)})`:"// Error: __yo_incr_rc requires exactly 1 argument"}function Cp(e,t,n){let r=e.args[0];return r?O(r,t,n):"// Error: __yo_rc_own requires exactly 1 argument"}function bp(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=O(r,t,n),a=O(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=M(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let c=u.length;if(!He(c))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} < ${c.value}; ${p}++) {`);let d=`(${o}).data[${a}].data[${p}]`;f.emitLine(" { // drop nested array element");let h=Or(d,u.childType,n);return h&&f.emitLine(` ${h};`),f.emitLine(" }"),f.emitLine("}"),""}let _=br(u,n);return _?`${_}((${o}).data[${a}])`:"// No drop function for array element type"}function kp(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=O(r,t,n),a=O(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=M(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let c=u.length;if(!He(c))return"// Error: array element has non-constant length";let p=`temp_array_${Math.floor(Math.random()*1e6)}`,f=`i_${Math.floor(Math.random()*1e6)}`,d=z(u,n),h=n.emitter;h.emitLine(`${d} ${p} = (${o}).data[${a}];`),h.emitLine(`for (size_t ${f} = 0; ${f} < ${c.value}; ${f}++) {`);let g=no(`${p}.data[${f}]`,u.childType,n);return h.emitLine(` ${p}.data[${f}] = ${g};`),h.emitLine("}"),p}let _=Dn(u,n);return _?`${_}((${o}).data[${a}])`:"// No dup function for array element type"}function wp(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=O(r,t,n);O(i,t,n);let a=r.$?.type;if(!a||!xe(a))return"// Error: __yo_drop_tuple_element requires a tuple type";let s=i.$?.value;if(!He(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,_=M(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(xe(_)){let p=`(${o})._${l}`;return Or(p,_,n)}let c=br(_,n);return c?`${c}((${o})._${l})`:"// No drop function for tuple element type"}function Fp(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=O(r,t,n);O(i,t,n);let a=r.$?.type;if(!a||!xe(a))return"// Error: __yo_dup_tuple_element requires a tuple type";let s=i.$?.value;if(!He(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,_=M(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(xe(_)){let p=`(${o})._${l}`;return no(p,_,n)}let c=Dn(_,n);return c?`${c}((${o})._${l})`:"// No dup function for tuple element type"}function Lp(e,t,n){let r=e.args[0];if(!r)return"// Error: ___dup requires exactly 1 argument";let i=O(r,t,n),o=r.$?.type??e.$?.type;return o?no(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=O(r,t,n),o=r.$?.type??e.$?.type;return o?Or(i,o,n):""}function Ip(e,t,n){let r=e.args[0];return r?`__yo_decr_rc((void*)(${O(r,t,n)}).data)`:"// Error: __yo_dyn_drop requires exactly 1 argument"}function Sp(e,t,n){let r=e.args[0];return r?`__yo_incr_rc((void*)(${O(r,t,n)}).data)`:"// Error: __yo_dyn_dup requires exactly 1 argument"}function xp(e,t,n){let r=e.args[0];return r?`__yo_incr_rc_atomic(${O(r,t,n)})`:"// Error: __yo_incr_rc_atomic requires exactly 1 argument"}function Np(e,t,n){let r=e.args[0];return r?`__yo_decr_rc_atomic(${O(r,t,n)})`:"// Error: __yo_decr_rc_atomic requires exactly 1 argument"}function Vp(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&&M(i)&&Fe(i)){let o=O(r,t,n);return`if (${o} != NULL) { __yo_decr_rc((void*)${o}); }`}if(i&&M(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=O(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_drop: no-op */"}function Dp(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&&M(i)&&Fe(i))return`__yo_incr_rc((void*)${O(r,t,n)})`;if(i&&M(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=O(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_dup: no-op */"}function Mp(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=O(r,t,n);return un(i)?`((__yo_ref_header_t*)(${o}))->ref_count`:"1"}function Op(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(r){let i=n,o=r.map(a=>{let s=O(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){ot(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return ve(l.$.variableName,l.$.env)}return s}).join(", ");return`${n.currentFunctionName}(${o})`}else return`// Error: No arguments for recur call ${w(e)}
11088
- `}function Rp(e,t,n){let r=e.args[0];return`sizeof(${O(r,t,n)})`}function Pp(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 c=O(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){ot(l,t,a);let p=l.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(c=ve(p.$.variableName,p.$.env))}return`._${u} = ${c}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=ut(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 _=O(l,t,n);return`._${u} = ${_}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=ut(e.$.type,o,n);return n.emitter.emitLine(`${t}${u} = ${l};`),o}else return`(${i}){ ${s} }`}}}function zp(e,t,n){let i=e.args[0].$?.value;if(!i||!P(i))throw new Error("typeid codegen: expected TypeValue argument");let o=i.value,a=o.id,s=n.types[a]?.cName||z(o,n),l=`__yo_typeid_${ie(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 rh(e,t){if(F(e)&&E(e,S.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=O(i,"",t),s=O(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=O(n,"",t),o=O(r,"",t);return`${i} = ${o}`}return O(e,"",t)}function Dl(e,t,n){if(F(e)&&E(e,S.begin)){let r=n,i=r.pendingDeferredDrops,o=e.$?.deferredDropExpressions??[],a=new Map;for(let _ of o){let c=An(_);c&&a.set(c,_)}r.pendingDeferredDrops=[...i??[]];let s=r.consumedVarPendingDrops,l=e.$?.consumedVariableDropExpressions??[];r.consumedVarPendingDrops=[...l,...s??[]];let u=new Set;for(let _ of e.args){let c=O(_,t,n);if(c&&n.emitter.emitLine(`${t}${c};`),_.$?.env&&a.size>u.size)for(let p of _.$.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 _ of e.$.deferredDropExpressions){let c=O(_,t,n);c&&n.emitter.emitLine(`${t}${c};`)}r.pendingDeferredDrops=i,r.consumedVarPendingDrops=s}else{let r=O(e,t,n);r&&n.emitter.emitLine(`${t}${r};`)}}function Up(e,t,n){if(e.$?.comptimeUnrolledBodies){for(let i of e.$.comptimeUnrolledBodies)Dl(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 _=O(i,t+" ",n);return n.emitter.emitLine(`${t} if (!(${_})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),Dl(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)}`,_=`continue_${Math.random().toString(36).substr(2,9)}`;n.currentLoopLabel=u,n.currentContinueLabel=_;let c=n,p=c.loopBodyDropsBaselineCount;c.loopBodyDropsBaselineCount=c.pendingDeferredDrops?.length??0,n.emitter.emitLine(`${t}while (true) {`);let f=O(i,t+" ",n);n.emitter.emitLine(`${t} if (!(${f})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),Dl(a,t+" ",n),n.emitter.emitLine(`${t}${_}:;`);let d=rh(o,n);return n.emitter.emitLine(`${t} ${d};`),n.emitter.emitLine(`${t}}`),n.emitter.emitLine(`${t}${u}:;`),c.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} */`),""}var ih=0;function oh(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;M(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),at(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function ah(e,t,n){let r=e.$?.indexMethodValue;if(!r||!ne(r))return"/* Error: Index trait method value missing */";let i=e.func,o=O(i,t,n);if(F(i)&&!B(i)&&!E(i,".")&&i.$?.type&&!(i.$?.variableName&&o===ve(i.$.variableName,i.$.env))){let c=z(i.$.type,n),p=`__yo_idx_tmp_${ih++}`;n.emitter.emitLine(`${t}${c} ${p} = ${o};`),o=p}let a=e.args[0],s=a?O(a,t,n):"0",l,u=Cr(r);if(u)if(k.__yo_array_index.includes(u)||k.__yo_slice_index.includes(u))l=`(&((&${o})->data[${s}]))`;else if((k.__yo_array_index_range.includes(u)||k.__yo_slice_index_range.includes(u))&&e.$?.indexTraitPtrType&&Ce(e.$.indexTraitPtrType))l=`(&(${z(e.$.indexTraitPtrType.childType,n)}){ .data = &((&${o})->data[(${s}).start]), .length = (${s}).end - (${s}).start })`;else if((k.__yo_array_index_range_inclusive.includes(u)||k.__yo_slice_index_range_inclusive.includes(u))&&e.$?.indexTraitPtrType&&Ce(e.$.indexTraitPtrType))l=`(&(${z(e.$.indexTraitPtrType.childType,n)}){ .data = &((&${o})->data[(${s}).start]), .length = (${s}).end - (${s}).start + 1 })`;else{let _=n.functions[r.funcId]?.cName;if(!_)return`/* Error: Index method ${r.funcId} not found in function registry */`;l=`${_}(&${o}, ${s})`}else{let _=n.functions[r.funcId]?.cName;if(!_)return`/* Error: Index method ${r.funcId} not found in function registry */`;l=`${_}(&${o}, ${s})`}return e.$?.isIndexTraitAddressOf?l:`(*${l})`}function sh(e,t,n,r){let i=e.args[0];if(!i?.$?.type)return;let o=e.args.find(c=>F(c)&&E(c,S.using));if(!o)return;let a=Rt(i.$.type);if(!a?.isFuture.effects?.length)return;let s=oh(a.isFuture.effects),l=o.args,u=r,_=u.emitter;for(let c=0;c<s.length&&c<l.length;c++){let p=s[c],f=l[c];if(W(p.type)){let d=p.label,h;if(u.currentEvidenceParams){for(let g of u.currentEvidenceParams.values())if(g.fieldLabel===d){h=g.cParamName;break}}if(!h&&u.stateMachineVariables){for(let[,g]of u.stateMachineVariables)if(g.name===d&&g.kind==="outer"){h=`sm->__capture.${d}`;break}}if(!h){let g=f.$?.value;if(g&&ne(g)){let y=r.functions[g.funcId];y&&(h=y.cName)}}h||(h=O(f,n,r)),h&&_.emitLine(`${n} ${t}->__capture.${d} = (void*)${h};`)}else if($e(p.type)){let d=p.type;for(let h of d.fields){if(!W(h.type))continue;let g;if(u.stateMachineVariables){for(let[,y]of u.stateMachineVariables)if(y.name===h.label&&y.kind==="outer"){g=`sm->__capture.${h.label}`;break}}if(!g){let y=f.$?.value;if(y&&We(y)){let v=d.fields.indexOf(h),T=y.fields[v];if(T&&ne(T)){let $=r.functions[T.funcId];$&&(g=$.cName)}}}if(!g&&u.currentEvidenceParams){for(let y of u.currentEvidenceParams.values())if(y.fieldLabel===h.label){g=y.cParamName;break}}g||(g=lh(h.label,d,u,e)),g&&_.emitLine(`${n} ${t}->__capture.${h.label} = (void*)${g};`)}}}}function lh(e,t,n,r){let i=r.$?.env??r.func.$?.env;if(!i)return;let o=hn(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(_=>_.label===e);if(u>=0){let _=l.fields[u];if(_&&ne(_)){let c=n.functions[_.funcId]?.cName;if(c)return c}}}}}function uh(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=O(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=O(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 fn(t,r,e,!1,!0,!0),Qn(t,r,e,!0),On({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(fn(t,r,e,!1,!0,!0),Qn(t,r,e,!0),r.currentFunctionType){let l=r.currentFunctionType.return.type;if(!fe(l)){let u=r.overrideReturnTypeStr??z(l,n);if(u!=="void")return`return (${u}){0}`}}return"return"}let s=O(i,t,n);if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);if(fn(t,r,e,!1,!0,!0),Qn(t,r,e,!0),(r.isModuleEffectMemberFunction||r.currentEvidenceParams&&r.currentEvidenceParams.size>0)&&r.currentFunctionType){let l=i.$?.type;if(l&&!fe(l)){let _=z(l,n);r.emitter.emitLine(`${t}{ ${_} _esc_val = ${s}; memcpy(__yo_effect_escape_value, &_esc_val, sizeof(${_})); }`)}let u=r.currentFunctionType.return.type;if(!fe(u)){let _=r.overrideReturnTypeStr??z(u,n);if(_!=="void")return`return (${_}){0}`}return"return"}return`return ${s}`}function Bp(e,t,n){let r;switch(e.tag){case"FnCall":r=_h(e,t,n);break;case"Atom":r=lo(e,n,t);break}return r}function _h(e,t,n){if(e.$?.macroExpansion)return O(e.$.macroExpansion,t,n);if(F(e.func)&&E(e.func,".",2)&&e.func.args[1]&&B(e.func.args[1])){let r=e.func.args[1].token.value,i=e.func.args[0],o=i?.$?.type;if(o&&M(o)&&Fe(o)){if(r===k.___drop[0]){let a=O(i,t,n);return`if (${a} != NULL) { __yo_decr_rc((void*)${a}); }`}if(r===k.___dup[0])return`__yo_incr_rc((void*)${O(i,t,n)})`}}if(H_(e))return j_(e,t,n);if(E(e,k.__yo_decr_rc))return Ep(e,t,n);if(E(e,k.__yo_incr_rc))return $p(e,t,n);if(E(e,k.__yo_rc_own))return Cp(e,t,n);if(E(e,k.__yo_drop_array_element))return bp(e,t,n);if(E(e,k.__yo_dup_array_element))return kp(e,t,n);if(E(e,k.__yo_drop_tuple_element))return wp(e,t,n);if(E(e,k.__yo_dup_tuple_element))return Fp(e,t,n);if(E(e,k.___dup))return Lp(e,t,n);if(E(e,k.___drop))return Ap(e,t,n);if(E(e,k.__yo_dyn_drop))return Ip(e,t,n);if(E(e,k.__yo_dyn_dup))return Sp(e,t,n);if(E(e,k.__yo_incr_rc_atomic))return xp(e,t,n);if(E(e,k.__yo_decr_rc_atomic))return Np(e,t,n);if(E(e,k.__yo_iso_extract))return tp(e,t,n);if(E(e,k.__yo_iso_dispose))return np(e,t,n);if(E(e,k.__yo_arc_dispose))return Oc(e,t,n);if(Il(e))return rp(e,t,n);if(Al(e))return Rc(e,t,n);if(E(e,k.__yo_sometype_drop))return Vp(e,t,n);if(E(e,k.__yo_sometype_dup))return Dp(e,t,n);if(E(e,k.__yo_gc_collect))return Jc(e,t,n);if(E(e,k.rc))return Mp(e,t,n);if(E(e,k.panic))return mp(e,t,n);if(E(e,k.asm))return gp(e,t,n);if(E(e,k.global_asm))return hp(e,t,n);if(E(e,S.test))return"/* test declaration skipped */";if(E(e,k.__yo_thread_set_maximum_threads))return _p(e,t,n);if(E(e,S.op_and))return Dc(e,t,n);if(E(e,S.op_or))return Mc(e,t,n);if(Bt(e))return e.$?.awaitAnalysis?K_(e,t,n):ec(e,t,n);if(E(e,S.dyn))return Zc(e,t,n);if(gn(e))return Gc(e,t,n);if(r_(e))return Wc(e,t,n);if(Na(e)){let r=e.args[0];if(!r)return"// Error: spawn requires a Future argument";let o=n.emitter,a=O(r,t,n),s=r.$?.type,l=s?z(s,n):"void*",u=e.$?.type,_=u?z(u,n):null,c=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} ${c} = ${a};`),o.emitLine(`${t}int ${p} = ${c}->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}}`),na(r.$?.type)||(o.emitLine(`${t}if (${p} == 0 && ${c}->__yo_resume_fn) {`),sh(e,c,t,n),o.emitLine(`${t} __yo_incr_rc((void*)${c});`),o.emitLine(`${t} ${c}->__yo_resume_fn((void*)${c});`),o.emitLine(`${t}}`)),_?`(${_}){ .__future = (void*)${c} }`:`(void*)${c}`}if(i_(e))return qc(e,t,n);if(E(e,S.return))return Tc(e,t,n);if(E(e,S.escape))return uh(e,t,n);if(E(e,k.__yo_array_fill,2))return zc(e,t,n);if(E(e,"::",2))return"";if(E(e,":",2))return jc(e,t,n);if(E(e,":=",2)){let r=ep(e,t,n);if(r!==void 0)return r}else{if(E(e,"=",2))return Uc(e,t,n);if(e.$?.value&&!ce(e.$?.value)&&!fe(e.$.type)&&!it(e.$?.controlFlow))return en(e.$.value,n,e);if(E(e,".",2))return vp(e,t,n);if(E(e,S.begin))return Hc(e,t,n);if(E(e,S.cond))return Kc(e,t,n);if(E(e,S.match))return op(e,t,n);if(E(e,k.__yo_address_of,1))return Tp(e,t,n);if(E(e,S.tuple))return Pp(e,t,n);if(E(e,S.array)){let r=Pc(e,t,n);if(r!==void 0)return r}else{if(E(e,S.recur))return Op(e,t,n);if(E(e,S.runtime,1))return O(e.args[0],t,n);if(E(e,k.sizeof,1))return Rp(e,t,n);if(E(e,k.typeid,1))return zp(e,t,n);if(E(e,k.downcast,2))return Qc(e,t,n);if(E(e,bi)){let r=e.$?.runtimeArgExprsInOrder||e.args;if(r){let i=n,o=r.map(a=>{let s=O(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){ot(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return ve(l.$.variableName,l.$.env)}return s});return oa(e.func.token.value,o,e,n,t)}}else{if(E(e,S.while))return Up(e,t,n);if(E(e,"->",2)&&F(e.args[0])&&E(e.args[0],S.fn)){let r=e.$?.value;return ne(r)?en(r,n):"// Error: Anonymous function missing function value"}else{if(E(e,k.consume))return Xc(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,S.open))return ap(e,t,n);if(e.$?.indexTraitPtrType&&e.$?.indexMethodType)return ah(e,t,n);{let r=dp(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 Gp({expr:e,env:t,context:n}){Ee(e,k.alignof,1);let r=e.args[0],i=N({expr:r,env:t,context:{...n}});if(!i.$)throw m({token:r.token,errorMessage:"Failed to evaluate expression."});t=i.$.env;let o;i.$.value&&P(i.$.value)?o=i.$.value.value:o=i.$.type;let a=tr(o),s;return a===null?s=X(Et(),{env:t,context:n}):s=Jt("Usize",a),e.$={env:t,type:Et(),value:s,pathCollection:[]},e}function Wp({expr:e,env:t,context:n}){let r=E(e,S.op_and)?"and":"or",i=e.args;if(i.length===0){let u=dt(r==="and");return e.$={env:t,type:et(),value:u,pathCollection:[],isAccessingProperty:!1},e}let o=t,a,s=!1,l=!1;for(let u=0;u<i.length;u++){let _=i[u],c=N({expr:_,env:o,context:{...n}});if(!c.$||!dn(c.$.type))throw m({token:_.token,errorMessage:`Expected bool type for "${r}" argument, got:
11085
+ `),s}function lp(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(M(o)){let g=o;g.resolvedConcreteType&&(a=g.resolvedConcreteType.id,s=g.resolvedConcreteType)}else pe(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,_=z(s,n),c=sp(u,l,n,e.$?.env.modulePath??""),p=O(i,t,n),f=i.$?.variableName?ve(i.$.variableName,i.$.env):p,d=`_thread_closure_data_${Pe(e.$?.env.modulePath??"")}`;n.emitter.emitLine(`${t}${_}* ${d} = (${_}*)__yo_malloc(sizeof(${_}));`),n.emitter.emitLine(`${t}*${d} = ${f};`);let h=e.$?.variableName;return h?(n.emitter.emitLine(`${t}__yo_thread_t ${h} = __yo_thread_spawn(${c}, ${d});`),h):`__yo_thread_spawn(${c}, ${d})`}function up(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(M(o)){let h=o;h.resolvedConcreteType&&(a=h.resolvedConcreteType.id,s=h.resolvedConcreteType)}else pe(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,_=z(s,n),c=sp(u,l,n,e.$?.env.modulePath??""),p=O(i,t,n),f=i.$?.variableName?ve(i.$.variableName,i.$.env):p,d=`_worker_closure_data_${Pe(e.$?.env.modulePath??"")}`;return n.emitter.emitLine(`${t}${_}* ${d} = (${_}*)__yo_malloc(sizeof(${_}));`),n.emitter.emitLine(`${t}*${d} = ${f};`),n.emitter.emitLine(`${t}__yo_worker_spawn(${c}, ${d});`),""}function _p(e,t,n){let r=e.args[0];return r?`__yo_thread_set_maximum_threads(${O(r,t,n)})`:"// Error: __yo_thread_set_maximum_threads requires exactly 1 argument"}function cp(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 In(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&&Fe(i.type))return;let o=`var_${i.id}`,a=re(e);n.emitter.emitLine(`${t}sm->${o} = ${a};`)}}function dp(e,t,n){if(e.$?.value!==void 0&&!ce(e.$.value))return e.$?.deferredDropExpressions&&$t(e,t,n),fe(e.$.type)?"":en(e.$.value,n,e);let r=e.func.$?.value,i=e.func.$?.type??(ne(r)?r.specializedType??r.type:void 0);if(W(i)){let o=e.$?.runtimeArgExprsInOrder;if(o){let a=!1;if(F(e.func)&&E(e.func,".",2)){let _=e.func.args[0]?.$?.type;_&&Ie(_)&&(a=!0)}let s=o.map((u,_)=>{if(u.$?.variableName&&u.$?.type){let c=n,p=c.currentClosureCaptures&&c.currentClosureCaptures.includes(u.$.variableName)&&B(u)&&u.$.env&&c.currentClosureCaptureFrameLevel!==void 0&&wr(u.token.value,u.$.env,c.currentClosureCaptureFrameLevel),f=O(u,t,n),d=!1;if(B(u)&&u.$.env&&u.$.variableName){let v=j(u.$.env,u.$.variableName);v.length>0&&v[v.length-1].isCompileTimeOnly&&(d=!0)}let h=(c.inAsyncStateMachine||c.inEffectStateMachine)&&f.startsWith("sm->"),g=!1;if(f&&f!==u.$.variableName&&!p&&!h&&!d){let v=ve(u.$.variableName,u.$.env);if(f!==v){let T=u.$.convertedRuntimeType||u.$.type,$=ut(T,u.$.variableName,n);n.emitter.emitLine(`${t}${$} = ${f};`),g=!0,In(u.$.variableName,t,n)}}let y=g?u.$.variableName:f;if(u.$?.deferredDupExpressions&&u.$.deferredDupExpressions.length>0){let v=new Set;u.$?.variableName&&v.add(ve(u.$.variableName,u.$.env)),f&&v.add(f),B(u)&&v.add(ve(u.token.value,u.$.env));let T=u.$.deferredDupExpressions.find($=>{let C=qa($);return C?v.has(ve(C,$.$?.env)):!1});T&&(ot(u,t,c),F(T)&&T.$?.variableName&&(y=ve(T.$.variableName,T.$.env)))}if(a&&_===0){if(F(e.func)&&E(e.func,".",2)){let $=e.func.args[0]?.$?.type,C=e.func.args[1];if(B(C)&&Ie($)){let L=C.token.value;if($.trait.fields.find(V=>V.label===L))return h?f:re(y,u.$.type.isExtern==="c")}}let v=u.$?.type;return v&&Ce(v)?h?`${f}->data`:`${re(y,u.$.type.isExtern==="c")}->data`:h?`(${f}).data`:`(${re(y,u.$.type.isExtern==="c")}).data`}else return p||h||d?f:re(y,u.$.type.isExtern==="c")}else if(a&&_===0){let c=O(u,t,n);if(F(e.func)&&E(e.func,".",2)){let d=e.func.args[0]?.$?.type,h=e.func.args[1];if(B(h)&&Ie(d)){let g=h.token.value;if(d.trait.fields.find(v=>v.label===g))return c}}let p=u.$?.type;return p&&Ce(p)?`(${c})->data`:`(${c}).data`}else return O(u,t,n)}),l=s.join(", ");if(i.isExtern==="yo"&&i.externName){let u=i.externName;return bi.includes(u)?oa(u,s,e,n,t):u==="__yo_thread_spawn"?lp(e,t,n):u==="__yo_worker_spawn"?up(e,t,n):fe(i.return.type)?(n.emitter.emitLine(`${t}${u}(${l});`),e.$?.deferredDropExpressions&&$t(e,t,n),""):`${u}(${l})`}{let u=n;if(u.currentEvidenceParams?.size){let _=e.func.token?.value,c;if(_==="."&&F(e.func)&&E(e.func,".",2)){let p=e.func.args[1];p&&B(p)&&(_=p.token.value);let f=e.func.args[0];if(f&&B(f))c=f.token.value;else if(f&&F(f)&&E(f,".",2)){let d=f.args[0];d&&B(d)&&(c=d.token.value)}}if(_&&_!=="."){for(let p of u.currentEvidenceParams.values())if(p.fieldLabel===_||p.implicitLabel===_||p.fieldPath[p.fieldPath.length-1]===_){if(c&&c!==p.implicitLabel)continue;return fp(p.cParamName,i,s,o,e,t,u,p)}}}}if(ne(r)){let u=Cr(r);if(u)return oa(u,s,e,n,t);let _=r.specializedType??r.type,c=n;if(c.currentEvidenceParams&&r.isModuleEffectMember){let f,d=e.func.$?.env??e.$?.env;if(d)for(let h of c.currentEvidenceParams.values()){let g=j(d,h.implicitLabel),v=g[g.length-1]?.value?.[0];if(v&&We(v)){let T=v,$=!0;for(let C=0;C<h.fieldPath.length-1;C++){let L=h.fieldPath[C],b=T.type.fields.findIndex(V=>V.label===L);if(b>=0&&T.fields[b]&&We(T.fields[b]))T=T.fields[b];else{$=!1;break}}if($){let C=h.fieldPath[h.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=h;break}}}}}if(f){let h=f.cParamName;return fp(h,_,s,o,e,t,c,f)}}let p=n.functions[r.funcId]?.cName;if(p){let f=r.specializedType??r.type,d=Ct(f);if(d.length===0&&r.specializedType){let y=Ct(r.type);y.length>0&&y.some(v=>v.fieldFunctionType.forallParameters&&v.fieldFunctionType.forallParameters.length>0)&&(d=y)}if(d.length>0){let{args:y,isHandlerInstallation:v}=xl(d,r,e,n);if(y.length>0){let T=l?`${l}, ${y.join(", ")}`:y.join(", ");return Nl(p,T,_,e,o,t,n,v)}}let h=r.isControlFunction||r.isModuleEffectMember||r.body?.$?.effectAnalysis?.hasEffects,g=!1;if(h){if(r.isControlFunction||r.isModuleEffectMember){let y=e.func?.$?.env??e.$?.env;if(y){let v=Xo(y,T=>T.isImplicit===!0&&ne(T.value?.[0])&&T.value[0].funcId===r.funcId);v>=0&&v>y.functionDeclarationFrameLevel&&y.frames[v]?.isBeginBlockFrame&&(g=!0)}}else if(r.specializedType){let y=Ct(r.type);if(y.length>0){let v=e.func?.$?.env??e.$?.env;if(v)for(let T of y){let $=Xo(v,C=>C.isImplicit===!0&&(C.name===T.implicitLabel||C.name===T.fieldLabel));if($>=0&&$>v.functionDeclarationFrameLevel&&v.frames[$]?.isBeginBlockFrame){g=!0;break}}}}}if(fe(_.return.type))return n.emitter.emitLine(`${t}${p}(${l});`),e.$?.deferredDropExpressions&&$t(e,t,n),h&&pp(t,n,g,e),"";{let y=e.$?.variableName;if(y){let v=r.specializedType?.return.type??_.return.type,T=e.$?.type,$=T&&Fe(T),C=v&&Fe(v),L;if($&&C){let V=r.body;if(V&&E(V,"begin")){let I=V.args;if(I.length>0){let U=I[I.length-1];Bt(U)&&(V=U)}}if(V&&Bt(V)&&V.$?.asyncStateMachineStructName){let I=V.$.asyncStateMachineStructName;L=`${I}*`,n.tempVarAsyncStructNames||(n.tempVarAsyncStructNames=new Map),n.tempVarAsyncStructNames.set(y,I)}else T&&M(T)&&T.resolvedConcreteType?L=z(T,n):L=z(v,n)}else L=z(v??T,n);let b=n;return b.declaredTempVars||(b.declaredTempVars=new Set),b.declaredTempVars.has(y)||(b.declaredTempVars.add(y),n.emitter.emitLine(`${t}${L} ${y} = ${p}(${l});`)),In(y,t,n),e.$?.deferredDropExpressions&&$t(e,t,n),h&&pp(t,n,g,e),y}else return`// Error: Regular function call returns ${z(r.specializedType?.return.type??_.return.type,n)} but no temp variable assigned`}}}else{let u=n.externFunctions[i.id];if(u){let _=u.cName;return e.$?.deferredDropExpressions&&$t(e,t,n),`${_}(${l})`}else{let _=O(e.func,t,n);if(r&&W(r.type)){let y=Ct(r.type);if(y.length>0){let{args:v,isHandlerInstallation:T}=xl(y,r,e,n);if(v.length>0){let $=l?`${l}, ${v.join(", ")}`:v.join(", ");return Nl(_,$,i,e,o,t,n,T)}}}let c=e.$?.type??i.return.type,p=z(c,n),f=i.parameters.filter(y=>!y.isCompileTimeOnly).map(y=>z(y.type,n)),d=`((${p} (*)(${f.join(", ")}))${_})`,h=n,g=_.includes("__capture.")&&!!h.inAsyncStateMachine;if(g&&n.emitter.emitLine(`${t}__yo_effect_escaped = 0;`),fe(i.return.type)||fe(c)){if(n.emitter.emitLine(`${t}${d}(${l});`),e.$?.deferredDropExpressions&&$t(e,t,n),g){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let y of o)if(y.$?.variableName&&y.$?.type&&Ne(y.$.type)){let v=cp(re(y.$.variableName),n),T=Or(v,y.$.type,n);T&&(n.emitter.emitLine(`${t} ${T};`),n.emitter.emitLine(`${t} memset(&${v}, 0, sizeof(${v}));`))}}On({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return""}else{let y=e.$?.variableName;if(y){let v=i.return.type,T=e.$?.type,$=T&&v&&Fe(T)&&Fe(v)?v:T??v,C=n;if(C.declaredTempVars||(C.declaredTempVars=new Set),C.declaredTempVars.has(y)||(C.declaredTempVars.add(y),n.emitter.emitLine(`${t}${z($,n)} ${y} = ${d}(${l});`)),In(y,t,n),e.$?.deferredDropExpressions&&$t(e,t,n),g){if(n.emitter.emitLine(`${t}if (__yo_effect_escaped) {`),o){for(let L of o)if(L.$?.variableName&&L.$?.type&&Ne(L.$.type)){let b=cp(re(L.$.variableName),n),V=Or(b,L.$.type,n);V&&(n.emitter.emitLine(`${t} ${V};`),n.emitter.emitLine(`${t} memset(&${b}, 0, sizeof(${b}));`))}}On({emitter:n.emitter,indent:t+" ",resultCode:void 0,debugLabel:void 0}),n.emitter.emitLine(`${t}}`)}return y}else return`// Error: Function parameter call returns ${z(i.return.type,n)} but no temp variable assigned`}}}}}else if(i&&Ht(i)){let o=i,a=on(o),s=Ie(o);{let l=a.isFn.callType,u=e.$?.runtimeArgExprsInOrder;if(u){let _=n;for(let h of u)if(h.$?.variableName&&h.$?.type){let g=_.currentClosureCaptures&&_.currentClosureCaptures.includes(h.$.variableName)&&B(h)&&h.$.env&&_.currentClosureCaptureFrameLevel!==void 0&&wr(h.token.value,h.$.env,_.currentClosureCaptureFrameLevel),y=O(h,t,n),v=!1;if(B(h)&&h.$.env&&h.$.variableName){let $=j(h.$.env,h.$.variableName);$.length>0&&$[$.length-1].isCompileTimeOnly&&(v=!0)}let T=(_.inAsyncStateMachine||_.inEffectStateMachine)&&y.startsWith("sm->");if(y&&y!==h.$.variableName&&!g&&!T&&!v){let $=h.$.convertedRuntimeType||h.$.type,C=ut($,h.$.variableName,n);n.emitter.emitLine(`${t}${C} = ${y};`),In(h.$.variableName,t,n)}}let c=O(e.func,t,n),p=u.map(h=>{if(h.$?.variableName&&h.$?.type){if(_.currentClosureCaptures&&_.currentClosureCaptures.includes(h.$.variableName)&&B(h)&&h.$.env&&_.currentClosureCaptureFrameLevel!==void 0&&wr(h.token.value,h.$.env,_.currentClosureCaptureFrameLevel))return O(h,t,n);{let y=ve(h.$.variableName,h.$.env),v=(_.inAsyncStateMachine||_.inEffectStateMachine)&&y.startsWith("sm->"),T=y;if(h.$?.deferredDupExpressions&&h.$.deferredDupExpressions.length>0){ot(h,t,_);let $=h.$.deferredDupExpressions[0];F($)&&$.$?.variableName&&(T=ve($.$.variableName,$.$.env))}return v?y:T}}else return O(h,t,n)}),f;if(s){let h=[`(${c}).data`,...p];f=`(${c}).vtable->call(${h.join(", ")})`}else{let h;if(M(o)){let y=o;y.resolvedConcreteType&&(h=y.resolvedConcreteType.id)}let g=h?n.implClosureCallMap.get(h):void 0;if(g){let y=Ct(l);if(y.length>0){let{args:T,isHandlerInstallation:$}=xl(y,{},e,_);if(T.length>0){let C=[`&(${c})`,...p,...T];return Nl(g.functionCName,C.join(", "),l,e,u,t,_,$)}}let v=[`&(${c})`,...p];f=`${g.functionCName}(${v.join(", ")})`}else{let y=[`(${c}).data`,...p];f=`(${c}).call(${y.join(", ")})`}}let d=l.return.type;if(fe(d))return n.emitter.emitLine(`${t}${f};`),e.$?.deferredDropExpressions&&$t(e,t,n),"";{let h=e.$?.variableName;return h?(n.emitter.emitLine(`${t}${z(d,n)} ${h} = ${f};`),In(h,t,n),e.$?.deferredDropExpressions&&$t(e,t,n),h):`// Error: Closure call returns ${z(d,n)} but no temp variable assigned`}}else return"// Error: No runtime args found for closure call"}}else if(P(r))if(pe(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=o.fields.map(_=>_.label),u=e.$?.variableName;if(a&&s&&l.length===a.length){if(o.isNewtype&&o.fields.length===1){let _=a[0],c=O(_,t,n),p=c;if(_.$?.deferredDupExpressions&&_.$.deferredDupExpressions.length>0){let d=n;if(_.$?.variableName&&_.$?.type){let g=ve(_.$.variableName,_.$.env);if(c!==g){let y=_.$.type,v=z(y,n);n.emitter.emitLine(`${t}${v} ${g} = ${c};`)}}ot(_,t,d);let h=_.$.deferredDupExpressions[0];F(h)&&h.$?.variableName&&(p=ve(h.$.variableName,h.$.env))}let f=`((${s})(${p}))`;if(u&&e.$?.type){let d=ut(e.$.type,u,n);return n.emitter.emitLine(`${t}${d} = ${f};`),In(u,t,n),u}else return f}if(o.isReferenceSemantics){let _=n,c=a.map(d=>{let h=O(d,t,n);if(d.$?.deferredDupExpressions&&d.$.deferredDupExpressions.length>0){if(d.$?.variableName&&d.$?.type){let y=ve(d.$.variableName,d.$.env);if(h!==y){let v=d.$.type,T=z(v,n);n.emitter.emitLine(`${t}${T} ${y} = ${h};`)}}ot(d,t,_);let g=d.$.deferredDupExpressions[0];if(F(g)&&g.$?.variableName)return ve(g.$.variableName,g.$.env)}return h}).join(", "),f=`${`__yo_new_${s}`}(${c})`;if(u&&e.$?.type){let d=ut(e.$.type,u,n);return n.emitter.emitLine(`${t}${d} = ${f};`),In(u,t,n),u}else return f}else{let _=n,c=a.map((f,d)=>{let h=O(f,t,n),g=xe(o)?`_${d}`:re(l[d],o.isExtern==="c"),y=h;if(f.$?.deferredDupExpressions&&f.$.deferredDupExpressions.length>0){if(f.$?.variableName&&f.$?.type){let T=ve(f.$.variableName,f.$.env),$=f.$.type,C=z($,n);h!==T&&n.emitter.emitLine(`${t}${C} ${T} = ${h};`)}ot(f,t,_);let v=f.$.deferredDupExpressions[0];F(v)&&v.$?.variableName&&(y=ve(v.$.variableName,v.$.env))}return`.${g} = `+y}).join(", "),p=`(${s}){ ${c} }`;if(u&&e.$?.type){let f=ut(e.$.type,u,n);return n.emitter.emitLine(`${t}${f} = ${p};`),In(u,t,n),u}else return p}}}else{if(Ht(r.value))return"// Error: Closure construction should have been handled by closureFunctionValue check at top of generateFuncCall";if(nt(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&&B(s)&&l){let _=n,c=s.token.value,p=ve(c,s.$?.env),d=O(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){ot(l,t,_);let g=l.$.deferredDupExpressions[0];F(g)&&g.$?.variableName&&(d=ve(g.$.variableName,g.$.env))}let h=`(${u}){ .${p} = ${d} }`;if(o&&e.$?.type){let g=ut(e.$.type,o,n);return n.emitter.emitLine(`${t}${g} = ${h};`),In(o,t,n),o}else return h}}}else if(Te(r.value)){let o=r.value,a=e.$?.runtimeArgExprsInOrder,s=n.types[o.id]?.cName,l=e.$?.variableName;if(o.selectedVariantName&&a&&s){if(Kt(o)){let f=o.selectedVariantName,d=o.variants.find(h=>h.name===f);if(d){if(!d.fields||d.fields.length===0){let h="NULL";if(l&&e.$?.type){let g=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${g} = ${h};`),In(l,t,n),l}else return h}else if(d.fields.length===1){let h=O(a[0],t,n);if(l&&e.$?.type){let g=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${g} = ${h};`),In(l,t,n),l}else return h}}}if(Vn(o)){let f=o.selectedVariantName,d=Yt(o,f,n);if(l&&e.$?.type){let h=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${h} = ${d};`),In(l,t,n),l}else return d}let c=o.selectedVariantName,p=o.variants.find(f=>f.name===c);if(p){let f=p.fields?.filter(y=>!fe(y.type))||[],d=n,h=a.map((y,v)=>{if(p.fields){let T=p.fields[v];if(T&&!fe(T.type)){let $=O(y,t,n),C=ve(T.label,y.$?.env),L=$;if(y.$?.variableName&&y.$?.type){let b=d.currentClosureCaptures&&d.currentClosureCaptures.includes(y.$.variableName)&&B(y)&&y.$.env&&d.currentClosureCaptureFrameLevel!==void 0&&wr(y.token.value,y.$.env,d.currentClosureCaptureFrameLevel),V=(d.inAsyncStateMachine||d.inEffectStateMachine)&&$.startsWith("sm->"),I=!1;if(B(y)&&y.$.env&&y.$.variableName){let D=j(y.$.env,y.$.variableName);D.length>0&&D[D.length-1].isCompileTimeOnly&&(I=!0)}let U=!1;if($&&$!==y.$.variableName&&!b&&!V&&!I){let D=ve(y.$.variableName,y.$.env);if($!==D){let x=ut(y.$.type,y.$.variableName,n);n.emitter.emitLine(`${t}${x} = ${$};`),U=!0,In(y.$.variableName,t,n)}}U&&(L=ve(y.$.variableName,y.$.env))}if(y.$?.deferredDupExpressions&&y.$.deferredDupExpressions.length>0){ot(y,t,d);let b=y.$.deferredDupExpressions[0];F(b)&&b.$?.variableName&&(L=ve(b.$.variableName,b.$.env))}return`.${C} = `+L}return""}else return""}).filter(y=>y).join(", "),g=f.length>0?`(${s}){ .tag = ${Yt(o,c,n)}, .data = { .${c} = { ${h} } } }`:`(${s}){ .tag = ${Yt(o,c,n)} }`;if(l&&e.$?.type){let y=ut(e.$.type,l,n);return n.emitter.emitLine(`${t}${y} = ${g};`),In(l,t,n),l}else return g}}}}else if(ke(i)){let o=e.args[0];if(o&&F(o)&&(E(o,"..")||E(o,"..="))){let l=E(o,"..="),u=O(e.func,t,n),_=O(o.args[0],t,n),c=O(o.args[1],t,n),p=`Slice_${re(z(i.childType,n))}`;return n.sliceStructTypes.has(p)||n.sliceStructTypes.set(p,{childType:z(i.childType,n)}),l?`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) + 1 }`:`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) }`}let a=O(e.func,t,n),s=O(o,t,n);return`${a}.data[${s}]`}else if(qe(i)){let o=e.args[0];if(o&&F(o)&&(E(o,"..")||E(o,"..="))){let l=E(o,"..="),u=O(e.func,t,n),_=O(o.args[0],t,n),c=O(o.args[1],t,n),p=`Slice_${re(z(i.childType,n))}`;return n.sliceStructTypes.has(p)||n.sliceStructTypes.set(p,{childType:z(i.childType,n)}),l?`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) + 1 }`:`(${p}){ .data = &${u}.data[${_}], .length = (${c}) - (${_}) }`}let a=O(e.func,t,n),s=O(o,t,n);return`${a}.data[${s}]`}else if(i&&Ce(i)&&qe(i.childType)){let o=O(e.func,t,n),a=O(e.args[0],t,n);return`${o}.data[${a}]`}}function pp(e,t,n,r){let i=t.emitter;if(i.emitLine(`${e}if (__yo_effect_escaped) {`),t.inAsyncStateMachine||(fn(e+" ",t,r,!1,!0,!1),Qn(e+" ",t,r)),t.inAsyncStateMachine)n&&i.emitLine(`${e} __yo_effect_escaped = 0;`),On({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&&!fe(o)){let a=z(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&&!fe(o)){let a=z(o,t);a!=="void"?i.emitLine(`${e} return (${a}){0};`):i.emitLine(`${e} return;`)}else i.emitLine(`${e} return;`)}i.emitLine(`${e}}`)}function fp(e,t,n,r,i,o,a,s){let l=n.join(", "),u=t.return.type,_=a.emitter,c,p=!1;if(s?.fieldFunctionType.forallParameters&&s.fieldFunctionType.forallParameters.length>0){let f=s.fieldFunctionType.return.type;p=M(f);let d=p?"void":i.$?.type?z(i.$.type,a):z(u,a),h=[],y=s.fieldFunctionType.parameters.filter(T=>!T.isCompileTimeOnly);for(let T=0;T<y.length;T++){let $=y[T].type,C=M($)&&r?.[T]?.$?.type?r[T].$.type:$,L=W(C)?kr(C,"(*)",a):z(C,a);h.push(L)}let v=h.join(", ");c=`((${d} (*)(${v}))${e})`}else c=e;if(fe(u)){if(_.emitLine(`${o}${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let f=a.currentFunctionType?.return.type;if(f&&!fe(f)){let d=z(f,a);d!=="void"?_.emitLine(`${o} return (${d}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),""}else{let f=i.$?.variableName;if(f){let d=s?.fieldFunctionType.forallParameters?.length&&i.$?.type?i.$.type:u,h=z(d,a);if(h==="void"||fe(d)){if(_.emitLine(`${o}${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!fe(g)){let y=z(g,a);y!=="void"?_.emitLine(`${o} return (${y}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),""}if(p){if(_.emitLine(`${o}${h} ${f} = (${h}){0};`),_.emitLine(`${o}${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!fe(g)){let y=z(g,a);y!=="void"?_.emitLine(`${o} return (${y}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),In(f,o,a),f}if(_.emitLine(`${o}${h} ${f} = ${c}(${l});`),i.$?.deferredDropExpressions&&$t(i,o,a),_.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,i,!1,!0,!1),Qn(o+" ",a,i)),a.inAsyncStateMachine)On({emitter:_,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let g=a.currentFunctionType?.return.type;if(g&&!fe(g)){let y=z(g,a);y!=="void"?_.emitLine(`${o} return (${y}){0};`):_.emitLine(`${o} return;`)}else _.emitLine(`${o} return;`)}return _.emitLine(`${o}}`),f}else return`${c}(${l})`}}function xl(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 _=r.currentEvidenceParams.get(l);_&&(i.push(_.cParamName),u=!0)}if(!u){if(o){if(o.effectHandlerInfos)for(let _ of o.effectHandlerInfos){if(_.effectParameterName!==s.fieldLabel&&_.effectParameterName!==s.implicitLabel)continue;let c=_.handlerValue;if(c&&ne(c)){if(c.specializedFunctionCaches?.length){let f=c.specializedFunctionCaches[0].specializedFunction,d=r.functions[f.funcId]?.cName;if(d){i.push(`(void*)${d}`),u=!0,a=!0;break}}let p=r.functions[c.funcId]?.cName;if(p){i.push(p),u=!0,a=!0;break}}}if(!u&&o.handlerValue&&e.length===1){let _=o.handlerValue;if(_&&ne(_)){if(_.specializedFunctionCaches?.length){let c=_.specializedFunctionCaches[0].specializedFunction,p=r.functions[c.funcId]?.cName;p&&(i.push(`(void*)${p}`),u=!0,a=!0)}if(!u){let c=r.functions[_.funcId]?.cName;c&&(i.push(c),u=!0,a=!0)}}}}if(!u){let _=n.func.$?.env??n.$?.env;if(_){let c=j(_,s.implicitLabel),p=hn(_,y=>y.isImplicit===!0&&W(y.type)&&W(s.fieldFunctionType)&&y.type===s.fieldFunctionType),f=c[c.length-1],d=p[p.length-1],g=(d&&d!==f?d:f??d)?.value?.[0];if(g&&We(g)){let y=g,v=!0;for(let T=0;T<s.fieldPath.length-1;T++){let $=s.fieldPath[T],C=y.type.fields.findIndex(L=>L.label===$);if(C>=0&&y.fields[C]&&We(y.fields[C]))y=y.fields[C];else{v=!1;break}}if(v){let T=s.fieldPath[s.fieldPath.length-1],$=y.type.fields.findIndex(C=>C.label===T);if($>=0){let C=y.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(g&&ne(g)){if(g.specializedFunctionCaches?.length){let y=g.specializedFunctionCaches[0].specializedFunction,v=r.functions[y.funcId]?.cName;v&&(i.push(`(void*)${v}`),u=!0)}if(!u){let y=r.functions[g.funcId]?.cName;y&&(i.push(y),u=!0)}}u&&(a=!0)}}if(!u&&r.stateMachineVariables){let _=s.fieldPath[s.fieldPath.length-1];for(let[,c]of r.stateMachineVariables)if(c.name===_&&c.kind==="outer"){i.push(`sm->__capture.${_}`),u=!0;break}}if(!u)break}}return{args:i,isHandlerInstallation:a}}function Nl(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;`),fe(u)){if(l.emitLine(`${o}${e}(${t});`),r.$?.deferredDropExpressions&&$t(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,r,!1,!0,!1),Qn(o+" ",a,r)),a.inAsyncStateMachine)On({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let _=a.currentFunctionType?.return.type;if(s&&l.emitLine(`${o} __yo_effect_escaped = 0;`),_&&!fe(_))if(s){let c=z(_,a);c!=="void"?(l.emitLine(`${o} ${c} _esc_result;`),l.emitLine(`${o} memcpy(&_esc_result, __yo_effect_escape_value, sizeof(${c}));`),l.emitLine(`${o} return _esc_result;`)):l.emitLine(`${o} return;`)}else{let c=z(_,a);c!=="void"?l.emitLine(`${o} return (${c}){0};`):l.emitLine(`${o} return;`)}else l.emitLine(`${o} return;`)}return l.emitLine(`${o}}`),""}else{let _=r.$?.variableName;if(_){let c=z(u,a);if(l.emitLine(`${o}${c} ${_} = ${e}(${t});`),In(_,o,a),r.$?.deferredDropExpressions&&$t(r,o,a),l.emitLine(`${o}if (__yo_effect_escaped) {`),a.inAsyncStateMachine||(fn(o+" ",a,r,!1,!0,!1),Qn(o+" ",a,r)),a.inAsyncStateMachine)On({emitter:l,indent:o+" ",resultCode:void 0,debugLabel:void 0});else{let p=a.currentFunctionType?.return.type;if(s&&p&&!fe(p)){let f=z(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&&!fe(p)){let f=z(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}}`),_}else return`${e}(${t})`}}function mp(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&&Le(a.$.value)){let s=a.$.value.value;r.emitLine(`${t}fprintf(stderr, "%s\\n", ${JSON.stringify(s)});`),r.emitLine(`${t}abort();`)}else{let s=O(a,t,n),l=a.$?.type;l&&pe(l)&&wn(l)&&l.typeName==="str"?r.emitLine(`${t}fprintf(stderr, "%.*s\\n", (int)${s}.length, ${s}.data);`):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`(*((${z(i,n)}*)NULL))`}var Hg={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"}},jg={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"},Kg={e:"k",x:"w",l:"b",h:"h",w:"w"};function Xg(e,t){if(!e)return"r";if(e.startsWith("raw:"))return e.slice(4);let n=jg[e];if(n)return n;let r=Hg[e];return r?r[t]??r.x86_64??"r":e}function Qg(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?Kg[l]??l:void 0,_=parseInt(s,10);isNaN(_)?u?n+=`%${u}[${s}]`:n+=`%[${s}]`:u?n+=`%${u}${_}`:n+=`%${_}`,r=i+1}else e[r]==="}"&&r+1<e.length&&e[r+1]==="}"?(n+="}",r+=2):(n+=e[r],r++);return n}function Zg(e,t,n,r){let i=e.args,o=n.targetInfo.arch;if(r==="const_val"){let y,v=0;i.length===2&&i[0].$?.value&&Le(i[0].$.value)&&(y=i[0].$.value.value,v=1);let T=O(i[v],t,n);return{kind:"const_val",name:y,constraint:"",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}if(r==="sym"){let y,v=0;i.length===2&&i[0].$?.value&&Le(i[0].$.value)&&(y=i[0].$.value.value,v=1);let T=O(i[v],t,n);return{kind:"sym",name:y,constraint:"i",cExpr:T,cType:"",isDiscarded:!1,isVariableTarget:!1}}let a,s=0;if(i.length>=2){let y=i[0];y.$?.value&&Le(y.$.value)&&!(y.tag==="Atom"&&yp(y.token.value))&&(a=y.$.value.value,s=1)}let l=s<i.length-1,u,_;l?(u=Jg(i[s],t,n),_=s+1):(a!==void 0&&(u=a),_=s);let c=Xg(u,o),p=i[_];if(p.tag==="Atom"&&p.token.value==="_")return{kind:r,name:a,constraint:c,cExpr:"",cType:"int32_t",isDiscarded:!0,isVariableTarget:!1};if(p.$?.value&&P(p.$.value)){let y=p.$.value.value,v=z(y,n);return{kind:r,name:a,constraint:c,cExpr:"",cType:v,isDiscarded:!1,isVariableTarget:!1}}let f=O(p,t,n),d=z(p.$?.type,n),g=(r==="out"||r==="lateout")&&p.tag==="Atom";return{kind:r,name:a,constraint:c,cExpr:f,cType:d,isDiscarded:!1,isVariableTarget:g}}function yp(e){return["reg","reg_byte","reg_abcd","xmm_reg","ymm_reg","imm","mem"].includes(e)}function Jg(e,t,n){if(e.tag==="Atom"&&yp(e.token.value))return e.token.value;if(e.$?.value&&Le(e.$.value))return e.$.value.value;if(E(e,"raw",1)){let r=e;if(r.args[0].$?.value&&Le(r.args[0].$.value))return`raw:${r.args[0].$.value.value}`}return"r"}function eh(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&&Le(i.$.value)?n.push(i.$.value.value):i.tag==="Atom"&&n.push(i.token.value);return n}function th(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 Vl=0;function gp(e,t,n){let r=n.emitter,i=e.$?.type;if(!i)return"/* Error: asm() missing type information */";if(Xn(n.targetInfo))return r.emitLine(`${t}/* Error: inline assembly is not supported on WebAssembly */`),r.emitLine(`${t}abort();`),`(*((${z(i,n)}*)NULL))`;let o=[],a=0;for(;a<e.args.length;){let D=e.args[a];if(F(D))break;if(D.$?.value&&Le(D.$.value))o.push(D.$.value.value),a++;else break}let s=o.join(`
11086
+ `),l=[],u=[],_={isVolatile:!0,intelSyntax:!1,noreturn:!1,pure:!1};for(;a<e.args.length;){let D=e.args[a];if(!F(D)){a++;continue}let x=D.func.tag==="Atom"?D.func.token.value:void 0;if(!x){a++;continue}["in","out","inout","lateout","inlateout","const_val","sym"].includes(x)?l.push(Zg(D,t,n,x)):x==="clobber"||x==="clobber_abi"?u.push(...eh(D,n)):x==="asm_options"&&(_=th(D)),a++}let c=new Map;for(let D=0;D<l.length;D++)l[D].name&&c.set(l[D].name,D);let p=s;for(let D=0;D<l.length;D++){let x=l[D];x.kind==="const_val"&&(x.name&&(p=p.replace(new RegExp(`\\{${x.name}(?::[^}]*)?\\}`,"g"),x.cExpr)),p=p.replace(new RegExp(`\\{${D}(?::[^}]*)?\\}`,"g"),x.cExpr))}let f=Qg(p,c),d=[],h=[],g=[];for(let D=0;D<l.length;D++){let x=l[D];if(x.isDiscarded){let R=`__asm_discard_${Vl++}`;g.push({varName:R,cType:x.cType,operandIdx:D}),r.emitLine(`${t}${x.cType} ${R};`)}else if(x.kind==="out"||x.kind==="lateout"){if(!x.isVariableTarget){if(x.cType){let R=`__asm_out_${Vl++}`;d.push({varName:R,cType:x.cType,operandIdx:D}),r.emitLine(`${t}${x.cType} ${R};`)}}}else if(x.kind==="inout"||x.kind==="inlateout"){let R=`__asm_inout_${Vl++}`;h.push({varName:R,cType:x.cType,initExpr:x.cExpr,operandIdx:D}),r.emitLine(`${t}${x.cType} ${R} = ${x.cExpr};`)}}let y=_.isVolatile?" __volatile__":"",v=f;_.intelSyntax&&(n.needsIntelAsmSyntax=!0);let T=JSON.stringify(v),$=[];for(let D=0;D<l.length;D++){let x=l[D];if(x.kind==="in"||x.kind==="const_val"||x.kind==="sym")continue;let R;x.kind==="out"||x.kind==="lateout"?R=x.kind==="lateout"?"=&":"=":R=x.kind==="inlateout"?"+&":"+";let Q=`${R}${x.constraint}`,J=x.name?`[${x.name}] `:"",G;x.isDiscarded?G=g.find(oe=>oe.operandIdx===D).varName:x.isVariableTarget?G=x.cExpr:x.kind==="out"||x.kind==="lateout"?G=d.find(oe=>oe.operandIdx===D).varName:G=h.find(oe=>oe.operandIdx===D).varName,$.push(`${J}"${Q}" (${G})`)}let C=[];for(let D=0;D<l.length;D++){let x=l[D];if(x.kind!=="in"&&x.kind!=="sym")continue;let R=x.constraint,Q=x.name?`[${x.name}] `:"";C.push(`${Q}"${R}" (${x.cExpr})`)}let L=u.map(D=>`"${D}"`),b=$.join(", "),V=C.join(", "),I=L.join(", ");if(r.emitLine(`${t}__asm__${y} (`),r.emitLine(`${t} ${T}`),r.emitLine(`${t} : ${b}`),r.emitLine(`${t} : ${V}`),r.emitLine(`${t} : ${I}`),r.emitLine(`${t});`),_.noreturn)return r.emitLine(`${t}__builtin_unreachable();`),`(*((${z(i,n)}*)NULL))`;if(fe(i))return"";let U=[];for(let D=0;D<l.length;D++){let x=l[D];if(!(x.isDiscarded||x.isVariableTarget)&&!(x.kind==="in"||x.kind==="const_val"||x.kind==="sym"))if(x.kind==="out"||x.kind==="lateout"){let R=d.find(Q=>Q.operandIdx===D);R&&U.push(R.varName)}else{let R=h.find(Q=>Q.operandIdx===D);R&&U.push(R.varName)}}if(U.length===1)return U[0];if(U.length>1){let D=z(i,n),x=U.map((R,Q)=>`._${Q} = ${R}`).join(", ");return`((${D}){ ${x} })`}return""}function hp(e,t,n){if(Xn(n.targetInfo))return"/* global_asm skipped: not supported on this target */";let r=e.args[0];if(r.$?.value&&Le(r.$.value)){let i=r.$.value.value;n.emitter.emitDeclarationLine(`__asm__(${JSON.stringify(i)});`)}return""}function vp(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=O(r,t,n),a=r.$?.type,s=r.$?.value;if(B(i)){let l=i.token.value,u=n;if(u.currentEvidenceParams&&B(r)){let c=`${r.token.value}.${l}`,p=u.currentEvidenceParams.get(c);if(p)return p.cParamName}if(e.$?.value&&ne(e.$.value)){let _=e.$.value;return n.functions[_.funcId]?.cName||_.funcId}if(!e.$?.value&&(k.___dispose.includes(l)||k.___drop.includes(l)||k.___dup.includes(l))&&a){let _=null;if((pe(a)||Te(a))&&(_=a.trait),_){let c=_.fields.find(p=>p.label===l&&p.assignedValue&&ne(p.assignedValue));if(c&&ne(c.assignedValue)){let p=c.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($e(a)||We(s)){let _=e.$?.value;if(_){if(ce(_)){if(_.variableName)return ve(_.variableName,e.$?.env);if((u.inAsyncStateMachine||u.inEffectStateMachine)&&u.stateMachineVariables){for(let[,c]of u.stateMachineVariables)if(c.name===l&&c.kind==="outer")return`sm->__capture.${l}`}}else if(!We(_))return en(_,n,e)}return ve(l,e.$?.env)}if(wn(a)&&a.fields.length===1){let _=a.fields[0];if(_&&_.label===l)return o}if(Te(a)){let _=a;if(Kt(_))return o;for(let p of _.variants)if(p.fields){for(let f of p.fields)if(f.label===l){let d=p.name;return`${o}.data.${d}.${re(l)}`}}return`/* ERROR: field ${l} not found in enum ${_.typeName} */`}else if(P(s)&&Te(s.value)){let _=s.value,c=_.variants.find(f=>f.name===l),p=n.types[_.id]?.cName;if(c&&!c.fields&&p){let f=Yt(_,c.name,n);return`(${p}){ .tag = ${f}, .data = { } }`}}else{if(bt(a)&&l==="*")return`${o}->value`;if(Ce(a)){if(l==="*")return`(*${o})`;if(qe(a.childType))return`${o}->${re(l)}`;{let _=0,c=a;for(;Ce(c);)_++,c=c.childType;if(_>0&&pe(c)&&c.isReferenceSemantics&&_++,wn(c)&&c.fields.length===1){let p=c.fields[0];if(p&&p.label===l)return _===1?`(*${o})`:`${"*".repeat(_)}(${o})`}return _>0?_===1?`${o}->${re(l)}`:`${`(${"*".repeat(_-1)}${o})`}->${re(l)}`:`${o}.${re(l)}`}}else if(xe(a)){if(l.match(/^\d+$/))return`${o}._${l}`;{let _=a.fields.findIndex(c=>c.label===l);return`${o}._${_}`}}else return Ie(a)?`${o}.vtable->${re(l)}`:ft(a)?`${o}->${re(l)}`:`${o}.${re(l)}`}}return"/* ERROR: field name must be an identifier */"}var nh=0;function Tp(e,t,n){if(!e.$?.type)return`// Error: No type information for pointer/reference expression ${w(e)}
11087
+ `;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,"..")||E(u,"..="))){let _=E(u,"..="),c=O(i.func,t,n),p=O(u.args[0],t,n),f=O(u.args[1],t,n),d=`Slice_${re(z(l.childType,n))}`;return n.sliceStructTypes.has(d)||n.sliceStructTypes.set(d,{childType:z(l.childType,n)}),_?`(${d}){ .data = &${c}.data[${p}], .length = (${f}) - (${p}) + 1 }`:`(${d}){ .data = &${c}.data[${p}], .length = (${f}) - (${p}) }`}}else if(l&&(qe(l)||Ce(l)&&qe(l.childType))){let u=qe(l)?l:l.childType,_=i.args[0];if(_&&F(_)&&(E(_,"..")||E(_,"..="))){let c=E(_,"..="),p=O(i.func,t,n),f=O(_.args[0],t,n),d=O(_.args[1],t,n),h=`Slice_${re(z(u.childType,n))}`;return n.sliceStructTypes.has(h)||n.sliceStructTypes.set(h,{childType:z(u.childType,n)}),c?`(${h}){ .data = &${p}.data[${f}], .length = (${d}) - (${f}) + 1 }`:`(${h}){ .data = &${p}.data[${f}], .length = (${d}) - (${f}) }`}}}let o=i.$?.value,a=i.$?.type;if(o!==void 0&&a){if(He(o)||Be(o)){let l=O(i,t,n);return`(&(${z(a,n)}){${l}})`}if(Le(o)&&i.$?.convertedRuntimeType)return`(&${O(i,t,n)})`}if(e.$?.isIndexTraitAddressOf&&F(i)&&i.$?.indexMethodValue){let l=i.$.indexMethodValue;if(ne(l)){let u=i.func,_=O(u,t,n);if(F(u)&&!B(u)&&!E(u,".")&&u.$?.type&&!(u.$?.variableName&&_===ve(u.$.variableName,u.$.env))){let g=z(u.$.type,n),y=`__yo_ptr_idx_tmp_${nh++}`;n.emitter.emitLine(`${t}${g} ${y} = ${_};`),_=y}let c=i.args[0],p=c?O(c,t,n):"0",f=Cr(l);if(f&&(k.__yo_array_index.includes(f)||k.__yo_slice_index.includes(f)))return`(&((&${_})->data[${p}]))`;let d=n.functions[l.funcId]?.cName;if(d)return`${d}(&${_}, ${p})`}}return`(&${O(i,t,n)})`}function Ep(e,t,n){let r=e.args[0];return r?`__yo_decr_rc(${O(r,t,n)})`:"// Error: __yo_decr_rc requires exactly 1 argument"}function $p(e,t,n){let r=e.args[0];return r?`__yo_incr_rc(${O(r,t,n)})`:"// Error: __yo_incr_rc requires exactly 1 argument"}function Cp(e,t,n){let r=e.args[0];return r?O(r,t,n):"// Error: __yo_rc_own requires exactly 1 argument"}function bp(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=O(r,t,n),a=O(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=M(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let c=u.length;if(!He(c))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} < ${c.value}; ${p}++) {`);let d=`(${o}).data[${a}].data[${p}]`;f.emitLine(" { // drop nested array element");let h=Or(d,u.childType,n);return h&&f.emitLine(` ${h};`),f.emitLine(" }"),f.emitLine("}"),""}let _=br(u,n);return _?`${_}((${o}).data[${a}])`:"// No drop function for array element type"}function kp(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=O(r,t,n),a=O(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=M(l)&&l.resolvedConcreteType?l.resolvedConcreteType:l;if(ke(u)){let c=u.length;if(!He(c))return"// Error: array element has non-constant length";let p=`temp_array_${Math.floor(Math.random()*1e6)}`,f=`i_${Math.floor(Math.random()*1e6)}`,d=z(u,n),h=n.emitter;h.emitLine(`${d} ${p} = (${o}).data[${a}];`),h.emitLine(`for (size_t ${f} = 0; ${f} < ${c.value}; ${f}++) {`);let g=no(`${p}.data[${f}]`,u.childType,n);return h.emitLine(` ${p}.data[${f}] = ${g};`),h.emitLine("}"),p}let _=Dn(u,n);return _?`${_}((${o}).data[${a}])`:"// No dup function for array element type"}function wp(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=O(r,t,n);O(i,t,n);let a=r.$?.type;if(!a||!xe(a))return"// Error: __yo_drop_tuple_element requires a tuple type";let s=i.$?.value;if(!He(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,_=M(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(xe(_)){let p=`(${o})._${l}`;return Or(p,_,n)}let c=br(_,n);return c?`${c}((${o})._${l})`:"// No drop function for tuple element type"}function Fp(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=O(r,t,n);O(i,t,n);let a=r.$?.type;if(!a||!xe(a))return"// Error: __yo_dup_tuple_element requires a tuple type";let s=i.$?.value;if(!He(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,_=M(u)&&u.resolvedConcreteType?u.resolvedConcreteType:u;if(xe(_)){let p=`(${o})._${l}`;return no(p,_,n)}let c=Dn(_,n);return c?`${c}((${o})._${l})`:"// No dup function for tuple element type"}function Lp(e,t,n){let r=e.args[0];if(!r)return"// Error: ___dup requires exactly 1 argument";let i=O(r,t,n),o=r.$?.type??e.$?.type;return o?no(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=O(r,t,n),o=r.$?.type??e.$?.type;return o?Or(i,o,n):""}function Ip(e,t,n){let r=e.args[0];return r?`__yo_decr_rc((void*)(${O(r,t,n)}).data)`:"// Error: __yo_dyn_drop requires exactly 1 argument"}function Sp(e,t,n){let r=e.args[0];return r?`__yo_incr_rc((void*)(${O(r,t,n)}).data)`:"// Error: __yo_dyn_dup requires exactly 1 argument"}function xp(e,t,n){let r=e.args[0];return r?`__yo_incr_rc_atomic(${O(r,t,n)})`:"// Error: __yo_incr_rc_atomic requires exactly 1 argument"}function Np(e,t,n){let r=e.args[0];return r?`__yo_decr_rc_atomic(${O(r,t,n)})`:"// Error: __yo_decr_rc_atomic requires exactly 1 argument"}function Vp(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&&M(i)&&Fe(i)){let o=O(r,t,n);return`if (${o} != NULL) { __yo_decr_rc((void*)${o}); }`}if(i&&M(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=O(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_drop: no-op */"}function Dp(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&&M(i)&&Fe(i))return`__yo_incr_rc((void*)${O(r,t,n)})`;if(i&&M(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=O(r,t,n);return`${s}(${l})`}}}return"/* __yo_sometype_dup: no-op */"}function Mp(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=O(r,t,n);return un(i)?`((__yo_ref_header_t*)(${o}))->ref_count`:"1"}function Op(e,t,n){let r=e.$?.runtimeArgExprsInOrder;if(r){let i=n,o=r.map(a=>{let s=O(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){ot(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return ve(l.$.variableName,l.$.env)}return s}).join(", ");return`${n.currentFunctionName}(${o})`}else return`// Error: No arguments for recur call ${w(e)}
11088
+ `}function Rp(e,t,n){let r=e.args[0];return`sizeof(${O(r,t,n)})`}function Pp(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 c=O(l,t,n);if(l.$?.deferredDupExpressions&&l.$.deferredDupExpressions.length>0){ot(l,t,a);let p=l.$.deferredDupExpressions[0];F(p)&&p.$?.variableName&&(c=ve(p.$.variableName,p.$.env))}return`._${u} = ${c}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=ut(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 _=O(l,t,n);return`._${u} = ${_}`}).join(", ");if(o&&e.$?.type){let l=`(${i}){ ${s} }`,u=ut(e.$.type,o,n);return n.emitter.emitLine(`${t}${u} = ${l};`),o}else return`(${i}){ ${s} }`}}}function zp(e,t,n){let i=e.args[0].$?.value;if(!i||!P(i))throw new Error("typeid codegen: expected TypeValue argument");let o=i.value,a=o.id,s=n.types[a]?.cName||z(o,n),l=`__yo_typeid_${re(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 rh(e,t){if(F(e)&&E(e,S.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=O(i,"",t),s=O(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=O(n,"",t),o=O(r,"",t);return`${i} = ${o}`}return O(e,"",t)}function Dl(e,t,n){if(F(e)&&E(e,S.begin)){let r=n,i=r.pendingDeferredDrops,o=e.$?.deferredDropExpressions??[],a=new Map;for(let _ of o){let c=An(_);c&&a.set(c,_)}r.pendingDeferredDrops=[...i??[]];let s=r.consumedVarPendingDrops,l=e.$?.consumedVariableDropExpressions??[];r.consumedVarPendingDrops=[...l,...s??[]];let u=new Set;for(let _ of e.args){let c=O(_,t,n);if(c&&n.emitter.emitLine(`${t}${c};`),_.$?.env&&a.size>u.size)for(let p of _.$.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 _ of e.$.deferredDropExpressions){let c=O(_,t,n);c&&n.emitter.emitLine(`${t}${c};`)}r.pendingDeferredDrops=i,r.consumedVarPendingDrops=s}else{let r=O(e,t,n);r&&n.emitter.emitLine(`${t}${r};`)}}function Up(e,t,n){if(e.$?.comptimeUnrolledBodies){for(let i of e.$.comptimeUnrolledBodies)Dl(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 _=O(i,t+" ",n);return n.emitter.emitLine(`${t} if (!(${_})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),Dl(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)}`,_=`continue_${Math.random().toString(36).substr(2,9)}`;n.currentLoopLabel=u,n.currentContinueLabel=_;let c=n,p=c.loopBodyDropsBaselineCount;c.loopBodyDropsBaselineCount=c.pendingDeferredDrops?.length??0,n.emitter.emitLine(`${t}while (true) {`);let f=O(i,t+" ",n);n.emitter.emitLine(`${t} if (!(${f})) {`),n.emitter.emitLine(`${t} break;`),n.emitter.emitLine(`${t} }`),Dl(a,t+" ",n),n.emitter.emitLine(`${t}${_}:;`);let d=rh(o,n);return n.emitter.emitLine(`${t} ${d};`),n.emitter.emitLine(`${t}}`),n.emitter.emitLine(`${t}${u}:;`),c.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} */`),""}var ih=0;function oh(e){let t=[];for(let n of e)if(n.isEffectRowSpread){let r=n.type;M(r)&&r.resolvedConcreteType&&(r=r.resolvedConcreteType),at(r)&&t.push(...r.implicitParameters)}else t.push(n);return t}function ah(e,t,n){let r=e.$?.indexMethodValue;if(!r||!ne(r))return"/* Error: Index trait method value missing */";let i=e.func,o=O(i,t,n);if(F(i)&&!B(i)&&!E(i,".")&&i.$?.type&&!(i.$?.variableName&&o===ve(i.$.variableName,i.$.env))){let c=z(i.$.type,n),p=`__yo_idx_tmp_${ih++}`;n.emitter.emitLine(`${t}${c} ${p} = ${o};`),o=p}let a=e.args[0],s=a?O(a,t,n):"0",l,u=Cr(r);if(u)if(k.__yo_array_index.includes(u)||k.__yo_slice_index.includes(u))l=`(&((&${o})->data[${s}]))`;else if((k.__yo_array_index_range.includes(u)||k.__yo_slice_index_range.includes(u))&&e.$?.indexTraitPtrType&&Ce(e.$.indexTraitPtrType))l=`(&(${z(e.$.indexTraitPtrType.childType,n)}){ .data = &((&${o})->data[(${s}).start]), .length = (${s}).end - (${s}).start })`;else if((k.__yo_array_index_range_inclusive.includes(u)||k.__yo_slice_index_range_inclusive.includes(u))&&e.$?.indexTraitPtrType&&Ce(e.$.indexTraitPtrType))l=`(&(${z(e.$.indexTraitPtrType.childType,n)}){ .data = &((&${o})->data[(${s}).start]), .length = (${s}).end - (${s}).start + 1 })`;else{let _=n.functions[r.funcId]?.cName;if(!_)return`/* Error: Index method ${r.funcId} not found in function registry */`;l=`${_}(&${o}, ${s})`}else{let _=n.functions[r.funcId]?.cName;if(!_)return`/* Error: Index method ${r.funcId} not found in function registry */`;l=`${_}(&${o}, ${s})`}return e.$?.isIndexTraitAddressOf?l:`(*${l})`}function sh(e,t,n,r){let i=e.args[0];if(!i?.$?.type)return;let o=e.args.find(c=>F(c)&&E(c,S.using));if(!o)return;let a=Rt(i.$.type);if(!a?.isFuture.effects?.length)return;let s=oh(a.isFuture.effects),l=o.args,u=r,_=u.emitter;for(let c=0;c<s.length&&c<l.length;c++){let p=s[c],f=l[c];if(W(p.type)){let d=p.label,h;if(u.currentEvidenceParams){for(let g of u.currentEvidenceParams.values())if(g.fieldLabel===d){h=g.cParamName;break}}if(!h&&u.stateMachineVariables){for(let[,g]of u.stateMachineVariables)if(g.name===d&&g.kind==="outer"){h=`sm->__capture.${d}`;break}}if(!h){let g=f.$?.value;if(g&&ne(g)){let y=r.functions[g.funcId];y&&(h=y.cName)}}h||(h=O(f,n,r)),h&&_.emitLine(`${n} ${t}->__capture.${d} = (void*)${h};`)}else if($e(p.type)){let d=p.type;for(let h of d.fields){if(!W(h.type))continue;let g;if(u.stateMachineVariables){for(let[,y]of u.stateMachineVariables)if(y.name===h.label&&y.kind==="outer"){g=`sm->__capture.${h.label}`;break}}if(!g){let y=f.$?.value;if(y&&We(y)){let v=d.fields.indexOf(h),T=y.fields[v];if(T&&ne(T)){let $=r.functions[T.funcId];$&&(g=$.cName)}}}if(!g&&u.currentEvidenceParams){for(let y of u.currentEvidenceParams.values())if(y.fieldLabel===h.label){g=y.cParamName;break}}g||(g=lh(h.label,d,u,e)),g&&_.emitLine(`${n} ${t}->__capture.${h.label} = (void*)${g};`)}}}}function lh(e,t,n,r){let i=r.$?.env??r.func.$?.env;if(!i)return;let o=hn(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(_=>_.label===e);if(u>=0){let _=l.fields[u];if(_&&ne(_)){let c=n.functions[_.funcId]?.cName;if(c)return c}}}}}function uh(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=O(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=O(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 fn(t,r,e,!1,!0,!0),Qn(t,r,e,!0),On({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(fn(t,r,e,!1,!0,!0),Qn(t,r,e,!0),r.currentFunctionType){let l=r.currentFunctionType.return.type;if(!fe(l)){let u=r.overrideReturnTypeStr??z(l,n);if(u!=="void")return`return (${u}){0}`}}return"return"}let s=O(i,t,n);if(r.effectHandlerParamDrops)for(let l of r.effectHandlerParamDrops)r.emitter.emitLine(`${t}${l};`);if(fn(t,r,e,!1,!0,!0),Qn(t,r,e,!0),(r.isModuleEffectMemberFunction||r.currentEvidenceParams&&r.currentEvidenceParams.size>0)&&r.currentFunctionType){let l=i.$?.type;if(l&&!fe(l)){let _=z(l,n);r.emitter.emitLine(`${t}{ ${_} _esc_val = ${s}; memcpy(__yo_effect_escape_value, &_esc_val, sizeof(${_})); }`)}let u=r.currentFunctionType.return.type;if(!fe(u)){let _=r.overrideReturnTypeStr??z(u,n);if(_!=="void")return`return (${_}){0}`}return"return"}return`return ${s}`}function Bp(e,t,n){let r;switch(e.tag){case"FnCall":r=_h(e,t,n);break;case"Atom":r=lo(e,n,t);break}return r}function _h(e,t,n){if(e.$?.macroExpansion)return O(e.$.macroExpansion,t,n);if(F(e.func)&&E(e.func,".",2)&&e.func.args[1]&&B(e.func.args[1])){let r=e.func.args[1].token.value,i=e.func.args[0],o=i?.$?.type;if(o&&M(o)&&Fe(o)){if(r===k.___drop[0]){let a=O(i,t,n);return`if (${a} != NULL) { __yo_decr_rc((void*)${a}); }`}if(r===k.___dup[0])return`__yo_incr_rc((void*)${O(i,t,n)})`}}if(H_(e))return j_(e,t,n);if(E(e,k.__yo_decr_rc))return Ep(e,t,n);if(E(e,k.__yo_incr_rc))return $p(e,t,n);if(E(e,k.__yo_rc_own))return Cp(e,t,n);if(E(e,k.__yo_drop_array_element))return bp(e,t,n);if(E(e,k.__yo_dup_array_element))return kp(e,t,n);if(E(e,k.__yo_drop_tuple_element))return wp(e,t,n);if(E(e,k.__yo_dup_tuple_element))return Fp(e,t,n);if(E(e,k.___dup))return Lp(e,t,n);if(E(e,k.___drop))return Ap(e,t,n);if(E(e,k.__yo_dyn_drop))return Ip(e,t,n);if(E(e,k.__yo_dyn_dup))return Sp(e,t,n);if(E(e,k.__yo_incr_rc_atomic))return xp(e,t,n);if(E(e,k.__yo_decr_rc_atomic))return Np(e,t,n);if(E(e,k.__yo_iso_extract))return tp(e,t,n);if(E(e,k.__yo_iso_dispose))return np(e,t,n);if(E(e,k.__yo_arc_dispose))return Oc(e,t,n);if(Il(e))return rp(e,t,n);if(Al(e))return Rc(e,t,n);if(E(e,k.__yo_sometype_drop))return Vp(e,t,n);if(E(e,k.__yo_sometype_dup))return Dp(e,t,n);if(E(e,k.__yo_gc_collect))return Jc(e,t,n);if(E(e,k.rc))return Mp(e,t,n);if(E(e,k.panic))return mp(e,t,n);if(E(e,k.asm))return gp(e,t,n);if(E(e,k.global_asm))return hp(e,t,n);if(E(e,S.test))return"/* test declaration skipped */";if(E(e,k.__yo_thread_set_maximum_threads))return _p(e,t,n);if(E(e,S.op_and))return Dc(e,t,n);if(E(e,S.op_or))return Mc(e,t,n);if(Bt(e))return e.$?.awaitAnalysis?K_(e,t,n):ec(e,t,n);if(E(e,S.dyn))return Zc(e,t,n);if(gn(e))return Gc(e,t,n);if(r_(e))return Wc(e,t,n);if(Na(e)){let r=e.args[0];if(!r)return"// Error: spawn requires a Future argument";let o=n.emitter,a=O(r,t,n),s=r.$?.type,l=s?z(s,n):"void*",u=e.$?.type,_=u?z(u,n):null,c=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} ${c} = ${a};`),o.emitLine(`${t}int ${p} = ${c}->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}}`),na(r.$?.type)||(o.emitLine(`${t}if (${p} == 0 && ${c}->__yo_resume_fn) {`),sh(e,c,t,n),o.emitLine(`${t} __yo_incr_rc((void*)${c});`),o.emitLine(`${t} ${c}->__yo_resume_fn((void*)${c});`),o.emitLine(`${t}}`)),_?`(${_}){ .__future = (void*)${c} }`:`(void*)${c}`}if(i_(e))return qc(e,t,n);if(E(e,S.return))return Tc(e,t,n);if(E(e,S.escape))return uh(e,t,n);if(E(e,k.__yo_array_fill,2))return zc(e,t,n);if(E(e,"::",2))return"";if(E(e,":",2))return jc(e,t,n);if(E(e,":=",2)){let r=ep(e,t,n);if(r!==void 0)return r}else{if(E(e,"=",2))return Uc(e,t,n);if(e.$?.value&&!ce(e.$?.value)&&!fe(e.$.type)&&!it(e.$?.controlFlow))return en(e.$.value,n,e);if(E(e,".",2))return vp(e,t,n);if(E(e,S.begin))return Hc(e,t,n);if(E(e,S.cond))return Kc(e,t,n);if(E(e,S.match))return op(e,t,n);if(E(e,k.__yo_address_of,1))return Tp(e,t,n);if(E(e,S.tuple))return Pp(e,t,n);if(E(e,S.array)){let r=Pc(e,t,n);if(r!==void 0)return r}else{if(E(e,S.recur))return Op(e,t,n);if(E(e,S.runtime,1))return O(e.args[0],t,n);if(E(e,k.sizeof,1))return Rp(e,t,n);if(E(e,k.typeid,1))return zp(e,t,n);if(E(e,k.downcast,2))return Qc(e,t,n);if(E(e,bi)){let r=e.$?.runtimeArgExprsInOrder||e.args;if(r){let i=n,o=r.map(a=>{let s=O(a,t,n);if(a.$?.deferredDupExpressions&&a.$.deferredDupExpressions.length>0){ot(a,t,i);let l=a.$.deferredDupExpressions[0];if(F(l)&&l.$?.variableName)return ve(l.$.variableName,l.$.env)}return s});return oa(e.func.token.value,o,e,n,t)}}else{if(E(e,S.while))return Up(e,t,n);if(E(e,"->",2)&&F(e.args[0])&&E(e.args[0],S.fn)){let r=e.$?.value;return ne(r)?en(r,n):"// Error: Anonymous function missing function value"}else{if(E(e,k.consume))return Xc(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,S.open))return ap(e,t,n);if(e.$?.indexTraitPtrType&&e.$?.indexMethodType)return ah(e,t,n);{let r=dp(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 Gp({expr:e,env:t,context:n}){Ee(e,k.alignof,1);let r=e.args[0],i=N({expr:r,env:t,context:{...n}});if(!i.$)throw m({token:r.token,errorMessage:"Failed to evaluate expression."});t=i.$.env;let o;i.$.value&&P(i.$.value)?o=i.$.value.value:o=i.$.type;let a=tr(o),s;return a===null?s=X(Et(),{env:t,context:n}):s=Jt("Usize",a),e.$={env:t,type:Et(),value:s,pathCollection:[]},e}function Wp({expr:e,env:t,context:n}){let r=E(e,S.op_and)?"and":"or",i=e.args;if(i.length===0){let u=dt(r==="and");return e.$={env:t,type:et(),value:u,pathCollection:[],isAccessingProperty:!1},e}let o=t,a,s=!1,l=!1;for(let u=0;u<i.length;u++){let _=i[u],c=N({expr:_,env:o,context:{...n}});if(!c.$||!dn(c.$.type))throw m({token:_.token,errorMessage:`Expected bool type for "${r}" argument, got:
11089
11089
  ${w(_)}`});o=c.$.env;let p=c.$.value;if(ce(p)){s=!0;continue}if(Be(p)){let f=p.value;if(r==="and"){if(!f){a=dt(!1);break}!s&&!l&&(a=dt(!0))}else{if(f){a=dt(!0);break}!s&&!l&&(a=dt(!1))}}else l=!0}return Be(a)||(l||s)&&(l?a=void 0:a=X(et(),{env:o,context:n})),e.$={env:o,type:et(),value:a,pathCollection:[],isAccessingProperty:!1},e}function qp({expr:e,env:t,context:n}){Ee(e,k.__yo_array_fill,2);let r=e.args[0],i=e.args[1],o=N({expr:r,env:t,context:{...n}});o.$?.env&&(t=o.$.env);let a=o.$?.value;if(!P(a)||!ke(a.value))throw m({token:r.token,errorMessage:`__yo_array_fill expects first argument to be an ArrayType, got ${a?Me(a):"undefined"}`});let s=a.value,l=N({expr:i,env:t,context:{...n,expectedType:{type:s.childType,env:t}}});l.$?.env&&(t=l.$.env);let u=l.$?.type,_=l.$?.value;if(!u)throw m({token:i.token,errorMessage:"Failed to evaluate fill value"});if(!_)throw m({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 m({token:i.token,errorMessage:`Fill value type ${A(u)} is not compatible with array element type ${A(s.childType)}`});let c=s.length;if(ce(c)){let h=X(s,{env:t,context:n});return e.$={env:t,type:s,value:h,pathCollection:[]},e}let p;if(He(c)){let h=c.value;if(p=typeof h=="bigint"?Number(h):h,!Number.isInteger(p)||p<0)throw m({token:i.token,errorMessage:`Array length must be a non-negative integer, got ${p}`})}else throw m({token:i.token,errorMessage:`Array length must be a compile-time known integer, got ${Me(c)}`});let f=[];if(ce(_)){let h=X(s,{env:t,context:n});return e.$={env:t,type:s,value:h,pathCollection:[]},e}for(let h=0;h<p;h++)f.push(_);let d=Gr(s,f);return e.$={env:t,type:s,value:d,pathCollection:[]},e}function Yp({expr:e,env:t,context:n}){if(n.isValidatingFunctionDefinition||!n.isExecuting){let s=n.expectedType?.type??K.type;return e.$={env:t,type:s,value:fe(s)?K:X(s,{env:t,context:n}),pathCollection:[]},e}let r=e.args[0],i=e.args[1],o=N({expr:r,env:t,context:{...n}});if(!o.$||!Be(o.$.value))throw m({token:r.token,errorMessage:`Expected bool value for "comptime_assert", got:
11090
11090
  ${w(r)}
11091
11091
 
@@ -11210,19 +11210,19 @@ Got: ${Me(d.$.value)}`});let g=d.$.value;if(!n.isCompileTimeOnly&&ui(h,d.$.env
11210
11210
  ${w(d)}`});let y=n.isCompileTimeOnly||s.forceCompileTimeBindings===!0,{env:v}=me({env:o,variable:{name:n.label,type:h,isCompileTimeOnly:y,value:g?[g]:void 0,token:_?.token??ue,initializedAtToken:_?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:n.isOwningTheRcValue}});if(o=v,g&&P(g)&&M(g.value)){let C=g.value,L=Un(a,C);if(L){for(let b of L.requiredTraits){let V={...b,receiverType:C};o=sr({env:o,someType:C,traitType:V,isNegated:!1})}for(let b of L.negativeTraits){let V={...b,receiverType:C};o=sr({env:o,someType:C,traitType:V,isNegated:!0})}}}try{let{expectedEnv:C}=Ze({type:p,env:o},{type:h,env:a});o=C}catch(C){throw m({token:_?.token??ue,errorMessage:`Failed to synthesize types for parameter "${n.label}":
11211
11211
  ${C.message}`})}let{parameterType:T,calleeEnv:$}=ua({functionType:e,definitionSiteEnclosingFunctionType:t,parameter:n,calleeEnv:o,context:{...s,isEvaluatingFunctionType:!0}});if(o=$,!Y({type:T,env:o},{type:h,env:a},i===0&&l))throw m({token:_?.token??ue,errorMessage:`Type mismatch for parameter "${n.label}":
11212
11212
  Expected: ${A(T)}
11213
- Got: ${A(h)}`});return{calleeEnv:o,callerEnv:a,context:{...s},argValue:g,argType:h,parameterType:T}}function go(e){if(e&&ne(e))return e}function is(e){let t=process.env[e];return t==="1"||t?.toLowerCase()==="true"}var os=is("YO_DEBUG_CALL")||is("YO_DEBUG_CALL_PROFILE")||is("YO_DEBUG_EVAL")||is("YO_DEBUG_EVAL_PROFILE"),Hf=globalThis,Fr=Hf.__yoCallProfilerState??(Hf.__yoCallProfilerState={tryCallCount:0,specializeCount:0,cacheHitCount:0,cacheMissCount:0,specializeNames:new Map,tryCallNames:new Map});function ti({expr:e,functionValue:t,functionType:n,functionCalleeExpr:r,argExprs:i,callerEnv:o,context:a,isMethodCall:s,skipSpecialization:l,skipCtfeExecution:u}){if(os){Fr.tryCallCount++;let re="(unknown)";t&&"funcName"in t&&t.funcName?re=t.funcName:t&&"funcId"in t?re=String(t.funcId):r&&(re=w(r).slice(0,60)),Fr.tryCallNames.set(re,(Fr.tryCallNames.get(re)??0)+1),Fr.tryCallCount<=5&&console.log(`[DEBUG tryCall] #${Fr.tryCallCount}: name=${re}, hasFuncValue=${!!t}, hasFuncCalleeExpr=${!!r}`)}t&&(t.specializedType?n=t.specializedType:n=t.type);let _,c=[],p=[],f=[],d=t?.definitionSiteEnclosingFunctionType,h=0;i.length>0&&F(i[0])&&E(i[0],S.forall)?(_=i[0],h=1):s&&i.length>1&&F(i[1])&&E(i[1],S.forall)&&(_=i[1],i=[i[0],...i.slice(2)]);let g,y=i.slice(h),v=y.findIndex(re=>F(re)&&E(re,S.using));if(v!==-1){let re=y.findIndex((ee,_e)=>_e>v&&F(ee)&&E(ee,S.using));if(re!==-1)throw m({token:y[re].token,errorMessage:'Only one "using(...)" is allowed per function call. Combine all implicit arguments into a single using(), e.g.: func(..., using(a, b))'});g=y[v],y=[...y.slice(0,v),...y.slice(v+1)]}let T=n.parameters.length,$=y;if(!n.variadicParameter){if($.length>T){let re=n.parameters.at(-1);if(!(re&&re.isQuote&&oi(re.type)))throw m({token:r?.token??ue,errorMessage:`Too many arguments for function call:
11213
+ Got: ${A(h)}`});return{calleeEnv:o,callerEnv:a,context:{...s},argValue:g,argType:h,parameterType:T}}function go(e){if(e&&ne(e))return e}function is(e){let t=process.env[e];return t==="1"||t?.toLowerCase()==="true"}var os=is("YO_DEBUG_CALL")||is("YO_DEBUG_CALL_PROFILE")||is("YO_DEBUG_EVAL")||is("YO_DEBUG_EVAL_PROFILE"),Hf=globalThis,Fr=Hf.__yoCallProfilerState??(Hf.__yoCallProfilerState={tryCallCount:0,specializeCount:0,cacheHitCount:0,cacheMissCount:0,specializeNames:new Map,tryCallNames:new Map});function ti({expr:e,functionValue:t,functionType:n,functionCalleeExpr:r,argExprs:i,callerEnv:o,context:a,isMethodCall:s,skipSpecialization:l,skipCtfeExecution:u}){if(os){Fr.tryCallCount++;let ie="(unknown)";t&&"funcName"in t&&t.funcName?ie=t.funcName:t&&"funcId"in t?ie=String(t.funcId):r&&(ie=w(r).slice(0,60)),Fr.tryCallNames.set(ie,(Fr.tryCallNames.get(ie)??0)+1),Fr.tryCallCount<=5&&console.log(`[DEBUG tryCall] #${Fr.tryCallCount}: name=${ie}, hasFuncValue=${!!t}, hasFuncCalleeExpr=${!!r}`)}t&&(t.specializedType?n=t.specializedType:n=t.type);let _,c=[],p=[],f=[],d=t?.definitionSiteEnclosingFunctionType,h=0;i.length>0&&F(i[0])&&E(i[0],S.forall)?(_=i[0],h=1):s&&i.length>1&&F(i[1])&&E(i[1],S.forall)&&(_=i[1],i=[i[0],...i.slice(2)]);let g,y=i.slice(h),v=y.findIndex(ie=>F(ie)&&E(ie,S.using));if(v!==-1){let ie=y.findIndex((ee,_e)=>_e>v&&F(ee)&&E(ee,S.using));if(ie!==-1)throw m({token:y[ie].token,errorMessage:'Only one "using(...)" is allowed per function call. Combine all implicit arguments into a single using(), e.g.: func(..., using(a, b))'});g=y[v],y=[...y.slice(0,v),...y.slice(v+1)]}let T=n.parameters.length,$=y;if(!n.variadicParameter){if($.length>T){let ie=n.parameters.at(-1);if(!(ie&&ie.isQuote&&oi(ie.type)))throw m({token:r?.token??ue,errorMessage:`Too many arguments for function call:
11214
11214
  Expected: ${T} arguments
11215
11215
  Got: ${$.length} arguments`})}else if($.length<T&&!n.parameters.slice($.length).every(ee=>ee.exprs.defaultValueExpr!==void 0))throw m({token:r?.token??ue,errorMessage:`Too few arguments for function call:
11216
11216
  Expected: ${T} arguments
11217
- Got: ${$.length} arguments`})}let C=y.slice(0,T),L=y.slice(T);i=C,o=Re(o);let b=Re(n.env);if(n.SelfType){let re=te(n.SelfType),{env:ee}=me({env:b,variable:{name:"Self",token:ue,type:re.type,isCompileTimeOnly:!0,initializedAtToken:ue,consumedAtToken:void 0,value:[re],isOwningTheRcValue:!1},allowVariableShadowing:!0});b=ee}for(let re=0;re<n.forallParameters.length;re++){let ee=n.forallParameters[re],_e;if(ee.exprs.labelExpr&&ee.label){let be=Ke(ee.type)&&ee.type.level===1&&F(ee.exprs.expr)&&E(ee.exprs.expr,"...",1)?te(vi(ee.label,b)):X(ee.type,{variableName:ee.label,env:b,context:a}),{env:ae,variable:ye}=me({env:b,variable:{name:ee.label,type:ee.type,isCompileTimeOnly:!0,value:[be],token:ee.exprs.labelExpr.token,initializedAtToken:ee.exprs.labelExpr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=ae,_e=ye}if(_){let le=_.args[re],be;if(F(le)&&E(le,":",2)){if(be=le.args[0],le=le.args[1],!B(be))throw m({token:be.token,errorMessage:`Expected identifier for type parameter label, got:
11217
+ Got: ${$.length} arguments`})}let C=y.slice(0,T),L=y.slice(T);i=C,o=Re(o);let b=Re(n.env);if(n.SelfType){let ie=te(n.SelfType),{env:ee}=me({env:b,variable:{name:"Self",token:ue,type:ie.type,isCompileTimeOnly:!0,initializedAtToken:ue,consumedAtToken:void 0,value:[ie],isOwningTheRcValue:!1},allowVariableShadowing:!0});b=ee}for(let ie=0;ie<n.forallParameters.length;ie++){let ee=n.forallParameters[ie],_e;if(ee.exprs.labelExpr&&ee.label){let be=Ke(ee.type)&&ee.type.level===1&&F(ee.exprs.expr)&&E(ee.exprs.expr,"...",1)?te(vi(ee.label,b)):X(ee.type,{variableName:ee.label,env:b,context:a}),{env:ae,variable:ye}=me({env:b,variable:{name:ee.label,type:ee.type,isCompileTimeOnly:!0,value:[be],token:ee.exprs.labelExpr.token,initializedAtToken:ee.exprs.labelExpr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=ae,_e=ye}if(_){let le=_.args[ie],be;if(F(le)&&E(le,":",2)){if(be=le.args[0],le=le.args[1],!B(be))throw m({token:be.token,errorMessage:`Expected identifier for type parameter label, got:
11218
11218
  ${w(be)}`});if(ee.label!==be.token.value)throw m({token:be.token,errorMessage:`Expected type parameter label "${ee.label}", got "${be.token.value}".`})}let ae;if(B(le)&&le.token.value==="_")continue;if(!le||B(le)&&vt(le,S.undefined))if(ee.exprs.defaultValueExpr){let je=N({expr:Se(ee.exprs.defaultValueExpr),env:b,context:{...a}});if(je.$?.env&&(o=je.$.env),le&&(le.$=je.$),!P(je.$?.value))throw m({token:le?.token??r?.token??ue,errorMessage:le?`Expected type for default value, got:
11219
11219
  ${w(le)}`:"Expected type for default value."});ae=je.$?.value}else throw m({token:le?.token??r?.token??ue,errorMessage:"Type parameter does not have default value."});else{let je=N({expr:le,env:o,context:{...a,expectedType:{type:ee.type,env:b}}});if(je.$?.env&&(o=je.$.env),W(ee.type)){if(!ne(je.$?.value))throw m({token:le.token,errorMessage:`Expected type constructor for HKT parameter "${ee.label}", got:
11220
11220
  ${w(le)}`});ae=je.$?.value}else{if(!P(je.$?.value))throw m({token:le.token,errorMessage:`Expected type for argument, got:
11221
11221
  ${w(le)}`});ae=je.$?.value}}be&&(be.$={env:b,type:ae.type,value:ae,pathCollection:[]});let ye=W(ee.type),we=ee.type;if(!ye){let{parameterType:je,calleeEnv:Ue}=ua({parameter:ee,calleeEnv:b,definitionSiteEnclosingFunctionType:d,context:{...a,isEvaluatingFunctionType:!0},functionType:n});b=Ue,we=je;let{expectedEnv:Je,givenEnv:Lt}=Ze({type:we,env:b},{type:ae.type,env:o});if(b=Je,o=Lt,!Y({type:we,env:b},{type:ae.type,env:o}))throw m({token:le?.token??r?.token??ue,errorMessage:`Type mismatch for type parameter "${ee.label}":
11222
11222
  Expected: ${A(we)}
11223
- Got: ${A(ae.type)}`})}if(ee.label)if(_e)b=Ge(b,_e,{..._e,value:[ae]});else{let je=le?.token??r?.token??ue,{env:Ue}=me({env:b,variable:{name:ee.label,type:ae.type,isCompileTimeOnly:!0,value:[ae],token:je,initializedAtToken:je,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=Ue}c.push({value:ae,argType:ae.type,parameterType:we})}}if(a.expectedType&&!_&&n.forallParameters.length>0&&!n.return.isUnquote)try{let{returnType:re,calleeEnv:ee}=Fi({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r}),{expectedEnv:_e}=Ze({type:re,env:ee},{type:a.expectedType.type,env:a.expectedType.env});b=_e}catch{}if(g&&n.implicitParameters.length>0&&n.implicitParameters.some(ee=>ee.isEffectRowSpread)){let _e=n.implicitParameters.filter(be=>!be.isEffectRowSpread).length,le=g.args.slice(_e);if(le.length>0){let be=[];for(let we of le){if(!B(we))throw m({token:we.token,errorMessage:`Expected identifier for using() argument in effect row spread, got ${w(we)}`});let je=we.token.value,Je=j(o,je).at(-1);if(!Je)throw m({token:we.token,errorMessage:`Variable "${je}" not found for using() argument in effect row spread.`});we.$={env:o,type:Je.type,value:Je.value?.[0],variableName:je,pathCollection:[]},be.push({label:je,type:Je.type,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:we,labelExpr:we,typeExpr:void 0,defaultValueExpr:void 0}})}let ae=Dr(be),ye=te(ae);for(let we of n.implicitParameters){if(!we.isEffectRowSpread)continue;let je=we.label,Je=j(b,je).at(-1);Je&&(b=Ge(b,Je,{...Je,value:[ye]})),M(we.type)&&we.type.isEffectsRow&&(we.type.resolvedConcreteType=ae)}}}n.ioBuiltin==="io_async"&&(a={...a,isInsideIoAsyncCall:!0});let V=n.parameters.length;for(let re=0;re<V;re++){let ee=n.parameters[re],{calleeEnv:_e,callerEnv:le,context:be,argValue:ae,argType:ye,parameterType:we}=kh({functionType:n,definitionSiteEnclosingFunctionType:d,parameter:ee,argExprs:i,argIndex:re,callerEnv:o,calleeEnv:b,context:a,isMethodCall:s,runtimeArgExprsInOrder:f});b=_e,o=le,a=be,p.push({value:ae,parameterType:we,argType:ye})}if(!_&&n.forallParameters.length>0){for(let re of n.forallParameters)if(re.label){let _e=j(b,re.label).at(-1);if(_e?.value?.[0]&&P(_e.value[0])){let le=_e.value[0];if(M(le.value)&&le.value.resolvedConcreteType&&(!le.value.requiredTraits||le.value.requiredTraits.length===0)){let be=te(le.value.resolvedConcreteType);b=Ge(b,_e,{..._e,value:[be]})}}}}if(!_&&n.forallParameters.length>0){for(let re of n.forallParameters)if(re.label){let _e=j(b,re.label).at(-1);_e?.value?.[0]&&P(_e.value[0])&&c.push({value:_e.value[0],argType:_e.value[0].type,parameterType:re.type})}}if(n.whereClauseExprs?.length){let re=n.whereClauseExprs.map(_e=>Se(_e));b=ei({constraintExprs:re,env:b,context:{...a,isEvaluatingFunctionType:!0}}).env}let{returnType:I,calleeEnv:U}=Fi({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});if(b=U,a.expectedType&&!n.return.isUnquote){let{expectedEnv:re}=Ze({type:I,env:b},{type:a.expectedType.type,env:a.expectedType.env});b=re;let ee=Fi({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});I=ee.returnType,b=ee.calleeEnv,Y({type:a.expectedType.type,env:a.expectedType.env},{type:I,env:b})&&(I=a.expectedType.type)}let D=[];if(n.variadicParameter){for(let re=0;re<L.length;re++){let ee=L[re],_e;if(n.variadicParameter.isQuote)_e=Se(ee),_e.$={type:mn(),value:jn(ee),env:o,pathCollection:[]},D.push({value:_e.$.value,argType:_e.$.type});else{if(_e=N({expr:ee,env:o,context:{...a}}),!_e.$?.env)throw m({token:ee.token,errorMessage:`Failed to evaluate the expression:
11224
- ${w(ee)}`});o=_e.$.env,D.push({value:_e.$.value,argType:_e.$.type}),n.variadicParameter.isCompileTimeOnly||f.push(ee)}}if(n.variadicParameter.label!=="..."){if(n.variadicParameter.isQuote){let re=qn(mn(),D.map(_e=>_e.value)),{env:ee}=me({env:b,variable:{name:n.variadicParameter.label,type:re.type,isCompileTimeOnly:n.variadicParameter.isCompileTimeOnly,value:[re],token:n.variadicParameter.exprs.expr.token,initializedAtToken:n.variadicParameter.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=ee}}}let x=[],R=[];if(n.implicitParameters.length>0)for(let re=0;re<n.implicitParameters.length;re++){let ee=n.implicitParameters[re],_e=!1;if(ee.isEffectRowSpread){let ae=[],we=j(b,ee.label).at(-1)?.value?.[0],je;if(we&&P(we)&&at(we.value))je=we.value;else if(M(ee.type)&&ee.type.isEffectsRow){let Ue=Ut(b,ee.type);at(Ue)&&(je=Ue)}else at(ee.type)&&(je=ee.type);if(!je&&M(ee.type)&&ee.type.isEffectsRow){let Ue=hn(o,At=>At.isImplicit===!0&&At.isCompileTimeOnly===!0&&(W(At.type)||$e(At.type))),Je=new Set(n.implicitParameters.filter(At=>!At.isEffectRowSpread).map(At=>At.label)),Lt=Ue.filter(At=>!Je.has(At.name));if(Lt.length>0){for(let ur of Lt){let ii=ur.value?.[0];if(ii){R.push({value:ii,parameterType:ur.type,argType:ur.type});let{env:qm}=me({env:b,variable:{name:ur.name,type:ur.type,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[ii],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=qm}}let At=Dr(Lt.map(ur=>({label:ur.name,type:ur.type,isCompileTimeOnly:!0,isQuote:!1,isOwningTheRcValue:!1,isImplicit:!0,exprs:{expr:void 0,labelExpr:void 0,typeExpr:void 0}}))),Tn=te(At),Br=j(b,ee.label).at(-1);Br&&(b=Ge(b,Br,{...Br,value:[Tn],type:At})),_e=!0;continue}}ae=je?.implicitParameters??[];for(let Ue of ae){let Je=Ue.type,At=hn(o,Tn=>Tn.isImplicit===!0&&Tn.isCompileTimeOnly===!0&&Tn.name===Ue.label&&Y({type:Je,env:b},{type:Tn.type,env:o})).at(-1);if(At?.value?.[0]){let Tn=At.value[0];R.push({value:Tn,parameterType:Je,argType:At.type});let{env:Zn}=me({env:b,variable:{name:Ue.label,type:Je,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[Tn],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Zn}else{let Zn=hn(o,ii=>ii.isImplicit===!0&&ii.isCompileTimeOnly===!0&&Y({type:Je,env:b},{type:ii.type,env:o})).at(-1);if(!Zn?.value?.[0])throw m({token:r?.token??e?.token??ue,errorMessage:`No "given" variable found for effect row parameter "${Ue.label}" of type ${A(Je)} (expanded from effect row ...(${ee.label})).
11225
- Please ensure a given variable of matching type is in scope.`});let Br=Zn.value[0];R.push({value:Br,parameterType:Je,argType:Zn.type});let{env:ur}=me({env:b,variable:{name:Ue.label,type:Je,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[Br],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=ur}}continue}let{parameterType:le,calleeEnv:be}=ua({parameter:ee,calleeEnv:b,definitionSiteEnclosingFunctionType:d,context:{...a,isEvaluatingFunctionType:!0},functionType:n});if(b=be,g){let ae=g.args[re],ye=ae&&B(ae)&&vt(ae,S.undefined);if(ae&&!ye){let we=N({expr:ae,env:o,context:{...a}});if(!we.$)throw m({token:ae.token,errorMessage:`Failed to evaluate using() argument: ${w(ae)}`});o=we.$.env;let je=we.$.value,Ue=we.$.type;if(!je)throw m({token:ae.token,errorMessage:`Expected compile-time value for using() argument, got runtime value: ${w(ae)}`});if(!Y({type:le,env:b},{type:Ue,env:o}))throw m({token:ae.token,errorMessage:`Incompatible type for implicit parameter "${ee.label}":
11223
+ Got: ${A(ae.type)}`})}if(ee.label)if(_e)b=Ge(b,_e,{..._e,value:[ae]});else{let je=le?.token??r?.token??ue,{env:Ue}=me({env:b,variable:{name:ee.label,type:ae.type,isCompileTimeOnly:!0,value:[ae],token:je,initializedAtToken:je,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=Ue}c.push({value:ae,argType:ae.type,parameterType:we})}}if(a.expectedType&&!_&&n.forallParameters.length>0&&!n.return.isUnquote)try{let{returnType:ie,calleeEnv:ee}=Fi({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r}),{expectedEnv:_e}=Ze({type:ie,env:ee},{type:a.expectedType.type,env:a.expectedType.env});b=_e}catch{}if(g&&n.implicitParameters.length>0&&n.implicitParameters.some(ee=>ee.isEffectRowSpread)){let _e=n.implicitParameters.filter(be=>!be.isEffectRowSpread).length,le=g.args.slice(_e);if(le.length>0){let be=[];for(let we of le){if(!B(we))throw m({token:we.token,errorMessage:`Expected identifier for using() argument in effect row spread, got ${w(we)}`});let je=we.token.value,Je=j(o,je).at(-1);if(!Je)throw m({token:we.token,errorMessage:`Variable "${je}" not found for using() argument in effect row spread.`});we.$={env:o,type:Je.type,value:Je.value?.[0],variableName:je,pathCollection:[]},be.push({label:je,type:Je.type,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:we,labelExpr:we,typeExpr:void 0,defaultValueExpr:void 0}})}let ae=Dr(be),ye=te(ae);for(let we of n.implicitParameters){if(!we.isEffectRowSpread)continue;let je=we.label,Je=j(b,je).at(-1);Je&&(b=Ge(b,Je,{...Je,value:[ye]})),M(we.type)&&we.type.isEffectsRow&&(we.type.resolvedConcreteType=ae)}}}n.ioBuiltin==="io_async"&&(a={...a,isInsideIoAsyncCall:!0});let V=n.parameters.length;for(let ie=0;ie<V;ie++){let ee=n.parameters[ie],{calleeEnv:_e,callerEnv:le,context:be,argValue:ae,argType:ye,parameterType:we}=kh({functionType:n,definitionSiteEnclosingFunctionType:d,parameter:ee,argExprs:i,argIndex:ie,callerEnv:o,calleeEnv:b,context:a,isMethodCall:s,runtimeArgExprsInOrder:f});b=_e,o=le,a=be,p.push({value:ae,parameterType:we,argType:ye})}if(!_&&n.forallParameters.length>0){for(let ie of n.forallParameters)if(ie.label){let _e=j(b,ie.label).at(-1);if(_e?.value?.[0]&&P(_e.value[0])){let le=_e.value[0];if(M(le.value)&&le.value.resolvedConcreteType&&(!le.value.requiredTraits||le.value.requiredTraits.length===0)){let be=te(le.value.resolvedConcreteType);b=Ge(b,_e,{..._e,value:[be]})}}}}if(!_&&n.forallParameters.length>0){for(let ie of n.forallParameters)if(ie.label){let _e=j(b,ie.label).at(-1);_e?.value?.[0]&&P(_e.value[0])&&c.push({value:_e.value[0],argType:_e.value[0].type,parameterType:ie.type})}}if(n.whereClauseExprs?.length){let ie=n.whereClauseExprs.map(_e=>Se(_e));b=ei({constraintExprs:ie,env:b,context:{...a,isEvaluatingFunctionType:!0}}).env}let{returnType:I,calleeEnv:U}=Fi({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});if(b=U,a.expectedType&&!n.return.isUnquote){let{expectedEnv:ie}=Ze({type:I,env:b},{type:a.expectedType.type,env:a.expectedType.env});b=ie;let ee=Fi({functionType:n,calleeEnv:b,context:{...a,isEvaluatingFunctionType:!0},functionCalleeExpr:r});I=ee.returnType,b=ee.calleeEnv,Y({type:a.expectedType.type,env:a.expectedType.env},{type:I,env:b})&&(I=a.expectedType.type)}let D=[];if(n.variadicParameter){for(let ie=0;ie<L.length;ie++){let ee=L[ie],_e;if(n.variadicParameter.isQuote)_e=Se(ee),_e.$={type:mn(),value:jn(ee),env:o,pathCollection:[]},D.push({value:_e.$.value,argType:_e.$.type});else{if(_e=N({expr:ee,env:o,context:{...a}}),!_e.$?.env)throw m({token:ee.token,errorMessage:`Failed to evaluate the expression:
11224
+ ${w(ee)}`});o=_e.$.env,D.push({value:_e.$.value,argType:_e.$.type}),n.variadicParameter.isCompileTimeOnly||f.push(ee)}}if(n.variadicParameter.label!=="..."){if(n.variadicParameter.isQuote){let ie=qn(mn(),D.map(_e=>_e.value)),{env:ee}=me({env:b,variable:{name:n.variadicParameter.label,type:ie.type,isCompileTimeOnly:n.variadicParameter.isCompileTimeOnly,value:[ie],token:n.variadicParameter.exprs.expr.token,initializedAtToken:n.variadicParameter.exprs.expr.token,consumedAtToken:void 0,isOwningTheRcValue:!1}});b=ee}}}let x=[],R=[];if(n.implicitParameters.length>0)for(let ie=0;ie<n.implicitParameters.length;ie++){let ee=n.implicitParameters[ie],_e=!1;if(ee.isEffectRowSpread){let ae=[],we=j(b,ee.label).at(-1)?.value?.[0],je;if(we&&P(we)&&at(we.value))je=we.value;else if(M(ee.type)&&ee.type.isEffectsRow){let Ue=Ut(b,ee.type);at(Ue)&&(je=Ue)}else at(ee.type)&&(je=ee.type);if(!je&&M(ee.type)&&ee.type.isEffectsRow){let Ue=hn(o,At=>At.isImplicit===!0&&At.isCompileTimeOnly===!0&&(W(At.type)||$e(At.type))),Je=new Set(n.implicitParameters.filter(At=>!At.isEffectRowSpread).map(At=>At.label)),Lt=Ue.filter(At=>!Je.has(At.name));if(Lt.length>0){for(let ur of Lt){let ii=ur.value?.[0];if(ii){R.push({value:ii,parameterType:ur.type,argType:ur.type});let{env:qm}=me({env:b,variable:{name:ur.name,type:ur.type,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[ii],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=qm}}let At=Dr(Lt.map(ur=>({label:ur.name,type:ur.type,isCompileTimeOnly:!0,isQuote:!1,isOwningTheRcValue:!1,isImplicit:!0,exprs:{expr:void 0,labelExpr:void 0,typeExpr:void 0}}))),Tn=te(At),Br=j(b,ee.label).at(-1);Br&&(b=Ge(b,Br,{...Br,value:[Tn],type:At})),_e=!0;continue}}ae=je?.implicitParameters??[];for(let Ue of ae){let Je=Ue.type,At=hn(o,Tn=>Tn.isImplicit===!0&&Tn.isCompileTimeOnly===!0&&Tn.name===Ue.label&&Y({type:Je,env:b},{type:Tn.type,env:o})).at(-1);if(At?.value?.[0]){let Tn=At.value[0];R.push({value:Tn,parameterType:Je,argType:At.type});let{env:Zn}=me({env:b,variable:{name:Ue.label,type:Je,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[Tn],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Zn}else{let Zn=hn(o,ii=>ii.isImplicit===!0&&ii.isCompileTimeOnly===!0&&Y({type:Je,env:b},{type:ii.type,env:o})).at(-1);if(!Zn?.value?.[0])throw m({token:r?.token??e?.token??ue,errorMessage:`No "given" variable found for effect row parameter "${Ue.label}" of type ${A(Je)} (expanded from effect row ...(${ee.label})).
11225
+ Please ensure a given variable of matching type is in scope.`});let Br=Zn.value[0];R.push({value:Br,parameterType:Je,argType:Zn.type});let{env:ur}=me({env:b,variable:{name:Ue.label,type:Je,isCompileTimeOnly:!0,isImplicit:!0,isFromEffectSpread:!0,value:[Br],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=ur}}continue}let{parameterType:le,calleeEnv:be}=ua({parameter:ee,calleeEnv:b,definitionSiteEnclosingFunctionType:d,context:{...a,isEvaluatingFunctionType:!0},functionType:n});if(b=be,g){let ae=g.args[ie],ye=ae&&B(ae)&&vt(ae,S.undefined);if(ae&&!ye){let we=N({expr:ae,env:o,context:{...a}});if(!we.$)throw m({token:ae.token,errorMessage:`Failed to evaluate using() argument: ${w(ae)}`});o=we.$.env;let je=we.$.value,Ue=we.$.type;if(!je)throw m({token:ae.token,errorMessage:`Expected compile-time value for using() argument, got runtime value: ${w(ae)}`});if(!Y({type:le,env:b},{type:Ue,env:o}))throw m({token:ae.token,errorMessage:`Incompatible type for implicit parameter "${ee.label}":
11226
11226
  Expected: ${A(le)}
11227
11227
  Got: ${A(Ue)}`});R.push({value:je,parameterType:le,argType:Ue});let Je=j(b,ee.label);if(Je.length>0){let Lt=Je[Je.length-1];b=Ge(b,Lt,{...Lt,type:le,isImplicit:!0,value:[je]})}else{let{env:Lt}=me({env:b,variable:{name:ee.label,type:le,isCompileTimeOnly:!0,isImplicit:!0,value:[je],token:ee.exprs.labelExpr?.token??ue,initializedAtToken:ee.exprs.labelExpr?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Lt}_e=!0}}if(!_e){let ae=hn(o,Lt=>Lt.isImplicit===!0&&Lt.isCompileTimeOnly===!0&&Y({type:le,env:b},{type:Lt.type,env:o}));if(ae.length===0)throw m({token:r?.token??e?.token??ue,errorMessage:`No "given" variable found for implicit parameter "${ee.label}" of type ${A(le)}.
11228
11228
  Please declare a given variable with a compatible type, e.g.:
@@ -11231,7 +11231,7 @@ Or pass it explicitly:
11231
11231
  ${t?.funcName??"func"}(..., using(<value>))`});if(ae[ae.length-1].isFromEffectSpread&&!(()=>{if(!r||!B(r))return!1;let At=r.token.value,Tn=a.isEvaluatingFunctionBodyOrAsyncBlock;return!Tn||Tn.kind!=="function-body"?!1:Tn.type.parameters.some(Br=>Br.label===At)})())throw m({token:r?.token??e?.token??ue,errorMessage:`Effect "${ee.label}" of type ${A(le)} is available through an effect row spread but not explicitly declared in the function's using clause.
11232
11232
  Add it explicitly:
11233
11233
  using(${ee.label} : ${A(le)}, ...(E))`});let we=ae;if(we.length>1){let Lt=Xo(o,At=>At.isImplicit===!0&&At.isCompileTimeOnly===!0&&Y({type:le,env:b},{type:At.type,env:o}));if(Lt>=0){let Tn=o.frames[Lt].variables.filter(Zn=>Zn.isImplicit===!0&&Zn.isCompileTimeOnly===!0&&Y({type:le,env:b},{type:Zn.type,env:o}));Tn.length>0&&(we=Tn)}}if(we.length>1)throw m({token:r?.token??e?.token??ue,errorMessage:`Ambiguous implicit parameter "${ee.label}": found ${we.length} "given" variables with compatible type ${A(le)} in the same scope.
11234
- Please use explicit using() to disambiguate.`});let je=we[we.length-1],Ue=je.value?.[0];if(!Ue)throw m({token:r?.token??e?.token??ue,errorMessage:`The "given" variable "${je.name}" has no compile-time value.`});R.push({value:Ue,parameterType:le,argType:je.type});let{env:Je}=me({env:b,variable:{name:ee.label,type:le,isCompileTimeOnly:!0,isImplicit:!0,value:[Ue],token:ee.exprs.labelExpr?.token??ue,initializedAtToken:ee.exprs.labelExpr?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Je}}let Q={args:p,forallArgs:c,implicitArgs:R,variadicArgs:D},J;if(n.return.isCompileTimeOnly)if(u)J=X(I,{variableName:n.return.label,env:n.env,context:a});else if(ne(t)){let{value:re,callerEnv:ee,calleeEnv:_e}=po({functionCalleeExpr:r,functionType:n,functionValue:t,argValues:Q,callerEnv:o,calleeEnv:b,context:{...a}});J=re,I=re.type,o=ee,b=_e}else{let re=Ke(I)&&I.level===0,ee=`${n.id}_return_sometype`;if(re)if(a.expectedType?.type)J=te(a.expectedType.type);else if(a.isEvaluatingFunctionType){let _e=Ln(I,n.return.label,{id:ee,env:b,context:a});_e.functionApplication=e;let le=Ut(b,_e);J=te(le)}else throw m({token:e?.token??r?.token??ue,errorMessage:"Cannot infer comptime return type. Please provide the expected type."});else J=X(I,{variableName:n.return.label,env:n.env,context:a})}Lh({returnType:I,env:b,expr:e,context:a});let G,H=a.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&a.isEvaluatingFunctionBodyOrAsyncBlock.value&&ne(a.isEvaluatingFunctionBodyOrAsyncBlock.value)&&t&&ne(t)&&a.isEvaluatingFunctionBodyOrAsyncBlock.value.funcId===t.funcId,oe=Q.implicitArgs?.some(re=>ce(re.value)),ge=oe&&!Q.implicitArgs?.some(re=>ce(re.value)&&!$e(re.parameterType)),q=Q.args.some(re=>re.argType&&M(re.argType)),Z=ge&&q,se=(()=>{if(!oe||!n.implicitParameters.some(le=>le.isEffectRowSpread))return!1;let ee=0;for(let le of n.implicitParameters)le.isEffectRowSpread||ee++;let _e=Q.implicitArgs??[];for(let le=0;le<ee&&le<_e.length;le++)if(ce(_e[le].value))return!1;return!0})(),De=Wn(n)&&!fr(n)&&n.implicitParameters.some(re=>$e(re.type)?re.type.fields.some(ee=>W(ee.type)&&ee.type.forallParameters.length===0):!!re.isEffectRowSpread);if(!l&&!De&&t&&ne(t)&&!t.isControlFunction&&Wn(n)&&!H&&(!oe||Z||se)){if(G=wh({originalFunction:t,argValues:Q,calleeEnv:b,callerEnv:o,context:a}),G&&M(I)){let re=G.body?.$?.type;re&&!M(re)&&(I=re,G.specializedType&&(G.specializedType={...G.specializedType,return:{...G.specializedType.return,type:re}}))}if(G){let re=new Set,ee=0;for(let _e=0;_e<n.parameters.length;_e++)if(!n.parameters[_e].isCompileTimeOnly){let ae=Q.args[_e]?.value;ae&&ne(ae)&&ae.type.implicitParameters.some(ye=>W(ye.type)||$e(ye.type))&&re.add(ee),ee++}if(re.size>0)for(let _e=f.length-1;_e>=0;_e--)re.has(_e)&&f.splice(_e,1)}}if(!l&&t&&ne(t)&&t.isControlFunction&&n.forallParameters.length>0&&!G&&(G=Fh({originalFunction:t,argValues:Q,calleeEnv:b,callerEnv:o,context:a}),G&&M(I))){let re=G.body?.$?.type;re&&!M(re)&&(I=re,G.specializedType&&(G.specializedType={...G.specializedType,return:{...G.specializedType.return,type:re}}))}let he=to(o),Xe;if(he.length>0){let re=bh({variablesToDrop:he,env:o,context:a});Xe=re.deferredDropExpressions,o=re.env}return{returnType:I,calleeEnv:b,callerEnv:o,pathCollection:x,argValues:Q,returnValue:J,specializedFunctionValue:G,runtimeArgExprsInOrder:f,deferredDropExpressions:Xe}}function wh({originalFunction:e,argValues:t,calleeEnv:n,callerEnv:r,context:i}){if(os){Fr.specializeCount++;let D=e.funcName??e.funcId;Fr.specializeNames.set(D,(Fr.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,x)=>{let R=t.args[x];if(D.isCompileTimeOnly)R.value&&a.push(R.value);else if(R.value&&ne(R.value)&&R.value.type.implicitParameters.some(J=>W(J.type)||$e(J.type)))R.value&&a.push(R.value);else{let G=M(R.argType)&&R.argType.resolvedConcreteType&&!Fe(R.argType)?R.argType.resolvedConcreteType:R.argType;s.push({...D,type:G})}});let l=s.map(D=>D.type),u=e.specializedFunctionCaches.find(D=>D.compileTimeArgValues.length===a.length&&D.compileTimeArgValues.every((Q,J)=>{let G=a[J];return xt({value:Q,env:D.env},{value:G,env:r})})?D.runtimeParameterTypes.length===l.length&&D.runtimeParameterTypes.every((Q,J)=>{let G=l[J];return Y({type:Q,env:D.env},{type:G,env:r},!0)}):!1);if(u)return os&&Fr.cacheHitCount++,u.specializedFunction;os&&Fr.cacheMissCount++;let _=n;for(let D of r.frames)for(let x of D.variables){if(!x.isCompileTimeOnly||j(_,x.name).length>0)continue;let{env:Q}=me({env:_,variable:{...x},allowVariableShadowing:!0});_=Q}for(let D of s){let x=j(_,D.label);if(x.length>0){let R=x[x.length-1],Q={...R,value:void 0};_=Ge(_,R,Q)}}let c=Se(e.body),{returnType:p,calleeEnv:f}=Fi({functionType:o,calleeEnv:_,context:{...i,isEvaluatingFunctionType:!0},functionCalleeExpr:void 0});_=f;let d=i.enclosingFunctionReturnType,h=t.implicitArgs?.some(D=>ne(D.value)&&D.value.isControlFunction||We(D.value)&&jf(D.value.type,D.value))??!1,g=Tt({expr:c,env:_,context:{...i,expectedType:{type:p,env:_},isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:o,value:e,evaluationEnv:_},isEvaluatingLoopBody:void 0,capturedVariables:void 0,functionReturnImplConcreteType:[],hasControlFunctionImplicitParams:h,...d?{enclosingFunctionReturnType:d}:{}},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(!g.$)throw m({token:e.body.token,errorMessage:"Failed to evaluate function body for specialization."});let y=[],v=0;for(let D=0;D<o.implicitParameters.length;D++){let x=o.implicitParameters[D];if(W(x.type)){let R=t.implicitArgs?.[v];(R&&ne(R.value)?R.value:void 0)?.isControlFunction&&y.push({handlerArgIndex:v,label:x.label,type:x.type,fromSpread:!1}),v+=1}else if(x.isEffectRowSpread){let R=x.type;if(M(R)){let J=j(_,x.label).at(-1)?.value?.[0];if(J&&P(J)&&at(J.value))R=J.value;else{let G=Ut(_,R);G&&(R=G)}}if(at(R)){for(let Q=0;Q<R.implicitParameters.length;Q++){let J=R.implicitParameters[Q];if(W(J.type)){let G=t.implicitArgs?.[v+Q];(G&&ne(G.value)?G.value:void 0)?.isControlFunction&&y.push({handlerArgIndex:v+Q,label:J.label,type:J.type,fromSpread:!0})}else if($e(J.type)){let G=t.implicitArgs?.[v+Q],H=G&&We(G.value)?G.value:void 0,oe=[],ge=(q,Z,se)=>{for(let Ae=0;Ae<q.fields.length;Ae++){let De=q.fields[Ae];if(W(De.type)){let he=se?.fields[Ae];if(he&&ne(he)&&he.isControlFunction){let Xe=he.specializedType??De.type;oe.push({path:[...Z,De.label],type:Xe})}}else if($e(De.type)){let he=se?.fields[Ae];ge(De.type,[...Z,De.label],he&&We(he)?he:void 0)}}};ge(J.type,[],H);for(let q of oe)y.push({handlerArgIndex:v+Q,label:J.label,type:q.type,fromSpread:!0,effectFieldPath:q.path})}}v+=R.implicitParameters.length}else v+=1}else if($e(x.type)){let R=[],Q=t.implicitArgs?.[v],J=(G,H,oe)=>{for(let ge=0;ge<G.fields.length;ge++){let q=G.fields[ge];if(W(q.type)){let Z=oe?.fields[ge];if(Z&&ne(Z)&&Z.isControlFunction){let se=Z.specializedType??q.type;R.push({path:[...H,q.label],type:se})}}else if($e(q.type)){let Z=oe?.fields[ge];J(q.type,[...H,q.label],Z&&We(Z)?Z:void 0)}}};J(x.type,[],Q&&We(Q.value)?Q.value:void 0);for(let G of R)y.push({handlerArgIndex:v,label:x.label,type:G.type,fromSpread:!1,effectFieldPath:G.path});v+=1}else v+=1}let T=[];for(let D of y){let x=Yf(g,D.label,D.type,!0,D.effectFieldPath);if(x.hasEffects){let R=t.implicitArgs?.[D.handlerArgIndex],Q,J=D.effectFieldPath;if(R&&ne(R.value))Q=R.value;else if(R&&We(R.value)&&J&&J.length>0){let G=R.value;for(let H of J){if(!We(G)){G=void 0;break}let oe=G.type.fields.findIndex(ge=>ge.label===H);if(oe<0||!G.fields[oe]){G=void 0;break}G=G.fields[oe]}G&&ne(G)&&(Q=G)}if(Q){let G=Q,H=D.type,oe=!G.body.$;if(!oe&&G.isControlFunction&&F(G.body)&&G.body.args.length>0&&!G.body.args[0]?.$&&(oe=!0),oe&&W(H)&&H.forallParameters.length>0&&x.effectCallPoints.length>0){let ge=new Map,q=H.return.type,Z=x.effectCallPoints[0].operationResultType;if(M(q)&&ge.set(q.name,Z),ge.size===0&&H.forallParameters.length===1){let re=H.forallParameters[0];ge.set(re.label,Z)}let se=Se(G.body),Ae=G.body.$?.env??_;Ae=Re(Ae);for(let re of H.forallParameters){let ee=ge.get(re.label);ee&&(Ae=me({env:Ae,variable:{name:re.label,type:re.type,isCompileTimeOnly:!0,value:[te(ee)],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0}).env)}let De=G.specializedType??G.type,he=G.definitionSiteEnclosingFunctionType?.return.type??zn(),Xe={...i,expectedType:void 0,enclosingFunctionReturnType:he,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:De,value:G,evaluationEnv:Ae}};try{let re=ni({expr:se,env:Ae,context:Xe}),ee=De.parameters.map(ae=>{if(ae.isCompileTimeOnly)return ae;if(M(ae.type)){let ye=ge.get(ae.type.name);if(ye)return{...ae,type:ye}}return ae}),_e=De.return.type;if(M(_e)){let ae=ge.get(_e.name);ae&&(_e=ae)}let le={...De,parameters:ee,return:{...De.return,type:_e}},be={...G,body:re,specializedType:le};x.handlerValue=be,x.effectParameterType=le;for(let ae of x.effectCallPoints)ae.isTransitiveEffectCall&&(ae.operationArgTypes=ae.operationArgTypes.map(ye=>M(ye)?ge.get(ye.name)??ye:ye))}catch(re){if(F(G.body)&&G.body.args.length>0&&!G.body.args[0]?.$)throw re;x.handlerValue=G}}else x.handlerValue=G}else R&&(x.handlerValue=R.value);T.push({analysis:x,ctlParam:D})}}if(T.length===1)g.$.effectAnalysis=T[0].analysis;else if(T.length>1){let D=[],x=new Map,R=new Map,Q=[];for(let H=0;H<T.length;H++){let{analysis:oe}=T[H];Q.push({effectParameterName:oe.effectParameterName,effectParameterType:oe.effectParameterType,effectFieldPath:oe.effectFieldPath,handlerValue:oe.handlerValue,operationArgTypes:oe.effectCallPoints.length>0?oe.effectCallPoints[0].operationArgTypes:[],operationResultType:oe.effectCallPoints.length>0?oe.effectCallPoints[0].operationResultType:{tag:"unit"}});for(let ge of oe.effectCallPoints)D.push({...ge,effectIndex:H});for(let ge of oe.capturedVariables)x.has(ge.id)||x.set(ge.id,ge);for(let[ge,q]of oe.variableIdRemapping)R.set(ge,q)}if(F(g)&&E(g,S.begin)){let H=g.args,oe=new Map;for(let q=0;q<H.length;q++)oe.set(H[q],q);let ge=q=>{for(let Z=0;Z<H.length;Z++)if(Wl(H[Z],q.expr))return Z;return 999};D.sort((q,Z)=>ge(q)-ge(Z))}for(let H=0;H<D.length;H++)D[H].index=H;let J=T[0].analysis,G={effectCallPoints:D,capturedVariables:Array.from(x.values()),hasEffects:!0,variableIdRemapping:R,effectParameterName:J.effectParameterName,effectParameterType:J.effectParameterType,effectFieldPath:J.effectFieldPath,handlerValue:J.handlerValue,effectHandlerInfos:Q};g.$.effectAnalysis=G}let $=[],C=D=>{if(P(D)){let x=D.value;if(!x.typeName&&x.id)return`${Me(D)}_id${x.id}`}return ne(D)?`fn_${D.funcId}`:Me(D)};o.forallParameters.forEach((D,x)=>{if(x<t.forallArgs.length){let R=t.forallArgs[x];$.push(ie(C(R.value)))}else{let R=D.label,Q=j(n,R);Q.length>0&&Q[Q.length-1]?.value?.[0]?$.push(ie(C(Q[Q.length-1].value[0]))):$.push("unknown")}}),o.parameters.forEach((D,x)=>{if(D.isCompileTimeOnly&&x<t.args.length){let R=t.args[x];R?$.push(ie(C(R.value))):$.push("unknown")}}),t.implicitArgs&&t.implicitArgs.forEach(D=>{$.push(ie(C(D.value)))}),s.forEach((D,x)=>{let R=D.type;(!R.typeName&&R.id||de(R))&&$.push(`rtparam${x}_${ie(A(R))}_id${R.id}`)});let L=$.join("_"),b=[];for(let D of o.implicitParameters)if(D.isEffectRowSpread){let x=D.type;if(M(x)){if(t.forallArgs){for(let R=0;R<o.forallParameters.length;R++)if(o.forallParameters[R].label===x.name&&R<t.forallArgs.length){let J=t.forallArgs[R].value;P(J)&&at(J.value)&&(x=J.value);break}}if(M(x)&&x.resolvedConcreteType&&at(x.resolvedConcreteType)&&(x=x.resolvedConcreteType),M(x)){let R=j(_,x.name);if(R.length>0){let J=R[R.length-1].value?.[0];J&&P(J)&&at(J.value)&&(x=J.value)}}}at(x)&&b.push(...x.implicitParameters)}else $e(D.type)&&b.push(D);let V=Vr({forallParameters:[],parameters:s,implicitParameters:b.length>0?b:void 0,variadicParameter:void 0,return_:{...o.return,type:p},parametersFrame:_.frames[_.frames.length-1],env:o.env,SelfType:o.SelfType}),I={...e,specializedType:V,body:g,isControlFunction:e.isControlFunction||or(g),funcId:`${e.funcId}_${L}`,funcName:`${e.funcName}_${L}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},U={funcId:e.funcId,compileTimeArgValues:a,runtimeParameterTypes:l,specializedFunction:I,env:g.$.env};return e.specializedFunctionCaches=[...e.specializedFunctionCaches,U],I}function Fh({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??zn(),s=ie(A(o)),l=e.specializedFunctionCaches.find(y=>y.specializedFunction.funcId===`${e.funcId}_ctl_${s}`);if(l)return l.specializedFunction;let u=Re(t);for(let y of n.frames)for(let v of y.variables){if(!v.isCompileTimeOnly||j(u,v.name).length>0)continue;let{env:$}=me({env:u,variable:{...v},allowVariableShadowing:!0});u=$}for(let y of i.forallParameters){let v=o,{env:T}=me({env:u,variable:{name:y.label,type:y.type,isCompileTimeOnly:!0,value:[te(v)],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});u=T}let _=Se(e.body),c={...r,expectedType:void 0,enclosingFunctionReturnType:a,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:i,value:e,evaluationEnv:u},functionReturnImplConcreteType:[]},p=ni({expr:_,env:u,context:c}),f={...e,body:p,isControlFunction:e.isControlFunction||or(p),funcId:`${e.funcId}_ctl_${s}`,funcName:`${e.funcName??e.funcId}_ctl_${s}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},d=new Set(i.forallParameters.map(y=>y.type)),h=y=>M(y)&&d.has(y)?o:y,g=Vr({forallParameters:[],parameters:i.parameters.map(y=>({...y,type:h(y.type)})),implicitParameters:i.implicitParameters.length>0?i.implicitParameters:void 0,variadicParameter:void 0,return_:{...i.return,type:h(i.return.type)},parametersFrame:u.frames[u.frames.length-1],env:i.env,SelfType:i.SelfType});return f.specializedType=g,e.specializedFunctionCaches=[...e.specializedFunctionCaches,{funcId:e.funcId,compileTimeArgValues:[],runtimeParameterTypes:[],specializedFunction:f,env:p.$?.env??u}],f}function Lh({returnType:e,expr:t,env:n,context:r}){if(r.isEvaluatingFunctionType||r.expectedType)return;let i=gs(e);for(let o of i){if(Fe(o)||Ht(o)||o.resolvedConcreteType||o.requiredTraits&&o.requiredTraits.length>0)continue;if(!j(n,o.name).length){let s=hn(n,()=>!0),l=!1;for(let u of s)if(P(u.value?.[0])){let _=u.value[0].value,c=gs(_);for(let p of c)if(p.name===o.name){l=!0;break}if(l)break}if(l)continue;throw m({token:t?.token??ue,errorMessage:`Failed to infer the function call return type.
11234
+ Please use explicit using() to disambiguate.`});let je=we[we.length-1],Ue=je.value?.[0];if(!Ue)throw m({token:r?.token??e?.token??ue,errorMessage:`The "given" variable "${je.name}" has no compile-time value.`});R.push({value:Ue,parameterType:le,argType:je.type});let{env:Je}=me({env:b,variable:{name:ee.label,type:le,isCompileTimeOnly:!0,isImplicit:!0,value:[Ue],token:ee.exprs.labelExpr?.token??ue,initializedAtToken:ee.exprs.labelExpr?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});b=Je}}let Q={args:p,forallArgs:c,implicitArgs:R,variadicArgs:D},J;if(n.return.isCompileTimeOnly)if(u)J=X(I,{variableName:n.return.label,env:n.env,context:a});else if(ne(t)){let{value:ie,callerEnv:ee,calleeEnv:_e}=po({functionCalleeExpr:r,functionType:n,functionValue:t,argValues:Q,callerEnv:o,calleeEnv:b,context:{...a}});J=ie,I=ie.type,o=ee,b=_e}else{let ie=Ke(I)&&I.level===0,ee=`${n.id}_return_sometype`;if(ie)if(a.expectedType?.type)J=te(a.expectedType.type);else if(a.isEvaluatingFunctionType){let _e=Ln(I,n.return.label,{id:ee,env:b,context:a});_e.functionApplication=e;let le=Ut(b,_e);J=te(le)}else throw m({token:e?.token??r?.token??ue,errorMessage:"Cannot infer comptime return type. Please provide the expected type."});else J=X(I,{variableName:n.return.label,env:n.env,context:a})}Lh({returnType:I,env:b,expr:e,context:a});let G,H=a.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"&&a.isEvaluatingFunctionBodyOrAsyncBlock.value&&ne(a.isEvaluatingFunctionBodyOrAsyncBlock.value)&&t&&ne(t)&&a.isEvaluatingFunctionBodyOrAsyncBlock.value.funcId===t.funcId,oe=Q.implicitArgs?.some(ie=>ce(ie.value)),ge=oe&&!Q.implicitArgs?.some(ie=>ce(ie.value)&&!$e(ie.parameterType)),q=Q.args.some(ie=>ie.argType&&M(ie.argType)),Z=ge&&q,se=(()=>{if(!oe||!n.implicitParameters.some(le=>le.isEffectRowSpread))return!1;let ee=0;for(let le of n.implicitParameters)le.isEffectRowSpread||ee++;let _e=Q.implicitArgs??[];for(let le=0;le<ee&&le<_e.length;le++)if(ce(_e[le].value))return!1;return!0})(),De=Wn(n)&&!fr(n)&&n.implicitParameters.some(ie=>$e(ie.type)?ie.type.fields.some(ee=>W(ee.type)&&ee.type.forallParameters.length===0):!!ie.isEffectRowSpread);if(!l&&!De&&t&&ne(t)&&!t.isControlFunction&&Wn(n)&&!H&&(!oe||Z||se)){if(G=wh({originalFunction:t,argValues:Q,calleeEnv:b,callerEnv:o,context:a}),G&&M(I)){let ie=G.body?.$?.type;ie&&!M(ie)&&(I=ie,G.specializedType&&(G.specializedType={...G.specializedType,return:{...G.specializedType.return,type:ie}}))}if(G){let ie=new Set,ee=0;for(let _e=0;_e<n.parameters.length;_e++)if(!n.parameters[_e].isCompileTimeOnly){let ae=Q.args[_e]?.value;ae&&ne(ae)&&ae.type.implicitParameters.some(ye=>W(ye.type)||$e(ye.type))&&ie.add(ee),ee++}if(ie.size>0)for(let _e=f.length-1;_e>=0;_e--)ie.has(_e)&&f.splice(_e,1)}}if(!l&&t&&ne(t)&&t.isControlFunction&&n.forallParameters.length>0&&!G&&(G=Fh({originalFunction:t,argValues:Q,calleeEnv:b,callerEnv:o,context:a}),G&&M(I))){let ie=G.body?.$?.type;ie&&!M(ie)&&(I=ie,G.specializedType&&(G.specializedType={...G.specializedType,return:{...G.specializedType.return,type:ie}}))}let he=to(o),Xe;if(he.length>0){let ie=bh({variablesToDrop:he,env:o,context:a});Xe=ie.deferredDropExpressions,o=ie.env}return{returnType:I,calleeEnv:b,callerEnv:o,pathCollection:x,argValues:Q,returnValue:J,specializedFunctionValue:G,runtimeArgExprsInOrder:f,deferredDropExpressions:Xe}}function wh({originalFunction:e,argValues:t,calleeEnv:n,callerEnv:r,context:i}){if(os){Fr.specializeCount++;let D=e.funcName??e.funcId;Fr.specializeNames.set(D,(Fr.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,x)=>{let R=t.args[x];if(D.isCompileTimeOnly)R.value&&a.push(R.value);else if(R.value&&ne(R.value)&&R.value.type.implicitParameters.some(J=>W(J.type)||$e(J.type)))R.value&&a.push(R.value);else{let G=M(R.argType)&&R.argType.resolvedConcreteType&&!Fe(R.argType)?R.argType.resolvedConcreteType:R.argType;s.push({...D,type:G})}});let l=s.map(D=>D.type),u=e.specializedFunctionCaches.find(D=>D.compileTimeArgValues.length===a.length&&D.compileTimeArgValues.every((Q,J)=>{let G=a[J];return xt({value:Q,env:D.env},{value:G,env:r})})?D.runtimeParameterTypes.length===l.length&&D.runtimeParameterTypes.every((Q,J)=>{let G=l[J];return Y({type:Q,env:D.env},{type:G,env:r},!0)}):!1);if(u)return os&&Fr.cacheHitCount++,u.specializedFunction;os&&Fr.cacheMissCount++;let _=n;for(let D of r.frames)for(let x of D.variables){if(!x.isCompileTimeOnly||j(_,x.name).length>0)continue;let{env:Q}=me({env:_,variable:{...x},allowVariableShadowing:!0});_=Q}for(let D of s){let x=j(_,D.label);if(x.length>0){let R=x[x.length-1],Q={...R,value:void 0};_=Ge(_,R,Q)}}let c=Se(e.body),{returnType:p,calleeEnv:f}=Fi({functionType:o,calleeEnv:_,context:{...i,isEvaluatingFunctionType:!0},functionCalleeExpr:void 0});_=f;let d=i.enclosingFunctionReturnType,h=t.implicitArgs?.some(D=>ne(D.value)&&D.value.isControlFunction||We(D.value)&&jf(D.value.type,D.value))??!1,g=Tt({expr:c,env:_,context:{...i,expectedType:{type:p,env:_},isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:o,value:e,evaluationEnv:_},isEvaluatingLoopBody:void 0,capturedVariables:void 0,functionReturnImplConcreteType:[],hasControlFunctionImplicitParams:h,...d?{enclosingFunctionReturnType:d}:{}},variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0});if(!g.$)throw m({token:e.body.token,errorMessage:"Failed to evaluate function body for specialization."});let y=[],v=0;for(let D=0;D<o.implicitParameters.length;D++){let x=o.implicitParameters[D];if(W(x.type)){let R=t.implicitArgs?.[v];(R&&ne(R.value)?R.value:void 0)?.isControlFunction&&y.push({handlerArgIndex:v,label:x.label,type:x.type,fromSpread:!1}),v+=1}else if(x.isEffectRowSpread){let R=x.type;if(M(R)){let J=j(_,x.label).at(-1)?.value?.[0];if(J&&P(J)&&at(J.value))R=J.value;else{let G=Ut(_,R);G&&(R=G)}}if(at(R)){for(let Q=0;Q<R.implicitParameters.length;Q++){let J=R.implicitParameters[Q];if(W(J.type)){let G=t.implicitArgs?.[v+Q];(G&&ne(G.value)?G.value:void 0)?.isControlFunction&&y.push({handlerArgIndex:v+Q,label:J.label,type:J.type,fromSpread:!0})}else if($e(J.type)){let G=t.implicitArgs?.[v+Q],H=G&&We(G.value)?G.value:void 0,oe=[],ge=(q,Z,se)=>{for(let Ae=0;Ae<q.fields.length;Ae++){let De=q.fields[Ae];if(W(De.type)){let he=se?.fields[Ae];if(he&&ne(he)&&he.isControlFunction){let Xe=he.specializedType??De.type;oe.push({path:[...Z,De.label],type:Xe})}}else if($e(De.type)){let he=se?.fields[Ae];ge(De.type,[...Z,De.label],he&&We(he)?he:void 0)}}};ge(J.type,[],H);for(let q of oe)y.push({handlerArgIndex:v+Q,label:J.label,type:q.type,fromSpread:!0,effectFieldPath:q.path})}}v+=R.implicitParameters.length}else v+=1}else if($e(x.type)){let R=[],Q=t.implicitArgs?.[v],J=(G,H,oe)=>{for(let ge=0;ge<G.fields.length;ge++){let q=G.fields[ge];if(W(q.type)){let Z=oe?.fields[ge];if(Z&&ne(Z)&&Z.isControlFunction){let se=Z.specializedType??q.type;R.push({path:[...H,q.label],type:se})}}else if($e(q.type)){let Z=oe?.fields[ge];J(q.type,[...H,q.label],Z&&We(Z)?Z:void 0)}}};J(x.type,[],Q&&We(Q.value)?Q.value:void 0);for(let G of R)y.push({handlerArgIndex:v,label:x.label,type:G.type,fromSpread:!1,effectFieldPath:G.path});v+=1}else v+=1}let T=[];for(let D of y){let x=Yf(g,D.label,D.type,!0,D.effectFieldPath);if(x.hasEffects){let R=t.implicitArgs?.[D.handlerArgIndex],Q,J=D.effectFieldPath;if(R&&ne(R.value))Q=R.value;else if(R&&We(R.value)&&J&&J.length>0){let G=R.value;for(let H of J){if(!We(G)){G=void 0;break}let oe=G.type.fields.findIndex(ge=>ge.label===H);if(oe<0||!G.fields[oe]){G=void 0;break}G=G.fields[oe]}G&&ne(G)&&(Q=G)}if(Q){let G=Q,H=D.type,oe=!G.body.$;if(!oe&&G.isControlFunction&&F(G.body)&&G.body.args.length>0&&!G.body.args[0]?.$&&(oe=!0),oe&&W(H)&&H.forallParameters.length>0&&x.effectCallPoints.length>0){let ge=new Map,q=H.return.type,Z=x.effectCallPoints[0].operationResultType;if(M(q)&&ge.set(q.name,Z),ge.size===0&&H.forallParameters.length===1){let ie=H.forallParameters[0];ge.set(ie.label,Z)}let se=Se(G.body),Ae=G.body.$?.env??_;Ae=Re(Ae);for(let ie of H.forallParameters){let ee=ge.get(ie.label);ee&&(Ae=me({env:Ae,variable:{name:ie.label,type:ie.type,isCompileTimeOnly:!0,value:[te(ee)],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0}).env)}let De=G.specializedType??G.type,he=G.definitionSiteEnclosingFunctionType?.return.type??zn(),Xe={...i,expectedType:void 0,enclosingFunctionReturnType:he,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:De,value:G,evaluationEnv:Ae}};try{let ie=ni({expr:se,env:Ae,context:Xe}),ee=De.parameters.map(ae=>{if(ae.isCompileTimeOnly)return ae;if(M(ae.type)){let ye=ge.get(ae.type.name);if(ye)return{...ae,type:ye}}return ae}),_e=De.return.type;if(M(_e)){let ae=ge.get(_e.name);ae&&(_e=ae)}let le={...De,parameters:ee,return:{...De.return,type:_e}},be={...G,body:ie,specializedType:le};x.handlerValue=be,x.effectParameterType=le;for(let ae of x.effectCallPoints)ae.isTransitiveEffectCall&&(ae.operationArgTypes=ae.operationArgTypes.map(ye=>M(ye)?ge.get(ye.name)??ye:ye))}catch(ie){if(F(G.body)&&G.body.args.length>0&&!G.body.args[0]?.$)throw ie;x.handlerValue=G}}else x.handlerValue=G}else R&&(x.handlerValue=R.value);T.push({analysis:x,ctlParam:D})}}if(T.length===1)g.$.effectAnalysis=T[0].analysis;else if(T.length>1){let D=[],x=new Map,R=new Map,Q=[];for(let H=0;H<T.length;H++){let{analysis:oe}=T[H];Q.push({effectParameterName:oe.effectParameterName,effectParameterType:oe.effectParameterType,effectFieldPath:oe.effectFieldPath,handlerValue:oe.handlerValue,operationArgTypes:oe.effectCallPoints.length>0?oe.effectCallPoints[0].operationArgTypes:[],operationResultType:oe.effectCallPoints.length>0?oe.effectCallPoints[0].operationResultType:{tag:"unit"}});for(let ge of oe.effectCallPoints)D.push({...ge,effectIndex:H});for(let ge of oe.capturedVariables)x.has(ge.id)||x.set(ge.id,ge);for(let[ge,q]of oe.variableIdRemapping)R.set(ge,q)}if(F(g)&&E(g,S.begin)){let H=g.args,oe=new Map;for(let q=0;q<H.length;q++)oe.set(H[q],q);let ge=q=>{for(let Z=0;Z<H.length;Z++)if(Wl(H[Z],q.expr))return Z;return 999};D.sort((q,Z)=>ge(q)-ge(Z))}for(let H=0;H<D.length;H++)D[H].index=H;let J=T[0].analysis,G={effectCallPoints:D,capturedVariables:Array.from(x.values()),hasEffects:!0,variableIdRemapping:R,effectParameterName:J.effectParameterName,effectParameterType:J.effectParameterType,effectFieldPath:J.effectFieldPath,handlerValue:J.handlerValue,effectHandlerInfos:Q};g.$.effectAnalysis=G}let $=[],C=D=>{if(P(D)){let x=D.value;if(!x.typeName&&x.id)return`${Me(D)}_id${x.id}`}return ne(D)?`fn_${D.funcId}`:Me(D)};o.forallParameters.forEach((D,x)=>{if(x<t.forallArgs.length){let R=t.forallArgs[x];$.push(re(C(R.value)))}else{let R=D.label,Q=j(n,R);Q.length>0&&Q[Q.length-1]?.value?.[0]?$.push(re(C(Q[Q.length-1].value[0]))):$.push("unknown")}}),o.parameters.forEach((D,x)=>{if(D.isCompileTimeOnly&&x<t.args.length){let R=t.args[x];R?$.push(re(C(R.value))):$.push("unknown")}}),t.implicitArgs&&t.implicitArgs.forEach(D=>{$.push(re(C(D.value)))}),s.forEach((D,x)=>{let R=D.type;(!R.typeName&&R.id||de(R))&&$.push(`rtparam${x}_${re(A(R))}_id${R.id}`)});let L=$.join("_"),b=[];for(let D of o.implicitParameters)if(D.isEffectRowSpread){let x=D.type;if(M(x)){if(t.forallArgs){for(let R=0;R<o.forallParameters.length;R++)if(o.forallParameters[R].label===x.name&&R<t.forallArgs.length){let J=t.forallArgs[R].value;P(J)&&at(J.value)&&(x=J.value);break}}if(M(x)&&x.resolvedConcreteType&&at(x.resolvedConcreteType)&&(x=x.resolvedConcreteType),M(x)){let R=j(_,x.name);if(R.length>0){let J=R[R.length-1].value?.[0];J&&P(J)&&at(J.value)&&(x=J.value)}}}at(x)&&b.push(...x.implicitParameters)}else $e(D.type)&&b.push(D);let V=Vr({forallParameters:[],parameters:s,implicitParameters:b.length>0?b:void 0,variadicParameter:void 0,return_:{...o.return,type:p},parametersFrame:_.frames[_.frames.length-1],env:o.env,SelfType:o.SelfType}),I={...e,specializedType:V,body:g,isControlFunction:e.isControlFunction||or(g),funcId:`${e.funcId}_${L}`,funcName:`${e.funcName}_${L}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},U={funcId:e.funcId,compileTimeArgValues:a,runtimeParameterTypes:l,specializedFunction:I,env:g.$.env};return e.specializedFunctionCaches=[...e.specializedFunctionCaches,U],I}function Fh({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??zn(),s=re(A(o)),l=e.specializedFunctionCaches.find(y=>y.specializedFunction.funcId===`${e.funcId}_ctl_${s}`);if(l)return l.specializedFunction;let u=Re(t);for(let y of n.frames)for(let v of y.variables){if(!v.isCompileTimeOnly||j(u,v.name).length>0)continue;let{env:$}=me({env:u,variable:{...v},allowVariableShadowing:!0});u=$}for(let y of i.forallParameters){let v=o,{env:T}=me({env:u,variable:{name:y.label,type:y.type,isCompileTimeOnly:!0,value:[te(v)],token:ue,initializedAtToken:ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});u=T}let _=Se(e.body),c={...r,expectedType:void 0,enclosingFunctionReturnType:a,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"function-body",type:i,value:e,evaluationEnv:u},functionReturnImplConcreteType:[]},p=ni({expr:_,env:u,context:c}),f={...e,body:p,isControlFunction:e.isControlFunction||or(p),funcId:`${e.funcId}_ctl_${s}`,funcName:`${e.funcName??e.funcId}_ctl_${s}`,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},d=new Set(i.forallParameters.map(y=>y.type)),h=y=>M(y)&&d.has(y)?o:y,g=Vr({forallParameters:[],parameters:i.parameters.map(y=>({...y,type:h(y.type)})),implicitParameters:i.implicitParameters.length>0?i.implicitParameters:void 0,variadicParameter:void 0,return_:{...i.return,type:h(i.return.type)},parametersFrame:u.frames[u.frames.length-1],env:i.env,SelfType:i.SelfType});return f.specializedType=g,e.specializedFunctionCaches=[...e.specializedFunctionCaches,{funcId:e.funcId,compileTimeArgValues:[],runtimeParameterTypes:[],specializedFunction:f,env:p.$?.env??u}],f}function Lh({returnType:e,expr:t,env:n,context:r}){if(r.isEvaluatingFunctionType||r.expectedType)return;let i=gs(e);for(let o of i){if(Fe(o)||Ht(o)||o.resolvedConcreteType||o.requiredTraits&&o.requiredTraits.length>0)continue;if(!j(n,o.name).length){let s=hn(n,()=>!0),l=!1;for(let u of s)if(P(u.value?.[0])){let _=u.value[0].value,c=gs(_);for(let p of c)if(p.name===o.name){l=!0;break}if(l)break}if(l)continue;throw m({token:t?.token??ue,errorMessage:`Failed to infer the function call return type.
11235
11235
  Please consider providing the expected type.`})}}}function Wl(e,t){if(e===t)return!0;if(e.tag==="FnCall"){if(Wl(e.func,t))return!0;for(let n of e.args)if(Wl(n,t))return!0}return!1}function Kf({concreteType:e,env:t}){let n=[];if(e.trait)for(let i of e.trait.fields){if(i.label===""&&i.assignedValue&&gt(i.assignedValue)){let o=i.assignedValue,a=o.type,s=a.fields.findIndex(l=>l.label==="index"&&W(l.type));if(s>=0){let l=a.fields[s];if(W(l.type)){let u=o.fields[s],_=l.type;ne(u)&&u.specializedType&&(_=u.specializedType),n.push({type:_,value:u})}}}i.label==="index"&&W(i.type)&&n.push({type:i.type,value:i.assignedValue})}let r=Bn({concreteType:e,methodName:"index",env:t});return n.push(...r),n}function Ah({concreteType:e,argType:t,env:n}){let r=Kf({concreteType:e,env:n});if(r.length!==0)for(let i of r){let o=i.type;if(o.parameters.length!==2)continue;let a=o.parameters[0],s=o.parameters[1];if(Ce(a.type)&&Y({type:s.type,env:n},{type:t,env:n})&&Ce(o.return.type))return i}}function ql({expr:e,valueType:t,argExprs:n,callerEnv:r,context:i}){if(n.length!==1)throw m({token:e.func.token,errorMessage:`Index trait expects exactly 1 argument, got ${n.length}.`});let o=n[0],a=N({expr:o,env:r,context:{...i,expectedType:void 0}});if(!a.$)throw m({token:o.token,errorMessage:`Failed to evaluate index argument:
11236
11236
  ${w(o)}`});r=a.$.env;let s=a.$.type,l=Ah({concreteType:t,argType:s,env:r});if(!l)throw m({token:e.func.token,errorMessage:`Type "${A(t)}" does not implement Index(${A(s)}).`});let u=l.type,_=u.return.type;if(!Ce(_))throw m({token:e.func.token,errorMessage:`Index method must return a pointer type, got: ${A(_)}`});let c=_.childType,p=X(c,{env:r,context:i});return ce(p)&&(p.isRuntimeOnly=!0),{value:p,type:c,ptrType:_,indexMethodType:u,indexMethodValue:l.value,callerEnv:r}}function Yl({concreteType:e,argExprs:t,callerEnv:n,_context:r}){if(t.length!==1)return!1;if(ke(e)||qe(e))return!0;try{return Kf({concreteType:e,env:n}).length>0}catch{return!1}}function Xf({expr:e,env:t,context:n}){let r=e.args[0],i=N({expr:r,env:t,context:{...n}});if(!i.$)throw m({token:r.token,errorMessage:`Failed to evaluate the argument expression for Iso:
11237
11237
  ${w(r)}`});if(t=i.$.env,!P(i.$.value))throw m({token:r.token,errorMessage:`Iso expects a type as argument, but got:
@@ -11441,7 +11441,7 @@ ${A(r)}${Ie(r)?`
11441
11441
  Use 'dyn((x) => expr)' for dynamic dispatch`:""}`});let l=o?"=>":"->",u=o?"closure":"function";if(!E(e,l,2))throw m({token:e.token,errorMessage:`Expected ${l} for anonymous ${u}, got:
11442
11442
  ${w(e)}`});let _=e.args[0],c=e.args[1],p=[];F(_)&&E(_,S.tuple)?p=_.args:p=[_];let f=[],d=[],h=[];for(let q=0;q<p.length;q++){let Z=p[q];if(F(Z)&&E(Z,S.forall)){if(q!==0)throw m({token:Z.token,errorMessage:"forall(...) must be the first parameter expression"});f=Z.args}else F(Z)&&E(Z,S.using)?d=Z.args:h.push(Z)}if(h.length!==i.parameters.length)throw m({token:e.token,errorMessage:`Expected ${i.parameters.length} regular parameters, got ${h.length}`});let g=t;t=Re(C_(t));for(let q=0;q<f.length;q++){let Z=f[q],se=i.forallParameters[q];if(!B(Z))throw m({token:Z.token,errorMessage:`Expected parameter name for forall parameter, got ${w(Z)}`});let Ae=Z.token.value;if(Ae!==se.label)throw m({token:Z.token,errorMessage:`Forall parameter name must match expected name.
11443
11443
  Expected: "${se.label}"
11444
- Got: "${Ae}"`})}for(let q=0;q<i.forallParameters.length;q++){let Z=f[q],se=i.forallParameters[q],{env:Ae}=me({env:t,variable:{name:se.label,type:se.type,isCompileTimeOnly:se.isCompileTimeOnly,value:[X(se.type,{variableName:se.label,env:t,context:n})],token:Z?.token??ue,initializedAtToken:Z?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});t=Ae,Z&&(Z.$={env:t,type:se.type,value:X(se.type,{variableName:se.label,env:t,context:n}),pathCollection:[]})}let y=i.implicitParameters.some(q=>q.isEffectRowSpread),v,T;if(y&&d.length>0){v=[];for(let q of d)if(F(q)&&E(q,":",2)){let Z=q.args[0],se=q.args[1];if(!B(Z))throw m({token:Z.token,errorMessage:`Expected identifier for effect name, got ${w(Z)}`});let Ae=Z.token.value,De=N({expr:Se(se),env:g,context:{...n,isEvaluatingFunctionType:!0}});if(!De.$?.value||!P(De.$.value))throw m({token:se.token,errorMessage:`Expected a type for effect parameter "${Ae}", got ${w(se)}`});let he=De.$.value.value;v.push({label:Ae,type:he,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:q,labelExpr:Z,typeExpr:se,defaultValueExpr:void 0}})}else if(B(q)){let Z=q.token.value,Ae=j(g,Z).at(-1);if(!Ae)throw m({token:q.token,errorMessage:`Variable "${Z}" not found. Cannot infer type for using() parameter.`});v.push({label:Z,type:Ae.type,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:q,labelExpr:q,typeExpr:q,defaultValueExpr:void 0}})}else throw m({token:q.token,errorMessage:`Expected "name : Type" or identifier in using(), got ${w(q)}`});T=Dr(v);for(let q of i.implicitParameters)q.isEffectRowSpread&&M(q.type)&&q.type.isEffectsRow&&(q.type.resolvedConcreteType=T)}else if(d.length>0){let q=[];for(let se of d)if(F(se)&&E(se,":",2)){let Ae=se.args[0],De=se.args[1];if(!B(Ae))throw m({token:Ae.token,errorMessage:`Expected identifier for effect name, got ${w(Ae)}`});let he=N({expr:Se(De),env:g,context:{...n,isEvaluatingFunctionType:!0}});if(!he.$?.value||!P(he.$.value))throw m({token:De.token,errorMessage:`Expected a type for effect parameter "${Ae.token.value}", got ${w(De)}`});q.push({name:Ae.token.value,type:he.$.value.value,nameExpr:Ae})}else if(B(se))q.push({name:se.token.value,type:void 0,nameExpr:se});else throw m({token:se.token,errorMessage:`Expected "name : Type" or identifier in using(), got ${w(se)}`});if(q.some(se=>se.type!==void 0)){if(q.length!==i.implicitParameters.length)throw m({token:e.token,errorMessage:`Effect row mismatch: closure declares ${q.length} effects, but call site resolved ${i.implicitParameters.length} effects.`});let se=new Set,Ae=[];for(let De=0;De<q.length;De++){let he=q[De];if(!he.type){Ae.push({...i.implicitParameters[De],label:he.name,exprs:{...i.implicitParameters[De].exprs,expr:he.nameExpr,labelExpr:he.nameExpr}}),se.add(De);continue}let Xe=!1;for(let re=0;re<i.implicitParameters.length;re++){if(se.has(re))continue;let ee=i.implicitParameters[re];if(Y({type:he.type,env:g},{type:ee.type,env:g})){Ae.push({...ee,label:he.name,exprs:{...ee.exprs,expr:he.nameExpr,labelExpr:he.nameExpr}}),se.add(re),Xe=!0;break}}if(!Xe)throw m({token:he.nameExpr.token,errorMessage:`Effect row type mismatch for "${he.name}": closure declares ${A(he.type)}, but no matching resolved effect found.`})}v=Ae,T=Dr(v)}else{if(d.length!==i.implicitParameters.length)throw m({token:e.token,errorMessage:`Expected ${i.implicitParameters.length} implicit parameters in using(...), got ${d.length}`});v=i.implicitParameters}}else v=i.implicitParameters;let $=[];for(let q=0;q<v.length;q++){let Z=v[q],se=T?Z.exprs?.labelExpr:d[q],Ae=Z.label;se&&B(se)&&(Ae=se.token.value);let De;if(W(Z.type)){let _e=i.implicitParameters[q]?.label,le=[Z.label];_e&&_e!==Z.label&&le.push(_e);for(let be of le){let ae=j(g,be),ye=ae[ae.length-1];if(ye?.value&&ye.value.length>0){let we=ye.value[0];if(we&&ne(we)){De=we;break}}}if(!De){let ae=hn(g,ye=>ye.isImplicit===!0&&ye.isCompileTimeOnly===!0&&ne(ye.value?.[0])&&Y({type:Z.type,env:g},{type:ye.type,env:g})).at(-1);ae?.value?.[0]&&ne(ae.value[0])&&(De=ae.value[0])}}let he=De||X(Z.type,{variableName:Ae,env:t,context:n}),Xe=n.isInsideIoAsyncCall&&o&&W(Z.type)&&!De;if(Xe&&$.push({name:Ae,type:Z.type,token:se?.token??ue}),!Xe&&n.isInsideIoAsyncCall&&o&&$e(Z.type)&&!De){let _e=Z.type;for(let le of _e.fields)W(le.type)&&$.push({name:le.label,type:le.type,token:se?.token??ue})}let{env:ee}=me({env:t,variable:{name:Ae,type:Z.type,isCompileTimeOnly:!Xe,isImplicit:!0,value:Xe?void 0:[he],token:se?.token??ue,initializedAtToken:se?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:!1,isEffectParam:Xe||void 0},allowVariableShadowing:!0});t=ee,se&&(se.$={env:t,type:Z.type,value:Xe?void 0:he,pathCollection:[]})}for(let q=0;q<h.length;q++){let Z=h[q],se=i.parameters[q];if(se.isCompileTimeOnly){if(!B(Z))throw m({token:Z.token,errorMessage:`Expected parameter name for compile-time parameter, got ${w(Z)}`});let Xe=Z.token.value;if(Xe!=="_"&&Xe!==se.label)throw m({token:Z.token,errorMessage:`Compile-time parameter name must match expected name.
11444
+ Got: "${Ae}"`})}for(let q=0;q<i.forallParameters.length;q++){let Z=f[q],se=i.forallParameters[q],{env:Ae}=me({env:t,variable:{name:se.label,type:se.type,isCompileTimeOnly:se.isCompileTimeOnly,value:[X(se.type,{variableName:se.label,env:t,context:n})],token:Z?.token??ue,initializedAtToken:Z?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:!1},allowVariableShadowing:!0});t=Ae,Z&&(Z.$={env:t,type:se.type,value:X(se.type,{variableName:se.label,env:t,context:n}),pathCollection:[]})}let y=i.implicitParameters.some(q=>q.isEffectRowSpread),v,T;if(y&&d.length>0){v=[];for(let q of d)if(F(q)&&E(q,":",2)){let Z=q.args[0],se=q.args[1];if(!B(Z))throw m({token:Z.token,errorMessage:`Expected identifier for effect name, got ${w(Z)}`});let Ae=Z.token.value,De=N({expr:Se(se),env:g,context:{...n,isEvaluatingFunctionType:!0}});if(!De.$?.value||!P(De.$.value))throw m({token:se.token,errorMessage:`Expected a type for effect parameter "${Ae}", got ${w(se)}`});let he=De.$.value.value;v.push({label:Ae,type:he,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:q,labelExpr:Z,typeExpr:se,defaultValueExpr:void 0}})}else if(B(q)){let Z=q.token.value,Ae=j(g,Z).at(-1);if(!Ae)throw m({token:q.token,errorMessage:`Variable "${Z}" not found. Cannot infer type for using() parameter.`});v.push({label:Z,type:Ae.type,isCompileTimeOnly:!0,isImplicit:!0,isOwningTheRcValue:!1,isQuote:!1,exprs:{expr:q,labelExpr:q,typeExpr:q,defaultValueExpr:void 0}})}else throw m({token:q.token,errorMessage:`Expected "name : Type" or identifier in using(), got ${w(q)}`});T=Dr(v);for(let q of i.implicitParameters)q.isEffectRowSpread&&M(q.type)&&q.type.isEffectsRow&&(q.type.resolvedConcreteType=T)}else if(d.length>0){let q=[];for(let se of d)if(F(se)&&E(se,":",2)){let Ae=se.args[0],De=se.args[1];if(!B(Ae))throw m({token:Ae.token,errorMessage:`Expected identifier for effect name, got ${w(Ae)}`});let he=N({expr:Se(De),env:g,context:{...n,isEvaluatingFunctionType:!0}});if(!he.$?.value||!P(he.$.value))throw m({token:De.token,errorMessage:`Expected a type for effect parameter "${Ae.token.value}", got ${w(De)}`});q.push({name:Ae.token.value,type:he.$.value.value,nameExpr:Ae})}else if(B(se))q.push({name:se.token.value,type:void 0,nameExpr:se});else throw m({token:se.token,errorMessage:`Expected "name : Type" or identifier in using(), got ${w(se)}`});if(q.some(se=>se.type!==void 0)){if(q.length!==i.implicitParameters.length)throw m({token:e.token,errorMessage:`Effect row mismatch: closure declares ${q.length} effects, but call site resolved ${i.implicitParameters.length} effects.`});let se=new Set,Ae=[];for(let De=0;De<q.length;De++){let he=q[De];if(!he.type){Ae.push({...i.implicitParameters[De],label:he.name,exprs:{...i.implicitParameters[De].exprs,expr:he.nameExpr,labelExpr:he.nameExpr}}),se.add(De);continue}let Xe=!1;for(let ie=0;ie<i.implicitParameters.length;ie++){if(se.has(ie))continue;let ee=i.implicitParameters[ie];if(Y({type:he.type,env:g},{type:ee.type,env:g})){Ae.push({...ee,label:he.name,exprs:{...ee.exprs,expr:he.nameExpr,labelExpr:he.nameExpr}}),se.add(ie),Xe=!0;break}}if(!Xe)throw m({token:he.nameExpr.token,errorMessage:`Effect row type mismatch for "${he.name}": closure declares ${A(he.type)}, but no matching resolved effect found.`})}v=Ae,T=Dr(v)}else{if(d.length!==i.implicitParameters.length)throw m({token:e.token,errorMessage:`Expected ${i.implicitParameters.length} implicit parameters in using(...), got ${d.length}`});v=i.implicitParameters}}else v=i.implicitParameters;let $=[];for(let q=0;q<v.length;q++){let Z=v[q],se=T?Z.exprs?.labelExpr:d[q],Ae=Z.label;se&&B(se)&&(Ae=se.token.value);let De;if(W(Z.type)){let _e=i.implicitParameters[q]?.label,le=[Z.label];_e&&_e!==Z.label&&le.push(_e);for(let be of le){let ae=j(g,be),ye=ae[ae.length-1];if(ye?.value&&ye.value.length>0){let we=ye.value[0];if(we&&ne(we)){De=we;break}}}if(!De){let ae=hn(g,ye=>ye.isImplicit===!0&&ye.isCompileTimeOnly===!0&&ne(ye.value?.[0])&&Y({type:Z.type,env:g},{type:ye.type,env:g})).at(-1);ae?.value?.[0]&&ne(ae.value[0])&&(De=ae.value[0])}}let he=De||X(Z.type,{variableName:Ae,env:t,context:n}),Xe=n.isInsideIoAsyncCall&&o&&W(Z.type)&&!De;if(Xe&&$.push({name:Ae,type:Z.type,token:se?.token??ue}),!Xe&&n.isInsideIoAsyncCall&&o&&$e(Z.type)&&!De){let _e=Z.type;for(let le of _e.fields)W(le.type)&&$.push({name:le.label,type:le.type,token:se?.token??ue})}let{env:ee}=me({env:t,variable:{name:Ae,type:Z.type,isCompileTimeOnly:!Xe,isImplicit:!0,value:Xe?void 0:[he],token:se?.token??ue,initializedAtToken:se?.token??ue,consumedAtToken:void 0,isOwningTheRcValue:!1,isEffectParam:Xe||void 0},allowVariableShadowing:!0});t=ee,se&&(se.$={env:t,type:Z.type,value:Xe?void 0:he,pathCollection:[]})}for(let q=0;q<h.length;q++){let Z=h[q],se=i.parameters[q];if(se.isCompileTimeOnly){if(!B(Z))throw m({token:Z.token,errorMessage:`Expected parameter name for compile-time parameter, got ${w(Z)}`});let Xe=Z.token.value;if(Xe!=="_"&&Xe!==se.label)throw m({token:Z.token,errorMessage:`Compile-time parameter name must match expected name.
11445
11445
  Expected: "${se.label}"
11446
11446
  Got: "${Xe}"`})}let Ae=Z.token.value,De=se.label,{env:he}=me({env:t,variable:{name:Ae,type:se.type,isCompileTimeOnly:se.isCompileTimeOnly,value:se.isCompileTimeOnly?[X(se.type,{variableName:se.label,env:t,context:n})]:void 0,token:Z.token,initializedAtToken:Z.token,consumedAtToken:void 0,isOwningTheRcValue:se.isOwningTheRcValue,parameterAlias:Ae!==De?De:void 0}});t=he,Z.$={env:t,type:se.type,value:se.isCompileTimeOnly?X(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=d[Z];if(se&&B(se)){let Ae=se.token.value;if(Ae!==q.label)return{...q,label:Ae}}return q}),parameters:i.parameters.map((q,Z)=>{if(q.isCompileTimeOnly)return q;{let se=h[Z];return{...q,label:B(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:Ga(i.env)};if(L.whereClauseExprs?.length){let q=L.whereClauseExprs.map(se=>Se(se));t=ei({constraintExprs:q,env:t,context:{...n,isEvaluatingFunctionType:!0}}).env}let b={tag:"Function",type:L,body:c,frameLevel:t.frames.length-1,funcId:`fn_${Pe(t.modulePath)}`,definitionSiteEnclosingFunctionType:n.isEvaluatingFunctionBodyOrAsyncBlock?.kind==="function-body"?n.isEvaluatingFunctionBodyOrAsyncBlock.type:void 0,calledComptimeFunctionCaches:[],specializedFunctionCaches:[]},V=!!a,I=f.length>0||i.parameters.some(q=>de(q.type))||i.SelfType&&de(i.SelfType),U,D;if(I)Gl({functionBodyExpr:c,functionType:i,functionValue:b,env:t,context:n}),c.$={env:t,type:i.return.type,value:i.return.isCompileTimeOnly?X(i.return.type,{variableName:"function_body",env:t,context:n}):void 0,pathCollection:[]},U={...n,isExecuting:!1,capturedVariables:new Map},D=c;else{let{evaluationContext:q}=yo({...n,isExecuting:!1,isValidatingFunctionDefinition:!1},i,b,t);if(U=q,n.isInsideIoAsyncCall&&o&&(U={...U,isEvaluatingFunctionBodyOrAsyncBlock:{kind:"async-block",evaluationEnv:t}}),D=Tt({expr:c,env:t,context:U,variablesToAdd:[],isEvaluatingFunctionBodyBeginBlock:!0}),!D.$)throw m({token:c.token,errorMessage:"Failed to evaluate the function body."});t=D.$.env}let x=U.capturedVariables;if(or(D)&&(b.isControlFunction=!0),D.$&&(i.implicitParameters.some(q=>$e(q.type))||n.isInsideIoAsyncCall)){let q=n_(D);q.hasAwaits&&(D.$.awaitAnalysis=q)}let R=D.$?.type;if(M(i.return.type)&&!i.return.type.resolvedConcreteType&&R){let q=R;if(M(q)&&q.resolvedConcreteType&&(q=q.resolvedConcreteType),!M(q)){let Z=ht({type:q,expectedType:void 0,expr:D,env:t});i.return.type.resolvedConcreteType=Z}}if(!M(i.return.type)&&de(i.return.type)&&R&&!M(R)&&!de(R)&&(Ze({type:i.return.type,env:t},{type:R,env:t},[],{setResolvedConcreteType:!0}),i.return.type=R,L.return.type=R),!b.isControlFunction&&R&&!Y({type:i.return.type,env:t},{type:R,env:t}))throw m({token:c.token,errorMessage:`Incompatible return type:
11447
11447
  - Expected: ${A(i.return.type)}
@@ -11521,7 +11521,7 @@ Use \`::\` for compile-time definitions inside impl.`});let y=!u&&!n.isEvaluatin
11521
11521
  - Expected: ${A(oe)}
11522
11522
  - Actual : ${A(G.$.type)}`})}d||(d=n.expectedType)}else if(!d)d={type:G.$?.type,env:b};else if(!Y({type:d.type,env:b},{type:G.$?.type,env:t}))if(Y({type:ht({type:d.type,expectedType:void 0,expr:void 0,env:d.env}),env:d.env},{type:G.$.type,env:b}))d={type:G.$.type,env:b};else throw m({token:G.token,errorMessage:`Incompatible types:
11523
11523
  - Previous: ${A(d.type)}
11524
- - Current : ${A(G.$.type)}`})}}else if(F(V)&&F(V.func)&&E(V.func,".",1)){if(y)throw m({token:V.token,errorMessage:'Wildcard pattern "_" can only be used once and must be the last match arm in a "match" expression.'});let U=V.func.args[0];if(!B(U))throw m({token:V.token,errorMessage:`Expected identifier for enum variant, got ${w(U)}`});let D=U.token.value,x=_.variants.find(ge=>ge.name===D);if(!x)throw m({token:V.token,errorMessage:`Enum variant "${D}" not found in ${A(_)}`});if(h.add(D),!ru(_,x)||Nt(s)&&s.variantName!==D)continue;let R=V.args;if(x.fields&&x.fields.length>0){if(!R.some(q=>F(q)&&E(q,":",2))&&R.length!==x.fields.length)throw m({token:V.token,errorMessage:`Variant "${D}" expects ${x.fields.length} parameters, got ${R.length}`})}else if(R.length>0)throw m({token:V.token,errorMessage:`Variant "${D}" has no fields, but destructuring parameters were provided`});let Q={..._,selectedVariantName:D};U.$={env:b,type:Q,value:void 0,pathCollection:[]};let J=Q;if(l&&l==="Ptr"&&(J=qt(Q)),b=Re(b),x.fields&&x.fields.length>0){let ge=new Set;for(let q=0;q<R.length;q++){let Z=R[q];if(F(Z)&&E(Z,":",2)){let se=Z.args[0],Ae=Z.args[1];if(!B(se))throw m({token:se.token,errorMessage:`Expected identifier for label in destructuring pattern, got ${w(se)}`});let De=se.token.value,he=x.fields.findIndex(_e=>_e.label===De);if(he===-1)throw m({token:se.token,errorMessage:`Label "${De}" not found in variant "${D}". Available labels: ${x.fields.map(_e=>_e.label).join(", ")}`});if(ge.has(De))throw m({token:se.token,errorMessage:`Label "${De}" is already destructured`});ge.add(De);let Xe=x.fields[he],re=Nt(s)&&!ce(s),ee=re?s.fields[he]:void 0;if(B(Ae)){let _e=Ae.token.value;if(_e!=="_"){let{env:le}=me({env:b,variable:{name:_e,type:Xe.type,isCompileTimeOnly:re,value:ee!==void 0?[ee]:void 0,token:Ae.token,initializedAtToken:Ae.token,consumedAtToken:void 0,isReassignable:!1,isOwningTheRcValue:!1}});b=le}Ae.$={env:b,type:Xe.type,value:void 0,pathCollection:[]},se.$={env:b,type:Xe.type,value:void 0,pathCollection:[]}}else throw m({token:Ae.token,errorMessage:`Expected identifier or "_" for variable in labeled destructuring, got ${w(Ae)}`})}else if(B(Z)){let se=Z.token.value,Ae=x.fields[q],De=Nt(s)&&!ce(s),he=De?s.fields[q]:void 0;if(se!=="_"){let{env:Xe}=me({env:b,variable:{name:se,type:Ae.type,isCompileTimeOnly:De,value:he!==void 0?[he]:void 0,token:Z.token,initializedAtToken:Z.token,consumedAtToken:void 0,isReassignable:!1,isOwningTheRcValue:!1}});b=Xe}Z.$={env:b,type:Ae.type,value:void 0,pathCollection:[]}}else throw m({token:Z.token,errorMessage:`Expected identifier, "_", or labeled pattern (label: variable) for destructuring parameter, got ${w(Z)}`})}}V.$={env:b,type:J,value:void 0,pathCollection:[],caseExecuted:!0};let G=I,H=Tt({expr:G,env:b,context:{...n,isExecuting:Nt(s)&&s.variantName===D},variablesToAdd:[]});if(!H.$?.type)throw m({token:G.token,errorMessage:`Expected type for match result expression, got ${w(G)}`});let oe=ct(H.$.env,!0);if(b=oe,H.$={...H.$,env:oe},b=pi(H,b),H.$.env=b,s===void 0&&H.$&&(H.$.value=void 0),it(H.$.controlFlow)?(v.push(H.$.controlFlow),tt(H.$.controlFlow,"return")&&T.push(H),s&&!ce(s)&&Nt(s)?e.$={env:H.$.env,type:n.expectedType?.type&&!de(n.expectedType.type)?n.expectedType.type:H.$.type,value:H.$.value,pathCollection:H.$.pathCollection,controlFlow:H.$.controlFlow}:s===void 0&&(e.$={env:H.$.env,type:n.expectedType?.type&&!de(n.expectedType.type)?n.expectedType.type:H.$.type,value:void 0,pathCollection:H.$.pathCollection,controlFlow:H.$.controlFlow})):g=!0,b=H.$.env,f.push(H),!it(H.$.controlFlow)){if(c){if(x.gadtReturnTypeArgs&&n.expectedType){let ge=xm(n.expectedType.type,_.typeConstructorArgs,x.gadtReturnTypeArgs);if(!Y({type:ge,env:b},{type:H.$.type,env:b}))throw m({token:H.token,errorMessage:`GADT type mismatch in branch ".${D}":
11524
+ - Current : ${A(G.$.type)}`})}}else if(F(V)&&F(V.func)&&E(V.func,".",1)){if(y)throw m({token:V.token,errorMessage:'Wildcard pattern "_" can only be used once and must be the last match arm in a "match" expression.'});let U=V.func.args[0];if(!B(U))throw m({token:V.token,errorMessage:`Expected identifier for enum variant, got ${w(U)}`});let D=U.token.value,x=_.variants.find(ge=>ge.name===D);if(!x)throw m({token:V.token,errorMessage:`Enum variant "${D}" not found in ${A(_)}`});if(h.add(D),!ru(_,x)||Nt(s)&&s.variantName!==D)continue;let R=V.args;if(x.fields&&x.fields.length>0){if(!R.some(q=>F(q)&&E(q,":",2))&&R.length!==x.fields.length)throw m({token:V.token,errorMessage:`Variant "${D}" expects ${x.fields.length} parameters, got ${R.length}`})}else if(R.length>0)throw m({token:V.token,errorMessage:`Variant "${D}" has no fields, but destructuring parameters were provided`});let Q={..._,selectedVariantName:D};U.$={env:b,type:Q,value:void 0,pathCollection:[]};let J=Q;if(l&&l==="Ptr"&&(J=qt(Q)),b=Re(b),x.fields&&x.fields.length>0){let ge=new Set;for(let q=0;q<R.length;q++){let Z=R[q];if(F(Z)&&E(Z,":",2)){let se=Z.args[0],Ae=Z.args[1];if(!B(se))throw m({token:se.token,errorMessage:`Expected identifier for label in destructuring pattern, got ${w(se)}`});let De=se.token.value,he=x.fields.findIndex(_e=>_e.label===De);if(he===-1)throw m({token:se.token,errorMessage:`Label "${De}" not found in variant "${D}". Available labels: ${x.fields.map(_e=>_e.label).join(", ")}`});if(ge.has(De))throw m({token:se.token,errorMessage:`Label "${De}" is already destructured`});ge.add(De);let Xe=x.fields[he],ie=Nt(s)&&!ce(s),ee=ie?s.fields[he]:void 0;if(B(Ae)){let _e=Ae.token.value;if(_e!=="_"){let{env:le}=me({env:b,variable:{name:_e,type:Xe.type,isCompileTimeOnly:ie,value:ee!==void 0?[ee]:void 0,token:Ae.token,initializedAtToken:Ae.token,consumedAtToken:void 0,isReassignable:!1,isOwningTheRcValue:!1}});b=le}Ae.$={env:b,type:Xe.type,value:void 0,pathCollection:[]},se.$={env:b,type:Xe.type,value:void 0,pathCollection:[]}}else throw m({token:Ae.token,errorMessage:`Expected identifier or "_" for variable in labeled destructuring, got ${w(Ae)}`})}else if(B(Z)){let se=Z.token.value,Ae=x.fields[q],De=Nt(s)&&!ce(s),he=De?s.fields[q]:void 0;if(se!=="_"){let{env:Xe}=me({env:b,variable:{name:se,type:Ae.type,isCompileTimeOnly:De,value:he!==void 0?[he]:void 0,token:Z.token,initializedAtToken:Z.token,consumedAtToken:void 0,isReassignable:!1,isOwningTheRcValue:!1}});b=Xe}Z.$={env:b,type:Ae.type,value:void 0,pathCollection:[]}}else throw m({token:Z.token,errorMessage:`Expected identifier, "_", or labeled pattern (label: variable) for destructuring parameter, got ${w(Z)}`})}}V.$={env:b,type:J,value:void 0,pathCollection:[],caseExecuted:!0};let G=I,H=Tt({expr:G,env:b,context:{...n,isExecuting:Nt(s)&&s.variantName===D},variablesToAdd:[]});if(!H.$?.type)throw m({token:G.token,errorMessage:`Expected type for match result expression, got ${w(G)}`});let oe=ct(H.$.env,!0);if(b=oe,H.$={...H.$,env:oe},b=pi(H,b),H.$.env=b,s===void 0&&H.$&&(H.$.value=void 0),it(H.$.controlFlow)?(v.push(H.$.controlFlow),tt(H.$.controlFlow,"return")&&T.push(H),s&&!ce(s)&&Nt(s)?e.$={env:H.$.env,type:n.expectedType?.type&&!de(n.expectedType.type)?n.expectedType.type:H.$.type,value:H.$.value,pathCollection:H.$.pathCollection,controlFlow:H.$.controlFlow}:s===void 0&&(e.$={env:H.$.env,type:n.expectedType?.type&&!de(n.expectedType.type)?n.expectedType.type:H.$.type,value:void 0,pathCollection:H.$.pathCollection,controlFlow:H.$.controlFlow})):g=!0,b=H.$.env,f.push(H),!it(H.$.controlFlow)){if(c){if(x.gadtReturnTypeArgs&&n.expectedType){let ge=xm(n.expectedType.type,_.typeConstructorArgs,x.gadtReturnTypeArgs);if(!Y({type:ge,env:b},{type:H.$.type,env:b}))throw m({token:H.token,errorMessage:`GADT type mismatch in branch ".${D}":
11525
11525
  - Expected: ${A(ge)}
11526
11526
  - Actual : ${A(H.$.type)}`})}d||(d=n.expectedType)}else if(!d)d={type:H.$?.type,env:b};else if(!Y({type:d.type,env:b},{type:H.$?.type,env:t}))if(Y({type:ht({type:d.type,expectedType:void 0,expr:void 0,env:d.env}),env:d.env},{type:H.$.type,env:b}))d={type:H.$.type,env:b};else throw m({token:H.token,errorMessage:`Incompatible types:
11527
11527
  - Previous: ${A(d.type)}