numbl 0.4.15 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-browser/browser/protocol.d.ts +10 -0
- package/dist-browser/browser/session.d.ts +20 -0
- package/dist-browser/browser.js +34 -2
- package/dist-browser/numbl-core/jit/builtins/runtime/system/isequal.d.ts +2 -2
- package/dist-browser/numbl-core/jit/builtins/runtime/text/strcmp.d.ts +2 -2
- package/dist-browser/numbl-core/version.d.ts +1 -1
- package/dist-browser/syncInputChannel.d.ts +21 -0
- package/dist-cli/cli.js +4 -2
- package/dist-lib/lib.js +3 -1
- package/dist-lib/numbl-core/version.d.ts +1 -1
- package/dist-site-viewer/assets/{index-CVQsfOm5.js → index-ChbDz1FG.js} +3 -3
- package/dist-site-viewer/assets/{numbl-worker-F20FKX9r.js → numbl-worker-DFeAt1Cu.js} +1 -1
- package/dist-site-viewer/index.html +1 -1
- package/package.json +1 -1
|
@@ -5244,7 +5244,7 @@ function mtoc2_strcmpi(a, b) {
|
|
|
5244
5244
|
if (!Number.isFinite(x) || !Number.isInteger(x))
|
|
5245
5245
|
throw new Error("Size inputs must be nonnegative integers.");
|
|
5246
5246
|
return x < 0 ? 0 : x;
|
|
5247
|
-
}`};function HT(e,t){return e.kind==="exact"?`${e.value}L`:`mtoc2_check_dim(${t[e.argIndex]})`}function bl(e,t,n,r,s={}){const o=s.minArgs??1,i=s.cFillValue,a=i!==void 0?`${i}, `:"";return{name:e,transfer(c,l){if(c.length<o||c.length>Zn)throw new W(`'${e}' supports ${o}..${Zn} arg(s), got ${c.length}`);if(l!==1)throw new W(`'${e}' does not support multi-output (nargout=${l})`);const u=f0(e,c),f=m0(u);if(f!==void 0){const p=Dt(f);if(p===0)return[et(f)];if(f.every(g=>g===1))return[Be(ft(t),t)];if(p<=wt){const g=new Float64Array(p);return t!==0&&g.fill(t),[et(f,g)]}const d=et(f);return d.sign=ft(t),[d]}const h=u.axes.map(p=>p.kind==="exact"?p.value===1?nn:{kind:"exact",value:p.value}:{kind:"unknown"}),m=Zt(h);return m.sign=ft(t),[m]},emitC({argsC:c,argTypes:l,useRuntime:u}){u(n),u(r);const f=f0(e,l),h=m0(f);if(h!==void 0){if(h.every(d=>d===1))return i!==void 0?i:Number.isInteger(t)?`${t}.0`:`${t}`;const p=h.map(d=>`${d}L`).join(", ");return`${n}(${a}${f.ndim}, (long[]){${p}})`}if(u(Qo),f.isSquare){const p=f.axes[0];return`${r}(${a}mtoc2_check_dim(${c[p.argIndex]}))`}const m=f.axes.map(p=>HT(p,c)).join(", ");return`${n}(${a}${f.ndim}, (long[]){${m}})`},emitJs({argsJs:c,argTypes:l,useRuntime:u}){u(n),u(r);const f=f0(e,l),h=m0(f),m=i!==void 0?`${pk(t)}, `:"";if(h!==void 0){if(h.every(g=>g===1))return i!==void 0?pk(t):`${t}`;const d=h.join(", ");return`${n}(${m}${f.ndim}, [${d}])`}if(u(Qo),f.isSquare){const d=f.axes[0];return`${r}(${m}mtoc2_check_dim(${c[d.argIndex]}))`}const p=f.axes.map(d=>d.kind==="exact"?String(d.value):`mtoc2_check_dim(${c[d.argIndex]})`).join(", ");return`${n}(${m}${f.ndim}, [${p}])`},call({args:c,argTypes:l}){if(l.length<o||l.length>Zn)throw new W(`'${e}' supports ${o}..${Zn} arg(s), got ${l.length}`);let u;if(l.length===1&&Me(l[0])&&!De(l[0])){const m=c[0];u=[];for(let p=0;p<m.data.length;p++)u.push(Ka(m.data[p]))}else{u=[];for(let m=0;m<c.length;m++){const p=c[m],d=typeof p=="number"?p:Number(p);u.push(Ka(d))}u.length===1&&u.push(u[0])}for(;u.length>2&&u[u.length-1]===1;)u.pop();for(;u.length<2;)u.push(1);if(u.every(m=>m===1))return[t];const f=XT[n];if(!f)throw new W(`'${e}' has no JS shape-constructor helper registered (needs an entry in JS_SHAPE_HELPERS keyed by '${n}')`);return[f(i!==void 0?t:void 0,u.length,u)]}}}function pk(e){return Number.isNaN(e)?"NaN":e===1/0?"Infinity":e===-1/0?"-Infinity":String(e)}const YT=bl("zeros",0,"mtoc2_tensor_zeros_nd","mtoc2_tensor_zeros_square"),JT=bl("ones",1,"mtoc2_tensor_ones_nd","mtoc2_tensor_ones_square");function sm(e){if(e.length<1||e.length>2)throw new W(`'eye' supports 1 or 2 arguments (got ${e.length})`);if(e.length===1&&Me(e[0])&&!De(e[0]))throw new W("'eye' with a size-vector argument is not yet supported; use 'eye(m, n)' instead");const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(!Me(r)||r.elem!=="double"||r.isComplex)throw new le(`'eye' arg ${n+1} must be a scalar real double (got ${r.kind})`);if(!De(r))throw new le(`'eye' arg ${n+1} must be a scalar real double (got tensor)`);const s=Je(r);if(s!==void 0){if(!Number.isInteger(s)||s<0)throw new le(`'eye' arg ${n+1} must be a finite non-negative integer (got ${s})`);t.push({exact:s,argIndex:n})}else t.push({exact:void 0,argIndex:n})}return t.length===1?[t[0],{exact:t[0].exact,argIndex:t[0].argIndex}]:t}const ZT={name:"eye",transfer(e,t){if(t!==1)throw new W(`'eye' does not support multi-output (nargout=${t})`);const n=sm(e),r=n[0].exact,s=n[1].exact;if(r!==void 0&&s!==void 0){const a=[r,s],c=r*s;if(c===0)return[et(a)];if(r===1&&s===1)return[Be("positive",1)];if(c<=wt){const u=new Float64Array(c),f=r<s?r:s;for(let h=0;h<f;h++)u[h+h*r]=1;return[et(a,u)]}const l=et(a);return l.sign="nonneg",[l]}const o=n.map(a=>a.exact===void 0?{kind:"unknown"}:a.exact===1?nn:{kind:"exact",value:a.exact}),i=Zt(o);return i.sign="nonneg",[i]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_eye");const r=sm(t),s=r[0].exact,o=r[1].exact;if(s===1&&o===1)return"1.0";(s===void 0||o===void 0)&&n(Qo);const i=s!==void 0?`${s}L`:`mtoc2_check_dim(${e[r[0].argIndex]})`,a=o!==void 0?`${o}L`:`mtoc2_check_dim(${e[r[1].argIndex]})`;return t.length===1&&s===void 0&&o===void 0&&r[0].argIndex===r[1].argIndex?`mtoc2_eye_square(mtoc2_check_dim(${e[r[0].argIndex]}))`:`mtoc2_eye_rect(${i}, ${a})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_eye");const r=sm(t),s=r[0].exact,o=r[1].exact;if(s===1&&o===1)return"1";(s===void 0||o===void 0)&&n(Qo);const i=s!==void 0?String(s):`mtoc2_check_dim(${e[r[0].argIndex]})`,a=o!==void 0?String(o):`mtoc2_check_dim(${e[r[1].argIndex]})`;return t.length===1&&s===void 0&&o===void 0&&r[0].argIndex===r[1].argIndex?`mtoc2_eye_square(mtoc2_check_dim(${e[r[0].argIndex]}))`:`mtoc2_eye_rect(${i}, ${a})`},call({args:e,argTypes:t}){const n=sm(t),r=n[0].exact!==void 0?n[0].exact:Ka(typeof e[n[0].argIndex]=="number"?e[n[0].argIndex]:Number(e[n[0].argIndex])),s=n[1].exact!==void 0?n[1].exact:Ka(typeof e[n[1].argIndex]=="number"?e[n[1].argIndex]:Number(e[n[1].argIndex]));return r===1&&s===1?[1]:[N5(r,s)]}},Ga=Zn;function dk(e){return!Me(e)||De(e)||e.shape===void 0?!1:Dt(e.shape)===0}function KT(e){const t=e.slice();for(;t.length>2&&t[t.length-1].kind==="exact"&&t[t.length-1].value===1;)t.pop();for(;t.length<2;)t.push({kind:"exact",value:1});return t}function om(e){if(e.length<1)throw new W("'reshape' requires at least one dim argument after the input tensor");let t;if(e.length===1&&Me(e[0])&&!De(e[0])){const n=e[0];if(dk(n))throw new W("reshape: '[]' auto-infer slot is not yet supported; specify all dims explicitly");if(n.elem!=="double"||n.isComplex)throw new le(`'reshape' dim vector must be a real-double tensor (got ${n.elem}${n.isComplex?" complex":""})`);const r=Mt(n);if(r===void 0)throw new W("'reshape' dim vector must be a statically-known constant in v1");if(r.length<1||r.length>Ga)throw new W(`'reshape' supports 1..${Ga} output dims (got ${r.length})`);t=[];for(let s=0;s<r.length;s++){const o=r[s];if(!Number.isFinite(o)||!Number.isInteger(o)||o<0)throw new le(`'reshape' dim ${s+1} must be a finite non-negative integer (got ${o})`);t.push({kind:"exact",value:o})}}else{if(e.length>Ga)throw new W(`'reshape' supports 1..${Ga} output dims (got ${e.length})`);t=[];let n=!1;for(let r=0;r<e.length;r++){const s=e[r];if(!Me(s)||s.elem!=="double"||s.isComplex)throw new le(`'reshape' dim arg ${r+1} must be a scalar real double (got ${s.kind})`);if(!De(s)){if(dk(s)){if(n)throw new W("'reshape' allows at most one '[]' auto-infer slot");n=!0,t.push({kind:"infer",argIndex:r});continue}throw new le(`'reshape' dim arg ${r+1} must be a scalar real double (got tensor)`)}const o=Je(s);if(o===void 0){t.push({kind:"dynamic",argIndex:r});continue}if(!Number.isFinite(o)||!Number.isInteger(o)||o<0)throw new le(`'reshape' dim arg ${r+1} must be a finite non-negative integer (got ${o})`);t.push({kind:"exact",value:o,argIndex:r})}}return{axes:KT(t)}}function h0(e){const t=[];for(const n of e.axes){if(n.kind!=="exact")return;t.push(n.value)}return t}function GT(e,t){return e.kind==="exact"?`${e.value}L`:e.kind==="infer"?"-1L":`mtoc2_check_dim(${t[e.argIndex]})`}const QT={name:"reshape",transfer(e,t){if(e.length<2||e.length>Ga+1)throw new le(`'reshape' expects 2..${Ga+1} arg(s), got ${e.length}`);if(t!==1)throw new W(`'reshape' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'reshape' first arg must be numeric (got ${n.kind})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'reshape' first arg must be a double or logical tensor (got ${n.elem})`);const r=om(e.slice(1));if(n.shape!==void 0){const i=r.axes.findIndex(a=>a.kind==="infer");if(i!==-1){const a=[];let c=!0;for(let l=0;l<r.axes.length;l++){if(l===i)continue;const u=r.axes[l];if(u.kind==="exact")a.push(u.value);else{c=!1;break}}if(c){const l=n.shape.reduce((h,m)=>h*m,1),u=a.reduce((h,m)=>h*m,1);if(u===0&&l!==0)throw new le(`'reshape' element count mismatch: input has ${l} elements but the explicit dims around '[]' multiply to 0`);if(u>0&&l%u!==0)throw new le(`'reshape' element count mismatch: input has ${l} elements, not divisible by ${u} (the explicit dims around '[]')`);const f=u===0?0:l/u;r.axes[i]={kind:"exact",value:f}}}}const s=h0(r);if(s!==void 0){const i=s.reduce((a,c)=>a*c,1);if(n.shape!==void 0){const a=n.shape.reduce((c,l)=>c*l,1);if(a!==i)throw new le(`'reshape' element count mismatch: input has ${a} elements, requested shape needs ${i}`)}if(s.every(a=>a===1)){if(n.isComplex){const a=An(n);if(a!==void 0)return[_t(a)];const c=rn(n);return c!==void 0&&c.re.length===1?[_t({re:c.re[0],im:c.im[0]})]:[_t()]}return typeof n.exact=="number"?[Be(ft(n.exact),n.exact)]:[Be("unknown")]}if(n.isComplex){const a=rn(n);return a!==void 0&&i<=wt&&a.re.length===i?[Ut(s,a)]:[Ut(s)]}return n.exact instanceof Float64Array&&i<=wt&&n.exact.length===i?[et(s,n.exact)]:[et(s)]}const o=r.axes.map(i=>i.kind==="exact"?i.value===1?nn:{kind:"exact",value:i.value}:{kind:"unknown"});return n.isComplex?[mr(o)]:[Zt(o)]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_reshape_nd"),n("mtoc2_reshape_nd_complex");const r=om(t.slice(1)),s=h0(r);if(s!==void 0&&s.every(u=>u===1))return e[0];const o=t[0],a=Me(o)&&o.isComplex?"mtoc2_reshape_nd_complex":"mtoc2_reshape_nd",c=e.slice(1);r.axes.some(u=>u.kind==="dynamic")&&n(Qo);const l=r.axes.map(u=>GT(u,c)).join(", ");return`${a}(${e[0]}, ${r.axes.length}, (long[]){${l}})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=om(t.slice(1)),s=h0(r);if(s!==void 0&&s.every(c=>c===1))return e[0];const o=t[0],i=e.slice(1);r.axes.some(c=>c.kind==="dynamic")&&n(Qo);const a=r.axes.map(c=>c.kind==="exact"?String(c.value):c.kind==="infer"?"-1":`mtoc2_check_dim(${i[c.argIndex]})`).join(", ");return Me(o)&&o.isComplex?(n("mtoc2_reshape_nd_complex"),`mtoc2_reshape_nd_complex(${e[0]}, ${r.axes.length}, [${a}])`):(n("mtoc2_reshape_nd"),`mtoc2_reshape_nd(${e[0]}, ${r.axes.length}, [${a}])`)},call({args:e,argTypes:t}){const n=om(t.slice(1)),r=t[0],s=[];for(const i of n.axes)if(i.kind==="exact")s.push(i.value);else if(i.kind==="infer")s.push(-1);else{const a=e[i.argIndex+1];s.push(Ka(typeof a=="number"?a:Number(a)))}return[(Me(r)&&r.isComplex?vL:kL)(e[0],n.axes.length,s)]}};function p0(e,t,n){const r=new Float64Array(t*n);for(let s=0;s<n;s++)for(let o=0;o<t;o++)r[s+o*n]=e[o+s*t];return r}const OT={name:"transpose",transfer(e,t){if(e.length!==1)throw new le(`'transpose' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'transpose' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`transpose argument must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`transpose argument must be a double or logical (got ${n.elem})`);if(De(n)){if(n.isComplex){const l=An(n);return l!==void 0?[_t(l)]:[_t()]}const a=Je(n),c=a!==void 0?Be(ft(a),a):Be(n.sign);return n.elem==="logical"&&(c.elem="logical"),[c]}if(n.dims.length!==2)throw new W(`transpose requires a 2-D operand (got ${n.dims.length}-D); use 'permute' for higher-rank reorderings (numbl flattens trailing dims into cols; mtoc2 follows MATLAB and rejects)`);if(n.shape===void 0)throw new W("transpose of a tensor with unknown shape is not yet supported");const r=n.shape[0],s=n.shape[1],o=[s,r];if(n.isComplex){const a=rn(n);return a!==void 0?[Ut(o,{re:p0(a.re,r,s),im:p0(a.im,r,s)})]:[Ut(o)]}const i=n.exact instanceof Float64Array?et(o,p0(n.exact,r,s)):et(o);return n.elem==="logical"&&(i.elem="logical"),[i]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_transpose"),n("mtoc2_tensor_transpose_complex");const r=t[0];return qe(r)?r.isComplex?`mtoc2_tensor_transpose_complex(${e[0]})`:`mtoc2_tensor_transpose(${e[0]})`:e[0]},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_transpose_complex"),`mtoc2_tensor_transpose_complex(${e[0]})`):(n("mtoc2_tensor_transpose"),`mtoc2_tensor_transpose(${e[0]})`):e[0]},call({args:e,argTypes:t}){const n=t[0];if(!qe(n))return[e[0]];if(!Wt(e[0]))throw new le("'transpose' runtime arg has type-system shape tensor but runtime value isn't a tensor");return[(n.isComplex?EL:AL)(e[0])]}},e8={name:"size",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'size' expects 1..2 arg(s), got ${e.length}`);if(t<1)throw new W(`'size' requires at least one output (got nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'size' first arg must be numeric (got ${ze(n)})`);if(e.length===2){if(t!==1)throw new W("'size(A, k)' is single-output only; drop the 'k' arg and use '[d1, d2, ...] = size(A)' for per-output dims");const s=e[1];if(!Me(s)||s.isComplex||!De(s))throw new le(`'size' second arg must be a real scalar (got ${ze(s)})`);const o=Je(s);if(o!==void 0){if(!Number.isFinite(o)||!Number.isInteger(o)||o<1)throw new le(`'size' dim argument must be a positive integer (got ${o})`);if(n.shape!==void 0){const i=o<=n.shape.length?n.shape[o-1]:1;return[Be(ft(i),i)]}}return[Be("nonneg")]}const r=n.dims.length;if(t>=2){const s=[];for(let o=0;o<t;o++)if(n.shape!==void 0){const i=o<r?n.shape[o]:1;s.push(Be(ft(i),i))}else if(o<r&&n.dims[o].kind==="exact"){const i=n.dims[o].value;s.push(Be(ft(i),i))}else o>=r?s.push(Be("positive",1)):s.push(Be("nonneg"));return s}if(n.shape!==void 0){const s=new Float64Array(r);for(let o=0;o<r;o++)s[o]=n.shape[o];return[et([1,r],s)]}return[et([1,r])]},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){const o=t[0];if(De(o))return n>=2?`((void)(${(r??[]).slice(0,n).map(c=>`(*${c} = 1.0)`).join(", ")}))`:t.length===2?"1.0":(s("mtoc2_tensor_size_row"),s("mtoc2_tensor_from_row"),"mtoc2_tensor_from_row((double[]){1.0, 1.0}, 2)");if(n>=2){const i=r??[],a=o.dims.length,c=[];for(let l=0;l<n;l++){const u=l<a?`(double)${e[0]}.dims[${l}]`:"1.0";c.push(`(*${i[l]} = ${u})`)}return`((void)(${c.join(", ")}))`}if(s("mtoc2_tensor_size_row"),s("mtoc2_tensor_from_row"),t.length===2){const i=Je(t[1]);if(i!==void 0){const a=o.dims.length;return i<=a?`((double)${e[0]}.dims[${i-1}])`:"1.0"}return`({ long _mtoc2_k = (long)(${e[1]}); (double)(_mtoc2_k >= 1 && _mtoc2_k <= ${e[0]}.ndim ? ${e[0]}.dims[_mtoc2_k - 1] : 1); })`}return qe(o)?`mtoc2_tensor_size_row(${e[0]})`:"mtoc2_tensor_from_row((double[]){1.0, 1.0}, 2)"},emitJs({argsJs:e,argTypes:t,nargout:n,useRuntime:r}){const s=t[0];if(De(s))return n>=2?`[${Array(n).fill("1").join(", ")}]`:t.length===2?"1":(r("mtoc2_tensor_size_row"),r("mtoc2_tensor_from_row"),"mtoc2_tensor_from_row([1, 1], 2)");if(n>=2){const o=s.dims.length,i=[];for(let a=0;a<n;a++)i.push(a<o?`${e[0]}.shape[${a}]`:"1");return`[${i.join(", ")}]`}if(r("mtoc2_tensor_size_row"),r("mtoc2_tensor_from_row"),t.length===2){const o=Je(t[1]);if(o!==void 0){const i=s.dims.length;return o<=i?`(${e[0]}.shape[${o-1}])`:"1"}return`((k => (k >= 1 && k <= ${e[0]}.shape.length ? ${e[0]}.shape[k - 1] : 1))(Math.trunc(${e[1]})))`}return qe(s)?`mtoc2_tensor_size_row(${e[0]})`:"mtoc2_tensor_from_row([1, 1], 2)"},call({args:e,argTypes:t,nargout:n}){const r=e[0];if(n>=2){const s=Wt(r)?r.shape:[1,1],o=[];for(let i=0;i<n;i++)o.push(i<s.length?s[i]:1);return o}if(t.length===2){const s=typeof e[1]=="number"?e[1]:Number(e[1]),o=Math.trunc(s);if(o<1)throw new le(`'size' dim argument must be a positive integer (got ${o})`);return Wt(r)?[o<=r.shape.length?r.shape[o-1]:1]:[1]}return Wt(r)?[ML(r)]:[u6([1,1],2)]}};function d0(e,t,n){const r=Dt(t),s=new Float64Array(r),o=n>=0&&n<t.length?t[n]:1;if(o<=1)return s.set(e),s;let i=1;for(let l=0;l<n;l++)i*=t[l];const a=i*o,c=r/a;for(let l=0;l<c;l++){const u=l*a;for(let f=0;f<o;f++){const h=u+f*i,m=u+(o-1-f)*i;for(let p=0;p<i;p++)s[m+p]=e[h+p]}}return s}function im(e,t,n){if(n!==null)return n;if(t.length===1){const o=t[0];if(o.shape!==void 0){const i=o.shape.findIndex(a=>a>1);return i===-1?0:i}return 0}const r=t[1];if(!De(r)||r.isComplex)throw new le(`'${e}' second arg must be a real scalar (got ${ze(r)})`);const s=Je(r);if(s===void 0)throw new W(`'${e}' with a dynamic dim argument is not yet supported (require statically-known axis)`);if(!Number.isFinite(s)||!Number.isInteger(s)||s<1)throw new le(`'${e}' dim argument must be a positive integer (got ${s})`);return s-1}function g0(e){return{name:e.name,transfer(t,n){if(t.length<e.minArgs||t.length>e.maxArgs)throw new le(`'${e.name}' expects ${e.minArgs}..${e.maxArgs} arg(s), got ${t.length}`);if(n!==1)throw new W(`'${e.name}' does not support multi-output (nargout=${n})`);const r=t[0];if(!Me(r))throw new le(`'${e.name}' arg must be numeric (got ${ze(r)})`);if(r.elem!=="double"&&r.elem!=="logical")throw new le(`'${e.name}' arg must be a real double or logical (got ${r.elem})`);if(De(r)){if(r.isComplex){const a=An(r);return a!==void 0?[_t(a)]:[_t()]}const i=Je(r);return i!==void 0?[Be(ft(i),i)]:[Be(r.sign)]}const s=im(e.name,t,e.fixedAxis);if(r.isComplex){const i=rn(r);if(r.shape!==void 0&&i!==void 0&&Dt(r.shape)<=wt){const c=d0(i.re,r.shape,s),l=d0(i.im,r.shape,s);return[Ut(r.shape,{re:c,im:l})]}return r.shape!==void 0?[Ut(r.shape)]:[{...r,exact:void 0}]}const o=Mt(r);if(r.shape!==void 0&&o!==void 0&&Dt(r.shape)<=wt){const a=d0(o,r.shape,s);return[et(r.shape,a)]}return r.shape!==void 0?[et(r.shape)]:[{...r,exact:void 0}]},emitC({argsC:t,argTypes:n,useRuntime:r}){const s=n[0];if(!qe(s))return t[0];const o=im(e.name,n,e.fixedAxis);return s.isComplex?(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip_complex(${t[0]}, ${o}L)`):(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip(${t[0]}, ${o}L)`)},emitJs({argsJs:t,argTypes:n,useRuntime:r}){const s=n[0];if(!qe(s))return t[0];const o=im(e.name,n,e.fixedAxis);return s.isComplex?(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip_complex(${t[0]}, ${o})`):(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip(${t[0]}, ${o})`)},call({args:t,argTypes:n}){const r=n[0];if(!qe(r))return[t[0]];const s=im(e.name,n,e.fixedAxis);return r.isComplex?[I5(t[0],s)]:[E5(t[0],s)]}}}const t8=g0({name:"flipud",fixedAxis:0,minArgs:1,maxArgs:1}),n8=g0({name:"fliplr",fixedAxis:1,minArgs:1,maxArgs:1}),r8=g0({name:"flip",fixedAxis:null,minArgs:1,maxArgs:2});function s8(e){pr(e,"'sort' arg 1");const t=e;if(!qe(t))throw new W("'sort' on a scalar is a no-op; pass a 1-D vector (1×N or N×1)");if(t.dims.length!==2)throw new W(`'sort' currently only supports 1-D vectors (got ${ze(t)}); matrix and N-D forms (with explicit 'dim' arg) are not yet supported`);const n=Dn(t.dims[0]),r=Dn(t.dims[1]);if(!n&&!r)throw new W(`'sort' currently only supports 1-D vectors (1×N or N×1); got ${ze(t)} — pass an explicit 'dim' (not yet supported) or reshape first`);return t}function am(e){if(e.length<2)return!1;const t=e[1];if(!os(t)||t.kind!=="Char"&&t.kind!=="String")throw new le(`'sort' mode arg must be a literal 'ascend' or 'descend' (got ${ze(t)})`);if(t.exact===void 0)throw new W("'sort' mode arg must be a literal; non-literal text is not supported");const n=t.exact.toLowerCase();if(n==="ascend")return!1;if(n==="descend")return!0;throw new le(`'sort' mode arg must be 'ascend' or 'descend' (got '${t.exact}')`)}const o8={name:"sort",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'sort' expects 1..2 arg(s), got ${e.length}`);if(t<1||t>2)throw new W(`'sort' supports 1..2 output(s); got nargout=${t}`);const n=s8(e[0]);am(e);const r=n.isComplex?mr(n.dims.slice()):Zt(n.dims.slice());if(t===1)return[r];const s=Zt(n.dims.slice());return s.sign="positive",[r,s]},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){s("mtoc2_sort_real");const o=t[0],i=Me(o)&&o.isComplex,a=am(t)?1:0,c=i?"mtoc2_sort_complex":"mtoc2_sort_real";if(n===1)return`${c}(${e[0]}, ${a})`;const l=r??[];return`${c}_2(${e[0]}, ${a}, ${l.join(", ")})`},emitJs({argsJs:e,argTypes:t,nargout:n,useRuntime:r}){r("mtoc2_sort_real");const s=t[0],o=Me(s)&&s.isComplex,i=am(t)?"true":"false",a=o?"mtoc2_sort_complex":"mtoc2_sort_real";return n===1?`${a}(${e[0]}, ${i})`:`(o => [o.v, o.ix])(${a}_2(${e[0]}, ${i}))`},call({args:e,argTypes:t,nargout:n}){const r=e[0],s=t[0],o=Me(s)&&s.isComplex,i=am(t);if(n===1)return[(o?SL:$L)(r,i)];const a=o?NL(r,i):CL(r,i);return[a.v,a.ix]}};function gk(e,t){ml(e,t);const n=e;if(!qe(n))throw new W(`${t} must be a 1-D vector (1×N or N×1); scalar inputs are not supported`);if(n.dims.length!==2)throw new W(`${t} must be a 1-D vector (got ${ze(n)})`);const r=Dn(n.dims[0]),s=Dn(n.dims[1]);if(!r&&!s)throw new W(`${t} must be a 1-D vector (1×N or N×1); got ${ze(n)}`);return n}function wk(e){return Dn(e.dims[0])?e.dims[1]:e.dims[0]}function i8(e,t){const n=e.length,r=t.length,s=new Float64Array(r*n);for(let o=0;o<n;o++)for(let i=0;i<r;i++)s[i+o*r]=e[o];return s}function a8(e,t){const n=e.length,r=t.length,s=new Float64Array(r*n);for(let o=0;o<n;o++)for(let i=0;i<r;i++)s[i+o*r]=t[i];return s}function w0(e,t,n){const r=wk(e),s=wk(t),o=Mt(e),i=Mt(t);if(r.kind==="exact"&&s.kind==="exact"&&o!==void 0&&i!==void 0&&o.length===r.value&&i.length===s.value&&r.value*s.value<=wt){const c=n==="X"?i8(o,i):a8(o,i);return et([s.value,r.value],c)}return Zt([s,r])}const c8={name:"meshgrid",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'meshgrid' expects 1..2 arg(s), got ${e.length}`);const n=gk(e[0],"'meshgrid' arg 1"),r=e.length>=2?gk(e[1],"'meshgrid' arg 2"):n;if(t===1)return[w0(n,r,"X")];if(t===2)return[w0(n,r,"X"),w0(n,r,"Y")];throw new W(`'meshgrid' supports 1..2 output(s); got nargout=${t}`)},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){if(s("mtoc2_meshgrid"),n===1){const i=e[0],a=e.length>=2?e[1]:e[0];return`mtoc2_meshgrid_x(${i}, ${a})`}const o=r??[];return t.length===1?`mtoc2_meshgrid_1arg(${e[0]}, ${o.join(", ")})`:`mtoc2_meshgrid(${e[0]}, ${e[1]}, ${o.join(", ")})`},emitJs({argsJs:e,argTypes:t,nargout:n,useRuntime:r}){if(r("mtoc2_meshgrid"),n===1){const s=e[0],o=e.length>=2?e[1]:e[0];return`mtoc2_meshgrid_x(${s}, ${o})`}return t.length===1?`(o => [o.X, o.Y])(mtoc2_meshgrid_1arg(${e[0]}))`:`(o => [o.X, o.Y])(mtoc2_meshgrid(${e[0]}, ${e[1]}))`},call({args:e,argTypes:t,nargout:n}){const r=e[0];if(n===1){const o=t.length>=2?e[1]:r;return[T5(r,o)]}if(t.length===1){const o=P5(r);return[o.X,o.Y]}const s=Mb(r,e[1]);return[s.X,s.Y]}};function l8(e){if(typeof e=="object"&&e!==null){const t=e;if(t.mtoc2Tag==="char"&&typeof t.value=="string")return t.value}return e}const u8={name:"assert",transfer(e,t){if(e.length<1)throw new le("'assert' requires at least 1 arg");if(t!==1)throw new W(`'assert' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'assert' first arg must be numeric (got ${ze(n)})`);if(n.isComplex)throw new le("'assert' on complex cond is not supported");if(!De(n))throw new W("'assert' on a tensor cond is not yet supported in mtoc2 v1 (numbl tests every element non-zero and non-NaN); pass a scalar predicate instead");if(e.length>=2){const s=e[1];if(!os(s))throw new W(`'assert' message must be char or string (got ${ze(s)})`);Ya("assert",e,2)}const r=Je(n);if(r!==void 0&&!(r!==0&&!Number.isNaN(r))){const o=e.length>=2?e[1]:void 0,i=o&&(o.kind==="String"||o.kind==="Char")?`: ${o.exact??"(opaque)"}`:"";throw new le(`'assert' is statically false${i}`)}return[{kind:"Void"}]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_assert_scalar"),n("mtoc2_assert_scalar_fmt");const r=t[0];if(Me(r)&&Je(r)!==void 0)return"((void)0)";const s=`(double)(${e[0]})`;if(t.length<2)return`mtoc2_assert_scalar(${s}, (const char *)0)`;if(t.length===2){const a=t[1];if((a.kind==="Char"||a.kind==="String")&&a.exact!==void 0)return`mtoc2_assert_scalar(${s}, ${JSON.stringify(a.exact)})`}const o=Vi(e[1],t[1]),i=[];for(let a=2;a<t.length;a++)i.push(Ja("assert",e[a],t[a],a));return`mtoc2_assert_scalar_fmt(${s}, ${o}, ${i.length}, ${Za(i)})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_assert_scalar_fmt");const r=t[0];return Me(r)&&Je(r)!==void 0?"undefined":t.length<2?`mtoc2_assert_scalar_fmt(${e[0]}, "assertion failed")`:`mtoc2_assert_scalar_fmt(${e.join(", ")})`},call({args:e,argTypes:t}){t[0];const n=typeof e[0]=="number"?e[0]:Number(e[0]);if(n!==0&&!Number.isNaN(n))return[];const s=e.slice(1).map(l8);if(s.length===0)throw new Error("assertion failed");return $R(!1,s[0],...s.slice(1)),[]}},f8={name:"tic",transfer(e,t){if(e.length!==0)throw new le(`'tic' expects 0 arg(s), got ${e.length}`);if(t!==1)throw new W(`'tic' does not support multi-output (nargout=${t})`);return[Be("positive")]},emitC({useRuntime:e}){return e("mtoc2_tic_toc"),"mtoc2_tic()"},emitJs({useRuntime:e}){return e("mtoc2_tic_toc"),"mtoc2_tic()"},call(){return[a6()]}},m8={name:"toc",transfer(e,t){if(e.length>1)throw new le(`'toc' expects 0..1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'toc' does not support multi-output (nargout=${t})`);if(e.length===1&&!Kn(e[0]))throw new le(`'toc' tic-handle argument must be a scalar real numeric (the value returned by 'tic'); got ${e[0].kind}`);return[Be("nonneg")]},emitC({argsC:e,useRuntime:t}){return t("mtoc2_tic_toc"),e.length===1?`mtoc2_toc_handle(${e[0]})`:"mtoc2_toc()"},emitJs({argsJs:e,useRuntime:t}){return t("mtoc2_tic_toc"),e.length===1?`mtoc2_toc_handle(${e[0]})`:"mtoc2_toc()"},call({args:e}){if(e.length===1){const t=typeof e[0]=="number"?e[0]:Number(e[0]);return[l6(t)]}return[c6()]}},_0=(e,t)=>({name:e,transfer(){throw new W(t)},emitC(){throw new W(t)},emitJs(){throw new W(t)},call(){throw new W(t)}}),h8=_0("addpath","'addpath' is only allowed at the top of the driver script, before any other non-comment statement; mtoc2 resolves the search path statically and cannot honor a runtime addpath call"),p8=_0("rmpath","'rmpath' is not supported by mtoc2; the search path is fixed after lowering begins"),d8=_0("savepath","'savepath' is not supported by mtoc2"),_k={cos:rD,sin:sD,tan:oD,atan:iD,sinh:aD,cosh:cD,tanh:lD,asinh:uD,exp:fD,log:mD,log2:hD,log10:pD,sqrt:dD,abs:gD,floor:wD,ceil:_D,fix:yD,round:xD,sign:bD},yk={cos:zL,sin:qL,tan:VL,atan:UL,sinh:WL,cosh:XL,tanh:HL,exp:DL,log:TL,log2:PL,log10:BL,sqrt:LL,floor:YL,ceil:JL,fix:KL,round:ZL,sign:GL};function cm(e,t){return n=>n.sign==="positive"&&e?"nonneg":n.sign==="negative"&&t?"nonpositive":n.sign==="nonzero"&&(e||t)?"unknown":n.sign}function Qn(e){const{name:t,cFnReal:n,jsFn:r,signRule:s,realDomainOk:o,complex:i}=e,a=e.jsExpr??(l=>`Math.${t}(${l})`),c=l=>l.isComplex||o===void 0||o(l)?!1:i!==void 0&&i.liftOnDomainMiss===!0;return{name:t,transfer(l,u){if(l.length!==1)throw new le(`'${t}' expects 1 arg(s), got ${l.length}`);if(u!==1)throw new W(`'${t}' does not support multi-output (nargout=${u})`);i!==void 0?pr(l[0],`'${t}' arg`):ml(l[0],`'${t}' arg`);const f=l[0],h=c(f);if(f.isComplex||h){if(De(f)){const p=f.isComplex?An(f):(()=>{const d=Je(f);return d!==void 0?{re:d,im:0}:void 0})();if(p!==void 0){const d=i.jsFnComplex(p);if(Number.isFinite(d.re)&&Number.isFinite(d.im))return[_t(d)]}return[_t()]}if(f.isComplex){const p=rn(f);if(p!==void 0&&f.shape!==void 0){const d=Dt(f.shape);if(d<=wt){const g=new Float64Array(d),w=new Float64Array(d);let _=!0;for(let y=0;y<d;y++){const b=i.jsFnComplex({re:p.re[y],im:p.im[y]});if(!Number.isFinite(b.re)||!Number.isFinite(b.im)){_=!1;break}g[y]=b.re,w[y]=b.im}if(_)return[Ut(f.shape,{re:g,im:w})]}}}else{const p=Mt(f);if(p!==void 0&&f.shape!==void 0){const d=Dt(f.shape);if(d<=wt){const g=new Float64Array(d),w=new Float64Array(d);let _=!0;for(let y=0;y<d;y++){const b=i.jsFnComplex({re:p[y],im:0});if(!Number.isFinite(b.re)||!Number.isFinite(b.im)){_=!1;break}g[y]=b.re,w[y]=b.im}if(_)return[Ut(f.shape,{re:g,im:w})]}}}return[mr(f.dims.slice())]}if(o!==void 0&&!o(f))throw new le(`'${t}' of input that may leave the real domain is not yet supported for real-typed input (would produce NaN / -Inf or a complex result). Guard upstream or make the input complex (e.g. '${t}(x + 0i)').`);if(De(f)){const p=Je(f);if(p!==void 0){const d=r(p);if(Number.isFinite(d))return[Be(ft(d),d)]}return[Be(s(f))]}if(f.shape!==void 0){const p=Mt(f),d=Dt(f.shape);if(p!==void 0&&d<=wt){const g=new Float64Array(p.length);let w=!0;for(let _=0;_<p.length;_++){const y=r(p[_]);if(!Number.isFinite(y)){w=!1;break}g[_]=y}if(w)return[et(f.shape,g)]}}const m=Zt(f.dims.slice());return m.sign=s(f),[m]},emitC({argsC:l,argTypes:u,useRuntime:f}){const h=u[0],m=c(h);if(Me(h)&&h.isComplex||m){if(f("mtoc2_cscalar"),qe(h))return f("mtoc2_tensor_unary_complex_math"),`mtoc2_tensor_${t}_complex(${l[0]})`;const p=m?`mtoc2_cmake(${l[0]}, 0.0)`:l[0];return`${i.cFnComplex}(${p})`}return qe(h)?(f("mtoc2_tensor_unary_real_math"),`mtoc2_tensor_${t}(${l[0]})`):(n.startsWith("mtoc2_")&&f("mtoc2_tensor_unary_real_math"),`${n}(${l[0]})`)},emitJs({argsJs:l,argTypes:u,useRuntime:f}){const h=u[0],m=c(h);if(Me(h)&&h.isComplex||m){if(qe(h)){if(yk[t]===void 0)throw new W(`'${t}' complex-tensor emitJs has no JS kernel registered`);return f("mtoc2_tensor_unary_complex_math"),f("mtoc2_cscalar"),`mtoc2_tensor_${t}_complex(${l[0]})`}f("mtoc2_cscalar");const p=m?`mtoc2_cmake(${l[0]}, 0.0)`:l[0];return`${i.cFnComplex}(${p})`}if(qe(h)){if(_k[t]===void 0)throw new W(`'${t}' tensor emitJs has no JS kernel registered`);return f("mtoc2_tensor_unary_real_math"),`mtoc2_tensor_${t}(${l[0]})`}return a(l[0])},call({args:l,argTypes:u}){const f=u[0],h=c(f);if(Me(f)&&f.isComplex||h){if(qe(f)){const g=yk[t];if(g===void 0)throw new W(`'${t}' complex-tensor 'call' has no JS kernel registered`);return[g(l[0])]}const p=l[0],d=un(p)?p:{re:typeof p=="number"?p:Number(p),im:0};return[i.jsFnComplex(d)]}if(qe(f)){const p=_k[t];if(p===void 0)throw new W(`'${t}' tensor 'call' has no JS kernel registered`);return[p(l[0])]}const m=typeof l[0]=="number"?l[0]:Number(l[0]);return[r(m)]},elementwise:!0}}function g8(e){const t=Math.hypot(e.re,e.im);if(t===0)return{re:0,im:0};const n=Math.sqrt((t+e.re)/2),r=(e.im>=0?1:-1)*Math.sqrt((t-e.re)/2);return{re:n,im:r}}function w8(e){const t=Math.exp(e.re);return{re:t*Math.cos(e.im),im:t*Math.sin(e.im)}}function lm(e){return{re:.5*Math.log(e.re*e.re+e.im*e.im),im:Math.atan2(e.im,e.re)}}function _8(e){const t=lm(e),n=Math.log(2);return{re:t.re/n,im:t.im/n}}function y8(e){const t=lm(e),n=Math.log(10);return{re:t.re/n,im:t.im/n}}function xk(e){return{re:Math.sin(e.re)*Math.cosh(e.im),im:Math.cos(e.re)*Math.sinh(e.im)}}function bk(e){return{re:Math.cos(e.re)*Math.cosh(e.im),im:-Math.sin(e.re)*Math.sinh(e.im)}}function kk(e,t){if(Math.abs(t.re)>=Math.abs(t.im)){const s=t.im/t.re,o=t.re+s*t.im;return{re:(e.re+e.im*s)/o,im:(e.im-e.re*s)/o}}const n=t.re/t.im,r=t.im+n*t.re;return{re:(e.re*n+e.im)/r,im:(e.im*n-e.re)/r}}function x8(e){return kk(xk(e),bk(e))}function b8(e){return{re:Math.sinh(e.re)*Math.cos(e.im),im:Math.cosh(e.re)*Math.sin(e.im)}}function k8(e){return{re:Math.cosh(e.re)*Math.cos(e.im),im:Math.sinh(e.re)*Math.sin(e.im)}}function v8(e){const t=Math.cosh(2*e.re)+Math.cos(2*e.im);return{re:Math.sinh(2*e.re)/t,im:Math.sin(2*e.im)/t}}function M8(e){const t={re:-e.im,im:e.re},n={re:1-t.re,im:-t.im},r={re:1+t.re,im:t.im},s=kk(n,r),o=lm(s);return{re:-o.im/2,im:o.re/2}}function $8(e){return{re:Math.floor(e.re),im:Math.floor(e.im)}}function C8(e){return{re:Math.ceil(e.re),im:Math.ceil(e.im)}}function S8(e){const t=n=>n>=0?Math.floor(n+.5):-Math.floor(-n+.5);return{re:t(e.re),im:t(e.im)}}function N8(e){return{re:Math.trunc(e.re),im:Math.trunc(e.im)}}function A8(e){if(e.re===0&&e.im===0)return{re:0,im:0};const t=Math.hypot(e.re,e.im);return{re:e.re/t,im:e.im/t}}const E8=Qn({name:"cos",cFnReal:"cos",jsFn:Math.cos,signRule:()=>"unknown",complex:{cFnComplex:"mtoc2_ccos",jsFnComplex:bk}}),I8=Qn({name:"sin",cFnReal:"sin",jsFn:Math.sin,signRule:()=>"unknown",complex:{cFnComplex:"mtoc2_csin",jsFnComplex:xk}}),F8={name:"rand",transfer(e,t){if(t>1)throw new W(`'rand' does not support multi-output (nargout=${t})`);if(e.length!==0)throw new W(`JS-JIT 'rand' supports only the scalar form rand() so far (got ${e.length} arg(s)); matrix/seed forms run in the interpreter`);return[Be("nonneg")]},emitJs(){return"$rand()"},call(){return[Ps()]}},j8=Qn({name:"tan",cFnReal:"tan",jsFn:Math.tan,signRule:()=>"unknown",complex:{cFnComplex:"mtoc2_ctan",jsFnComplex:x8}}),R8=Qn({name:"atan",cFnReal:"atan",jsFn:Math.atan,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_catan",jsFnComplex:M8}}),L8=Qn({name:"sinh",cFnReal:"sinh",jsFn:Math.sinh,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_csinh",jsFnComplex:b8}}),D8=Qn({name:"cosh",cFnReal:"cosh",jsFn:Math.cosh,signRule:()=>"positive",complex:{cFnComplex:"mtoc2_ccosh",jsFnComplex:k8}}),T8=Qn({name:"tanh",cFnReal:"tanh",jsFn:Math.tanh,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_ctanh",jsFnComplex:v8}}),P8=Qn({name:"asinh",cFnReal:"asinh",jsFn:Math.asinh,signRule:e=>e.sign}),B8=Qn({name:"exp",cFnReal:"exp",jsFn:Math.exp,signRule:()=>"positive",complex:{cFnComplex:"mtoc2_cexp",jsFnComplex:w8}}),um=Qn({name:"abs",cFnReal:"fabs",jsFn:Math.abs,signRule:e=>e.sign==="positive"||e.sign==="negative"||e.sign==="nonzero"?"positive":"nonneg"}),q8={name:"abs",transfer(e,t){if(e.length!==1)throw new le(`'abs' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'abs' does not support multi-output (nargout=${t})`);pr(e[0],"'abs' arg");const n=e[0];if(n.isComplex){if(De(n)){const o=An(n);if(o!==void 0){const i=Math.hypot(o.re,o.im);if(Number.isFinite(i))return[Be(ft(i),i)]}return[Be("nonneg")]}const r=rn(n);if(r!==void 0&&n.shape!==void 0){const o=Dt(n.shape);if(o<=wt){const i=new Float64Array(o);for(let a=0;a<o;a++)i[a]=Math.hypot(r.re[a],r.im[a]);return[et(n.shape,i)]}}const s=Zt(n.dims.slice());return s.sign="nonneg",[s]}return um.transfer(e,t)},emitC(e){const{argsC:t,argTypes:n,useRuntime:r}=e,s=n[0];return s.isComplex?(r("mtoc2_cscalar"),qe(s)?(r("mtoc2_tensor_unary_complex_math"),`mtoc2_tensor_abs_complex(${t[0]})`):`mtoc2_cabs(${t[0]})`):ul(um)(e)},emitJs(e){const{argsJs:t,argTypes:n,useRuntime:r}=e,s=n[0];return s.isComplex?qe(s)?(r("mtoc2_tensor_unary_complex_math"),r("mtoc2_cscalar"),`mtoc2_tensor_abs_complex(${t[0]})`):(r("mtoc2_cscalar"),`mtoc2_cabs(${t[0]})`):ko(um)(e)},call(e){const t=e.argTypes[0];if(t.isComplex){if(qe(t))return[tD(e.args[0])];const n=e.args[0],r=un(n)?n:{re:Number(n),im:0};return[wb(r)]}return fl(um)(e)},elementwise:!0},z8=Qn({name:"sign",cFnReal:"mtoc2_signum",jsFn:Math.sign,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_csign",jsFnComplex:A8}}),V8=Qn({name:"floor",cFnReal:"floor",jsFn:Math.floor,signRule:cm(!0,!1),complex:{cFnComplex:"mtoc2_cfloor",jsFnComplex:$8}}),U8=Qn({name:"ceil",cFnReal:"ceil",jsFn:Math.ceil,signRule:cm(!1,!0),complex:{cFnComplex:"mtoc2_cceil",jsFnComplex:C8}});function W8(e){return Math.sign(e)*Math.round(Math.abs(e))}const X8=Qn({name:"round",cFnReal:"mtoc2_round_half_away",jsFn:W8,jsExpr:e=>`(Math.sign(${e}) * Math.round(Math.abs(${e})))`,signRule:cm(!0,!0),complex:{cFnComplex:"mtoc2_cround",jsFnComplex:S8}}),H8=Qn({name:"fix",cFnReal:"trunc",jsFn:Math.trunc,jsExpr:e=>`Math.trunc(${e})`,signRule:cm(!0,!0),complex:{cFnComplex:"mtoc2_cfix",jsFnComplex:N8}}),Y8=Qn({name:"sqrt",cFnReal:"sqrt",jsFn:e=>Math.sqrt(e),signRule:e=>mR(e.sign)?"positive":"nonneg",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_csqrt",jsFnComplex:g8,liftOnDomainMiss:!0}});function fm(e){if(e.length<2)return 2;const t=e[1];if(t.kind==="Char"||t.kind==="String"){if(t.exact===void 0)throw new W("'norm' order arg must be a literal; non-literal text is not supported");const r=t.exact.toLowerCase();if(r==="fro")return 2;if(r==="inf")return 1/0;throw new le(`'norm' string order arg must be 'fro' or 'inf' (got '${t.exact}')`)}if(!Me(t)||t.isComplex||!De(t))throw new le(`'norm' order arg must be a real scalar or 'fro' / 'inf' (got ${ze(t)})`);const n=Je(t);if(n!==void 0)return n}function J8(e){if(De(e))return"scalar";if(!(e.dims.length===2&&(e.dims[0].kind==="exact"&&e.dims[0].value===1||e.dims[1].kind==="exact"&&e.dims[1].value===1)))throw new W(`'norm' input must be a scalar or vector (got ${ze(e)}); matrix-norm forms are not yet supported`);return"vector"}function Z8(e,t){if(t.length===0)return 0;let n;if(e===1/0){n=0;for(let r=0;r<t.length;r++){const s=Math.abs(t[r]);s>n&&(n=s)}}else if(e===-1/0){n=Math.abs(t[0]);for(let r=1;r<t.length;r++){const s=Math.abs(t[r]);s<n&&(n=s)}}else if(e===1){n=0;for(let r=0;r<t.length;r++)n+=Math.abs(t[r])}else if(e===2){let r=0;for(let s=0;s<t.length;s++)r+=t[s]*t[s];n=Math.sqrt(r)}else{let r=0;for(let s=0;s<t.length;s++)r+=Math.pow(Math.abs(t[s]),e);n=Math.pow(r,1/e)}return Number.isFinite(n)?n:void 0}function K8(e,t,n){if(t.length===0)return 0;const r=o=>Math.hypot(t[o],n[o]);let s;if(e===1/0){s=0;for(let o=0;o<t.length;o++){const i=r(o);i>s&&(s=i)}}else if(e===-1/0){s=r(0);for(let o=1;o<t.length;o++){const i=r(o);i<s&&(s=i)}}else if(e===2){let o=0;for(let i=0;i<t.length;i++)o+=t[i]*t[i]+n[i]*n[i];s=Math.sqrt(o)}else if(e===1){s=0;for(let o=0;o<t.length;o++)s+=r(o)}else{let o=0;for(let i=0;i<t.length;i++)o+=Math.pow(r(i),e);s=Math.pow(o,1/e)}return Number.isFinite(s)?s:void 0}function G8(e){return e===1/0?"INFINITY":e===-1/0?"-INFINITY":String(e)}function Q8(e){return e===1/0?"Infinity":e===-1/0?"-Infinity":String(e)}const O8={name:"norm",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'norm' expects 1..2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'norm' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'norm' arg must be a real or complex numeric (got ${ze(n)})`);if(n.elem!=="double")throw new le(`'norm' arg must be double (got ${n.elem})`);const r=J8(n),s=fm(e);if(r==="scalar"){if(!n.isComplex){const i=Je(n);if(i!==void 0){const a=Math.abs(i);if(Number.isFinite(a))return[Be(ft(a),a)]}return[Be("nonneg")]}const o=An(n);if(o!==void 0){const i=Math.hypot(o.re,o.im);if(Number.isFinite(i))return[Be(ft(i),i)]}return[Be("nonneg")]}if(s!==void 0)if(n.isComplex){const o=rn(n);if(o!==void 0){const i=K8(s,o.re,o.im);if(i!==void 0)return[Be(ft(i),i)]}}else{const o=Mt(n);if(o!==void 0){const i=Z8(s,o);if(i!==void 0)return[Be(ft(i),i)]}}return[Be("nonneg")]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];if(n("mtoc2_cscalar"),qe(r)){n("mtoc2_tensor_norm");const s=fm(t);if(s===2&&t.length<2)return r.isComplex?`mtoc2_norm2_complex(${e[0]})`:`mtoc2_norm2_real(${e[0]})`;const o=s!==void 0?G8(s):`(double)(${e[1]})`;return r.isComplex?`mtoc2_norm_p_complex(${e[0]}, ${o})`:`mtoc2_norm_p_real(${e[0]}, ${o})`}return r.isComplex?`mtoc2_cabs(${e[0]})`:`fabs(${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];if(qe(r)){n("mtoc2_tensor_norm");const s=fm(t);if(s===2&&t.length<2)return r.isComplex?`mtoc2_norm2_complex(${e[0]})`:`mtoc2_norm2_real(${e[0]})`;const o=s!==void 0?Q8(s):e[1];return r.isComplex?`mtoc2_norm_p_complex(${e[0]}, ${o})`:`mtoc2_norm_p_real(${e[0]}, ${o})`}return r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cabs(${e[0]})`):`Math.abs(${e[0]})`},call({args:e,argTypes:t}){const n=t[0];if(qe(n)){const s=fm(t),o=s!==void 0?s:Number(e[1]);return o===2&&t.length<2?[(n.isComplex?Cb:$b)(e[0])]:[(n.isComplex?W5:U5)(e[0],o)]}if(n.isComplex){const s=e[0],o=un(s)?s:{re:Number(s),im:0};return[wb(o)]}const r=typeof e[0]=="number"?e[0]:Number(e[0]);return[Math.abs(r)]}};function vk(e,t){if(!Me(e))throw new le(`${t} must be a numeric (got ${ze(e)})`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);return e}function Xr(e){if(De(e))return!0;if(e.dims.length!==2)return!1;const t=e.dims[0].kind==="exact"&&e.dims[0].value===1,n=e.dims[1].kind==="exact"&&e.dims[1].value===1;return t||n}function Mk(e){return e.shape!==void 0?Dt(e.shape):void 0}function e7(e){if(!(e.shape===void 0||e.shape.length!==2))return e.shape[1]}function $k(e){return Number.isFinite(e)?Be(ft(e),e):Be()}function t7(e,t,n,r){let s=0,o=0;for(let i=0;i<e.length;i++){const a=e[i],c=t!==void 0?t[i]:0,l=n[i],u=r!==void 0?r[i]:0;s+=a*l+c*u,o+=a*u-c*l}return{re:s,im:o}}const n7={name:"dot",transfer(e,t){if(e.length!==2)throw new le(`'dot' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'dot' does not support multi-output (nargout=${t})`);const n=vk(e[0],"'dot' arg 1"),r=vk(e[1],"'dot' arg 2"),s=n.isComplex||r.isComplex;if(De(n)&&De(r)){if(s){const l=Us(n),u=Us(r);return l!==void 0&&u!==void 0?[_t({re:l.re*u.re+l.im*u.im,im:l.re*u.im-l.im*u.re})]:[_t()]}const a=Je(n),c=Je(r);return a!==void 0&&c!==void 0?[$k(a*c)]:[Be()]}const o=Xr(n),i=Xr(r);if(o&&i){const a=Mk(n),c=Mk(r);if(a!==void 0&&c!==void 0&&a!==c)throw new le(`'dot' vectors must be same length (got ${a} and ${c})`);if(s){const f=n.isComplex?rn(n)?.re:Mt(n),h=n.isComplex?rn(n)?.im:void 0,m=r.isComplex?rn(r)?.re:Mt(r),p=r.isComplex?rn(r)?.im:void 0;if(f!==void 0&&m!==void 0&&f.length===m.length&&f.length<=wt){const d=t7(f,h,m,p);return[_t(d)]}return[_t()]}const l=Mt(n),u=Mt(r);if(l!==void 0&&u!==void 0&&l.length===u.length&&l.length<=wt){let f=0;for(let h=0;h<l.length;h++)f+=l[h]*u[h];return[$k(f)]}return[Be()]}if(!o&&!i&&n.shape!==void 0&&r.shape!==void 0&&n.shape.length===2&&r.shape.length===2&&n.shape[0]===r.shape[0]&&n.shape[1]===r.shape[1]){const a=e7(n)??0;if(s){const u=n.isComplex?rn(n)?.re:Mt(n),f=n.isComplex?rn(n)?.im:void 0,h=r.isComplex?rn(r)?.re:Mt(r),m=r.isComplex?rn(r)?.im:void 0;if(u!==void 0&&h!==void 0&&u.length===h.length&&u.length<=wt){const p=n.shape[0],d=new Float64Array(a),g=new Float64Array(a);for(let w=0;w<a;w++){let _=0,y=0;for(let b=0;b<p;b++){const k=w*p+b,M=u[k],$=f!==void 0?f[k]:0,N=h[k],E=m!==void 0?m[k]:0;_+=M*N+$*E,y+=M*E-$*N}d[w]=_,g[w]=y}return[Ut([1,a],{re:d,im:g})]}return[Ut([1,a])]}const c=Mt(n),l=Mt(r);if(c!==void 0&&l!==void 0&&c.length===l.length&&c.length<=wt){const u=n.shape[0],f=new Float64Array(a);for(let h=0;h<a;h++){let m=0;for(let p=0;p<u;p++){const d=h*u+p;m+=c[d]*l[d]}f[h]=m}return[et([1,a],f)]}return[et([1,a])]}throw new W(`'dot' supports two vectors of the same length, or two matrices of the same shape (got ${ze(n)} and ${ze(r)})`)},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=t[1],o=r.isComplex||s.isComplex;if(qe(r)&&qe(s))return n("mtoc2_dot_real"),o&&n("mtoc2_cscalar"),`${o?Xr(r)||Xr(s)?"mtoc2_dot_complex":"mtoc2_dot_complex_matrix":Xr(r)||Xr(s)?"mtoc2_dot_real":"mtoc2_dot_real_matrix"}(${e[0]}, ${e[1]})`;if(o){n("mtoc2_cscalar");const i=r.isComplex?e[0]:`mtoc2_cmake((double)(${e[0]}), 0.0)`,a=s.isComplex?e[1]:`mtoc2_cmake((double)(${e[1]}), 0.0)`;return`mtoc2_cmul(mtoc2_cconj(${i}), ${a})`}return`((${e[0]}) * (${e[1]}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0],s=t[1],o=r.isComplex||s.isComplex;if(qe(r)&&qe(s))return n("mtoc2_dot_real"),`${o?Xr(r)||Xr(s)?"mtoc2_dot_complex":"mtoc2_dot_complex_matrix":Xr(r)||Xr(s)?"mtoc2_dot_real":"mtoc2_dot_real_matrix"}(${e[0]}, ${e[1]})`;if(o){n("mtoc2_cscalar");const i=r.isComplex?e[0]:`mtoc2_cmake(${e[0]}, 0)`,a=s.isComplex?e[1]:`mtoc2_cmake(${e[1]}, 0)`;return`mtoc2_cmul(mtoc2_cconj(${i}), ${a})`}return`((${e[0]}) * (${e[1]}))`},call({args:e,argTypes:t}){const n=t[0],r=t[1],s=n.isComplex||r.isComplex;if(qe(n)&&qe(r))return s?Xr(n)||Xr(r)?[A6(e[0],e[1])]:[E6(e[0],e[1])]:Xr(n)||Xr(r)?[S6(e[0],e[1])]:[N6(e[0],e[1])];const o=e[0],i=e[1];if(s){const l=h=>un(h)?h:{re:typeof h=="number"?h:Number(h),im:0},u=l(o),f=l(i);return[{re:u.re*f.re+u.im*f.im,im:u.re*f.im-u.im*f.re}]}const a=typeof o=="number"?o:Number(o),c=typeof i=="number"?i:Number(i);return[a*c]}},y0=1e-6;function r7(e){if(!Me(e))throw new le(`'uniquetol' first arg must be numeric (got ${ze(e)})`);if(e.isComplex)throw new W("'uniquetol' on complex inputs is not yet supported");if(e.elem!=="double"&&e.elem!=="logical")throw new le(`'uniquetol' first arg must be double or logical (got ${e.elem})`);return e}function s7(e){if(!Me(e)||e.isComplex||!De(e))throw new le(`'uniquetol' tol arg must be a real scalar (got ${ze(e)})`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`'uniquetol' tol arg must be double or logical (got ${e.elem})`)}function mm(e){if(e.dims.length<2)return!1;const t=e.dims[0];return t.kind==="exact"&&t.value===1}const o7={name:"uniquetol",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'uniquetol' expects 1..2 arg(s), got ${e.length}`);if(t!==1)throw new W("'uniquetol' multi-output form ([c, ia, ic] = uniquetol(...)) is not yet supported");const n=r7(e[0]);if(e.length===2&&s7(e[1]),De(n)){const o=Je(n);return o!==void 0&&Number.isFinite(o)?[Be(ft(o),o)]:[Be()]}const s=mm(n)?[nn,{kind:"unknown"}]:[{kind:"unknown"},nn];return[Zt(s)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];if(De(r))return`(${e[0]})`;n("mtoc2_uniquetol_real");const s=t.length===2?`(double)(${e[1]})`:`${y0}`,o=mm(r)?1:0;return`mtoc2_uniquetol_real(${e[0]}, ${s}, ${o})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];if(De(r))return`(${e[0]})`;n("mtoc2_uniquetol_real");const s=t.length===2?e[1]:String(y0),o=mm(r)?1:0;return`mtoc2_uniquetol_real(${e[0]}, ${s}, ${o})`},call({args:e,argTypes:t}){const n=t[0];if(De(n))return[typeof e[0]=="number"?e[0]:Number(e[0])];let r=y0;if(t.length===2){const o=t[1],i=Je(o);r=i!==void 0?i:Number(e[1])}const s=mm(n)?1:0;return[kD(e[0],r,s)]}},i7=Qn({name:"log",cFnReal:"log",jsFn:Math.log,signRule:()=>"unknown",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_clog",jsFnComplex:lm,liftOnDomainMiss:!0}}),a7=Qn({name:"log2",cFnReal:"log2",jsFn:Math.log2,signRule:()=>"unknown",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_clog2",jsFnComplex:_8,liftOnDomainMiss:!0}}),c7=Qn({name:"log10",cFnReal:"log10",jsFn:Math.log10,signRule:()=>"unknown",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_clog10",jsFnComplex:y8,liftOnDomainMiss:!0}});function l7(e,t){if(t===0)return e;let n=e%t;return n!==0&&n<0!=t<0&&(n+=t),n}function u7(e,t){return t.sign}function f7(e,t){return`(((a, b) => { if (b===0) return a; let r = a % b; if (r !== 0 && (r < 0) !== (b < 0)) r += b; return r; })(${e}, ${t}))`}const m7=Of({name:"mod",cFn:"mtoc2_mod_real",helperBase:"mod",commutative:!1,fold:l7,jsScalarExpr:f7,signRule:u7,runtimeDep:"mtoc2_tensor_elemwise_real_fn"}),h7=Of({name:"rem",cFn:"fmod",helperBase:"rem",commutative:!1,fold:(e,t)=>e%t,jsScalarExpr:(e,t)=>`((${e}) % (${t}))`,signRule:e=>e.sign,runtimeDep:"mtoc2_tensor_elemwise_real_fn"}),p7=Of({name:"atan2",cFn:"atan2",helperBase:"atan2",commutative:!1,fold:Math.atan2,jsScalarExpr:(e,t)=>`Math.atan2(${e}, ${t})`,signRule:()=>"unknown",runtimeDep:"mtoc2_tensor_elemwise_real_fn"}),d7=Of({name:"hypot",cFn:"hypot",helperBase:"hypot",commutative:!0,fold:Math.hypot,jsScalarExpr:(e,t)=>`Math.hypot(${e}, ${t})`,signRule:()=>"nonneg",runtimeDep:"mtoc2_tensor_elemwise_real_fn"});function Ck(e,t){const n=Je(e);if(n===void 0||!Number.isInteger(n))throw new W(`'besselh' ${t} must be a compile-time integer (got non-exact or non-integer)`);return n}const g7={name:"besselh",transfer(e,t){if(e.length!==3)throw new le(`'besselh' expects 3 arg(s), got ${e.length}`);if(t!==1)throw new W(`'besselh' does not support multi-output (nargout=${t})`);for(let a=0;a<3;a++){if(!Me(e[a]))throw new le(`'besselh' arg ${a+1} must be a real numeric (got ${ze(e[a])})`);if(e[a].isComplex)throw new W("'besselh' with complex args is not yet supported")}const n=e[0],r=e[1],s=e[2],o=Ck(n,"arg 1 (nu)"),i=Ck(r,"arg 2 (kind)");if(o!==0&&o!==1)throw new W(`'besselh' supports only nu in {0, 1} today (got ${o})`);if(i!==1)throw new W(`'besselh' supports only kind == 1 today (got ${i})`);if(s.elem!=="double")throw new le(`'besselh' arg 3 (x) must be double (got ${s.elem})`);return qe(s)?[mr(s.dims.slice())]:[_t()]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_besselh"),n("mtoc2_cscalar");const r=t[0].exact,s=t[2];return qe(s)?r===0?`mtoc2_tensor_besselh0(${e[2]})`:`mtoc2_tensor_besselh1(${e[2]})`:r===0?`mtoc2_besselh0_scalar(${e[2]})`:`mtoc2_besselh1_scalar(${e[2]})`},emitJs(){throw new W("'besselh' is not yet implemented for the js-aot backend (needs a JS port of POSIX j0/j1/y0/y1; see numbl/helpers/bessel.ts)")},call(){throw new W("'besselh' is not yet implemented for the interpreter (needs a JS port of POSIX j0/j1/y0/y1; see numbl/helpers/bessel.ts)")}},hm=100;function x0(e,t){if(!Me(e))throw new le(`${t} must be a scalar real numeric (got ${e.kind})`);if(e.isComplex)throw new le(`${t} must be real (got complex)`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);if(!De(e))throw new le(`${t} must be a scalar (got tensor)`)}function w7(e,t,n){const r=new Float64Array(n);if(n===0)return r;if(n===1)return r[0]=t,r;r[0]=e,r[n-1]=t;for(let s=1;s<n-1;s++)r[s]=e+(t-e)*s/(n-1);return(n&1)===1&&!Number.isFinite(e)&&!Number.isFinite(t)&&Math.sign(e)!==Math.sign(t)&&(r[(n-1)/2]=0),r}const _7={name:"linspace",transfer(e,t){if(e.length<2||e.length>3)throw new le(`'linspace' expects 2..3 arg(s), got ${e.length}`);if(t!==1)throw new W(`'linspace' does not support multi-output (nargout=${t})`);x0(e[0],"'linspace' arg 1"),x0(e[1],"'linspace' arg 2"),e.length===3&&x0(e[2],"'linspace' arg 3");const n=Je(e[0]),r=Je(e[1]),s=e.length===3?Je(e[2]):hm;if(s!==void 0){const i=Math.round(s);if(i<=0)return[et([1,0])];if(i===1)return r!==void 0&&Number.isFinite(r)?[Be(ft(r),r)]:[Be()];if(n!==void 0&&r!==void 0&&Number.isFinite(n)&&Number.isFinite(r)&&i<=wt){const a=w7(n,r,i);let c=!0;for(let l=0;l<a.length;l++)if(!Number.isFinite(a[l])){c=!1;break}if(c)return[et([1,i],a)]}return[et([1,i])]}return[Zt([nn,{kind:"unknown"}])]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_linspace");const r=e[0],s=e[1],o=t.length===3?e[2]:`${hm}.0`;if(t.length===3){const i=Je(t[2]);if(i!==void 0&&Math.round(i)===1)return`((${r}), (${s}))`}return`mtoc2_tensor_linspace((double)(${r}), (double)(${s}), (long)lround(${o}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_linspace");const r=e[0],s=e[1],o=t.length===3?e[2]:String(hm);if(t.length===3){const i=Je(t[2]);if(i!==void 0&&Math.round(i)===1)return`((${r}), (${s}))`}return`mtoc2_tensor_linspace(${r}, ${s}, Math.round(${o}))`},call({args:e,argTypes:t}){const n=typeof e[0]=="number"?e[0]:Number(e[0]),r=typeof e[1]=="number"?e[1]:Number(e[1]);let s=hm;if(t.length===3){const o=typeof e[2]=="number"?e[2]:Number(e[2]);if(s=Math.round(o),s===1)return[r]}return[j5(n,r,s)]}},pm=50;function b0(e,t){if(!Me(e))throw new le(`${t} must be a scalar real numeric (got ${e.kind})`);if(e.isComplex)throw new le(`${t} must be real (got complex)`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);if(!De(e))throw new le(`${t} must be a scalar (got tensor)`)}const y7=()=>Zt([nn,{kind:"unknown"}]),x7={name:"logspace",transfer(e,t){if(e.length<2||e.length>3)throw new le(`'logspace' expects 2..3 arg(s), got ${e.length}`);if(t!==1)throw new W(`'logspace' does not support multi-output (nargout=${t})`);b0(e[0],"'logspace' arg 1"),b0(e[1],"'logspace' arg 2"),e.length===3&&b0(e[2],"'logspace' arg 3");const n=e.length===3?Je(e[2]):pm;if(n!==void 0){const r=Math.round(n);if(r<=0)return[et([1,0])];if(r>=2)return[et([1,r])]}return[y7()]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_logspace");const r=e[0],s=e[1],o=t.length===3?e[2]:`${pm}.0`;return`mtoc2_tensor_logspace((double)(${r}), (double)(${s}), (long)lround(${o}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_logspace");const r=e[0],s=e[1],o=t.length===3?e[2]:String(pm);return`mtoc2_tensor_logspace(${r}, ${s}, Math.round(${o}))`},call({args:e,argTypes:t}){const n=typeof e[0]=="number"?e[0]:Number(e[0]),r=typeof e[1]=="number"?e[1]:Number(e[1]);let s=pm;if(t.length===3){const o=typeof e[2]=="number"?e[2]:Number(e[2]);s=Math.round(o)}return[D5(n,r,s)]}},b7={name:"real",transfer(e,t){if(e.length!==1)throw new le(`'real' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'real' does not support multi-output (nargout=${t})`);pr(e[0],"'real' arg");const n=e[0];if(qe(n)){const s=Zt(n.dims.slice());return n.isComplex||(s.sign=n.sign),[s]}if(n.isComplex){const s=An(n);return s!==void 0?[Be(ft(s.re),s.re)]:[Be()]}const r=Je(n);return r!==void 0?[Be(ft(r),r)]:[Be(n.sign)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_real_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_creal(${e[0]})`):`(${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_real_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_creal(${e[0]})`):`(${e[0]})`},call({args:e,argTypes:t}){const n=t[0];return qe(n)?n.isComplex?[eD(e[0])]:[e[0]]:n.isComplex?[e[0].re]:[e[0]]},elementwise:!0},k7={name:"imag",transfer(e,t){if(e.length!==1)throw new le(`'imag' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'imag' does not support multi-output (nargout=${t})`);pr(e[0],"'imag' arg");const n=e[0];if(qe(n)){const r=Zt(n.dims.slice());return n.isComplex||(r.sign="zero"),[r]}if(n.isComplex){const r=An(n);return r!==void 0?[Be(ft(r.im),r.im)]:[Be()]}return[Be("zero",0)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_imag_complex(${e[0]})`):(n("mtoc2_tensor_elemwise_real"),`mtoc2_tensor_times_ts(${e[0]}, 0.0)`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cimag(${e[0]})`):"0.0"},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_imag_complex(${e[0]})`):(n("mtoc2_tensor_elemwise_real"),`mtoc2_tensor_times_ts(${e[0]}, 0)`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cimag(${e[0]})`):"0"},call({args:e,argTypes:t}){const n=t[0];if(qe(n)){if(n.isComplex)return[OL(e[0])];const r=e[0];return[{mtoc2Tag:"tensor",shape:r.shape.slice(),data:new Float64Array(r.data.length)}]}return n.isComplex?[e[0].im]:[0]},elementwise:!0},v7={name:"conj",transfer(e,t){if(e.length!==1)throw new le(`'conj' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'conj' does not support multi-output (nargout=${t})`);pr(e[0],"'conj' arg");const n=e[0];if(!qe(n)){if(n.isComplex){const i=An(n);return i!==void 0?[_t({re:i.re,im:-i.im})]:[_t()]}const o=Je(n);return o!==void 0?[Be(ft(o),o)]:[Be(n.sign)]}if(n.isComplex){const o=rn(n);if(o!==void 0&&n.shape!==void 0&&Dt(n.shape)<=wt){const a=new Float64Array(o.re.length),c=new Float64Array(o.im.length);for(let l=0;l<o.re.length;l++)a[l]=o.re[l],c[l]=-o.im[l];return[Ut(n.shape,{re:a,im:c})]}return[mr(n.dims.slice())]}const r=Mt(n);if(r!==void 0&&n.shape!==void 0)return[et(n.shape,r)];const s=Zt(n.dims.slice());return s.sign=n.sign,[s]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_conj_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cconj(${e[0]})`):`(${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_conj_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cconj(${e[0]})`):`(${e[0]})`},call({args:e,argTypes:t}){const n=t[0];if(qe(n))return n.isComplex?[QL(e[0])]:[e[0]];if(n.isComplex){const r=e[0];return[{re:r.re,im:-r.im}]}return[e[0]]},elementwise:!0},M7={name:"angle",transfer(e,t){if(e.length!==1)throw new le(`'angle' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'angle' does not support multi-output (nargout=${t})`);pr(e[0],"'angle' arg");const n=e[0];if(qe(n))throw new W("'angle' on a tensor is not yet supported");if(n.isComplex){const s=An(n);if(s!==void 0){const o=Math.atan2(s.im,s.re);if(Number.isFinite(o))return[Be(ft(o),o)]}return[Be()]}const r=Je(n);if(r!==void 0){const s=Math.atan2(0,r);if(Number.isFinite(s))return[Be(ft(s),s)]}return[Be()]},emitC({argsC:e,argTypes:t,useRuntime:n}){return t[0].isComplex?(n("mtoc2_cscalar"),`mtoc2_cangle(${e[0]})`):`atan2(0.0, ${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){return t[0].isComplex?(n("mtoc2_cscalar"),`mtoc2_cangle(${e[0]})`):`Math.atan2(0, ${e[0]})`},call({args:e,argTypes:t}){if(t[0].isComplex){const s=e[0];return[Math.atan2(s.im,s.re)]}const r=typeof e[0]=="number"?e[0]:Number(e[0]);return[Math.atan2(0,r)]}};function Sk(e,t,n,r){const s=Number.isFinite(t)?String(t):t>0?"Infinity":t<0?"-Infinity":"NaN";return{name:e,transfer(o,i){if(o.length!==0)throw new le(`'${e}' expects 0 arg(s), got ${o.length}`);if(i!==1)throw new W(`'${e}' does not support multi-output (nargout=${i})`);return[Be(n,t)]},emitC(){return r},emitJs(){return s},call(){return[t]},elementwise:!0}}function dm(e,t,n,r){const s=bl(e,t,"mtoc2_tensor_fill_nd","mtoc2_tensor_fill_square",{minArgs:0,cFillValue:r});return{name:e,transfer(o,i){if(o.length===0){if(i!==1)throw new W(`'${e}' does not support multi-output (nargout=${i})`);return[Be(n,t)]}return s.transfer(o,i)},emitC(o){return o.argTypes.length===0?r:ul(s)(o)},emitJs(o){return o.argTypes.length===0?Number.isFinite(t)?String(t):t>0?"Infinity":"NaN":ko(s)(o)},call(o){return o.argTypes.length===0?[t]:fl(s)(o)},elementwise:!0}}const $7=Sk("pi",Math.PI,"positive","3.141592653589793"),C7=Sk("eps",Number.EPSILON,"positive","2.220446049250313e-16"),S7=dm("Inf",1/0,"positive","INFINITY"),N7=dm("inf",1/0,"positive","INFINITY"),A7=dm("NaN",NaN,"unknown","NAN"),E7=dm("nan",NaN,"unknown","NAN");function gm(e,t,n){const r={kind:"Numeric",elem:"logical",isComplex:!1,dims:e,sign:"nonneg"};return t!==void 0&&(r.shape=t.slice()),n!==void 0&&(r.exact=n),r}const I7={name:"not",transfer(e,t){if(e.length!==1)throw new le(`'not' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'not' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'~' / 'not' arg must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'~' / 'not' arg must be a real double or logical (got ${n.elem})`);if(De(n)){if(n.isComplex){const o=An(n);return o!==void 0?[at(o.re===0&&o.im===0)]:[at()]}const s=Je(n);return s!==void 0?[at(s===0)]:[at()]}if(n.isComplex){const s=rn(n);if(n.shape!==void 0&&s!==void 0){const o=Dt(n.shape);if(o<=wt){const i=new Float64Array(o);for(let a=0;a<o;a++)i[a]=s.re[a]===0&&s.im[a]===0?1:0;return[gm(n.dims,n.shape,i)]}}return[gm(n.dims,n.shape)]}const r=Mt(n);if(n.shape!==void 0&&r!==void 0&&Dt(n.shape)<=wt){const o=new Float64Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]===0?1:0;return[gm(n.dims,n.shape,o)]}return[gm(n.dims,n.shape)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not_complex(${e[0]})`):(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`(!mtoc2_cnonzero(${e[0]}))`):`(!(${e[0]}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not_complex(${e[0]})`):(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`(!mtoc2_cnonzero(${e[0]}))`):r.elem==="logical"?`(!(${e[0]}))`:`((${e[0]}) === 0)`},call({args:e,argTypes:t}){const n=t[0];if(qe(n))return n.isComplex?[L5(e[0])]:[R5(e[0])];if(n.isComplex){const s=e[0],o=un(s)?s:{re:Number(s),im:0};return[!VR(o)]}return[(typeof e[0]=="number"?e[0]:Number(e[0]))===0]}};function Nk(e,t,n){if(!Me(e))throw new le(`${t} must be a real or complex scalar (got ${ze(e)}); '${n}' requires scalar operands (numbl accepts tensors via toBool, but mtoc2 follows MATLAB)`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be a real double or logical (got ${e.elem})`);if(!De(e))throw new le(`${t} must be a scalar (got ${ze(e)}); '${n}' requires scalar operands (numbl accepts tensors via toBool, but mtoc2 follows MATLAB — use elementwise '|' / '&' when added)`)}function Ak(e){if(!Me(e))return;if(e.isComplex){const n=Us(e);return n===void 0?void 0:n.re!==0||n.im!==0}const t=Je(e);if(t!==void 0)return t!==0}function wm(e,t,n){const r=n==="or"?"||":"&&";return{name:e,transfer(s,o){if(s.length!==2)throw new le(`'${e}' expects 2 arg(s), got ${s.length}`);if(o!==1)throw new W(`'${e}' does not support multi-output (nargout=${o})`);Nk(s[0],`'${t}' left operand`,t),Nk(s[1],`'${t}' right operand`,t);const i=Ak(s[0]),a=Ak(s[1]);return n==="or"?i===!0?[at(!0)]:i!==void 0&&a!==void 0?[at(a)]:[at()]:i===!1?[at(!1)]:i!==void 0&&a!==void 0?[at(a)]:[at()]},emitC({argsC:s,argTypes:o,useRuntime:i}){(o[0].isComplex||o[1].isComplex)&&i("mtoc2_cscalar");const c=o[0].isComplex?`mtoc2_cnonzero(${s[0]})`:`(${s[0]})`,l=o[1].isComplex?`mtoc2_cnonzero(${s[1]})`:`(${s[1]})`;return`(${c} ${r} ${l})`},emitJs({argsJs:s,argTypes:o,useRuntime:i}){const a=o[0],c=o[1];(a.isComplex||c.isComplex)&&i("mtoc2_cscalar");const u=(m,p)=>m.isComplex?`mtoc2_cnonzero(${p})`:m.elem==="logical"?`(${p})`:`((${p}) !== 0)`,f=u(a,s[0]),h=u(c,s[1]);return`(${f} ${r} ${h})`},call({args:s,argTypes:o}){const i=o[0],a=o[1],c=(f,h)=>{if(h){const p=f;return p.re!==0||p.im!==0}return(typeof f=="number"?f:Number(f))!==0},l=c(s[0],i.isComplex),u=c(s[1],a.isComplex);return[n==="or"?l||u:l&&u]}}}const F7=wm("oror","||","or"),j7=wm("andand","&&","and"),R7=wm("or","|","or"),L7=wm("and","&","and");function Ek(e,t){if(!Me(e))throw new le(`${t} must be numeric (got ${e.kind})`);if(e.isComplex)throw new W("'xor' on complex operands is not JIT-compiled");if(!De(e))throw new W("'xor' on tensor operands is not JIT-compiled");if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);return e}const D7={name:"xor",transfer(e,t){if(e.length!==2)throw new le(`'xor' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'xor' does not support multi-output (nargout=${t})`);const n=Ek(e[0],"'xor' arg 1"),r=Ek(e[1],"'xor' arg 2"),s=Je(n),o=Je(r);return s!==void 0&&o!==void 0?[at(s!==0!=(o!==0))]:[at()]},emitC({argsC:e}){return`(((${e[0]}) != 0) != ((${e[1]}) != 0))`},emitJs({argsJs:e}){return`((Number(${e[0]}) !== 0) !== (Number(${e[1]}) !== 0))`},call({args:e}){const t=Number(e[0]),n=Number(e[1]);return[t!==0!=(n!==0)]}};function _m(e,t){return!ji(e)&&!al(e)?!1:cl(e,t)!==void 0}function ym(e){if(!xo(e)&&!Jo(e))throw new le(`'isfield' second arg must be a char or string (got ${ze(e)})`);if(e.exact===void 0)throw new W(`'isfield' requires a literal field name; got a non-literal ${e.kind.toLowerCase()}`);return e.exact}const T7={name:"isfield",transfer(e,t){if(e.length!==2)throw new le(`'isfield' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isfield' does not support multi-output (nargout=${t})`);const n=ym(e[1]);return[at(_m(e[0],n))]},emitC({argTypes:e}){const t=ym(e[1]);return _m(e[0],t)?"1.0":"0.0"},emitJs({argTypes:e}){const t=ym(e[1]);return _m(e[0],t)?"true":"false"},call({argTypes:e}){const t=ym(e[1]);return[_m(e[0],t)]}};function k0(e){if(Me(e))return e.shape===void 0?void 0:Dt(e.shape)===1;if(Jo(e))return!0;if(xo(e)||ji(e)||al(e)||Mf(e))return!1}function P7(e){if(e.kind!=="Numeric"&&e.kind!=="String"&&e.kind!=="Char"&&e.kind!=="Struct"&&e.kind!=="Class"&&e.kind!=="Handle"&&e.kind!=="Unknown")throw new le(`'isscalar' got an unsupported argument type (${ze(e)})`)}const B7={name:"isscalar",transfer(e,t){if(e.length!==1)throw new le(`'isscalar' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isscalar' does not support multi-output (nargout=${t})`);const n=e[0];P7(n);const r=k0(n);return[r===void 0?at():at(r)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=k0(r);return s!==void 0?s?"1.0":"0.0":(n("mtoc2_numel"),`(mtoc2_numel(${e[0]}) == 1)`)},emitJs({argsJs:e,argTypes:t}){const n=t[0],r=k0(n);return r!==void 0?r?"true":"false":`(${e[0]}.shape.reduce((a,b)=>a*b, 1) === 1)`},call({args:e}){const t=e[0];return typeof t=="number"||typeof t=="boolean"?[!0]:un(t)?[!0]:typeof t=="string"?[!0]:Er(t)?[!1]:Wt(t)?[t.data.length===1]:Hd(t)?[!1]:[!1]}},q7={name:"iscell",transfer(e,t){if(e.length!==1)throw new le(`'iscell' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'iscell' does not support multi-output (nargout=${t})`);return[at(ys(e[0]))]},emitC({argTypes:e}){return ys(e[0])?"1.0":"0.0"},emitJs({argTypes:e}){return ys(e[0])?"true":"false"},call({args:e}){const t=e[0];return typeof t=="object"&&t!==null&&t.mtoc2Tag==="cell"?[!0]:[!1]}},z7={name:"isstruct",transfer(e,t){if(e.length!==1)throw new le(`'isstruct' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isstruct' does not support multi-output (nargout=${t})`);return[at(ji(e[0]))]},emitC({argTypes:e}){return ji(e[0])?"1.0":"0.0"},emitJs({argTypes:e}){return ji(e[0])?"true":"false"},call({args:e}){const t=e[0];return typeof t=="object"&&t!==null&&!Wt(t)&&!Er(t)&&t.mtoc2Tag!=="cell"&&t.mtoc2Class===void 0&&t.mtoc2Handle!==!0?[!0]:[!1]}};function v0(e){return al(e)?e.className:ji(e)?"struct":Mf(e)?"function_handle":xo(e)?"char":Jo(e)?"string":ys(e)?"cell":Me(e)?e.elem==="logical"?"logical":"double":null}function M0(e,t,n){return t===e?!0:e==="numeric"?Me(n)&&n.elem!=="logical":!1}const V7={name:"isa",transfer(e,t){if(e.length!==2)throw new le(`'isa' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isa' does not support multi-output (nargout=${t})`);const n=e[1];if(!xo(n)&&!Jo(n))throw new le("'isa' second argument must be a class name (char or string)");if(n.exact===void 0)throw new W("'isa' requires a statically-known class name (got a runtime text value)");const r=v0(e[0]);return r===null?[at()]:[at(M0(n.exact,r,e[0]))]},emitC({argTypes:e}){const t=e[1];if((xo(t)||Jo(t))&&t.exact!==void 0){const n=v0(e[0]);if(n!==null)return M0(t.exact,n,e[0])?"1.0":"0.0"}return"0.0"},emitJs({argTypes:e}){const t=e[1];if((xo(t)||Jo(t))&&t.exact!==void 0){const n=v0(e[0]);if(n!==null)return M0(t.exact,n,e[0])?"true":"false"}return"false"},call({args:e}){const t=e[0],n=e[1];let r;typeof n=="string"?r=n:n&&typeof n=="object"&&Er(n)?r=n.value:r=String(n);let s="unknown";if(typeof t=="number")s="double";else if(typeof t=="boolean")s="logical";else if(typeof t=="string")s="string";else if(t!==null&&typeof t=="object")if(Er(t))s="char";else if(Wt(t)){const o=t.mtoc2Tag;s="double"}else t.mtoc2Tag==="cell"?s="cell":t.mtoc2Handle===!0?s="function_handle":t.mtoc2Class!==void 0?s=t.mtoc2Class:s="struct";return s===r?[!0]:r==="numeric"?s==="double"?[!0]:[!1]:[!1]}},U7={name:"fieldnames",transfer(e,t){if(e.length!==1)throw new le(`'fieldnames' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'fieldnames' does not support multi-output (nargout=${t})`);const n=e[0];if(!ji(n)&&!al(n))throw new le("'fieldnames' argument must be a struct or class instance");return[Pr]},emitC(){throw new W("'fieldnames' is interpreter-only; the c-aot backend can't materialize a runtime-length cell of chars")},emitJs(){throw new W("'fieldnames' is interpreter-only; the js-aot backend can't materialize a runtime-length cell of chars")},call({args:e}){const t=e[0];if(t===null||typeof t!="object")throw new Error("fieldnames: argument must be a struct or class");const n=t;if(Wt(n)||Er(n))throw new Error("fieldnames: argument must be a struct or class");const r=t;if(r.mtoc2Tag==="cell"||r.mtoc2Handle===!0||r.mtoc2Tag==="tensor"||r.mtoc2Tag==="char")throw new Error("fieldnames: argument must be a struct or class");const s=Object.keys(t),o=s.map(i=>Wr(i));return[{mtoc2Tag:"cell",shape:[s.length,1],data:o}]}},W7={name:"isnumeric",transfer(e,t){if(e.length!==1)throw new le(`'isnumeric' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isnumeric' does not support multi-output (nargout=${t})`);const n=e[0];return Me(n)&&n.elem!=="logical"?[at(!0)]:[at(!1)]},emitC({argTypes:e}){const t=e[0];return Me(t)&&t.elem!=="logical"?"1.0":"0.0"},emitJs({argTypes:e}){const t=e[0];return Me(t)&&t.elem!=="logical"?"true":"false"},call({args:e}){const t=e[0];return typeof t=="number"?[!0]:typeof t=="boolean"?[!1]:un(t)?[!0]:Wt(t)?[!t.isLogical]:[!1]}};function X7(e,t){if(!Me(e))return e;const n={...e,elem:"logical"};return n.sign=t===1?"positive":"zero",n}function Ik(e){const t=e==="true"?1:0,n=t===1?bl(e,1,"mtoc2_tensor_ones_nd","mtoc2_tensor_ones_square",{minArgs:1}):bl(e,0,"mtoc2_tensor_zeros_nd","mtoc2_tensor_zeros_square",{minArgs:1});return{name:e,transfer(r,s){if(s!==1)throw new W(`'${e}' does not support multi-output (nargout=${s})`);return r.length===0?[at(t===1)]:n.transfer(r,s).map(o=>X7(o,t))},emitC(r){if(r.argTypes.length===0)return t===1?"1.0":"0.0";if(!n.emitC)throw new le(`internal: '${e}' shape constructor has no emitC`);return n.emitC(r)},emitJs(r){if(r.argTypes.length===0)return t===1?"true":"false";if(!n.emitJs)throw new le(`internal: '${e}' shape constructor has no emitJs`);return n.emitJs(r)},call(r){if(r.argTypes.length===0)return[t===1];if(!n.call)throw new le(`internal: '${e}' shape constructor has no call`);return n.call(r)},elementwise:!0}}const H7=Ik("true"),Y7=Ik("false");function xm(e){return Me(e)?De(e)?e.isComplex?"cs":"rs":e.isComplex?"ct":"rt":"other"}function J7(e,t,n){if(t.length<2)throw new le(`'${e}' expects at least 2 arg(s), got ${t.length}`);if(n>1)throw new W(`'${e}' does not support multi-output (nargout=${n})`)}function Z7(e,t,n,r,s){const o=xm(e),i=xm(n),a=()=>s("mtoc2_isequal"),c=()=>s("mtoc2_cscalar");if(o==="rs"&&i==="rs")return`(${t} == ${r} ? 1.0 : 0.0)`;if(o==="rs"&&i==="cs")return c(),`(cimag(${r}) == 0.0 && creal(${r}) == ${t} ? 1.0 : 0.0)`;if(o==="cs"&&i==="rs")return c(),`(cimag(${t}) == 0.0 && creal(${t}) == ${r} ? 1.0 : 0.0)`;if(o==="cs"&&i==="cs")return c(),`(creal(${t}) == creal(${r}) && cimag(${t}) == cimag(${r}) ? 1.0 : 0.0)`;if(o==="rs"&&i==="rt")return a(),`mtoc2_isequal_st(${t}, ${r})`;if(o==="rt"&&i==="rs")return a(),`mtoc2_isequal_st(${r}, ${t})`;if(o==="rs"&&i==="ct"||o==="ct"&&i==="rs")return"0.0";if(o==="cs"&&i==="rt")return a(),c(),`(cimag(${t}) == 0.0 ? mtoc2_isequal_st(creal(${t}), ${r}) : 0.0)`;if(o==="rt"&&i==="cs")return a(),c(),`(cimag(${r}) == 0.0 ? mtoc2_isequal_st(creal(${r}), ${t}) : 0.0)`;if(o==="rt"&&i==="rt")return a(),`mtoc2_isequal_tt(${t}, ${r})`;if(o==="rt"&&i==="ct"||o==="ct"&&i==="rt")return"0.0";throw new W("'isequal' with these argument types is not yet supported by the AOT backends (complex-tensor, char/string, struct or cell comparison); the interpreter handles it")}function K7(e,t,n,r,s){const o=xm(e),i=xm(n),a=()=>s("mtoc2_isequal"),c=(f,h)=>Me(f)&&De(f)&&f.elem==="logical"?`(+(${h}))`:h,l=c(e,t),u=c(n,r);if(o==="rs"&&i==="rs")return`(${l} === ${u} ? 1 : 0)`;if(o==="rs"&&i==="cs")return`(${r}.im === 0 && ${r}.re === ${l} ? 1 : 0)`;if(o==="cs"&&i==="rs")return`(${t}.im === 0 && ${t}.re === ${u} ? 1 : 0)`;if(o==="cs"&&i==="cs")return`(${t}.re === ${r}.re && ${t}.im === ${r}.im ? 1 : 0)`;if(o==="rs"&&i==="rt")return a(),`mtoc2_isequal_st(${l}, ${r})`;if(o==="rt"&&i==="rs")return a(),`mtoc2_isequal_st(${u}, ${t})`;if(o==="rs"&&i==="ct"||o==="ct"&&i==="rs")return"0";if(o==="cs"&&i==="rt")return a(),`(${t}.im === 0 ? mtoc2_isequal_st(${t}.re, ${r}) : 0)`;if(o==="rt"&&i==="cs")return a(),`(${r}.im === 0 ? mtoc2_isequal_st(${r}.re, ${t}) : 0)`;if(o==="rt"&&i==="rt")return a(),`mtoc2_isequal_tt(${t}, ${r})`;if(o==="rt"&&i==="ct"||o==="ct"&&i==="rt")return"0";throw new W("'isequal' with these argument types is not yet supported by the AOT backends (complex-tensor, char/string, struct or cell comparison); the interpreter handles it")}function Fk(e){return Er(e)?e.value:typeof e=="string"?e:null}function jk(e){return typeof e=="number"?e:typeof e=="boolean"?e?1:0:null}function G7(e,t){if(e.data.length!==t.data.length||e.shape.length!==t.shape.length)return!1;for(let n=0;n<e.shape.length;n++)if(e.shape[n]!==t.shape[n])return!1;for(let n=0;n<e.data.length;n++)if(e.data[n]!==t.data[n])return!1;if(e.imag||t.imag){if(!e.imag||!t.imag)return!1;for(let n=0;n<e.imag.length;n++)if(e.imag[n]!==t.imag[n])return!1}return!0}function Rk(e,t){const n=Fk(e),r=Fk(t);if(n!==null&&r!==null)return n===r;if(n!==null||r!==null)return!1;const s=jk(e),o=jk(t);if(s!==null&&o!==null)return s===o;if(un(e)&&un(t))return e.re===t.re&&e.im===t.im;if(un(e)&&o!==null)return e.re===o&&e.im===0;if(s!==null&&un(t))return t.re===s&&t.im===0;if(Wt(e)&&Wt(t))return G7(e,t);if(Wt(e)&&o!==null)return e.data.length===1&&!e.imag&&e.data[0]===o;if(s!==null&&Wt(t))return t.data.length===1&&!t.imag&&t.data[0]===s;if(Wt(e)&&un(t))return e.data.length===1&&e.data[0]===t.re&&(e.imag?e.imag[0]===t.im:t.im===0);if(un(e)&&Wt(t))return t.data.length===1&&t.data[0]===e.re&&(t.imag?t.imag[0]===e.im:e.im===0);if(Lk(e)&&Lk(t)){const i=e,a=t,c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(const u of c)if(!(u in a)||!Rk(i[u],a[u]))return!1;return!0}return!1}function Lk(e){return typeof e=="object"&&e!==null&&!Wt(e)&&!Er(e)&&!un(e)&&!("mtoc2Handle"in e)}const Q7={name:"isequal",transfer(e,t){return J7("isequal",e,t),[at()]},emitC({argTypes:e,argsC:t,useRuntime:n}){const r=[];for(let s=1;s<e.length;s++)r.push(`(${Z7(e[0],t[0],e[s],t[s],n)}) != 0.0`);return`(${r.join(" && ")})`},emitJs({argTypes:e,argsJs:t,useRuntime:n}){const r=[];for(let s=1;s<e.length;s++)r.push(`(${K7(e[0],t[0],e[s],t[s],n)}) !== 0`);return`(${r.join(" && ")})`},call({args:e}){for(let t=1;t<e.length;t++)if(!Rk(e[0],e[t]))return[!1];return[!0]}};function O7(e,t){if(e.length!==1)throw new le(`'isreal' expects 1 arg(s), got ${e.length}`);if(t>1)throw new W(`'isreal' does not support multi-output (nargout=${t})`)}function $0(e){if(!Me(e)||!e.isComplex)return!0;if(!De(e))return"runtime";const t=e.exact;if(t!==void 0&&typeof t=="object"&&"im"in t){const n=t.im;if(typeof n=="number")return n===0}return"runtime"}const eP={name:"isreal",transfer(e,t){O7(e,t);const n=$0(e[0]);return n==="runtime"?[at()]:[at(n)]},emitC({argTypes:e,argsC:t,useRuntime:n}){const r=e[0],s=$0(r);return s===!0?"1.0":s===!1?"0.0":Me(r)&&r.isComplex&&!De(r)?(n("mtoc2_tensor_imag_all_zero"),`mtoc2_tensor_imag_all_zero(${t[0]})`):(n("mtoc2_cscalar"),`(cimag(${t[0]}) == 0.0)`)},emitJs({argTypes:e,argsJs:t,useRuntime:n}){const r=e[0],s=$0(r);return s===!0?"true":s===!1?"false":Me(r)&&r.isComplex&&!De(r)?(n("mtoc2_tensor_imag_all_zero"),`mtoc2_tensor_imag_all_zero(${t[0]})`):`(${t[0]}.im === 0)`},call({args:e}){const t=e[0];return typeof t=="number"||typeof t=="boolean"?[!0]:un(t)?[t.im===0]:Wt(t)?[F5(t)]:[!0]}};function Dk(e){if(!Me(e))throw new W("'isempty' on a non-numeric value of unknown size is not supported by the AOT backends; the interpreter handles it")}function tP(e,t){if(e.length!==1)throw new le(`'isempty' expects 1 arg(s), got ${e.length}`);if(t>1)throw new W(`'isempty' does not support multi-output (nargout=${t})`)}function C0(e){return Me(e)?De(e)?!1:e.shape!==void 0?Dt(e.shape)===0:"runtime":xo(e)?e.exact!==void 0?e.exact.length===0:"runtime":!1}const nP={name:"isempty",transfer(e,t){tP(e,t);const n=C0(e[0]);return n==="runtime"?[at()]:[at(n)]},emitC({argTypes:e,argsC:t,useRuntime:n}){const r=C0(e[0]);return r===!0?"1.0":r===!1?"0.0":(Dk(e[0]),n("mtoc2_numel"),`(mtoc2_numel(${t[0]}) == 0)`)},emitJs({argTypes:e,argsJs:t}){const n=C0(e[0]);return n===!0?"true":n===!1?"false":(Dk(e[0]),`(${t[0]}.shape.reduce((a,b)=>a*b,1) === 0)`)},call({args:e}){const t=e[0];return typeof t=="number"||typeof t=="boolean"?[!1]:Wt(t)?[t.data.length===0]:Er(t)?[t.value.length===0]:typeof t=="string"?[!1]:[!1]}};function bm(e){return{...e,elem:"logical",sign:"nonneg"}}function km(e){const{name:t,cScalar:n,jsScalar:r,jsFn:s,tensorHelper:o,complex:i}=e;return{name:t,transfer(a,c){if(a.length!==1)throw new le(`'${t}' expects 1 arg(s), got ${a.length}`);if(c!==1)throw new W(`'${t}' does not support multi-output (nargout=${c})`);i!==void 0?pr(a[0],`'${t}' arg`):ml(a[0],`'${t}' arg`);const l=a[0];if(l.isComplex){if(De(l)){const h=An(l);return h!==void 0?[at(i.jsFnComplex(h.re,h.im))]:[at()]}const f=rn(l);if(f!==void 0&&l.shape!==void 0){const h=Dt(l.shape);if(h<=wt){const m=new Float64Array(h);for(let p=0;p<h;p++)m[p]=i.jsFnComplex(f.re[p],f.im[p])?1:0;return[bm(et(l.shape,m))]}}return[bm(Zt(l.dims.slice()))]}if(De(l)){const f=Je(l);return f!==void 0?[at(s(f))]:[at()]}const u=Mt(l);if(u!==void 0&&l.shape!==void 0){const f=Dt(l.shape);if(f<=wt){const h=new Float64Array(f);for(let m=0;m<f;m++)h[m]=s(u[m])?1:0;return[bm(et(l.shape,h))]}}return[bm(Zt(l.dims.slice()))]},emitC({argsC:a,argTypes:c,useRuntime:l}){const u=c[0];if(u.isComplex){if(l("mtoc2_cscalar"),qe(u))return l("mtoc2_tensor_predicate"),`${i.tensorHelperComplex}(${a[0]})`;const f=`creal(${a[0]})`,h=`cimag(${a[0]})`;return`(${i.cScalarComplex(f,h)})`}return qe(u)?(l(o),`mtoc2_tensor_${t}(${a[0]})`):n(a[0])},emitJs({argsJs:a,argTypes:c,useRuntime:l}){const u=c[0];if(u.isComplex)return qe(u)?(l("mtoc2_tensor_predicate"),`${i.tensorHelperComplex}(${a[0]})`):`(${i.jsScalarComplex(`${a[0]}.re`,`${a[0]}.im`)})`;if(qe(u))return l(o),`mtoc2_tensor_${t}(${a[0]})`;const f=u.elem==="double"?a[0]:`(+(${a[0]}))`;return r(f)},call({args:a,argTypes:c}){const l=c[0],u=a[0];if(qe(l)&&Wt(u)){const h=new Float64Array(u.data.length);if(u.imag!==void 0&&i!==void 0)for(let p=0;p<u.data.length;p++)h[p]=i.jsFnComplex(u.data[p],u.imag[p])?1:0;else for(let p=0;p<u.data.length;p++)h[p]=s(u.data[p])?1:0;return[{mtoc2Tag:"tensor",shape:u.shape.slice(),data:h,isLogical:!0}]}if(i!==void 0&&un(u))return[i.jsFnComplex(u.re,u.im)];const f=typeof u=="number"?u:Number(u);return[s(f)]},elementwise:!0}}const rP=km({name:"isnan",cScalar:e=>`isnan(${e})`,jsScalar:e=>`Number.isNaN(${e})`,jsFn:Number.isNaN,tensorHelper:"mtoc2_tensor_predicate",complex:{cScalarComplex:(e,t)=>`isnan(${e}) || isnan(${t})`,jsScalarComplex:(e,t)=>`Number.isNaN(${e}) || Number.isNaN(${t})`,jsFnComplex:(e,t)=>Number.isNaN(e)||Number.isNaN(t),tensorHelperComplex:"mtoc2_tensor_isnan_complex"}}),sP=km({name:"logical",cScalar:e=>`((${e}) != 0.0)`,jsScalar:e=>`((${e}) !== 0)`,jsFn:e=>e!==0,tensorHelper:"mtoc2_tensor_predicate"}),S0=e=>e===1/0||e===-1/0,oP=km({name:"isinf",cScalar:e=>`(isinf(${e}) != 0)`,jsScalar:e=>`(Math.abs(${e}) === Infinity)`,jsFn:S0,tensorHelper:"mtoc2_tensor_predicate",complex:{cScalarComplex:(e,t)=>`isinf(${e}) || isinf(${t})`,jsScalarComplex:(e,t)=>`Math.abs(${e}) === Infinity || Math.abs(${t}) === Infinity`,jsFnComplex:(e,t)=>S0(e)||S0(t),tensorHelperComplex:"mtoc2_tensor_isinf_complex"}}),iP=km({name:"isfinite",cScalar:e=>`isfinite(${e})`,jsScalar:e=>`Number.isFinite(${e})`,jsFn:Number.isFinite,tensorHelper:"mtoc2_tensor_predicate",complex:{cScalarComplex:(e,t)=>`isfinite(${e}) && isfinite(${t})`,jsScalarComplex:(e,t)=>`Number.isFinite(${e}) && Number.isFinite(${t})`,jsFnComplex:(e,t)=>Number.isFinite(e)&&Number.isFinite(t),tensorHelperComplex:"mtoc2_tensor_isfinite_complex"}});function vm(e){switch(e.kind){case"Numeric":return e.elem==="logical"?"logical":"double";case"Char":return"char";case"String":return"string";case"Struct":return"struct";case"Class":return e.className;case"Cell":return"cell";case"Handle":return"function_handle";case"Unknown":case"Void":throw new W(`'class' on a ${e.kind==="Void"?"void":"unknown"} value is not supported`)}}function aP(e){let t='"';for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r===92?t+="\\\\":r===34?t+='\\"':r>=32&&r<127?t+=String.fromCharCode(r):t+=`\\x${r.toString(16).padStart(2,"0")}`}return t+='"',{lit:t,byteLen:new TextEncoder().encode(e).length}}const cP={name:"class",transfer(e,t){if(e.length!==1)throw new le(`'class' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'class' does not support multi-output (nargout=${t})`);return[{kind:"Char",exact:vm(e[0])}]},emitC({argTypes:e,useRuntime:t}){const n=vm(e[0]);t("mtoc2_char_tensor_from_literal");const{lit:r,byteLen:s}=aP(n);return`mtoc2_char_tensor_from_literal(${r}, ${s})`},emitJs({argTypes:e}){const t=vm(e[0]);return`({mtoc2Tag:"char", value:${JSON.stringify(t)}})`},call({args:e,argTypes:t}){if(Hd(e[0]))return[Wr("function_handle")];const n=t[0];if(n.kind!=="Unknown"&&n.kind!=="Void")return[Wr(vm(n))];const r=e[0];if(typeof r=="number")return[Wr("double")];if(typeof r=="boolean")return[Wr("logical")];if(typeof r=="string")return[Wr("string")];if(Er(r))return[Wr("char")];if(un(r))return[Wr("double")];if(Wt(r))return[Wr(r.isLogical?"logical":"double")];if(Hd(r))return[Wr("function_handle")];if(r&&typeof r=="object"){if(r.mtoc2Tag==="cell")return[Wr("cell")];const s=r.mtoc2Class;return s!==void 0?[Wr(s)]:[Wr("struct")]}return[Wr("unknown")]}},lP={cumsum:p6,cumprod:d6,cummax:g6,cummin:w6},uP={cumsum:_6,cumprod:y6};function N0(e){const t=e.findIndex(n=>n>1);return t>=0?t+1:1}function fP(e,t){if(t===void 0)return;if(!Me(t)||t.isComplex||!De(t))throw new le(`'${e}' dim arg must be a scalar real integer`);const n=Je(t);if(n===void 0)throw new W(`'${e}' dim arg must be a statically-known integer in v1`);if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)throw new le(`'${e}' dim arg must be a finite positive integer (got ${n})`);return n}function mP(e,t,n,r){const s=new Float64Array(t.length);if(r>n.length)return s.set(t),s;const o=r-1,i=n[o];let a=1;for(let l=0;l<o;l++)a*=n[l];let c=1;for(let l=o+1;l<n.length;l++)c*=n[l];for(let l=0;l<c;l++){const u=l*a*i;for(let f=0;f<a;f++){let h=e.init;for(let m=0;m<i;m++){const p=u+f+m*a;h=e.step(h,t[p]),s[p]=h}}}return s}function hP(e,t,n,r,s){const o=new Float64Array(t.length),i=new Float64Array(t.length);if(s>r.length)return o.set(t),i.set(n),{re:o,im:i};const a=s-1,c=r[a];let l=1;for(let m=0;m<a;m++)l*=r[m];let u=1;for(let m=a+1;m<r.length;m++)u*=r[m];const f=0,h=e.stepComplex;if(h===void 0)throw new Error(`internal: ${e.name} reached complex scan without stepComplex`);for(let m=0;m<u;m++){const p=m*l*c;for(let d=0;d<l;d++){let g=e.init,w=f;for(let _=0;_<c;_++){const y=p+d+_*l,b=h(g,w,t[y],n[y]);g=b[0],w=b[1],o[y]=g,i[y]=w}}}return{re:o,im:i}}function Tk(e,t,n){const r=t[1];if(r!==void 0){if(!Me(r))throw new Error(`internal: ${e} codegen unexpected dim type`);const s=Je(r);if(s===void 0)throw new Error(`internal: ${e} codegen reached with non-exact dim`);return s}if(n.shape!==void 0)return N0(n.shape);throw new Error(`internal: ${e} codegen on lattice-only shape with no dim arg`)}function pP(e,t){if(e.length>=2&&e[1]!==void 0){const n=e[1];return Math.round(typeof n=="number"?n:Number(n))}return N0(t.shape)}function Mm(e){return{name:e.name,transfer(t,n){if(t.length<1||t.length>2)throw new le(`'${e.name}' expects 1..2 arg(s), got ${t.length}`);if(n!==1)throw new W(`'${e.name}' does not support multi-output (nargout=${n})`);const r=t[0];if(!Me(r))throw new le(`'${e.name}' arg must be numeric (got ${r.kind})`);if(r.elem!=="double"&&r.elem!=="logical")throw new le(`'${e.name}' arg must be double or logical (got ${r.elem})`);if(r.isComplex&&(e.supportsComplex===!1||e.stepComplex===void 0))throw new W(`'${e.name}' on complex input is not JIT-compiled`);const s=fP(e.name,t[1]);if(De(r)){if(r.isComplex){const l=An(r);return l!==void 0?[_t(l)]:[_t()]}const c=Je(r);return c!==void 0?[Be(ft(c),c)]:[Be(e.signRule(r.sign))]}let o;if(s!==void 0)o=s;else if(r.shape!==void 0)o=N0(r.shape);else throw new W(`'${e.name}' on a tensor with non-concrete shape requires an explicit dim arg (lattice-only shape can't pick a default axis)`);if(r.isComplex){const c=rn(r);if(c!==void 0&&r.shape!==void 0&&c.re.length<=wt){const l=hP(e,c.re,c.im,r.shape,o);return[Ut(r.shape,l)]}return r.shape!==void 0?[Ut(r.shape)]:[mr(r.dims.slice())]}const i=Mt(r);if(i!==void 0&&r.shape!==void 0&&i.length<=wt){const c=mP(e,i,r.shape,o);return[et(r.shape,c)]}if(r.shape!==void 0){const c=et(r.shape);return c.sign=e.signRule(r.sign),[c]}const a=Zt(r.dims.slice());return a.sign=e.signRule(r.sign),[a]},emitC({argsC:t,argTypes:n,useRuntime:r}){const s=n[0];if(De(s))return`(${t[0]})`;r("mtoc2_tensor_cumulative");const o=Tk(e.name,n,s),i=s.isComplex?"_complex_dim":"_dim";return`mtoc2_tensor_${e.name}${i}(${t[0]}, ${o})`},emitJs({argsJs:t,argTypes:n,useRuntime:r}){const s=n[0];if(De(s))return t[0];r("mtoc2_tensor_cumulative");const o=Tk(e.name,n,s),i=s.isComplex?"_complex_dim":"_dim";return`mtoc2_tensor_${e.name}${i}(${t[0]}, ${o})`},call({args:t,argTypes:n}){const r=n[0];if(De(r)){const c=t[0];return r.isComplex?[c]:[typeof c=="number"?c:Number(c)]}const o=(r.isComplex?uP:lP)[e.name];if(o===void 0)throw new W(`'${e.name}' tensor 'call' has no JS kernel registered`);const i=t[0],a=pP(t,i);return[o(i,a)]}}}function A0(e){switch(e){case"positive":return"positive";case"nonneg":return"nonneg";case"zero":return"zero";case"negative":return"negative";case"nonpositive":return"nonpositive";default:return"unknown"}}function dP(e){switch(e){case"positive":return"positive";case"nonneg":return"nonneg";case"zero":return"zero";default:return"unknown"}}const gP=Mm({name:"cumsum",init:0,step:(e,t)=>e+t,stepComplex:(e,t,n,r)=>[e+n,t+r],signRule:A0}),wP=Mm({name:"cumprod",init:1,step:(e,t)=>e*t,stepComplex:(e,t,n,r)=>[e*n-t*r,e*r+t*n],signRule:dP}),_P=Mm({name:"cummax",init:-1/0,step:(e,t)=>Math.max(e,t),signRule:A0,supportsComplex:!1}),yP=Mm({name:"cummin",init:1/0,step:(e,t)=>Math.min(e,t),signRule:A0,supportsComplex:!1});function xP(e,t){let n;t!==void 0?n=t-1:e.length<=1||e.length===2&&e[0]===1?n=e.length===2&&e[0]===1?1:0:n=0;const r=n<e.length?e[n]:1,s=e.slice();for(r<=1?n<s.length&&(s[n]=0):s[n]=r-1;s.length>2&&s[s.length-1]===1;)s.pop();return s}function $m(e){if(e.length<1||e.length>3)throw new le(`'diff' expects 1..3 arg(s), got ${e.length}`);const t=e[0];if(!Me(t))throw new le(`'diff' arg must be numeric (got ${t.kind})`);if(t.isComplex)throw new W("'diff' on complex input is not JIT-compiled");if(t.elem!=="double"&&t.elem!=="logical")throw new le(`'diff' arg must be double or logical (got ${t.elem})`);if(De(t))throw new W("'diff' on a scalar is not JIT-compiled");if(t.shape===void 0)throw new W("'diff' on a tensor with non-concrete shape is not JIT-compiled");if(e.length>=2){const r=e[1];if(!Me(r)||r.isComplex||!De(r))throw new W("'diff' order arg must be the scalar 1 (higher-order / '[]' decline)");const s=Je(r);if(s===void 0||s!==1)throw new W(`'diff' only JIT-compiles first-order (n == 1); got ${s??"non-exact"}`)}let n;if(e.length>=3){const r=e[2];if(!Me(r)||r.isComplex||!De(r))throw new le("'diff' dim arg must be a scalar real integer");const s=Je(r);if(s===void 0)throw new W("'diff' dim arg must be a statically-known integer");if(!Number.isFinite(s)||!Number.isInteger(s)||s<1)throw new le(`'diff' dim arg must be a positive integer (got ${s})`);if(s>t.shape.length)throw new W(`'diff' with dim ${s} > ndims ${t.shape.length} is not JIT-compiled`);n=s}return{shape:t.shape,dim:n}}const bP={name:"diff",transfer(e,t){if(t!==1)throw new W(`'diff' does not support multi-output (nargout=${t})`);const{shape:n,dim:r}=$m(e),s=xP(n,r);if(s.every(i=>i===1))return[Zt([nn,{kind:"unknown"}])];const o=et(s);return o.sign="unknown",[o]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_diff");const{dim:r}=$m(t);return`mtoc2_tensor_diff(${e[0]}, ${r??0})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_diff");const{dim:r}=$m(t);return`mtoc2_tensor_diff(${e[0]}, ${r??0})`},call({args:e,argTypes:t}){const{dim:n}=$m(t);return[C6(e[0],n??0)]}};function Cm(e){if(e.length<2)throw new W(`'repmat' requires at least 2 arguments (got ${e.length})`);if(e.length===2&&Me(e[1])&&!De(e[1])){const n=e[1];if(n.isComplex||n.elem!=="double"&&n.elem!=="logical")throw new le(`'repmat' rep vector must be a real double / logical tensor (got ${ze(n)})`);const r=Mt(n);if(r===void 0)throw new W("'repmat' rep vector must be a statically-known constant in v1");if(r.length<1)throw new le("'repmat' rep vector must be non-empty");if(r.length>Zn)throw new W(`'repmat' supports up to ${Zn} rep dims (got ${r.length})`);const s=[];for(let o=0;o<r.length;o++){const i=r[o];if(!Number.isFinite(i)||!Number.isInteger(i))throw new le(`'repmat' rep ${o+1} must be a finite integer (got ${i})`);s.push({kind:"exact",value:i<0?0:i,argIndex:1})}return{reps:s,squareFromScalar:!1,formB:!0}}if(e.length-1>Zn)throw new W(`'repmat' supports up to ${Zn} rep dims (got ${e.length-1})`);const t=[];for(let n=1;n<e.length;n++){const r=e[n];if(!Me(r)||!De(r))throw new le(`'repmat' rep arg ${n} must be a scalar real numeric (got ${ze(r)})`);if(r.isComplex||r.elem!=="double"&&r.elem!=="logical")throw new le(`'repmat' rep arg ${n} must be a scalar real double / logical (got ${ze(r)})`);const s=Je(r);if(s===void 0){t.push({kind:"dynamic",argIndex:n});continue}if(!Number.isFinite(s)||!Number.isInteger(s))throw new le(`'repmat' rep arg ${n} must be a finite integer (got ${s})`);t.push({kind:"exact",value:s<0?0:s,argIndex:n})}return t.length===1?{reps:[t[0],t[0]],squareFromScalar:!0,formB:!1}:{reps:t,squareFromScalar:!1,formB:!1}}function kP(e){if(e.shape!==void 0)return e.shape.slice()}function Sm(e){return e.formB&&e.reps.length===1?[e.reps[0],e.reps[0]]:e.reps}function E0(e,t,n){const r=t.length,s=t.map((u,f)=>u*n[f]);let o=1;for(const u of s)o*=u;const i=new Float64Array(o);if(o===0)return i;let a=1;for(const u of t)a*=u;if(a===0)return i;i.set(e.subarray(0,a),0);const c=t.slice();let l=a;for(let u=0;u<r;u++){const f=n[u];if(f===1)continue;let h=1;for(let p=0;p<=u;p++)h*=c[p];if(f===0||h===0)return new Float64Array(o);const m=l/h;for(let p=m-1;p>=0;p--){const d=p*h,g=p*h*f;g!==d&&i.copyWithin(g,d,d+h);for(let w=1;w<f;w++)i.copyWithin(g+w*h,g,g+h)}c[u]*=f,l*=f}return i}function Pk(e,t,n){const r=e.slice();for(;r.length<n;)r.push(t);return r}function Bk(e){const t=e.slice();for(;t.length>2&&t[t.length-1]===1;)t.pop();for(;t.length<2;)t.push(1);return t}function vP(e){const t=e.slice(),n=r=>r.kind==="exact"&&r.value===1;for(;t.length>2&&n(t[t.length-1]);)t.pop();for(;t.length<2;)t.push(nn);return t}function I0(e,t,n){const r=Math.max(n?0:e.length,t.length);let s=r<2?2:r;for(;s>2;){const i=s-1,a=n||i>=e.length||e[i].kind==="exact"&&e[i].value===1,c=i<t.length?t[i]:{kind:"exact",value:1},l=c.kind==="exact"&&c.value===1;if(!(a&&l))break;s--}const o=t.slice(0,s);for(;o.length<s;)o.push({kind:"exact",value:1,argIndex:0});return{reps:o,ndim:s}}function qk(e,t){return e.kind==="exact"?`${e.value}L`:`mtoc2_check_dim(${t[e.argIndex]})`}function zk(e,t){return e.kind==="exact"?String(e.value):`mtoc2_check_dim(${t[e.argIndex]})`}const MP={name:"repmat",transfer(e,t){if(t!==1)throw new W(`'repmat' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'repmat' first arg must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'repmat' first arg must be a real double / logical (got ${n.elem})`);const r=Cm(e),s=De(n),o=s?Sm(r):r.reps;if(o.every(h=>h.kind==="exact")){const h=o.map(p=>p.value);if(s){const p=Bk(h.slice()),d=Dt(p);if(n.isComplex){const _=An(n);if(p.every(y=>y===1))return _!==void 0?[_t(_)]:[_t()];if(_!==void 0&&d<=wt){const y=new Float64Array(d),b=new Float64Array(d);return y.fill(_.re),b.fill(_.im),[Ut(p,{re:y,im:b})]}return[Ut(p)]}const g=Je(n);if(p.every(_=>_===1))return g!==void 0?[Be(ft(g),g)]:[Be(n.sign)];if(g!==void 0&&d<=wt){const _=new Float64Array(d);return g!==0&&_.fill(g),[et(p,_)]}const w=et(p);return w.sign=g!==void 0?ft(g):n.sign,[w]}const m=kP(n);if(m!==void 0){const p=Math.max(m.length,h.length),d=Pk(m,1,p),g=Pk(h,1,p),w=Bk(d.map((M,$)=>M*g[$])),_=w.length;for(;d.length>_;)d.pop();for(;g.length>_;)g.pop();for(;d.length<_;)d.push(1);for(;g.length<_;)g.push(1);if(n.isComplex){if(w.every(N=>N===1)){const N=rn(n);return N!==void 0&&N.re.length===1?[_t({re:N.re[0],im:N.im[0]})]:[_t()]}const M=Dt(w),$=rn(n);if($!==void 0&&M<=wt){const N=E0($.re,d,g),E=E0($.im,d,g);return[Ut(w,{re:N,im:E})]}return[Ut(w)]}if(w.every(M=>M===1)){const M=Mt(n);if(M!==void 0&&M.length===1)return[Be(ft(M[0]),M[0])];const $=Je(n);return $!==void 0?[Be(ft($),$)]:[Be(n.sign)]}const y=Dt(w),b=Mt(n);if(b!==void 0&&y<=wt){const M=E0(b,d,g),$=et(w,M);return $.sign=ol(M),[$]}const k=et(w);return k.sign=n.sign,[k]}}const a=n.dims,c=Math.max(a.length,o.length),l=[];for(let h=0;h<c;h++){const m=h<a.length?a[h]:nn,p=h<o.length?o[h]:{kind:"exact",value:1};if(m.kind==="exact"&&p.kind==="exact"){const d=m.value*p.value;l.push(d===1?nn:{kind:"exact",value:d})}else l.push({kind:"unknown"})}const u=vP(l);if(n.isComplex)return[mr(u)];const f=Zt(u);return f.sign=n.sign,[f]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=Cm(t),o=De(r),i=o?Sm(s):s.reps,{reps:a,ndim:c}=I0(r.dims,i,o);a.some(f=>f.kind==="dynamic")&&n(Qo);const l=a.every(f=>f.kind==="exact"&&f.value===1);if(o){if(l)return e[0];n("mtoc2_tensor_fill_nd");const f=a.map(h=>qk(h,e)).join(", ");return r.isComplex?(n("mtoc2_cscalar"),`mtoc2_tensor_fill_nd_complex(creal(${e[0]}), cimag(${e[0]}), ${c}, (long[]){${f}})`):`mtoc2_tensor_fill_nd((double)(${e[0]}), ${c}, (long[]){${f}})`}n("mtoc2_tensor_repmat");const u=a.map(f=>qk(f,e)).join(", ");return r.isComplex?`mtoc2_tensor_repmat_complex(${e[0]}, ${c}, (long[]){${u}})`:`mtoc2_tensor_repmat(${e[0]}, ${c}, (long[]){${u}})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0],s=Cm(t),o=De(r),i=o?Sm(s):s.reps,{reps:a,ndim:c}=I0(r.dims,i,o);a.some(f=>f.kind==="dynamic")&&n(Qo);const l=a.every(f=>f.kind==="exact"&&f.value===1);if(o){if(l)return e[0];n("mtoc2_tensor_fill_nd");const f=a.map(h=>zk(h,e)).join(", ");return r.isComplex?`mtoc2_tensor_fill_nd_complex(${e[0]}.re, ${e[0]}.im, ${c}, [${f}])`:`mtoc2_tensor_fill_nd(${e[0]}, ${c}, [${f}])`}n("mtoc2_tensor_repmat");const u=a.map(f=>zk(f,e)).join(", ");return r.isComplex?`mtoc2_tensor_repmat_complex(${e[0]}, ${c}, [${u}])`:`mtoc2_tensor_repmat(${e[0]}, ${c}, [${u}])`},call({args:e,argTypes:t}){const n=t[0],r=Cm(t),s=De(n),o=s?Sm(r):r.reps,{reps:i}=I0(n.dims,o,s),a=i.map(c=>{if(c.kind==="exact")return c.value;const l=e[c.argIndex],u=typeof l=="number"?l:Number(l);return Ka(u)});if(s){const c=a.slice();for(;c.length<2;)c.push(1);if(n.isComplex){const u=e[0],f=un(u)?u:{re:typeof u=="number"?u:Number(u),im:0};return[A5(f.re,f.im,c.length,c)]}const l=typeof e[0]=="number"?e[0]:Number(e[0]);return[vb(l,c.length,c)]}return n.isComplex?[bL(e[0],a.length,a)]:[xL(e[0],a.length,a)]}};function Nm(e){if(e.length<2)return 0;const t=e[1];if(!Me(t)||!De(t)||t.isComplex)throw new le(`'diag' second arg must be a scalar real integer (got ${ze(t)})`);if(t.elem!=="double"&&t.elem!=="logical")throw new le(`'diag' second arg must be double or logical (got ${t.elem})`);const n=Je(t);if(n===void 0)throw new W("'diag' with a dynamic k argument is not yet supported (require a literal integer)");if(!Number.isFinite(n)||!Number.isInteger(n))throw new le(`'diag' k must be a finite integer (got ${n})`);return n}function Am(e,t,n){return n>=0?Math.max(0,Math.min(e,t-n)):Math.max(0,Math.min(e+n,t))}const $P={name:"diag",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'diag' expects 1..2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'diag' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'diag' first arg must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'diag' first arg must be a double or logical tensor (got ${n.elem})`);const r=Nm(e),s=Math.abs(r);if(De(n)){if(r===0){if(n.isComplex){const d=An(n);return d!==void 0?[_t(d)]:[_t()]}const p=Je(n);return p!==void 0?[Be(ft(p),p)]:[Be(n.sign)]}const u=1+s,f=[u,u],h=u*u;if(n.isComplex){const p=An(n);if(p!==void 0&&h<=wt){const d=new Float64Array(h),g=new Float64Array(h),w=r<0?-r:0,_=r>0?r:0;return d[w+_*u]=p.re,g[w+_*u]=p.im,[Ut(f,{re:d,im:g})]}return[Ut(f)]}const m=Je(n);if(m!==void 0&&h<=wt){const p=new Float64Array(h),d=r<0?-r:0,g=r>0?r:0;return p[d+g*u]=m,[et(f,p)]}return[et(f)]}if(n.dims.length!==2)throw new W(`'diag' requires a 2-D operand (got ${n.dims.length}-D)`);if(n.shape===void 0)throw new W("'diag' of a tensor with unknown shape is not yet supported");const[o,i]=n.shape;if(o===1||i===1){const u=Math.max(o,i),f=u+s,h=[f,f],m=f*f;if(n.isComplex){const d=rn(n);if(d!==void 0&&m<=wt){const g=new Float64Array(m),w=new Float64Array(m);for(let _=0;_<u;_++){const y=r<0?_-r:_,b=r>0?_+r:_;g[y+b*f]=d.re[_],w[y+b*f]=d.im[_]}return[Ut(h,{re:g,im:w})]}return[Ut(h)]}const p=Mt(n);if(p!==void 0&&m<=wt){const d=new Float64Array(m);for(let g=0;g<u;g++){const w=r<0?g-r:g,_=r>0?g+r:g;d[w+_*f]=p[g]}return[et(h,d)]}return[et(h)]}const a=Am(o,i,r);if(a===0)return n.isComplex?[Ut([0,1])]:[et([0,1])];if(a===1){if(n.isComplex){const f=rn(n);if(f!==void 0){const h=r<0?-r:0,m=r>0?r:0,p=h+m*o;return[_t({re:f.re[p],im:f.im[p]})]}return[_t()]}const u=Mt(n);if(u!==void 0){const f=r<0?-r:0,h=r>0?r:0,m=u[f+h*o];return[Be(ft(m),m)]}return[Be("unknown")]}const c=[a,1];if(n.isComplex){const u=rn(n);if(u!==void 0&&a<=wt){const f=new Float64Array(a),h=new Float64Array(a);for(let m=0;m<a;m++){const p=r<0?-r+m:m,d=r>0?r+m:m;f[m]=u.re[p+d*o],h[m]=u.im[p+d*o]}return[Ut(c,{re:f,im:h})]}return[Ut(c)]}const l=Mt(n);if(l!==void 0&&a<=wt){const u=new Float64Array(a);for(let f=0;f<a;f++){const h=r<0?-r+f:f,m=r>0?r+f:f;u[f]=l[h+m*o]}return[et(c,u)]}return[et(c)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=Nm(t);if(De(r))return s===0?e[0]:r.isComplex?(n("mtoc2_tensor_diag"),n("mtoc2_cscalar"),`mtoc2_tensor_diag_from_scalar_complex(creal(${e[0]}), cimag(${e[0]}), ${s}L)`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_from_scalar(${e[0]}, ${s}L)`);const o=r.shape[0],i=r.shape[1];if(o===1||i===1)return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct_complex(${e[0]}, ${s}L)`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct(${e[0]}, ${s}L)`);if(Am(o,i,s)===1){const c=s<0?-s:0,l=s>0?s:0,u=c+l*o;return r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cmake(${e[0]}.real[${u}], ${e[0]}.imag != NULL ? ${e[0]}.imag[${u}] : 0.0)`):`${e[0]}.real[${u}]`}return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract_complex(${e[0]}, ${s}L)`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract(${e[0]}, ${s}L)`)},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0],s=Nm(t);if(De(r))return s===0?e[0]:r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_from_scalar_complex(${e[0]}.re, ${e[0]}.im, ${s})`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_from_scalar(${e[0]}, ${s})`);const o=r.shape[0],i=r.shape[1];if(o===1||i===1)return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct_complex(${e[0]}, ${s})`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct(${e[0]}, ${s})`);if(Am(o,i,s)===1){const c=s<0?-s:0,l=s>0?s:0,u=c+l*o;return r.isComplex?`{ re: ${e[0]}.data[${u}], im: ${e[0]}.imag !== undefined ? ${e[0]}.imag[${u}] : 0 }`:`${e[0]}.data[${u}]`}return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract_complex(${e[0]}, ${s})`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract(${e[0]}, ${s})`)},call({args:e,argTypes:t}){const n=t[0],r=Nm(t);if(De(n)){if(r===0)return[e[0]];if(n.isComplex){const l=e[0],u=un(l)?l:{re:typeof l=="number"?l:Number(l),im:0};return[v6(u.re,u.im,r)]}const c=typeof e[0]=="number"?e[0]:Number(e[0]);return[x6(c,r)]}if(!Wt(e[0]))throw new le("'diag' runtime arg has tensor type but runtime value isn't a tensor");const s=e[0],o=s.shape[0],i=s.shape[1];if(o===1||i===1)return n.isComplex?[M6(s,r)]:[b6(s,r)];const a=Am(o,i,r);if(a===0)return[Bi([0,1],new Float64Array(0))];if(a===1){const c=r<0?-r:0,l=r>0?r:0,u=c+l*o;if(n.isComplex){const f=s.imag!==void 0?s.imag[u]:0;return[{re:s.data[u],im:f}]}return[s.data[u]]}return n.isComplex?[$6(s,r)]:[k6(s,r)]}};function Em(e,t){if(t.length<2)return 0;const n=t[1];if(!Me(n)||!De(n)||n.isComplex)throw new le(`'${e}' second arg must be a scalar real integer (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'${e}' second arg must be double or logical (got ${n.elem})`);const r=Je(n);if(r===void 0)throw new W(`'${e}' with a dynamic k argument is not yet supported (require a literal integer)`);if(!Number.isFinite(r)||!Number.isInteger(r))throw new le(`'${e}' k must be a finite integer (got ${r})`);return r}function Vk(e){const{name:t,cHelper:n,cHelperComplex:r,keep:s,jsHelper:o,jsHelperComplex:i}=e;function a(f,h){if(f.length<1||f.length>2)throw new le(`'${t}' expects 1..2 arg(s), got ${f.length}`);if(h!==1)throw new W(`'${t}' does not support multi-output (nargout=${h})`);const m=f[0];if(!Me(m))throw new le(`'${t}' first arg must be numeric (got ${ze(m)})`);if(m.elem!=="double"&&m.elem!=="logical")throw new le(`'${t}' first arg must be a double or logical tensor (got ${m.elem})`);const p=Em(t,f);if(De(m)){if(m.isComplex){const k=An(m);return k!==void 0?[_t(s(0,0,p)?k:{re:0,im:0})]:[s(0,0,p)?_t():_t({re:0,im:0})]}const b=Je(m);if(b!==void 0){const k=s(0,0,p)?b:0;return[Be(ft(k),k)]}return s(0,0,p)?[Be(m.sign)]:[Be("zero",0)]}if(m.dims.length!==2)throw new W(`'${t}' requires a 2-D operand (got ${m.dims.length}-D)`);if(m.shape===void 0)throw new W(`'${t}' of a tensor with unknown shape is not yet supported`);const[d,g]=m.shape,w=[d,g],_=d*g;if(m.isComplex){const b=rn(m);if(b!==void 0&&_<=wt){const k=new Float64Array(_),M=new Float64Array(_);for(let $=0;$<g;$++)for(let N=0;N<d;N++)if(s(N,$,p)){const E=N+$*d;k[E]=b.re[E],M[E]=b.im[E]}return[Ut(w,{re:k,im:M})]}return[Ut(w)]}const y=Mt(m);if(y!==void 0&&_<=wt){const b=new Float64Array(_);for(let k=0;k<g;k++)for(let M=0;M<d;M++)if(s(M,k,p)){const $=M+k*d;b[$]=y[$]}return[et(w,b)]}return[et(w)]}function c({argsC:f,argTypes:h,useRuntime:m}){const p=h[0],d=Em(t,h);return De(p)?p.isComplex?(m("mtoc2_cscalar"),s(0,0,d)?f[0]:"mtoc2_cmake(0.0, 0.0)"):s(0,0,d)?f[0]:"0.0":p.isComplex?(m("mtoc2_tensor_triangular"),`${r}(${f[0]}, ${d}L)`):(m("mtoc2_tensor_triangular"),`${n}(${f[0]}, ${d}L)`)}function l({argsJs:f,argTypes:h,useRuntime:m}){const p=h[0],d=Em(t,h);return De(p)?p.isComplex?(m("mtoc2_cscalar"),s(0,0,d)?f[0]:"mtoc2_cmake(0, 0)"):s(0,0,d)?f[0]:"0":p.isComplex?(m("mtoc2_tensor_triangular"),`${r}(${f[0]}, ${d})`):(m("mtoc2_tensor_triangular"),`${n}(${f[0]}, ${d})`)}function u({args:f,argTypes:h}){const m=h[0],p=Em(t,h);if(De(m))return s(0,0,p)?[f[0]]:m.isComplex?[{re:0,im:0}]:[0];if(!Wt(f[0]))throw new le(`'${t}' runtime arg has tensor type but runtime value isn't a tensor`);const d=f[0],g=d.shape[0],w=d.shape[1];return g===0||w===0?[Bi([g,w],new Float64Array(0))]:m.isComplex?[i(d,p)]:[o(d,p)]}return{name:t,transfer:a,emitC:c,emitJs:l,call:u}}const CP=Vk({name:"triu",cHelper:"mtoc2_tensor_triu",cHelperComplex:"mtoc2_tensor_triu_complex",keep:(e,t,n)=>t-e>=n,jsHelper:IL,jsHelperComplex:jL}),SP=Vk({name:"tril",cHelper:"mtoc2_tensor_tril",cHelperComplex:"mtoc2_tensor_tril_complex",keep:(e,t,n)=>e-t>=-n,jsHelper:FL,jsHelperComplex:RL});function Im(e){const t=e[0];if(!Me(t)||!De(t)||t.isComplex)throw new le(`'cat' first arg (dim) must be a scalar real integer (got ${ze(t)})`);if(t.elem!=="double"&&t.elem!=="logical")throw new le(`'cat' first arg (dim) must be a scalar real integer (got ${t.elem})`);const n=Je(t);if(n===void 0)throw new W("'cat' with a dynamic dim argument is not yet supported (require a statically-known dim)");if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)throw new le(`'cat' dim must be a positive integer (got ${n})`);if(n>Zn)throw new W(`'cat' supports dim ≤ ${Zn} (got ${n})`);return n}function NP(e,t){const n=[];for(let r=1;r<e.length;r++){const s=e[r];if(!Me(s))throw new le(`'cat' arg ${r+1} must be numeric (got ${ze(s)})`);if(s.elem!=="double"&&s.elem!=="logical")throw new le(`'cat' arg ${r+1} must be a double or logical (got ${s.elem})`);if(De(s)){const a=new Array(t).fill(1);if(s.isComplex){const c=An(s);n.push({shape:a,total:1,exact:c!==void 0?c.re:void 0,exactIm:c!==void 0?c.im:void 0,isComplex:!0,idx:r})}else{const c=Je(s);n.push({shape:a,total:1,exact:c,isComplex:!1,idx:r})}continue}if(s.dims.length>t)throw new W(`'cat' result ndim ${t} cannot accommodate input rank ${s.dims.length}`);const o=[];let i=1;for(let a=0;a<t;a++){const c=a<s.dims.length?s.dims[a]:{kind:"exact",value:1};c.kind==="exact"?(o.push(c.value),i!==null&&(i*=c.value)):(o.push(null),i=null)}if(s.isComplex){const a=rn(s);n.push({shape:o,total:i,exact:a!==void 0?a.re:void 0,exactIm:a!==void 0?a.im:void 0,isComplex:!0,idx:r})}else{const a=Mt(s);n.push({shape:o,total:i,exact:a,isComplex:!1,idx:r})}}return n}function AP(e,t,n){let r=-1;for(let l=0;l<e.length;l++)if(e[l].total!==null&&e[l].total>0){r=l;break}if(r===-1){if(e.every(l=>l.total===0)){const l=new Array(n).fill(0);return l[0]=0,l[1]=0,{shape:l,allStatic:!0,refShape:l.slice()}}return{shape:new Array(n).fill(null),allStatic:!1}}const s=e[r].shape;if(s.some(l=>l===null))return{shape:new Array(n).fill(null),allStatic:!1};const o=s.map(l=>l);let i=!0;for(let l=0;l<e.length;l++){if(l===r)continue;const u=e[l];if(u.shape.some(f=>f===null)){i=!1;continue}if(u.total!==0){for(let f=0;f<n;f++)if(f!==t&&u.shape[f]!==o[f])throw new le(`'cat' dimension mismatch on dimension ${f+1}: arg ${r+2} has size ${o[f]}, arg ${u.idx+1} has size ${u.shape[f]}`)}}if(!i){const l=o.slice();return l[t]=null,{shape:l,allStatic:!1}}let a=0;for(const l of e){if(l.shape.some(f=>f===null))return{shape:new Array(n).fill(null),allStatic:!1};const u=l.shape.map(f=>f);if(l.total===0){let f=!0;for(let h=0;h<n;h++)if(h!==t&&u[h]!==o[h]){f=!1;break}if(!f)continue}a+=u[t]}const c=o.slice();return c[t]=a,{shape:c,allStatic:!0,refShape:o}}function F0(e,t,n,r,s,o="re"){for(const u of e){if(u.shape.some(f=>f===null)||u.total===null)return;if(u.total!==0){if(o==="re"){if(u.exact===void 0)return}else if(u.isComplex&&u.exactIm===void 0)return}}const i=Dt(t);if(i>wt)return;const a=new Float64Array(i);if(i===0)return a;let c=1;for(let u=0;u<r;u++)c*=t[u];let l=1;for(let u=r+1;u<s;u++)l*=t[u];for(let u=0;u<l;u++){let f=u*c*t[r];for(const h of e){if(h.total===0){const _=h.shape.map(b=>b);let y=!0;for(let b=0;b<s;b++)if(b!==r&&_[b]!==n[b]){y=!1;break}if(!y)continue;continue}const p=h.shape.map(_=>_)[r],d=c*p,g=u*d,w=o==="re"?h.exact:h.exactIm;if(w===void 0){f+=d;continue}if(typeof w=="number")a[f]=w;else if(w instanceof Float64Array)a.set(w.subarray(g,g+d),f);else return;f+=d}}return a}const EP={name:"cat",transfer(e,t){if(t!==1)throw new W(`'cat' does not support multi-output (nargout=${t})`);if(e.length<1)throw new le("'cat' requires at least the dim argument");const n=Im(e);if(e.length===1)return[et([0,0])];let r=Math.max(2,n);for(let m=1;m<e.length;m++){const p=e[m];Me(p)&&!De(p)&&p.dims.length>r&&(r=p.dims.length)}if(r>Zn)throw new W(`'cat' result ndim ${r} exceeds ${Zn}`);const s=NP(e,r),o=s.some(m=>m.isComplex),{shape:i,allStatic:a,refShape:c}=AP(s,n-1,r);if(a){const m=i.map(d=>d);for(;m.length>2&&m[m.length-1]===1;)m.pop();for(;m.length<2;)m.push(1);if(o){let d;if(c!==void 0){const g=F0(s,i.map(_=>_),c,n-1,r,"re"),w=F0(s,i.map(_=>_),c,n-1,r,"im");g!==void 0&&w!==void 0&&(d={re:g,im:w})}return[Ut(m,d)]}let p;if(c!==void 0){const d=F0(s,i.map(g=>g),c,n-1,r);d!==void 0&&(p=d)}return[et(m,p)]}const l=[];let u=!1;for(const m of i){if(m===null){u=!0;break}l.push(m)}if(!u){const m=l.slice();for(;m.length>2&&m[m.length-1]===1;)m.pop();for(;m.length<2;)m.push(1);return o?[Ut(m)]:[et(m)]}const f=i.map(m=>m===null?{kind:"unknown"}:m===1?{kind:"exact",value:1}:{kind:"exact",value:m});for(;f.length>2&&f[f.length-1].kind==="exact"&&f[f.length-1].value===1;)f.pop();const h={kind:"Numeric",elem:"double",isComplex:o,dims:f,sign:"unknown"};return f.every(m=>m.kind==="exact")&&(h.shape=f.map(m=>m.value)),[h]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_cat");const r=Im(t),s=t.length-1,o=t.slice(1).some(a=>Me(a)&&a.isComplex);if(s===0)return o?(n("mtoc2_tensor_alloc_nd_complex"),"mtoc2_tensor_alloc_nd_complex(2, (long[]){0L, 0L})"):(n("mtoc2_tensor_alloc_nd"),"mtoc2_tensor_alloc_nd(2, (long[]){0L, 0L})");if(o){n("mtoc2_cscalar");const a=[];for(let c=1;c<t.length;c++){const l=t[c];Me(l)&&De(l)?l.isComplex?a.push(`{.kind = 1, .scalar_re = creal(${e[c]}), .scalar_im = cimag(${e[c]}), .tensor = {0}}`):a.push(`{.kind = 1, .scalar_re = (double)(${e[c]}), .scalar_im = 0.0, .tensor = {0}}`):a.push(`{.kind = 0, .scalar_re = 0.0, .scalar_im = 0.0, .tensor = ${e[c]}}`)}return`mtoc2_tensor_cat_complex(${r}L, ${s}, (mtoc2_cat_complex_arg_t[]){${a.join(", ")}})`}const i=[];for(let a=1;a<t.length;a++){const c=t[a];Me(c)&&De(c)?i.push(`{.kind = 1, .scalar = (double)(${e[a]})}`):i.push(`{.kind = 0, .tensor = ${e[a]}}`)}return`mtoc2_tensor_cat(${r}L, ${s}, (mtoc2_cat_arg_t[]){${i.join(", ")}})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_cat");const r=Im(t),s=t.length-1,o=t.slice(1).some(c=>Me(c)&&c.isComplex);if(s===0)return o?(n("mtoc2_tensor_alloc_nd_complex"),"mtoc2_tensor_alloc_nd_complex(2, [0, 0])"):(n("mtoc2_tensor_alloc_nd"),"mtoc2_tensor_alloc_nd(2, [0, 0])");const i=[];for(let c=1;c<t.length;c++)i.push(e[c]);return`${o?"mtoc2_tensor_cat_complex":"mtoc2_tensor_cat"}(${r}, ${s}, [${i.join(", ")}])`},call({args:e,argTypes:t}){const n=Im(t),r=t.slice(1).some(o=>Me(o)&&o.isComplex),s=[];for(let o=1;o<e.length;o++)s.push(e[o]);return r?[h6(n,s.length,s)]:[f6(n,s.length,s)]}};function IP(e){if(e.length===0)return et([0,0],new Float64Array(0));if(e.length===1){const n=e.charCodeAt(0);return Be(ft(n),n)}const t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return et([1,e.length],t)}function Uk(e){return Number.isInteger(e)&&Math.abs(e)<1e16?`${e}.0`:String(e)}function FP(e){const t=[];for(let n=0;n<e.length;n++)t.push(Uk(e.charCodeAt(n)));return t.join(", ")}function jP(e){const t=[];for(let n=0;n<e.length;n++)t.push(String(e.charCodeAt(n)));return t.join(", ")}const RP={name:"double",transfer(e,t){if(e.length!==1)throw new le(`'double' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'double' does not support multi-output (nargout=${t})`);const n=e[0];if(Me(n)){if(n.isComplex&&De(n)){if(n.exact!==void 0&&typeof n.exact=="object"&&!(n.exact instanceof Float64Array)&&typeof n.exact.re=="number"){const s=n.exact.re;return[Be(ft(s),s)]}return[Be()]}return[{...n,elem:"double"}]}if(n.kind==="Char"){if(n.exact===void 0)throw new W("'double' on a non-exact char value is not supported (only char literals fold to numeric)");return[IP(n.exact)]}throw new le(`'double' arg must be numeric or char (got ${n.kind})`)},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];if(Me(r))return r.isComplex&&De(r)?(n("mtoc2_cscalar"),`mtoc2_creal(${e[0]})`):qe(r)?r.isComplex?(n("mtoc2_tensor_copy_complex"),`mtoc2_tensor_copy_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):e[0];if(r.kind==="Char"){const s=r.exact;return s.length===0?(n("mtoc2_tensor_alloc"),"mtoc2_tensor_alloc(0, 0)"):s.length===1?Uk(s.charCodeAt(0)):(n("mtoc2_tensor_from_row"),`mtoc2_tensor_from_row((double[]){${FP(s)}}, ${s.length})`)}throw new le(`internal: 'double' emitC reached on type ${r.kind}`)},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];if(Me(r))return r.isComplex&&De(r)?`(${e[0]}).re`:qe(r)?r.isComplex?`({mtoc2Tag:"tensor", shape:${e[0]}.shape.slice(), data:new Float64Array(${e[0]}.data), imag:new Float64Array(${e[0]}.imag)})`:`({mtoc2Tag:"tensor", shape:${e[0]}.shape.slice(), data:new Float64Array(${e[0]}.data)})`:r.elem==="logical"?`(+${e[0]})`:e[0];if(r.kind==="Char"){const s=r.exact;return s.length===0?(n("mtoc2_tensor_alloc"),"mtoc2_tensor_alloc(0, 0)"):s.length===1?String(s.charCodeAt(0)):(n("mtoc2_tensor_from_row"),`mtoc2_tensor_from_row([${jP(s)}], ${s.length})`)}throw new le(`internal: 'double' emitJs reached on type ${r.kind}`)},call({args:e}){const t=e[0];if(typeof t=="number")return[t];if(typeof t=="boolean")return[t?1:0];if(un(t))return[t.re];if(Wt(t))return t.imag!==void 0?[bR(t.shape.slice(),new Float64Array(t.data),new Float64Array(t.imag))]:[Bi(t.shape.slice(),new Float64Array(t.data))];if(Er(t)){const n=t.value;if(n.length===0)return[Bi([0,0],new Float64Array(0))];if(n.length===1)return[n.charCodeAt(0)];const r=new Float64Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return[Bi([1,n.length],r)]}throw new le(`'double' got an unsupported runtime value (typeof = ${typeof t})`)}};function j0(e){if(e.kind==="Numeric"&&e.dims.some(t=>t.kind!=="exact"||t.value!==1))return{copy:e.isComplex?"mtoc2_tensor_copy_complex":"mtoc2_tensor_copy",assign:"mtoc2_tensor_assign",cType:"mtoc2_tensor_t",isRuntime:!0};if(e.kind==="String")return{copy:"mtoc2_string_copy",assign:"mtoc2_string_assign",cType:"mtoc2_string_t",isRuntime:!0};if(e.kind==="Char")return{copy:"mtoc2_char_tensor_copy",assign:"mtoc2_char_tensor_assign",cType:"mtoc2_char_tensor_t",isRuntime:!0};if(e.kind==="Struct"){const t=Wd(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}if(e.kind==="Class"){const t=sb(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}if(e.kind==="Handle"){const t=nb(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}if(e.kind==="Cell"){const t=Xd(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}return null}function Fm(e,t){if(e.length===0)throw new le("'deal' requires at least one input argument");if(t<1)throw new W(`'deal' requires at least one output (got nargout=${t})`);if(e.length===1)return new Array(t).fill(0);if(e.length!==t)throw new le(`'deal': number of inputs (${e.length}) must match number of outputs (${t})`);return e.map((n,r)=>r)}function LP(e,t){if(!Kn(e)&&!hr(e))throw new W(`'deal' input ${t+1} has type ${ze(e)}; this type isn't supported in a multi-output slot`)}const DP={name:"deal",transfer(e,t){const n=Fm(e,t);if(t>=2)for(let r=0;r<t;r++)LP(e[n[r]],n[r]);return n.map(r=>e[r])},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){const o=Fm(t,n);if(r!==void 0){if(n>=2){const f=[],h=[];for(let m=0;m<n;m++){const p=t[o[m]],d=e[o[m]],g=j0(p),w=`_mtoc2_deal_t${m}`;g!==null?(g.isRuntime&&(s(g.copy),s(g.assign)),f.push(`${g.cType} ${w} = ${g.copy}(${d});`),h.push(`${g.assign}(${r[m]}, ${w})`)):(f.push(`double ${w} = ${d};`),h.push(`(*${r[m]} = ${w})`))}return`${f.join(" ")} (void)(${h.join(", ")})`}const c=t[o[0]],l=e[o[0]],u=j0(c);return u!==null?(u.isRuntime&&(s(u.copy),s(u.assign)),`((void)(${u.assign}(${r[0]}, ${u.copy}(${l}))))`):`((void)(*${r[0]} = ${l}))`}const i=t[o[0]],a=j0(i);return a!==null?(a.isRuntime&&s(a.copy),`${a.copy}(${e[o[0]]})`):e[o[0]]},emitJs({argsJs:e,argTypes:t,nargout:n,outTargetsJs:r,useRuntime:s}){const o=Fm(t,n),i=a=>{const c=t[o[a]];return hr(c)?(s("mtoc2_deep_clone"),`mtoc2_deep_clone(${e[o[a]]})`):e[o[a]]};if(r!==void 0){const a=[];for(let c=0;c<n;c++)a.push(i(c));return`[${a.join(", ")}]`}return i(0)},call({args:e,argTypes:t,nargout:n}){const r=Fm(t,n),s=i=>{const a=e[r[i]];return hr(t[r[i]])?If(a):a},o=[];for(let i=0;i<n;i++)o.push(s(i));return o}},jm="'feval' must be intercepted by the lowerer or interpreter (see src/lowering/lowerFuncCall.ts and src/interpreter/interpreterFunctions.ts); reaching the builtin registry hook indicates a routing bug or an unsupported first argument shape (only @name handles, in-scope handle vars, and char-name strings are supported — runtime-computed handle expressions are deferred)",TP={name:"feval",transfer(e){throw e.length<1?new W("'feval' expects at least 1 argument (the function handle or name), got 0"):new W(jm)},emitC(){throw new W(jm)},emitJs(){throw new W(jm)},call(){throw new W(jm)}};function Rm(e,t,n){if(t.length!==1)throw new le(`'${e}' expects 1 arg(s), got ${t.length}`);if(n>1)throw new W(`'${e}' does not support multi-output (nargout=${n})`)}function R0(e){return Wt(e)?e.shape:Er(e)?[1,e.value.length]:[1,1]}function kl(e,t,n){return{name:e,transfer(r,s){return Rm(e,r,s),[at(t(r[0]))]},emitC({argTypes:r}){return t(r[0])?"1.0":"0.0"},emitJs({argTypes:r}){return t(r[0])?"true":"false"},call({args:r}){return[n(r[0])]}}}const PP=kl("islogical",e=>Me(e)&&e.elem==="logical",e=>!!(typeof e=="boolean"||Wt(e)&&e.isLogical)),BP=kl("isfloat",e=>Me(e)&&e.elem==="double",e=>typeof e=="number"?!0:typeof e=="boolean"?!1:un(e)?!0:Wt(e)?!e.isLogical:!1),qP=kl("ischar",e=>xo(e),e=>Er(e)),zP=kl("isstring",e=>Jo(e),e=>typeof e=="string"),VP=kl("isinteger",()=>!1,()=>!1);function Qa(e){return Me(e)?e.dims.length:2}const UP={name:"ndims",transfer(e,t){Rm("ndims",e,t);const n=Math.max(2,Qa(e[0]));return[Be(ft(n),n)]},emitC({argTypes:e}){return`${Math.max(2,Qa(e[0])).toFixed(1)}`},emitJs({argTypes:e}){return`${Math.max(2,Qa(e[0]))}`},call({args:e}){return[Math.max(2,R0(e[0]).length)]}},WP={name:"ismatrix",transfer(e,t){return Rm("ismatrix",e,t),[at(Qa(e[0])<=2)]},emitC({argTypes:e}){return Qa(e[0])<=2?"1.0":"0.0"},emitJs({argTypes:e}){return Qa(e[0])<=2?"true":"false"},call({args:e}){return[R0(e[0]).length<=2]}};function Wk(e,t){const n=r=>{if(!Me(r))return!1;const s=r.dims;return s.length!==2?!1:Dn(s[t])?!0:s[t].kind==="exact"?!1:"runtime"};return{name:e,transfer(r,s){Rm(e,r,s);const o=n(r[0]);return o==="runtime"?[at()]:[at(o)]},emitC({argTypes:r,argsC:s}){const o=n(r[0]);return o===!0?"1.0":o===!1?"0.0":`((${s[0]}).ndim == 2 && (${s[0]}).dims[${t}] == 1)`},emitJs({argTypes:r,argsJs:s}){const o=n(r[0]);return o===!0?"true":o===!1?"false":`(${s[0]}.shape.length === 2 && ${s[0]}.shape[${t}] === 1)`},call({args:r}){const s=R0(r[0]);return[s.length===2&&s[t]===1]}}}const XP=Wk("isrow",0),HP=Wk("iscolumn",1);function L0(e,t,n){if(!os(e)||!os(t))return!1;if(!(e.kind!=="Char"&&e.kind!=="String")&&!(t.kind!=="Char"&&t.kind!=="String")&&!(e.exact===void 0||t.exact===void 0))return n==="case-fold"?e.exact.toLowerCase()===t.exact.toLowerCase():e.exact===t.exact}function YP(e,t,n){if(t.length!==2)throw new le(`'${e}' expects 2 arg(s), got ${t.length}`);if(n!==1)throw new W(`'${e}' does not support multi-output (nargout=${n})`)}function Xk(e){return typeof e=="string"?e:Er(e)?e.value:null}function Hk(e,t,n){const r=t==="case-fold"?ED:AD;return{name:e,transfer(s,o){YP(e,s,o);const i=L0(s[0],s[1],t);return[i===void 0?at():at(i)]},emitC({argsC:s,argTypes:o,useRuntime:i}){const a=L0(o[0],o[1],t);if(a!==void 0)return a?"1.0":"0.0";i(n);const c=Vi(s[0],o[0]),l=Vi(s[1],o[1]);return`${n}(${c}, ${l})`},emitJs({argsJs:s,argTypes:o,useRuntime:i}){const a=L0(o[0],o[1],t);return a!==void 0?a?"true":"false":(i(n),`(${n}(${s[0]}, ${s[1]}) !== 0)`)},call({args:s}){const o=Xk(s[0]),i=Xk(s[1]);return o===null||i===null?[!1]:[r(o,i)!==0]}}}const JP=Hk("strcmp","exact","mtoc2_strcmp"),ZP=Hk("strcmpi","case-fold","mtoc2_strcmpi");function KP(e){if(typeof e=="object"&&e!==null){const t=e;if(t.mtoc2Tag==="char"&&typeof t.value=="string")return t.value}return e}const GP=lF;function QP(e){let t="";for(const n of e)n==="\\"||n==='"'?t+="\\"+n:t+=n;return t}function OP(e){const t=QP(e);return{name:e,transfer(n,r){if(r!==1)throw new W(`'${e}' does not support multi-output (nargout=${r})`);return Ya(e,n,0),[Fi]},emitC({argsC:n,argTypes:r,useRuntime:s}){s("mtoc2_plot_dispatch");const o=[];for(let i=0;i<r.length;i++)o.push(Ja(e,n[i],r[i],i));return`mtoc2_plot_dispatch("${t}", ${o.length}, ${Za(o)})`},emitJs({argsJs:n,useRuntime:r}){return r("mtoc2_plot_dispatch"),`mtoc2_plot_dispatch(${[JSON.stringify(e),...n].join(", ")})`},call({args:n,ctx:r}){return globalThis.$write=r.helpers.write,qR(e,...n.map(KP)),[]}}}const eB=GP.map(OP);for(const e of[...eB,TD,PD,_l,yl,VD,UD,WD,xl,KD,GD,QD,OD,eT,tT,nT,sT,lT,fT,hT,gT,wT,_T,jT,RT,LT,BT,qT,zT,VT,F8,UT,WT,YT,JT,ZT,QT,OT,e8,t8,n8,r8,o8,c8,u8,f8,m8,h8,p8,d8,E8,I8,j8,R8,L8,D8,T8,P8,B8,q8,z8,V8,U8,X8,H8,Y8,O8,n7,o7,i7,a7,c7,m7,h7,p7,d7,g7,_7,x7,b7,k7,v7,M7,$7,C7,S7,N7,A7,E7,I7,F7,j7,R7,L7,D7,T7,B7,q7,z7,V7,U7,W7,H7,Y7,Q7,eP,nP,rP,sP,oP,iP,qP,zP,VP,PP,BP,UP,WP,XP,HP,cP,gP,wP,_P,yP,bP,MP,$P,CP,SP,EP,RP,DP,TP,JP,ZP])xR(e);function tB(e){switch(e){case je.Pow:return"^";case je.ElemPow:return".^";case je.LeftDiv:return"\\";case je.ElemLeftDiv:return".\\";case je.OrOr:return"||";case je.AndAnd:return"&&";case je.BitOr:return"|";case je.BitAnd:return"&";default:return e}}function nB(e){switch(e){case gn.Not:return"~";case gn.Transpose:return"'";case gn.NonConjugateTranspose:return".'";default:return e}}function rB(e,t){switch(e){case je.Add:return"plus";case je.Sub:return"minus";case je.Mul:return"mtimes";case je.ElemMul:return"times";case je.Div:return"mrdivide";case je.ElemDiv:return"rdivide";case je.Equal:return"eq";case je.NotEqual:return"ne";case je.Less:return"lt";case je.LessEqual:return"le";case je.Greater:return"gt";case je.GreaterEqual:return"ge";case je.OrOr:return"oror";case je.AndAnd:return"andand";case je.BitOr:return"or";case je.BitAnd:return"and";case je.Pow:return"mpower";case je.ElemPow:return"power";default:throw new W(`binary operator '${tB(e)}' is not yet supported`,t)}}function sB(e,t){switch(e){case gn.Minus:return"uminus";case gn.Plus:return"uplus";case gn.Transpose:case gn.NonConjugateTranspose:return"transpose";case gn.Not:return"not";default:throw new W(`unary operator '${nB(e)}' is not yet supported`,t)}}function Lm(e){return e.type==="Range"||e.type==="Colon"}function oB(e,t,n){if(e.base.type!=="Member")throw new W(`internal: resolveMemberRootedIndexBase called with non-Member base (got ${e.base.type})`,t);const r=_R(e.base);if(r===null)throw new W(`${Xi(n)} requires a root variable`,e.base.span);const{root:s,fields:o}=r,i=s.name,a=this.envLookup(i);if(a===void 0)throw new le(`use of undefined variable '${i}'`,s.span);if(a.ty.kind!=="Struct"&&a.ty.kind!=="Class")throw new W(`${Xi(n)} of '${i}.${o.join(".")}' but '${i}' is ${ze(a.ty)}; only struct and class fields can be indexed`,e.base.span);let c=a.ty;for(let m=0;m<o.length;m++){const p=o[m],d=cl(c,p);if(d===void 0)throw c.kind==="Class"&&this.classReg(c.className)?.dependentProperties.has(p)?new W(`${Xi(n)} of dependent property '${i}.${o.slice(0,m+1).join(".")}' via indexing is not supported in v1`,e.base.span):new le(`'${i}.${o.slice(0,m+1).join(".")}': no such field on type ${ze(c)}`,e.base.span);c=d}if(!Me(c))throw new W(`${Xi(n)} of '${i}.${o.join(".")}' but the field has type ${ze(c)} (only numeric fields can be indexed)`,e.base.span);if(!qe(c))throw new W(Jk(n,`${i}.${o.join(".")}`,c),t);if(c.elem!=="double")throw new W(`${Xi(n)} into ${ze(c)} is not yet supported`,t);const l=c.dims.length,u=e.indices.length;if(u===0&&(n==="read"||n==="write"))throw new W(n==="read"?`indexing '${i}.${o.join(".")}' requires at least one index`:"indexed write requires at least one index",t);if(u!==1&&u!==l)throw new W(Zk(n,u,l),t);const f=`${a.cName}.${o.join(".")}`;return{rootVar:{kind:"Var",name:i,cName:a.cName,ty:a.ty,span:e.base.span},fieldPath:o,leafTy:c,slotCName:f}}function Yk(e,t,n){if(e.base.type==="Member"){const r=oB.call(this,e,t,n);return{base:r.rootVar,baseTy:r.leafTy,baseCName:r.slotCName,fieldPath:r.fieldPath,leafTy:r.leafTy,displayName:`${r.rootVar.name}.${r.fieldPath.join(".")}`}}if(e.base.type==="Ident"){const r=e.base.name,s=D0.call(this,r,e.indices.length,t,{baseSpan:e.base.span,notInScope:"user-facing",operation:n});return{base:s.base,baseTy:s.baseTy,baseCName:s.baseCName,displayName:r}}throw new W(`indexed assignment requires a simple variable or member chain on the left (got ${e.base.type})`,t)}function D0(e,t,n,r){const{baseSpan:s=n,notInScope:o,operation:i}=r,a=this.envLookup(e);if(a===void 0){if(o==="internal"){const f=i==="read"?"lowerIndexLoad":"lowerIndexSlice";throw new W(`internal: ${f} called for '${e}' which is not in scope`,n)}throw new le(`use of undefined variable '${e}'`,s)}if(!Me(a.ty))throw new W(`${Xi(i)} into ${ze(a.ty)} is not yet supported`,n);if(i==="read"&&De(a.ty))throw new W(`indexing into a scalar variable '${e}' is not yet supported`,n);if(!qe(a.ty))throw new W(Jk(i,e,a.ty),n);if(a.ty.elem!=="double")throw new W(`${Xi(i)} into ${ze(a.ty)} is not yet supported`,n);const c=a.ty.dims.length;if(t===0&&(i==="read"||i==="write")){const f=i==="read"?`indexing '${e}' requires at least one index`:"indexed write requires at least one index";throw new W(f,n)}if(t!==1&&t!==c)throw new W(Zk(i,t,c),n);const l=a.cName,u={kind:"Var",name:e,cName:l,ty:a.ty,span:s};return{baseTy:a.ty,baseCName:l,base:u}}function Xi(e){switch(e){case"read":return"indexing";case"write":return"indexed write";case"sliceRead":return"range/colon indexing";case"sliceWrite":return"range/colon indexed write"}}function Jk(e,t,n){switch(e){case"read":return`cannot index variable '${t}' with type ${ze(n)}`;case"write":return`indexed write requires a multi-element tensor (got ${ze(n)})`;case"sliceRead":return`range/colon indexing requires a multi-element tensor (got ${ze(n)})`;case"sliceWrite":return`range/colon indexed write requires a multi-element tensor (got ${ze(n)})`}}function Zk(e,t,n){switch(e){case"read":return`${t}-index access into a ${n}-D tensor is not yet supported (use 1 linear index or ${n} per-axis indices)`;case"write":return`${t}-index write into a ${n}-D tensor is not yet supported (use 1 linear index or ${n} per-axis indices)`;case"sliceRead":return`range/colon indexing of a ${n}-D tensor requires either 1 slot (linear) or ${n} slots (one per axis); got ${t}`;case"sliceWrite":return`range/colon indexed write into a ${n}-D tensor requires either 1 slot (linear) or ${n} slots (one per axis); got ${t}`}}function iB(e){if(e.rows.length===0)return{kind:"TensorBuild",elements:[],shape:[0,0],ty:et([0,0]),span:e.span};const t=[];let n=!1,r=!1;for(const d of e.rows){const g=[];for(const w of d){const _=this.lowerExpr(w),y=_.ty;if(!Me(y))throw new W(`bracket literal cell must be a numeric scalar or tensor (got ${ze(y)})`,w.span);if(y.elem!=="double"&&y.elem!=="logical")throw new W(`bracket literal cell must be a real double or logical (got ${y.elem})`,w.span);if(y.dims.length>2)throw new W(`bracket concatenation requires 2-D cells (got a rank-${y.dims.length} tensor); use 'cat'/'permute' for higher-rank inputs`,w.span);if(y.isComplex){if(qe(y))throw new W("bracket literal with a complex tensor cell is not yet supported",w.span);r=!0}if(De(y)){g.push({kind:"scalar",expr:_,ty:y});continue}const b=y.dims[0],k=y.dims[1],M=b.kind==="exact"?b.value:null,$=k.kind==="exact"?k.value:null;if(M===0||$===0){g.push({kind:"empty",ty:y});continue}n=!0,g.push({kind:"tensor",expr:_,ty:y,rows:M,cols:$})}t.push(g)}if(!n&&t.every(d=>d.every(g=>g.kind==="scalar"))){const d=t.length,g=t[0].length;for(const M of t)if(M.length!==g)throw new le(`bracket horzcat row-count mismatch: row 1 has ${g} cells, another row has ${M.length}`,e.span);const w=g,_=d*w,y=new Array(_);for(let M=0;M<d;M++)for(let $=0;$<w;$++){const N=t[M][$];if(N.kind!=="scalar")throw new Error("internal: unexpected non-scalar in scalar fast path");y[$*d+M]=N.expr}if(d===1&&w===1)return y[0];if(r){let M;if(_<=wt){const N=new Float64Array(_),E=new Float64Array(_);let R=!0;for(let D=0;D<_;D++){const I=Us(y[D].ty);if(I===void 0){R=!1;break}N[D]=I.re,E[D]=I.im}R&&(M={re:N,im:E})}const $=Ut([d,w],M);return{kind:"TensorBuild",elements:y,shape:[d,w],ty:$,span:e.span}}let b;if(_<=wt){const M=new Float64Array(_);let $=!0;for(let N=0;N<_;N++){const E=Je(y[N].ty);if(E===void 0){$=!1;break}M[N]=E}$&&(b=M)}const k=et([d,w],b);return y.every(M=>Me(M.ty)&&M.ty.elem==="logical")&&(k.elem="logical",k.sign="nonneg"),{kind:"TensorBuild",elements:y,shape:[d,w],ty:k,span:e.span}}if(r)throw new W("bracket literal mixing complex cells with multi-element tensor cells is not yet supported (concat lane-copy is deferred)",e.span);const s=[],o=[],i=[],a=[];for(let d=0;d<t.length;d++){const g=t[d],w=[],_=[];let y,b=0;for(let k=0;k<g.length;k++){const M=g[k];if(M.kind==="empty")continue;const $=M.kind==="scalar"?1:M.rows,N=M.kind==="scalar"?1:M.cols;if(y===void 0)y=$;else{if(y!==null&&$!==null&&y!==$)throw new le(`bracket horzcat row-height mismatch: cell ${k+1} on row ${d+1} has ${$} row(s) but a neighbor in the same row has ${y}`,e.rows[d][k].span);y===null&&$!==null&&(y=$)}w.push(M),_.push(N),b=b===null||N===null?null:b+N}y!==void 0&&(s.push(w),o.push(y),i.push(b),a.push(_))}if(s.length===0)return{kind:"TensorBuild",elements:[],shape:[0,0],ty:et([0,0]),span:e.span};let c=null;for(const d of i)if(d!==null){if(c===null)c=d;else if(c!==d)throw new le(`bracket vertcat column-count mismatch: a row has ${c} column(s), another has ${d}`,e.span)}const l=c;let u=0;for(const d of o){if(d===null){u=null;break}u+=d}if(s.length===1&&s[0].length===1)return s[0][0].expr;const f=s.map(d=>d.map(g=>g.expr));let h;if(u!==null&&l!==null&&o.every(d=>d!==null)&&a.every(d=>d.every(g=>g!==null))){const d=u*l;if(d<=wt){const g=new Float64Array(d);let w=!0,_=0;for(let y=0;y<s.length&&w;y++){const b=s[y];let k=0;for(let M=0;M<b.length&&w;M++){const $=b[M],N=$.kind==="scalar"?1:$.rows,E=$.kind==="scalar"?1:$.cols;if($.kind==="scalar"){const R=Je($.ty);if(R===void 0){w=!1;break}const D=_+k*u;g[D]=R}else{const R=$.ty.exact;if(!(R instanceof Float64Array)){w=!1;break}for(let D=0;D<E;D++)for(let I=0;I<N;I++){const q=_+I+(k+D)*u,Y=I+D*N;g[q]=R[Y]}}k+=E}_+=o[y]}w&&(h=g)}}const p=Zt([u===null?{kind:"unknown"}:u===1?nn:{kind:"exact",value:u},l===null?{kind:"unknown"}:l===1?nn:{kind:"exact",value:l}]);return h!==void 0&&p.shape!==void 0&&(p.exact=h,p.sign=ol(h)),{kind:"TensorConcat",cells:f,rowHeights:o,cellCols:a,shape:[u,l],ty:p,span:e.span}}function aB(e){if(e.rows.length===0){const l=[0,0];return{kind:"CellLit",elements:[],shape:l,ty:il(l,[]),span:e.span}}const t=e.rows.length,n=e.rows[0].length;for(let l=0;l<t;l++)if(e.rows[l].length!==n)throw new W(`cell literal: row ${l+1} has ${e.rows[l].length} cells, expected ${n} (every row must have the same width)`,e.span);const r=[];for(let l=0;l<t;l++){const u=[];for(let f=0;f<n;f++){const h=this.lowerExpr(e.rows[l][f]);if(zd(h.ty))throw new W(`cell literal slot: cannot use the result of a zero-output function as a value (got ${ze(h.ty)})`,e.rows[l][f].span);u.push(h)}r.push(u)}const s=[],o=[];for(let l=0;l<n;l++)for(let u=0;u<t;u++)s.push(r[u][l]),o.push(r[u][l].ty);const i=[t,n],a=Dt(i);if(a>wt)throw new W(`cell literal with ${a} slots exceeds the EXACT_ARRAY_MAX_ELEMENTS cap (${wt})`,e.span);return{kind:"CellLit",elements:s,shape:i,ty:il(i,o),span:e.span}}function cB(e){if(e.base.type!=="Ident")throw new W("cell brace indexing supports a bare cell variable as the base; member-rooted forms (e.g. 'obj.f{i}') are not yet supported",e.span);const t=this.env.get(e.base.name);if(t===void 0)throw new le(`undefined variable '${e.base.name}'`,e.span);if(!ys(t.ty))throw new le(`'${e.base.name}' is not a cell (got ${ze(t.ty)}); brace indexing 'c{...}' requires a cell-typed variable`,e.span);const n=t.ty,r=t.cName;if(e.indices.length===0)throw new W("cell brace indexing requires at least one index",e.span);if(e.indices.length>2)throw new W(`cell brace indexing supports 1 or 2 indices (got ${e.indices.length})`,e.span);const s=e.indices.map(i=>{if(i.type==="Colon"||i.type==="Range")throw new W("cell brace indexing with ':' / range slices not yet supported",i.span);const a=this.lowerExpr(i);if(!Me(a.ty)||!De(a.ty)||a.ty.isComplex)throw new le(`cell brace index must be a real scalar (got ${ze(a.ty)})`,i.span);return a}),o=lB(n,s,e.span);return{kind:"CellIndexLoad",base:{kind:"Var",name:e.base.name,cName:r,ty:n,span:e.base.span},indices:s,ty:o,span:e.span}}function lB(e,t,n){if(e.mode==="uniform")return e.elem;const r=e.elements,s=e.shape;if(s===void 0)throw new W("internal: tuple cell missing exact shape",n);const o=Kk(t,e);if(o!==null){if(o<0||o>=r.length)throw new le(`cell brace index out of range: slot ${o+1} is outside the cell's ${Dt(s)} slots`,n);return r[o]}if(r.length===0)throw new le("cell brace read into an empty cell {}",n);let i=r[0];for(let a=1;a<r.length;a++)if(i=Li(i,r[a]),i.kind==="Unknown")throw new W(`cell brace read with a non-static index requires all slot types to unify; got divergent slot types (slot 1: ${ze(r[0])}, slot ${a+1}: ${ze(r[a])})`,n);return i}function Kk(e,t){const n=t.shape;if(n===void 0)return null;if(e.length===1){if(e[0].kind!=="NumLit")return null;const r=e[0].value;return!Number.isInteger(r)||r<1?null:r-1}if(e.length===2){if(e[0].kind!=="NumLit"||e[1].kind!=="NumLit")return null;const r=e[0].value-1,s=e[1].value-1;if(r<0||s<0)return null;const o=n[0];return s*o+r}return null}function uB(e,t,n){if(e.base.type!=="Ident")throw new W("cell brace assignment supports a bare cell variable as the base; member-rooted forms (e.g. 'obj.f{i} = rhs') are not yet supported",n);const r=this.env.get(e.base.name);if(r===void 0)throw new le(`undefined variable '${e.base.name}' (must be initialised before brace-indexed assignment)`,n);if(!ys(r.ty))throw new le(`'${e.base.name}' is not a cell (got ${ze(r.ty)}); brace assignment 'c{...} = rhs' requires a cell-typed variable`,n);const s=r.ty,o=r.cName;if(e.indices.length===0)throw new W("cell brace assignment requires at least one index",n);if(e.indices.length>2)throw new W(`cell brace assignment supports 1 or 2 indices (got ${e.indices.length})`,n);const i=[],a=e.indices.map(h=>{if(h.type==="Colon"||h.type==="Range")throw new W("cell brace assignment with ':' / range slices not yet supported",h.span);const m=this.lowerExpr(h);if(!Me(m.ty)||!De(m.ty)||m.ty.isComplex)throw new le(`cell brace index must be a real scalar (got ${ze(m.ty)})`,h.span);return this.anfRequireScalarOrVar(m,i)}),c=this.lowerExpr(t);if(c.ty.kind==="Void")throw new le("cannot store the result of a zero-output function into a cell slot",t.span);const l=c,u=Kk(a,s);if(s.mode==="tuple"){const h=s.elements;if(u!==null){if(u<0||u>=h.length)throw new le(`cell brace assignment slot ${u+1} is outside the cell's ${Dt(s.shape)} slots`,n);const m=h[u];if(!ll(m,l.ty))throw new W(`cell brace assignment: rhs type ${ze(l.ty)} is not storage-equivalent to slot ${u+1}'s type ${ze(m)} (cells don't reshape mid-lifetime; introduce a new cell literal or construct the cell with the target slot type)`,n)}else for(let m=0;m<h.length;m++)if(!ll(h[m],l.ty))throw new W(`cell brace assignment with a non-static index requires every slot's storage to match the rhs; slot ${m+1} has type ${ze(h[m])}, rhs has ${ze(l.ty)}`,n)}else if(!ll(s.elem,l.ty))throw new W(`cell brace assignment: rhs type ${ze(l.ty)} is not storage-equivalent to the cell's elem type ${ze(s.elem)} (cells don't reshape mid-lifetime)`,n);const f={kind:"CellIndexStore",base:{kind:"Var",name:e.base.name,cName:o,ty:r.ty,span:e.base.span},indices:a,rhs:l,span:n};return i.length===0?f:[...i,f]}function fB(e){if(this.env.has(e.name))throw new le(`function-handle target '@${e.name}' refers to an in-scope variable, not a function`,e.span);if(is(e.name))throw new W(`builtin function handles (e.g. '@${e.name}') are not supported`,e.span);const t=this.workspace.resolve(e.name,[],this.callSite(),e.span);if(t?.kind!=="userFunction")throw new W(`unresolved function-handle target '@${e.name}'`,e.span);const n=Kx(e.name,t.ast,[]);return{kind:"HandleLit",captures:[],ty:n,span:e.span}}function mB(e){const t=new Set(e.params),n=[],r=new Set;Ir(this.env,e.body,t,n,r);const s=[],o=[];for(const f of n){if(t.has(f))throw new W(`anonymous-function parameter '${f}' shadows a captured variable; rename the parameter`,e.span);const h=this.env.get(f);if(h===void 0)throw new W(`internal: capture '${f}' lost between detection and lowering`,e.span);if(h.ty.kind!=="Numeric"&&h.ty.kind!=="Struct"&&h.ty.kind!=="Class"&&h.ty.kind!=="Handle")throw new W(`anonymous function captures '${f}' of unsupported type ${ze(h.ty)} (string / void / unknown captures are not supported)`,e.span);s.push({name:f,ty:h.ty}),o.push({name:f,value:{kind:"Var",name:f,cName:h.cName,ty:h.ty,span:e.span}})}const i=this.anonCounter++,a=`anon_${i}`,c=`anonOut_${i}`,l={type:"Function",name:a,functionId:a,params:[...e.params,...n],outputs:[c],body:[{type:"Assign",name:c,expr:e.body,suppressed:!0,span:e.span}],argumentsBlocks:[],span:e.span},u=Kx(a,l,s);return{kind:"HandleLit",captures:o,ty:u,span:e.span}}function hB(e,t,n,r){const s=t.ty,o=n.map(l=>this.lowerExpr(l));for(const l of o)this.requireValueType(l,`argument to handle '${e}'`);const i={kind:"Var",name:e,cName:t.cName,ty:s,span:r},a=s.captures.map(l=>({kind:"HandleCaptureLoad",base:i,captureName:l.name,ty:l.ty,span:r})),c=[...o,...a];return So.call(this,s.ast,c,s.targetName,r,{definingFile:s.ast.span.file})}function pB(e,t,n,r,s){const o=t.ty,i=n.map(_=>this.lowerExpr(_));for(const _ of i)this.requireValueType(_,`argument to handle '${e}'`);const a={kind:"Var",name:e,cName:t.cName,ty:o,span:s},c=o.captures.map(_=>({kind:"HandleCaptureLoad",base:a,captureName:_.name,ty:_.ty,span:s})),l=[...i,...c],u=[],f=l.map(_=>this.anfRequireScalarOrVar(_,u)),h=l.map(_=>_.ty);if(r.length>o.ast.outputs.length)throw new W(`handle '${e}' targets '${o.targetName}', which returns ${o.ast.outputs.length} output(s); ${r.length} were requested`,s);if(o.ast.outputs.length===0&&r.length>0)throw new W(`handle '${e}' targets '${o.targetName}', which has no outputs and cannot be assigned`,s);const m=r.length,p=vl.call(this,o.ast,h,o.targetName,o.ast.span.file,void 0,m,s);if(p.outputTypes.length===1){const _={kind:"Call",cName:p.cName,name:o.targetName,args:f,ty:p.outputTypes[0]??{kind:"Unknown"},span:s},y=r[0];if(y===void 0||y.type!=="Var"){const k={kind:"ExprStmt",expr:_,span:s};return u.length===0?k:[...u,k]}const b=this.recordAssignment(y.name,_,s);return u.length===0?b:[...u,b]}if(p.outputTypes.length===0){const y={kind:"ExprStmt",expr:{kind:"Call",cName:p.cName,name:o.targetName,args:f,ty:Fi,span:s},span:s};return u.length===0?y:[...u,y]}const d=p.outputTypes.map(_=>_??{kind:"Unknown"}),g=V0.call(this,o.targetName,d,r,_=>`output '${o.ast.outputs[_]}'`,s),w={kind:"MultiAssignCall",cName:p.cName,name:o.targetName,args:f,outputs:g,span:s};return u.length===0?w:[...u,w]}function Ir(e,t,n,r,s){const o=i=>{n.has(i)||s.has(i)||is(i)||e.has(i)&&(s.add(i),r.push(i))};switch(t.type){case"Ident":o(t.name);return;case"Number":return;case"Binary":Ir(e,t.left,n,r,s),Ir(e,t.right,n,r,s);return;case"Unary":Ir(e,t.operand,n,r,s);return;case"Range":Ir(e,t.start,n,r,s),t.step&&Ir(e,t.step,n,r,s),Ir(e,t.end,n,r,s);return;case"FuncCall":o(t.name);for(const i of t.args)Ir(e,i,n,r,s);return;case"Tensor":for(const i of t.rows)for(const a of i)Ir(e,a,n,r,s);return;case"AnonFunc":{const i=new Set(n);for(const a of t.params)i.add(a);Ir(e,t.body,i,r,s);return}case"FuncHandle":return;case"Member":Ir(e,t.base,n,r,s);return;case"Index":Ir(e,t.base,n,r,s);for(const i of t.indices)Ir(e,i,n,r,s);return;case"MethodCall":Ir(e,t.base,n,r,s);for(const i of t.args)Ir(e,i,n,r,s);return;case"SuperMethodCall":for(const i of t.args)Ir(e,i,n,r,s);return;default:return}}function Gk(e){if(e.kind!=="Range")return;const t=Me(e.start.ty)&&typeof e.start.ty.exact=="number"?e.start.ty.exact:void 0,n=Me(e.end.ty)&&typeof e.end.ty.exact=="number"?e.end.ty.exact:void 0;if(e.step.kind!=="NumLit")return;const r=e.step.value;if(!(t===void 0||n===void 0)&&r!==0&&!(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)))return ob(t,r,n)}function dB(e,t){if(e.kind==="Colon")return t;if(e.kind==="Range"){const n=Gk(e);return n===void 0?{kind:"unknown"}:{kind:"exact",value:n}}if(e.kind==="IndexVec"){const n=e.expr.ty;return Me(n)&&n.shape!==void 0?{kind:"exact",value:Dt(n.shape)}:{kind:"unknown"}}return e.kind==="LogicalMask"?{kind:"unknown"}:{kind:"exact",value:1}}function Dm(e,t,n){const{baseTy:r,baseCName:s,base:o}=D0.call(this,e,t.length,n,{notInScope:"internal",operation:"sliceRead"}),i=t.length===1,a=[];for(let u=0;u<t.length;u++){const f=i?"linear":u;a.push(Qk.call(this,s,r,f,t[u]))}const c=r.isComplex;let l;if(i){const u=a[0];if(u.kind==="Colon")if(r.shape!==void 0){const f=Dt(r.shape);l=c?Ut([f,1]):et([f,1])}else{const f=[{kind:"unknown"},{kind:"exact",value:1}];l=c?mr(f):Zt(f)}else if(u.kind==="Range"){const f=Vd(r),h=Ud(r),m=(()=>{const g=Gk(u);return g===void 0?{kind:"unknown"}:{kind:"exact",value:g}})(),p={kind:"exact",value:1},d=h?[m,p]:f?[p,m]:[p,m];l=c?mr(d):Zt(d)}else if(u.kind==="LogicalMask"){const f=Vd(r),h=Ud(r),m={kind:"unknown"},p={kind:"exact",value:1},d=f?[p,m]:h?[m,p]:[m,p];l=c?mr(d):Zt(d)}else throw new W("internal: single-slot scalar slice should have routed through lowerIndexLoad",n)}else{const u=a.map((f,h)=>dB(f,r.dims[h]));l=c?mr(u):Zt(u)}return{kind:"IndexSlice",base:o,index:a,ty:l,span:n}}function Qk(e,t,n,r){if(r.type==="Colon")return{kind:"Colon",span:r.span};if(r.type!=="Range"){this.endStack.push({baseCName:e,baseTy:t,axis:n});let a;try{a=this.lowerExpr(r)}finally{this.endStack.pop()}if(Me(a.ty)&&!a.ty.isComplex&&a.ty.elem==="logical"&&Kn(a.ty))throw new W("scalar logical index (a 1-element logical mask) is not JIT-compiled",r.span);if(Kn(a.ty))return{kind:"Scalar",expr:a,span:r.span};if(Me(a.ty)&&!a.ty.isComplex&&(a.ty.elem==="double"||a.ty.elem==="logical")&&!Kn(a.ty)){if(a.ty.elem==="logical")return{kind:"LogicalMask",expr:a,span:r.span};if(n==="linear")throw new W(`linear vector-of-indices reads (got '${ze(a.ty)}' in a single-slot context) are not yet supported`,r.span);return{kind:"IndexVec",expr:a,span:r.span}}throw new le(`index slot must be a real scalar or a numeric index vector (got ${ze(a.ty)})`,r.span)}this.endStack.push({baseCName:e,baseTy:t,axis:n});let s,o,i;try{s=this.lowerExpr(r.start),r.step===null?o={kind:"NumLit",value:1,ty:{kind:"Numeric",elem:"double",isComplex:!1,dims:[{kind:"exact",value:1},{kind:"exact",value:1}],shape:[1,1],sign:"positive",exact:1},span:r.span}:o=this.lowerExpr(r.step),i=this.lowerExpr(r.end)}finally{this.endStack.pop()}if(!Kn(s.ty))throw new le(`range start must be a real scalar (got ${ze(s.ty)})`,r.start.span);if(!Kn(i.ty))throw new le(`range end must be a real scalar (got ${ze(i.ty)})`,r.end.span);if(!Kn(o.ty))throw new le(`range step must be a real scalar (got ${ze(o.ty)})`,r.step?.span??r.span);if(o.kind!=="NumLit"){const a=o.ty.kind==="Numeric"&&typeof o.ty.exact=="number"?o.ty.exact:void 0;if(a===void 0)throw new W("range step in an index expression must be a compile-time-known numeric value (got expression with unknown value)",r.step?.span??r.span);o={kind:"NumLit",value:a,ty:{kind:"Numeric",elem:"double",isComplex:!1,dims:[{kind:"exact",value:1},{kind:"exact",value:1}],shape:[1,1],sign:a>0?"positive":a<0?"negative":"zero",exact:a},span:r.step?.span??r.span}}if(o.value===0)throw new W("range step in an index expression must be non-zero",r.step?.span??r.span);return{kind:"Range",start:s,step:o,end:i,span:r.span}}function T0(e,t,n){const{baseTy:r,baseCName:s,base:o}=D0.call(this,e,t.length,n,{notInScope:"internal",operation:"read"}),i=[],a=t.length;for(let l=0;l<a;l++){const u=a===1?"linear":l;this.endStack.push({baseCName:s,baseTy:r,axis:u});let f;try{f=this.lowerExpr(t[l])}finally{this.endStack.pop()}if(!Kn(f.ty)){if(Me(f.ty)&&!f.ty.isComplex&&qe(f.ty)&&(f.ty.elem==="double"||f.ty.elem==="logical"))return Dm.call(this,e,t,n);throw new le(`index ${l+1} of '${e}' must be a real scalar (got ${ze(f.ty)})`,t[l].span)}if(Me(f.ty)&&!f.ty.isComplex&&f.ty.elem==="logical")throw new W(`scalar logical index of '${e}' (a 1-element logical mask) is not JIT-compiled`,t[l].span);i.push(f)}const c=gB(r,i);return{kind:"IndexLoad",base:o,indices:i,ty:c??(r.isComplex?_t():Be("unknown")),span:n}}function gB(e,t){const n=e.shape;if(n===void 0)return;const r=Mt(e),s=r===void 0?rn(e):void 0;if(r===void 0&&s===void 0)return;const o=[];for(const c of t){if(!Me(c.ty)||typeof c.ty.exact!="number")return;const l=c.ty.exact;if(!Number.isFinite(l)||!Number.isInteger(l)||l<1)return;o.push(l)}const i=ib(n,o);if(i===void 0)return;if(s!==void 0)return _t({re:s.re[i],im:s.im[i]});const a=r[i];return Be(ft(a),a)}function Tm(e,t,n){if(e.constructor===null){if(t.length!==0)throw new le(`class '${e.className}' has no constructor; cannot pass arguments`,n);const u=Ok.call(this,e,[],n);return ev.call(this,e,u,n)}const r=t.map(u=>this.lowerExpr(u));for(const u of r)this.requireValueType(u,`argument to constructor '${e.className}'`);const s=r.map(u=>u.ty),o=Ok.call(this,e,s,n),i=ev.call(this,e,o,n),a=e.constructor.outputs[0],c=vl.call(this,e.constructor,s,e.className,e.file,{name:a,ty:o,initExpr:i},1,n),l=c.outputTypes[0]??o;return{kind:"Call",cName:c.cName,name:e.className,args:r,ty:l,span:n}}function Ok(e,t,n){if(e.ty!==null)return e.ty;if(e.constructor===null)throw new W(`internal: class '${e.className}' has pending properties but no constructor`,n);const r=e.constructor;if(t.length>r.params.length)throw new le(`constructor '${e.className}' expects at most ${r.params.length} arg(s), got ${t.length}`,n);const s=r.outputs[0],o=this.env,i=this.tempCounter,a=this.currentFile;this.env=new Map,this.tempCounter=0,this.currentFile=e.file;for(let u=0;u<t.length;u++)this.env.set(r.params[u],{cName:Hi(r.params[u]),ty:t[u]});const c=[];try{for(const u of e.propertyNames){if(e.dependentProperties.has(u))continue;const f=e.defaults.get(u);if(f!==void 0){c.push({name:u,ty:f.ty});continue}const h=wB(r.body,s,u);if(h===null)throw new W(`class '${e.className}' property '${u}' has no default and is not directly assigned at the top level of the constructor body (\`${s}.${u} = <expr>;\`); either add a default value or add such an assignment`,r.span);const m=this.lowerExpr(h);this.requireValueType(m,`inferring type of '${e.className}.${u}'`),c.push({name:u,ty:m.ty})}}finally{this.env=o,this.tempCounter=i,this.currentFile=a}const l=Bd(e.className,c);return e.ty=l,l}function ev(e,t,n){const r=[];for(const s of t.properties){const o=e.defaults.get(s.name);let i;if(o!==void 0){const a=this.env;this.env=new Map,i=this.lowerExpr(o.expr),this.env=a}else i=_B(s.ty,e.className,s.name,n);r.push({name:s.name,value:i})}return{kind:"StructLit",fields:r,ty:t,span:n}}function wB(e,t,n){for(const r of e)if(r.type==="AssignLValue"&&r.lvalue.type==="Member"&&r.lvalue.name===n&&r.lvalue.base.type==="Ident"&&r.lvalue.base.name===t)return r.expr;return null}function _B(e,t,n,r){if(e.kind==="Numeric")return qe(e)?{kind:"TensorBuild",elements:[],shape:[0,0],ty:et([0,0]),span:r}:{kind:"NumLit",value:0,ty:Be("zero",0),span:r};throw new W(`class '${t}' property '${n}' is inferred to type ${ze(e)}, but v1 can only synthesize a zero placeholder for numeric properties; provide an explicit default value`,r)}function P0(e){const t=this.env.get(e.name);if(t===void 0&&e.name==="struct")return bB.call(this,e);if(t===void 0&&e.name==="cell")return kB.call(this,e);if(t===void 0&&e.name==="bsxfun"){const o=xB.call(this,e);if(o!==null)return o}if(t===void 0&&e.name==="feval")return yB.call(this,e);if(t!==void 0&&Mf(t.ty))return hB.call(this,e.name,t,e.args,e.span);if(t===void 0&&this.workspace.isClass(e.name)){const o=this.workspace.requireClass(e.name);if(o===void 0)throw new W(`internal: class '${e.name}' missing from workspace registry`,e.span);return Tm.call(this,o,e.args,e.span)}if(t!==void 0){if(Me(t.ty)&&qe(t.ty))return e.args.some(Lm)?Dm.call(this,e.name,e.args,e.span):T0.call(this,e.name,e.args,e.span);throw new W(`'${e.name}' is an in-scope variable of type ${ze(t.ty)}; cannot be called as a function (scalar indexing and dynamically-typed handles are not supported)`,e.span)}const n=e.args.map(o=>this.lowerExpr(o));for(const o of n)this.requireValueType(o,`argument to '${e.name}'`);const r=n.map(o=>o.ty);if(n.length===0){const o=is(e.name);if(o!==void 0){let i;try{i=o.transfer([],1)}catch{i=void 0}if(i!==void 0)return{kind:"Call",cName:e.name,name:e.name,args:[],ty:i[0],span:e.span}}}const s=this.workspace.resolve(e.name,r,this.callSite(),e.span);if(!s){const o=is(e.name);if(o!==void 0){const i=Yo(e.span,()=>o.transfer(r,1))[0];return{kind:"Call",cName:e.name,name:e.name,args:n,ty:i,span:e.span}}throw new W(`unknown function '${e.name}'`,e.span)}switch(s.kind){case"builtin":{const o=is(e.name);if(!o)throw new W(`builtin '${e.name}' is not supported by mtoc2`,e.span);const i=Yo(e.span,()=>o.transfer(r,1))[0];return{kind:"Call",cName:e.name,name:e.name,args:n,ty:i,span:e.span}}case"userFunction":return So.call(this,s.ast,n,e.name,e.span,{definingFile:s.file});case"classMethod":{const o=this.classReg(s.className);if(o===void 0)throw new W(`internal: class '${s.className}' missing from workspace registry`,e.span);const i=s.stripInstance?o.staticMethods.get(s.methodName):o.methods.get(s.methodName);if(i===void 0)throw new le(`class '${s.className}' has no ${s.stripInstance?"static ":""}method '${s.methodName}'`,e.span);if(i.outputs.length>=2)throw new W(`class method '${s.className}.${s.methodName}' has ${i.outputs.length} outputs; multi-output methods can only be called via '[a, b, ...] = ...' (not yet supported for class methods) or as a bare statement`,e.span);const a=s.stripInstance?n.slice(1):n;return So.call(this,i,a,`${s.className}.${s.methodName}`,e.span,{specSource:Xa(s.className,s.methodName),definingFile:i.span.file??o.file})}case"classConstructor":{const o=this.classReg(s.className);if(o===void 0)throw new W(`internal: class '${s.className}' missing from workspace registry`,e.span);return Tm.call(this,o,e.args,e.span)}case"mtoc2UserFunction":{const o=this.workspace.getUserBuiltin(s.name);if(!o)throw new W(`internal: workspace resolved '${s.name}' to a .mtoc2.js function but no Builtin is loaded`,e.span);const i=Yo(e.span,()=>o.transfer(r,1))[0];return{kind:"Call",cName:e.name,name:e.name,args:n,ty:i,span:e.span}}}}function yB(e){const t=tv(e);return P0.call(this,t)}function tv(e){if(e.args.length<1)throw new W("'feval' expects at least 1 argument (the function handle or name), got 0",e.span);const t=e.args[0],n=e.args.slice(1);let r;switch(t.type){case"FuncHandle":r=t.name;break;case"Ident":r=t.name;break;case"Char":case"String":if(r=ov(t.value),!/^[A-Za-z_][A-Za-z0-9_.]*$/.test(r))throw new W(`'feval' name argument '${r}' is not a valid function identifier`,t.span);break;case"AnonFunc":throw new W("'feval' on an inline anonymous handle ('@(...) ...') is not supported; bind the handle to a local variable first (f = @(...) ...; feval(f, ...))",e.span);default:throw new W(`'feval' first argument must be a function-handle literal (@name), an in-scope handle variable, or a char/string function name; got '${t.type}' (runtime-computed handle expressions are not supported — bind to a local first)`,t.span)}return{type:"FuncCall",name:r,args:n,span:e.span}}function xB(e){if(e.args.length!==3)return null;const t=e.args[0];if(t.type!=="FuncHandle")throw new W("'bsxfun' first arg must be a function-handle literal (e.g. @times); dynamic handle-value bsxfun is not yet supported",e.span);const n=t.name,r=new Set(["plus","minus","times","rdivide","power","eq","ne","lt","le","gt","ge","mod","rem","atan2","hypot","max","min"]);if(!r.has(n))throw new W(`'bsxfun' with handle target '@${n}' is not supported; supported targets: ${[...r].sort().join(", ")}`,e.span);const s={type:"FuncCall",name:n,args:[e.args[1],e.args[2]],span:e.span};return P0.call(this,s)}function bB(e){if(e.args.length%2!==0)throw new le("'struct' expects an even number of args (name, value, name, value, ...)",e.span);const t=[],n=new Set;for(let o=0;o<e.args.length;o+=2){const i=e.args[o];if(i.type!=="String"&&i.type!=="Char")throw new le(`'struct' field name (arg ${o+1}) must be a string or char literal`,i.span);const a=ov(i.value);if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(a))throw new le(`'struct' field name '${a}' is not a valid identifier`,i.span);if(n.has(a))throw new le(`'struct': duplicate field '${a}'`,i.span);n.add(a);const c=this.lowerExpr(e.args[o+1]);if(this.requireValueType(c,`value for field '${a}'`),ys(c.ty))throw new W("'struct' with a cell-valued field (cell-expansion / struct-array construction) is not JIT-compiled; the interpreter handles it",e.args[o+1].span);if(c.ty.kind==="Void"||c.ty.kind==="Unknown")throw new le(`value for field '${a}': type ${ze(c.ty)} is not a valid struct field type`,e.args[o+1].span);t.push({name:a,value:c})}const r=t.map(o=>({name:o.name,ty:o.value.ty})),s=Pd(r);return{kind:"StructLit",fields:t,ty:s,span:e.span}}function kB(e){if(e.args.length===0)return{kind:"CellEmpty",dims:[],ty:il([0,0],[]),span:e.span};if(e.args.length>Zn)throw new W(`'cell' accepts up to ${Zn} dim arguments (got ${e.args.length})`,e.span);const t=e.args.map(a=>{const c=this.lowerExpr(a);if(this.requireValueType(c,"'cell' dim argument"),!Me(c.ty)||!De(c.ty)||c.ty.isComplex)throw new le(`'cell' dim argument must be a real scalar (got ${ze(c.ty)})`,a.span);return c}),n=[];if(t.length===1){const a=Me(t[0].ty)&&typeof t[0].ty.exact=="number"?t[0].ty.exact:null;n.push({exactValue:a,expr:t[0]}),n.push({exactValue:a,expr:t[0]})}else for(const a of t){const c=Me(a.ty)&&typeof a.ty.exact=="number"?a.ty.exact:null;n.push({exactValue:c,expr:a})}for(let a=0;a<n.length;a++){const c=n[a].exactValue;if(c!==null&&(!Number.isInteger(c)||c<0))throw new le(`'cell' dim argument ${a+1} must be a non-negative integer (got ${c})`,e.span)}const r=n.every(a=>a.exactValue!==null);let s=null;if(r){s=1;for(const a of n)s*=a.exactValue}if(r&&s!==null&&s<=wt){const a=n.map(u=>u.exactValue),c=s,l=[];for(let u=0;u<c;u++)l.push(qd());return{kind:"CellEmpty",dims:n.map(u=>u.expr),ty:il(a,l),span:e.span}}const i=n.map(a=>a.exactValue===null?{kind:"unknown"}:a.exactValue===1?nn:{kind:"exact",value:a.exactValue});return{kind:"CellEmpty",dims:n.map(a=>a.expr),ty:vf(i,qd()),span:e.span}}function B0(e){let t,n,r,s;if(e.expr.type==="FuncCall"){let M=e.expr;M.name==="feval"&&this.env.get("feval")===void 0&&(M=tv(M)),t=M.name,n=M.args,r=M.span,s=void 0}else if(e.expr.type==="MethodCall"){const M=Cf(e.expr.base);if(M===null||this.env.has(M.split(".")[0]))throw new W("multi-assign right-hand side must be a user-function or package-function call (got instance-method dispatch, not yet supported in '[...] = ...')",e.span);t=`${M}.${e.expr.name}`,n=e.expr.args,r=e.expr.span,s=t}else throw new W("multi-assign right-hand side must be a user-function call",e.span);const o={args:n,span:r},i=MB.call(this,e.lvalues,e.span);for(const M of i)if(M.type!=="Var"&&M.type!=="Ignore"&&M.type!=="Member"&&M.type!=="Index"&&M.type!=="IndexCell")throw new W(`multi-assign lvalue must be a simple identifier, '~' ignore, a member access, an indexed write, or a brace-indexed cell write (got '${M.type}')`,e.span);if(e={...e,lvalues:i},e.expr.type==="FuncCall"){const M=this.env.get(t);if(M!==void 0&&Mf(M.ty))return pB.call(this,t,M,n,e.lvalues,e.span)}if(this.env.get(t)!==void 0)throw new W(`multi-assign of '${t}': name resolves to an in-scope variable, not a function`,e.span);if(this.workspace.isClass(t))throw new W(`multi-assign of '${t}': class constructors have a single output`,e.span);const a=o.args.map(M=>this.lowerExpr(M));for(const M of a)this.requireValueType(M,`argument to '${t}'`);const c=a.map(M=>M.ty),l=[],u=a.map(M=>this.anfRequireScalarOrVar(M,l)),f=this.workspace.resolve(t,c,this.callSite(),o.span);if(f?.kind==="builtin"){const M=is(t);if(M!==void 0)return vB.call(this,t,M,u,c,l,e)}if(f?.kind!=="userFunction")throw new W(`multi-assign of '${t}': only user-defined functions can appear on the right of '[...] = ...' (or as a bare multi-output statement)`,e.span);const h=f.ast,m=f.file;if(e.lvalues.length>h.outputs.length)throw new W(`function '${t}' returns ${h.outputs.length} output(s) but ${e.lvalues.length} were requested`,e.span);if(h.outputs.length===0&&e.lvalues.length>0)throw new W(`function '${t}' has no outputs and cannot be assigned`,e.span);const p=e.lvalues.length,d=vl.call(this,h,c,s,m,void 0,p,e.span);if(d.outputTypes.length===1){const M={kind:"Call",cName:d.cName,name:t,args:u,ty:d.outputTypes[0]??{kind:"Unknown"},span:e.span},$=e.lvalues[0];if($===void 0||$.type==="Ignore"){const q={kind:"ExprStmt",expr:M,span:e.span};return l.length===0?q:[...l,q]}if($.type==="Var"){const q=this.recordAssignment($.name,M,e.span);return l.length===0?q:[...l,q]}const N=q0.call(this,[$],[d.outputTypes[0]??{kind:"Unknown"}],e.span),E=N.effectiveLvalues[0],R=this.recordAssignment(E.name,M,e.span),D=z0.call(this,N.postStores);return[...l.length===0?[R]:[...l,R],...D]}if(d.outputTypes.length===0){const $={kind:"ExprStmt",expr:{kind:"Call",cName:d.cName,name:t,args:u,ty:Fi,span:e.span},span:e.span};return l.length===0?$:[...l,$]}const g=d.outputTypes.map(M=>M??{kind:"Unknown"}),w=q0.call(this,e.lvalues,g,e.span),_=V0.call(this,t,g,w.effectiveLvalues,M=>`output '${h.outputs[M]}'`,e.span),y={kind:"MultiAssignCall",cName:d.cName,name:t,args:u,outputs:_,span:e.span},b=z0.call(this,w.postStores);return[...l.length===0?[y]:[...l,y],...b]}function q0(e,t,n){const r=[],s=[];for(let o=0;o<e.length;o++){const i=e[o];if(i.type==="Var"||i.type==="Ignore"){r.push(i);continue}const a=this.freshTempName(),c=t[o]??{kind:"Unknown"};this.env.set(a,{cName:a,ty:c}),r.push({type:"Var",name:a});const l={type:"Ident",name:a,span:n};s.push({type:"AssignLValue",lvalue:i,expr:l,suppressed:!0,span:n})}return{effectiveLvalues:r,postStores:s}}function z0(e){const t=[];for(const n of e){if(n.type!=="AssignLValue")continue;const r=this.lowerAssignLValue(n);Array.isArray(r)?t.push(...r):t.push(r)}return t}function V0(e,t,n,r,s){const o=[];for(let i=0;i<t.length;i++){const a=t[i];if(!fR(a))throw new W(`multi-output call '${e}': ${r(i)} has type ${ze(a)}; this type isn't supported in a multi-output slot`,s);const c=n[i];if(c===void 0||c.type!=="Var"){o.push({ty:a,binding:null});continue}const l={kind:"Var",name:c.name,cName:"<placeholder>",ty:a,span:s},u=this.recordAssignment(c.name,l,s);o.push({ty:a,binding:{name:c.name,cName:u.cName}})}return o}function vB(e,t,n,r,s,o){const i=o.lvalues.length,a=Yo(o.span,()=>t.transfer(r,i));if(a.length!==i)throw new W(`internal: builtin '${e}' transfer returned ${a.length} type(s) for nargout=${i}`,o.span);const c=q0.call(this,o.lvalues,a,o.span),l=V0.call(this,e,a,c.effectiveLvalues,m=>`output slot ${m+1}`,o.span),u={kind:"MultiAssignCall",cName:e,name:e,isBuiltin:!0,args:n,outputs:l,span:o.span},f=z0.call(this,c.postStores);return[...s.length===0?[u]:[...s,u],...f]}function MB(e,t){if(e.length!==1)return e.slice();const n=e[0];if(n.type!=="IndexCell"||n.indices.length!==1)return e.slice();const r=n.indices[0];if(r.type!=="Range")return e.slice();const s=this.lowerExpr(r.start).ty,o=this.lowerExpr(r.end).ty,i=r.step!==null?this.lowerExpr(r.step).ty:null,a=s.kind==="Numeric"&&typeof s.exact=="number"?s.exact:null,c=o.kind==="Numeric"&&typeof o.exact=="number"?o.exact:null,l=i===null?1:i.kind==="Numeric"&&typeof i.exact=="number"?i.exact:null;if(a===null||c===null||l===null)throw new W("multi-assign LHS '[<cell>{<range>}]': the range bounds must be statically known at compile time (got non-exact bounds)",t);if(!Number.isInteger(a)||!Number.isInteger(c)||!Number.isInteger(l)||l===0)throw new W(`multi-assign LHS '[<cell>{<range>}]': range bounds must be non-zero integers (got ${a}:${l}:${c})`,t);const u=[];if(l>0)for(let h=a;h<=c;h+=l)u.push(h);else for(let h=a;h>=c;h+=l)u.push(h);if(u.length===0)throw new W("multi-assign LHS '[<cell>{<range>}]': empty range (no slots to assign)",t);return u.map(h=>({type:"IndexCell",base:n.base,indices:[{type:"Number",value:String(h),span:t}]}))}function $B(e){const t=Cf(e.base);if(t&&!this.env.has(t.split(".")[0])){const p=`${t}.${e.name}`;if(this.workspace.isClass(p)){const _=this.workspace.requireClass(p);if(_===void 0)throw new W(`internal: class '${p}' missing from workspace registry`,e.span);return Tm.call(this,_,e.args,e.span)}if(this.workspace.isClass(t))return NB.call(this,t,e,e.span);const d=e.args.map(_=>this.lowerExpr(_));for(const _ of d)this.requireValueType(_,`argument to '${p}'`);const g=d.map(_=>_.ty),w=this.workspace.resolve(p,g,this.callSite(),e.span);if(w?.kind==="userFunction")return So.call(this,w.ast,d,p,e.span,{specSource:p,definingFile:w.file});if(w?.kind==="classConstructor"){const _=this.classReg(w.className);if(_===void 0)throw new W(`internal: class '${w.className}' missing from workspace registry`,e.span);return Tm.call(this,_,e.args,e.span)}throw new W(`unknown function '${p}'`,e.span)}const n=this.lowerExpr(e.base);if(this.requireValueType(n,`method call '.${e.name}'`),!al(n.ty))throw new W(`method call '.${e.name}' on a value of type ${ze(n.ty)} is not supported (v1: classes only)`,e.span);const r=this.classReg(n.ty.className),o=n.ty.properties.some(p=>p.name===e.name),i=r?.dependentProperties.has(e.name)??!1,a=r?r.methods.has(e.name)||r.staticMethods.has(e.name):!1;if(o&&!a)return SB.call(this,n,e.name,e.args,e.span);if(i&&r!==void 0)return CB.call(this,n,r,e.name,e.args,e.span);const c=e.args.map(p=>this.lowerExpr(p));for(const p of c)this.requireValueType(p,`argument to method '${e.name}'`);const l=[n.ty,...c.map(p=>p.ty)],u=this.workspace.resolve(e.name,l,{...this.callSite(),targetClassName:n.ty.className},e.span);if(u?.kind!=="classMethod")throw new le(`class '${n.ty.className}' has no method '${e.name}'`,e.span);const f=this.classReg(u.className);if(f===void 0)throw new W(`internal: class '${u.className}' missing from workspace registry`,e.span);const h=u.stripInstance?f.staticMethods.get(u.methodName):f.methods.get(u.methodName);if(h===void 0)throw new le(`class '${u.className}' has no ${u.stripInstance?"static ":""}method '${u.methodName}'`,e.span);const m=u.stripInstance?c:[n,...c];return So.call(this,h,m,`${u.className}.${u.methodName}`,e.span,{specSource:Xa(u.className,u.methodName),definingFile:h.span.file??f.file})}function CB(e,t,n,r,s){const o=t.getters.get(n);if(o===void 0)throw new W(`internal: dependent property '${t.className}.${n}' has no getter`,s);const i=So.call(this,o,[e],`${t.className}.get.${n}`,s,{specSource:Xa(t.className,`get.${n}`),definingFile:o.span.file??t.file}),a=this.freshTempName();return this.env.set(a,{cName:a,ty:i.ty}),this.pendingExprHoists.push({kind:"Assign",name:a,cName:a,ty:i.ty,expr:i,span:s}),r.some(Lm)?Dm.call(this,a,r,s):T0.call(this,a,r,s)}function SB(e,t,n,r){const s=cl(e.ty,t);if(s===void 0)throw new le(`no field '${t}' on type ${ze(e.ty)}`,r);const o={kind:"MemberLoad",base:e,field:t,ty:s,span:r},i=this.freshTempName();return this.env.set(i,{cName:i,ty:s}),this.pendingExprHoists.push({kind:"Assign",name:i,cName:i,ty:s,expr:o,span:r}),n.some(Lm)?Dm.call(this,i,n,r):T0.call(this,i,n,r)}function NB(e,t,n){const r=t.args.map(c=>this.lowerExpr(c));for(const c of r)this.requireValueType(c,`argument to static method '${t.name}'`);const s=r.map(c=>c.ty),o=this.workspace.resolve(t.name,s,{...this.callSite(),targetClassName:e},n);if(o?.kind!=="classMethod")throw new le(`class '${e}' has no static method '${t.name}'`,n);const i=this.classReg(o.className);if(i===void 0)throw new W(`internal: class '${o.className}' missing from workspace registry`,n);const a=i.staticMethods.get(o.methodName);if(a===void 0)throw i.methods.has(o.methodName)?new le(`'${o.className}.${o.methodName}' is an instance method; call it on an instance (e.g. 'obj.${o.methodName}(...)')`,n):new le(`class '${o.className}' has no static method '${o.methodName}'`,n);if(a.outputs.length>=2)throw new W(`static class method '${o.className}.${o.methodName}' has ${a.outputs.length} outputs; multi-output methods are not supported yet`,n);return So.call(this,a,r,`${o.className}.${o.methodName}`,n,{specSource:Xa(o.className,o.methodName),definingFile:a.span.file??i.file})}function nv(e){if(!Me(e))return null;let t=1;for(const n of e.dims){if(n.kind!=="exact")return null;t*=n.value}return t}function rv(e,t,n){const r=Yk.call(this,e,n,"sliceWrite"),{fieldPath:s,leafTy:o,displayName:i}=r,a=e.indices.length===1,c=[],l=[];for(let g=0;g<e.indices.length;g++){const w=a?"linear":g,_=Qk.call(this,r.baseCName,r.baseTy,w,e.indices[g]);_.kind==="LogicalMask"||_.kind==="IndexVec"?l.push({..._,expr:this.anfRequireScalarOrVar(_.expr,c)}):l.push(_)}if(a&&l[0].kind==="LogicalMask"){const g=nv(r.baseTy),w=nv(l[0].expr.ty);if(g!==null&&w!==null&&w>g)throw new W("logical-mask store with a statically-longer mask may grow the base; deferring to the interpreter",l[0].span)}if(!a){for(const g of l)if(g.kind==="LogicalMask")throw new W("per-axis logical-mask writes are not yet supported; only linear-form 'a(mask) = rhs' is handled",g.span)}if(!a&&r.baseTy.kind==="Numeric")for(let g=0;g<l.length;g++){const w=l[g];if(w.kind!=="Scalar")continue;const _=r.baseTy.dims[g],y=w.expr.ty,b=_!==void 0&&_.kind==="exact",k=y.kind==="Numeric"&&typeof y.exact=="number";if(!(b&&k&&Math.round(y.exact)>=1&&Math.round(y.exact)<=_.value))throw new W(`indexed write to '${i}' at axis ${g+1}: cannot statically prove the index stays within the tensor's bounds; would auto-grow / OOB in MATLAB, but auto-grow is not modeled in the JIT`,w.span)}const u=this.lowerExpr(t);if(!Me(u.ty))throw new le(`right-hand side of an indexed assignment must be numeric (got ${ze(u.ty)})`,t.span);if(u.ty.elem!=="double")throw new W(`right-hand side of a range/colon indexed write must be a double (got ${ze(u.ty)})`,t.span);if(!r.baseTy.isComplex&&u.ty.isComplex)throw new le(`cannot store a complex RHS into a real-typed tensor '${i}' (would silently drop the imaginary part). Promote the base to complex first (e.g. via 'x = x + 0i' before the indexed write).`,t.span);const f=[];let h;if(De(u.ty))h=u;else if(qe(u.ty))h=this.anfRequireScalarOrVar(u,f);else throw new le(`right-hand side of a range/colon indexed write must be a scalar or a tensor (got ${ze(u.ty)})`,t.span);const p={kind:"IndexSliceStore",base:r.base,index:l,rhs:h,span:n,...s!==void 0?{fieldPath:s,leafTy:o}:{}},d=[...c,...f];return d.length===0?p:[...d,p]}function AB(e,t,n){const{base:r,baseTy:s,baseCName:o,fieldPath:i,leafTy:a,displayName:c}=Yk.call(this,e,n,"write");for(const m of e.indices)if(m.type==="Range"||m.type==="Colon")throw new W("internal: lowerIndexStore received a range/colon slot; should have been routed to lowerIndexSliceStore",m.span);const l=[],u=e.indices.length;for(let m=0;m<u;m++){const p=u===1?"linear":m;this.endStack.push({baseCName:o,baseTy:s,axis:p});let d;try{d=this.lowerExpr(e.indices[m])}finally{this.endStack.pop()}if(!Kn(d.ty)){if(Me(d.ty)&&!d.ty.isComplex&&qe(d.ty)&&d.ty.elem==="logical")return rv.call(this,e,t,n);throw new le(`index ${m+1} of '${c}' must be a real scalar (got ${ze(d.ty)})`,e.indices[m].span)}if(Me(d.ty)&&!d.ty.isComplex&&d.ty.elem==="logical")throw new W(`scalar logical index of '${c}' (a 1-element logical mask) is not JIT-compiled`,e.indices[m].span);l.push(d)}if(Me(s)&&s.shape!==void 0)if(u===1){const m=sv(l[0].ty),p=Dt(s.shape);if(m!==void 0&&m>p)throw new W(`indexed assignment to '${c}' grows the array (index ${m} exceeds the ${p}-element static shape); array growth is not supported in the JIT`,n)}else for(let m=0;m<u;m++){const p=sv(l[m].ty),d=m<s.shape.length?s.shape[m]:1;if(p!==void 0&&p>d)throw new W(`indexed assignment to '${c}' grows axis ${m+1} (index ${p} exceeds static dim ${d}); array growth is not supported in the JIT`,n)}const f=this.lowerExpr(t);if(s.isComplex){if(!Me(f.ty)||!De(f.ty))throw new le(`right-hand side of an indexed assignment must be a numeric scalar (got ${ze(f.ty)})`,t.span)}else if(!Kn(f.ty))throw Me(f.ty)&&f.ty.isComplex&&De(f.ty)?new le(`cannot store a complex value into a real-typed tensor '${c}' (would silently drop the imaginary part). Promote the base to complex first (e.g. via 'x = x + 0i' before the indexed write).`,t.span):new le(`right-hand side of an indexed assignment must be a numeric scalar (got ${ze(f.ty)})`,t.span);return{kind:"IndexStore",base:r,indices:l,rhs:f,span:n,...i!==void 0?{fieldPath:i,leafTy:a}:{}}}function sv(e){return Me(e)&&typeof e.exact=="number"?e.exact:void 0}let EB=e=>console.error(e);function Pm(e){switch(e.kind){case"NumLit":case"ImagLit":case"StringLit":case"Var":return!0;case"Binary":return Pm(e.left)&&Pm(e.right);case"Unary":return Pm(e.operand);default:return!1}}class IB{constructor(t){this.workspace=t,this.currentFile=t.mainFile}env=new Map;specializations=new Map;endStack=[];tempCounter=0;splitCounter=0;controlDepth=0;pendingExprHoists=[];anonCounter=0;currentFile;callFrameStack=[];recursiveSpecsConsumed=new Set;specCountPerSource=new Map;callSite(){return{file:this.currentFile}}envLookup(t){return this.env.get(t)}withControlDepth(t){this.controlDepth++;try{return t()}finally{this.controlDepth--}}classReg(t){return this.workspace.requireClass(t)}lowerProgram(t){return this.workspace.finalize(),{topLevelStmts:this.lowerStmts(t.body),functions:this.specializations}}lowerStmts(t){const n=[];for(const r of t){const s=this.lowerStmt(r);if(s===null)continue;Array.isArray(s)?n.push(...s):n.push(s);const o=n[n.length-1];if(o!==void 0&&(o.kind==="ReturnFromFunction"||o.kind==="Break"||o.kind==="Continue"))break}return n}lowerStmt(t){const n=this.pendingExprHoists.length,r=this.lowerStmtInner(t);if(this.pendingExprHoists.length===n)return r;const s=this.pendingExprHoists.splice(n);return r===null?s:Array.isArray(r)?[...s,...r]:[...s,r]}lowerStmtInner(t){switch(t.type){case"Function":return null;case"ClassDef":return null;case"ExprStmt":return this.lowerExprStmt(t);case"Assign":return this.lowerAssign(t);case"AssignLValue":return this.lowerAssignLValue(t);case"MultiAssign":return B0.call(this,t);case"If":return this.lowerIf(t);case"While":return this.lowerWhile(t);case"For":return this.lowerFor(t);case"Return":return{kind:"ReturnFromFunction",span:t.span};case"Break":return{kind:"Break",span:t.span};case"Continue":return{kind:"Continue",span:t.span};case"Directive":return this.lowerDirective(t);default:throw new W(`statement type '${t.type}' not supported`,t.span)}}lowerDirective(t){if(t.directive==="opaque"){for(const n of t.args){const r=this.env.get(n);if(r===void 0)throw new W(`'%!numbl:opaque' references unknown variable '${n}'`,t.span);const s=bo(r.ty);s!==r.ty&&this.env.set(n,{cName:r.cName,ty:s})}return null}if(t.directive==="showtype")return{kind:"TypeComment",entries:this.snapshotTypeEntries(t.args,t.span,"showtype"),span:t.span};if(t.directive==="printtype"){const n=this.snapshotTypeEntries(t.args,t.span,"printtype"),r=this.workspace.sourceOf(t.span.file)??"",{line:s,column:o}=wR(r,t.span.start);for(const i of n)EB(`${t.span.file}:${s}:${o}: type ${i.name} :: ${ze(i.ty)}`);return null}return null}snapshotTypeEntries(t,n,r){const s=[];for(const o of t){const i=this.env.get(o);if(i===void 0)throw new W(`'%!numbl:${r}' references unknown variable '${o}'`,n);s.push({name:o,cName:i.cName,ty:i.ty})}return s}lowerExprStmt(t){if(this.env.get("toc")===void 0&&!this.workspace.isClass("toc")){if(t.expr.type==="Ident"&&t.expr.name==="toc")return{kind:"ExprStmt",expr:{kind:"Call",cName:"mtoc2_toc_print",name:"toc_print",args:[],ty:Fi,span:t.expr.span},span:t.span};if(t.expr.type==="FuncCall"&&t.expr.name==="toc"){if(t.expr.args.length===0)return{kind:"ExprStmt",expr:{kind:"Call",cName:"mtoc2_toc_print",name:"toc_print",args:[],ty:Fi,span:t.expr.span},span:t.span};if(t.expr.args.length===1){const o=this.lowerExpr(t.expr.args[0]);if(!Kn(o.ty))throw new le(`'toc' tic-handle argument must be a scalar real numeric (the value returned by 'tic'); got ${o.ty.kind}`,t.expr.args[0].span);return{kind:"ExprStmt",expr:{kind:"Call",cName:"mtoc2_toc_handle_print",name:"toc_handle_print",args:[o],ty:Fi,span:t.expr.span},span:t.span}}}}if(t.expr.type==="FuncCall"){const o=t.expr;if(this.env.get(o.name)===void 0&&!this.workspace.isClass(o.name)){const a=this.workspace.resolve(o.name,[],this.callSite(),o.span);if(a?.kind==="userFunction"&&a.ast.outputs.length>=2)return B0.call(this,{type:"MultiAssign",lvalues:[],expr:o,suppressed:t.suppressed,span:t.span})}}if(t.expr.type==="MethodCall"){const o=t.expr,i=Cf(o.base);if(i&&!this.env.has(i.split(".")[0])){const a=`${i}.${o.name}`;if(!this.workspace.isClass(a)){const c=this.workspace.resolve(a,[],this.callSite(),o.span);if(c?.kind==="userFunction"&&c.ast.outputs.length>=2)return B0.call(this,{type:"MultiAssign",lvalues:[],expr:o,suppressed:t.suppressed,span:t.span})}}}const n=this.lowerExpr(t.expr);if(n.kind==="NumLit"||n.kind==="ImagLit")return null;if(zd(n.ty)){const o=[],i=this.anfChildren(n,o);return o.length>0?[...o,{kind:"ExprStmt",expr:i,span:t.span}]:{kind:"ExprStmt",expr:n,span:t.span}}const r=[],s=this.anfRequireScalarOrVar(n,r);return r.length>0?[...r,{kind:"ExprStmt",expr:s,span:t.span}]:{kind:"ExprStmt",expr:n,span:t.span}}requireValueType(t,n){if(zd(t.ty))throw new W(`${n}: cannot use the result of a zero-output function as a value`,t.span)}anfChildren(t,n){switch(t.kind){case"NumLit":case"ImagLit":case"StringLit":case"Var":case"HandleLit":case"HandleCaptureLoad":case"EndRef":return t;case"TensorBuild":return{...t,elements:t.elements.map(r=>this.anfRequireScalarOrVar(r,n))};case"TensorConcat":return{...t,cells:t.cells.map(r=>r.map(s=>this.anfRequireScalarOrVar(s,n)))};case"CellLit":return{...t,elements:t.elements.map(r=>hr(r.ty)?this.anfChildren(r,n):this.anfRequireScalarOrVar(r,n))};case"CellEmpty":return{...t,dims:t.dims.map(r=>this.anfRequireScalarOrVar(r,n))};case"CellIndexLoad":return{...t,base:this.anfRequireScalarOrVar(t.base,n),indices:t.indices.map(r=>this.anfRequireScalarOrVar(r,n))};case"Binary":return{...t,left:this.anfRequireScalarOrVar(t.left,n),right:this.anfRequireScalarOrVar(t.right,n)};case"Unary":return{...t,operand:this.anfRequireScalarOrVar(t.operand,n)};case"Call":return{...t,args:t.args.map(r=>this.anfRequireScalarOrVar(r,n))};case"StructLit":return{...t,fields:t.fields.map(r=>({name:r.name,value:hr(r.value.ty)?this.anfChildren(r.value,n):this.anfRequireScalarOrVar(r.value,n)}))};case"MemberLoad":return{...t,base:this.anfRequireScalarOrVar(t.base,n)};case"IndexLoad":return{...t,base:this.anfRequireScalarOrVar(t.base,n),indices:t.indices.map(r=>this.anfRequireScalarOrVar(r,n))};case"IndexSlice":return{...t,base:this.anfRequireScalarOrVar(t.base,n),index:t.index.map(r=>r.kind==="Range"?{...r,start:this.anfRequireScalarOrVar(r.start,n),step:this.anfRequireScalarOrVar(r.step,n),end:this.anfRequireScalarOrVar(r.end,n)}:r.kind==="Scalar"?{...r,expr:this.anfRequireScalarOrVar(r.expr,n)}:r.kind==="IndexVec"?{...r,expr:this.anfRequireScalarOrVar(r.expr,n)}:r.kind==="LogicalMask"?{...r,expr:this.anfRequireScalarOrVar(r.expr,n)}:r)};case"MakeRange":return{...t,start:this.anfRequireScalarOrVar(t.start,n),step:this.anfRequireScalarOrVar(t.step,n),end:this.anfRequireScalarOrVar(t.end,n)}}}anfRequireScalarOrVar(t,n){const r=this.anfChildren(t,n);return hr(r.ty)&&r.kind!=="Var"?this.hoistToTemp(r,n):r}hoistToTemp(t,n){const r=this.freshTempName();return this.env.set(r,{cName:r,ty:t.ty}),n.push({kind:"Assign",name:r,cName:r,ty:t.ty,expr:t,span:t.span}),{kind:"Var",name:r,cName:r,ty:t.ty,span:t.span}}freshTempName(){return this.tempCounter+=1,`_mtoc2_t${this.tempCounter}`}lowerAssign(t){const n=this.lowerExpr(t.expr);this.requireValueType(n,`assigning to '${t.name}'`);const r=[],i=hr(n.ty)&&n.kind!=="Var"?this.anfChildren(n,r):this.anfRequireScalarOrVar(n,r),a=this.recordAssignment(t.name,i,t.span);return r.length===0?a:[...r,a]}lowerAssignLValue(t){const n=t.lvalue;if(n.type==="IndexCell")return uB.call(this,n,t.expr,t.span);if(n.type==="Index"){if(t.expr.type==="Tensor"&&t.expr.rows.length===0)throw new W("indexed deletion `x(idx) = []` is not JIT-compiled; resizing the base requires the interpreter",t.span);const w=n.indices.some(Lm)?rv.call(this,n,t.expr,t.span):AB.call(this,n,t.expr,t.span);if(n.base.type==="Ident"){if(!RB(this.env,n.base.name,w)){const y=LB(w);pR(this.env,n.base.name,y)}}else if(n.base.type==="Member"){const _=Array.isArray(w)?w[w.length-1]:w;_!==void 0&&(_.kind==="IndexStore"||_.kind==="IndexSliceStore")&&_.fieldPath!==void 0&&_.leafTy!==void 0&&dR(this.env,_.base.name,_.fieldPath,_.leafTy)}return w}if(n.type!=="Member")throw new W(`assignment lvalue '${n.type}' is not supported`,t.span);const r=yR(n);if(r===null)throw new W("assignment lvalue must be rooted at a named variable",t.span);const{rootName:s,fields:o}=r,i=this.env.get(s);if(i===void 0)throw new W(`assignment to '${s}.${o.join(".")}' but '${s}' is not yet defined (struct variables must first be introduced via 'struct(...)' or a class constructor call)`,t.span);if(o.length===1&&i.ty.kind==="Class"){const w=this.classReg(i.ty.className),_=o[0],y=w?.setters.get(_);if(y!==void 0&&w!==void 0){const b=this.lowerExpr(t.expr);this.requireValueType(b,`assignment to '${s}.${_}'`);const k={kind:"Var",name:s,cName:i.cName,ty:i.ty,span:t.span},M=So.call(this,y,[k,b],`${i.ty.className}.set.${_}`,t.span,{specSource:Xa(i.ty.className,`set.${_}`),definingFile:y.span.file??w.file}),$=[],R=hr(M.ty)&&M.kind!=="Var"?this.anfChildren(M,$):this.anfRequireScalarOrVar(M,$),D=this.recordAssignment(s,R,t.span);return $.length===0?D:[...$,D]}if(w?.dependentProperties.has(_))throw new W(`dependent property '${i.ty.className}.${_}' has no setter; cannot assign`,t.span)}let a=i.ty;for(let w=0;w<o.length;w++){const _=o[w],y=cl(a,_);if(y===void 0)throw new le(`'${s}.${o.slice(0,w+1).join(".")}': no such field on type ${ze(a)}`,t.span);a=y}const c=a,l=this.lowerExpr(t.expr);if(this.requireValueType(l,`assignment to '${s}.${o.join(".")}'`),!ll(l.ty,c))throw new le(`assignment to '${s}.${o.join(".")}': field has C type ${ze(c)} but rhs has type ${ze(l.ty)}`,t.span);const u=[],m=hr(c)&&l.kind!=="Var"?this.anfChildren(l,u):this.anfRequireScalarOrVar(l,u),d={kind:"MemberStore",base:{kind:"Var",name:s,cName:i.cName,ty:i.ty,span:t.span},fieldPath:o,leafTy:l.ty,rhs:m,span:t.span},g=$f(i.ty,o,l.ty);return this.env.set(s,{cName:i.cName,ty:g}),u.length===0?d:[...u,d]}recordAssignment(t,n,r){const s=this.env.get(t);if(s&&!ll(s.ty,n.ty)){if(this.controlDepth>0)throw qe(s.ty)!==qe(n.ty)?new W(`cannot reassign '${t}' across scalar/tensor boundary inside control flow`,r):new W(`cannot reassign '${t}': new value's C storage (${ze(n.ty)}) is incompatible with the existing binding (${ze(s.ty)}) inside control flow`,r);const i=`_mtoc2_${s.cName}__v${++this.splitCounter}`;return this.env.set(t,{cName:i,ty:n.ty}),{kind:"Assign",name:t,cName:i,ty:n.ty,expr:n,span:r}}const o=s?.cName??Hi(t);return this.env.set(t,{cName:o,ty:n.ty}),{kind:"Assign",name:t,cName:o,ty:n.ty,expr:n,span:r}}lowerIf(t){const n=this.lowerExpr(t.cond);this.requireScalarCondType(n.ty,"if condition",t.span);const r=jB(n),s=Bm(n)?[]:[{kind:"ExprStmt",expr:n,span:t.cond.span}];if(r===!0)return[...s,...this.lowerStmts(t.thenBody)];if(r===!1){if(t.elseifBlocks.length===0)return[...s,...t.elseBody?this.lowerStmts(t.elseBody):[]];const[a,...c]=t.elseifBlocks,l={type:"If",cond:a.cond,thenBody:a.body,elseifBlocks:c,elseBody:t.elseBody,span:a.cond.span},u=this.lowerIf(l);return[...s,...Array.isArray(u)?u:[u]]}const o=new Map(this.env),i=[];return this.withControlDepth(()=>{this.env=new Map(o);const a=this.lowerStmts(t.thenBody);i.push(this.env),this.env=new Map(o);const c=this.lowerElseChain(t.elseifBlocks,t.elseBody,o,i);return this.env=this.mergeBranchEnvs(i,!0),{kind:"If",cond:n,thenBody:a,elseBody:c,span:t.span}})}lowerElseChain(t,n,r,s){if(t.length===0){if(n===null)return s.push(new Map(r)),[];this.env=new Map(r);const f=this.lowerStmts(n);return s.push(this.env),f}const[o,...i]=t;this.env=new Map(r);const a=this.lowerExpr(o.cond);this.requireScalarCondType(a.ty,"elseif condition",o.cond.span);const c=new Map(this.env);this.env=c;const l=this.lowerStmts(o.body);s.push(this.env),this.env=new Map(r);const u=this.lowerElseChain(i,n,r,s);return[{kind:"If",cond:a,thenBody:l,elseBody:u,span:o.cond.span}]}lowerWhile(t){const n=new Map(this.env);Gx(this.env,U0(t.body));const r=this.lowerExpr(t.cond);this.requireScalarCondType(r.ty,"while condition",t.span);const s=new Map(this.env),o=this.withControlDepth(()=>this.lowerStmts(t.body));return iv(s,this.env,t.body,t.span),this.env=this.mergeBranchEnvs([n,this.env]),{kind:"While",cond:r,body:o,span:t.span}}lowerFor(t){if(t.expr.type!=="Range")throw new W("for-loop iterables other than ranges are not yet supported",t.span);const n=this.lowerExpr(t.expr.start),r=this.lowerExpr(t.expr.end);this.requireScalarReal(n.ty,"for-loop start",t.expr.start.span),this.requireScalarReal(r.ty,"for-loop end",t.expr.end.span);let s=1;if(t.expr.step){const h=this.lowerExpr(t.expr.step);this.requireScalarReal(h.ty,"for-loop step",t.expr.step.span);const m=Me(h.ty)&&typeof h.ty.exact=="number"?h.ty.exact:void 0;if(m===void 0)throw new W("for-loop step must be a compile-time-known numeric literal",t.expr.step.span);if(m===0)throw new W("for-loop step must be non-zero",t.expr.step.span);s=m}const o=new Map(this.env),i=Me(n.ty)?n.ty.sign:"unknown",a=Me(r.ty)?r.ty.sign:"unknown",c=kf(i,a),l=Hi(t.varName);this.env.set(t.varName,{cName:l,ty:Be(c)}),Gx(this.env,U0(t.body));const u=new Map(this.env),f=this.withControlDepth(()=>this.lowerStmts(t.body));return iv(u,this.env,t.body,t.span),this.env=this.mergeBranchEnvs([o,this.env]),{kind:"For",varName:t.varName,cVar:l,start:n,step:s,end:r,body:f,span:t.span}}lowerExpr(t){switch(t.type){case"Number":{const n=Number(t.value);if(!Number.isFinite(n))throw new W(`non-finite numeric literal '${t.value}'`,t.span);return{kind:"NumLit",value:n,ty:Be(ft(n),n),span:t.span}}case"ImagUnit":return{kind:"ImagLit",value:1,ty:_t({re:0,im:1}),span:t.span};case"Ident":return this.lowerIdent(t);case"Binary":return this.lowerBinary(t);case"Unary":return this.lowerUnary(t);case"FuncCall":return P0.call(this,t);case"Tensor":return iB.call(this,t);case"Cell":return aB.call(this,t);case"IndexCell":return cB.call(this,t);case"FuncHandle":return fB.call(this,t);case"AnonFunc":return mB.call(this,t);case"Member":return this.lowerMember(t);case"MethodCall":return $B.call(this,t);case"EndKeyword":return this.lowerEndKeyword(t);case"Range":return this.lowerRangeAsValue(t);case"Char":{const n=t.value,r=n.slice(1,n.length-1).replaceAll("''","'");return{kind:"StringLit",value:r,ty:{kind:"Char",exact:r},span:t.span}}case"String":{const n=t.value,r=n.slice(1,n.length-1).replaceAll('""','"');return{kind:"StringLit",value:r,ty:{kind:"String",exact:r},span:t.span}}case"Colon":throw new W("bare ':' is only valid inside an index expression",t.span);default:throw new W(`expression type '${t.type}' not supported`,t.span)}}lowerEndKeyword(t){if(this.endStack.length===0)throw new W("'end' is only valid inside an index expression",t.span);const n=this.endStack[this.endStack.length-1];if(n.axis==="linear"){if(n.baseTy.shape!==void 0){const r=Dt(n.baseTy.shape);return{kind:"NumLit",value:r,ty:Be(r>0?"positive":"nonneg",r),span:t.span}}}else{const r=n.axis;if(n.baseTy.shape!==void 0&&r<n.baseTy.shape.length){const s=n.baseTy.shape[r];return{kind:"NumLit",value:s,ty:Be(s>0?"positive":"nonneg",s),span:t.span}}}return{kind:"EndRef",baseCName:n.baseCName,baseTy:n.baseTy,axis:n.axis,ty:Be("nonneg"),span:t.span}}lowerRangeAsValue(t){const n=this.lowerExpr(t.start),r=this.lowerExpr(t.end);let s;t.step===null?s={kind:"NumLit",value:1,ty:Be("positive",1),span:t.span}:s=this.lowerExpr(t.step),this.requireScalarReal(n.ty,"range start",t.start.span),this.requireScalarReal(r.ty,"range end",t.end.span),this.requireScalarReal(s.ty,"range step",t.step?.span??t.span);let o;const i=Me(n.ty)&&typeof n.ty.exact=="number"?n.ty.exact:void 0,a=Me(s.ty)&&typeof s.ty.exact=="number"?s.ty.exact:void 0,c=Me(r.ty)&&typeof r.ty.exact=="number"?r.ty.exact:void 0;if(i!==void 0&&a!==void 0&&c!==void 0&&a!==0&&Number.isFinite(i)&&Number.isFinite(a)&&Number.isFinite(c)){const l=ob(i,a,c);if(l===1)return n;o=et([1,l])}else o={kind:"Numeric",elem:"double",isComplex:!1,dims:[{kind:"exact",value:1},{kind:"unknown"}],sign:"unknown"};return{kind:"MakeRange",start:n,step:s,end:r,ty:o,span:t.span}}lowerMember(t){const n=this.lowerExpr(t.base);if(this.requireValueType(n,`field access '.${t.name}'`),n.ty.kind==="Class"){const s=this.classReg(n.ty.className),o=s?.getters.get(t.name);if(o!==void 0&&s!==void 0)return So.call(this,o,[n],`${n.ty.className}.get.${t.name}`,t.span,{specSource:Xa(n.ty.className,`get.${t.name}`),definingFile:o.span.file??s.file})}const r=cl(n.ty,t.name);if(r===void 0)throw new le(`no field '${t.name}' on type ${ze(n.ty)}`,t.span);return{kind:"MemberLoad",base:n,field:t.name,ty:r,span:t.span}}lowerIdent(t){const n=this.env.get(t.name);if(n!==void 0){if(n.maybeUnassigned)throw new W(`'${t.name}' may be used before it is assigned (assigned only on some branches)`,t.span);return{kind:"Var",name:t.name,cName:n.cName,ty:n.ty,span:t.span}}if((t.name==="nargout"||t.name==="nargin")&&this.callFrameStack.length>0){const s=this.callFrameStack[this.callFrameStack.length-1],o=t.name==="nargout"?s.nargout:s.nargin;return{kind:"NumLit",value:o,ty:Be(ft(o),o),span:t.span}}const r=is(t.name);if(r!==void 0){let s;try{s=r.transfer([],1)}catch{s=void 0}if(s!==void 0)return{kind:"Call",cName:t.name,name:t.name,args:[],ty:s[0],span:t.span}}throw new W(`undefined variable '${t.name}' (or unsupported reference)`,t.span)}lowerBinary(t){if(t.op===je.Mul&&t.left.type==="Number"&&t.right.type==="ImagUnit"){const a=Number(t.left.value);if(Number.isFinite(a))return{kind:"ImagLit",value:a,ty:_t({re:0,im:a}),span:t.span}}if(t.op===je.OrOr||t.op===je.AndAnd){const a=this.lowerExpr(t.left);this.requireValueType(a,"binary operator operand");let c;Me(a.ty)&&!a.ty.isComplex&&Kn(a.ty)&&typeof a.ty.exact=="number"&&(c=a.ty.exact);const l=t.op===je.OrOr;if(c!==void 0&&(l&&c!==0&&!Number.isNaN(c)||!l&&c===0)){const u={kind:"NumLit",value:l?1:0,ty:at(l),span:t.span};return Pm(a)?u:{kind:"Binary",builtin:l?"oror":"andand",op:t.op,left:a,right:u,ty:at(l),span:t.span}}}const n=this.lowerExpr(t.left);this.requireValueType(n,"binary operator operand");const r=this.lowerExpr(t.right);this.requireValueType(r,"binary operator operand");const s=rB(t.op,t.span),o=is(s);if(!o)throw new W(`builtin '${s}' not registered`,t.span);const i=Yo(t.span,()=>o.transfer([n.ty,r.ty],1))[0];return{kind:"Binary",builtin:s,op:t.op,left:n,right:r,ty:i,span:t.span}}lowerUnary(t){const n=this.lowerExpr(t.operand);if(this.requireValueType(n,"unary operator operand"),t.op===gn.Transpose&&Me(n.ty)&&n.ty.isComplex){const i=is("conj"),a=is("transpose");if(!i||!a)throw new W("internal: 'conj'/'transpose' must be registered for complex ctranspose",t.span);const c=Yo(t.span,()=>i.transfer([n.ty],1))[0],l={kind:"Call",cName:"conj",name:"conj",args:[n],ty:c,span:t.span},u=Yo(t.span,()=>a.transfer([c],1))[0];return{kind:"Call",cName:"transpose",name:"transpose",args:[l],ty:u,span:t.span}}const r=sB(t.op,t.span),s=is(r);if(!s)throw new W(`builtin '${r}' not registered`,t.span);const o=Yo(t.span,()=>s.transfer([n.ty],1))[0];return{kind:"Unary",builtin:r,op:t.op,operand:n,ty:o,span:t.span}}requireScalarReal(t,n,r,s){if(!Kn(t)){const o=s?` ${s}`:"";throw new W(`${n} must be a scalar real numeric${o}`,r)}}requireScalarCondType(t,n,r){if(!(Me(t)&&(t.elem==="double"||t.elem==="logical")&&t.dims.length===2&&t.dims[0].kind==="exact"&&t.dims[0].value===1&&t.dims[1].kind==="exact"&&t.dims[1].value===1))throw new W(`${n} must be a scalar numeric`,r)}mergeBranchEnvs(t,n=!1){const r=new Set;for(const o of t)for(const i of o.keys())r.add(i);const s=new Map;for(const o of r){const i=t.map(u=>u.get(o)).filter(u=>u!==void 0);if(i.length===0)continue;let a=i[0].ty;for(let u=1;u<i.length;u++)a=Li(a,i[u].ty);i.length<t.length&&(a=bo(a));const c=n&&i.length<t.length||i.some(u=>u.maybeUnassigned),l={cName:i[0].cName,ty:a};c&&(l.maybeUnassigned=!0),s.set(o,l)}return s}}const FB=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","main","_Bool","_Complex","_Imaginary","async","await","catch","class","debugger","delete","export","extends","false","finally","function","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","super","this","throw","true","try","typeof","var","with","yield","arguments","eval"]);function Hi(e){return FB.has(e)?`v_${e}`:e}function jB(e){if(!Me(e.ty))return null;const t=e.ty.exact;if(typeof t=="number")return Number.isFinite(t)?t!==0:null;const n=An(e.ty);return n!==void 0?!Number.isFinite(n.re)||!Number.isFinite(n.im)?null:n.re!==0||n.im!==0:null}function Bm(e){switch(e.kind){case"NumLit":case"ImagLit":case"Var":case"EndRef":case"HandleCaptureLoad":return!0;case"Unary":return Bm(e.operand);case"Binary":return Bm(e.left)&&Bm(e.right);default:return!1}}function ov(e){if(e.length>=2){const t=e[0],n=e[e.length-1];if(t==="'"&&n==="'"||t==='"'&&n==='"')return e.slice(1,-1)}return e}function RB(e,t,n){const r=Array.isArray(n)?n[n.length-1]:n;if(r.kind!=="IndexStore")return!1;const s=e.get(t);if(s===void 0||s.ty.kind!=="Numeric")return!1;const o=s.ty,i=o.shape,a=o.exact;if(i===void 0||!(a instanceof Float64Array)||!Me(r.rhs.ty)||typeof r.rhs.ty.exact!="number")return!1;const c=r.rhs.ty.exact,l=[];for(const m of r.indices){if(!Me(m.ty)||typeof m.ty.exact!="number")return!1;const p=m.ty.exact;if(!Number.isFinite(p)||!Number.isInteger(p)||p<1)return!1;l.push(p)}const u=ib(i,l);if(u===void 0)return!1;const f=new Float64Array(a);f[u]=c;const h=ol(f);return e.set(t,{cName:s.cName,ty:{...o,exact:f,sign:h}}),!0}function LB(e){const t=Array.isArray(e)?e[e.length-1]:e;return t.kind!=="IndexStore"&&t.kind!=="IndexSliceStore"?"unknown":Me(t.rhs.ty)?t.rhs.ty.sign:"unknown"}function iv(e,t,n,r){for(const s of U0(n)){const o=e.get(s),i=t.get(s);if(!(o===void 0||i===void 0)&&DB(o.ty,i.ty))throw new W(`loop body changes the shape of '${s}' across iterations (entry shape differs from end-of-iter shape); mtoc2 lowers the body once per spec and cannot specialize per-iteration growing tensors`,r)}}function DB(e,t){if(!Me(e)||!Me(t))return!1;if(e.dims.length!==t.dims.length)return!0;for(let s=0;s<e.dims.length;s++){const o=e.dims[s],i=t.dims[s];if(o.kind==="exact"&&i.kind==="exact"&&o.value!==i.value||o.kind==="exact"&&i.kind==="unknown")return!0}const n=e.shape,r=t.shape;if(n!==void 0&&r!==void 0){if(n.length!==r.length)return!0;for(let s=0;s<n.length;s++)if(n[s]!==r[s])return!0}else if(n!==void 0&&r===void 0)return!0;return!1}function U0(e){const t=new Set,n=s=>{if(s.type==="Var"){t.add(s.name);return}if(s.type==="Member"||s.type==="Index"){let o=s.base;for(;o!==null&&o.type==="Member";)o=o.base;o!==null&&o.type==="Ident"&&t.add(o.name)}},r=s=>{for(const o of s)switch(o.type){case"Assign":t.add(o.name);break;case"AssignLValue":n(o.lvalue);break;case"MultiAssign":for(const i of o.lvalues)n(i);break;case"If":r(o.thenBody);for(const i of o.elseifBlocks)r(i.body);o.elseBody&&r(o.elseBody);break;case"While":r(o.body);break;case"For":t.add(o.varName),r(o.body);break;case"Switch":for(const i of o.cases)r(i.body);o.otherwise&&r(o.otherwise);break;case"TryCatch":r(o.tryBody),r(o.catchBody);break}};return r(e),t}var TB={};const av=(()=>{const e=typeof globalThis<"u"&&TB,t=e?e.MTOC2_MAX_SPECS_PER_FUNCTION:void 0;if(!t)return 256;const n=Number.parseInt(t,10);return Number.isFinite(n)&&n>0?n:256})();function So(e,t,n,r,s={}){const o=t.map(l=>l.ty),i=e.outputs.length===0?0:1,a=vl.call(this,e,o,s.specSource,s.definingFile,void 0,i,r),c=e.outputs.length===0?Fi:a.outputTypes[0]??{kind:"Unknown"};return{kind:"Call",cName:a.cName,name:n,args:t,ty:c,span:r}}function vl(e,t,n,r,s,o,i){const a=i??e.span;for(const N of e.params)if(N==="~")throw new W(`function '${e.name}' has a '~' placeholder parameter — cannot specialize`,a);if(t.length>e.params.length)throw new le(`function '${e.name}' expects ${e.params.length} arg(s), got ${t.length}`,a);const c=n??e.name,l=r??e.span.file??this.currentFile,u=o??e.outputs.length,f=`${l}|${t.map(Di).join("|")}|nargout=${u}`,h=`${rb(c)}__${Ti(f)}`,m=this.specializations.get(h);if(m)return m.body.length===0&&this.recursiveSpecsConsumed.add(h),m;const p=`${c}|${l}`,d=this.specCountPerSource.get(p)??0;if(d>=av)throw new W(`function '${e.name}' has exceeded the per-function specialization cap (${av}). This usually means exact-value tracking is sharding a call site into one spec per distinct input; widen the inputs (e.g. via '%!numbl:opaque') or raise the cap via the MTOC2_MAX_SPECS_PER_FUNCTION env var.`,a);this.specCountPerSource.set(p,d+1);const g=e.outputs.slice(0,u),w=g.map((N,E)=>t[E]??Pr),_=e.params.slice(0,t.length),y={name:e.name,cName:h,params:_.slice(),cParams:_.map(Hi),paramTypes:t,outputs:g.slice(),cOutputs:g.map(Hi),outputTypes:w,body:[],span:e.span};this.specializations.set(h,y);const b=this.env,k=this.tempCounter,M=this.currentFile;this.currentFile=l,this.callFrameStack.push({nargin:t.length,nargout:u});const $=()=>{this.env=new Map,this.tempCounter=0;for(let D=0;D<t.length;D++){const I=e.params[D];this.env.set(I,{cName:Hi(I),ty:t[D]})}let N=[];s!==void 0&&(this.requireValueType(s.initExpr,`constructor init for '${s.name}'`),N=[this.recordAssignment(s.name,s.initExpr,e.span)]);const E=[...N,...this.lowerStmts(e.body)],R=g.map(D=>{const I=this.env.get(D);if(!I)throw new le(`function '${e.name}': output '${D}' was never assigned`,a);if(I.maybeUnassigned)throw new W(`function '${e.name}': output '${D}' is assigned only on some branches`,a);return I.ty});return{body:E,outputTypes:R}};try{let{body:N,outputTypes:E}=$(),R=w;if(this.recursiveSpecsConsumed.has(h)&&!cv(R,E)){y.outputTypes=E,R=E;const I=$();if(N=I.body,E=I.outputTypes,!cv(R,E))throw new le(`function '${e.name}': recursive output type did not stabilize after two lowering passes. First pass produced [${w.map(Di).join(", ")}], second pass produced [${E.map(Di).join(", ")}]. This usually means the output type genuinely depends on a runtime value the lowerer can't resolve, or that the function is mutually recursive in a shape mtoc2 can't yet handle. Try annotating the output via an early assignment, or avoid recursion for this call.`,a)}for(let I=0;I<g.length;I++){const q=g[I],Y=this.env.get(q);if(Y===void 0)continue;const U=Hi(q);if(Y.cName!==U)throw new W(`function '${e.name}': output '${q}' was reassigned with an incompatible C storage type partway through the body — the function output cannot be represented as a single C variable.`,a);if(E[I].kind==="Unknown")throw new W(`function '${e.name}': output '${q}' resolves to an unknown type at function exit — usually because the body unifies two storage-distinct values for it (e.g. a real and a complex tensor, or a scalar and a tensor). Cannot represent this in the C/JS ABI as a single output slot.`,a)}const D={...y,body:N,outputTypes:E};return this.specializations.set(h,D),D}catch(N){throw this.specializations.delete(h),N}finally{this.env=b,this.tempCounter=k,this.currentFile=M,this.callFrameStack.pop(),this.recursiveSpecsConsumed.delete(h)}}function cv(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(Di(e[n])!==Di(t[n]))return!1;return!0}function PB(e){throw new Error("C runtime snippets not registered; call setCSnippets at bootstrap (C-JIT is Node-only — see executors/jit/compileC.node.ts)")}function Pe(e,t=[]){const n=e.replace(/\.h$/,".js"),r=ID[n];let s=null;const o=()=>(s===null&&(s=PB()),s),i={get headers(){return o().headers},get code(){return o().code},deps:t,srcFilename:e};return r!==void 0&&(i.jsCode=r),i}const lv=new Map([["mtoc2_host_output",Pe("host_output.h")],["mtoc2_format_double",Pe("format_double.h")],["mtoc2_disp_double",Pe("disp_double.h",["mtoc2_format_double","mtoc2_host_output"])],["mtoc2_cscalar",Pe("cscalar.h")],["mtoc2_cdiv",Pe("cdiv.h")],["mtoc2_format_complex",Pe("format_complex.h",["mtoc2_format_double"])],["mtoc2_disp_complex",Pe("disp_complex.h",["mtoc2_format_complex","mtoc2_host_output"])],["mtoc2_string_t",Pe("string.h")],["mtoc2_string_empty",Pe("string_empty.h",["mtoc2_string_t"])],["mtoc2_string_free",Pe("string_free.h",["mtoc2_string_t"])],["mtoc2_string_assign",Pe("string_assign.h",["mtoc2_string_t","mtoc2_string_free"])],["mtoc2_string_copy",Pe("string_copy.h",["mtoc2_string_t"])],["mtoc2_string_from_literal",Pe("string_from_literal.h",["mtoc2_string_t"])],["mtoc2_char_tensor_t",Pe("char_tensor.h")],["mtoc2_char_tensor_empty",Pe("char_tensor_empty.h",["mtoc2_char_tensor_t"])],["mtoc2_char_tensor_free",Pe("char_tensor_free.h",["mtoc2_char_tensor_t"])],["mtoc2_char_tensor_assign",Pe("char_tensor_assign.h",["mtoc2_char_tensor_t","mtoc2_char_tensor_free"])],["mtoc2_char_tensor_copy",Pe("char_tensor_copy.h",["mtoc2_char_tensor_t"])],["mtoc2_char_tensor_from_literal",Pe("char_tensor_from_literal.h",["mtoc2_char_tensor_t"])],["mtoc2_text_view_t",Pe("text_view.h",["mtoc2_string_t","mtoc2_char_tensor_t"])],["mtoc2_disp_text",Pe("disp_text.h",["mtoc2_text_view_t","mtoc2_host_output"])],["mtoc2_strcmp",Pe("strcmp.h",["mtoc2_text_view_t"])],["mtoc2_strcmpi",Pe("strcmp.h",["mtoc2_text_view_t"])],["mtoc2_dot_real",Pe("tensor_dot.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_cscalar","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_uniquetol_real",Pe("tensor_uniquetol.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_format_engine",Pe("format_engine.h",["mtoc2_text_view_t","mtoc2_tensor_t"])],["mtoc2_fprintf",Pe("fprintf.h",["mtoc2_format_engine","mtoc2_host_output"])],["mtoc2_error_fmt",Pe("error_fmt.h",["mtoc2_format_engine"])],["mtoc2_error_fmt_id",Pe("error_fmt.h",["mtoc2_format_engine"])],["mtoc2_warning_fmt",Pe("warning_fmt.h",["mtoc2_format_engine"])],["mtoc2_warning_fmt_id",Pe("warning_fmt.h",["mtoc2_format_engine"])],["mtoc2_assert_scalar_fmt",Pe("assert_fmt.h",["mtoc2_format_engine"])],["mtoc2_sprintf_str",Pe("sprintf.h",["mtoc2_format_engine","mtoc2_string_t","mtoc2_char_tensor_t"])],["mtoc2_sprintf_char",{headers:[],code:"",deps:["mtoc2_sprintf_str"]}],["mtoc2_scalar_index",Pe("scalar_index.h")],["mtoc2_deep_clone",Pe("deep_clone.h")],["mtoc2_alloc",Pe("alloc.h")],["mtoc2_tensor_t",Pe("tensor.h")],["mtoc2_tensor_alloc",Pe("tensor_alloc.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_empty",Pe("tensor_empty.h",["mtoc2_tensor_t"])],["mtoc2_tensor_copy",Pe("tensor_copy.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_empty"])],["mtoc2_tensor_assign",Pe("tensor_assign.h",["mtoc2_tensor_t"])],["mtoc2_tensor_free",Pe("tensor_free.h",["mtoc2_tensor_t"])],["mtoc2_tensor_from_row",Pe("tensor_from_row.h",["mtoc2_tensor_alloc"])],["mtoc2_tensor_from_matrix",Pe("tensor_from_matrix.h",["mtoc2_tensor_alloc"])],["mtoc2_tensor_alloc_nd",Pe("tensor_alloc_nd.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_zeros_nd",Pe("tensor_zeros_nd.h",["mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_ones_nd",Pe("tensor_ones_nd.h",["mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_zeros_square",Pe("tensor_zeros_square.h",["mtoc2_tensor_zeros_nd"])],["mtoc2_tensor_ones_square",Pe("tensor_ones_square.h",["mtoc2_tensor_ones_nd"])],["mtoc2_tensor_eye",Pe("tensor_eye.h",["mtoc2_tensor_alloc"])],["mtoc2_tensor_fill_nd",Pe("tensor_fill_nd.h",["mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_fill_square",Pe("tensor_fill_square.h",["mtoc2_tensor_fill_nd"])],["mtoc2_reshape_nd",Pe("tensor_reshape_nd.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd"])],["mtoc2_reshape_nd_complex",Pe("tensor_reshape_nd_complex.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_transpose",Pe("tensor_transpose.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc"])],["mtoc2_tensor_transpose_complex",Pe("tensor_transpose_complex.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_mtimes_real",Pe("tensor_mtimes_real.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc"])],["mtoc2_tensor_mtimes_complex",Pe("tensor_mtimes_complex.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_size_row",Pe("tensor_size.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_flip",Pe("tensor_flip.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_sort_real",Pe("tensor_sort_real.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_assign","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_meshgrid",Pe("tensor_meshgrid.h",["mtoc2_tensor_t","mtoc2_tensor_alloc","mtoc2_tensor_assign"])],["mtoc2_assert_scalar",Pe("assert_fail.h")],["mtoc2_tensor_norm",Pe("tensor_norm.h",["mtoc2_tensor_t"])],["mtoc2_isequal",Pe("isequal.h",["mtoc2_tensor_t"])],["mtoc2_tensor_predicate",Pe("tensor_predicate.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_cumulative",Pe("tensor_cumulative.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_repmat",Pe("tensor_repmat.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_diag",Pe("tensor_diag.h",["mtoc2_tensor_t","mtoc2_tensor_alloc","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_triangular",Pe("tensor_triangular.h",["mtoc2_tensor_t","mtoc2_tensor_alloc","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_cat",Pe("tensor_cat.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_besselh",Pe("tensor_besselh.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_logical_real",Pe("tensor_logical_real.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_disp_tensor",Pe("disp_tensor.h",["mtoc2_tensor_t","mtoc2_format_double","mtoc2_host_output"])],["mtoc2_disp_tensor_inline",Pe("disp_tensor_inline.h",["mtoc2_tensor_t","mtoc2_format_double","mtoc2_host_output"])],["mtoc2_disp_struct",Pe("disp_struct.h")],["mtoc2_cell_make",Pe("cell.h")],["mtoc2_cell_empty",Pe("cell.h")],["mtoc2_format_cell",Pe("cell.h")],["mtoc2_tensor_alloc_complex",Pe("tensor_alloc_complex.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_alloc_nd_complex",Pe("tensor_alloc_nd_complex.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_copy_complex",Pe("tensor_copy_complex.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_empty"])],["mtoc2_tensor_from_row_complex",Pe("tensor_from_row_complex.h",["mtoc2_tensor_alloc_complex"])],["mtoc2_tensor_from_matrix_complex",Pe("tensor_from_matrix_complex.h",["mtoc2_tensor_alloc_complex"])],["mtoc2_disp_tensor_complex",Pe("disp_tensor_complex.h",["mtoc2_tensor_t","mtoc2_format_complex","mtoc2_cscalar","mtoc2_host_output"])],["mtoc2_tensor_elemwise_complex",Pe("tensor_elemwise_complex.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd_complex","mtoc2_cscalar","mtoc2_cdiv"])],["mtoc2_tensor_unary_complex_math",Pe("tensor_unary_complex_math.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex","mtoc2_cscalar"])],["mtoc2_tensor_reduce_complex",Pe("tensor_reduce_complex.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex","mtoc2_cscalar","mtoc2_cdiv"])],["mtoc2_tensor_imag_all_zero",Pe("tensor_imag_all_zero.h",["mtoc2_tensor_t"])],["mtoc2_tensor_elemwise_real",Pe("tensor_elemwise_real.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_elemwise_real_fn",Pe("tensor_elemwise_real_fn.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_unary_real_math",Pe("tensor_unary_real_math.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_reduce_real",Pe("tensor_reduce_real.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_var",Pe("tensor_var.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_diff",Pe("tensor_diff.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_length",Pe("length.h",["mtoc2_tensor_t"])],["mtoc2_numel",Pe("numel.h",["mtoc2_tensor_t"])],["mtoc2_loop_count",Pe("loop_count.h")],["mtoc2_range_value",Pe("range_value.h")],["mtoc2_oob_abort",Pe("oob.h",["mtoc2_tensor_t"])],["mtoc2_grow_bail",Pe("grow_bail.h",["mtoc2_tensor_t","mtoc2_oob_abort"])],["mtoc2_tensor_make_range",Pe("tensor_make_range.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd","mtoc2_loop_count","mtoc2_range_value"])],["mtoc2_tensor_linspace",Pe("tensor_linspace.h",["mtoc2_tensor_t","mtoc2_tensor_alloc"])],["mtoc2_tensor_logspace",Pe("tensor_logspace.h",["mtoc2_tensor_t","mtoc2_tensor_alloc"])],["mtoc2_logical_mask_indices",Pe("tensor_logical_mask.h",["mtoc2_tensor_t","mtoc2_oob_abort"])],["mtoc2_tic_toc",Pe("tictoc.h")],["mtoc2_plot_dispatch",Pe("plot_dispatch.h",["mtoc2_format_engine"])]]);function BB(e){const t=lv.get(e);if(!t)throw new Error(`runtime snippet '${e}' not registered`);return t}function uv(e,t){const n=e.extraSnippets.get(t);return n!==void 0?n:BB(t)}function qB(e){return{active:new Set,multiAssignCallCounter:0,extraSnippets:new Map,...e!==void 0?{workspace:e}:{}}}function qm(e,t){const n=e.workspace?.getUserBuiltin(t);return n!==void 0?n:is(t)}let W0;function zB(){if(W0!==void 0)return W0;const e=new Map;for(const[t,n]of lv.entries())n.srcFilename!==void 0&&e.set(n.srcFilename,t);return W0=e,e}function Pt(e,t){if(e.active.has(t))return;const n=uv(e,t);for(const r of n.deps)Pt(e,r);if(n.srcFilename!==void 0){const r=n.srcFilename.replace(/\.h$/,".js"),s=FD[r];if(s!==void 0&&s.length>0){const o=zB();for(const i of s){const a=i.replace(/\.js$/,".h"),c=o.get(a);c!==void 0&&Pt(e,c)}}}e.active.add(t)}function VB(e){if(e.active.size===0)return"";const t=[];for(const n of e.active){const r=uv(e,n);r.jsCode!==void 0&&t.push(r.jsCode)}return t.join(`
|
|
5247
|
+
}`};function HT(e,t){return e.kind==="exact"?`${e.value}L`:`mtoc2_check_dim(${t[e.argIndex]})`}function bl(e,t,n,r,s={}){const o=s.minArgs??1,i=s.cFillValue,a=i!==void 0?`${i}, `:"";return{name:e,transfer(c,l){if(c.length<o||c.length>Zn)throw new W(`'${e}' supports ${o}..${Zn} arg(s), got ${c.length}`);if(l!==1)throw new W(`'${e}' does not support multi-output (nargout=${l})`);const u=f0(e,c),f=m0(u);if(f!==void 0){const p=Dt(f);if(p===0)return[et(f)];if(f.every(g=>g===1))return[Be(ft(t),t)];if(p<=wt){const g=new Float64Array(p);return t!==0&&g.fill(t),[et(f,g)]}const d=et(f);return d.sign=ft(t),[d]}const h=u.axes.map(p=>p.kind==="exact"?p.value===1?nn:{kind:"exact",value:p.value}:{kind:"unknown"}),m=Zt(h);return m.sign=ft(t),[m]},emitC({argsC:c,argTypes:l,useRuntime:u}){u(n),u(r);const f=f0(e,l),h=m0(f);if(h!==void 0){if(h.every(d=>d===1))return i!==void 0?i:Number.isInteger(t)?`${t}.0`:`${t}`;const p=h.map(d=>`${d}L`).join(", ");return`${n}(${a}${f.ndim}, (long[]){${p}})`}if(u(Qo),f.isSquare){const p=f.axes[0];return`${r}(${a}mtoc2_check_dim(${c[p.argIndex]}))`}const m=f.axes.map(p=>HT(p,c)).join(", ");return`${n}(${a}${f.ndim}, (long[]){${m}})`},emitJs({argsJs:c,argTypes:l,useRuntime:u}){u(n),u(r);const f=f0(e,l),h=m0(f),m=i!==void 0?`${pk(t)}, `:"";if(h!==void 0){if(h.every(g=>g===1))return i!==void 0?pk(t):`${t}`;const d=h.join(", ");return`${n}(${m}${f.ndim}, [${d}])`}if(u(Qo),f.isSquare){const d=f.axes[0];return`${r}(${m}mtoc2_check_dim(${c[d.argIndex]}))`}const p=f.axes.map(d=>d.kind==="exact"?String(d.value):`mtoc2_check_dim(${c[d.argIndex]})`).join(", ");return`${n}(${m}${f.ndim}, [${p}])`},call({args:c,argTypes:l}){if(l.length<o||l.length>Zn)throw new W(`'${e}' supports ${o}..${Zn} arg(s), got ${l.length}`);let u;if(l.length===1&&Me(l[0])&&!De(l[0])){const m=c[0];u=[];for(let p=0;p<m.data.length;p++)u.push(Ka(m.data[p]))}else{u=[];for(let m=0;m<c.length;m++){const p=c[m],d=typeof p=="number"?p:Number(p);u.push(Ka(d))}u.length===1&&u.push(u[0])}for(;u.length>2&&u[u.length-1]===1;)u.pop();for(;u.length<2;)u.push(1);if(u.every(m=>m===1))return[t];const f=XT[n];if(!f)throw new W(`'${e}' has no JS shape-constructor helper registered (needs an entry in JS_SHAPE_HELPERS keyed by '${n}')`);return[f(i!==void 0?t:void 0,u.length,u)]}}}function pk(e){return Number.isNaN(e)?"NaN":e===1/0?"Infinity":e===-1/0?"-Infinity":String(e)}const YT=bl("zeros",0,"mtoc2_tensor_zeros_nd","mtoc2_tensor_zeros_square"),JT=bl("ones",1,"mtoc2_tensor_ones_nd","mtoc2_tensor_ones_square");function sm(e){if(e.length<1||e.length>2)throw new W(`'eye' supports 1 or 2 arguments (got ${e.length})`);if(e.length===1&&Me(e[0])&&!De(e[0]))throw new W("'eye' with a size-vector argument is not yet supported; use 'eye(m, n)' instead");const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(!Me(r)||r.elem!=="double"||r.isComplex)throw new le(`'eye' arg ${n+1} must be a scalar real double (got ${r.kind})`);if(!De(r))throw new le(`'eye' arg ${n+1} must be a scalar real double (got tensor)`);const s=Je(r);if(s!==void 0){if(!Number.isInteger(s)||s<0)throw new le(`'eye' arg ${n+1} must be a finite non-negative integer (got ${s})`);t.push({exact:s,argIndex:n})}else t.push({exact:void 0,argIndex:n})}return t.length===1?[t[0],{exact:t[0].exact,argIndex:t[0].argIndex}]:t}const ZT={name:"eye",transfer(e,t){if(t!==1)throw new W(`'eye' does not support multi-output (nargout=${t})`);const n=sm(e),r=n[0].exact,s=n[1].exact;if(r!==void 0&&s!==void 0){const a=[r,s],c=r*s;if(c===0)return[et(a)];if(r===1&&s===1)return[Be("positive",1)];if(c<=wt){const u=new Float64Array(c),f=r<s?r:s;for(let h=0;h<f;h++)u[h+h*r]=1;return[et(a,u)]}const l=et(a);return l.sign="nonneg",[l]}const o=n.map(a=>a.exact===void 0?{kind:"unknown"}:a.exact===1?nn:{kind:"exact",value:a.exact}),i=Zt(o);return i.sign="nonneg",[i]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_eye");const r=sm(t),s=r[0].exact,o=r[1].exact;if(s===1&&o===1)return"1.0";(s===void 0||o===void 0)&&n(Qo);const i=s!==void 0?`${s}L`:`mtoc2_check_dim(${e[r[0].argIndex]})`,a=o!==void 0?`${o}L`:`mtoc2_check_dim(${e[r[1].argIndex]})`;return t.length===1&&s===void 0&&o===void 0&&r[0].argIndex===r[1].argIndex?`mtoc2_eye_square(mtoc2_check_dim(${e[r[0].argIndex]}))`:`mtoc2_eye_rect(${i}, ${a})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_eye");const r=sm(t),s=r[0].exact,o=r[1].exact;if(s===1&&o===1)return"1";(s===void 0||o===void 0)&&n(Qo);const i=s!==void 0?String(s):`mtoc2_check_dim(${e[r[0].argIndex]})`,a=o!==void 0?String(o):`mtoc2_check_dim(${e[r[1].argIndex]})`;return t.length===1&&s===void 0&&o===void 0&&r[0].argIndex===r[1].argIndex?`mtoc2_eye_square(mtoc2_check_dim(${e[r[0].argIndex]}))`:`mtoc2_eye_rect(${i}, ${a})`},call({args:e,argTypes:t}){const n=sm(t),r=n[0].exact!==void 0?n[0].exact:Ka(typeof e[n[0].argIndex]=="number"?e[n[0].argIndex]:Number(e[n[0].argIndex])),s=n[1].exact!==void 0?n[1].exact:Ka(typeof e[n[1].argIndex]=="number"?e[n[1].argIndex]:Number(e[n[1].argIndex]));return r===1&&s===1?[1]:[N5(r,s)]}},Ga=Zn;function dk(e){return!Me(e)||De(e)||e.shape===void 0?!1:Dt(e.shape)===0}function KT(e){const t=e.slice();for(;t.length>2&&t[t.length-1].kind==="exact"&&t[t.length-1].value===1;)t.pop();for(;t.length<2;)t.push({kind:"exact",value:1});return t}function om(e){if(e.length<1)throw new W("'reshape' requires at least one dim argument after the input tensor");let t;if(e.length===1&&Me(e[0])&&!De(e[0])){const n=e[0];if(dk(n))throw new W("reshape: '[]' auto-infer slot is not yet supported; specify all dims explicitly");if(n.elem!=="double"||n.isComplex)throw new le(`'reshape' dim vector must be a real-double tensor (got ${n.elem}${n.isComplex?" complex":""})`);const r=Mt(n);if(r===void 0)throw new W("'reshape' dim vector must be a statically-known constant in v1");if(r.length<1||r.length>Ga)throw new W(`'reshape' supports 1..${Ga} output dims (got ${r.length})`);t=[];for(let s=0;s<r.length;s++){const o=r[s];if(!Number.isFinite(o)||!Number.isInteger(o)||o<0)throw new le(`'reshape' dim ${s+1} must be a finite non-negative integer (got ${o})`);t.push({kind:"exact",value:o})}}else{if(e.length>Ga)throw new W(`'reshape' supports 1..${Ga} output dims (got ${e.length})`);t=[];let n=!1;for(let r=0;r<e.length;r++){const s=e[r];if(!Me(s)||s.elem!=="double"||s.isComplex)throw new le(`'reshape' dim arg ${r+1} must be a scalar real double (got ${s.kind})`);if(!De(s)){if(dk(s)){if(n)throw new W("'reshape' allows at most one '[]' auto-infer slot");n=!0,t.push({kind:"infer",argIndex:r});continue}throw new le(`'reshape' dim arg ${r+1} must be a scalar real double (got tensor)`)}const o=Je(s);if(o===void 0){t.push({kind:"dynamic",argIndex:r});continue}if(!Number.isFinite(o)||!Number.isInteger(o)||o<0)throw new le(`'reshape' dim arg ${r+1} must be a finite non-negative integer (got ${o})`);t.push({kind:"exact",value:o,argIndex:r})}}return{axes:KT(t)}}function h0(e){const t=[];for(const n of e.axes){if(n.kind!=="exact")return;t.push(n.value)}return t}function GT(e,t){return e.kind==="exact"?`${e.value}L`:e.kind==="infer"?"-1L":`mtoc2_check_dim(${t[e.argIndex]})`}const QT={name:"reshape",transfer(e,t){if(e.length<2||e.length>Ga+1)throw new le(`'reshape' expects 2..${Ga+1} arg(s), got ${e.length}`);if(t!==1)throw new W(`'reshape' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'reshape' first arg must be numeric (got ${n.kind})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'reshape' first arg must be a double or logical tensor (got ${n.elem})`);const r=om(e.slice(1));if(n.shape!==void 0){const i=r.axes.findIndex(a=>a.kind==="infer");if(i!==-1){const a=[];let c=!0;for(let l=0;l<r.axes.length;l++){if(l===i)continue;const u=r.axes[l];if(u.kind==="exact")a.push(u.value);else{c=!1;break}}if(c){const l=n.shape.reduce((h,m)=>h*m,1),u=a.reduce((h,m)=>h*m,1);if(u===0&&l!==0)throw new le(`'reshape' element count mismatch: input has ${l} elements but the explicit dims around '[]' multiply to 0`);if(u>0&&l%u!==0)throw new le(`'reshape' element count mismatch: input has ${l} elements, not divisible by ${u} (the explicit dims around '[]')`);const f=u===0?0:l/u;r.axes[i]={kind:"exact",value:f}}}}const s=h0(r);if(s!==void 0){const i=s.reduce((a,c)=>a*c,1);if(n.shape!==void 0){const a=n.shape.reduce((c,l)=>c*l,1);if(a!==i)throw new le(`'reshape' element count mismatch: input has ${a} elements, requested shape needs ${i}`)}if(s.every(a=>a===1)){if(n.isComplex){const a=An(n);if(a!==void 0)return[_t(a)];const c=rn(n);return c!==void 0&&c.re.length===1?[_t({re:c.re[0],im:c.im[0]})]:[_t()]}return typeof n.exact=="number"?[Be(ft(n.exact),n.exact)]:[Be("unknown")]}if(n.isComplex){const a=rn(n);return a!==void 0&&i<=wt&&a.re.length===i?[Ut(s,a)]:[Ut(s)]}return n.exact instanceof Float64Array&&i<=wt&&n.exact.length===i?[et(s,n.exact)]:[et(s)]}const o=r.axes.map(i=>i.kind==="exact"?i.value===1?nn:{kind:"exact",value:i.value}:{kind:"unknown"});return n.isComplex?[mr(o)]:[Zt(o)]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_reshape_nd"),n("mtoc2_reshape_nd_complex");const r=om(t.slice(1)),s=h0(r);if(s!==void 0&&s.every(u=>u===1))return e[0];const o=t[0],a=Me(o)&&o.isComplex?"mtoc2_reshape_nd_complex":"mtoc2_reshape_nd",c=e.slice(1);r.axes.some(u=>u.kind==="dynamic")&&n(Qo);const l=r.axes.map(u=>GT(u,c)).join(", ");return`${a}(${e[0]}, ${r.axes.length}, (long[]){${l}})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=om(t.slice(1)),s=h0(r);if(s!==void 0&&s.every(c=>c===1))return e[0];const o=t[0],i=e.slice(1);r.axes.some(c=>c.kind==="dynamic")&&n(Qo);const a=r.axes.map(c=>c.kind==="exact"?String(c.value):c.kind==="infer"?"-1":`mtoc2_check_dim(${i[c.argIndex]})`).join(", ");return Me(o)&&o.isComplex?(n("mtoc2_reshape_nd_complex"),`mtoc2_reshape_nd_complex(${e[0]}, ${r.axes.length}, [${a}])`):(n("mtoc2_reshape_nd"),`mtoc2_reshape_nd(${e[0]}, ${r.axes.length}, [${a}])`)},call({args:e,argTypes:t}){const n=om(t.slice(1)),r=t[0],s=[];for(const i of n.axes)if(i.kind==="exact")s.push(i.value);else if(i.kind==="infer")s.push(-1);else{const a=e[i.argIndex+1];s.push(Ka(typeof a=="number"?a:Number(a)))}return[(Me(r)&&r.isComplex?vL:kL)(e[0],n.axes.length,s)]}};function p0(e,t,n){const r=new Float64Array(t*n);for(let s=0;s<n;s++)for(let o=0;o<t;o++)r[s+o*n]=e[o+s*t];return r}const OT={name:"transpose",transfer(e,t){if(e.length!==1)throw new le(`'transpose' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'transpose' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`transpose argument must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`transpose argument must be a double or logical (got ${n.elem})`);if(De(n)){if(n.isComplex){const l=An(n);return l!==void 0?[_t(l)]:[_t()]}const a=Je(n),c=a!==void 0?Be(ft(a),a):Be(n.sign);return n.elem==="logical"&&(c.elem="logical"),[c]}if(n.dims.length!==2)throw new W(`transpose requires a 2-D operand (got ${n.dims.length}-D); use 'permute' for higher-rank reorderings (numbl flattens trailing dims into cols; mtoc2 follows MATLAB and rejects)`);if(n.shape===void 0)throw new W("transpose of a tensor with unknown shape is not yet supported");const r=n.shape[0],s=n.shape[1],o=[s,r];if(n.isComplex){const a=rn(n);return a!==void 0?[Ut(o,{re:p0(a.re,r,s),im:p0(a.im,r,s)})]:[Ut(o)]}const i=n.exact instanceof Float64Array?et(o,p0(n.exact,r,s)):et(o);return n.elem==="logical"&&(i.elem="logical"),[i]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_transpose"),n("mtoc2_tensor_transpose_complex");const r=t[0];return qe(r)?r.isComplex?`mtoc2_tensor_transpose_complex(${e[0]})`:`mtoc2_tensor_transpose(${e[0]})`:e[0]},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_transpose_complex"),`mtoc2_tensor_transpose_complex(${e[0]})`):(n("mtoc2_tensor_transpose"),`mtoc2_tensor_transpose(${e[0]})`):e[0]},call({args:e,argTypes:t}){const n=t[0];if(!qe(n))return[e[0]];if(!Wt(e[0]))throw new le("'transpose' runtime arg has type-system shape tensor but runtime value isn't a tensor");return[(n.isComplex?EL:AL)(e[0])]}},e8={name:"size",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'size' expects 1..2 arg(s), got ${e.length}`);if(t<1)throw new W(`'size' requires at least one output (got nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'size' first arg must be numeric (got ${ze(n)})`);if(e.length===2){if(t!==1)throw new W("'size(A, k)' is single-output only; drop the 'k' arg and use '[d1, d2, ...] = size(A)' for per-output dims");const s=e[1];if(!Me(s)||s.isComplex||!De(s))throw new le(`'size' second arg must be a real scalar (got ${ze(s)})`);const o=Je(s);if(o!==void 0){if(!Number.isFinite(o)||!Number.isInteger(o)||o<1)throw new le(`'size' dim argument must be a positive integer (got ${o})`);if(n.shape!==void 0){const i=o<=n.shape.length?n.shape[o-1]:1;return[Be(ft(i),i)]}}return[Be("nonneg")]}const r=n.dims.length;if(t>=2){const s=[];for(let o=0;o<t;o++)if(n.shape!==void 0){const i=o<r?n.shape[o]:1;s.push(Be(ft(i),i))}else if(o<r&&n.dims[o].kind==="exact"){const i=n.dims[o].value;s.push(Be(ft(i),i))}else o>=r?s.push(Be("positive",1)):s.push(Be("nonneg"));return s}if(n.shape!==void 0){const s=new Float64Array(r);for(let o=0;o<r;o++)s[o]=n.shape[o];return[et([1,r],s)]}return[et([1,r])]},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){const o=t[0];if(De(o))return n>=2?`((void)(${(r??[]).slice(0,n).map(c=>`(*${c} = 1.0)`).join(", ")}))`:t.length===2?"1.0":(s("mtoc2_tensor_size_row"),s("mtoc2_tensor_from_row"),"mtoc2_tensor_from_row((double[]){1.0, 1.0}, 2)");if(n>=2){const i=r??[],a=o.dims.length,c=[];for(let l=0;l<n;l++){const u=l<a?`(double)${e[0]}.dims[${l}]`:"1.0";c.push(`(*${i[l]} = ${u})`)}return`((void)(${c.join(", ")}))`}if(s("mtoc2_tensor_size_row"),s("mtoc2_tensor_from_row"),t.length===2){const i=Je(t[1]);if(i!==void 0){const a=o.dims.length;return i<=a?`((double)${e[0]}.dims[${i-1}])`:"1.0"}return`({ long _mtoc2_k = (long)(${e[1]}); (double)(_mtoc2_k >= 1 && _mtoc2_k <= ${e[0]}.ndim ? ${e[0]}.dims[_mtoc2_k - 1] : 1); })`}return qe(o)?`mtoc2_tensor_size_row(${e[0]})`:"mtoc2_tensor_from_row((double[]){1.0, 1.0}, 2)"},emitJs({argsJs:e,argTypes:t,nargout:n,useRuntime:r}){const s=t[0];if(De(s))return n>=2?`[${Array(n).fill("1").join(", ")}]`:t.length===2?"1":(r("mtoc2_tensor_size_row"),r("mtoc2_tensor_from_row"),"mtoc2_tensor_from_row([1, 1], 2)");if(n>=2){const o=s.dims.length,i=[];for(let a=0;a<n;a++)i.push(a<o?`${e[0]}.shape[${a}]`:"1");return`[${i.join(", ")}]`}if(r("mtoc2_tensor_size_row"),r("mtoc2_tensor_from_row"),t.length===2){const o=Je(t[1]);if(o!==void 0){const i=s.dims.length;return o<=i?`(${e[0]}.shape[${o-1}])`:"1"}return`((k => (k >= 1 && k <= ${e[0]}.shape.length ? ${e[0]}.shape[k - 1] : 1))(Math.trunc(${e[1]})))`}return qe(s)?`mtoc2_tensor_size_row(${e[0]})`:"mtoc2_tensor_from_row([1, 1], 2)"},call({args:e,argTypes:t,nargout:n}){const r=e[0];if(n>=2){const s=Wt(r)?r.shape:[1,1],o=[];for(let i=0;i<n;i++)o.push(i<s.length?s[i]:1);return o}if(t.length===2){const s=typeof e[1]=="number"?e[1]:Number(e[1]),o=Math.trunc(s);if(o<1)throw new le(`'size' dim argument must be a positive integer (got ${o})`);return Wt(r)?[o<=r.shape.length?r.shape[o-1]:1]:[1]}return Wt(r)?[ML(r)]:[u6([1,1],2)]}};function d0(e,t,n){const r=Dt(t),s=new Float64Array(r),o=n>=0&&n<t.length?t[n]:1;if(o<=1)return s.set(e),s;let i=1;for(let l=0;l<n;l++)i*=t[l];const a=i*o,c=r/a;for(let l=0;l<c;l++){const u=l*a;for(let f=0;f<o;f++){const h=u+f*i,m=u+(o-1-f)*i;for(let p=0;p<i;p++)s[m+p]=e[h+p]}}return s}function im(e,t,n){if(n!==null)return n;if(t.length===1){const o=t[0];if(o.shape!==void 0){const i=o.shape.findIndex(a=>a>1);return i===-1?0:i}return 0}const r=t[1];if(!De(r)||r.isComplex)throw new le(`'${e}' second arg must be a real scalar (got ${ze(r)})`);const s=Je(r);if(s===void 0)throw new W(`'${e}' with a dynamic dim argument is not yet supported (require statically-known axis)`);if(!Number.isFinite(s)||!Number.isInteger(s)||s<1)throw new le(`'${e}' dim argument must be a positive integer (got ${s})`);return s-1}function g0(e){return{name:e.name,transfer(t,n){if(t.length<e.minArgs||t.length>e.maxArgs)throw new le(`'${e.name}' expects ${e.minArgs}..${e.maxArgs} arg(s), got ${t.length}`);if(n!==1)throw new W(`'${e.name}' does not support multi-output (nargout=${n})`);const r=t[0];if(!Me(r))throw new le(`'${e.name}' arg must be numeric (got ${ze(r)})`);if(r.elem!=="double"&&r.elem!=="logical")throw new le(`'${e.name}' arg must be a real double or logical (got ${r.elem})`);if(De(r)){if(r.isComplex){const a=An(r);return a!==void 0?[_t(a)]:[_t()]}const i=Je(r);return i!==void 0?[Be(ft(i),i)]:[Be(r.sign)]}const s=im(e.name,t,e.fixedAxis);if(r.isComplex){const i=rn(r);if(r.shape!==void 0&&i!==void 0&&Dt(r.shape)<=wt){const c=d0(i.re,r.shape,s),l=d0(i.im,r.shape,s);return[Ut(r.shape,{re:c,im:l})]}return r.shape!==void 0?[Ut(r.shape)]:[{...r,exact:void 0}]}const o=Mt(r);if(r.shape!==void 0&&o!==void 0&&Dt(r.shape)<=wt){const a=d0(o,r.shape,s);return[et(r.shape,a)]}return r.shape!==void 0?[et(r.shape)]:[{...r,exact:void 0}]},emitC({argsC:t,argTypes:n,useRuntime:r}){const s=n[0];if(!qe(s))return t[0];const o=im(e.name,n,e.fixedAxis);return s.isComplex?(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip_complex(${t[0]}, ${o}L)`):(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip(${t[0]}, ${o}L)`)},emitJs({argsJs:t,argTypes:n,useRuntime:r}){const s=n[0];if(!qe(s))return t[0];const o=im(e.name,n,e.fixedAxis);return s.isComplex?(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip_complex(${t[0]}, ${o})`):(r("mtoc2_tensor_flip"),`mtoc2_tensor_flip(${t[0]}, ${o})`)},call({args:t,argTypes:n}){const r=n[0];if(!qe(r))return[t[0]];const s=im(e.name,n,e.fixedAxis);return r.isComplex?[I5(t[0],s)]:[E5(t[0],s)]}}}const t8=g0({name:"flipud",fixedAxis:0,minArgs:1,maxArgs:1}),n8=g0({name:"fliplr",fixedAxis:1,minArgs:1,maxArgs:1}),r8=g0({name:"flip",fixedAxis:null,minArgs:1,maxArgs:2});function s8(e){pr(e,"'sort' arg 1");const t=e;if(!qe(t))throw new W("'sort' on a scalar is a no-op; pass a 1-D vector (1×N or N×1)");if(t.dims.length!==2)throw new W(`'sort' currently only supports 1-D vectors (got ${ze(t)}); matrix and N-D forms (with explicit 'dim' arg) are not yet supported`);const n=Dn(t.dims[0]),r=Dn(t.dims[1]);if(!n&&!r)throw new W(`'sort' currently only supports 1-D vectors (1×N or N×1); got ${ze(t)} — pass an explicit 'dim' (not yet supported) or reshape first`);return t}function am(e){if(e.length<2)return!1;const t=e[1];if(!os(t)||t.kind!=="Char"&&t.kind!=="String")throw new le(`'sort' mode arg must be a literal 'ascend' or 'descend' (got ${ze(t)})`);if(t.exact===void 0)throw new W("'sort' mode arg must be a literal; non-literal text is not supported");const n=t.exact.toLowerCase();if(n==="ascend")return!1;if(n==="descend")return!0;throw new le(`'sort' mode arg must be 'ascend' or 'descend' (got '${t.exact}')`)}const o8={name:"sort",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'sort' expects 1..2 arg(s), got ${e.length}`);if(t<1||t>2)throw new W(`'sort' supports 1..2 output(s); got nargout=${t}`);const n=s8(e[0]);am(e);const r=n.isComplex?mr(n.dims.slice()):Zt(n.dims.slice());if(t===1)return[r];const s=Zt(n.dims.slice());return s.sign="positive",[r,s]},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){s("mtoc2_sort_real");const o=t[0],i=Me(o)&&o.isComplex,a=am(t)?1:0,c=i?"mtoc2_sort_complex":"mtoc2_sort_real";if(n===1)return`${c}(${e[0]}, ${a})`;const l=r??[];return`${c}_2(${e[0]}, ${a}, ${l.join(", ")})`},emitJs({argsJs:e,argTypes:t,nargout:n,useRuntime:r}){r("mtoc2_sort_real");const s=t[0],o=Me(s)&&s.isComplex,i=am(t)?"true":"false",a=o?"mtoc2_sort_complex":"mtoc2_sort_real";return n===1?`${a}(${e[0]}, ${i})`:`(o => [o.v, o.ix])(${a}_2(${e[0]}, ${i}))`},call({args:e,argTypes:t,nargout:n}){const r=e[0],s=t[0],o=Me(s)&&s.isComplex,i=am(t);if(n===1)return[(o?SL:$L)(r,i)];const a=o?NL(r,i):CL(r,i);return[a.v,a.ix]}};function gk(e,t){ml(e,t);const n=e;if(!qe(n))throw new W(`${t} must be a 1-D vector (1×N or N×1); scalar inputs are not supported`);if(n.dims.length!==2)throw new W(`${t} must be a 1-D vector (got ${ze(n)})`);const r=Dn(n.dims[0]),s=Dn(n.dims[1]);if(!r&&!s)throw new W(`${t} must be a 1-D vector (1×N or N×1); got ${ze(n)}`);return n}function wk(e){return Dn(e.dims[0])?e.dims[1]:e.dims[0]}function i8(e,t){const n=e.length,r=t.length,s=new Float64Array(r*n);for(let o=0;o<n;o++)for(let i=0;i<r;i++)s[i+o*r]=e[o];return s}function a8(e,t){const n=e.length,r=t.length,s=new Float64Array(r*n);for(let o=0;o<n;o++)for(let i=0;i<r;i++)s[i+o*r]=t[i];return s}function w0(e,t,n){const r=wk(e),s=wk(t),o=Mt(e),i=Mt(t);if(r.kind==="exact"&&s.kind==="exact"&&o!==void 0&&i!==void 0&&o.length===r.value&&i.length===s.value&&r.value*s.value<=wt){const c=n==="X"?i8(o,i):a8(o,i);return et([s.value,r.value],c)}return Zt([s,r])}const c8={name:"meshgrid",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'meshgrid' expects 1..2 arg(s), got ${e.length}`);const n=gk(e[0],"'meshgrid' arg 1"),r=e.length>=2?gk(e[1],"'meshgrid' arg 2"):n;if(t===1)return[w0(n,r,"X")];if(t===2)return[w0(n,r,"X"),w0(n,r,"Y")];throw new W(`'meshgrid' supports 1..2 output(s); got nargout=${t}`)},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){if(s("mtoc2_meshgrid"),n===1){const i=e[0],a=e.length>=2?e[1]:e[0];return`mtoc2_meshgrid_x(${i}, ${a})`}const o=r??[];return t.length===1?`mtoc2_meshgrid_1arg(${e[0]}, ${o.join(", ")})`:`mtoc2_meshgrid(${e[0]}, ${e[1]}, ${o.join(", ")})`},emitJs({argsJs:e,argTypes:t,nargout:n,useRuntime:r}){if(r("mtoc2_meshgrid"),n===1){const s=e[0],o=e.length>=2?e[1]:e[0];return`mtoc2_meshgrid_x(${s}, ${o})`}return t.length===1?`(o => [o.X, o.Y])(mtoc2_meshgrid_1arg(${e[0]}))`:`(o => [o.X, o.Y])(mtoc2_meshgrid(${e[0]}, ${e[1]}))`},call({args:e,argTypes:t,nargout:n}){const r=e[0];if(n===1){const o=t.length>=2?e[1]:r;return[T5(r,o)]}if(t.length===1){const o=P5(r);return[o.X,o.Y]}const s=Mb(r,e[1]);return[s.X,s.Y]}};function l8(e){if(typeof e=="object"&&e!==null){const t=e;if(t.mtoc2Tag==="char"&&typeof t.value=="string")return t.value}return e}const u8={name:"assert",transfer(e,t){if(e.length<1)throw new le("'assert' requires at least 1 arg");if(t!==1)throw new W(`'assert' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'assert' first arg must be numeric (got ${ze(n)})`);if(n.isComplex)throw new le("'assert' on complex cond is not supported");if(!De(n))throw new W("'assert' on a tensor cond is not yet supported in mtoc2 v1 (numbl tests every element non-zero and non-NaN); pass a scalar predicate instead");if(e.length>=2){const s=e[1];if(!os(s))throw new W(`'assert' message must be char or string (got ${ze(s)})`);Ya("assert",e,2)}const r=Je(n);if(r!==void 0&&!(r!==0&&!Number.isNaN(r))){const o=e.length>=2?e[1]:void 0,i=o&&(o.kind==="String"||o.kind==="Char")?`: ${o.exact??"(opaque)"}`:"";throw new le(`'assert' is statically false${i}`)}return[{kind:"Void"}]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_assert_scalar"),n("mtoc2_assert_scalar_fmt");const r=t[0];if(Me(r)&&Je(r)!==void 0)return"((void)0)";const s=`(double)(${e[0]})`;if(t.length<2)return`mtoc2_assert_scalar(${s}, (const char *)0)`;if(t.length===2){const a=t[1];if((a.kind==="Char"||a.kind==="String")&&a.exact!==void 0)return`mtoc2_assert_scalar(${s}, ${JSON.stringify(a.exact)})`}const o=Vi(e[1],t[1]),i=[];for(let a=2;a<t.length;a++)i.push(Ja("assert",e[a],t[a],a));return`mtoc2_assert_scalar_fmt(${s}, ${o}, ${i.length}, ${Za(i)})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_assert_scalar_fmt");const r=t[0];return Me(r)&&Je(r)!==void 0?"undefined":t.length<2?`mtoc2_assert_scalar_fmt(${e[0]}, "assertion failed")`:`mtoc2_assert_scalar_fmt(${e.join(", ")})`},call({args:e,argTypes:t}){t[0];const n=typeof e[0]=="number"?e[0]:Number(e[0]);if(n!==0&&!Number.isNaN(n))return[];const s=e.slice(1).map(l8);if(s.length===0)throw new Error("assertion failed");return $R(!1,s[0],...s.slice(1)),[]}},f8={name:"tic",transfer(e,t){if(e.length!==0)throw new le(`'tic' expects 0 arg(s), got ${e.length}`);if(t!==1)throw new W(`'tic' does not support multi-output (nargout=${t})`);return[Be("positive")]},emitC({useRuntime:e}){return e("mtoc2_tic_toc"),"mtoc2_tic()"},emitJs({useRuntime:e}){return e("mtoc2_tic_toc"),"mtoc2_tic()"},call(){return[a6()]}},m8={name:"toc",transfer(e,t){if(e.length>1)throw new le(`'toc' expects 0..1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'toc' does not support multi-output (nargout=${t})`);if(e.length===1&&!Kn(e[0]))throw new le(`'toc' tic-handle argument must be a scalar real numeric (the value returned by 'tic'); got ${e[0].kind}`);return[Be("nonneg")]},emitC({argsC:e,useRuntime:t}){return t("mtoc2_tic_toc"),e.length===1?`mtoc2_toc_handle(${e[0]})`:"mtoc2_toc()"},emitJs({argsJs:e,useRuntime:t}){return t("mtoc2_tic_toc"),e.length===1?`mtoc2_toc_handle(${e[0]})`:"mtoc2_toc()"},call({args:e}){if(e.length===1){const t=typeof e[0]=="number"?e[0]:Number(e[0]);return[l6(t)]}return[c6()]}},_0=(e,t)=>({name:e,transfer(){throw new W(t)},emitC(){throw new W(t)},emitJs(){throw new W(t)},call(){throw new W(t)}}),h8=_0("addpath","'addpath' is only allowed at the top of the driver script, before any other non-comment statement; mtoc2 resolves the search path statically and cannot honor a runtime addpath call"),p8=_0("rmpath","'rmpath' is not supported by mtoc2; the search path is fixed after lowering begins"),d8=_0("savepath","'savepath' is not supported by mtoc2"),_k={cos:rD,sin:sD,tan:oD,atan:iD,sinh:aD,cosh:cD,tanh:lD,asinh:uD,exp:fD,log:mD,log2:hD,log10:pD,sqrt:dD,abs:gD,floor:wD,ceil:_D,fix:yD,round:xD,sign:bD},yk={cos:zL,sin:qL,tan:VL,atan:UL,sinh:WL,cosh:XL,tanh:HL,exp:DL,log:TL,log2:PL,log10:BL,sqrt:LL,floor:YL,ceil:JL,fix:KL,round:ZL,sign:GL};function cm(e,t){return n=>n.sign==="positive"&&e?"nonneg":n.sign==="negative"&&t?"nonpositive":n.sign==="nonzero"&&(e||t)?"unknown":n.sign}function Qn(e){const{name:t,cFnReal:n,jsFn:r,signRule:s,realDomainOk:o,complex:i}=e,a=e.jsExpr??(l=>`Math.${t}(${l})`),c=l=>l.isComplex||o===void 0||o(l)?!1:i!==void 0&&i.liftOnDomainMiss===!0;return{name:t,transfer(l,u){if(l.length!==1)throw new le(`'${t}' expects 1 arg(s), got ${l.length}`);if(u!==1)throw new W(`'${t}' does not support multi-output (nargout=${u})`);i!==void 0?pr(l[0],`'${t}' arg`):ml(l[0],`'${t}' arg`);const f=l[0],h=c(f);if(f.isComplex||h){if(De(f)){const p=f.isComplex?An(f):(()=>{const d=Je(f);return d!==void 0?{re:d,im:0}:void 0})();if(p!==void 0){const d=i.jsFnComplex(p);if(Number.isFinite(d.re)&&Number.isFinite(d.im))return[_t(d)]}return[_t()]}if(f.isComplex){const p=rn(f);if(p!==void 0&&f.shape!==void 0){const d=Dt(f.shape);if(d<=wt){const g=new Float64Array(d),w=new Float64Array(d);let _=!0;for(let y=0;y<d;y++){const b=i.jsFnComplex({re:p.re[y],im:p.im[y]});if(!Number.isFinite(b.re)||!Number.isFinite(b.im)){_=!1;break}g[y]=b.re,w[y]=b.im}if(_)return[Ut(f.shape,{re:g,im:w})]}}}else{const p=Mt(f);if(p!==void 0&&f.shape!==void 0){const d=Dt(f.shape);if(d<=wt){const g=new Float64Array(d),w=new Float64Array(d);let _=!0;for(let y=0;y<d;y++){const b=i.jsFnComplex({re:p[y],im:0});if(!Number.isFinite(b.re)||!Number.isFinite(b.im)){_=!1;break}g[y]=b.re,w[y]=b.im}if(_)return[Ut(f.shape,{re:g,im:w})]}}}return[mr(f.dims.slice())]}if(o!==void 0&&!o(f))throw new le(`'${t}' of input that may leave the real domain is not yet supported for real-typed input (would produce NaN / -Inf or a complex result). Guard upstream or make the input complex (e.g. '${t}(x + 0i)').`);if(De(f)){const p=Je(f);if(p!==void 0){const d=r(p);if(Number.isFinite(d))return[Be(ft(d),d)]}return[Be(s(f))]}if(f.shape!==void 0){const p=Mt(f),d=Dt(f.shape);if(p!==void 0&&d<=wt){const g=new Float64Array(p.length);let w=!0;for(let _=0;_<p.length;_++){const y=r(p[_]);if(!Number.isFinite(y)){w=!1;break}g[_]=y}if(w)return[et(f.shape,g)]}}const m=Zt(f.dims.slice());return m.sign=s(f),[m]},emitC({argsC:l,argTypes:u,useRuntime:f}){const h=u[0],m=c(h);if(Me(h)&&h.isComplex||m){if(f("mtoc2_cscalar"),qe(h))return f("mtoc2_tensor_unary_complex_math"),`mtoc2_tensor_${t}_complex(${l[0]})`;const p=m?`mtoc2_cmake(${l[0]}, 0.0)`:l[0];return`${i.cFnComplex}(${p})`}return qe(h)?(f("mtoc2_tensor_unary_real_math"),`mtoc2_tensor_${t}(${l[0]})`):(n.startsWith("mtoc2_")&&f("mtoc2_tensor_unary_real_math"),`${n}(${l[0]})`)},emitJs({argsJs:l,argTypes:u,useRuntime:f}){const h=u[0],m=c(h);if(Me(h)&&h.isComplex||m){if(qe(h)){if(yk[t]===void 0)throw new W(`'${t}' complex-tensor emitJs has no JS kernel registered`);return f("mtoc2_tensor_unary_complex_math"),f("mtoc2_cscalar"),`mtoc2_tensor_${t}_complex(${l[0]})`}f("mtoc2_cscalar");const p=m?`mtoc2_cmake(${l[0]}, 0.0)`:l[0];return`${i.cFnComplex}(${p})`}if(qe(h)){if(_k[t]===void 0)throw new W(`'${t}' tensor emitJs has no JS kernel registered`);return f("mtoc2_tensor_unary_real_math"),`mtoc2_tensor_${t}(${l[0]})`}return a(l[0])},call({args:l,argTypes:u}){const f=u[0],h=c(f);if(Me(f)&&f.isComplex||h){if(qe(f)){const g=yk[t];if(g===void 0)throw new W(`'${t}' complex-tensor 'call' has no JS kernel registered`);return[g(l[0])]}const p=l[0],d=un(p)?p:{re:typeof p=="number"?p:Number(p),im:0};return[i.jsFnComplex(d)]}if(qe(f)){const p=_k[t];if(p===void 0)throw new W(`'${t}' tensor 'call' has no JS kernel registered`);return[p(l[0])]}const m=typeof l[0]=="number"?l[0]:Number(l[0]);return[r(m)]},elementwise:!0}}function g8(e){const t=Math.hypot(e.re,e.im);if(t===0)return{re:0,im:0};const n=Math.sqrt((t+e.re)/2),r=(e.im>=0?1:-1)*Math.sqrt((t-e.re)/2);return{re:n,im:r}}function w8(e){const t=Math.exp(e.re);return{re:t*Math.cos(e.im),im:t*Math.sin(e.im)}}function lm(e){return{re:.5*Math.log(e.re*e.re+e.im*e.im),im:Math.atan2(e.im,e.re)}}function _8(e){const t=lm(e),n=Math.log(2);return{re:t.re/n,im:t.im/n}}function y8(e){const t=lm(e),n=Math.log(10);return{re:t.re/n,im:t.im/n}}function xk(e){return{re:Math.sin(e.re)*Math.cosh(e.im),im:Math.cos(e.re)*Math.sinh(e.im)}}function bk(e){return{re:Math.cos(e.re)*Math.cosh(e.im),im:-Math.sin(e.re)*Math.sinh(e.im)}}function kk(e,t){if(Math.abs(t.re)>=Math.abs(t.im)){const s=t.im/t.re,o=t.re+s*t.im;return{re:(e.re+e.im*s)/o,im:(e.im-e.re*s)/o}}const n=t.re/t.im,r=t.im+n*t.re;return{re:(e.re*n+e.im)/r,im:(e.im*n-e.re)/r}}function x8(e){return kk(xk(e),bk(e))}function b8(e){return{re:Math.sinh(e.re)*Math.cos(e.im),im:Math.cosh(e.re)*Math.sin(e.im)}}function k8(e){return{re:Math.cosh(e.re)*Math.cos(e.im),im:Math.sinh(e.re)*Math.sin(e.im)}}function v8(e){const t=Math.cosh(2*e.re)+Math.cos(2*e.im);return{re:Math.sinh(2*e.re)/t,im:Math.sin(2*e.im)/t}}function M8(e){const t={re:-e.im,im:e.re},n={re:1-t.re,im:-t.im},r={re:1+t.re,im:t.im},s=kk(n,r),o=lm(s);return{re:-o.im/2,im:o.re/2}}function $8(e){return{re:Math.floor(e.re),im:Math.floor(e.im)}}function C8(e){return{re:Math.ceil(e.re),im:Math.ceil(e.im)}}function S8(e){const t=n=>n>=0?Math.floor(n+.5):-Math.floor(-n+.5);return{re:t(e.re),im:t(e.im)}}function N8(e){return{re:Math.trunc(e.re),im:Math.trunc(e.im)}}function A8(e){if(e.re===0&&e.im===0)return{re:0,im:0};const t=Math.hypot(e.re,e.im);return{re:e.re/t,im:e.im/t}}const E8=Qn({name:"cos",cFnReal:"cos",jsFn:Math.cos,signRule:()=>"unknown",complex:{cFnComplex:"mtoc2_ccos",jsFnComplex:bk}}),I8=Qn({name:"sin",cFnReal:"sin",jsFn:Math.sin,signRule:()=>"unknown",complex:{cFnComplex:"mtoc2_csin",jsFnComplex:xk}}),F8={name:"rand",transfer(e,t){if(t>1)throw new W(`'rand' does not support multi-output (nargout=${t})`);if(e.length!==0)throw new W(`JS-JIT 'rand' supports only the scalar form rand() so far (got ${e.length} arg(s)); matrix/seed forms run in the interpreter`);return[Be("nonneg")]},emitJs(){return"$rand()"},call(){return[Ps()]}},j8=Qn({name:"tan",cFnReal:"tan",jsFn:Math.tan,signRule:()=>"unknown",complex:{cFnComplex:"mtoc2_ctan",jsFnComplex:x8}}),R8=Qn({name:"atan",cFnReal:"atan",jsFn:Math.atan,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_catan",jsFnComplex:M8}}),L8=Qn({name:"sinh",cFnReal:"sinh",jsFn:Math.sinh,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_csinh",jsFnComplex:b8}}),D8=Qn({name:"cosh",cFnReal:"cosh",jsFn:Math.cosh,signRule:()=>"positive",complex:{cFnComplex:"mtoc2_ccosh",jsFnComplex:k8}}),T8=Qn({name:"tanh",cFnReal:"tanh",jsFn:Math.tanh,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_ctanh",jsFnComplex:v8}}),P8=Qn({name:"asinh",cFnReal:"asinh",jsFn:Math.asinh,signRule:e=>e.sign}),B8=Qn({name:"exp",cFnReal:"exp",jsFn:Math.exp,signRule:()=>"positive",complex:{cFnComplex:"mtoc2_cexp",jsFnComplex:w8}}),um=Qn({name:"abs",cFnReal:"fabs",jsFn:Math.abs,signRule:e=>e.sign==="positive"||e.sign==="negative"||e.sign==="nonzero"?"positive":"nonneg"}),q8={name:"abs",transfer(e,t){if(e.length!==1)throw new le(`'abs' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'abs' does not support multi-output (nargout=${t})`);pr(e[0],"'abs' arg");const n=e[0];if(n.isComplex){if(De(n)){const o=An(n);if(o!==void 0){const i=Math.hypot(o.re,o.im);if(Number.isFinite(i))return[Be(ft(i),i)]}return[Be("nonneg")]}const r=rn(n);if(r!==void 0&&n.shape!==void 0){const o=Dt(n.shape);if(o<=wt){const i=new Float64Array(o);for(let a=0;a<o;a++)i[a]=Math.hypot(r.re[a],r.im[a]);return[et(n.shape,i)]}}const s=Zt(n.dims.slice());return s.sign="nonneg",[s]}return um.transfer(e,t)},emitC(e){const{argsC:t,argTypes:n,useRuntime:r}=e,s=n[0];return s.isComplex?(r("mtoc2_cscalar"),qe(s)?(r("mtoc2_tensor_unary_complex_math"),`mtoc2_tensor_abs_complex(${t[0]})`):`mtoc2_cabs(${t[0]})`):ul(um)(e)},emitJs(e){const{argsJs:t,argTypes:n,useRuntime:r}=e,s=n[0];return s.isComplex?qe(s)?(r("mtoc2_tensor_unary_complex_math"),r("mtoc2_cscalar"),`mtoc2_tensor_abs_complex(${t[0]})`):(r("mtoc2_cscalar"),`mtoc2_cabs(${t[0]})`):ko(um)(e)},call(e){const t=e.argTypes[0];if(t.isComplex){if(qe(t))return[tD(e.args[0])];const n=e.args[0],r=un(n)?n:{re:Number(n),im:0};return[wb(r)]}return fl(um)(e)},elementwise:!0},z8=Qn({name:"sign",cFnReal:"mtoc2_signum",jsFn:Math.sign,signRule:e=>e.sign,complex:{cFnComplex:"mtoc2_csign",jsFnComplex:A8}}),V8=Qn({name:"floor",cFnReal:"floor",jsFn:Math.floor,signRule:cm(!0,!1),complex:{cFnComplex:"mtoc2_cfloor",jsFnComplex:$8}}),U8=Qn({name:"ceil",cFnReal:"ceil",jsFn:Math.ceil,signRule:cm(!1,!0),complex:{cFnComplex:"mtoc2_cceil",jsFnComplex:C8}});function W8(e){return Math.sign(e)*Math.round(Math.abs(e))}const X8=Qn({name:"round",cFnReal:"mtoc2_round_half_away",jsFn:W8,jsExpr:e=>`(Math.sign(${e}) * Math.round(Math.abs(${e})))`,signRule:cm(!0,!0),complex:{cFnComplex:"mtoc2_cround",jsFnComplex:S8}}),H8=Qn({name:"fix",cFnReal:"trunc",jsFn:Math.trunc,jsExpr:e=>`Math.trunc(${e})`,signRule:cm(!0,!0),complex:{cFnComplex:"mtoc2_cfix",jsFnComplex:N8}}),Y8=Qn({name:"sqrt",cFnReal:"sqrt",jsFn:e=>Math.sqrt(e),signRule:e=>mR(e.sign)?"positive":"nonneg",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_csqrt",jsFnComplex:g8,liftOnDomainMiss:!0}});function fm(e){if(e.length<2)return 2;const t=e[1];if(t.kind==="Char"||t.kind==="String"){if(t.exact===void 0)throw new W("'norm' order arg must be a literal; non-literal text is not supported");const r=t.exact.toLowerCase();if(r==="fro")return 2;if(r==="inf")return 1/0;throw new le(`'norm' string order arg must be 'fro' or 'inf' (got '${t.exact}')`)}if(!Me(t)||t.isComplex||!De(t))throw new le(`'norm' order arg must be a real scalar or 'fro' / 'inf' (got ${ze(t)})`);const n=Je(t);if(n!==void 0)return n}function J8(e){if(De(e))return"scalar";if(!(e.dims.length===2&&(e.dims[0].kind==="exact"&&e.dims[0].value===1||e.dims[1].kind==="exact"&&e.dims[1].value===1)))throw new W(`'norm' input must be a scalar or vector (got ${ze(e)}); matrix-norm forms are not yet supported`);return"vector"}function Z8(e,t){if(t.length===0)return 0;let n;if(e===1/0){n=0;for(let r=0;r<t.length;r++){const s=Math.abs(t[r]);s>n&&(n=s)}}else if(e===-1/0){n=Math.abs(t[0]);for(let r=1;r<t.length;r++){const s=Math.abs(t[r]);s<n&&(n=s)}}else if(e===1){n=0;for(let r=0;r<t.length;r++)n+=Math.abs(t[r])}else if(e===2){let r=0;for(let s=0;s<t.length;s++)r+=t[s]*t[s];n=Math.sqrt(r)}else{let r=0;for(let s=0;s<t.length;s++)r+=Math.pow(Math.abs(t[s]),e);n=Math.pow(r,1/e)}return Number.isFinite(n)?n:void 0}function K8(e,t,n){if(t.length===0)return 0;const r=o=>Math.hypot(t[o],n[o]);let s;if(e===1/0){s=0;for(let o=0;o<t.length;o++){const i=r(o);i>s&&(s=i)}}else if(e===-1/0){s=r(0);for(let o=1;o<t.length;o++){const i=r(o);i<s&&(s=i)}}else if(e===2){let o=0;for(let i=0;i<t.length;i++)o+=t[i]*t[i]+n[i]*n[i];s=Math.sqrt(o)}else if(e===1){s=0;for(let o=0;o<t.length;o++)s+=r(o)}else{let o=0;for(let i=0;i<t.length;i++)o+=Math.pow(r(i),e);s=Math.pow(o,1/e)}return Number.isFinite(s)?s:void 0}function G8(e){return e===1/0?"INFINITY":e===-1/0?"-INFINITY":String(e)}function Q8(e){return e===1/0?"Infinity":e===-1/0?"-Infinity":String(e)}const O8={name:"norm",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'norm' expects 1..2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'norm' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'norm' arg must be a real or complex numeric (got ${ze(n)})`);if(n.elem!=="double")throw new le(`'norm' arg must be double (got ${n.elem})`);const r=J8(n),s=fm(e);if(r==="scalar"){if(!n.isComplex){const i=Je(n);if(i!==void 0){const a=Math.abs(i);if(Number.isFinite(a))return[Be(ft(a),a)]}return[Be("nonneg")]}const o=An(n);if(o!==void 0){const i=Math.hypot(o.re,o.im);if(Number.isFinite(i))return[Be(ft(i),i)]}return[Be("nonneg")]}if(s!==void 0)if(n.isComplex){const o=rn(n);if(o!==void 0){const i=K8(s,o.re,o.im);if(i!==void 0)return[Be(ft(i),i)]}}else{const o=Mt(n);if(o!==void 0){const i=Z8(s,o);if(i!==void 0)return[Be(ft(i),i)]}}return[Be("nonneg")]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];if(n("mtoc2_cscalar"),qe(r)){n("mtoc2_tensor_norm");const s=fm(t);if(s===2&&t.length<2)return r.isComplex?`mtoc2_norm2_complex(${e[0]})`:`mtoc2_norm2_real(${e[0]})`;const o=s!==void 0?G8(s):`(double)(${e[1]})`;return r.isComplex?`mtoc2_norm_p_complex(${e[0]}, ${o})`:`mtoc2_norm_p_real(${e[0]}, ${o})`}return r.isComplex?`mtoc2_cabs(${e[0]})`:`fabs(${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];if(qe(r)){n("mtoc2_tensor_norm");const s=fm(t);if(s===2&&t.length<2)return r.isComplex?`mtoc2_norm2_complex(${e[0]})`:`mtoc2_norm2_real(${e[0]})`;const o=s!==void 0?Q8(s):e[1];return r.isComplex?`mtoc2_norm_p_complex(${e[0]}, ${o})`:`mtoc2_norm_p_real(${e[0]}, ${o})`}return r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cabs(${e[0]})`):`Math.abs(${e[0]})`},call({args:e,argTypes:t}){const n=t[0];if(qe(n)){const s=fm(t),o=s!==void 0?s:Number(e[1]);return o===2&&t.length<2?[(n.isComplex?Cb:$b)(e[0])]:[(n.isComplex?W5:U5)(e[0],o)]}if(n.isComplex){const s=e[0],o=un(s)?s:{re:Number(s),im:0};return[wb(o)]}const r=typeof e[0]=="number"?e[0]:Number(e[0]);return[Math.abs(r)]}};function vk(e,t){if(!Me(e))throw new le(`${t} must be a numeric (got ${ze(e)})`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);return e}function Xr(e){if(De(e))return!0;if(e.dims.length!==2)return!1;const t=e.dims[0].kind==="exact"&&e.dims[0].value===1,n=e.dims[1].kind==="exact"&&e.dims[1].value===1;return t||n}function Mk(e){return e.shape!==void 0?Dt(e.shape):void 0}function e7(e){if(!(e.shape===void 0||e.shape.length!==2))return e.shape[1]}function $k(e){return Number.isFinite(e)?Be(ft(e),e):Be()}function t7(e,t,n,r){let s=0,o=0;for(let i=0;i<e.length;i++){const a=e[i],c=t!==void 0?t[i]:0,l=n[i],u=r!==void 0?r[i]:0;s+=a*l+c*u,o+=a*u-c*l}return{re:s,im:o}}const n7={name:"dot",transfer(e,t){if(e.length!==2)throw new le(`'dot' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'dot' does not support multi-output (nargout=${t})`);const n=vk(e[0],"'dot' arg 1"),r=vk(e[1],"'dot' arg 2"),s=n.isComplex||r.isComplex;if(De(n)&&De(r)){if(s){const l=Us(n),u=Us(r);return l!==void 0&&u!==void 0?[_t({re:l.re*u.re+l.im*u.im,im:l.re*u.im-l.im*u.re})]:[_t()]}const a=Je(n),c=Je(r);return a!==void 0&&c!==void 0?[$k(a*c)]:[Be()]}const o=Xr(n),i=Xr(r);if(o&&i){const a=Mk(n),c=Mk(r);if(a!==void 0&&c!==void 0&&a!==c)throw new le(`'dot' vectors must be same length (got ${a} and ${c})`);if(s){const f=n.isComplex?rn(n)?.re:Mt(n),h=n.isComplex?rn(n)?.im:void 0,m=r.isComplex?rn(r)?.re:Mt(r),p=r.isComplex?rn(r)?.im:void 0;if(f!==void 0&&m!==void 0&&f.length===m.length&&f.length<=wt){const d=t7(f,h,m,p);return[_t(d)]}return[_t()]}const l=Mt(n),u=Mt(r);if(l!==void 0&&u!==void 0&&l.length===u.length&&l.length<=wt){let f=0;for(let h=0;h<l.length;h++)f+=l[h]*u[h];return[$k(f)]}return[Be()]}if(!o&&!i&&n.shape!==void 0&&r.shape!==void 0&&n.shape.length===2&&r.shape.length===2&&n.shape[0]===r.shape[0]&&n.shape[1]===r.shape[1]){const a=e7(n)??0;if(s){const u=n.isComplex?rn(n)?.re:Mt(n),f=n.isComplex?rn(n)?.im:void 0,h=r.isComplex?rn(r)?.re:Mt(r),m=r.isComplex?rn(r)?.im:void 0;if(u!==void 0&&h!==void 0&&u.length===h.length&&u.length<=wt){const p=n.shape[0],d=new Float64Array(a),g=new Float64Array(a);for(let w=0;w<a;w++){let _=0,y=0;for(let b=0;b<p;b++){const k=w*p+b,M=u[k],$=f!==void 0?f[k]:0,N=h[k],E=m!==void 0?m[k]:0;_+=M*N+$*E,y+=M*E-$*N}d[w]=_,g[w]=y}return[Ut([1,a],{re:d,im:g})]}return[Ut([1,a])]}const c=Mt(n),l=Mt(r);if(c!==void 0&&l!==void 0&&c.length===l.length&&c.length<=wt){const u=n.shape[0],f=new Float64Array(a);for(let h=0;h<a;h++){let m=0;for(let p=0;p<u;p++){const d=h*u+p;m+=c[d]*l[d]}f[h]=m}return[et([1,a],f)]}return[et([1,a])]}throw new W(`'dot' supports two vectors of the same length, or two matrices of the same shape (got ${ze(n)} and ${ze(r)})`)},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=t[1],o=r.isComplex||s.isComplex;if(qe(r)&&qe(s))return n("mtoc2_dot_real"),o&&n("mtoc2_cscalar"),`${o?Xr(r)||Xr(s)?"mtoc2_dot_complex":"mtoc2_dot_complex_matrix":Xr(r)||Xr(s)?"mtoc2_dot_real":"mtoc2_dot_real_matrix"}(${e[0]}, ${e[1]})`;if(o){n("mtoc2_cscalar");const i=r.isComplex?e[0]:`mtoc2_cmake((double)(${e[0]}), 0.0)`,a=s.isComplex?e[1]:`mtoc2_cmake((double)(${e[1]}), 0.0)`;return`mtoc2_cmul(mtoc2_cconj(${i}), ${a})`}return`((${e[0]}) * (${e[1]}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0],s=t[1],o=r.isComplex||s.isComplex;if(qe(r)&&qe(s))return n("mtoc2_dot_real"),`${o?Xr(r)||Xr(s)?"mtoc2_dot_complex":"mtoc2_dot_complex_matrix":Xr(r)||Xr(s)?"mtoc2_dot_real":"mtoc2_dot_real_matrix"}(${e[0]}, ${e[1]})`;if(o){n("mtoc2_cscalar");const i=r.isComplex?e[0]:`mtoc2_cmake(${e[0]}, 0)`,a=s.isComplex?e[1]:`mtoc2_cmake(${e[1]}, 0)`;return`mtoc2_cmul(mtoc2_cconj(${i}), ${a})`}return`((${e[0]}) * (${e[1]}))`},call({args:e,argTypes:t}){const n=t[0],r=t[1],s=n.isComplex||r.isComplex;if(qe(n)&&qe(r))return s?Xr(n)||Xr(r)?[A6(e[0],e[1])]:[E6(e[0],e[1])]:Xr(n)||Xr(r)?[S6(e[0],e[1])]:[N6(e[0],e[1])];const o=e[0],i=e[1];if(s){const l=h=>un(h)?h:{re:typeof h=="number"?h:Number(h),im:0},u=l(o),f=l(i);return[{re:u.re*f.re+u.im*f.im,im:u.re*f.im-u.im*f.re}]}const a=typeof o=="number"?o:Number(o),c=typeof i=="number"?i:Number(i);return[a*c]}},y0=1e-6;function r7(e){if(!Me(e))throw new le(`'uniquetol' first arg must be numeric (got ${ze(e)})`);if(e.isComplex)throw new W("'uniquetol' on complex inputs is not yet supported");if(e.elem!=="double"&&e.elem!=="logical")throw new le(`'uniquetol' first arg must be double or logical (got ${e.elem})`);return e}function s7(e){if(!Me(e)||e.isComplex||!De(e))throw new le(`'uniquetol' tol arg must be a real scalar (got ${ze(e)})`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`'uniquetol' tol arg must be double or logical (got ${e.elem})`)}function mm(e){if(e.dims.length<2)return!1;const t=e.dims[0];return t.kind==="exact"&&t.value===1}const o7={name:"uniquetol",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'uniquetol' expects 1..2 arg(s), got ${e.length}`);if(t!==1)throw new W("'uniquetol' multi-output form ([c, ia, ic] = uniquetol(...)) is not yet supported");const n=r7(e[0]);if(e.length===2&&s7(e[1]),De(n)){const o=Je(n);return o!==void 0&&Number.isFinite(o)?[Be(ft(o),o)]:[Be()]}const s=mm(n)?[nn,{kind:"unknown"}]:[{kind:"unknown"},nn];return[Zt(s)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];if(De(r))return`(${e[0]})`;n("mtoc2_uniquetol_real");const s=t.length===2?`(double)(${e[1]})`:`${y0}`,o=mm(r)?1:0;return`mtoc2_uniquetol_real(${e[0]}, ${s}, ${o})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];if(De(r))return`(${e[0]})`;n("mtoc2_uniquetol_real");const s=t.length===2?e[1]:String(y0),o=mm(r)?1:0;return`mtoc2_uniquetol_real(${e[0]}, ${s}, ${o})`},call({args:e,argTypes:t}){const n=t[0];if(De(n))return[typeof e[0]=="number"?e[0]:Number(e[0])];let r=y0;if(t.length===2){const o=t[1],i=Je(o);r=i!==void 0?i:Number(e[1])}const s=mm(n)?1:0;return[kD(e[0],r,s)]}},i7=Qn({name:"log",cFnReal:"log",jsFn:Math.log,signRule:()=>"unknown",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_clog",jsFnComplex:lm,liftOnDomainMiss:!0}}),a7=Qn({name:"log2",cFnReal:"log2",jsFn:Math.log2,signRule:()=>"unknown",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_clog2",jsFnComplex:_8,liftOnDomainMiss:!0}}),c7=Qn({name:"log10",cFnReal:"log10",jsFn:Math.log10,signRule:()=>"unknown",realDomainOk:e=>Ri(e.sign),complex:{cFnComplex:"mtoc2_clog10",jsFnComplex:y8,liftOnDomainMiss:!0}});function l7(e,t){if(t===0)return e;let n=e%t;return n!==0&&n<0!=t<0&&(n+=t),n}function u7(e,t){return t.sign}function f7(e,t){return`(((a, b) => { if (b===0) return a; let r = a % b; if (r !== 0 && (r < 0) !== (b < 0)) r += b; return r; })(${e}, ${t}))`}const m7=Of({name:"mod",cFn:"mtoc2_mod_real",helperBase:"mod",commutative:!1,fold:l7,jsScalarExpr:f7,signRule:u7,runtimeDep:"mtoc2_tensor_elemwise_real_fn"}),h7=Of({name:"rem",cFn:"fmod",helperBase:"rem",commutative:!1,fold:(e,t)=>e%t,jsScalarExpr:(e,t)=>`((${e}) % (${t}))`,signRule:e=>e.sign,runtimeDep:"mtoc2_tensor_elemwise_real_fn"}),p7=Of({name:"atan2",cFn:"atan2",helperBase:"atan2",commutative:!1,fold:Math.atan2,jsScalarExpr:(e,t)=>`Math.atan2(${e}, ${t})`,signRule:()=>"unknown",runtimeDep:"mtoc2_tensor_elemwise_real_fn"}),d7=Of({name:"hypot",cFn:"hypot",helperBase:"hypot",commutative:!0,fold:Math.hypot,jsScalarExpr:(e,t)=>`Math.hypot(${e}, ${t})`,signRule:()=>"nonneg",runtimeDep:"mtoc2_tensor_elemwise_real_fn"});function Ck(e,t){const n=Je(e);if(n===void 0||!Number.isInteger(n))throw new W(`'besselh' ${t} must be a compile-time integer (got non-exact or non-integer)`);return n}const g7={name:"besselh",transfer(e,t){if(e.length!==3)throw new le(`'besselh' expects 3 arg(s), got ${e.length}`);if(t!==1)throw new W(`'besselh' does not support multi-output (nargout=${t})`);for(let a=0;a<3;a++){if(!Me(e[a]))throw new le(`'besselh' arg ${a+1} must be a real numeric (got ${ze(e[a])})`);if(e[a].isComplex)throw new W("'besselh' with complex args is not yet supported")}const n=e[0],r=e[1],s=e[2],o=Ck(n,"arg 1 (nu)"),i=Ck(r,"arg 2 (kind)");if(o!==0&&o!==1)throw new W(`'besselh' supports only nu in {0, 1} today (got ${o})`);if(i!==1)throw new W(`'besselh' supports only kind == 1 today (got ${i})`);if(s.elem!=="double")throw new le(`'besselh' arg 3 (x) must be double (got ${s.elem})`);return qe(s)?[mr(s.dims.slice())]:[_t()]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_besselh"),n("mtoc2_cscalar");const r=t[0].exact,s=t[2];return qe(s)?r===0?`mtoc2_tensor_besselh0(${e[2]})`:`mtoc2_tensor_besselh1(${e[2]})`:r===0?`mtoc2_besselh0_scalar(${e[2]})`:`mtoc2_besselh1_scalar(${e[2]})`},emitJs(){throw new W("'besselh' is not yet implemented for the js-aot backend (needs a JS port of POSIX j0/j1/y0/y1; see numbl/helpers/bessel.ts)")},call(){throw new W("'besselh' is not yet implemented for the interpreter (needs a JS port of POSIX j0/j1/y0/y1; see numbl/helpers/bessel.ts)")}},hm=100;function x0(e,t){if(!Me(e))throw new le(`${t} must be a scalar real numeric (got ${e.kind})`);if(e.isComplex)throw new le(`${t} must be real (got complex)`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);if(!De(e))throw new le(`${t} must be a scalar (got tensor)`)}function w7(e,t,n){const r=new Float64Array(n);if(n===0)return r;if(n===1)return r[0]=t,r;r[0]=e,r[n-1]=t;for(let s=1;s<n-1;s++)r[s]=e+(t-e)*s/(n-1);return(n&1)===1&&!Number.isFinite(e)&&!Number.isFinite(t)&&Math.sign(e)!==Math.sign(t)&&(r[(n-1)/2]=0),r}const _7={name:"linspace",transfer(e,t){if(e.length<2||e.length>3)throw new le(`'linspace' expects 2..3 arg(s), got ${e.length}`);if(t!==1)throw new W(`'linspace' does not support multi-output (nargout=${t})`);x0(e[0],"'linspace' arg 1"),x0(e[1],"'linspace' arg 2"),e.length===3&&x0(e[2],"'linspace' arg 3");const n=Je(e[0]),r=Je(e[1]),s=e.length===3?Je(e[2]):hm;if(s!==void 0){const i=Math.round(s);if(i<=0)return[et([1,0])];if(i===1)return r!==void 0&&Number.isFinite(r)?[Be(ft(r),r)]:[Be()];if(n!==void 0&&r!==void 0&&Number.isFinite(n)&&Number.isFinite(r)&&i<=wt){const a=w7(n,r,i);let c=!0;for(let l=0;l<a.length;l++)if(!Number.isFinite(a[l])){c=!1;break}if(c)return[et([1,i],a)]}return[et([1,i])]}return[Zt([nn,{kind:"unknown"}])]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_linspace");const r=e[0],s=e[1],o=t.length===3?e[2]:`${hm}.0`;if(t.length===3){const i=Je(t[2]);if(i!==void 0&&Math.round(i)===1)return`((${r}), (${s}))`}return`mtoc2_tensor_linspace((double)(${r}), (double)(${s}), (long)lround(${o}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_linspace");const r=e[0],s=e[1],o=t.length===3?e[2]:String(hm);if(t.length===3){const i=Je(t[2]);if(i!==void 0&&Math.round(i)===1)return`((${r}), (${s}))`}return`mtoc2_tensor_linspace(${r}, ${s}, Math.round(${o}))`},call({args:e,argTypes:t}){const n=typeof e[0]=="number"?e[0]:Number(e[0]),r=typeof e[1]=="number"?e[1]:Number(e[1]);let s=hm;if(t.length===3){const o=typeof e[2]=="number"?e[2]:Number(e[2]);if(s=Math.round(o),s===1)return[r]}return[j5(n,r,s)]}},pm=50;function b0(e,t){if(!Me(e))throw new le(`${t} must be a scalar real numeric (got ${e.kind})`);if(e.isComplex)throw new le(`${t} must be real (got complex)`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);if(!De(e))throw new le(`${t} must be a scalar (got tensor)`)}const y7=()=>Zt([nn,{kind:"unknown"}]),x7={name:"logspace",transfer(e,t){if(e.length<2||e.length>3)throw new le(`'logspace' expects 2..3 arg(s), got ${e.length}`);if(t!==1)throw new W(`'logspace' does not support multi-output (nargout=${t})`);b0(e[0],"'logspace' arg 1"),b0(e[1],"'logspace' arg 2"),e.length===3&&b0(e[2],"'logspace' arg 3");const n=e.length===3?Je(e[2]):pm;if(n!==void 0){const r=Math.round(n);if(r<=0)return[et([1,0])];if(r>=2)return[et([1,r])]}return[y7()]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_logspace");const r=e[0],s=e[1],o=t.length===3?e[2]:`${pm}.0`;return`mtoc2_tensor_logspace((double)(${r}), (double)(${s}), (long)lround(${o}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_logspace");const r=e[0],s=e[1],o=t.length===3?e[2]:String(pm);return`mtoc2_tensor_logspace(${r}, ${s}, Math.round(${o}))`},call({args:e,argTypes:t}){const n=typeof e[0]=="number"?e[0]:Number(e[0]),r=typeof e[1]=="number"?e[1]:Number(e[1]);let s=pm;if(t.length===3){const o=typeof e[2]=="number"?e[2]:Number(e[2]);s=Math.round(o)}return[D5(n,r,s)]}},b7={name:"real",transfer(e,t){if(e.length!==1)throw new le(`'real' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'real' does not support multi-output (nargout=${t})`);pr(e[0],"'real' arg");const n=e[0];if(qe(n)){const s=Zt(n.dims.slice());return n.isComplex||(s.sign=n.sign),[s]}if(n.isComplex){const s=An(n);return s!==void 0?[Be(ft(s.re),s.re)]:[Be()]}const r=Je(n);return r!==void 0?[Be(ft(r),r)]:[Be(n.sign)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_real_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_creal(${e[0]})`):`(${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_real_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_creal(${e[0]})`):`(${e[0]})`},call({args:e,argTypes:t}){const n=t[0];return qe(n)?n.isComplex?[eD(e[0])]:[e[0]]:n.isComplex?[e[0].re]:[e[0]]},elementwise:!0},k7={name:"imag",transfer(e,t){if(e.length!==1)throw new le(`'imag' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'imag' does not support multi-output (nargout=${t})`);pr(e[0],"'imag' arg");const n=e[0];if(qe(n)){const r=Zt(n.dims.slice());return n.isComplex||(r.sign="zero"),[r]}if(n.isComplex){const r=An(n);return r!==void 0?[Be(ft(r.im),r.im)]:[Be()]}return[Be("zero",0)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_imag_complex(${e[0]})`):(n("mtoc2_tensor_elemwise_real"),`mtoc2_tensor_times_ts(${e[0]}, 0.0)`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cimag(${e[0]})`):"0.0"},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_imag_complex(${e[0]})`):(n("mtoc2_tensor_elemwise_real"),`mtoc2_tensor_times_ts(${e[0]}, 0)`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cimag(${e[0]})`):"0"},call({args:e,argTypes:t}){const n=t[0];if(qe(n)){if(n.isComplex)return[OL(e[0])];const r=e[0];return[{mtoc2Tag:"tensor",shape:r.shape.slice(),data:new Float64Array(r.data.length)}]}return n.isComplex?[e[0].im]:[0]},elementwise:!0},v7={name:"conj",transfer(e,t){if(e.length!==1)throw new le(`'conj' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'conj' does not support multi-output (nargout=${t})`);pr(e[0],"'conj' arg");const n=e[0];if(!qe(n)){if(n.isComplex){const i=An(n);return i!==void 0?[_t({re:i.re,im:-i.im})]:[_t()]}const o=Je(n);return o!==void 0?[Be(ft(o),o)]:[Be(n.sign)]}if(n.isComplex){const o=rn(n);if(o!==void 0&&n.shape!==void 0&&Dt(n.shape)<=wt){const a=new Float64Array(o.re.length),c=new Float64Array(o.im.length);for(let l=0;l<o.re.length;l++)a[l]=o.re[l],c[l]=-o.im[l];return[Ut(n.shape,{re:a,im:c})]}return[mr(n.dims.slice())]}const r=Mt(n);if(r!==void 0&&n.shape!==void 0)return[et(n.shape,r)];const s=Zt(n.dims.slice());return s.sign=n.sign,[s]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_conj_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cconj(${e[0]})`):`(${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_unary_complex_math"),n("mtoc2_cscalar"),`mtoc2_tensor_conj_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cconj(${e[0]})`):`(${e[0]})`},call({args:e,argTypes:t}){const n=t[0];if(qe(n))return n.isComplex?[QL(e[0])]:[e[0]];if(n.isComplex){const r=e[0];return[{re:r.re,im:-r.im}]}return[e[0]]},elementwise:!0},M7={name:"angle",transfer(e,t){if(e.length!==1)throw new le(`'angle' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'angle' does not support multi-output (nargout=${t})`);pr(e[0],"'angle' arg");const n=e[0];if(qe(n))throw new W("'angle' on a tensor is not yet supported");if(n.isComplex){const s=An(n);if(s!==void 0){const o=Math.atan2(s.im,s.re);if(Number.isFinite(o))return[Be(ft(o),o)]}return[Be()]}const r=Je(n);if(r!==void 0){const s=Math.atan2(0,r);if(Number.isFinite(s))return[Be(ft(s),s)]}return[Be()]},emitC({argsC:e,argTypes:t,useRuntime:n}){return t[0].isComplex?(n("mtoc2_cscalar"),`mtoc2_cangle(${e[0]})`):`atan2(0.0, ${e[0]})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){return t[0].isComplex?(n("mtoc2_cscalar"),`mtoc2_cangle(${e[0]})`):`Math.atan2(0, ${e[0]})`},call({args:e,argTypes:t}){if(t[0].isComplex){const s=e[0];return[Math.atan2(s.im,s.re)]}const r=typeof e[0]=="number"?e[0]:Number(e[0]);return[Math.atan2(0,r)]}};function Sk(e,t,n,r){const s=Number.isFinite(t)?String(t):t>0?"Infinity":t<0?"-Infinity":"NaN";return{name:e,transfer(o,i){if(o.length!==0)throw new le(`'${e}' expects 0 arg(s), got ${o.length}`);if(i!==1)throw new W(`'${e}' does not support multi-output (nargout=${i})`);return[Be(n,t)]},emitC(){return r},emitJs(){return s},call(){return[t]},elementwise:!0}}function dm(e,t,n,r){const s=bl(e,t,"mtoc2_tensor_fill_nd","mtoc2_tensor_fill_square",{minArgs:0,cFillValue:r});return{name:e,transfer(o,i){if(o.length===0){if(i!==1)throw new W(`'${e}' does not support multi-output (nargout=${i})`);return[Be(n,t)]}return s.transfer(o,i)},emitC(o){return o.argTypes.length===0?r:ul(s)(o)},emitJs(o){return o.argTypes.length===0?Number.isFinite(t)?String(t):t>0?"Infinity":"NaN":ko(s)(o)},call(o){return o.argTypes.length===0?[t]:fl(s)(o)},elementwise:!0}}const $7=Sk("pi",Math.PI,"positive","3.141592653589793"),C7=Sk("eps",Number.EPSILON,"positive","2.220446049250313e-16"),S7=dm("Inf",1/0,"positive","INFINITY"),N7=dm("inf",1/0,"positive","INFINITY"),A7=dm("NaN",NaN,"unknown","NAN"),E7=dm("nan",NaN,"unknown","NAN");function gm(e,t,n){const r={kind:"Numeric",elem:"logical",isComplex:!1,dims:e,sign:"nonneg"};return t!==void 0&&(r.shape=t.slice()),n!==void 0&&(r.exact=n),r}const I7={name:"not",transfer(e,t){if(e.length!==1)throw new le(`'not' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'not' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'~' / 'not' arg must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'~' / 'not' arg must be a real double or logical (got ${n.elem})`);if(De(n)){if(n.isComplex){const o=An(n);return o!==void 0?[at(o.re===0&&o.im===0)]:[at()]}const s=Je(n);return s!==void 0?[at(s===0)]:[at()]}if(n.isComplex){const s=rn(n);if(n.shape!==void 0&&s!==void 0){const o=Dt(n.shape);if(o<=wt){const i=new Float64Array(o);for(let a=0;a<o;a++)i[a]=s.re[a]===0&&s.im[a]===0?1:0;return[gm(n.dims,n.shape,i)]}}return[gm(n.dims,n.shape)]}const r=Mt(n);if(n.shape!==void 0&&r!==void 0&&Dt(n.shape)<=wt){const o=new Float64Array(r.length);for(let i=0;i<r.length;i++)o[i]=r[i]===0?1:0;return[gm(n.dims,n.shape,o)]}return[gm(n.dims,n.shape)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not_complex(${e[0]})`):(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`(!mtoc2_cnonzero(${e[0]}))`):`(!(${e[0]}))`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];return qe(r)?r.isComplex?(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not_complex(${e[0]})`):(n("mtoc2_tensor_logical_real"),`mtoc2_tensor_not(${e[0]})`):r.isComplex?(n("mtoc2_cscalar"),`(!mtoc2_cnonzero(${e[0]}))`):r.elem==="logical"?`(!(${e[0]}))`:`((${e[0]}) === 0)`},call({args:e,argTypes:t}){const n=t[0];if(qe(n))return n.isComplex?[L5(e[0])]:[R5(e[0])];if(n.isComplex){const s=e[0],o=un(s)?s:{re:Number(s),im:0};return[!VR(o)]}return[(typeof e[0]=="number"?e[0]:Number(e[0]))===0]}};function Nk(e,t,n){if(!Me(e))throw new le(`${t} must be a real or complex scalar (got ${ze(e)}); '${n}' requires scalar operands (numbl accepts tensors via toBool, but mtoc2 follows MATLAB)`);if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be a real double or logical (got ${e.elem})`);if(!De(e))throw new le(`${t} must be a scalar (got ${ze(e)}); '${n}' requires scalar operands (numbl accepts tensors via toBool, but mtoc2 follows MATLAB — use elementwise '|' / '&' when added)`)}function Ak(e){if(!Me(e))return;if(e.isComplex){const n=Us(e);return n===void 0?void 0:n.re!==0||n.im!==0}const t=Je(e);if(t!==void 0)return t!==0}function wm(e,t,n){const r=n==="or"?"||":"&&";return{name:e,transfer(s,o){if(s.length!==2)throw new le(`'${e}' expects 2 arg(s), got ${s.length}`);if(o!==1)throw new W(`'${e}' does not support multi-output (nargout=${o})`);Nk(s[0],`'${t}' left operand`,t),Nk(s[1],`'${t}' right operand`,t);const i=Ak(s[0]),a=Ak(s[1]);return n==="or"?i===!0?[at(!0)]:i!==void 0&&a!==void 0?[at(a)]:[at()]:i===!1?[at(!1)]:i!==void 0&&a!==void 0?[at(a)]:[at()]},emitC({argsC:s,argTypes:o,useRuntime:i}){(o[0].isComplex||o[1].isComplex)&&i("mtoc2_cscalar");const c=o[0].isComplex?`mtoc2_cnonzero(${s[0]})`:`(${s[0]})`,l=o[1].isComplex?`mtoc2_cnonzero(${s[1]})`:`(${s[1]})`;return`(${c} ${r} ${l})`},emitJs({argsJs:s,argTypes:o,useRuntime:i}){const a=o[0],c=o[1];(a.isComplex||c.isComplex)&&i("mtoc2_cscalar");const u=(m,p)=>m.isComplex?`mtoc2_cnonzero(${p})`:m.elem==="logical"?`(${p})`:`((${p}) !== 0)`,f=u(a,s[0]),h=u(c,s[1]);return`(${f} ${r} ${h})`},call({args:s,argTypes:o}){const i=o[0],a=o[1],c=(f,h)=>{if(h){const p=f;return p.re!==0||p.im!==0}return(typeof f=="number"?f:Number(f))!==0},l=c(s[0],i.isComplex),u=c(s[1],a.isComplex);return[n==="or"?l||u:l&&u]}}}const F7=wm("oror","||","or"),j7=wm("andand","&&","and"),R7=wm("or","|","or"),L7=wm("and","&","and");function Ek(e,t){if(!Me(e))throw new le(`${t} must be numeric (got ${e.kind})`);if(e.isComplex)throw new W("'xor' on complex operands is not JIT-compiled");if(!De(e))throw new W("'xor' on tensor operands is not JIT-compiled");if(e.elem!=="double"&&e.elem!=="logical")throw new le(`${t} must be double or logical (got ${e.elem})`);return e}const D7={name:"xor",transfer(e,t){if(e.length!==2)throw new le(`'xor' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'xor' does not support multi-output (nargout=${t})`);const n=Ek(e[0],"'xor' arg 1"),r=Ek(e[1],"'xor' arg 2"),s=Je(n),o=Je(r);return s!==void 0&&o!==void 0?[at(s!==0!=(o!==0))]:[at()]},emitC({argsC:e}){return`(((${e[0]}) != 0) != ((${e[1]}) != 0))`},emitJs({argsJs:e}){return`((Number(${e[0]}) !== 0) !== (Number(${e[1]}) !== 0))`},call({args:e}){const t=Number(e[0]),n=Number(e[1]);return[t!==0!=(n!==0)]}};function _m(e,t){return!ji(e)&&!al(e)?!1:cl(e,t)!==void 0}function ym(e){if(!xo(e)&&!Jo(e))throw new le(`'isfield' second arg must be a char or string (got ${ze(e)})`);if(e.exact===void 0)throw new W(`'isfield' requires a literal field name; got a non-literal ${e.kind.toLowerCase()}`);return e.exact}const T7={name:"isfield",transfer(e,t){if(e.length!==2)throw new le(`'isfield' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isfield' does not support multi-output (nargout=${t})`);const n=ym(e[1]);return[at(_m(e[0],n))]},emitC({argTypes:e}){const t=ym(e[1]);return _m(e[0],t)?"1.0":"0.0"},emitJs({argTypes:e}){const t=ym(e[1]);return _m(e[0],t)?"true":"false"},call({argTypes:e}){const t=ym(e[1]);return[_m(e[0],t)]}};function k0(e){if(Me(e))return e.shape===void 0?void 0:Dt(e.shape)===1;if(Jo(e))return!0;if(xo(e)||ji(e)||al(e)||Mf(e))return!1}function P7(e){if(e.kind!=="Numeric"&&e.kind!=="String"&&e.kind!=="Char"&&e.kind!=="Struct"&&e.kind!=="Class"&&e.kind!=="Handle"&&e.kind!=="Unknown")throw new le(`'isscalar' got an unsupported argument type (${ze(e)})`)}const B7={name:"isscalar",transfer(e,t){if(e.length!==1)throw new le(`'isscalar' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isscalar' does not support multi-output (nargout=${t})`);const n=e[0];P7(n);const r=k0(n);return[r===void 0?at():at(r)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=k0(r);return s!==void 0?s?"1.0":"0.0":(n("mtoc2_numel"),`(mtoc2_numel(${e[0]}) == 1)`)},emitJs({argsJs:e,argTypes:t}){const n=t[0],r=k0(n);return r!==void 0?r?"true":"false":`(${e[0]}.shape.reduce((a,b)=>a*b, 1) === 1)`},call({args:e}){const t=e[0];return typeof t=="number"||typeof t=="boolean"?[!0]:un(t)?[!0]:typeof t=="string"?[!0]:Er(t)?[!1]:Wt(t)?[t.data.length===1]:Hd(t)?[!1]:[!1]}},q7={name:"iscell",transfer(e,t){if(e.length!==1)throw new le(`'iscell' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'iscell' does not support multi-output (nargout=${t})`);return[at(ys(e[0]))]},emitC({argTypes:e}){return ys(e[0])?"1.0":"0.0"},emitJs({argTypes:e}){return ys(e[0])?"true":"false"},call({args:e}){const t=e[0];return typeof t=="object"&&t!==null&&t.mtoc2Tag==="cell"?[!0]:[!1]}},z7={name:"isstruct",transfer(e,t){if(e.length!==1)throw new le(`'isstruct' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isstruct' does not support multi-output (nargout=${t})`);return[at(ji(e[0]))]},emitC({argTypes:e}){return ji(e[0])?"1.0":"0.0"},emitJs({argTypes:e}){return ji(e[0])?"true":"false"},call({args:e}){const t=e[0];return typeof t=="object"&&t!==null&&!Wt(t)&&!Er(t)&&t.mtoc2Tag!=="cell"&&t.mtoc2Class===void 0&&t.mtoc2Handle!==!0?[!0]:[!1]}};function v0(e){return al(e)?e.className:ji(e)?"struct":Mf(e)?"function_handle":xo(e)?"char":Jo(e)?"string":ys(e)?"cell":Me(e)?e.elem==="logical"?"logical":"double":null}function M0(e,t,n){return t===e?!0:e==="numeric"?Me(n)&&n.elem!=="logical":!1}const V7={name:"isa",transfer(e,t){if(e.length!==2)throw new le(`'isa' expects 2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isa' does not support multi-output (nargout=${t})`);const n=e[1];if(!xo(n)&&!Jo(n))throw new le("'isa' second argument must be a class name (char or string)");if(n.exact===void 0)throw new W("'isa' requires a statically-known class name (got a runtime text value)");const r=v0(e[0]);return r===null?[at()]:[at(M0(n.exact,r,e[0]))]},emitC({argTypes:e}){const t=e[1];if((xo(t)||Jo(t))&&t.exact!==void 0){const n=v0(e[0]);if(n!==null)return M0(t.exact,n,e[0])?"1.0":"0.0"}return"0.0"},emitJs({argTypes:e}){const t=e[1];if((xo(t)||Jo(t))&&t.exact!==void 0){const n=v0(e[0]);if(n!==null)return M0(t.exact,n,e[0])?"true":"false"}return"false"},call({args:e}){const t=e[0],n=e[1];let r;typeof n=="string"?r=n:n&&typeof n=="object"&&Er(n)?r=n.value:r=String(n);let s="unknown";if(typeof t=="number")s="double";else if(typeof t=="boolean")s="logical";else if(typeof t=="string")s="string";else if(t!==null&&typeof t=="object")if(Er(t))s="char";else if(Wt(t)){const o=t.mtoc2Tag;s="double"}else t.mtoc2Tag==="cell"?s="cell":t.mtoc2Handle===!0?s="function_handle":t.mtoc2Class!==void 0?s=t.mtoc2Class:s="struct";return s===r?[!0]:r==="numeric"?s==="double"?[!0]:[!1]:[!1]}},U7={name:"fieldnames",transfer(e,t){if(e.length!==1)throw new le(`'fieldnames' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'fieldnames' does not support multi-output (nargout=${t})`);const n=e[0];if(!ji(n)&&!al(n))throw new le("'fieldnames' argument must be a struct or class instance");return[Pr]},emitC(){throw new W("'fieldnames' is interpreter-only; the c-aot backend can't materialize a runtime-length cell of chars")},emitJs(){throw new W("'fieldnames' is interpreter-only; the js-aot backend can't materialize a runtime-length cell of chars")},call({args:e}){const t=e[0];if(t===null||typeof t!="object")throw new Error("fieldnames: argument must be a struct or class");const n=t;if(Wt(n)||Er(n))throw new Error("fieldnames: argument must be a struct or class");const r=t;if(r.mtoc2Tag==="cell"||r.mtoc2Handle===!0||r.mtoc2Tag==="tensor"||r.mtoc2Tag==="char")throw new Error("fieldnames: argument must be a struct or class");const s=Object.keys(t),o=s.map(i=>Wr(i));return[{mtoc2Tag:"cell",shape:[s.length,1],data:o}]}},W7={name:"isnumeric",transfer(e,t){if(e.length!==1)throw new le(`'isnumeric' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'isnumeric' does not support multi-output (nargout=${t})`);const n=e[0];return Me(n)&&n.elem!=="logical"?[at(!0)]:[at(!1)]},emitC({argTypes:e}){const t=e[0];return Me(t)&&t.elem!=="logical"?"1.0":"0.0"},emitJs({argTypes:e}){const t=e[0];return Me(t)&&t.elem!=="logical"?"true":"false"},call({args:e}){const t=e[0];return typeof t=="number"?[!0]:typeof t=="boolean"?[!1]:un(t)?[!0]:Wt(t)?[!t.isLogical]:[!1]}};function X7(e,t){if(!Me(e))return e;const n={...e,elem:"logical"};return n.sign=t===1?"positive":"zero",n}function Ik(e){const t=e==="true"?1:0,n=t===1?bl(e,1,"mtoc2_tensor_ones_nd","mtoc2_tensor_ones_square",{minArgs:1}):bl(e,0,"mtoc2_tensor_zeros_nd","mtoc2_tensor_zeros_square",{minArgs:1});return{name:e,transfer(r,s){if(s!==1)throw new W(`'${e}' does not support multi-output (nargout=${s})`);return r.length===0?[at(t===1)]:n.transfer(r,s).map(o=>X7(o,t))},emitC(r){if(r.argTypes.length===0)return t===1?"1.0":"0.0";if(!n.emitC)throw new le(`internal: '${e}' shape constructor has no emitC`);return n.emitC(r)},emitJs(r){if(r.argTypes.length===0)return t===1?"true":"false";if(!n.emitJs)throw new le(`internal: '${e}' shape constructor has no emitJs`);return n.emitJs(r)},call(r){if(r.argTypes.length===0)return[t===1];if(!n.call)throw new le(`internal: '${e}' shape constructor has no call`);return n.call(r)},elementwise:!0}}const H7=Ik("true"),Y7=Ik("false");function xm(e){return Me(e)?De(e)?e.isComplex?"cs":"rs":e.isComplex?"ct":"rt":"other"}function J7(e,t,n){if(t.length<2)throw new le(`'${e}' expects at least 2 arg(s), got ${t.length}`);if(n>1)throw new W(`'${e}' does not support multi-output (nargout=${n})`)}function Z7(e,t,n,r,s){const o=xm(e),i=xm(n),a=()=>s("mtoc2_isequal"),c=()=>s("mtoc2_cscalar");if(o==="rs"&&i==="rs")return`(${t} == ${r} ? 1.0 : 0.0)`;if(o==="rs"&&i==="cs")return c(),`(cimag(${r}) == 0.0 && creal(${r}) == ${t} ? 1.0 : 0.0)`;if(o==="cs"&&i==="rs")return c(),`(cimag(${t}) == 0.0 && creal(${t}) == ${r} ? 1.0 : 0.0)`;if(o==="cs"&&i==="cs")return c(),`(creal(${t}) == creal(${r}) && cimag(${t}) == cimag(${r}) ? 1.0 : 0.0)`;if(o==="rs"&&i==="rt")return a(),`mtoc2_isequal_st(${t}, ${r})`;if(o==="rt"&&i==="rs")return a(),`mtoc2_isequal_st(${r}, ${t})`;if(o==="rs"&&i==="ct"||o==="ct"&&i==="rs")return"0.0";if(o==="cs"&&i==="rt")return a(),c(),`(cimag(${t}) == 0.0 ? mtoc2_isequal_st(creal(${t}), ${r}) : 0.0)`;if(o==="rt"&&i==="cs")return a(),c(),`(cimag(${r}) == 0.0 ? mtoc2_isequal_st(creal(${r}), ${t}) : 0.0)`;if(o==="rt"&&i==="rt")return a(),`mtoc2_isequal_tt(${t}, ${r})`;if(o==="rt"&&i==="ct"||o==="ct"&&i==="rt")return"0.0";throw new W("'isequal' with these argument types is not yet supported by the AOT backends (complex-tensor, char/string, struct or cell comparison); the interpreter handles it")}function K7(e,t,n,r,s){const o=xm(e),i=xm(n),a=()=>s("mtoc2_isequal"),c=(f,h)=>Me(f)&&De(f)&&f.elem==="logical"?`(+(${h}))`:h,l=c(e,t),u=c(n,r);if(o==="rs"&&i==="rs")return`(${l} === ${u} ? 1 : 0)`;if(o==="rs"&&i==="cs")return`(${r}.im === 0 && ${r}.re === ${l} ? 1 : 0)`;if(o==="cs"&&i==="rs")return`(${t}.im === 0 && ${t}.re === ${u} ? 1 : 0)`;if(o==="cs"&&i==="cs")return`(${t}.re === ${r}.re && ${t}.im === ${r}.im ? 1 : 0)`;if(o==="rs"&&i==="rt")return a(),`mtoc2_isequal_st(${l}, ${r})`;if(o==="rt"&&i==="rs")return a(),`mtoc2_isequal_st(${u}, ${t})`;if(o==="rs"&&i==="ct"||o==="ct"&&i==="rs")return"0";if(o==="cs"&&i==="rt")return a(),`(${t}.im === 0 ? mtoc2_isequal_st(${t}.re, ${r}) : 0)`;if(o==="rt"&&i==="cs")return a(),`(${r}.im === 0 ? mtoc2_isequal_st(${r}.re, ${t}) : 0)`;if(o==="rt"&&i==="rt")return a(),`mtoc2_isequal_tt(${t}, ${r})`;if(o==="rt"&&i==="ct"||o==="ct"&&i==="rt")return"0";throw new W("'isequal' with these argument types is not yet supported by the AOT backends (complex-tensor, char/string, struct or cell comparison); the interpreter handles it")}function Fk(e){return Er(e)?e.value:typeof e=="string"?e:null}function jk(e){return typeof e=="number"?e:typeof e=="boolean"?e?1:0:null}function G7(e,t){if(e.data.length!==t.data.length||e.shape.length!==t.shape.length)return!1;for(let n=0;n<e.shape.length;n++)if(e.shape[n]!==t.shape[n])return!1;for(let n=0;n<e.data.length;n++)if(e.data[n]!==t.data[n])return!1;if(e.imag||t.imag){if(!e.imag||!t.imag)return!1;for(let n=0;n<e.imag.length;n++)if(e.imag[n]!==t.imag[n])return!1}return!0}function Rk(e,t){const n=Fk(e),r=Fk(t);if(n!==null&&r!==null)return n===r;if(n!==null||r!==null)return!1;const s=jk(e),o=jk(t);if(s!==null&&o!==null)return s===o;if(un(e)&&un(t))return e.re===t.re&&e.im===t.im;if(un(e)&&o!==null)return e.re===o&&e.im===0;if(s!==null&&un(t))return t.re===s&&t.im===0;if(Wt(e)&&Wt(t))return G7(e,t);if(Wt(e)&&o!==null)return e.data.length===1&&!e.imag&&e.data[0]===o;if(s!==null&&Wt(t))return t.data.length===1&&!t.imag&&t.data[0]===s;if(Wt(e)&&un(t))return e.data.length===1&&e.data[0]===t.re&&(e.imag?e.imag[0]===t.im:t.im===0);if(un(e)&&Wt(t))return t.data.length===1&&t.data[0]===e.re&&(t.imag?t.imag[0]===e.im:e.im===0);if(Lk(e)&&Lk(t)){const i=e,a=t,c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(const u of c)if(!(u in a)||!Rk(i[u],a[u]))return!1;return!0}return!1}function Lk(e){return typeof e=="object"&&e!==null&&!Wt(e)&&!Er(e)&&!un(e)&&!("mtoc2Handle"in e)}const Q7={name:"isequal",transfer(e,t){return J7("isequal",e,t),[at()]},emitC({argTypes:e,argsC:t,useRuntime:n}){const r=[];for(let s=1;s<e.length;s++)r.push(`(${Z7(e[0],t[0],e[s],t[s],n)}) != 0.0`);return`(${r.join(" && ")})`},emitJs({argTypes:e,argsJs:t,useRuntime:n}){const r=[];for(let s=1;s<e.length;s++)r.push(`(${K7(e[0],t[0],e[s],t[s],n)}) !== 0`);return`(${r.join(" && ")})`},call({args:e}){for(let t=1;t<e.length;t++)if(!Rk(e[0],e[t]))return[!1];return[!0]}};function O7(e,t){if(e.length!==1)throw new le(`'isreal' expects 1 arg(s), got ${e.length}`);if(t>1)throw new W(`'isreal' does not support multi-output (nargout=${t})`)}function $0(e){if(!Me(e)||!e.isComplex)return!0;if(!De(e))return"runtime";const t=e.exact;if(t!==void 0&&typeof t=="object"&&"im"in t){const n=t.im;if(typeof n=="number")return n===0}return"runtime"}const eP={name:"isreal",transfer(e,t){O7(e,t);const n=$0(e[0]);return n==="runtime"?[at()]:[at(n)]},emitC({argTypes:e,argsC:t,useRuntime:n}){const r=e[0],s=$0(r);return s===!0?"1.0":s===!1?"0.0":Me(r)&&r.isComplex&&!De(r)?(n("mtoc2_tensor_imag_all_zero"),`mtoc2_tensor_imag_all_zero(${t[0]})`):(n("mtoc2_cscalar"),`(cimag(${t[0]}) == 0.0)`)},emitJs({argTypes:e,argsJs:t,useRuntime:n}){const r=e[0],s=$0(r);return s===!0?"true":s===!1?"false":Me(r)&&r.isComplex&&!De(r)?(n("mtoc2_tensor_imag_all_zero"),`mtoc2_tensor_imag_all_zero(${t[0]})`):`(${t[0]}.im === 0)`},call({args:e}){const t=e[0];return typeof t=="number"||typeof t=="boolean"?[!0]:un(t)?[t.im===0]:Wt(t)?[F5(t)]:[!0]}};function Dk(e){if(!Me(e))throw new W("'isempty' on a non-numeric value of unknown size is not supported by the AOT backends; the interpreter handles it")}function tP(e,t){if(e.length!==1)throw new le(`'isempty' expects 1 arg(s), got ${e.length}`);if(t>1)throw new W(`'isempty' does not support multi-output (nargout=${t})`)}function C0(e){return Me(e)?De(e)?!1:e.shape!==void 0?Dt(e.shape)===0:"runtime":xo(e)?e.exact!==void 0?e.exact.length===0:"runtime":!1}const nP={name:"isempty",transfer(e,t){tP(e,t);const n=C0(e[0]);return n==="runtime"?[at()]:[at(n)]},emitC({argTypes:e,argsC:t,useRuntime:n}){const r=C0(e[0]);return r===!0?"1.0":r===!1?"0.0":(Dk(e[0]),n("mtoc2_numel"),`(mtoc2_numel(${t[0]}) == 0)`)},emitJs({argTypes:e,argsJs:t}){const n=C0(e[0]);return n===!0?"true":n===!1?"false":(Dk(e[0]),`(${t[0]}.shape.reduce((a,b)=>a*b,1) === 0)`)},call({args:e}){const t=e[0];return typeof t=="number"||typeof t=="boolean"?[!1]:Wt(t)?[t.data.length===0]:Er(t)?[t.value.length===0]:typeof t=="string"?[!1]:[!1]}};function bm(e){return{...e,elem:"logical",sign:"nonneg"}}function km(e){const{name:t,cScalar:n,jsScalar:r,jsFn:s,tensorHelper:o,complex:i}=e;return{name:t,transfer(a,c){if(a.length!==1)throw new le(`'${t}' expects 1 arg(s), got ${a.length}`);if(c!==1)throw new W(`'${t}' does not support multi-output (nargout=${c})`);i!==void 0?pr(a[0],`'${t}' arg`):ml(a[0],`'${t}' arg`);const l=a[0];if(l.isComplex){if(De(l)){const h=An(l);return h!==void 0?[at(i.jsFnComplex(h.re,h.im))]:[at()]}const f=rn(l);if(f!==void 0&&l.shape!==void 0){const h=Dt(l.shape);if(h<=wt){const m=new Float64Array(h);for(let p=0;p<h;p++)m[p]=i.jsFnComplex(f.re[p],f.im[p])?1:0;return[bm(et(l.shape,m))]}}return[bm(Zt(l.dims.slice()))]}if(De(l)){const f=Je(l);return f!==void 0?[at(s(f))]:[at()]}const u=Mt(l);if(u!==void 0&&l.shape!==void 0){const f=Dt(l.shape);if(f<=wt){const h=new Float64Array(f);for(let m=0;m<f;m++)h[m]=s(u[m])?1:0;return[bm(et(l.shape,h))]}}return[bm(Zt(l.dims.slice()))]},emitC({argsC:a,argTypes:c,useRuntime:l}){const u=c[0];if(u.isComplex){if(l("mtoc2_cscalar"),qe(u))return l("mtoc2_tensor_predicate"),`${i.tensorHelperComplex}(${a[0]})`;const f=`creal(${a[0]})`,h=`cimag(${a[0]})`;return`(${i.cScalarComplex(f,h)})`}return qe(u)?(l(o),`mtoc2_tensor_${t}(${a[0]})`):n(a[0])},emitJs({argsJs:a,argTypes:c,useRuntime:l}){const u=c[0];if(u.isComplex)return qe(u)?(l("mtoc2_tensor_predicate"),`${i.tensorHelperComplex}(${a[0]})`):`(${i.jsScalarComplex(`${a[0]}.re`,`${a[0]}.im`)})`;if(qe(u))return l(o),`mtoc2_tensor_${t}(${a[0]})`;const f=u.elem==="double"?a[0]:`(+(${a[0]}))`;return r(f)},call({args:a,argTypes:c}){const l=c[0],u=a[0];if(qe(l)&&Wt(u)){const h=new Float64Array(u.data.length);if(u.imag!==void 0&&i!==void 0)for(let p=0;p<u.data.length;p++)h[p]=i.jsFnComplex(u.data[p],u.imag[p])?1:0;else for(let p=0;p<u.data.length;p++)h[p]=s(u.data[p])?1:0;return[{mtoc2Tag:"tensor",shape:u.shape.slice(),data:h,isLogical:!0}]}if(i!==void 0&&un(u))return[i.jsFnComplex(u.re,u.im)];const f=typeof u=="number"?u:Number(u);return[s(f)]},elementwise:!0}}const rP=km({name:"isnan",cScalar:e=>`isnan(${e})`,jsScalar:e=>`Number.isNaN(${e})`,jsFn:Number.isNaN,tensorHelper:"mtoc2_tensor_predicate",complex:{cScalarComplex:(e,t)=>`isnan(${e}) || isnan(${t})`,jsScalarComplex:(e,t)=>`Number.isNaN(${e}) || Number.isNaN(${t})`,jsFnComplex:(e,t)=>Number.isNaN(e)||Number.isNaN(t),tensorHelperComplex:"mtoc2_tensor_isnan_complex"}}),sP=km({name:"logical",cScalar:e=>`((${e}) != 0.0)`,jsScalar:e=>`((${e}) !== 0)`,jsFn:e=>e!==0,tensorHelper:"mtoc2_tensor_predicate"}),S0=e=>e===1/0||e===-1/0,oP=km({name:"isinf",cScalar:e=>`(isinf(${e}) != 0)`,jsScalar:e=>`(Math.abs(${e}) === Infinity)`,jsFn:S0,tensorHelper:"mtoc2_tensor_predicate",complex:{cScalarComplex:(e,t)=>`isinf(${e}) || isinf(${t})`,jsScalarComplex:(e,t)=>`Math.abs(${e}) === Infinity || Math.abs(${t}) === Infinity`,jsFnComplex:(e,t)=>S0(e)||S0(t),tensorHelperComplex:"mtoc2_tensor_isinf_complex"}}),iP=km({name:"isfinite",cScalar:e=>`isfinite(${e})`,jsScalar:e=>`Number.isFinite(${e})`,jsFn:Number.isFinite,tensorHelper:"mtoc2_tensor_predicate",complex:{cScalarComplex:(e,t)=>`isfinite(${e}) && isfinite(${t})`,jsScalarComplex:(e,t)=>`Number.isFinite(${e}) && Number.isFinite(${t})`,jsFnComplex:(e,t)=>Number.isFinite(e)&&Number.isFinite(t),tensorHelperComplex:"mtoc2_tensor_isfinite_complex"}});function vm(e){switch(e.kind){case"Numeric":return e.elem==="logical"?"logical":"double";case"Char":return"char";case"String":return"string";case"Struct":return"struct";case"Class":return e.className;case"Cell":return"cell";case"Handle":return"function_handle";case"Unknown":case"Void":throw new W(`'class' on a ${e.kind==="Void"?"void":"unknown"} value is not supported`)}}function aP(e){let t='"';for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r===92?t+="\\\\":r===34?t+='\\"':r>=32&&r<127?t+=String.fromCharCode(r):t+=`\\x${r.toString(16).padStart(2,"0")}`}return t+='"',{lit:t,byteLen:new TextEncoder().encode(e).length}}const cP={name:"class",transfer(e,t){if(e.length!==1)throw new le(`'class' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'class' does not support multi-output (nargout=${t})`);return[{kind:"Char",exact:vm(e[0])}]},emitC({argTypes:e,useRuntime:t}){const n=vm(e[0]);t("mtoc2_char_tensor_from_literal");const{lit:r,byteLen:s}=aP(n);return`mtoc2_char_tensor_from_literal(${r}, ${s})`},emitJs({argTypes:e}){const t=vm(e[0]);return`({mtoc2Tag:"char", value:${JSON.stringify(t)}})`},call({args:e,argTypes:t}){if(Hd(e[0]))return[Wr("function_handle")];const n=t[0];if(n.kind!=="Unknown"&&n.kind!=="Void")return[Wr(vm(n))];const r=e[0];if(typeof r=="number")return[Wr("double")];if(typeof r=="boolean")return[Wr("logical")];if(typeof r=="string")return[Wr("string")];if(Er(r))return[Wr("char")];if(un(r))return[Wr("double")];if(Wt(r))return[Wr(r.isLogical?"logical":"double")];if(Hd(r))return[Wr("function_handle")];if(r&&typeof r=="object"){if(r.mtoc2Tag==="cell")return[Wr("cell")];const s=r.mtoc2Class;return s!==void 0?[Wr(s)]:[Wr("struct")]}return[Wr("unknown")]}},lP={cumsum:p6,cumprod:d6,cummax:g6,cummin:w6},uP={cumsum:_6,cumprod:y6};function N0(e){const t=e.findIndex(n=>n>1);return t>=0?t+1:1}function fP(e,t){if(t===void 0)return;if(!Me(t)||t.isComplex||!De(t))throw new le(`'${e}' dim arg must be a scalar real integer`);const n=Je(t);if(n===void 0)throw new W(`'${e}' dim arg must be a statically-known integer in v1`);if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)throw new le(`'${e}' dim arg must be a finite positive integer (got ${n})`);return n}function mP(e,t,n,r){const s=new Float64Array(t.length);if(r>n.length)return s.set(t),s;const o=r-1,i=n[o];let a=1;for(let l=0;l<o;l++)a*=n[l];let c=1;for(let l=o+1;l<n.length;l++)c*=n[l];for(let l=0;l<c;l++){const u=l*a*i;for(let f=0;f<a;f++){let h=e.init;for(let m=0;m<i;m++){const p=u+f+m*a;h=e.step(h,t[p]),s[p]=h}}}return s}function hP(e,t,n,r,s){const o=new Float64Array(t.length),i=new Float64Array(t.length);if(s>r.length)return o.set(t),i.set(n),{re:o,im:i};const a=s-1,c=r[a];let l=1;for(let m=0;m<a;m++)l*=r[m];let u=1;for(let m=a+1;m<r.length;m++)u*=r[m];const f=0,h=e.stepComplex;if(h===void 0)throw new Error(`internal: ${e.name} reached complex scan without stepComplex`);for(let m=0;m<u;m++){const p=m*l*c;for(let d=0;d<l;d++){let g=e.init,w=f;for(let _=0;_<c;_++){const y=p+d+_*l,b=h(g,w,t[y],n[y]);g=b[0],w=b[1],o[y]=g,i[y]=w}}}return{re:o,im:i}}function Tk(e,t,n){const r=t[1];if(r!==void 0){if(!Me(r))throw new Error(`internal: ${e} codegen unexpected dim type`);const s=Je(r);if(s===void 0)throw new Error(`internal: ${e} codegen reached with non-exact dim`);return s}if(n.shape!==void 0)return N0(n.shape);throw new Error(`internal: ${e} codegen on lattice-only shape with no dim arg`)}function pP(e,t){if(e.length>=2&&e[1]!==void 0){const n=e[1];return Math.round(typeof n=="number"?n:Number(n))}return N0(t.shape)}function Mm(e){return{name:e.name,transfer(t,n){if(t.length<1||t.length>2)throw new le(`'${e.name}' expects 1..2 arg(s), got ${t.length}`);if(n!==1)throw new W(`'${e.name}' does not support multi-output (nargout=${n})`);const r=t[0];if(!Me(r))throw new le(`'${e.name}' arg must be numeric (got ${r.kind})`);if(r.elem!=="double"&&r.elem!=="logical")throw new le(`'${e.name}' arg must be double or logical (got ${r.elem})`);if(r.isComplex&&(e.supportsComplex===!1||e.stepComplex===void 0))throw new W(`'${e.name}' on complex input is not JIT-compiled`);const s=fP(e.name,t[1]);if(De(r)){if(r.isComplex){const l=An(r);return l!==void 0?[_t(l)]:[_t()]}const c=Je(r);return c!==void 0?[Be(ft(c),c)]:[Be(e.signRule(r.sign))]}let o;if(s!==void 0)o=s;else if(r.shape!==void 0)o=N0(r.shape);else throw new W(`'${e.name}' on a tensor with non-concrete shape requires an explicit dim arg (lattice-only shape can't pick a default axis)`);if(r.isComplex){const c=rn(r);if(c!==void 0&&r.shape!==void 0&&c.re.length<=wt){const l=hP(e,c.re,c.im,r.shape,o);return[Ut(r.shape,l)]}return r.shape!==void 0?[Ut(r.shape)]:[mr(r.dims.slice())]}const i=Mt(r);if(i!==void 0&&r.shape!==void 0&&i.length<=wt){const c=mP(e,i,r.shape,o);return[et(r.shape,c)]}if(r.shape!==void 0){const c=et(r.shape);return c.sign=e.signRule(r.sign),[c]}const a=Zt(r.dims.slice());return a.sign=e.signRule(r.sign),[a]},emitC({argsC:t,argTypes:n,useRuntime:r}){const s=n[0];if(De(s))return`(${t[0]})`;r("mtoc2_tensor_cumulative");const o=Tk(e.name,n,s),i=s.isComplex?"_complex_dim":"_dim";return`mtoc2_tensor_${e.name}${i}(${t[0]}, ${o})`},emitJs({argsJs:t,argTypes:n,useRuntime:r}){const s=n[0];if(De(s))return t[0];r("mtoc2_tensor_cumulative");const o=Tk(e.name,n,s),i=s.isComplex?"_complex_dim":"_dim";return`mtoc2_tensor_${e.name}${i}(${t[0]}, ${o})`},call({args:t,argTypes:n}){const r=n[0];if(De(r)){const c=t[0];return r.isComplex?[c]:[typeof c=="number"?c:Number(c)]}const o=(r.isComplex?uP:lP)[e.name];if(o===void 0)throw new W(`'${e.name}' tensor 'call' has no JS kernel registered`);const i=t[0],a=pP(t,i);return[o(i,a)]}}}function A0(e){switch(e){case"positive":return"positive";case"nonneg":return"nonneg";case"zero":return"zero";case"negative":return"negative";case"nonpositive":return"nonpositive";default:return"unknown"}}function dP(e){switch(e){case"positive":return"positive";case"nonneg":return"nonneg";case"zero":return"zero";default:return"unknown"}}const gP=Mm({name:"cumsum",init:0,step:(e,t)=>e+t,stepComplex:(e,t,n,r)=>[e+n,t+r],signRule:A0}),wP=Mm({name:"cumprod",init:1,step:(e,t)=>e*t,stepComplex:(e,t,n,r)=>[e*n-t*r,e*r+t*n],signRule:dP}),_P=Mm({name:"cummax",init:-1/0,step:(e,t)=>Math.max(e,t),signRule:A0,supportsComplex:!1}),yP=Mm({name:"cummin",init:1/0,step:(e,t)=>Math.min(e,t),signRule:A0,supportsComplex:!1});function xP(e,t){let n;t!==void 0?n=t-1:e.length<=1||e.length===2&&e[0]===1?n=e.length===2&&e[0]===1?1:0:n=0;const r=n<e.length?e[n]:1,s=e.slice();for(r<=1?n<s.length&&(s[n]=0):s[n]=r-1;s.length>2&&s[s.length-1]===1;)s.pop();return s}function $m(e){if(e.length<1||e.length>3)throw new le(`'diff' expects 1..3 arg(s), got ${e.length}`);const t=e[0];if(!Me(t))throw new le(`'diff' arg must be numeric (got ${t.kind})`);if(t.isComplex)throw new W("'diff' on complex input is not JIT-compiled");if(t.elem!=="double"&&t.elem!=="logical")throw new le(`'diff' arg must be double or logical (got ${t.elem})`);if(De(t))throw new W("'diff' on a scalar is not JIT-compiled");if(t.shape===void 0)throw new W("'diff' on a tensor with non-concrete shape is not JIT-compiled");if(e.length>=2){const r=e[1];if(!Me(r)||r.isComplex||!De(r))throw new W("'diff' order arg must be the scalar 1 (higher-order / '[]' decline)");const s=Je(r);if(s===void 0||s!==1)throw new W(`'diff' only JIT-compiles first-order (n == 1); got ${s??"non-exact"}`)}let n;if(e.length>=3){const r=e[2];if(!Me(r)||r.isComplex||!De(r))throw new le("'diff' dim arg must be a scalar real integer");const s=Je(r);if(s===void 0)throw new W("'diff' dim arg must be a statically-known integer");if(!Number.isFinite(s)||!Number.isInteger(s)||s<1)throw new le(`'diff' dim arg must be a positive integer (got ${s})`);if(s>t.shape.length)throw new W(`'diff' with dim ${s} > ndims ${t.shape.length} is not JIT-compiled`);n=s}return{shape:t.shape,dim:n}}const bP={name:"diff",transfer(e,t){if(t!==1)throw new W(`'diff' does not support multi-output (nargout=${t})`);const{shape:n,dim:r}=$m(e),s=xP(n,r);if(s.every(i=>i===1))return[Zt([nn,{kind:"unknown"}])];const o=et(s);return o.sign="unknown",[o]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_diff");const{dim:r}=$m(t);return`mtoc2_tensor_diff(${e[0]}, ${r??0})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_diff");const{dim:r}=$m(t);return`mtoc2_tensor_diff(${e[0]}, ${r??0})`},call({args:e,argTypes:t}){const{dim:n}=$m(t);return[C6(e[0],n??0)]}};function Cm(e){if(e.length<2)throw new W(`'repmat' requires at least 2 arguments (got ${e.length})`);if(e.length===2&&Me(e[1])&&!De(e[1])){const n=e[1];if(n.isComplex||n.elem!=="double"&&n.elem!=="logical")throw new le(`'repmat' rep vector must be a real double / logical tensor (got ${ze(n)})`);const r=Mt(n);if(r===void 0)throw new W("'repmat' rep vector must be a statically-known constant in v1");if(r.length<1)throw new le("'repmat' rep vector must be non-empty");if(r.length>Zn)throw new W(`'repmat' supports up to ${Zn} rep dims (got ${r.length})`);const s=[];for(let o=0;o<r.length;o++){const i=r[o];if(!Number.isFinite(i)||!Number.isInteger(i))throw new le(`'repmat' rep ${o+1} must be a finite integer (got ${i})`);s.push({kind:"exact",value:i<0?0:i,argIndex:1})}return{reps:s,squareFromScalar:!1,formB:!0}}if(e.length-1>Zn)throw new W(`'repmat' supports up to ${Zn} rep dims (got ${e.length-1})`);const t=[];for(let n=1;n<e.length;n++){const r=e[n];if(!Me(r)||!De(r))throw new le(`'repmat' rep arg ${n} must be a scalar real numeric (got ${ze(r)})`);if(r.isComplex||r.elem!=="double"&&r.elem!=="logical")throw new le(`'repmat' rep arg ${n} must be a scalar real double / logical (got ${ze(r)})`);const s=Je(r);if(s===void 0){t.push({kind:"dynamic",argIndex:n});continue}if(!Number.isFinite(s)||!Number.isInteger(s))throw new le(`'repmat' rep arg ${n} must be a finite integer (got ${s})`);t.push({kind:"exact",value:s<0?0:s,argIndex:n})}return t.length===1?{reps:[t[0],t[0]],squareFromScalar:!0,formB:!1}:{reps:t,squareFromScalar:!1,formB:!1}}function kP(e){if(e.shape!==void 0)return e.shape.slice()}function Sm(e){return e.formB&&e.reps.length===1?[e.reps[0],e.reps[0]]:e.reps}function E0(e,t,n){const r=t.length,s=t.map((u,f)=>u*n[f]);let o=1;for(const u of s)o*=u;const i=new Float64Array(o);if(o===0)return i;let a=1;for(const u of t)a*=u;if(a===0)return i;i.set(e.subarray(0,a),0);const c=t.slice();let l=a;for(let u=0;u<r;u++){const f=n[u];if(f===1)continue;let h=1;for(let p=0;p<=u;p++)h*=c[p];if(f===0||h===0)return new Float64Array(o);const m=l/h;for(let p=m-1;p>=0;p--){const d=p*h,g=p*h*f;g!==d&&i.copyWithin(g,d,d+h);for(let w=1;w<f;w++)i.copyWithin(g+w*h,g,g+h)}c[u]*=f,l*=f}return i}function Pk(e,t,n){const r=e.slice();for(;r.length<n;)r.push(t);return r}function Bk(e){const t=e.slice();for(;t.length>2&&t[t.length-1]===1;)t.pop();for(;t.length<2;)t.push(1);return t}function vP(e){const t=e.slice(),n=r=>r.kind==="exact"&&r.value===1;for(;t.length>2&&n(t[t.length-1]);)t.pop();for(;t.length<2;)t.push(nn);return t}function I0(e,t,n){const r=Math.max(n?0:e.length,t.length);let s=r<2?2:r;for(;s>2;){const i=s-1,a=n||i>=e.length||e[i].kind==="exact"&&e[i].value===1,c=i<t.length?t[i]:{kind:"exact",value:1},l=c.kind==="exact"&&c.value===1;if(!(a&&l))break;s--}const o=t.slice(0,s);for(;o.length<s;)o.push({kind:"exact",value:1,argIndex:0});return{reps:o,ndim:s}}function qk(e,t){return e.kind==="exact"?`${e.value}L`:`mtoc2_check_dim(${t[e.argIndex]})`}function zk(e,t){return e.kind==="exact"?String(e.value):`mtoc2_check_dim(${t[e.argIndex]})`}const MP={name:"repmat",transfer(e,t){if(t!==1)throw new W(`'repmat' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'repmat' first arg must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'repmat' first arg must be a real double / logical (got ${n.elem})`);const r=Cm(e),s=De(n),o=s?Sm(r):r.reps;if(o.every(h=>h.kind==="exact")){const h=o.map(p=>p.value);if(s){const p=Bk(h.slice()),d=Dt(p);if(n.isComplex){const _=An(n);if(p.every(y=>y===1))return _!==void 0?[_t(_)]:[_t()];if(_!==void 0&&d<=wt){const y=new Float64Array(d),b=new Float64Array(d);return y.fill(_.re),b.fill(_.im),[Ut(p,{re:y,im:b})]}return[Ut(p)]}const g=Je(n);if(p.every(_=>_===1))return g!==void 0?[Be(ft(g),g)]:[Be(n.sign)];if(g!==void 0&&d<=wt){const _=new Float64Array(d);return g!==0&&_.fill(g),[et(p,_)]}const w=et(p);return w.sign=g!==void 0?ft(g):n.sign,[w]}const m=kP(n);if(m!==void 0){const p=Math.max(m.length,h.length),d=Pk(m,1,p),g=Pk(h,1,p),w=Bk(d.map((M,$)=>M*g[$])),_=w.length;for(;d.length>_;)d.pop();for(;g.length>_;)g.pop();for(;d.length<_;)d.push(1);for(;g.length<_;)g.push(1);if(n.isComplex){if(w.every(N=>N===1)){const N=rn(n);return N!==void 0&&N.re.length===1?[_t({re:N.re[0],im:N.im[0]})]:[_t()]}const M=Dt(w),$=rn(n);if($!==void 0&&M<=wt){const N=E0($.re,d,g),E=E0($.im,d,g);return[Ut(w,{re:N,im:E})]}return[Ut(w)]}if(w.every(M=>M===1)){const M=Mt(n);if(M!==void 0&&M.length===1)return[Be(ft(M[0]),M[0])];const $=Je(n);return $!==void 0?[Be(ft($),$)]:[Be(n.sign)]}const y=Dt(w),b=Mt(n);if(b!==void 0&&y<=wt){const M=E0(b,d,g),$=et(w,M);return $.sign=ol(M),[$]}const k=et(w);return k.sign=n.sign,[k]}}const a=n.dims,c=Math.max(a.length,o.length),l=[];for(let h=0;h<c;h++){const m=h<a.length?a[h]:nn,p=h<o.length?o[h]:{kind:"exact",value:1};if(m.kind==="exact"&&p.kind==="exact"){const d=m.value*p.value;l.push(d===1?nn:{kind:"exact",value:d})}else l.push({kind:"unknown"})}const u=vP(l);if(n.isComplex)return[mr(u)];const f=Zt(u);return f.sign=n.sign,[f]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=Cm(t),o=De(r),i=o?Sm(s):s.reps,{reps:a,ndim:c}=I0(r.dims,i,o);a.some(f=>f.kind==="dynamic")&&n(Qo);const l=a.every(f=>f.kind==="exact"&&f.value===1);if(o){if(l)return e[0];n("mtoc2_tensor_fill_nd");const f=a.map(h=>qk(h,e)).join(", ");return r.isComplex?(n("mtoc2_cscalar"),`mtoc2_tensor_fill_nd_complex(creal(${e[0]}), cimag(${e[0]}), ${c}, (long[]){${f}})`):`mtoc2_tensor_fill_nd((double)(${e[0]}), ${c}, (long[]){${f}})`}n("mtoc2_tensor_repmat");const u=a.map(f=>qk(f,e)).join(", ");return r.isComplex?`mtoc2_tensor_repmat_complex(${e[0]}, ${c}, (long[]){${u}})`:`mtoc2_tensor_repmat(${e[0]}, ${c}, (long[]){${u}})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0],s=Cm(t),o=De(r),i=o?Sm(s):s.reps,{reps:a,ndim:c}=I0(r.dims,i,o);a.some(f=>f.kind==="dynamic")&&n(Qo);const l=a.every(f=>f.kind==="exact"&&f.value===1);if(o){if(l)return e[0];n("mtoc2_tensor_fill_nd");const f=a.map(h=>zk(h,e)).join(", ");return r.isComplex?`mtoc2_tensor_fill_nd_complex(${e[0]}.re, ${e[0]}.im, ${c}, [${f}])`:`mtoc2_tensor_fill_nd(${e[0]}, ${c}, [${f}])`}n("mtoc2_tensor_repmat");const u=a.map(f=>zk(f,e)).join(", ");return r.isComplex?`mtoc2_tensor_repmat_complex(${e[0]}, ${c}, [${u}])`:`mtoc2_tensor_repmat(${e[0]}, ${c}, [${u}])`},call({args:e,argTypes:t}){const n=t[0],r=Cm(t),s=De(n),o=s?Sm(r):r.reps,{reps:i}=I0(n.dims,o,s),a=i.map(c=>{if(c.kind==="exact")return c.value;const l=e[c.argIndex],u=typeof l=="number"?l:Number(l);return Ka(u)});if(s){const c=a.slice();for(;c.length<2;)c.push(1);if(n.isComplex){const u=e[0],f=un(u)?u:{re:typeof u=="number"?u:Number(u),im:0};return[A5(f.re,f.im,c.length,c)]}const l=typeof e[0]=="number"?e[0]:Number(e[0]);return[vb(l,c.length,c)]}return n.isComplex?[bL(e[0],a.length,a)]:[xL(e[0],a.length,a)]}};function Nm(e){if(e.length<2)return 0;const t=e[1];if(!Me(t)||!De(t)||t.isComplex)throw new le(`'diag' second arg must be a scalar real integer (got ${ze(t)})`);if(t.elem!=="double"&&t.elem!=="logical")throw new le(`'diag' second arg must be double or logical (got ${t.elem})`);const n=Je(t);if(n===void 0)throw new W("'diag' with a dynamic k argument is not yet supported (require a literal integer)");if(!Number.isFinite(n)||!Number.isInteger(n))throw new le(`'diag' k must be a finite integer (got ${n})`);return n}function Am(e,t,n){return n>=0?Math.max(0,Math.min(e,t-n)):Math.max(0,Math.min(e+n,t))}const $P={name:"diag",transfer(e,t){if(e.length<1||e.length>2)throw new le(`'diag' expects 1..2 arg(s), got ${e.length}`);if(t!==1)throw new W(`'diag' does not support multi-output (nargout=${t})`);const n=e[0];if(!Me(n))throw new le(`'diag' first arg must be numeric (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'diag' first arg must be a double or logical tensor (got ${n.elem})`);const r=Nm(e),s=Math.abs(r);if(De(n)){if(r===0){if(n.isComplex){const d=An(n);return d!==void 0?[_t(d)]:[_t()]}const p=Je(n);return p!==void 0?[Be(ft(p),p)]:[Be(n.sign)]}const u=1+s,f=[u,u],h=u*u;if(n.isComplex){const p=An(n);if(p!==void 0&&h<=wt){const d=new Float64Array(h),g=new Float64Array(h),w=r<0?-r:0,_=r>0?r:0;return d[w+_*u]=p.re,g[w+_*u]=p.im,[Ut(f,{re:d,im:g})]}return[Ut(f)]}const m=Je(n);if(m!==void 0&&h<=wt){const p=new Float64Array(h),d=r<0?-r:0,g=r>0?r:0;return p[d+g*u]=m,[et(f,p)]}return[et(f)]}if(n.dims.length!==2)throw new W(`'diag' requires a 2-D operand (got ${n.dims.length}-D)`);if(n.shape===void 0)throw new W("'diag' of a tensor with unknown shape is not yet supported");const[o,i]=n.shape;if(o===1||i===1){const u=Math.max(o,i),f=u+s,h=[f,f],m=f*f;if(n.isComplex){const d=rn(n);if(d!==void 0&&m<=wt){const g=new Float64Array(m),w=new Float64Array(m);for(let _=0;_<u;_++){const y=r<0?_-r:_,b=r>0?_+r:_;g[y+b*f]=d.re[_],w[y+b*f]=d.im[_]}return[Ut(h,{re:g,im:w})]}return[Ut(h)]}const p=Mt(n);if(p!==void 0&&m<=wt){const d=new Float64Array(m);for(let g=0;g<u;g++){const w=r<0?g-r:g,_=r>0?g+r:g;d[w+_*f]=p[g]}return[et(h,d)]}return[et(h)]}const a=Am(o,i,r);if(a===0)return n.isComplex?[Ut([0,1])]:[et([0,1])];if(a===1){if(n.isComplex){const f=rn(n);if(f!==void 0){const h=r<0?-r:0,m=r>0?r:0,p=h+m*o;return[_t({re:f.re[p],im:f.im[p]})]}return[_t()]}const u=Mt(n);if(u!==void 0){const f=r<0?-r:0,h=r>0?r:0,m=u[f+h*o];return[Be(ft(m),m)]}return[Be("unknown")]}const c=[a,1];if(n.isComplex){const u=rn(n);if(u!==void 0&&a<=wt){const f=new Float64Array(a),h=new Float64Array(a);for(let m=0;m<a;m++){const p=r<0?-r+m:m,d=r>0?r+m:m;f[m]=u.re[p+d*o],h[m]=u.im[p+d*o]}return[Ut(c,{re:f,im:h})]}return[Ut(c)]}const l=Mt(n);if(l!==void 0&&a<=wt){const u=new Float64Array(a);for(let f=0;f<a;f++){const h=r<0?-r+f:f,m=r>0?r+f:f;u[f]=l[h+m*o]}return[et(c,u)]}return[et(c)]},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0],s=Nm(t);if(De(r))return s===0?e[0]:r.isComplex?(n("mtoc2_tensor_diag"),n("mtoc2_cscalar"),`mtoc2_tensor_diag_from_scalar_complex(creal(${e[0]}), cimag(${e[0]}), ${s}L)`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_from_scalar(${e[0]}, ${s}L)`);const o=r.shape[0],i=r.shape[1];if(o===1||i===1)return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct_complex(${e[0]}, ${s}L)`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct(${e[0]}, ${s}L)`);if(Am(o,i,s)===1){const c=s<0?-s:0,l=s>0?s:0,u=c+l*o;return r.isComplex?(n("mtoc2_cscalar"),`mtoc2_cmake(${e[0]}.real[${u}], ${e[0]}.imag != NULL ? ${e[0]}.imag[${u}] : 0.0)`):`${e[0]}.real[${u}]`}return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract_complex(${e[0]}, ${s}L)`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract(${e[0]}, ${s}L)`)},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0],s=Nm(t);if(De(r))return s===0?e[0]:r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_from_scalar_complex(${e[0]}.re, ${e[0]}.im, ${s})`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_from_scalar(${e[0]}, ${s})`);const o=r.shape[0],i=r.shape[1];if(o===1||i===1)return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct_complex(${e[0]}, ${s})`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_construct(${e[0]}, ${s})`);if(Am(o,i,s)===1){const c=s<0?-s:0,l=s>0?s:0,u=c+l*o;return r.isComplex?`{ re: ${e[0]}.data[${u}], im: ${e[0]}.imag !== undefined ? ${e[0]}.imag[${u}] : 0 }`:`${e[0]}.data[${u}]`}return r.isComplex?(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract_complex(${e[0]}, ${s})`):(n("mtoc2_tensor_diag"),`mtoc2_tensor_diag_extract(${e[0]}, ${s})`)},call({args:e,argTypes:t}){const n=t[0],r=Nm(t);if(De(n)){if(r===0)return[e[0]];if(n.isComplex){const l=e[0],u=un(l)?l:{re:typeof l=="number"?l:Number(l),im:0};return[v6(u.re,u.im,r)]}const c=typeof e[0]=="number"?e[0]:Number(e[0]);return[x6(c,r)]}if(!Wt(e[0]))throw new le("'diag' runtime arg has tensor type but runtime value isn't a tensor");const s=e[0],o=s.shape[0],i=s.shape[1];if(o===1||i===1)return n.isComplex?[M6(s,r)]:[b6(s,r)];const a=Am(o,i,r);if(a===0)return[Bi([0,1],new Float64Array(0))];if(a===1){const c=r<0?-r:0,l=r>0?r:0,u=c+l*o;if(n.isComplex){const f=s.imag!==void 0?s.imag[u]:0;return[{re:s.data[u],im:f}]}return[s.data[u]]}return n.isComplex?[$6(s,r)]:[k6(s,r)]}};function Em(e,t){if(t.length<2)return 0;const n=t[1];if(!Me(n)||!De(n)||n.isComplex)throw new le(`'${e}' second arg must be a scalar real integer (got ${ze(n)})`);if(n.elem!=="double"&&n.elem!=="logical")throw new le(`'${e}' second arg must be double or logical (got ${n.elem})`);const r=Je(n);if(r===void 0)throw new W(`'${e}' with a dynamic k argument is not yet supported (require a literal integer)`);if(!Number.isFinite(r)||!Number.isInteger(r))throw new le(`'${e}' k must be a finite integer (got ${r})`);return r}function Vk(e){const{name:t,cHelper:n,cHelperComplex:r,keep:s,jsHelper:o,jsHelperComplex:i}=e;function a(f,h){if(f.length<1||f.length>2)throw new le(`'${t}' expects 1..2 arg(s), got ${f.length}`);if(h!==1)throw new W(`'${t}' does not support multi-output (nargout=${h})`);const m=f[0];if(!Me(m))throw new le(`'${t}' first arg must be numeric (got ${ze(m)})`);if(m.elem!=="double"&&m.elem!=="logical")throw new le(`'${t}' first arg must be a double or logical tensor (got ${m.elem})`);const p=Em(t,f);if(De(m)){if(m.isComplex){const k=An(m);return k!==void 0?[_t(s(0,0,p)?k:{re:0,im:0})]:[s(0,0,p)?_t():_t({re:0,im:0})]}const b=Je(m);if(b!==void 0){const k=s(0,0,p)?b:0;return[Be(ft(k),k)]}return s(0,0,p)?[Be(m.sign)]:[Be("zero",0)]}if(m.dims.length!==2)throw new W(`'${t}' requires a 2-D operand (got ${m.dims.length}-D)`);if(m.shape===void 0)throw new W(`'${t}' of a tensor with unknown shape is not yet supported`);const[d,g]=m.shape,w=[d,g],_=d*g;if(m.isComplex){const b=rn(m);if(b!==void 0&&_<=wt){const k=new Float64Array(_),M=new Float64Array(_);for(let $=0;$<g;$++)for(let N=0;N<d;N++)if(s(N,$,p)){const E=N+$*d;k[E]=b.re[E],M[E]=b.im[E]}return[Ut(w,{re:k,im:M})]}return[Ut(w)]}const y=Mt(m);if(y!==void 0&&_<=wt){const b=new Float64Array(_);for(let k=0;k<g;k++)for(let M=0;M<d;M++)if(s(M,k,p)){const $=M+k*d;b[$]=y[$]}return[et(w,b)]}return[et(w)]}function c({argsC:f,argTypes:h,useRuntime:m}){const p=h[0],d=Em(t,h);return De(p)?p.isComplex?(m("mtoc2_cscalar"),s(0,0,d)?f[0]:"mtoc2_cmake(0.0, 0.0)"):s(0,0,d)?f[0]:"0.0":p.isComplex?(m("mtoc2_tensor_triangular"),`${r}(${f[0]}, ${d}L)`):(m("mtoc2_tensor_triangular"),`${n}(${f[0]}, ${d}L)`)}function l({argsJs:f,argTypes:h,useRuntime:m}){const p=h[0],d=Em(t,h);return De(p)?p.isComplex?(m("mtoc2_cscalar"),s(0,0,d)?f[0]:"mtoc2_cmake(0, 0)"):s(0,0,d)?f[0]:"0":p.isComplex?(m("mtoc2_tensor_triangular"),`${r}(${f[0]}, ${d})`):(m("mtoc2_tensor_triangular"),`${n}(${f[0]}, ${d})`)}function u({args:f,argTypes:h}){const m=h[0],p=Em(t,h);if(De(m))return s(0,0,p)?[f[0]]:m.isComplex?[{re:0,im:0}]:[0];if(!Wt(f[0]))throw new le(`'${t}' runtime arg has tensor type but runtime value isn't a tensor`);const d=f[0],g=d.shape[0],w=d.shape[1];return g===0||w===0?[Bi([g,w],new Float64Array(0))]:m.isComplex?[i(d,p)]:[o(d,p)]}return{name:t,transfer:a,emitC:c,emitJs:l,call:u}}const CP=Vk({name:"triu",cHelper:"mtoc2_tensor_triu",cHelperComplex:"mtoc2_tensor_triu_complex",keep:(e,t,n)=>t-e>=n,jsHelper:IL,jsHelperComplex:jL}),SP=Vk({name:"tril",cHelper:"mtoc2_tensor_tril",cHelperComplex:"mtoc2_tensor_tril_complex",keep:(e,t,n)=>e-t>=-n,jsHelper:FL,jsHelperComplex:RL});function Im(e){const t=e[0];if(!Me(t)||!De(t)||t.isComplex)throw new le(`'cat' first arg (dim) must be a scalar real integer (got ${ze(t)})`);if(t.elem!=="double"&&t.elem!=="logical")throw new le(`'cat' first arg (dim) must be a scalar real integer (got ${t.elem})`);const n=Je(t);if(n===void 0)throw new W("'cat' with a dynamic dim argument is not yet supported (require a statically-known dim)");if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)throw new le(`'cat' dim must be a positive integer (got ${n})`);if(n>Zn)throw new W(`'cat' supports dim ≤ ${Zn} (got ${n})`);return n}function NP(e,t){const n=[];for(let r=1;r<e.length;r++){const s=e[r];if(!Me(s))throw new le(`'cat' arg ${r+1} must be numeric (got ${ze(s)})`);if(s.elem!=="double"&&s.elem!=="logical")throw new le(`'cat' arg ${r+1} must be a double or logical (got ${s.elem})`);if(De(s)){const a=new Array(t).fill(1);if(s.isComplex){const c=An(s);n.push({shape:a,total:1,exact:c!==void 0?c.re:void 0,exactIm:c!==void 0?c.im:void 0,isComplex:!0,idx:r})}else{const c=Je(s);n.push({shape:a,total:1,exact:c,isComplex:!1,idx:r})}continue}if(s.dims.length>t)throw new W(`'cat' result ndim ${t} cannot accommodate input rank ${s.dims.length}`);const o=[];let i=1;for(let a=0;a<t;a++){const c=a<s.dims.length?s.dims[a]:{kind:"exact",value:1};c.kind==="exact"?(o.push(c.value),i!==null&&(i*=c.value)):(o.push(null),i=null)}if(s.isComplex){const a=rn(s);n.push({shape:o,total:i,exact:a!==void 0?a.re:void 0,exactIm:a!==void 0?a.im:void 0,isComplex:!0,idx:r})}else{const a=Mt(s);n.push({shape:o,total:i,exact:a,isComplex:!1,idx:r})}}return n}function AP(e,t,n){let r=-1;for(let l=0;l<e.length;l++)if(e[l].total!==null&&e[l].total>0){r=l;break}if(r===-1){if(e.every(l=>l.total===0)){const l=new Array(n).fill(0);return l[0]=0,l[1]=0,{shape:l,allStatic:!0,refShape:l.slice()}}return{shape:new Array(n).fill(null),allStatic:!1}}const s=e[r].shape;if(s.some(l=>l===null))return{shape:new Array(n).fill(null),allStatic:!1};const o=s.map(l=>l);let i=!0;for(let l=0;l<e.length;l++){if(l===r)continue;const u=e[l];if(u.shape.some(f=>f===null)){i=!1;continue}if(u.total!==0){for(let f=0;f<n;f++)if(f!==t&&u.shape[f]!==o[f])throw new le(`'cat' dimension mismatch on dimension ${f+1}: arg ${r+2} has size ${o[f]}, arg ${u.idx+1} has size ${u.shape[f]}`)}}if(!i){const l=o.slice();return l[t]=null,{shape:l,allStatic:!1}}let a=0;for(const l of e){if(l.shape.some(f=>f===null))return{shape:new Array(n).fill(null),allStatic:!1};const u=l.shape.map(f=>f);if(l.total===0){let f=!0;for(let h=0;h<n;h++)if(h!==t&&u[h]!==o[h]){f=!1;break}if(!f)continue}a+=u[t]}const c=o.slice();return c[t]=a,{shape:c,allStatic:!0,refShape:o}}function F0(e,t,n,r,s,o="re"){for(const u of e){if(u.shape.some(f=>f===null)||u.total===null)return;if(u.total!==0){if(o==="re"){if(u.exact===void 0)return}else if(u.isComplex&&u.exactIm===void 0)return}}const i=Dt(t);if(i>wt)return;const a=new Float64Array(i);if(i===0)return a;let c=1;for(let u=0;u<r;u++)c*=t[u];let l=1;for(let u=r+1;u<s;u++)l*=t[u];for(let u=0;u<l;u++){let f=u*c*t[r];for(const h of e){if(h.total===0){const _=h.shape.map(b=>b);let y=!0;for(let b=0;b<s;b++)if(b!==r&&_[b]!==n[b]){y=!1;break}if(!y)continue;continue}const p=h.shape.map(_=>_)[r],d=c*p,g=u*d,w=o==="re"?h.exact:h.exactIm;if(w===void 0){f+=d;continue}if(typeof w=="number")a[f]=w;else if(w instanceof Float64Array)a.set(w.subarray(g,g+d),f);else return;f+=d}}return a}const EP={name:"cat",transfer(e,t){if(t!==1)throw new W(`'cat' does not support multi-output (nargout=${t})`);if(e.length<1)throw new le("'cat' requires at least the dim argument");const n=Im(e);if(e.length===1)return[et([0,0])];let r=Math.max(2,n);for(let m=1;m<e.length;m++){const p=e[m];Me(p)&&!De(p)&&p.dims.length>r&&(r=p.dims.length)}if(r>Zn)throw new W(`'cat' result ndim ${r} exceeds ${Zn}`);const s=NP(e,r),o=s.some(m=>m.isComplex),{shape:i,allStatic:a,refShape:c}=AP(s,n-1,r);if(a){const m=i.map(d=>d);for(;m.length>2&&m[m.length-1]===1;)m.pop();for(;m.length<2;)m.push(1);if(o){let d;if(c!==void 0){const g=F0(s,i.map(_=>_),c,n-1,r,"re"),w=F0(s,i.map(_=>_),c,n-1,r,"im");g!==void 0&&w!==void 0&&(d={re:g,im:w})}return[Ut(m,d)]}let p;if(c!==void 0){const d=F0(s,i.map(g=>g),c,n-1,r);d!==void 0&&(p=d)}return[et(m,p)]}const l=[];let u=!1;for(const m of i){if(m===null){u=!0;break}l.push(m)}if(!u){const m=l.slice();for(;m.length>2&&m[m.length-1]===1;)m.pop();for(;m.length<2;)m.push(1);return o?[Ut(m)]:[et(m)]}const f=i.map(m=>m===null?{kind:"unknown"}:m===1?{kind:"exact",value:1}:{kind:"exact",value:m});for(;f.length>2&&f[f.length-1].kind==="exact"&&f[f.length-1].value===1;)f.pop();const h={kind:"Numeric",elem:"double",isComplex:o,dims:f,sign:"unknown"};return f.every(m=>m.kind==="exact")&&(h.shape=f.map(m=>m.value)),[h]},emitC({argsC:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_cat");const r=Im(t),s=t.length-1,o=t.slice(1).some(a=>Me(a)&&a.isComplex);if(s===0)return o?(n("mtoc2_tensor_alloc_nd_complex"),"mtoc2_tensor_alloc_nd_complex(2, (long[]){0L, 0L})"):(n("mtoc2_tensor_alloc_nd"),"mtoc2_tensor_alloc_nd(2, (long[]){0L, 0L})");if(o){n("mtoc2_cscalar");const a=[];for(let c=1;c<t.length;c++){const l=t[c];Me(l)&&De(l)?l.isComplex?a.push(`{.kind = 1, .scalar_re = creal(${e[c]}), .scalar_im = cimag(${e[c]}), .tensor = {0}}`):a.push(`{.kind = 1, .scalar_re = (double)(${e[c]}), .scalar_im = 0.0, .tensor = {0}}`):a.push(`{.kind = 0, .scalar_re = 0.0, .scalar_im = 0.0, .tensor = ${e[c]}}`)}return`mtoc2_tensor_cat_complex(${r}L, ${s}, (mtoc2_cat_complex_arg_t[]){${a.join(", ")}})`}const i=[];for(let a=1;a<t.length;a++){const c=t[a];Me(c)&&De(c)?i.push(`{.kind = 1, .scalar = (double)(${e[a]})}`):i.push(`{.kind = 0, .tensor = ${e[a]}}`)}return`mtoc2_tensor_cat(${r}L, ${s}, (mtoc2_cat_arg_t[]){${i.join(", ")}})`},emitJs({argsJs:e,argTypes:t,useRuntime:n}){n("mtoc2_tensor_cat");const r=Im(t),s=t.length-1,o=t.slice(1).some(c=>Me(c)&&c.isComplex);if(s===0)return o?(n("mtoc2_tensor_alloc_nd_complex"),"mtoc2_tensor_alloc_nd_complex(2, [0, 0])"):(n("mtoc2_tensor_alloc_nd"),"mtoc2_tensor_alloc_nd(2, [0, 0])");const i=[];for(let c=1;c<t.length;c++)i.push(e[c]);return`${o?"mtoc2_tensor_cat_complex":"mtoc2_tensor_cat"}(${r}, ${s}, [${i.join(", ")}])`},call({args:e,argTypes:t}){const n=Im(t),r=t.slice(1).some(o=>Me(o)&&o.isComplex),s=[];for(let o=1;o<e.length;o++)s.push(e[o]);return r?[h6(n,s.length,s)]:[f6(n,s.length,s)]}};function IP(e){if(e.length===0)return et([0,0],new Float64Array(0));if(e.length===1){const n=e.charCodeAt(0);return Be(ft(n),n)}const t=new Float64Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return et([1,e.length],t)}function Uk(e){return Number.isInteger(e)&&Math.abs(e)<1e16?`${e}.0`:String(e)}function FP(e){const t=[];for(let n=0;n<e.length;n++)t.push(Uk(e.charCodeAt(n)));return t.join(", ")}function jP(e){const t=[];for(let n=0;n<e.length;n++)t.push(String(e.charCodeAt(n)));return t.join(", ")}const RP={name:"double",transfer(e,t){if(e.length!==1)throw new le(`'double' expects 1 arg(s), got ${e.length}`);if(t!==1)throw new W(`'double' does not support multi-output (nargout=${t})`);const n=e[0];if(Me(n)){if(n.isComplex&&De(n)){if(n.exact!==void 0&&typeof n.exact=="object"&&!(n.exact instanceof Float64Array)&&typeof n.exact.re=="number"){const s=n.exact.re;return[Be(ft(s),s)]}return[Be()]}return[{...n,elem:"double"}]}if(n.kind==="Char"){if(n.exact===void 0)throw new W("'double' on a non-exact char value is not supported (only char literals fold to numeric)");return[IP(n.exact)]}throw new le(`'double' arg must be numeric or char (got ${n.kind})`)},emitC({argsC:e,argTypes:t,useRuntime:n}){const r=t[0];if(Me(r))return r.isComplex&&De(r)?(n("mtoc2_cscalar"),`mtoc2_creal(${e[0]})`):qe(r)?r.isComplex?(n("mtoc2_tensor_copy_complex"),`mtoc2_tensor_copy_complex(${e[0]})`):(n("mtoc2_tensor_copy"),`mtoc2_tensor_copy(${e[0]})`):e[0];if(r.kind==="Char"){const s=r.exact;return s.length===0?(n("mtoc2_tensor_alloc"),"mtoc2_tensor_alloc(0, 0)"):s.length===1?Uk(s.charCodeAt(0)):(n("mtoc2_tensor_from_row"),`mtoc2_tensor_from_row((double[]){${FP(s)}}, ${s.length})`)}throw new le(`internal: 'double' emitC reached on type ${r.kind}`)},emitJs({argsJs:e,argTypes:t,useRuntime:n}){const r=t[0];if(Me(r))return r.isComplex&&De(r)?`(${e[0]}).re`:qe(r)?r.isComplex?`({mtoc2Tag:"tensor", shape:${e[0]}.shape.slice(), data:new Float64Array(${e[0]}.data), imag:new Float64Array(${e[0]}.imag)})`:`({mtoc2Tag:"tensor", shape:${e[0]}.shape.slice(), data:new Float64Array(${e[0]}.data)})`:r.elem==="logical"?`(+${e[0]})`:e[0];if(r.kind==="Char"){const s=r.exact;return s.length===0?(n("mtoc2_tensor_alloc"),"mtoc2_tensor_alloc(0, 0)"):s.length===1?String(s.charCodeAt(0)):(n("mtoc2_tensor_from_row"),`mtoc2_tensor_from_row([${jP(s)}], ${s.length})`)}throw new le(`internal: 'double' emitJs reached on type ${r.kind}`)},call({args:e}){const t=e[0];if(typeof t=="number")return[t];if(typeof t=="boolean")return[t?1:0];if(un(t))return[t.re];if(Wt(t))return t.imag!==void 0?[bR(t.shape.slice(),new Float64Array(t.data),new Float64Array(t.imag))]:[Bi(t.shape.slice(),new Float64Array(t.data))];if(Er(t)){const n=t.value;if(n.length===0)return[Bi([0,0],new Float64Array(0))];if(n.length===1)return[n.charCodeAt(0)];const r=new Float64Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return[Bi([1,n.length],r)]}throw new le(`'double' got an unsupported runtime value (typeof = ${typeof t})`)}};function j0(e){if(e.kind==="Numeric"&&e.dims.some(t=>t.kind!=="exact"||t.value!==1))return{copy:e.isComplex?"mtoc2_tensor_copy_complex":"mtoc2_tensor_copy",assign:"mtoc2_tensor_assign",cType:"mtoc2_tensor_t",isRuntime:!0};if(e.kind==="String")return{copy:"mtoc2_string_copy",assign:"mtoc2_string_assign",cType:"mtoc2_string_t",isRuntime:!0};if(e.kind==="Char")return{copy:"mtoc2_char_tensor_copy",assign:"mtoc2_char_tensor_assign",cType:"mtoc2_char_tensor_t",isRuntime:!0};if(e.kind==="Struct"){const t=Wd(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}if(e.kind==="Class"){const t=sb(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}if(e.kind==="Handle"){const t=nb(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}if(e.kind==="Cell"){const t=Xd(e);return{copy:`${t}_copy`,assign:`${t}_assign`,cType:t,isRuntime:!1}}return null}function Fm(e,t){if(e.length===0)throw new le("'deal' requires at least one input argument");if(t<1)throw new W(`'deal' requires at least one output (got nargout=${t})`);if(e.length===1)return new Array(t).fill(0);if(e.length!==t)throw new le(`'deal': number of inputs (${e.length}) must match number of outputs (${t})`);return e.map((n,r)=>r)}function LP(e,t){if(!Kn(e)&&!hr(e))throw new W(`'deal' input ${t+1} has type ${ze(e)}; this type isn't supported in a multi-output slot`)}const DP={name:"deal",transfer(e,t){const n=Fm(e,t);if(t>=2)for(let r=0;r<t;r++)LP(e[n[r]],n[r]);return n.map(r=>e[r])},emitC({argsC:e,argTypes:t,nargout:n,outArgsC:r,useRuntime:s}){const o=Fm(t,n);if(r!==void 0){if(n>=2){const f=[],h=[];for(let m=0;m<n;m++){const p=t[o[m]],d=e[o[m]],g=j0(p),w=`_mtoc2_deal_t${m}`;g!==null?(g.isRuntime&&(s(g.copy),s(g.assign)),f.push(`${g.cType} ${w} = ${g.copy}(${d});`),h.push(`${g.assign}(${r[m]}, ${w})`)):(f.push(`double ${w} = ${d};`),h.push(`(*${r[m]} = ${w})`))}return`${f.join(" ")} (void)(${h.join(", ")})`}const c=t[o[0]],l=e[o[0]],u=j0(c);return u!==null?(u.isRuntime&&(s(u.copy),s(u.assign)),`((void)(${u.assign}(${r[0]}, ${u.copy}(${l}))))`):`((void)(*${r[0]} = ${l}))`}const i=t[o[0]],a=j0(i);return a!==null?(a.isRuntime&&s(a.copy),`${a.copy}(${e[o[0]]})`):e[o[0]]},emitJs({argsJs:e,argTypes:t,nargout:n,outTargetsJs:r,useRuntime:s}){const o=Fm(t,n),i=a=>{const c=t[o[a]];return hr(c)?(s("mtoc2_deep_clone"),`mtoc2_deep_clone(${e[o[a]]})`):e[o[a]]};if(r!==void 0){const a=[];for(let c=0;c<n;c++)a.push(i(c));return`[${a.join(", ")}]`}return i(0)},call({args:e,argTypes:t,nargout:n}){const r=Fm(t,n),s=i=>{const a=e[r[i]];return hr(t[r[i]])?If(a):a},o=[];for(let i=0;i<n;i++)o.push(s(i));return o}},jm="'feval' must be intercepted by the lowerer or interpreter (see src/lowering/lowerFuncCall.ts and src/interpreter/interpreterFunctions.ts); reaching the builtin registry hook indicates a routing bug or an unsupported first argument shape (only @name handles, in-scope handle vars, and char-name strings are supported — runtime-computed handle expressions are deferred)",TP={name:"feval",transfer(e){throw e.length<1?new W("'feval' expects at least 1 argument (the function handle or name), got 0"):new W(jm)},emitC(){throw new W(jm)},emitJs(){throw new W(jm)},call(){throw new W(jm)}};function Rm(e,t,n){if(t.length!==1)throw new le(`'${e}' expects 1 arg(s), got ${t.length}`);if(n>1)throw new W(`'${e}' does not support multi-output (nargout=${n})`)}function R0(e){return Wt(e)?e.shape:Er(e)?[1,e.value.length]:[1,1]}function kl(e,t,n){return{name:e,transfer(r,s){return Rm(e,r,s),[at(t(r[0]))]},emitC({argTypes:r}){return t(r[0])?"1.0":"0.0"},emitJs({argTypes:r}){return t(r[0])?"true":"false"},call({args:r}){return[n(r[0])]}}}const PP=kl("islogical",e=>Me(e)&&e.elem==="logical",e=>!!(typeof e=="boolean"||Wt(e)&&e.isLogical)),BP=kl("isfloat",e=>Me(e)&&e.elem==="double",e=>typeof e=="number"?!0:typeof e=="boolean"?!1:un(e)?!0:Wt(e)?!e.isLogical:!1),qP=kl("ischar",e=>xo(e),e=>Er(e)),zP=kl("isstring",e=>Jo(e),e=>typeof e=="string"),VP=kl("isinteger",()=>!1,()=>!1);function Qa(e){return Me(e)?e.dims.length:2}const UP={name:"ndims",transfer(e,t){Rm("ndims",e,t);const n=Math.max(2,Qa(e[0]));return[Be(ft(n),n)]},emitC({argTypes:e}){return`${Math.max(2,Qa(e[0])).toFixed(1)}`},emitJs({argTypes:e}){return`${Math.max(2,Qa(e[0]))}`},call({args:e}){return[Math.max(2,R0(e[0]).length)]}},WP={name:"ismatrix",transfer(e,t){return Rm("ismatrix",e,t),[at(Qa(e[0])<=2)]},emitC({argTypes:e}){return Qa(e[0])<=2?"1.0":"0.0"},emitJs({argTypes:e}){return Qa(e[0])<=2?"true":"false"},call({args:e}){return[R0(e[0]).length<=2]}};function Wk(e,t){const n=r=>{if(!Me(r))return!1;const s=r.dims;return s.length!==2?!1:Dn(s[t])?!0:s[t].kind==="exact"?!1:"runtime"};return{name:e,transfer(r,s){Rm(e,r,s);const o=n(r[0]);return o==="runtime"?[at()]:[at(o)]},emitC({argTypes:r,argsC:s}){const o=n(r[0]);return o===!0?"1.0":o===!1?"0.0":`((${s[0]}).ndim == 2 && (${s[0]}).dims[${t}] == 1)`},emitJs({argTypes:r,argsJs:s}){const o=n(r[0]);return o===!0?"true":o===!1?"false":`(${s[0]}.shape.length === 2 && ${s[0]}.shape[${t}] === 1)`},call({args:r}){const s=R0(r[0]);return[s.length===2&&s[t]===1]}}}const XP=Wk("isrow",0),HP=Wk("iscolumn",1);function L0(e,t,n){if(!os(e)||!os(t))return!1;if(!(e.kind!=="Char"&&e.kind!=="String")&&!(t.kind!=="Char"&&t.kind!=="String")&&!(e.exact===void 0||t.exact===void 0))return n==="case-fold"?e.exact.toLowerCase()===t.exact.toLowerCase():e.exact===t.exact}function YP(e,t,n){if(t.length!==2)throw new le(`'${e}' expects 2 arg(s), got ${t.length}`);if(n!==1)throw new W(`'${e}' does not support multi-output (nargout=${n})`)}function Xk(e){return typeof e=="string"?e:Er(e)?e.value:null}function Hk(e,t,n){const r=t==="case-fold"?ED:AD;return{name:e,transfer(s,o){YP(e,s,o);const i=L0(s[0],s[1],t);return[i===void 0?at():at(i)]},emitC({argsC:s,argTypes:o,useRuntime:i}){const a=L0(o[0],o[1],t);if(a!==void 0)return a?"1.0":"0.0";i(n);const c=Vi(s[0],o[0]),l=Vi(s[1],o[1]);return`${n}(${c}, ${l})`},emitJs({argsJs:s,argTypes:o,useRuntime:i}){const a=L0(o[0],o[1],t);return a!==void 0?a?"true":"false":(i(n),`(${n}(${s[0]}, ${s[1]}) !== 0)`)},call({args:s}){const o=Xk(s[0]),i=Xk(s[1]);return o===null||i===null?[!1]:[r(o,i)!==0]}}}const JP=Hk("strcmp","exact","mtoc2_strcmp"),ZP=Hk("strcmpi","case-fold","mtoc2_strcmpi");function KP(e){if(typeof e=="object"&&e!==null){const t=e;if(t.mtoc2Tag==="char"&&typeof t.value=="string")return t.value}return e}const GP=lF;function QP(e){let t="";for(const n of e)n==="\\"||n==='"'?t+="\\"+n:t+=n;return t}function OP(e){const t=QP(e);return{name:e,transfer(n,r){if(r!==1)throw new W(`'${e}' does not support multi-output (nargout=${r})`);return Ya(e,n,0),[Fi]},emitC({argsC:n,argTypes:r,useRuntime:s}){s("mtoc2_plot_dispatch");const o=[];for(let i=0;i<r.length;i++)o.push(Ja(e,n[i],r[i],i));return`mtoc2_plot_dispatch("${t}", ${o.length}, ${Za(o)})`},emitJs({argsJs:n,useRuntime:r}){return r("mtoc2_plot_dispatch"),`mtoc2_plot_dispatch(${[JSON.stringify(e),...n].join(", ")})`},call({args:n,ctx:r}){return globalThis.$write=r.helpers.write,qR(e,...n.map(KP)),[]}}}const eB=GP.map(OP);for(const e of[...eB,TD,PD,_l,yl,VD,UD,WD,xl,KD,GD,QD,OD,eT,tT,nT,sT,lT,fT,hT,gT,wT,_T,jT,RT,LT,BT,qT,zT,VT,F8,UT,WT,YT,JT,ZT,QT,OT,e8,t8,n8,r8,o8,c8,u8,f8,m8,h8,p8,d8,E8,I8,j8,R8,L8,D8,T8,P8,B8,q8,z8,V8,U8,X8,H8,Y8,O8,n7,o7,i7,a7,c7,m7,h7,p7,d7,g7,_7,x7,b7,k7,v7,M7,$7,C7,S7,N7,A7,E7,I7,F7,j7,R7,L7,D7,T7,B7,q7,z7,V7,U7,W7,H7,Y7,Q7,eP,nP,rP,sP,oP,iP,qP,zP,VP,PP,BP,UP,WP,XP,HP,cP,gP,wP,_P,yP,bP,MP,$P,CP,SP,EP,RP,DP,TP,JP,ZP])xR(e);function tB(e){switch(e){case je.Pow:return"^";case je.ElemPow:return".^";case je.LeftDiv:return"\\";case je.ElemLeftDiv:return".\\";case je.OrOr:return"||";case je.AndAnd:return"&&";case je.BitOr:return"|";case je.BitAnd:return"&";default:return e}}function nB(e){switch(e){case gn.Not:return"~";case gn.Transpose:return"'";case gn.NonConjugateTranspose:return".'";default:return e}}function rB(e,t){switch(e){case je.Add:return"plus";case je.Sub:return"minus";case je.Mul:return"mtimes";case je.ElemMul:return"times";case je.Div:return"mrdivide";case je.ElemDiv:return"rdivide";case je.Equal:return"eq";case je.NotEqual:return"ne";case je.Less:return"lt";case je.LessEqual:return"le";case je.Greater:return"gt";case je.GreaterEqual:return"ge";case je.OrOr:return"oror";case je.AndAnd:return"andand";case je.BitOr:return"or";case je.BitAnd:return"and";case je.Pow:return"mpower";case je.ElemPow:return"power";default:throw new W(`binary operator '${tB(e)}' is not yet supported`,t)}}function sB(e,t){switch(e){case gn.Minus:return"uminus";case gn.Plus:return"uplus";case gn.Transpose:case gn.NonConjugateTranspose:return"transpose";case gn.Not:return"not";default:throw new W(`unary operator '${nB(e)}' is not yet supported`,t)}}function Lm(e){return e.type==="Range"||e.type==="Colon"}function oB(e,t,n){if(e.base.type!=="Member")throw new W(`internal: resolveMemberRootedIndexBase called with non-Member base (got ${e.base.type})`,t);const r=_R(e.base);if(r===null)throw new W(`${Xi(n)} requires a root variable`,e.base.span);const{root:s,fields:o}=r,i=s.name,a=this.envLookup(i);if(a===void 0)throw new le(`use of undefined variable '${i}'`,s.span);if(a.ty.kind!=="Struct"&&a.ty.kind!=="Class")throw new W(`${Xi(n)} of '${i}.${o.join(".")}' but '${i}' is ${ze(a.ty)}; only struct and class fields can be indexed`,e.base.span);let c=a.ty;for(let m=0;m<o.length;m++){const p=o[m],d=cl(c,p);if(d===void 0)throw c.kind==="Class"&&this.classReg(c.className)?.dependentProperties.has(p)?new W(`${Xi(n)} of dependent property '${i}.${o.slice(0,m+1).join(".")}' via indexing is not supported in v1`,e.base.span):new le(`'${i}.${o.slice(0,m+1).join(".")}': no such field on type ${ze(c)}`,e.base.span);c=d}if(!Me(c))throw new W(`${Xi(n)} of '${i}.${o.join(".")}' but the field has type ${ze(c)} (only numeric fields can be indexed)`,e.base.span);if(!qe(c))throw new W(Jk(n,`${i}.${o.join(".")}`,c),t);if(c.elem!=="double")throw new W(`${Xi(n)} into ${ze(c)} is not yet supported`,t);const l=c.dims.length,u=e.indices.length;if(u===0&&(n==="read"||n==="write"))throw new W(n==="read"?`indexing '${i}.${o.join(".")}' requires at least one index`:"indexed write requires at least one index",t);if(u!==1&&u!==l)throw new W(Zk(n,u,l),t);const f=`${a.cName}.${o.join(".")}`;return{rootVar:{kind:"Var",name:i,cName:a.cName,ty:a.ty,span:e.base.span},fieldPath:o,leafTy:c,slotCName:f}}function Yk(e,t,n){if(e.base.type==="Member"){const r=oB.call(this,e,t,n);return{base:r.rootVar,baseTy:r.leafTy,baseCName:r.slotCName,fieldPath:r.fieldPath,leafTy:r.leafTy,displayName:`${r.rootVar.name}.${r.fieldPath.join(".")}`}}if(e.base.type==="Ident"){const r=e.base.name,s=D0.call(this,r,e.indices.length,t,{baseSpan:e.base.span,notInScope:"user-facing",operation:n});return{base:s.base,baseTy:s.baseTy,baseCName:s.baseCName,displayName:r}}throw new W(`indexed assignment requires a simple variable or member chain on the left (got ${e.base.type})`,t)}function D0(e,t,n,r){const{baseSpan:s=n,notInScope:o,operation:i}=r,a=this.envLookup(e);if(a===void 0){if(o==="internal"){const f=i==="read"?"lowerIndexLoad":"lowerIndexSlice";throw new W(`internal: ${f} called for '${e}' which is not in scope`,n)}throw new le(`use of undefined variable '${e}'`,s)}if(!Me(a.ty))throw new W(`${Xi(i)} into ${ze(a.ty)} is not yet supported`,n);if(i==="read"&&De(a.ty))throw new W(`indexing into a scalar variable '${e}' is not yet supported`,n);if(!qe(a.ty))throw new W(Jk(i,e,a.ty),n);if(a.ty.elem!=="double")throw new W(`${Xi(i)} into ${ze(a.ty)} is not yet supported`,n);const c=a.ty.dims.length;if(t===0&&(i==="read"||i==="write")){const f=i==="read"?`indexing '${e}' requires at least one index`:"indexed write requires at least one index";throw new W(f,n)}if(t!==1&&t!==c)throw new W(Zk(i,t,c),n);const l=a.cName,u={kind:"Var",name:e,cName:l,ty:a.ty,span:s};return{baseTy:a.ty,baseCName:l,base:u}}function Xi(e){switch(e){case"read":return"indexing";case"write":return"indexed write";case"sliceRead":return"range/colon indexing";case"sliceWrite":return"range/colon indexed write"}}function Jk(e,t,n){switch(e){case"read":return`cannot index variable '${t}' with type ${ze(n)}`;case"write":return`indexed write requires a multi-element tensor (got ${ze(n)})`;case"sliceRead":return`range/colon indexing requires a multi-element tensor (got ${ze(n)})`;case"sliceWrite":return`range/colon indexed write requires a multi-element tensor (got ${ze(n)})`}}function Zk(e,t,n){switch(e){case"read":return`${t}-index access into a ${n}-D tensor is not yet supported (use 1 linear index or ${n} per-axis indices)`;case"write":return`${t}-index write into a ${n}-D tensor is not yet supported (use 1 linear index or ${n} per-axis indices)`;case"sliceRead":return`range/colon indexing of a ${n}-D tensor requires either 1 slot (linear) or ${n} slots (one per axis); got ${t}`;case"sliceWrite":return`range/colon indexed write into a ${n}-D tensor requires either 1 slot (linear) or ${n} slots (one per axis); got ${t}`}}function iB(e){if(e.rows.length===0)return{kind:"TensorBuild",elements:[],shape:[0,0],ty:et([0,0]),span:e.span};const t=[];let n=!1,r=!1;for(const d of e.rows){const g=[];for(const w of d){const _=this.lowerExpr(w),y=_.ty;if(!Me(y))throw new W(`bracket literal cell must be a numeric scalar or tensor (got ${ze(y)})`,w.span);if(y.elem!=="double"&&y.elem!=="logical")throw new W(`bracket literal cell must be a real double or logical (got ${y.elem})`,w.span);if(y.dims.length>2)throw new W(`bracket concatenation requires 2-D cells (got a rank-${y.dims.length} tensor); use 'cat'/'permute' for higher-rank inputs`,w.span);if(y.isComplex){if(qe(y))throw new W("bracket literal with a complex tensor cell is not yet supported",w.span);r=!0}if(De(y)){g.push({kind:"scalar",expr:_,ty:y});continue}const b=y.dims[0],k=y.dims[1],M=b.kind==="exact"?b.value:null,$=k.kind==="exact"?k.value:null;if(M===0||$===0){g.push({kind:"empty",ty:y});continue}n=!0,g.push({kind:"tensor",expr:_,ty:y,rows:M,cols:$})}t.push(g)}if(!n&&t.every(d=>d.every(g=>g.kind==="scalar"))){const d=t.length,g=t[0].length;for(const M of t)if(M.length!==g)throw new le(`bracket horzcat row-count mismatch: row 1 has ${g} cells, another row has ${M.length}`,e.span);const w=g,_=d*w,y=new Array(_);for(let M=0;M<d;M++)for(let $=0;$<w;$++){const N=t[M][$];if(N.kind!=="scalar")throw new Error("internal: unexpected non-scalar in scalar fast path");y[$*d+M]=N.expr}if(d===1&&w===1)return y[0];if(r){let M;if(_<=wt){const N=new Float64Array(_),E=new Float64Array(_);let R=!0;for(let D=0;D<_;D++){const I=Us(y[D].ty);if(I===void 0){R=!1;break}N[D]=I.re,E[D]=I.im}R&&(M={re:N,im:E})}const $=Ut([d,w],M);return{kind:"TensorBuild",elements:y,shape:[d,w],ty:$,span:e.span}}let b;if(_<=wt){const M=new Float64Array(_);let $=!0;for(let N=0;N<_;N++){const E=Je(y[N].ty);if(E===void 0){$=!1;break}M[N]=E}$&&(b=M)}const k=et([d,w],b);return y.every(M=>Me(M.ty)&&M.ty.elem==="logical")&&(k.elem="logical",k.sign="nonneg"),{kind:"TensorBuild",elements:y,shape:[d,w],ty:k,span:e.span}}if(r)throw new W("bracket literal mixing complex cells with multi-element tensor cells is not yet supported (concat lane-copy is deferred)",e.span);const s=[],o=[],i=[],a=[];for(let d=0;d<t.length;d++){const g=t[d],w=[],_=[];let y,b=0;for(let k=0;k<g.length;k++){const M=g[k];if(M.kind==="empty")continue;const $=M.kind==="scalar"?1:M.rows,N=M.kind==="scalar"?1:M.cols;if(y===void 0)y=$;else{if(y!==null&&$!==null&&y!==$)throw new le(`bracket horzcat row-height mismatch: cell ${k+1} on row ${d+1} has ${$} row(s) but a neighbor in the same row has ${y}`,e.rows[d][k].span);y===null&&$!==null&&(y=$)}w.push(M),_.push(N),b=b===null||N===null?null:b+N}y!==void 0&&(s.push(w),o.push(y),i.push(b),a.push(_))}if(s.length===0)return{kind:"TensorBuild",elements:[],shape:[0,0],ty:et([0,0]),span:e.span};let c=null;for(const d of i)if(d!==null){if(c===null)c=d;else if(c!==d)throw new le(`bracket vertcat column-count mismatch: a row has ${c} column(s), another has ${d}`,e.span)}const l=c;let u=0;for(const d of o){if(d===null){u=null;break}u+=d}if(s.length===1&&s[0].length===1)return s[0][0].expr;const f=s.map(d=>d.map(g=>g.expr));let h;if(u!==null&&l!==null&&o.every(d=>d!==null)&&a.every(d=>d.every(g=>g!==null))){const d=u*l;if(d<=wt){const g=new Float64Array(d);let w=!0,_=0;for(let y=0;y<s.length&&w;y++){const b=s[y];let k=0;for(let M=0;M<b.length&&w;M++){const $=b[M],N=$.kind==="scalar"?1:$.rows,E=$.kind==="scalar"?1:$.cols;if($.kind==="scalar"){const R=Je($.ty);if(R===void 0){w=!1;break}const D=_+k*u;g[D]=R}else{const R=$.ty.exact;if(!(R instanceof Float64Array)){w=!1;break}for(let D=0;D<E;D++)for(let I=0;I<N;I++){const q=_+I+(k+D)*u,Y=I+D*N;g[q]=R[Y]}}k+=E}_+=o[y]}w&&(h=g)}}const p=Zt([u===null?{kind:"unknown"}:u===1?nn:{kind:"exact",value:u},l===null?{kind:"unknown"}:l===1?nn:{kind:"exact",value:l}]);return h!==void 0&&p.shape!==void 0&&(p.exact=h,p.sign=ol(h)),{kind:"TensorConcat",cells:f,rowHeights:o,cellCols:a,shape:[u,l],ty:p,span:e.span}}function aB(e){if(e.rows.length===0){const l=[0,0];return{kind:"CellLit",elements:[],shape:l,ty:il(l,[]),span:e.span}}const t=e.rows.length,n=e.rows[0].length;for(let l=0;l<t;l++)if(e.rows[l].length!==n)throw new W(`cell literal: row ${l+1} has ${e.rows[l].length} cells, expected ${n} (every row must have the same width)`,e.span);const r=[];for(let l=0;l<t;l++){const u=[];for(let f=0;f<n;f++){const h=this.lowerExpr(e.rows[l][f]);if(zd(h.ty))throw new W(`cell literal slot: cannot use the result of a zero-output function as a value (got ${ze(h.ty)})`,e.rows[l][f].span);u.push(h)}r.push(u)}const s=[],o=[];for(let l=0;l<n;l++)for(let u=0;u<t;u++)s.push(r[u][l]),o.push(r[u][l].ty);const i=[t,n],a=Dt(i);if(a>wt)throw new W(`cell literal with ${a} slots exceeds the EXACT_ARRAY_MAX_ELEMENTS cap (${wt})`,e.span);return{kind:"CellLit",elements:s,shape:i,ty:il(i,o),span:e.span}}function cB(e){if(e.base.type!=="Ident")throw new W("cell brace indexing supports a bare cell variable as the base; member-rooted forms (e.g. 'obj.f{i}') are not yet supported",e.span);const t=this.env.get(e.base.name);if(t===void 0)throw new le(`undefined variable '${e.base.name}'`,e.span);if(!ys(t.ty))throw new le(`'${e.base.name}' is not a cell (got ${ze(t.ty)}); brace indexing 'c{...}' requires a cell-typed variable`,e.span);const n=t.ty,r=t.cName;if(e.indices.length===0)throw new W("cell brace indexing requires at least one index",e.span);if(e.indices.length>2)throw new W(`cell brace indexing supports 1 or 2 indices (got ${e.indices.length})`,e.span);const s=e.indices.map(i=>{if(i.type==="Colon"||i.type==="Range")throw new W("cell brace indexing with ':' / range slices not yet supported",i.span);const a=this.lowerExpr(i);if(!Me(a.ty)||!De(a.ty)||a.ty.isComplex)throw new le(`cell brace index must be a real scalar (got ${ze(a.ty)})`,i.span);return a}),o=lB(n,s,e.span);return{kind:"CellIndexLoad",base:{kind:"Var",name:e.base.name,cName:r,ty:n,span:e.base.span},indices:s,ty:o,span:e.span}}function lB(e,t,n){if(e.mode==="uniform")return e.elem;const r=e.elements,s=e.shape;if(s===void 0)throw new W("internal: tuple cell missing exact shape",n);const o=Kk(t,e);if(o!==null){if(o<0||o>=r.length)throw new le(`cell brace index out of range: slot ${o+1} is outside the cell's ${Dt(s)} slots`,n);return r[o]}if(r.length===0)throw new le("cell brace read into an empty cell {}",n);let i=r[0];for(let a=1;a<r.length;a++)if(i=Li(i,r[a]),i.kind==="Unknown")throw new W(`cell brace read with a non-static index requires all slot types to unify; got divergent slot types (slot 1: ${ze(r[0])}, slot ${a+1}: ${ze(r[a])})`,n);return i}function Kk(e,t){const n=t.shape;if(n===void 0)return null;if(e.length===1){if(e[0].kind!=="NumLit")return null;const r=e[0].value;return!Number.isInteger(r)||r<1?null:r-1}if(e.length===2){if(e[0].kind!=="NumLit"||e[1].kind!=="NumLit")return null;const r=e[0].value-1,s=e[1].value-1;if(r<0||s<0)return null;const o=n[0];return s*o+r}return null}function uB(e,t,n){if(e.base.type!=="Ident")throw new W("cell brace assignment supports a bare cell variable as the base; member-rooted forms (e.g. 'obj.f{i} = rhs') are not yet supported",n);const r=this.env.get(e.base.name);if(r===void 0)throw new le(`undefined variable '${e.base.name}' (must be initialised before brace-indexed assignment)`,n);if(!ys(r.ty))throw new le(`'${e.base.name}' is not a cell (got ${ze(r.ty)}); brace assignment 'c{...} = rhs' requires a cell-typed variable`,n);const s=r.ty,o=r.cName;if(e.indices.length===0)throw new W("cell brace assignment requires at least one index",n);if(e.indices.length>2)throw new W(`cell brace assignment supports 1 or 2 indices (got ${e.indices.length})`,n);const i=[],a=e.indices.map(h=>{if(h.type==="Colon"||h.type==="Range")throw new W("cell brace assignment with ':' / range slices not yet supported",h.span);const m=this.lowerExpr(h);if(!Me(m.ty)||!De(m.ty)||m.ty.isComplex)throw new le(`cell brace index must be a real scalar (got ${ze(m.ty)})`,h.span);return this.anfRequireScalarOrVar(m,i)}),c=this.lowerExpr(t);if(c.ty.kind==="Void")throw new le("cannot store the result of a zero-output function into a cell slot",t.span);const l=c,u=Kk(a,s);if(s.mode==="tuple"){const h=s.elements;if(u!==null){if(u<0||u>=h.length)throw new le(`cell brace assignment slot ${u+1} is outside the cell's ${Dt(s.shape)} slots`,n);const m=h[u];if(!ll(m,l.ty))throw new W(`cell brace assignment: rhs type ${ze(l.ty)} is not storage-equivalent to slot ${u+1}'s type ${ze(m)} (cells don't reshape mid-lifetime; introduce a new cell literal or construct the cell with the target slot type)`,n)}else for(let m=0;m<h.length;m++)if(!ll(h[m],l.ty))throw new W(`cell brace assignment with a non-static index requires every slot's storage to match the rhs; slot ${m+1} has type ${ze(h[m])}, rhs has ${ze(l.ty)}`,n)}else if(!ll(s.elem,l.ty))throw new W(`cell brace assignment: rhs type ${ze(l.ty)} is not storage-equivalent to the cell's elem type ${ze(s.elem)} (cells don't reshape mid-lifetime)`,n);const f={kind:"CellIndexStore",base:{kind:"Var",name:e.base.name,cName:o,ty:r.ty,span:e.base.span},indices:a,rhs:l,span:n};return i.length===0?f:[...i,f]}function fB(e){if(this.env.has(e.name))throw new le(`function-handle target '@${e.name}' refers to an in-scope variable, not a function`,e.span);if(is(e.name))throw new W(`builtin function handles (e.g. '@${e.name}') are not supported`,e.span);const t=this.workspace.resolve(e.name,[],this.callSite(),e.span);if(t?.kind!=="userFunction")throw new W(`unresolved function-handle target '@${e.name}'`,e.span);const n=Kx(e.name,t.ast,[]);return{kind:"HandleLit",captures:[],ty:n,span:e.span}}function mB(e){const t=new Set(e.params),n=[],r=new Set;Ir(this.env,e.body,t,n,r);const s=[],o=[];for(const f of n){if(t.has(f))throw new W(`anonymous-function parameter '${f}' shadows a captured variable; rename the parameter`,e.span);const h=this.env.get(f);if(h===void 0)throw new W(`internal: capture '${f}' lost between detection and lowering`,e.span);if(h.ty.kind!=="Numeric"&&h.ty.kind!=="Struct"&&h.ty.kind!=="Class"&&h.ty.kind!=="Handle")throw new W(`anonymous function captures '${f}' of unsupported type ${ze(h.ty)} (string / void / unknown captures are not supported)`,e.span);s.push({name:f,ty:h.ty}),o.push({name:f,value:{kind:"Var",name:f,cName:h.cName,ty:h.ty,span:e.span}})}const i=this.anonCounter++,a=`anon_${i}`,c=`anonOut_${i}`,l={type:"Function",name:a,functionId:a,params:[...e.params,...n],outputs:[c],body:[{type:"Assign",name:c,expr:e.body,suppressed:!0,span:e.span}],argumentsBlocks:[],span:e.span},u=Kx(a,l,s);return{kind:"HandleLit",captures:o,ty:u,span:e.span}}function hB(e,t,n,r){const s=t.ty,o=n.map(l=>this.lowerExpr(l));for(const l of o)this.requireValueType(l,`argument to handle '${e}'`);const i={kind:"Var",name:e,cName:t.cName,ty:s,span:r},a=s.captures.map(l=>({kind:"HandleCaptureLoad",base:i,captureName:l.name,ty:l.ty,span:r})),c=[...o,...a];return So.call(this,s.ast,c,s.targetName,r,{definingFile:s.ast.span.file})}function pB(e,t,n,r,s){const o=t.ty,i=n.map(_=>this.lowerExpr(_));for(const _ of i)this.requireValueType(_,`argument to handle '${e}'`);const a={kind:"Var",name:e,cName:t.cName,ty:o,span:s},c=o.captures.map(_=>({kind:"HandleCaptureLoad",base:a,captureName:_.name,ty:_.ty,span:s})),l=[...i,...c],u=[],f=l.map(_=>this.anfRequireScalarOrVar(_,u)),h=l.map(_=>_.ty);if(r.length>o.ast.outputs.length)throw new W(`handle '${e}' targets '${o.targetName}', which returns ${o.ast.outputs.length} output(s); ${r.length} were requested`,s);if(o.ast.outputs.length===0&&r.length>0)throw new W(`handle '${e}' targets '${o.targetName}', which has no outputs and cannot be assigned`,s);const m=r.length,p=vl.call(this,o.ast,h,o.targetName,o.ast.span.file,void 0,m,s);if(p.outputTypes.length===1){const _={kind:"Call",cName:p.cName,name:o.targetName,args:f,ty:p.outputTypes[0]??{kind:"Unknown"},span:s},y=r[0];if(y===void 0||y.type!=="Var"){const k={kind:"ExprStmt",expr:_,span:s};return u.length===0?k:[...u,k]}const b=this.recordAssignment(y.name,_,s);return u.length===0?b:[...u,b]}if(p.outputTypes.length===0){const y={kind:"ExprStmt",expr:{kind:"Call",cName:p.cName,name:o.targetName,args:f,ty:Fi,span:s},span:s};return u.length===0?y:[...u,y]}const d=p.outputTypes.map(_=>_??{kind:"Unknown"}),g=V0.call(this,o.targetName,d,r,_=>`output '${o.ast.outputs[_]}'`,s),w={kind:"MultiAssignCall",cName:p.cName,name:o.targetName,args:f,outputs:g,span:s};return u.length===0?w:[...u,w]}function Ir(e,t,n,r,s){const o=i=>{n.has(i)||s.has(i)||is(i)||e.has(i)&&(s.add(i),r.push(i))};switch(t.type){case"Ident":o(t.name);return;case"Number":return;case"Binary":Ir(e,t.left,n,r,s),Ir(e,t.right,n,r,s);return;case"Unary":Ir(e,t.operand,n,r,s);return;case"Range":Ir(e,t.start,n,r,s),t.step&&Ir(e,t.step,n,r,s),Ir(e,t.end,n,r,s);return;case"FuncCall":o(t.name);for(const i of t.args)Ir(e,i,n,r,s);return;case"Tensor":for(const i of t.rows)for(const a of i)Ir(e,a,n,r,s);return;case"AnonFunc":{const i=new Set(n);for(const a of t.params)i.add(a);Ir(e,t.body,i,r,s);return}case"FuncHandle":return;case"Member":Ir(e,t.base,n,r,s);return;case"Index":Ir(e,t.base,n,r,s);for(const i of t.indices)Ir(e,i,n,r,s);return;case"MethodCall":Ir(e,t.base,n,r,s);for(const i of t.args)Ir(e,i,n,r,s);return;case"SuperMethodCall":for(const i of t.args)Ir(e,i,n,r,s);return;default:return}}function Gk(e){if(e.kind!=="Range")return;const t=Me(e.start.ty)&&typeof e.start.ty.exact=="number"?e.start.ty.exact:void 0,n=Me(e.end.ty)&&typeof e.end.ty.exact=="number"?e.end.ty.exact:void 0;if(e.step.kind!=="NumLit")return;const r=e.step.value;if(!(t===void 0||n===void 0)&&r!==0&&!(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)))return ob(t,r,n)}function dB(e,t){if(e.kind==="Colon")return t;if(e.kind==="Range"){const n=Gk(e);return n===void 0?{kind:"unknown"}:{kind:"exact",value:n}}if(e.kind==="IndexVec"){const n=e.expr.ty;return Me(n)&&n.shape!==void 0?{kind:"exact",value:Dt(n.shape)}:{kind:"unknown"}}return e.kind==="LogicalMask"?{kind:"unknown"}:{kind:"exact",value:1}}function Dm(e,t,n){const{baseTy:r,baseCName:s,base:o}=D0.call(this,e,t.length,n,{notInScope:"internal",operation:"sliceRead"}),i=t.length===1,a=[];for(let u=0;u<t.length;u++){const f=i?"linear":u;a.push(Qk.call(this,s,r,f,t[u]))}const c=r.isComplex;let l;if(i){const u=a[0];if(u.kind==="Colon")if(r.shape!==void 0){const f=Dt(r.shape);l=c?Ut([f,1]):et([f,1])}else{const f=[{kind:"unknown"},{kind:"exact",value:1}];l=c?mr(f):Zt(f)}else if(u.kind==="Range"){const f=Vd(r),h=Ud(r),m=(()=>{const g=Gk(u);return g===void 0?{kind:"unknown"}:{kind:"exact",value:g}})(),p={kind:"exact",value:1},d=h?[m,p]:f?[p,m]:[p,m];l=c?mr(d):Zt(d)}else if(u.kind==="LogicalMask"){const f=Vd(r),h=Ud(r),m={kind:"unknown"},p={kind:"exact",value:1},d=f?[p,m]:h?[m,p]:[m,p];l=c?mr(d):Zt(d)}else throw new W("internal: single-slot scalar slice should have routed through lowerIndexLoad",n)}else{const u=a.map((f,h)=>dB(f,r.dims[h]));l=c?mr(u):Zt(u)}return{kind:"IndexSlice",base:o,index:a,ty:l,span:n}}function Qk(e,t,n,r){if(r.type==="Colon")return{kind:"Colon",span:r.span};if(r.type!=="Range"){this.endStack.push({baseCName:e,baseTy:t,axis:n});let a;try{a=this.lowerExpr(r)}finally{this.endStack.pop()}if(Me(a.ty)&&!a.ty.isComplex&&a.ty.elem==="logical"&&Kn(a.ty))throw new W("scalar logical index (a 1-element logical mask) is not JIT-compiled",r.span);if(Kn(a.ty))return{kind:"Scalar",expr:a,span:r.span};if(Me(a.ty)&&!a.ty.isComplex&&(a.ty.elem==="double"||a.ty.elem==="logical")&&!Kn(a.ty)){if(a.ty.elem==="logical")return{kind:"LogicalMask",expr:a,span:r.span};if(n==="linear")throw new W(`linear vector-of-indices reads (got '${ze(a.ty)}' in a single-slot context) are not yet supported`,r.span);return{kind:"IndexVec",expr:a,span:r.span}}throw new le(`index slot must be a real scalar or a numeric index vector (got ${ze(a.ty)})`,r.span)}this.endStack.push({baseCName:e,baseTy:t,axis:n});let s,o,i;try{s=this.lowerExpr(r.start),r.step===null?o={kind:"NumLit",value:1,ty:{kind:"Numeric",elem:"double",isComplex:!1,dims:[{kind:"exact",value:1},{kind:"exact",value:1}],shape:[1,1],sign:"positive",exact:1},span:r.span}:o=this.lowerExpr(r.step),i=this.lowerExpr(r.end)}finally{this.endStack.pop()}if(!Kn(s.ty))throw new le(`range start must be a real scalar (got ${ze(s.ty)})`,r.start.span);if(!Kn(i.ty))throw new le(`range end must be a real scalar (got ${ze(i.ty)})`,r.end.span);if(!Kn(o.ty))throw new le(`range step must be a real scalar (got ${ze(o.ty)})`,r.step?.span??r.span);if(o.kind!=="NumLit"){const a=o.ty.kind==="Numeric"&&typeof o.ty.exact=="number"?o.ty.exact:void 0;if(a===void 0)throw new W("range step in an index expression must be a compile-time-known numeric value (got expression with unknown value)",r.step?.span??r.span);o={kind:"NumLit",value:a,ty:{kind:"Numeric",elem:"double",isComplex:!1,dims:[{kind:"exact",value:1},{kind:"exact",value:1}],shape:[1,1],sign:a>0?"positive":a<0?"negative":"zero",exact:a},span:r.step?.span??r.span}}if(o.value===0)throw new W("range step in an index expression must be non-zero",r.step?.span??r.span);return{kind:"Range",start:s,step:o,end:i,span:r.span}}function T0(e,t,n){const{baseTy:r,baseCName:s,base:o}=D0.call(this,e,t.length,n,{notInScope:"internal",operation:"read"}),i=[],a=t.length;for(let l=0;l<a;l++){const u=a===1?"linear":l;this.endStack.push({baseCName:s,baseTy:r,axis:u});let f;try{f=this.lowerExpr(t[l])}finally{this.endStack.pop()}if(!Kn(f.ty)){if(Me(f.ty)&&!f.ty.isComplex&&qe(f.ty)&&(f.ty.elem==="double"||f.ty.elem==="logical"))return Dm.call(this,e,t,n);throw new le(`index ${l+1} of '${e}' must be a real scalar (got ${ze(f.ty)})`,t[l].span)}if(Me(f.ty)&&!f.ty.isComplex&&f.ty.elem==="logical")throw new W(`scalar logical index of '${e}' (a 1-element logical mask) is not JIT-compiled`,t[l].span);i.push(f)}const c=gB(r,i);return{kind:"IndexLoad",base:o,indices:i,ty:c??(r.isComplex?_t():Be("unknown")),span:n}}function gB(e,t){const n=e.shape;if(n===void 0)return;const r=Mt(e),s=r===void 0?rn(e):void 0;if(r===void 0&&s===void 0)return;const o=[];for(const c of t){if(!Me(c.ty)||typeof c.ty.exact!="number")return;const l=c.ty.exact;if(!Number.isFinite(l)||!Number.isInteger(l)||l<1)return;o.push(l)}const i=ib(n,o);if(i===void 0)return;if(s!==void 0)return _t({re:s.re[i],im:s.im[i]});const a=r[i];return Be(ft(a),a)}function Tm(e,t,n){if(e.constructor===null){if(t.length!==0)throw new le(`class '${e.className}' has no constructor; cannot pass arguments`,n);const u=Ok.call(this,e,[],n);return ev.call(this,e,u,n)}const r=t.map(u=>this.lowerExpr(u));for(const u of r)this.requireValueType(u,`argument to constructor '${e.className}'`);const s=r.map(u=>u.ty),o=Ok.call(this,e,s,n),i=ev.call(this,e,o,n),a=e.constructor.outputs[0],c=vl.call(this,e.constructor,s,e.className,e.file,{name:a,ty:o,initExpr:i},1,n),l=c.outputTypes[0]??o;return{kind:"Call",cName:c.cName,name:e.className,args:r,ty:l,span:n}}function Ok(e,t,n){if(e.ty!==null)return e.ty;if(e.constructor===null)throw new W(`internal: class '${e.className}' has pending properties but no constructor`,n);const r=e.constructor;if(t.length>r.params.length)throw new le(`constructor '${e.className}' expects at most ${r.params.length} arg(s), got ${t.length}`,n);const s=r.outputs[0],o=this.env,i=this.tempCounter,a=this.currentFile;this.env=new Map,this.tempCounter=0,this.currentFile=e.file;for(let u=0;u<t.length;u++)this.env.set(r.params[u],{cName:Hi(r.params[u]),ty:t[u]});const c=[];try{for(const u of e.propertyNames){if(e.dependentProperties.has(u))continue;const f=e.defaults.get(u);if(f!==void 0){c.push({name:u,ty:f.ty});continue}const h=wB(r.body,s,u);if(h===null)throw new W(`class '${e.className}' property '${u}' has no default and is not directly assigned at the top level of the constructor body (\`${s}.${u} = <expr>;\`); either add a default value or add such an assignment`,r.span);const m=this.lowerExpr(h);this.requireValueType(m,`inferring type of '${e.className}.${u}'`),c.push({name:u,ty:m.ty})}}finally{this.env=o,this.tempCounter=i,this.currentFile=a}const l=Bd(e.className,c);return e.ty=l,l}function ev(e,t,n){const r=[];for(const s of t.properties){const o=e.defaults.get(s.name);let i;if(o!==void 0){const a=this.env;this.env=new Map,i=this.lowerExpr(o.expr),this.env=a}else i=_B(s.ty,e.className,s.name,n);r.push({name:s.name,value:i})}return{kind:"StructLit",fields:r,ty:t,span:n}}function wB(e,t,n){for(const r of e)if(r.type==="AssignLValue"&&r.lvalue.type==="Member"&&r.lvalue.name===n&&r.lvalue.base.type==="Ident"&&r.lvalue.base.name===t)return r.expr;return null}function _B(e,t,n,r){if(e.kind==="Numeric")return qe(e)?{kind:"TensorBuild",elements:[],shape:[0,0],ty:et([0,0]),span:r}:{kind:"NumLit",value:0,ty:Be("zero",0),span:r};throw new W(`class '${t}' property '${n}' is inferred to type ${ze(e)}, but v1 can only synthesize a zero placeholder for numeric properties; provide an explicit default value`,r)}function P0(e){const t=this.env.get(e.name);if(t===void 0&&e.name==="struct")return bB.call(this,e);if(t===void 0&&e.name==="cell")return kB.call(this,e);if(t===void 0&&e.name==="bsxfun"){const o=xB.call(this,e);if(o!==null)return o}if(t===void 0&&e.name==="feval")return yB.call(this,e);if(t!==void 0&&Mf(t.ty))return hB.call(this,e.name,t,e.args,e.span);if(t===void 0&&this.workspace.isClass(e.name)){const o=this.workspace.requireClass(e.name);if(o===void 0)throw new W(`internal: class '${e.name}' missing from workspace registry`,e.span);return Tm.call(this,o,e.args,e.span)}if(t!==void 0){if(Me(t.ty)&&qe(t.ty))return e.args.some(Lm)?Dm.call(this,e.name,e.args,e.span):T0.call(this,e.name,e.args,e.span);throw new W(`'${e.name}' is an in-scope variable of type ${ze(t.ty)}; cannot be called as a function (scalar indexing and dynamically-typed handles are not supported)`,e.span)}const n=e.args.map(o=>this.lowerExpr(o));for(const o of n)this.requireValueType(o,`argument to '${e.name}'`);const r=n.map(o=>o.ty);if(n.length===0){const o=is(e.name);if(o!==void 0){let i;try{i=o.transfer([],1)}catch{i=void 0}if(i!==void 0)return{kind:"Call",cName:e.name,name:e.name,args:[],ty:i[0],span:e.span}}}const s=this.workspace.resolve(e.name,r,this.callSite(),e.span);if(!s){const o=is(e.name);if(o!==void 0){const i=Yo(e.span,()=>o.transfer(r,1))[0];return{kind:"Call",cName:e.name,name:e.name,args:n,ty:i,span:e.span}}throw new W(`unknown function '${e.name}'`,e.span)}switch(s.kind){case"builtin":{const o=is(e.name);if(!o)throw new W(`builtin '${e.name}' is not supported by mtoc2`,e.span);const i=Yo(e.span,()=>o.transfer(r,1))[0];return{kind:"Call",cName:e.name,name:e.name,args:n,ty:i,span:e.span}}case"userFunction":return So.call(this,s.ast,n,e.name,e.span,{definingFile:s.file});case"classMethod":{const o=this.classReg(s.className);if(o===void 0)throw new W(`internal: class '${s.className}' missing from workspace registry`,e.span);const i=s.stripInstance?o.staticMethods.get(s.methodName):o.methods.get(s.methodName);if(i===void 0)throw new le(`class '${s.className}' has no ${s.stripInstance?"static ":""}method '${s.methodName}'`,e.span);if(i.outputs.length>=2)throw new W(`class method '${s.className}.${s.methodName}' has ${i.outputs.length} outputs; multi-output methods can only be called via '[a, b, ...] = ...' (not yet supported for class methods) or as a bare statement`,e.span);const a=s.stripInstance?n.slice(1):n;return So.call(this,i,a,`${s.className}.${s.methodName}`,e.span,{specSource:Xa(s.className,s.methodName),definingFile:i.span.file??o.file})}case"classConstructor":{const o=this.classReg(s.className);if(o===void 0)throw new W(`internal: class '${s.className}' missing from workspace registry`,e.span);return Tm.call(this,o,e.args,e.span)}case"mtoc2UserFunction":{const o=this.workspace.getUserBuiltin(s.name);if(!o)throw new W(`internal: workspace resolved '${s.name}' to a .mtoc2.js function but no Builtin is loaded`,e.span);const i=Yo(e.span,()=>o.transfer(r,1))[0];return{kind:"Call",cName:e.name,name:e.name,args:n,ty:i,span:e.span}}}}function yB(e){const t=tv(e);return P0.call(this,t)}function tv(e){if(e.args.length<1)throw new W("'feval' expects at least 1 argument (the function handle or name), got 0",e.span);const t=e.args[0],n=e.args.slice(1);let r;switch(t.type){case"FuncHandle":r=t.name;break;case"Ident":r=t.name;break;case"Char":case"String":if(r=ov(t.value),!/^[A-Za-z_][A-Za-z0-9_.]*$/.test(r))throw new W(`'feval' name argument '${r}' is not a valid function identifier`,t.span);break;case"AnonFunc":throw new W("'feval' on an inline anonymous handle ('@(...) ...') is not supported; bind the handle to a local variable first (f = @(...) ...; feval(f, ...))",e.span);default:throw new W(`'feval' first argument must be a function-handle literal (@name), an in-scope handle variable, or a char/string function name; got '${t.type}' (runtime-computed handle expressions are not supported — bind to a local first)`,t.span)}return{type:"FuncCall",name:r,args:n,span:e.span}}function xB(e){if(e.args.length!==3)return null;const t=e.args[0];if(t.type!=="FuncHandle")throw new W("'bsxfun' first arg must be a function-handle literal (e.g. @times); dynamic handle-value bsxfun is not yet supported",e.span);const n=t.name,r=new Set(["plus","minus","times","rdivide","power","eq","ne","lt","le","gt","ge","mod","rem","atan2","hypot","max","min"]);if(!r.has(n))throw new W(`'bsxfun' with handle target '@${n}' is not supported; supported targets: ${[...r].sort().join(", ")}`,e.span);const s={type:"FuncCall",name:n,args:[e.args[1],e.args[2]],span:e.span};return P0.call(this,s)}function bB(e){if(e.args.length%2!==0)throw new le("'struct' expects an even number of args (name, value, name, value, ...)",e.span);const t=[],n=new Set;for(let o=0;o<e.args.length;o+=2){const i=e.args[o];if(i.type!=="String"&&i.type!=="Char")throw new le(`'struct' field name (arg ${o+1}) must be a string or char literal`,i.span);const a=ov(i.value);if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(a))throw new le(`'struct' field name '${a}' is not a valid identifier`,i.span);if(n.has(a))throw new le(`'struct': duplicate field '${a}'`,i.span);n.add(a);const c=this.lowerExpr(e.args[o+1]);if(this.requireValueType(c,`value for field '${a}'`),ys(c.ty))throw new W("'struct' with a cell-valued field (cell-expansion / struct-array construction) is not JIT-compiled; the interpreter handles it",e.args[o+1].span);if(c.ty.kind==="Void"||c.ty.kind==="Unknown")throw new le(`value for field '${a}': type ${ze(c.ty)} is not a valid struct field type`,e.args[o+1].span);t.push({name:a,value:c})}const r=t.map(o=>({name:o.name,ty:o.value.ty})),s=Pd(r);return{kind:"StructLit",fields:t,ty:s,span:e.span}}function kB(e){if(e.args.length===0)return{kind:"CellEmpty",dims:[],ty:il([0,0],[]),span:e.span};if(e.args.length>Zn)throw new W(`'cell' accepts up to ${Zn} dim arguments (got ${e.args.length})`,e.span);const t=e.args.map(a=>{const c=this.lowerExpr(a);if(this.requireValueType(c,"'cell' dim argument"),!Me(c.ty)||!De(c.ty)||c.ty.isComplex)throw new le(`'cell' dim argument must be a real scalar (got ${ze(c.ty)})`,a.span);return c}),n=[];if(t.length===1){const a=Me(t[0].ty)&&typeof t[0].ty.exact=="number"?t[0].ty.exact:null;n.push({exactValue:a,expr:t[0]}),n.push({exactValue:a,expr:t[0]})}else for(const a of t){const c=Me(a.ty)&&typeof a.ty.exact=="number"?a.ty.exact:null;n.push({exactValue:c,expr:a})}for(let a=0;a<n.length;a++){const c=n[a].exactValue;if(c!==null&&(!Number.isInteger(c)||c<0))throw new le(`'cell' dim argument ${a+1} must be a non-negative integer (got ${c})`,e.span)}const r=n.every(a=>a.exactValue!==null);let s=null;if(r){s=1;for(const a of n)s*=a.exactValue}if(r&&s!==null&&s<=wt){const a=n.map(u=>u.exactValue),c=s,l=[];for(let u=0;u<c;u++)l.push(qd());return{kind:"CellEmpty",dims:n.map(u=>u.expr),ty:il(a,l),span:e.span}}const i=n.map(a=>a.exactValue===null?{kind:"unknown"}:a.exactValue===1?nn:{kind:"exact",value:a.exactValue});return{kind:"CellEmpty",dims:n.map(a=>a.expr),ty:vf(i,qd()),span:e.span}}function B0(e){let t,n,r,s;if(e.expr.type==="FuncCall"){let M=e.expr;M.name==="feval"&&this.env.get("feval")===void 0&&(M=tv(M)),t=M.name,n=M.args,r=M.span,s=void 0}else if(e.expr.type==="MethodCall"){const M=Cf(e.expr.base);if(M===null||this.env.has(M.split(".")[0]))throw new W("multi-assign right-hand side must be a user-function or package-function call (got instance-method dispatch, not yet supported in '[...] = ...')",e.span);t=`${M}.${e.expr.name}`,n=e.expr.args,r=e.expr.span,s=t}else throw new W("multi-assign right-hand side must be a user-function call",e.span);const o={args:n,span:r},i=MB.call(this,e.lvalues,e.span);for(const M of i)if(M.type!=="Var"&&M.type!=="Ignore"&&M.type!=="Member"&&M.type!=="Index"&&M.type!=="IndexCell")throw new W(`multi-assign lvalue must be a simple identifier, '~' ignore, a member access, an indexed write, or a brace-indexed cell write (got '${M.type}')`,e.span);if(e={...e,lvalues:i},e.expr.type==="FuncCall"){const M=this.env.get(t);if(M!==void 0&&Mf(M.ty))return pB.call(this,t,M,n,e.lvalues,e.span)}if(this.env.get(t)!==void 0)throw new W(`multi-assign of '${t}': name resolves to an in-scope variable, not a function`,e.span);if(this.workspace.isClass(t))throw new W(`multi-assign of '${t}': class constructors have a single output`,e.span);const a=o.args.map(M=>this.lowerExpr(M));for(const M of a)this.requireValueType(M,`argument to '${t}'`);const c=a.map(M=>M.ty),l=[],u=a.map(M=>this.anfRequireScalarOrVar(M,l)),f=this.workspace.resolve(t,c,this.callSite(),o.span);if(f?.kind==="builtin"){const M=is(t);if(M!==void 0)return vB.call(this,t,M,u,c,l,e)}if(f?.kind!=="userFunction")throw new W(`multi-assign of '${t}': only user-defined functions can appear on the right of '[...] = ...' (or as a bare multi-output statement)`,e.span);const h=f.ast,m=f.file;if(e.lvalues.length>h.outputs.length)throw new W(`function '${t}' returns ${h.outputs.length} output(s) but ${e.lvalues.length} were requested`,e.span);if(h.outputs.length===0&&e.lvalues.length>0)throw new W(`function '${t}' has no outputs and cannot be assigned`,e.span);const p=e.lvalues.length,d=vl.call(this,h,c,s,m,void 0,p,e.span);if(d.outputTypes.length===1){const M={kind:"Call",cName:d.cName,name:t,args:u,ty:d.outputTypes[0]??{kind:"Unknown"},span:e.span},$=e.lvalues[0];if($===void 0||$.type==="Ignore"){const q={kind:"ExprStmt",expr:M,span:e.span};return l.length===0?q:[...l,q]}if($.type==="Var"){const q=this.recordAssignment($.name,M,e.span);return l.length===0?q:[...l,q]}const N=q0.call(this,[$],[d.outputTypes[0]??{kind:"Unknown"}],e.span),E=N.effectiveLvalues[0],R=this.recordAssignment(E.name,M,e.span),D=z0.call(this,N.postStores);return[...l.length===0?[R]:[...l,R],...D]}if(d.outputTypes.length===0){const $={kind:"ExprStmt",expr:{kind:"Call",cName:d.cName,name:t,args:u,ty:Fi,span:e.span},span:e.span};return l.length===0?$:[...l,$]}const g=d.outputTypes.map(M=>M??{kind:"Unknown"}),w=q0.call(this,e.lvalues,g,e.span),_=V0.call(this,t,g,w.effectiveLvalues,M=>`output '${h.outputs[M]}'`,e.span),y={kind:"MultiAssignCall",cName:d.cName,name:t,args:u,outputs:_,span:e.span},b=z0.call(this,w.postStores);return[...l.length===0?[y]:[...l,y],...b]}function q0(e,t,n){const r=[],s=[];for(let o=0;o<e.length;o++){const i=e[o];if(i.type==="Var"||i.type==="Ignore"){r.push(i);continue}const a=this.freshTempName(),c=t[o]??{kind:"Unknown"};this.env.set(a,{cName:a,ty:c}),r.push({type:"Var",name:a});const l={type:"Ident",name:a,span:n};s.push({type:"AssignLValue",lvalue:i,expr:l,suppressed:!0,span:n})}return{effectiveLvalues:r,postStores:s}}function z0(e){const t=[];for(const n of e){if(n.type!=="AssignLValue")continue;const r=this.lowerAssignLValue(n);Array.isArray(r)?t.push(...r):t.push(r)}return t}function V0(e,t,n,r,s){const o=[];for(let i=0;i<t.length;i++){const a=t[i];if(!fR(a))throw new W(`multi-output call '${e}': ${r(i)} has type ${ze(a)}; this type isn't supported in a multi-output slot`,s);const c=n[i];if(c===void 0||c.type!=="Var"){o.push({ty:a,binding:null});continue}const l={kind:"Var",name:c.name,cName:"<placeholder>",ty:a,span:s},u=this.recordAssignment(c.name,l,s);o.push({ty:a,binding:{name:c.name,cName:u.cName}})}return o}function vB(e,t,n,r,s,o){const i=o.lvalues.length,a=Yo(o.span,()=>t.transfer(r,i));if(a.length!==i)throw new W(`internal: builtin '${e}' transfer returned ${a.length} type(s) for nargout=${i}`,o.span);const c=q0.call(this,o.lvalues,a,o.span),l=V0.call(this,e,a,c.effectiveLvalues,m=>`output slot ${m+1}`,o.span),u={kind:"MultiAssignCall",cName:e,name:e,isBuiltin:!0,args:n,outputs:l,span:o.span},f=z0.call(this,c.postStores);return[...s.length===0?[u]:[...s,u],...f]}function MB(e,t){if(e.length!==1)return e.slice();const n=e[0];if(n.type!=="IndexCell"||n.indices.length!==1)return e.slice();const r=n.indices[0];if(r.type!=="Range")return e.slice();const s=this.lowerExpr(r.start).ty,o=this.lowerExpr(r.end).ty,i=r.step!==null?this.lowerExpr(r.step).ty:null,a=s.kind==="Numeric"&&typeof s.exact=="number"?s.exact:null,c=o.kind==="Numeric"&&typeof o.exact=="number"?o.exact:null,l=i===null?1:i.kind==="Numeric"&&typeof i.exact=="number"?i.exact:null;if(a===null||c===null||l===null)throw new W("multi-assign LHS '[<cell>{<range>}]': the range bounds must be statically known at compile time (got non-exact bounds)",t);if(!Number.isInteger(a)||!Number.isInteger(c)||!Number.isInteger(l)||l===0)throw new W(`multi-assign LHS '[<cell>{<range>}]': range bounds must be non-zero integers (got ${a}:${l}:${c})`,t);const u=[];if(l>0)for(let h=a;h<=c;h+=l)u.push(h);else for(let h=a;h>=c;h+=l)u.push(h);if(u.length===0)throw new W("multi-assign LHS '[<cell>{<range>}]': empty range (no slots to assign)",t);return u.map(h=>({type:"IndexCell",base:n.base,indices:[{type:"Number",value:String(h),span:t}]}))}function $B(e){const t=Cf(e.base);if(t&&!this.env.has(t.split(".")[0])){const p=`${t}.${e.name}`;if(this.workspace.isClass(p)){const _=this.workspace.requireClass(p);if(_===void 0)throw new W(`internal: class '${p}' missing from workspace registry`,e.span);return Tm.call(this,_,e.args,e.span)}if(this.workspace.isClass(t))return NB.call(this,t,e,e.span);const d=e.args.map(_=>this.lowerExpr(_));for(const _ of d)this.requireValueType(_,`argument to '${p}'`);const g=d.map(_=>_.ty),w=this.workspace.resolve(p,g,this.callSite(),e.span);if(w?.kind==="userFunction")return So.call(this,w.ast,d,p,e.span,{specSource:p,definingFile:w.file});if(w?.kind==="classConstructor"){const _=this.classReg(w.className);if(_===void 0)throw new W(`internal: class '${w.className}' missing from workspace registry`,e.span);return Tm.call(this,_,e.args,e.span)}throw new W(`unknown function '${p}'`,e.span)}const n=this.lowerExpr(e.base);if(this.requireValueType(n,`method call '.${e.name}'`),!al(n.ty))throw new W(`method call '.${e.name}' on a value of type ${ze(n.ty)} is not supported (v1: classes only)`,e.span);const r=this.classReg(n.ty.className),o=n.ty.properties.some(p=>p.name===e.name),i=r?.dependentProperties.has(e.name)??!1,a=r?r.methods.has(e.name)||r.staticMethods.has(e.name):!1;if(o&&!a)return SB.call(this,n,e.name,e.args,e.span);if(i&&r!==void 0)return CB.call(this,n,r,e.name,e.args,e.span);const c=e.args.map(p=>this.lowerExpr(p));for(const p of c)this.requireValueType(p,`argument to method '${e.name}'`);const l=[n.ty,...c.map(p=>p.ty)],u=this.workspace.resolve(e.name,l,{...this.callSite(),targetClassName:n.ty.className},e.span);if(u?.kind!=="classMethod")throw new le(`class '${n.ty.className}' has no method '${e.name}'`,e.span);const f=this.classReg(u.className);if(f===void 0)throw new W(`internal: class '${u.className}' missing from workspace registry`,e.span);const h=u.stripInstance?f.staticMethods.get(u.methodName):f.methods.get(u.methodName);if(h===void 0)throw new le(`class '${u.className}' has no ${u.stripInstance?"static ":""}method '${u.methodName}'`,e.span);const m=u.stripInstance?c:[n,...c];return So.call(this,h,m,`${u.className}.${u.methodName}`,e.span,{specSource:Xa(u.className,u.methodName),definingFile:h.span.file??f.file})}function CB(e,t,n,r,s){const o=t.getters.get(n);if(o===void 0)throw new W(`internal: dependent property '${t.className}.${n}' has no getter`,s);const i=So.call(this,o,[e],`${t.className}.get.${n}`,s,{specSource:Xa(t.className,`get.${n}`),definingFile:o.span.file??t.file}),a=this.freshTempName();return this.env.set(a,{cName:a,ty:i.ty}),this.pendingExprHoists.push({kind:"Assign",name:a,cName:a,ty:i.ty,expr:i,span:s}),r.some(Lm)?Dm.call(this,a,r,s):T0.call(this,a,r,s)}function SB(e,t,n,r){const s=cl(e.ty,t);if(s===void 0)throw new le(`no field '${t}' on type ${ze(e.ty)}`,r);const o={kind:"MemberLoad",base:e,field:t,ty:s,span:r},i=this.freshTempName();return this.env.set(i,{cName:i,ty:s}),this.pendingExprHoists.push({kind:"Assign",name:i,cName:i,ty:s,expr:o,span:r}),n.some(Lm)?Dm.call(this,i,n,r):T0.call(this,i,n,r)}function NB(e,t,n){const r=t.args.map(c=>this.lowerExpr(c));for(const c of r)this.requireValueType(c,`argument to static method '${t.name}'`);const s=r.map(c=>c.ty),o=this.workspace.resolve(t.name,s,{...this.callSite(),targetClassName:e},n);if(o?.kind!=="classMethod")throw new le(`class '${e}' has no static method '${t.name}'`,n);const i=this.classReg(o.className);if(i===void 0)throw new W(`internal: class '${o.className}' missing from workspace registry`,n);const a=i.staticMethods.get(o.methodName);if(a===void 0)throw i.methods.has(o.methodName)?new le(`'${o.className}.${o.methodName}' is an instance method; call it on an instance (e.g. 'obj.${o.methodName}(...)')`,n):new le(`class '${o.className}' has no static method '${o.methodName}'`,n);if(a.outputs.length>=2)throw new W(`static class method '${o.className}.${o.methodName}' has ${a.outputs.length} outputs; multi-output methods are not supported yet`,n);return So.call(this,a,r,`${o.className}.${o.methodName}`,n,{specSource:Xa(o.className,o.methodName),definingFile:a.span.file??i.file})}function nv(e){if(!Me(e))return null;let t=1;for(const n of e.dims){if(n.kind!=="exact")return null;t*=n.value}return t}function rv(e,t,n){const r=Yk.call(this,e,n,"sliceWrite"),{fieldPath:s,leafTy:o,displayName:i}=r,a=e.indices.length===1,c=[],l=[];for(let g=0;g<e.indices.length;g++){const w=a?"linear":g,_=Qk.call(this,r.baseCName,r.baseTy,w,e.indices[g]);_.kind==="LogicalMask"||_.kind==="IndexVec"?l.push({..._,expr:this.anfRequireScalarOrVar(_.expr,c)}):l.push(_)}if(a&&l[0].kind==="LogicalMask"){const g=nv(r.baseTy),w=nv(l[0].expr.ty);if(g!==null&&w!==null&&w>g)throw new W("logical-mask store with a statically-longer mask may grow the base; deferring to the interpreter",l[0].span)}if(!a){for(const g of l)if(g.kind==="LogicalMask")throw new W("per-axis logical-mask writes are not yet supported; only linear-form 'a(mask) = rhs' is handled",g.span)}if(!a&&r.baseTy.kind==="Numeric")for(let g=0;g<l.length;g++){const w=l[g];if(w.kind!=="Scalar")continue;const _=r.baseTy.dims[g],y=w.expr.ty,b=_!==void 0&&_.kind==="exact",k=y.kind==="Numeric"&&typeof y.exact=="number";if(!(b&&k&&Math.round(y.exact)>=1&&Math.round(y.exact)<=_.value))throw new W(`indexed write to '${i}' at axis ${g+1}: cannot statically prove the index stays within the tensor's bounds; would auto-grow / OOB in MATLAB, but auto-grow is not modeled in the JIT`,w.span)}const u=this.lowerExpr(t);if(!Me(u.ty))throw new le(`right-hand side of an indexed assignment must be numeric (got ${ze(u.ty)})`,t.span);if(u.ty.elem!=="double")throw new W(`right-hand side of a range/colon indexed write must be a double (got ${ze(u.ty)})`,t.span);if(!r.baseTy.isComplex&&u.ty.isComplex)throw new le(`cannot store a complex RHS into a real-typed tensor '${i}' (would silently drop the imaginary part). Promote the base to complex first (e.g. via 'x = x + 0i' before the indexed write).`,t.span);const f=[];let h;if(De(u.ty))h=u;else if(qe(u.ty))h=this.anfRequireScalarOrVar(u,f);else throw new le(`right-hand side of a range/colon indexed write must be a scalar or a tensor (got ${ze(u.ty)})`,t.span);const p={kind:"IndexSliceStore",base:r.base,index:l,rhs:h,span:n,...s!==void 0?{fieldPath:s,leafTy:o}:{}},d=[...c,...f];return d.length===0?p:[...d,p]}function AB(e,t,n){const{base:r,baseTy:s,baseCName:o,fieldPath:i,leafTy:a,displayName:c}=Yk.call(this,e,n,"write");for(const m of e.indices)if(m.type==="Range"||m.type==="Colon")throw new W("internal: lowerIndexStore received a range/colon slot; should have been routed to lowerIndexSliceStore",m.span);const l=[],u=e.indices.length;for(let m=0;m<u;m++){const p=u===1?"linear":m;this.endStack.push({baseCName:o,baseTy:s,axis:p});let d;try{d=this.lowerExpr(e.indices[m])}finally{this.endStack.pop()}if(!Kn(d.ty)){if(Me(d.ty)&&!d.ty.isComplex&&qe(d.ty)&&d.ty.elem==="logical")return rv.call(this,e,t,n);throw new le(`index ${m+1} of '${c}' must be a real scalar (got ${ze(d.ty)})`,e.indices[m].span)}if(Me(d.ty)&&!d.ty.isComplex&&d.ty.elem==="logical")throw new W(`scalar logical index of '${c}' (a 1-element logical mask) is not JIT-compiled`,e.indices[m].span);l.push(d)}if(Me(s)&&s.shape!==void 0)if(u===1){const m=sv(l[0].ty),p=Dt(s.shape);if(m!==void 0&&m>p)throw new W(`indexed assignment to '${c}' grows the array (index ${m} exceeds the ${p}-element static shape); array growth is not supported in the JIT`,n)}else for(let m=0;m<u;m++){const p=sv(l[m].ty),d=m<s.shape.length?s.shape[m]:1;if(p!==void 0&&p>d)throw new W(`indexed assignment to '${c}' grows axis ${m+1} (index ${p} exceeds static dim ${d}); array growth is not supported in the JIT`,n)}const f=this.lowerExpr(t);if(s.isComplex){if(!Me(f.ty)||!De(f.ty))throw new le(`right-hand side of an indexed assignment must be a numeric scalar (got ${ze(f.ty)})`,t.span)}else if(!Kn(f.ty))throw Me(f.ty)&&f.ty.isComplex&&De(f.ty)?new le(`cannot store a complex value into a real-typed tensor '${c}' (would silently drop the imaginary part). Promote the base to complex first (e.g. via 'x = x + 0i' before the indexed write).`,t.span):new le(`right-hand side of an indexed assignment must be a numeric scalar (got ${ze(f.ty)})`,t.span);return{kind:"IndexStore",base:r,indices:l,rhs:f,span:n,...i!==void 0?{fieldPath:i,leafTy:a}:{}}}function sv(e){return Me(e)&&typeof e.exact=="number"?e.exact:void 0}let EB=e=>console.error(e);function Pm(e){switch(e.kind){case"NumLit":case"ImagLit":case"StringLit":case"Var":return!0;case"Binary":return Pm(e.left)&&Pm(e.right);case"Unary":return Pm(e.operand);default:return!1}}class IB{constructor(t){this.workspace=t,this.currentFile=t.mainFile}env=new Map;specializations=new Map;endStack=[];tempCounter=0;splitCounter=0;controlDepth=0;pendingExprHoists=[];anonCounter=0;currentFile;callFrameStack=[];recursiveSpecsConsumed=new Set;specCountPerSource=new Map;callSite(){return{file:this.currentFile}}envLookup(t){return this.env.get(t)}withControlDepth(t){this.controlDepth++;try{return t()}finally{this.controlDepth--}}classReg(t){return this.workspace.requireClass(t)}lowerProgram(t){return this.workspace.finalize(),{topLevelStmts:this.lowerStmts(t.body),functions:this.specializations}}lowerStmts(t){const n=[];for(const r of t){const s=this.lowerStmt(r);if(s===null)continue;Array.isArray(s)?n.push(...s):n.push(s);const o=n[n.length-1];if(o!==void 0&&(o.kind==="ReturnFromFunction"||o.kind==="Break"||o.kind==="Continue"))break}return n}lowerStmt(t){const n=this.pendingExprHoists.length,r=this.lowerStmtInner(t);if(this.pendingExprHoists.length===n)return r;const s=this.pendingExprHoists.splice(n);return r===null?s:Array.isArray(r)?[...s,...r]:[...s,r]}lowerStmtInner(t){switch(t.type){case"Function":return null;case"ClassDef":return null;case"ExprStmt":return this.lowerExprStmt(t);case"Assign":return this.lowerAssign(t);case"AssignLValue":return this.lowerAssignLValue(t);case"MultiAssign":return B0.call(this,t);case"If":return this.lowerIf(t);case"While":return this.lowerWhile(t);case"For":return this.lowerFor(t);case"Return":return{kind:"ReturnFromFunction",span:t.span};case"Break":return{kind:"Break",span:t.span};case"Continue":return{kind:"Continue",span:t.span};case"Directive":return this.lowerDirective(t);default:throw new W(`statement type '${t.type}' not supported`,t.span)}}lowerDirective(t){if(t.directive==="opaque"){for(const n of t.args){const r=this.env.get(n);if(r===void 0)throw new W(`'%!numbl:opaque' references unknown variable '${n}'`,t.span);const s=bo(r.ty);s!==r.ty&&this.env.set(n,{cName:r.cName,ty:s})}return null}if(t.directive==="showtype")return{kind:"TypeComment",entries:this.snapshotTypeEntries(t.args,t.span,"showtype"),span:t.span};if(t.directive==="printtype"){const n=this.snapshotTypeEntries(t.args,t.span,"printtype"),r=this.workspace.sourceOf(t.span.file)??"",{line:s,column:o}=wR(r,t.span.start);for(const i of n)EB(`${t.span.file}:${s}:${o}: type ${i.name} :: ${ze(i.ty)}`);return null}return null}snapshotTypeEntries(t,n,r){const s=[];for(const o of t){const i=this.env.get(o);if(i===void 0)throw new W(`'%!numbl:${r}' references unknown variable '${o}'`,n);s.push({name:o,cName:i.cName,ty:i.ty})}return s}lowerExprStmt(t){if(this.env.get("toc")===void 0&&!this.workspace.isClass("toc")){if(t.expr.type==="Ident"&&t.expr.name==="toc")return{kind:"ExprStmt",expr:{kind:"Call",cName:"mtoc2_toc_print",name:"toc_print",args:[],ty:Fi,span:t.expr.span},span:t.span};if(t.expr.type==="FuncCall"&&t.expr.name==="toc"){if(t.expr.args.length===0)return{kind:"ExprStmt",expr:{kind:"Call",cName:"mtoc2_toc_print",name:"toc_print",args:[],ty:Fi,span:t.expr.span},span:t.span};if(t.expr.args.length===1){const o=this.lowerExpr(t.expr.args[0]);if(!Kn(o.ty))throw new le(`'toc' tic-handle argument must be a scalar real numeric (the value returned by 'tic'); got ${o.ty.kind}`,t.expr.args[0].span);return{kind:"ExprStmt",expr:{kind:"Call",cName:"mtoc2_toc_handle_print",name:"toc_handle_print",args:[o],ty:Fi,span:t.expr.span},span:t.span}}}}if(t.expr.type==="FuncCall"){const o=t.expr;if(this.env.get(o.name)===void 0&&!this.workspace.isClass(o.name)){const a=this.workspace.resolve(o.name,[],this.callSite(),o.span);if(a?.kind==="userFunction"&&a.ast.outputs.length>=2)return B0.call(this,{type:"MultiAssign",lvalues:[],expr:o,suppressed:t.suppressed,span:t.span})}}if(t.expr.type==="MethodCall"){const o=t.expr,i=Cf(o.base);if(i&&!this.env.has(i.split(".")[0])){const a=`${i}.${o.name}`;if(!this.workspace.isClass(a)){const c=this.workspace.resolve(a,[],this.callSite(),o.span);if(c?.kind==="userFunction"&&c.ast.outputs.length>=2)return B0.call(this,{type:"MultiAssign",lvalues:[],expr:o,suppressed:t.suppressed,span:t.span})}}}const n=this.lowerExpr(t.expr);if((n.kind==="NumLit"||n.kind==="ImagLit")&&t.suppressed)return null;if(zd(n.ty)){const o=[],i=this.anfChildren(n,o);return o.length>0?[...o,{kind:"ExprStmt",expr:i,span:t.span}]:{kind:"ExprStmt",expr:n,span:t.span}}const r=[],s=this.anfRequireScalarOrVar(n,r);return r.length>0?[...r,{kind:"ExprStmt",expr:s,span:t.span}]:{kind:"ExprStmt",expr:n,span:t.span}}requireValueType(t,n){if(zd(t.ty))throw new W(`${n}: cannot use the result of a zero-output function as a value`,t.span)}anfChildren(t,n){switch(t.kind){case"NumLit":case"ImagLit":case"StringLit":case"Var":case"HandleLit":case"HandleCaptureLoad":case"EndRef":return t;case"TensorBuild":return{...t,elements:t.elements.map(r=>this.anfRequireScalarOrVar(r,n))};case"TensorConcat":return{...t,cells:t.cells.map(r=>r.map(s=>this.anfRequireScalarOrVar(s,n)))};case"CellLit":return{...t,elements:t.elements.map(r=>hr(r.ty)?this.anfChildren(r,n):this.anfRequireScalarOrVar(r,n))};case"CellEmpty":return{...t,dims:t.dims.map(r=>this.anfRequireScalarOrVar(r,n))};case"CellIndexLoad":return{...t,base:this.anfRequireScalarOrVar(t.base,n),indices:t.indices.map(r=>this.anfRequireScalarOrVar(r,n))};case"Binary":return{...t,left:this.anfRequireScalarOrVar(t.left,n),right:this.anfRequireScalarOrVar(t.right,n)};case"Unary":return{...t,operand:this.anfRequireScalarOrVar(t.operand,n)};case"Call":return{...t,args:t.args.map(r=>this.anfRequireScalarOrVar(r,n))};case"StructLit":return{...t,fields:t.fields.map(r=>({name:r.name,value:hr(r.value.ty)?this.anfChildren(r.value,n):this.anfRequireScalarOrVar(r.value,n)}))};case"MemberLoad":return{...t,base:this.anfRequireScalarOrVar(t.base,n)};case"IndexLoad":return{...t,base:this.anfRequireScalarOrVar(t.base,n),indices:t.indices.map(r=>this.anfRequireScalarOrVar(r,n))};case"IndexSlice":return{...t,base:this.anfRequireScalarOrVar(t.base,n),index:t.index.map(r=>r.kind==="Range"?{...r,start:this.anfRequireScalarOrVar(r.start,n),step:this.anfRequireScalarOrVar(r.step,n),end:this.anfRequireScalarOrVar(r.end,n)}:r.kind==="Scalar"?{...r,expr:this.anfRequireScalarOrVar(r.expr,n)}:r.kind==="IndexVec"?{...r,expr:this.anfRequireScalarOrVar(r.expr,n)}:r.kind==="LogicalMask"?{...r,expr:this.anfRequireScalarOrVar(r.expr,n)}:r)};case"MakeRange":return{...t,start:this.anfRequireScalarOrVar(t.start,n),step:this.anfRequireScalarOrVar(t.step,n),end:this.anfRequireScalarOrVar(t.end,n)}}}anfRequireScalarOrVar(t,n){const r=this.anfChildren(t,n);return hr(r.ty)&&r.kind!=="Var"?this.hoistToTemp(r,n):r}hoistToTemp(t,n){const r=this.freshTempName();return this.env.set(r,{cName:r,ty:t.ty}),n.push({kind:"Assign",name:r,cName:r,ty:t.ty,expr:t,span:t.span}),{kind:"Var",name:r,cName:r,ty:t.ty,span:t.span}}freshTempName(){return this.tempCounter+=1,`_mtoc2_t${this.tempCounter}`}lowerAssign(t){const n=this.lowerExpr(t.expr);this.requireValueType(n,`assigning to '${t.name}'`);const r=[],i=hr(n.ty)&&n.kind!=="Var"?this.anfChildren(n,r):this.anfRequireScalarOrVar(n,r),a=this.recordAssignment(t.name,i,t.span);return r.length===0?a:[...r,a]}lowerAssignLValue(t){const n=t.lvalue;if(n.type==="IndexCell")return uB.call(this,n,t.expr,t.span);if(n.type==="Index"){if(t.expr.type==="Tensor"&&t.expr.rows.length===0)throw new W("indexed deletion `x(idx) = []` is not JIT-compiled; resizing the base requires the interpreter",t.span);const w=n.indices.some(Lm)?rv.call(this,n,t.expr,t.span):AB.call(this,n,t.expr,t.span);if(n.base.type==="Ident"){if(!RB(this.env,n.base.name,w)){const y=LB(w);pR(this.env,n.base.name,y)}}else if(n.base.type==="Member"){const _=Array.isArray(w)?w[w.length-1]:w;_!==void 0&&(_.kind==="IndexStore"||_.kind==="IndexSliceStore")&&_.fieldPath!==void 0&&_.leafTy!==void 0&&dR(this.env,_.base.name,_.fieldPath,_.leafTy)}return w}if(n.type!=="Member")throw new W(`assignment lvalue '${n.type}' is not supported`,t.span);const r=yR(n);if(r===null)throw new W("assignment lvalue must be rooted at a named variable",t.span);const{rootName:s,fields:o}=r,i=this.env.get(s);if(i===void 0)throw new W(`assignment to '${s}.${o.join(".")}' but '${s}' is not yet defined (struct variables must first be introduced via 'struct(...)' or a class constructor call)`,t.span);if(o.length===1&&i.ty.kind==="Class"){const w=this.classReg(i.ty.className),_=o[0],y=w?.setters.get(_);if(y!==void 0&&w!==void 0){const b=this.lowerExpr(t.expr);this.requireValueType(b,`assignment to '${s}.${_}'`);const k={kind:"Var",name:s,cName:i.cName,ty:i.ty,span:t.span},M=So.call(this,y,[k,b],`${i.ty.className}.set.${_}`,t.span,{specSource:Xa(i.ty.className,`set.${_}`),definingFile:y.span.file??w.file}),$=[],R=hr(M.ty)&&M.kind!=="Var"?this.anfChildren(M,$):this.anfRequireScalarOrVar(M,$),D=this.recordAssignment(s,R,t.span);return $.length===0?D:[...$,D]}if(w?.dependentProperties.has(_))throw new W(`dependent property '${i.ty.className}.${_}' has no setter; cannot assign`,t.span)}let a=i.ty;for(let w=0;w<o.length;w++){const _=o[w],y=cl(a,_);if(y===void 0)throw new le(`'${s}.${o.slice(0,w+1).join(".")}': no such field on type ${ze(a)}`,t.span);a=y}const c=a,l=this.lowerExpr(t.expr);if(this.requireValueType(l,`assignment to '${s}.${o.join(".")}'`),!ll(l.ty,c))throw new le(`assignment to '${s}.${o.join(".")}': field has C type ${ze(c)} but rhs has type ${ze(l.ty)}`,t.span);const u=[],m=hr(c)&&l.kind!=="Var"?this.anfChildren(l,u):this.anfRequireScalarOrVar(l,u),d={kind:"MemberStore",base:{kind:"Var",name:s,cName:i.cName,ty:i.ty,span:t.span},fieldPath:o,leafTy:l.ty,rhs:m,span:t.span},g=$f(i.ty,o,l.ty);return this.env.set(s,{cName:i.cName,ty:g}),u.length===0?d:[...u,d]}recordAssignment(t,n,r){const s=this.env.get(t);if(s&&!ll(s.ty,n.ty)){if(this.controlDepth>0)throw qe(s.ty)!==qe(n.ty)?new W(`cannot reassign '${t}' across scalar/tensor boundary inside control flow`,r):new W(`cannot reassign '${t}': new value's C storage (${ze(n.ty)}) is incompatible with the existing binding (${ze(s.ty)}) inside control flow`,r);const i=`_mtoc2_${s.cName}__v${++this.splitCounter}`;return this.env.set(t,{cName:i,ty:n.ty}),{kind:"Assign",name:t,cName:i,ty:n.ty,expr:n,span:r}}const o=s?.cName??Hi(t);return this.env.set(t,{cName:o,ty:n.ty}),{kind:"Assign",name:t,cName:o,ty:n.ty,expr:n,span:r}}lowerIf(t){const n=this.lowerExpr(t.cond);this.requireScalarCondType(n.ty,"if condition",t.span);const r=jB(n),s=Bm(n)?[]:[{kind:"ExprStmt",expr:n,span:t.cond.span}];if(r===!0)return[...s,...this.lowerStmts(t.thenBody)];if(r===!1){if(t.elseifBlocks.length===0)return[...s,...t.elseBody?this.lowerStmts(t.elseBody):[]];const[a,...c]=t.elseifBlocks,l={type:"If",cond:a.cond,thenBody:a.body,elseifBlocks:c,elseBody:t.elseBody,span:a.cond.span},u=this.lowerIf(l);return[...s,...Array.isArray(u)?u:[u]]}const o=new Map(this.env),i=[];return this.withControlDepth(()=>{this.env=new Map(o);const a=this.lowerStmts(t.thenBody);i.push(this.env),this.env=new Map(o);const c=this.lowerElseChain(t.elseifBlocks,t.elseBody,o,i);return this.env=this.mergeBranchEnvs(i,!0),{kind:"If",cond:n,thenBody:a,elseBody:c,span:t.span}})}lowerElseChain(t,n,r,s){if(t.length===0){if(n===null)return s.push(new Map(r)),[];this.env=new Map(r);const f=this.lowerStmts(n);return s.push(this.env),f}const[o,...i]=t;this.env=new Map(r);const a=this.lowerExpr(o.cond);this.requireScalarCondType(a.ty,"elseif condition",o.cond.span);const c=new Map(this.env);this.env=c;const l=this.lowerStmts(o.body);s.push(this.env),this.env=new Map(r);const u=this.lowerElseChain(i,n,r,s);return[{kind:"If",cond:a,thenBody:l,elseBody:u,span:o.cond.span}]}lowerWhile(t){const n=new Map(this.env);Gx(this.env,U0(t.body));const r=this.lowerExpr(t.cond);this.requireScalarCondType(r.ty,"while condition",t.span);const s=new Map(this.env),o=this.withControlDepth(()=>this.lowerStmts(t.body));return iv(s,this.env,t.body,t.span),this.env=this.mergeBranchEnvs([n,this.env]),{kind:"While",cond:r,body:o,span:t.span}}lowerFor(t){if(t.expr.type!=="Range")throw new W("for-loop iterables other than ranges are not yet supported",t.span);const n=this.lowerExpr(t.expr.start),r=this.lowerExpr(t.expr.end);this.requireScalarReal(n.ty,"for-loop start",t.expr.start.span),this.requireScalarReal(r.ty,"for-loop end",t.expr.end.span);let s=1;if(t.expr.step){const h=this.lowerExpr(t.expr.step);this.requireScalarReal(h.ty,"for-loop step",t.expr.step.span);const m=Me(h.ty)&&typeof h.ty.exact=="number"?h.ty.exact:void 0;if(m===void 0)throw new W("for-loop step must be a compile-time-known numeric literal",t.expr.step.span);if(m===0)throw new W("for-loop step must be non-zero",t.expr.step.span);s=m}const o=new Map(this.env),i=Me(n.ty)?n.ty.sign:"unknown",a=Me(r.ty)?r.ty.sign:"unknown",c=kf(i,a),l=Hi(t.varName);this.env.set(t.varName,{cName:l,ty:Be(c)}),Gx(this.env,U0(t.body));const u=new Map(this.env),f=this.withControlDepth(()=>this.lowerStmts(t.body));return iv(u,this.env,t.body,t.span),this.env=this.mergeBranchEnvs([o,this.env]),{kind:"For",varName:t.varName,cVar:l,start:n,step:s,end:r,body:f,span:t.span}}lowerExpr(t){switch(t.type){case"Number":{const n=Number(t.value);if(!Number.isFinite(n))throw new W(`non-finite numeric literal '${t.value}'`,t.span);return{kind:"NumLit",value:n,ty:Be(ft(n),n),span:t.span}}case"ImagUnit":return{kind:"ImagLit",value:1,ty:_t({re:0,im:1}),span:t.span};case"Ident":return this.lowerIdent(t);case"Binary":return this.lowerBinary(t);case"Unary":return this.lowerUnary(t);case"FuncCall":return P0.call(this,t);case"Tensor":return iB.call(this,t);case"Cell":return aB.call(this,t);case"IndexCell":return cB.call(this,t);case"FuncHandle":return fB.call(this,t);case"AnonFunc":return mB.call(this,t);case"Member":return this.lowerMember(t);case"MethodCall":return $B.call(this,t);case"EndKeyword":return this.lowerEndKeyword(t);case"Range":return this.lowerRangeAsValue(t);case"Char":{const n=t.value,r=n.slice(1,n.length-1).replaceAll("''","'");return{kind:"StringLit",value:r,ty:{kind:"Char",exact:r},span:t.span}}case"String":{const n=t.value,r=n.slice(1,n.length-1).replaceAll('""','"');return{kind:"StringLit",value:r,ty:{kind:"String",exact:r},span:t.span}}case"Colon":throw new W("bare ':' is only valid inside an index expression",t.span);default:throw new W(`expression type '${t.type}' not supported`,t.span)}}lowerEndKeyword(t){if(this.endStack.length===0)throw new W("'end' is only valid inside an index expression",t.span);const n=this.endStack[this.endStack.length-1];if(n.axis==="linear"){if(n.baseTy.shape!==void 0){const r=Dt(n.baseTy.shape);return{kind:"NumLit",value:r,ty:Be(r>0?"positive":"nonneg",r),span:t.span}}}else{const r=n.axis;if(n.baseTy.shape!==void 0&&r<n.baseTy.shape.length){const s=n.baseTy.shape[r];return{kind:"NumLit",value:s,ty:Be(s>0?"positive":"nonneg",s),span:t.span}}}return{kind:"EndRef",baseCName:n.baseCName,baseTy:n.baseTy,axis:n.axis,ty:Be("nonneg"),span:t.span}}lowerRangeAsValue(t){const n=this.lowerExpr(t.start),r=this.lowerExpr(t.end);let s;t.step===null?s={kind:"NumLit",value:1,ty:Be("positive",1),span:t.span}:s=this.lowerExpr(t.step),this.requireScalarReal(n.ty,"range start",t.start.span),this.requireScalarReal(r.ty,"range end",t.end.span),this.requireScalarReal(s.ty,"range step",t.step?.span??t.span);let o;const i=Me(n.ty)&&typeof n.ty.exact=="number"?n.ty.exact:void 0,a=Me(s.ty)&&typeof s.ty.exact=="number"?s.ty.exact:void 0,c=Me(r.ty)&&typeof r.ty.exact=="number"?r.ty.exact:void 0;if(i!==void 0&&a!==void 0&&c!==void 0&&a!==0&&Number.isFinite(i)&&Number.isFinite(a)&&Number.isFinite(c)){const l=ob(i,a,c);if(l===1)return n;o=et([1,l])}else o={kind:"Numeric",elem:"double",isComplex:!1,dims:[{kind:"exact",value:1},{kind:"unknown"}],sign:"unknown"};return{kind:"MakeRange",start:n,step:s,end:r,ty:o,span:t.span}}lowerMember(t){const n=this.lowerExpr(t.base);if(this.requireValueType(n,`field access '.${t.name}'`),n.ty.kind==="Class"){const s=this.classReg(n.ty.className),o=s?.getters.get(t.name);if(o!==void 0&&s!==void 0)return So.call(this,o,[n],`${n.ty.className}.get.${t.name}`,t.span,{specSource:Xa(n.ty.className,`get.${t.name}`),definingFile:o.span.file??s.file})}const r=cl(n.ty,t.name);if(r===void 0)throw new le(`no field '${t.name}' on type ${ze(n.ty)}`,t.span);return{kind:"MemberLoad",base:n,field:t.name,ty:r,span:t.span}}lowerIdent(t){const n=this.env.get(t.name);if(n!==void 0){if(n.maybeUnassigned)throw new W(`'${t.name}' may be used before it is assigned (assigned only on some branches)`,t.span);return{kind:"Var",name:t.name,cName:n.cName,ty:n.ty,span:t.span}}if((t.name==="nargout"||t.name==="nargin")&&this.callFrameStack.length>0){const s=this.callFrameStack[this.callFrameStack.length-1],o=t.name==="nargout"?s.nargout:s.nargin;return{kind:"NumLit",value:o,ty:Be(ft(o),o),span:t.span}}const r=is(t.name);if(r!==void 0){let s;try{s=r.transfer([],1)}catch{s=void 0}if(s!==void 0)return{kind:"Call",cName:t.name,name:t.name,args:[],ty:s[0],span:t.span}}throw new W(`undefined variable '${t.name}' (or unsupported reference)`,t.span)}lowerBinary(t){if(t.op===je.Mul&&t.left.type==="Number"&&t.right.type==="ImagUnit"){const a=Number(t.left.value);if(Number.isFinite(a))return{kind:"ImagLit",value:a,ty:_t({re:0,im:a}),span:t.span}}if(t.op===je.OrOr||t.op===je.AndAnd){const a=this.lowerExpr(t.left);this.requireValueType(a,"binary operator operand");let c;Me(a.ty)&&!a.ty.isComplex&&Kn(a.ty)&&typeof a.ty.exact=="number"&&(c=a.ty.exact);const l=t.op===je.OrOr;if(c!==void 0&&(l&&c!==0&&!Number.isNaN(c)||!l&&c===0)){const u={kind:"NumLit",value:l?1:0,ty:at(l),span:t.span};return Pm(a)?u:{kind:"Binary",builtin:l?"oror":"andand",op:t.op,left:a,right:u,ty:at(l),span:t.span}}}const n=this.lowerExpr(t.left);this.requireValueType(n,"binary operator operand");const r=this.lowerExpr(t.right);this.requireValueType(r,"binary operator operand");const s=rB(t.op,t.span),o=is(s);if(!o)throw new W(`builtin '${s}' not registered`,t.span);const i=Yo(t.span,()=>o.transfer([n.ty,r.ty],1))[0];return{kind:"Binary",builtin:s,op:t.op,left:n,right:r,ty:i,span:t.span}}lowerUnary(t){const n=this.lowerExpr(t.operand);if(this.requireValueType(n,"unary operator operand"),t.op===gn.Transpose&&Me(n.ty)&&n.ty.isComplex){const i=is("conj"),a=is("transpose");if(!i||!a)throw new W("internal: 'conj'/'transpose' must be registered for complex ctranspose",t.span);const c=Yo(t.span,()=>i.transfer([n.ty],1))[0],l={kind:"Call",cName:"conj",name:"conj",args:[n],ty:c,span:t.span},u=Yo(t.span,()=>a.transfer([c],1))[0];return{kind:"Call",cName:"transpose",name:"transpose",args:[l],ty:u,span:t.span}}const r=sB(t.op,t.span),s=is(r);if(!s)throw new W(`builtin '${r}' not registered`,t.span);const o=Yo(t.span,()=>s.transfer([n.ty],1))[0];return{kind:"Unary",builtin:r,op:t.op,operand:n,ty:o,span:t.span}}requireScalarReal(t,n,r,s){if(!Kn(t)){const o=s?` ${s}`:"";throw new W(`${n} must be a scalar real numeric${o}`,r)}}requireScalarCondType(t,n,r){if(!(Me(t)&&(t.elem==="double"||t.elem==="logical")&&t.dims.length===2&&t.dims[0].kind==="exact"&&t.dims[0].value===1&&t.dims[1].kind==="exact"&&t.dims[1].value===1))throw new W(`${n} must be a scalar numeric`,r)}mergeBranchEnvs(t,n=!1){const r=new Set;for(const o of t)for(const i of o.keys())r.add(i);const s=new Map;for(const o of r){const i=t.map(u=>u.get(o)).filter(u=>u!==void 0);if(i.length===0)continue;let a=i[0].ty;for(let u=1;u<i.length;u++)a=Li(a,i[u].ty);i.length<t.length&&(a=bo(a));const c=n&&i.length<t.length||i.some(u=>u.maybeUnassigned),l={cName:i[0].cName,ty:a};c&&(l.maybeUnassigned=!0),s.set(o,l)}return s}}const FB=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","main","_Bool","_Complex","_Imaginary","async","await","catch","class","debugger","delete","export","extends","false","finally","function","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","super","this","throw","true","try","typeof","var","with","yield","arguments","eval"]);function Hi(e){return FB.has(e)?`v_${e}`:e}function jB(e){if(!Me(e.ty))return null;const t=e.ty.exact;if(typeof t=="number")return Number.isFinite(t)?t!==0:null;const n=An(e.ty);return n!==void 0?!Number.isFinite(n.re)||!Number.isFinite(n.im)?null:n.re!==0||n.im!==0:null}function Bm(e){switch(e.kind){case"NumLit":case"ImagLit":case"Var":case"EndRef":case"HandleCaptureLoad":return!0;case"Unary":return Bm(e.operand);case"Binary":return Bm(e.left)&&Bm(e.right);default:return!1}}function ov(e){if(e.length>=2){const t=e[0],n=e[e.length-1];if(t==="'"&&n==="'"||t==='"'&&n==='"')return e.slice(1,-1)}return e}function RB(e,t,n){const r=Array.isArray(n)?n[n.length-1]:n;if(r.kind!=="IndexStore")return!1;const s=e.get(t);if(s===void 0||s.ty.kind!=="Numeric")return!1;const o=s.ty,i=o.shape,a=o.exact;if(i===void 0||!(a instanceof Float64Array)||!Me(r.rhs.ty)||typeof r.rhs.ty.exact!="number")return!1;const c=r.rhs.ty.exact,l=[];for(const m of r.indices){if(!Me(m.ty)||typeof m.ty.exact!="number")return!1;const p=m.ty.exact;if(!Number.isFinite(p)||!Number.isInteger(p)||p<1)return!1;l.push(p)}const u=ib(i,l);if(u===void 0)return!1;const f=new Float64Array(a);f[u]=c;const h=ol(f);return e.set(t,{cName:s.cName,ty:{...o,exact:f,sign:h}}),!0}function LB(e){const t=Array.isArray(e)?e[e.length-1]:e;return t.kind!=="IndexStore"&&t.kind!=="IndexSliceStore"?"unknown":Me(t.rhs.ty)?t.rhs.ty.sign:"unknown"}function iv(e,t,n,r){for(const s of U0(n)){const o=e.get(s),i=t.get(s);if(!(o===void 0||i===void 0)&&DB(o.ty,i.ty))throw new W(`loop body changes the shape of '${s}' across iterations (entry shape differs from end-of-iter shape); mtoc2 lowers the body once per spec and cannot specialize per-iteration growing tensors`,r)}}function DB(e,t){if(!Me(e)||!Me(t))return!1;if(e.dims.length!==t.dims.length)return!0;for(let s=0;s<e.dims.length;s++){const o=e.dims[s],i=t.dims[s];if(o.kind==="exact"&&i.kind==="exact"&&o.value!==i.value||o.kind==="exact"&&i.kind==="unknown")return!0}const n=e.shape,r=t.shape;if(n!==void 0&&r!==void 0){if(n.length!==r.length)return!0;for(let s=0;s<n.length;s++)if(n[s]!==r[s])return!0}else if(n!==void 0&&r===void 0)return!0;return!1}function U0(e){const t=new Set,n=s=>{if(s.type==="Var"){t.add(s.name);return}if(s.type==="Member"||s.type==="Index"){let o=s.base;for(;o!==null&&o.type==="Member";)o=o.base;o!==null&&o.type==="Ident"&&t.add(o.name)}},r=s=>{for(const o of s)switch(o.type){case"Assign":t.add(o.name);break;case"AssignLValue":n(o.lvalue);break;case"MultiAssign":for(const i of o.lvalues)n(i);break;case"If":r(o.thenBody);for(const i of o.elseifBlocks)r(i.body);o.elseBody&&r(o.elseBody);break;case"While":r(o.body);break;case"For":t.add(o.varName),r(o.body);break;case"Switch":for(const i of o.cases)r(i.body);o.otherwise&&r(o.otherwise);break;case"TryCatch":r(o.tryBody),r(o.catchBody);break}};return r(e),t}var TB={};const av=(()=>{const e=typeof globalThis<"u"&&TB,t=e?e.MTOC2_MAX_SPECS_PER_FUNCTION:void 0;if(!t)return 256;const n=Number.parseInt(t,10);return Number.isFinite(n)&&n>0?n:256})();function So(e,t,n,r,s={}){const o=t.map(l=>l.ty),i=e.outputs.length===0?0:1,a=vl.call(this,e,o,s.specSource,s.definingFile,void 0,i,r),c=e.outputs.length===0?Fi:a.outputTypes[0]??{kind:"Unknown"};return{kind:"Call",cName:a.cName,name:n,args:t,ty:c,span:r}}function vl(e,t,n,r,s,o,i){const a=i??e.span;for(const N of e.params)if(N==="~")throw new W(`function '${e.name}' has a '~' placeholder parameter — cannot specialize`,a);if(t.length>e.params.length)throw new le(`function '${e.name}' expects ${e.params.length} arg(s), got ${t.length}`,a);const c=n??e.name,l=r??e.span.file??this.currentFile,u=o??e.outputs.length,f=`${l}|${t.map(Di).join("|")}|nargout=${u}`,h=`${rb(c)}__${Ti(f)}`,m=this.specializations.get(h);if(m)return m.body.length===0&&this.recursiveSpecsConsumed.add(h),m;const p=`${c}|${l}`,d=this.specCountPerSource.get(p)??0;if(d>=av)throw new W(`function '${e.name}' has exceeded the per-function specialization cap (${av}). This usually means exact-value tracking is sharding a call site into one spec per distinct input; widen the inputs (e.g. via '%!numbl:opaque') or raise the cap via the MTOC2_MAX_SPECS_PER_FUNCTION env var.`,a);this.specCountPerSource.set(p,d+1);const g=e.outputs.slice(0,u),w=g.map((N,E)=>t[E]??Pr),_=e.params.slice(0,t.length),y={name:e.name,cName:h,params:_.slice(),cParams:_.map(Hi),paramTypes:t,outputs:g.slice(),cOutputs:g.map(Hi),outputTypes:w,body:[],span:e.span};this.specializations.set(h,y);const b=this.env,k=this.tempCounter,M=this.currentFile;this.currentFile=l,this.callFrameStack.push({nargin:t.length,nargout:u});const $=()=>{this.env=new Map,this.tempCounter=0;for(let D=0;D<t.length;D++){const I=e.params[D];this.env.set(I,{cName:Hi(I),ty:t[D]})}let N=[];s!==void 0&&(this.requireValueType(s.initExpr,`constructor init for '${s.name}'`),N=[this.recordAssignment(s.name,s.initExpr,e.span)]);const E=[...N,...this.lowerStmts(e.body)],R=g.map(D=>{const I=this.env.get(D);if(!I)throw new le(`function '${e.name}': output '${D}' was never assigned`,a);if(I.maybeUnassigned)throw new W(`function '${e.name}': output '${D}' is assigned only on some branches`,a);return I.ty});return{body:E,outputTypes:R}};try{let{body:N,outputTypes:E}=$(),R=w;if(this.recursiveSpecsConsumed.has(h)&&!cv(R,E)){y.outputTypes=E,R=E;const I=$();if(N=I.body,E=I.outputTypes,!cv(R,E))throw new le(`function '${e.name}': recursive output type did not stabilize after two lowering passes. First pass produced [${w.map(Di).join(", ")}], second pass produced [${E.map(Di).join(", ")}]. This usually means the output type genuinely depends on a runtime value the lowerer can't resolve, or that the function is mutually recursive in a shape mtoc2 can't yet handle. Try annotating the output via an early assignment, or avoid recursion for this call.`,a)}for(let I=0;I<g.length;I++){const q=g[I],Y=this.env.get(q);if(Y===void 0)continue;const U=Hi(q);if(Y.cName!==U)throw new W(`function '${e.name}': output '${q}' was reassigned with an incompatible C storage type partway through the body — the function output cannot be represented as a single C variable.`,a);if(E[I].kind==="Unknown")throw new W(`function '${e.name}': output '${q}' resolves to an unknown type at function exit — usually because the body unifies two storage-distinct values for it (e.g. a real and a complex tensor, or a scalar and a tensor). Cannot represent this in the C/JS ABI as a single output slot.`,a)}const D={...y,body:N,outputTypes:E};return this.specializations.set(h,D),D}catch(N){throw this.specializations.delete(h),N}finally{this.env=b,this.tempCounter=k,this.currentFile=M,this.callFrameStack.pop(),this.recursiveSpecsConsumed.delete(h)}}function cv(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(Di(e[n])!==Di(t[n]))return!1;return!0}function PB(e){throw new Error("C runtime snippets not registered; call setCSnippets at bootstrap (C-JIT is Node-only — see executors/jit/compileC.node.ts)")}function Pe(e,t=[]){const n=e.replace(/\.h$/,".js"),r=ID[n];let s=null;const o=()=>(s===null&&(s=PB()),s),i={get headers(){return o().headers},get code(){return o().code},deps:t,srcFilename:e};return r!==void 0&&(i.jsCode=r),i}const lv=new Map([["mtoc2_host_output",Pe("host_output.h")],["mtoc2_format_double",Pe("format_double.h")],["mtoc2_disp_double",Pe("disp_double.h",["mtoc2_format_double","mtoc2_host_output"])],["mtoc2_cscalar",Pe("cscalar.h")],["mtoc2_cdiv",Pe("cdiv.h")],["mtoc2_format_complex",Pe("format_complex.h",["mtoc2_format_double"])],["mtoc2_disp_complex",Pe("disp_complex.h",["mtoc2_format_complex","mtoc2_host_output"])],["mtoc2_string_t",Pe("string.h")],["mtoc2_string_empty",Pe("string_empty.h",["mtoc2_string_t"])],["mtoc2_string_free",Pe("string_free.h",["mtoc2_string_t"])],["mtoc2_string_assign",Pe("string_assign.h",["mtoc2_string_t","mtoc2_string_free"])],["mtoc2_string_copy",Pe("string_copy.h",["mtoc2_string_t"])],["mtoc2_string_from_literal",Pe("string_from_literal.h",["mtoc2_string_t"])],["mtoc2_char_tensor_t",Pe("char_tensor.h")],["mtoc2_char_tensor_empty",Pe("char_tensor_empty.h",["mtoc2_char_tensor_t"])],["mtoc2_char_tensor_free",Pe("char_tensor_free.h",["mtoc2_char_tensor_t"])],["mtoc2_char_tensor_assign",Pe("char_tensor_assign.h",["mtoc2_char_tensor_t","mtoc2_char_tensor_free"])],["mtoc2_char_tensor_copy",Pe("char_tensor_copy.h",["mtoc2_char_tensor_t"])],["mtoc2_char_tensor_from_literal",Pe("char_tensor_from_literal.h",["mtoc2_char_tensor_t"])],["mtoc2_text_view_t",Pe("text_view.h",["mtoc2_string_t","mtoc2_char_tensor_t"])],["mtoc2_disp_text",Pe("disp_text.h",["mtoc2_text_view_t","mtoc2_host_output"])],["mtoc2_strcmp",Pe("strcmp.h",["mtoc2_text_view_t"])],["mtoc2_strcmpi",Pe("strcmp.h",["mtoc2_text_view_t"])],["mtoc2_dot_real",Pe("tensor_dot.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_cscalar","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_uniquetol_real",Pe("tensor_uniquetol.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_format_engine",Pe("format_engine.h",["mtoc2_text_view_t","mtoc2_tensor_t"])],["mtoc2_fprintf",Pe("fprintf.h",["mtoc2_format_engine","mtoc2_host_output"])],["mtoc2_error_fmt",Pe("error_fmt.h",["mtoc2_format_engine"])],["mtoc2_error_fmt_id",Pe("error_fmt.h",["mtoc2_format_engine"])],["mtoc2_warning_fmt",Pe("warning_fmt.h",["mtoc2_format_engine"])],["mtoc2_warning_fmt_id",Pe("warning_fmt.h",["mtoc2_format_engine"])],["mtoc2_assert_scalar_fmt",Pe("assert_fmt.h",["mtoc2_format_engine"])],["mtoc2_sprintf_str",Pe("sprintf.h",["mtoc2_format_engine","mtoc2_string_t","mtoc2_char_tensor_t"])],["mtoc2_sprintf_char",{headers:[],code:"",deps:["mtoc2_sprintf_str"]}],["mtoc2_scalar_index",Pe("scalar_index.h")],["mtoc2_deep_clone",Pe("deep_clone.h")],["mtoc2_alloc",Pe("alloc.h")],["mtoc2_tensor_t",Pe("tensor.h")],["mtoc2_tensor_alloc",Pe("tensor_alloc.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_empty",Pe("tensor_empty.h",["mtoc2_tensor_t"])],["mtoc2_tensor_copy",Pe("tensor_copy.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_empty"])],["mtoc2_tensor_assign",Pe("tensor_assign.h",["mtoc2_tensor_t"])],["mtoc2_tensor_free",Pe("tensor_free.h",["mtoc2_tensor_t"])],["mtoc2_tensor_from_row",Pe("tensor_from_row.h",["mtoc2_tensor_alloc"])],["mtoc2_tensor_from_matrix",Pe("tensor_from_matrix.h",["mtoc2_tensor_alloc"])],["mtoc2_tensor_alloc_nd",Pe("tensor_alloc_nd.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_zeros_nd",Pe("tensor_zeros_nd.h",["mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_ones_nd",Pe("tensor_ones_nd.h",["mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_zeros_square",Pe("tensor_zeros_square.h",["mtoc2_tensor_zeros_nd"])],["mtoc2_tensor_ones_square",Pe("tensor_ones_square.h",["mtoc2_tensor_ones_nd"])],["mtoc2_tensor_eye",Pe("tensor_eye.h",["mtoc2_tensor_alloc"])],["mtoc2_tensor_fill_nd",Pe("tensor_fill_nd.h",["mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_fill_square",Pe("tensor_fill_square.h",["mtoc2_tensor_fill_nd"])],["mtoc2_reshape_nd",Pe("tensor_reshape_nd.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd"])],["mtoc2_reshape_nd_complex",Pe("tensor_reshape_nd_complex.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_transpose",Pe("tensor_transpose.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc"])],["mtoc2_tensor_transpose_complex",Pe("tensor_transpose_complex.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_mtimes_real",Pe("tensor_mtimes_real.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc"])],["mtoc2_tensor_mtimes_complex",Pe("tensor_mtimes_complex.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_size_row",Pe("tensor_size.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_flip",Pe("tensor_flip.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_sort_real",Pe("tensor_sort_real.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_assign","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_meshgrid",Pe("tensor_meshgrid.h",["mtoc2_tensor_t","mtoc2_tensor_alloc","mtoc2_tensor_assign"])],["mtoc2_assert_scalar",Pe("assert_fail.h")],["mtoc2_tensor_norm",Pe("tensor_norm.h",["mtoc2_tensor_t"])],["mtoc2_isequal",Pe("isequal.h",["mtoc2_tensor_t"])],["mtoc2_tensor_predicate",Pe("tensor_predicate.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_cumulative",Pe("tensor_cumulative.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_repmat",Pe("tensor_repmat.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_diag",Pe("tensor_diag.h",["mtoc2_tensor_t","mtoc2_tensor_alloc","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_triangular",Pe("tensor_triangular.h",["mtoc2_tensor_t","mtoc2_tensor_alloc","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_cat",Pe("tensor_cat.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex"])],["mtoc2_tensor_besselh",Pe("tensor_besselh.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_logical_real",Pe("tensor_logical_real.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_disp_tensor",Pe("disp_tensor.h",["mtoc2_tensor_t","mtoc2_format_double","mtoc2_host_output"])],["mtoc2_disp_tensor_inline",Pe("disp_tensor_inline.h",["mtoc2_tensor_t","mtoc2_format_double","mtoc2_host_output"])],["mtoc2_disp_struct",Pe("disp_struct.h")],["mtoc2_cell_make",Pe("cell.h")],["mtoc2_cell_empty",Pe("cell.h")],["mtoc2_format_cell",Pe("cell.h")],["mtoc2_tensor_alloc_complex",Pe("tensor_alloc_complex.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_alloc_nd_complex",Pe("tensor_alloc_nd_complex.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_copy_complex",Pe("tensor_copy_complex.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_empty"])],["mtoc2_tensor_from_row_complex",Pe("tensor_from_row_complex.h",["mtoc2_tensor_alloc_complex"])],["mtoc2_tensor_from_matrix_complex",Pe("tensor_from_matrix_complex.h",["mtoc2_tensor_alloc_complex"])],["mtoc2_disp_tensor_complex",Pe("disp_tensor_complex.h",["mtoc2_tensor_t","mtoc2_format_complex","mtoc2_cscalar","mtoc2_host_output"])],["mtoc2_tensor_elemwise_complex",Pe("tensor_elemwise_complex.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd_complex","mtoc2_cscalar","mtoc2_cdiv"])],["mtoc2_tensor_unary_complex_math",Pe("tensor_unary_complex_math.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex","mtoc2_cscalar"])],["mtoc2_tensor_reduce_complex",Pe("tensor_reduce_complex.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd","mtoc2_tensor_alloc_nd_complex","mtoc2_cscalar","mtoc2_cdiv"])],["mtoc2_tensor_imag_all_zero",Pe("tensor_imag_all_zero.h",["mtoc2_tensor_t"])],["mtoc2_tensor_elemwise_real",Pe("tensor_elemwise_real.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_elemwise_real_fn",Pe("tensor_elemwise_real_fn.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_unary_real_math",Pe("tensor_unary_real_math.h",["mtoc2_tensor_t","mtoc2_alloc"])],["mtoc2_tensor_reduce_real",Pe("tensor_reduce_real.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_var",Pe("tensor_var.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_tensor_diff",Pe("tensor_diff.h",["mtoc2_tensor_t","mtoc2_alloc","mtoc2_tensor_alloc_nd"])],["mtoc2_length",Pe("length.h",["mtoc2_tensor_t"])],["mtoc2_numel",Pe("numel.h",["mtoc2_tensor_t"])],["mtoc2_loop_count",Pe("loop_count.h")],["mtoc2_range_value",Pe("range_value.h")],["mtoc2_oob_abort",Pe("oob.h",["mtoc2_tensor_t"])],["mtoc2_grow_bail",Pe("grow_bail.h",["mtoc2_tensor_t","mtoc2_oob_abort"])],["mtoc2_tensor_make_range",Pe("tensor_make_range.h",["mtoc2_tensor_t","mtoc2_tensor_alloc_nd","mtoc2_loop_count","mtoc2_range_value"])],["mtoc2_tensor_linspace",Pe("tensor_linspace.h",["mtoc2_tensor_t","mtoc2_tensor_alloc"])],["mtoc2_tensor_logspace",Pe("tensor_logspace.h",["mtoc2_tensor_t","mtoc2_tensor_alloc"])],["mtoc2_logical_mask_indices",Pe("tensor_logical_mask.h",["mtoc2_tensor_t","mtoc2_oob_abort"])],["mtoc2_tic_toc",Pe("tictoc.h")],["mtoc2_plot_dispatch",Pe("plot_dispatch.h",["mtoc2_format_engine"])]]);function BB(e){const t=lv.get(e);if(!t)throw new Error(`runtime snippet '${e}' not registered`);return t}function uv(e,t){const n=e.extraSnippets.get(t);return n!==void 0?n:BB(t)}function qB(e){return{active:new Set,multiAssignCallCounter:0,extraSnippets:new Map,...e!==void 0?{workspace:e}:{}}}function qm(e,t){const n=e.workspace?.getUserBuiltin(t);return n!==void 0?n:is(t)}let W0;function zB(){if(W0!==void 0)return W0;const e=new Map;for(const[t,n]of lv.entries())n.srcFilename!==void 0&&e.set(n.srcFilename,t);return W0=e,e}function Pt(e,t){if(e.active.has(t))return;const n=uv(e,t);for(const r of n.deps)Pt(e,r);if(n.srcFilename!==void 0){const r=n.srcFilename.replace(/\.h$/,".js"),s=FD[r];if(s!==void 0&&s.length>0){const o=zB();for(const i of s){const a=i.replace(/\.js$/,".h"),c=o.get(a);c!==void 0&&Pt(e,c)}}}e.active.add(t)}function VB(e){if(e.active.size===0)return"";const t=[];for(const n of e.active){const r=uv(e,n);r.jsCode!==void 0&&t.push(r.jsCode)}return t.join(`
|
|
5248
5248
|
`)}function UB(e,t,n){const r=e.ty.kind==="Numeric"&&e.ty.isComplex;return r?Pt(t,"mtoc2_tensor_alloc_nd_complex"):Pt(t,"mtoc2_tensor_alloc_nd"),e.shape.every(o=>o!==null)&&e.rowHeights.every(o=>o!==null)&&e.cellCols.every(o=>o.every(i=>i!==null))?WB(e.cells,e.shape,e.rowHeights,e.cellCols,r,t,n):XB(e,r,t,n)}function WB(e,t,n,r,s,o,i){const[a]=t,c=[];s?c.push(`const _mtoc2_t = mtoc2_tensor_alloc_nd_complex(2, [${a}, ${t[1]}]);`):c.push(`const _mtoc2_t = mtoc2_tensor_alloc_nd(2, [${a}, ${t[1]}]);`);let l=0;for(let u=0;u<e.length;u++){const f=e[u],h=n[u];let m=0;for(let p=0;p<f.length;p++){const d=f[p],g=r[u][p],w=i(d,o),_=d.ty.kind==="Numeric"&&d.ty.isComplex;if(h===1&&g===1){const y=`${l} + ${m} * ${a}`;if(s){const b=`_mtoc2_c_${u}_${p}`;c.push(`const ${b} = ${w};`);const k=_?`${b}.re`:b,M=_?`${b}.im`:"0";c.push(`_mtoc2_t.data[${y}] = ${k};`),c.push(`_mtoc2_t.imag[${y}] = ${M};`)}else c.push(`_mtoc2_t.data[${y}] = ${w};`)}else{c.push(`for (let _mtoc2_sc = 0; _mtoc2_sc < ${g}; _mtoc2_sc++) {`),c.push(` for (let _mtoc2_sr = 0; _mtoc2_sr < ${h}; _mtoc2_sr++) {`);const y=`(${l} + _mtoc2_sr) + (${m} + _mtoc2_sc) * ${a}`,b=`_mtoc2_sr + _mtoc2_sc * ${h}`;if(s){const k=`_mtoc2_c_${u}_${p}`;c.push(` const ${k} = ${w};`),c.push(` _mtoc2_t.data[${y}] = ${k}.data[${b}];`),c.push(` _mtoc2_t.imag[${y}] = ${k}.imag !== undefined ? ${k}.imag[${b}] : 0;`)}else c.push(` _mtoc2_t.data[${y}] = ${w}.data[${b}];`);c.push(" }"),c.push("}")}m+=g}l+=h}return c.push("return _mtoc2_t;"),`(() => { ${c.join(" ")} })()`}function XB(e,t,n,r){if(t)throw new Error("emitJs: dynamic-shape complex TensorConcat is not yet supported");const s=[],o=e.cells.map(f=>f.map(h=>r(h,n))),i=(f,h)=>{const m=e.cells[f][h];if(m.ty.kind!=="Numeric"||m.ty.dims.length===0||De(m.ty))return"1";const p=e.rowHeights[f];return p!==null?`${p}`:`${o[f][h]}.shape[0]`},a=(f,h)=>{const m=e.cells[f][h];if(m.ty.kind!=="Numeric"||m.ty.dims.length===0||De(m.ty))return"1";const p=e.cellCols[f][h];return p!==null?`${p}`:`${o[f][h]}.shape[1]`},c=[];for(let f=0;f<e.cells.length;f++){const h=`_mtoc2_rh_${f}`;c.push(h),s.push(`const ${h} = ${i(f,0)};`)}const l=e.shape[0]!==null?`${e.shape[0]}`:c.join(" + ");s.push(`const _mtoc2_tr = ${l};`);const u=e.shape[1]!==null?`${e.shape[1]}`:e.cells.length===0?"0":e.cells[0].map((f,h)=>a(0,h)).join(" + ");s.push(`const _mtoc2_tc = ${u};`),s.push("const _mtoc2_t = mtoc2_tensor_alloc_nd(2, [_mtoc2_tr, _mtoc2_tc]);"),s.push("let _mtoc2_row_off = 0;");for(let f=0;f<e.cells.length;f++){const h=e.cells[f];s.push(`let _mtoc2_col_off_${f} = 0;`);for(let m=0;m<h.length;m++){const p=h[m],d=o[f][m],g=i(f,m),w=a(f,m);if(m>0&&s.push(`if ((${g}) !== ${c[f]}) throw new Error("Dimensions of arrays being concatenated are not consistent");`),p.ty.kind==="Numeric"&&(p.ty.dims.length===0||De(p.ty))){const y=`_mtoc2_row_off + _mtoc2_col_off_${f} * _mtoc2_tr`;s.push(`_mtoc2_t.data[${y}] = ${d};`),s.push(`_mtoc2_col_off_${f} += 1;`)}else{const y=`_mtoc2_sc_${f}_${m}`,b=`_mtoc2_sr_${f}_${m}`,k=`_mtoc2_cw_${f}_${m}`,M=`_mtoc2_ch_${f}_${m}`;s.push(`const ${k} = ${w};`),s.push(`const ${M} = ${g};`),s.push(`for (let ${y} = 0; ${y} < ${k}; ${y}++) {`),s.push(` for (let ${b} = 0; ${b} < ${M}; ${b}++) {`);const $=`(_mtoc2_row_off + ${b}) + (_mtoc2_col_off_${f} + ${y}) * _mtoc2_tr`,N=`${b} + ${y} * ${M}`;s.push(` _mtoc2_t.data[${$}] = ${d}.data[${N}];`),s.push(" }"),s.push("}"),s.push(`_mtoc2_col_off_${f} += ${k};`)}}s.push(`if (_mtoc2_col_off_${f} !== _mtoc2_tc) throw new Error("Dimensions of arrays being concatenated are not consistent");`),s.push(`_mtoc2_row_off += ${c[f]};`)}return s.push("return _mtoc2_t;"),`(() => { ${s.join(" ")} })()`}function HB(e,t={}){const n=qB(t.workspace),r=t.includeRuntime??!0;if(t.exposeSpec!==void 0){if(e.topLevelStmts.length>0)throw new Error("emitJsProgram: 'exposeSpec' is incompatible with non-empty 'topLevelStmts'");if(!e.functions.has(t.exposeSpec))throw new Error(`emitJsProgram: 'exposeSpec' references unknown spec '${t.exposeSpec}'`)}const s=[];for(const a of e.functions.values())s.push(JB(a,n)),s.push("");const o=[];if(t.exposeSpec!==void 0)o.push(`return function ($h) { globalThis.$write = $h.write; globalThis.$plotDispatch = $h.plotDispatch; globalThis.$rand = $h.rand; return ${t.exposeSpec}; };`);else{o.push("function run($h) {"),o.push(" globalThis.$write = $h.write;"),o.push(" globalThis.$plotDispatch = $h.plotDispatch;"),o.push(" globalThis.$rand = $h.rand;");const a=mv(e.topLevelStmts);a.length>0&&o.push(` let ${a.join(", ")};`);const c=Oa(e.topLevelStmts," ",n);c.length>0&&o.push(c),o.push("}"),o.push("return run;")}const i=[];return n.active.size>0&&(i.push(r?VB(n):YB(n)),i.push("")),i.push(...s),i.push(...o),{source:i.join(`
|
|
5249
5249
|
`),activatedSnippets:Array.from(n.active)}}function YB(e){if(e.active.size===0)return"";const t=Array.from(e.active).join(", ");return`/* runtime helpers omitted (${e.active.size}): ${t} */`}function JB(e,t){const n=e.cParams.join(", "),r=[];r.push(`function ${e.cName}(${n}) {`);const s=new Set(e.cParams),o=mv(e.body).filter(c=>!s.has(c));o.length>0&&r.push(` let ${o.join(", ")};`);const i=t.currentFnOutputs;t.currentFnOutputs=e.cOutputs;const a=Oa(e.body," ",t);return t.currentFnOutputs=i,a.length>0&&r.push(a),e.outputs.length===0||(e.outputs.length===1?r.push(` return ${e.cOutputs[0]};`):r.push(` return [${e.cOutputs.join(", ")}];`)),r.push("}"),r.join(`
|
|
5250
5250
|
`)}function ZB(e,t){const n=e.currentFnOutputs;return n===void 0||n.length===0?`${t}return;`:n.length===1?`${t}return ${n[0]};`:`${t}return [${n.join(", ")}];`}function Oa(e,t,n){const r=[];for(const s of e){const o=KB(s,t,n);o.length>0&&r.push(o)}return r.join(`
|