@gasm-compiler/core 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/dist/browser-executor.js +1 -1
- package/dist/browser.d.ts +84 -3
- package/dist/browser.js +10 -1
- package/dist/{chunk-G6YRZSKB.js → chunk-IZGS3OS2.js} +1 -1
- package/dist/chunk-PS4NV6ZB.js +5 -0
- package/dist/chunk-VSCQDCQR.js +9 -0
- package/dist/compiler.js +1 -1
- package/dist/{parser-C7xAx4nx.d.ts → error_codes-D6RsiZ33.d.ts} +78 -1
- package/dist/gasm_core_rs.wasm +0 -0
- package/dist/mod.d.ts +6 -3
- package/dist/mod.js +1 -1
- package/package.json +10 -5
- package/dist/chunk-3GAG34KX.js +0 -5
- package/dist/chunk-OJJM3SJ5.js +0 -5
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{A as le,B as de,C as fe,G,H as N,I as q,J as j,K as H,L as Z,a as S,c as te,d as O,e as W,f as M,g as F,h as U,j as z,k as T,n as ne,p as re,q as oe,r as ie,s as se,t as ae,y as ce,z as ue}from"./chunk-PS4NV6ZB.js";import{a as h}from"./chunk-STDXBN5E.js";import{resolve as _e}from"node:path";import{stat as Me,readFile as ct,writeFile as ut,unlink as lt,mkdir as dt}from"node:fs/promises";import{spawn as ft}from"node:child_process";import{dirname as pt}from"node:path";function pe(e){let t=e.functions.map(n=>!("parallelLoopInfo"in n)||!n.parallelLoopInfo?n:Ve(n));return{...e,functions:t}}function Ve(e){let t=e.parallelLoopInfo.loopLocalIndex,{writes:n}=Re(e.body,t);if(n>0){let r=x(e.body,t);return{...e,body:r}}return e}function Re(e,t){let n=0,r=0;function o(s){switch(s.kind){case"simple":if(s.instructions)for(let i of s.instructions)i.opcode==="local.get"&&i.immediates?.[0]===t&&n++,(i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates?.[0]===t&&r++;break;case"block":for(let i of s.children)o(i);break;case"loop":o(s.body);break;case"if":o(s.thenBranch),s.elseBranch&&o(s.elseBranch);break;case"parallel_loop":o(s.body),s.epilogue&&o(s.epilogue);break;case"return":case"break":case"continue":break}}return o(e),{reads:n,writes:r}}function x(e,t){switch(e.kind){case"simple":{if(!e.instructions)return e;let n=e.instructions.filter(r=>!((r.opcode==="local.set"||r.opcode==="local.tee")&&r.immediates?.[0]===t));return n.length===0?{kind:"block",children:[]}:{...e,instructions:n}}case"block":{let n=e.children.map(r=>x(r,t)).filter(r=>!Be(r));return{...e,children:n}}case"loop":return{...e,body:x(e.body,t)};case"if":return{...e,thenBranch:x(e.thenBranch,t),elseBranch:e.elseBranch?x(e.elseBranch,t):void 0};case"parallel_loop":return{...e,body:x(e.body,t),epilogue:e.epilogue?x(e.epilogue,t):void 0};case"return":case"break":case"continue":return e}}function Be(e){return e.kind==="block"&&e.children.length===0||e.kind==="simple"&&(!e.instructions||e.instructions.length===0)}function me(e){let t=e.functions.map(n=>Oe(n));return{...e,functions:t}}function Oe(e){let t=C(e.body,e);return{...e,body:t}}function C(e,t){switch(e.kind){case"loop":{let n=We(e.body),r=[],o=ge(e.body,n,r,t);return r.length===0?{...e,body:C(e.body,t)}:{kind:"block",children:[{kind:"simple",instructions:r},{...e,body:C(o,t)}],label:void 0}}case"block":return{...e,children:e.children.map(n=>C(n,t))};case"if":return{...e,thenBranch:C(e.thenBranch,t),elseBranch:e.elseBranch?C(e.elseBranch,t):void 0};case"simple":return e;default:return e}}function We(e){let t=new Set;function n(r){if(r.kind==="simple"&&r.instructions){for(let o of r.instructions)if(o.id!==void 0&&t.add(o.id),(o.opcode==="local.set"||o.opcode==="local.tee")&&o.immediates){let s=o.immediates[0];t.add(-s-1)}}r.kind==="block"&&r.children.forEach(n),r.kind==="loop"&&n(r.body),r.kind==="if"&&(n(r.thenBranch),r.elseBranch&&n(r.elseBranch))}return n(e),t}function ge(e,t,n,r){switch(e.kind){case"simple":{if(!e.instructions||e.instructions.length===0)return e;let o=[],s=new Set;for(let i of e.instructions)De(i,t,s)?(n.push(i),i.id!==void 0&&s.add(i.id)):(o.push(i),i.id!==void 0&&s.add(i.id));return{...e,instructions:o}}case"block":{let o=e.children.map(s=>ge(s,t,n,r));return{...e,children:o}}case"loop":return e;case"if":return e;default:return e}}function De(e,t,n){if(!Le(e.opcode))return!1;if(e.opcode==="local.get"&&e.immediates){let o=-e.immediates[0]-1;if(t.has(o))return!1}if(e.args){for(let r of e.args)if(t.has(r))return!1}return!0}function Le(e){return new Set(["i32.const","i64.const","f32.const","f64.const","local.get","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","f32.add","f32.sub","f32.mul","f32.div","f64.add","f64.sub","f64.mul","f64.div","i32.and","i32.or","i32.xor","i32.shl","i32.shr_s","i32.shr_u","i32.rotl","i32.rotr","i64.and","i64.or","i64.xor","i64.shl","i64.shr_s","i64.shr_u","i64.rotl","i64.rotr","i32.eqz","i32.eq","i32.ne","i32.lt_s","i32.lt_u","i32.gt_s","i32.gt_u","i32.le_s","i32.le_u","i32.ge_s","i32.ge_u","i64.eqz","i64.eq","i64.ne","i64.lt_s","i64.lt_u","i64.gt_s","i64.gt_u","i64.le_s","i64.le_u","i64.ge_s","i64.ge_u","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge","i32.wrap_i64","i64.extend_i32_s","i64.extend_i32_u","f32.convert_i32_s","f32.convert_i32_u","f32.convert_i64_s","f32.convert_i64_u","f32.demote_f64","f64.convert_i32_s","f64.convert_i32_u","f64.convert_i64_s","f64.convert_i64_u","f64.promote_f32","i32.reinterpret_f32","i64.reinterpret_f64","f32.reinterpret_i32","f64.reinterpret_i64","i32.clz","i32.ctz","i32.popcnt","i64.clz","i64.ctz","i64.popcnt","f32.abs","f32.neg","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f64.abs","f64.neg","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f32.min","f32.max","f32.copysign","f64.min","f64.max","f64.copysign"]).has(e)}function he(e){for(let t of e.functions)Pe(t);return e}function Pe(e){$(e.body,e)}function $(e,t){switch(e.kind){case"simple":Fe(e,t);break;case"block":for(let n of e.children)$(n,t);break;case"loop":$(e.body,t);break;case"if":$(e.thenBranch,t),e.elseBranch&&$(e.elseBranch,t);break;case"parallel_loop":$(e.body,t),e.epilogue&&$(e.epilogue,t);break}}function Fe(e,t){let n=Te(e.instructions,t);n.length>0&&Ne(e,t,n);let r=Ge(e.instructions,t);r.length>0&&qe(e,t,r)}function ye(e,t){let n=L(e,t);if(!n)return null;if(n.opcode==="i32.shr_u"&&n.args.length===2){if(D(n.args[1],t)!==2)return null;let o=n.args[0];return Ue(o,t)}return ze(e,t)}function Ue(e,t){let n=L(e,t);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let r=D(n.args[1],t);if(r!==null&&r>=0&&r%4===0)return{baseVar:n.args[0],wordOffset:r/4};let o=D(n.args[0],t);return o!==null&&o>=0&&o%4===0?{baseVar:n.args[1],wordOffset:o/4}:null}return{baseVar:e,wordOffset:0}}function ze(e,t){let n=L(e,t);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let r=D(n.args[1],t);if(r!==null&&r>=0)return{baseVar:n.args[0],wordOffset:r}}return{baseVar:e,wordOffset:0}}function L(e,t){if(t.inlinedExpressionMap){let n=t.inlinedExpressionMap.get(e);if(n)return n}return A(t.body,e)}function A(e,t){switch(e.kind){case"simple":for(let n of e.instructions)if(n.id===t)return n;return null;case"block":for(let n of e.children){let r=A(n,t);if(r)return r}return null;case"loop":return A(e.body,t);case"if":{let n=A(e.thenBranch,t);return n||(e.elseBranch?A(e.elseBranch,t):null)}case"parallel_loop":{let n=A(e.body,t);return n||(e.epilogue?A(e.epilogue,t):null)}default:return null}}function D(e,t){let n=L(e,t);return n&&n.opcode==="i32.const"&&n.immediates&&n.immediates.length>0?n.immediates[0]:null}function Te(e,t){let n=[],r=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.store_f32"&&i.args.length===2){let a=ye(i.args[0],t);a&&r.push({index:s,addr:a,valueArg:i.args[1]})}}let o=new Map;for(let s of r){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(g=>g.index);be(m,e)&&n.push({instrIndices:m,baseVar:s,valueArgs:d.map(g=>g.valueArg),components:p})}a=c+1}}return n}function Ge(e,t){let n=[],r=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.load_f32"&&i.args.length===1&&i.id!==void 0){let a=ye(i.args[0],t);a&&r.push({index:s,addr:a,resultVar:i.id})}}let o=new Map;for(let s of r){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(g=>g.index);be(m,e)&&n.push({instrIndices:m,baseVar:s,resultVars:d.map(g=>g.resultVar),components:p})}a=c+1}}return n}function be(e,t){if(e.length<3)return!1;let n=Math.min(...e),r=Math.max(...e),o=e.length*4;if(r-n>=o)return!1;for(let s=n;s<=r;s++)if(t[s].opcode.startsWith("wgsl.store")&&!e.includes(s))return!1;return!0}function Ne(e,t,n){n.sort((r,o)=>o.instrIndices[0]-r.instrIndices[0]);for(let r of n){let o=r.components===4?"wgsl.store_vec4f":"wgsl.store_vec3f",s=e.instructions[r.instrIndices[0]].args[0],i={type:"instr",opcode:o,args:[s,...r.valueArgs],synthetic:!0},a=[...r.instrIndices].sort((c,u)=>c-u);for(let c=a.length-1;c>=0;c--)e.instructions.splice(a[c],1);e.instructions.splice(a[0],0,i)}}function qe(e,t,n){n.sort((r,o)=>o.instrIndices[0]-r.instrIndices[0]);for(let r of n){let o=r.components===4?"wgsl.load_vec4f":"wgsl.load_vec3f",s=0;for(let d of t.vars.keys())d>s&&(s=d);let i=s+1;t.vars.set(i,{id:i,type:"v128"});let a=e.instructions[r.instrIndices[0]].args[0],c={type:"instr",id:i,opcode:o,args:[a],synthetic:!0},u=r.resultVars.map((d,m)=>({type:"instr",id:d,opcode:"wgsl.extract_f32",args:[i],immediates:[m],synthetic:!0})),p=[...r.instrIndices].sort((d,m)=>d-m);for(let d=p.length-1;d>=0;d--)e.instructions.splice(p[d],1);e.instructions.splice(p[0],0,c,...u)}}function K(e,t){let n={valid:!0,mathImports:[],errors:[],requiredLevel:null},r=t===!0||t==="M0"||t==="M1"||t==="M2",o=t===!0?"M2":t==="M0"||t==="M1"||t==="M2"?t:null,s=["M0","M1","M2"],i=0;for(let a of e.imports){if(a.kind!=="func")continue;let c=i++;if(!z(a.module,a.name))continue;let u=a.typeIndex;if(u===void 0){n.errors.push(S(`Math import ${a.name} has no type index`,{functionName:a.name})),n.valid=!1;continue}let p=e.types[u];if(!p){n.errors.push(S(`Math import ${a.name} references invalid type index ${u}`,{functionName:a.name})),n.valid=!1;continue}let d=T(a.name);if(!d){n.errors.push(S(`Unknown math intrinsic: ${a.name}`,{functionName:a.name})),n.valid=!1;continue}let m={funcIndex:c,module:a.module,name:a.name,level:d.level,params:p.params,results:p.results};if(n.mathImports.push(m),(n.requiredLevel===null||s.indexOf(d.level)>s.indexOf(n.requiredLevel))&&(n.requiredLevel=d.level),!r){n.errors.push(S(`Math intrinsic ${a.name} requires mathExtension option to be enabled`,{functionName:a.name})),n.valid=!1;continue}if(o&&!ne(a.name,o)){n.errors.push(S(`Math intrinsic ${a.name} requires level ${d.level}, but only ${o} is enabled`,{functionName:a.name})),n.valid=!1;continue}let g=re(a.name,p.params,p.results);g&&(n.errors.push(S(g,{functionName:a.name})),n.valid=!1)}return n}import{readFileSync as je}from"node:fs";var we,Se;async function He(e=Q()){let t=await Ke(e),n=await WebAssembly.instantiate(ve(t),{});return j(n.instance.exports)}function J(e=Q()){return Se??=He(e),Se}function Ze(e=Q()){let t=Je(e),n=new WebAssembly.Module(ve(t)),r=new WebAssembly.Instance(n,{});return j(r.exports)}function Ie(e,t={}){return we??=Ze(),we.compile(e,t)}function Q(){let e=globalThis.Deno,t=new URL("./gasm_core_rs.wasm",import.meta.url);if(e){let n=new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(n),n}catch{}let r=new URL("../../core-rs/target/wasm32-unknown-unknown/release/gasm_core_rs.wasm",import.meta.url);try{return e.statSync(r),r}catch{}try{return e.statSync(t),t}catch{}}return new URL("../../core-rs/target/wasm32-unknown-unknown/debug/gasm_core_rs.wasm",import.meta.url)}async function Ke(e){let t=globalThis.Deno;return t?await t.readFile(e):await(await import("node:fs/promises")).readFile(e)}function Je(e){let t=globalThis.Deno;return t?t.readFileSync(e):je(e)}function ve(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}var ke={};for(let[e,t]of Object.entries(te))ke[t]=e.replace(/_/g,".");function Qe(e){let t=[];t.push("(module");for(let r of e.memories)t.push(` (memory ${r.min}${r.max!==void 0?` ${r.max}`:""})`);for(let r of e.imports)if(r.kind==="func"&&r.typeIndex!==void 0){let o=e.types[r.typeIndex];if(o){let s=o.params.map((a,c)=>`(param $${c} ${a})`).join(" "),i=o.results.map(a=>`(result ${a})`).join(" ");t.push(` (import "${r.module}" "${r.name}" (func ${s}${i?" "+i:""}))`)}}let n=new Set;for(let r of e.globals){if(r.kind==="import")continue;let o=r.mutable?"(mut ":"",s=r.mutable?")":"",i="";r.initValue!==void 0&&(r.type==="i32"||r.type==="i64"?i=`${r.type}.const ${r.initValue}`:(r.type==="f32"||r.type==="f64")&&(i=`${r.type}.const ${r.initValue}`)),t.push(` (global $${r.index} ${o}${r.type}${s} ${i?`(${i})`:""})`)}for(let r of e.data){let o=Array.from(r.data.slice(0,Math.min(32,r.data.length))).map(i=>`\\${i.toString(16).padStart(2,"0")}`).join(""),s=r.data.length>32?"...":"";t.push(` (data (i32.const ${r.memoryIndex}) "${o}${s}") ;; ${r.data.length} bytes`)}for(let r of e.functions)t.push(""),t.push(...Xe(r,e));if(e.exports.length>0){t.push("");for(let r of e.exports)r.kind==="func"?t.push(` (export "${r.name}" (func $${r.index}))`):r.kind==="mem"?t.push(` (export "${r.name}" (memory ${r.index}))`):r.kind==="global"&&t.push(` (export "${r.name}" (global ${r.index}))`)}return e.startFunctionIndex!==void 0&&t.push(` (start $${e.startFunctionIndex})`),t.push(")"),t.join(`
|
|
2
|
+
`)}function Xe(e,t){let n=[],r=e.params.map((i,a)=>`(param $${a} ${i})`).join(" "),o=e.results.map(i=>`(result ${i})`).join(" ");if(n.push(` (func $${e.index} ${r}${o?" "+o:""}`),e.locals.length>0){let i=new Map;for(let a of e.locals)i.set(a.type,(i.get(a.type)||0)+1);for(let[a,c]of i)n.push(` (local ${a} (;${c}x;))`)}let s=Ye(e.body,2);return n.push(...s),n.push(" )"),n}function Ye(e,t){let n=[],r=" ".repeat(t);for(let o of e){let s=et(o,t);n.push(`${r}${s}`)}return n}function et(e,t){if(!e||typeof e!="object")return";; Error: Invalid instruction";let{opcode:n,immediates:r}=e,o=ke[n]||`unknown_0x${n.toString(16)}`;if(!r||r.length===0)return o;switch(o){case"local.get":case"local.set":case"local.tee":return`${o} $${r[0]}`;case"global.get":case"global.set":return`${o} $${r[0]}`;case"i32.const":case"i64.const":return`${o} ${r[0]}`;case"f32.const":case"f64.const":return`${o} ${r[0]}`;case"call":return`${o} $${r[0]}`;case"call_indirect":return`${o} (type ${r[0]})`;case"br":case"br_if":return`${o} ${r[0]}`;case"br_table":let s=r[0].join(" "),i=r[1];return`${o} ${s} ${i}`;case"if":case"block":case"loop":let a=r[0];return`${o} ${a!==void 0&&a!=="void"?`(result ${a})`:""}`;case"i32.load":case"i64.load":case"f32.load":case"f64.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":case"i32.store":case"i64.store":case"f32.store":case"f64.store":case"i32.store8":case"i32.store16":case"i64.store8":case"i64.store16":case"i64.store32":let c=r[0],u=r[1],p=[];return u!==0&&p.push(`offset=${u}`),c!==void 0&&p.push(`align=${1<<c}`),`${o}${p.length>0?" "+p.join(" "):""}`;case"memory.size":case"memory.grow":return o;default:if(o.startsWith("v128.")){if(o.includes("load")||o.includes("store")){let d=r[0],m=r[1],g=[];return m!==0&&g.push(`offset=${m}`),d!==void 0&&g.push(`align=${1<<d}`),`${o}${g.length>0?" "+g.join(" "):""}`}if(o.includes("const")){let d=r.join(" ");return`${o} ${d}`}return o.includes("extract_lane")||o.includes("replace_lane")?`${o} ${r[0]}`:`${o}${r.length>0?" "+r.join(" "):""}`}return`${o}${r.length>0?" "+r.join(" "):""}`}}var Bt=globalThis.gpu,tt=globalThis.navigator?.gpu,X=class{constructor(t={}){this.config=t}device=null;queue=null;initialized=!1;buffers=new Map;async ensureInitialized(){if(!this.initialized)try{let t=await tt?.requestAdapter?.();if(!t)throw new h("No GPU adapter available","compilation","navigator.gpu.requestAdapter() returned null");if(this.device=await t.requestDevice?.(),!this.device)throw new h("Failed to request GPU device","compilation","adapter.requestDevice() returned null");this.queue=this.device.queue,this.initialized=!0}catch(t){throw t instanceof h?t:new h(`GPU initialization failed: ${t instanceof Error?t.message:String(t)}`,"compilation",String(t))}}createBuffer(t,n,r){if(!this.device)throw new h("Device not initialized","binding","Call ensureInitialized() first");let o=this.device.createBuffer({label:t,size:n.byteLength,usage:r});return this.queue.writeBuffer(o,0,n.buffer,n.byteOffset,n.byteLength),o}async readBuffer(t,n,r){if(!this.device||!this.queue)throw new h("Device not initialized","readback","Call ensureInitialized() first");let o=Math.max(4,Math.ceil(n/4)*4),s=this.device.createBuffer({size:o,usage:9}),i=this.device.createCommandEncoder();i.copyBufferToBuffer(t,0,s,0,Math.min(n,o)),this.queue.submit([i.finish()]);try{await s.mapAsync(1)}catch(u){throw s.destroy(),new h(`Failed to map staging buffer: ${u instanceof Error?u.message:String(u)}`,"readback",String(u))}let a=s.getMappedRange(),c;return r==="f32"?c=new Float32Array(new Uint8Array(a).buffer).slice():r==="i32"?c=new Int32Array(new Uint8Array(a).buffer).slice():c=new Uint32Array(new Uint8Array(a).buffer).slice(),s.unmap(),s.destroy(),{data:c,type:r}}async execute(t,n,r,o={}){let s=o.workgroupSize??[1,1,1],i=o.workgroupCount??[1,1,1],a=o.timeout??5e3;if(await this.ensureInitialized(),!this.device||!this.queue)throw new h("Device initialization failed","compilation");try{let c;try{let l=o.shaderLabel||"Gasm Compiler Compute Shader";c=this.device.createShaderModule({code:t,label:l});let f=await c.getCompilationInfo?.();if(f&&f.messages.length>0){let y=f.messages.filter(w=>w.type==="error");if(y.length>0){let w=y.map(k=>`${k.message} at ${k.lineNum}:${k.linePos}`).join("; ");throw new h(`WGSL compilation failed: ${w}`,"compilation")}}}catch(l){throw l instanceof h?l:new h(`Failed to create shader module: ${l instanceof Error?l.message:String(l)}`,"compilation",String(l))}let u=[],p=0,d=new Map,m=Object.entries(n).sort((l,f)=>l[0]==="memory"?-1:f[0]==="memory"?1:l[0].localeCompare(f[0]));for(let[l,{data:f,type:y}]of m){let w=this.createBuffer(`input_${l}`,f,140);d.set(l,w),u.push({binding:p++,resource:{buffer:w}})}let g=new Map,b=new Map;for(let l of r){if(d.has(l)){let Ee=d.get(l),ee=n[l];g.set(l,Ee),b.set(l,{size:ee.data.byteLength,type:ee.type});continue}let f=o.outputBuffers?.[l]??{type:"f32",size:1},y=f.size??1,w=y*4,k=this.device.createBuffer({label:`output_${l}`,size:w,usage:140}),_;f.type==="f32"?_=new Float32Array(y).fill(0):f.type==="i32"?_=new Int32Array(y).fill(0):_=new Uint32Array(y).fill(0),this.queue.writeBuffer(k,0,_.buffer,_.byteOffset,_.byteLength),g.set(l,k),b.set(l,{size:w,type:f.type}),u.push({binding:p++,resource:{buffer:k}})}let I=Object.keys(n).length,E=this.device.createBindGroupLayout({entries:u.map((l,f)=>{let y=f===0&&n.memory!==void 0,w=f>=I;return{binding:f,visibility:4,buffer:{type:!y&&!w?"read-only-storage":"storage"}}})}),v=this.device.createBindGroup({layout:E,entries:u}),V=this.device.createPipelineLayout({bindGroupLayouts:[E]}),R;try{R=this.device.createComputePipeline({layout:V,compute:{module:c,entryPoint:"main"}})}catch(l){throw new h(`Failed to create compute pipeline: ${l instanceof Error?l.message:String(l)}`,"binding",String(l))}try{let l=this.device.createCommandEncoder(),f=l.beginComputePass();f.setPipeline(R),f.setBindGroup(0,v),f.dispatchWorkgroups(i[0],i[1],i[2]),f.end(),this.queue.submit([l.finish()])}catch(l){throw new h(`Compute shader dispatch failed: ${l instanceof Error?l.message:String(l)}`,"dispatch",String(l))}let B={};try{for(let l of r){let f=g.get(l),y=b.get(l);if(!f||!y)throw new h(`Output buffer "${l}" not found`,"readback");B[l]=await this.readBuffer(f,y.size,y.type)}}catch(l){throw l instanceof h?l:new h(`Failed to read back results: ${l instanceof Error?l.message:String(l)}`,"readback",String(l))}finally{let l=new Set;d.forEach(f=>{f.destroy(),l.add(f)}),g.forEach(f=>{l.has(f)||f.destroy()})}return B}catch(c){throw c instanceof h?c:new h(`Unexpected error during execution: ${c instanceof Error?c.message:String(c)}`,"dispatch",String(c))}}async destroy(){this.buffers.forEach(t=>t.destroy()),this.buffers.clear(),this.device&&typeof this.device.destroy=="function"&&this.device.destroy(),this.device=null,this.queue=null,this.initialized=!1}};function P(e,t={}){return Y()?it(e,t):xe(e,t)}async function gn(){Y()&&await J()}async function ot(e,t={}){return Y()?await st(e,t):xe(e,t)}function xe(e,t={}){let n=N(),r=G(t),o=t.strictConformance||r,s=O(e);if(W(s))return n.errors.push({severity:"error",code:s.code??M.ERR_PARSE,message:s.message,functionName:s.functionName}),{ok:!1,diagnostics:n};let i=s,a=F(i,{strictConformance:o});if(U(a))return n.errors.push({severity:"error",code:a.code??M.ERR_VALIDATION,message:a.message,functionName:a.functionName}),{ok:!1,diagnostics:n};let c=a;if(t.mathExtension){let b=K(i,t.mathExtension);if(!b.valid){for(let I of b.errors)n.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:I.message,functionName:I.functionName});return{ok:!1,diagnostics:n}}}let u=q(c,t);if(n.warnings.push(...u.diagnostics.warnings),n.errors.push(...u.diagnostics.errors),n.demotions.push(...u.diagnostics.demotions),n.featuresUsed=u.diagnostics.featuresUsed,n.errors.length>0)return{ok:!1,diagnostics:n};let p=ue(c);t.optimize!==!1&&(p=de(p,{verbose:t.verbose??!1}));let d=fe(p);d=oe(d),t.optimize!==!1&&(d=ie(d)),t.vectorPromotion&&(d=he(d));let m=se();if(t.optimize!==!1){let b=ae(d);d=b.module,m=b.dispatchInfo,d=pe(d),d=me(d)}return{ok:!0,wgsl:le(d,t,e,m),diagnostics:n,dispatchInfo:m}}function Y(){let t=globalThis.Deno?.env?.get("GASM_CORE_BACKEND")?.toLowerCase();return t!=="typescript"&&t!=="ts"}function it(e,t){let n=$e(e,t);if(!n.ok)return{ok:!1,diagnostics:n.diagnostics};let r=Ie(e,t);return r.ok?{ok:!0,wgsl:Ae(r.wgsl,t,e,n.module),diagnostics:n.diagnostics,dispatchInfo:H(r.dispatchInfo)}:(n.diagnostics.errors.push(...Z(r.diagnostics).errors),{ok:!1,diagnostics:n.diagnostics})}async function st(e,t){let n=$e(e,t);if(!n.ok)return{ok:!1,diagnostics:n.diagnostics};let o=(await J()).compile(e,t);return o.ok?{ok:!0,wgsl:Ae(o.wgsl,t,e,n.module),diagnostics:n.diagnostics,dispatchInfo:H(o.dispatchInfo)}:(n.diagnostics.errors.push(...Z(o.diagnostics).errors),{ok:!1,diagnostics:n.diagnostics})}function $e(e,t){let n=N(),r=O(e);if(W(r))return n.errors.push({severity:"error",code:r.code??M.ERR_PARSE,message:r.message,functionName:r.functionName}),{ok:!1,diagnostics:n};let o=G(t),s=t.strictConformance||o,i=F(r,{strictConformance:s});if(U(i))return n.errors.push({severity:"error",code:i.code??M.ERR_VALIDATION,message:i.message,functionName:i.functionName}),{ok:!1,diagnostics:n};if(t.mathExtension){let c=K(r,t.mathExtension);if(!c.valid){for(let u of c.errors)n.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:u.message,functionName:u.functionName});return{ok:!1,diagnostics:n}}}let a=q(i,t);return n.warnings.push(...a.diagnostics.warnings),n.errors.push(...a.diagnostics.errors),n.demotions.push(...a.diagnostics.demotions),n.featuresUsed=a.diagnostics.featuresUsed,n.errors.length>0?{ok:!1,diagnostics:n}:{ok:!0,diagnostics:n,module:i}}function Ae(e,t,n,r){let o=e;if(o=at(o,t,n,r),t.compilerMetadata&&(o=o.replace(/(\/\/ Generated: .*\n)/,`$1// Metadata: ${t.compilerMetadata}
|
|
3
|
+
`)),t.workgroupSize){let[s,i,a]=t.workgroupSize;o=o.replace(/@compute @workgroup_size\(\d+, \d+, \d+\)/g,`@compute @workgroup_size(${s}, ${i}, ${a})`)}return o}function at(e,t,n,r){if(t.stripComments||t.releaseMode)return e;let s=ce(n,t.sourceMapping);if(!s)return e;let i=s.generateHeaderComment(),a=i?e.replace(/(\/\/ Generated: .*\n)/,`$1${i}
|
|
4
|
+
`):e,c=0;return a=a.replace(/^fn ([A-Za-z_][A-Za-z0-9_]*)\(/gm,(u,p)=>{let d=r.functions[c],m=s.commentForFunction(d?.index??c,p);if(c+=1,!m)return u;let g=t.sourceMapping==="minimal"?"":`
|
|
5
|
+
// [WAT] rust backend instruction mapping`;return`${m}${g}
|
|
6
|
+
${u}`}),a}function hn(e,t={}){let n=P(e,t);if(!n.ok){let r=n.diagnostics.errors[0];throw S(r?.message??"Compilation failed",{functionName:r?.functionName,instructionName:r?.code,code:r?.code})}return n.wgsl}async function yn(e,t={}){let n=await ot(e,t);if(!n.ok){let r=n.diagnostics.errors[0];throw S(r?.message??"Compilation failed",{functionName:r?.functionName,instructionName:r?.code,code:r?.code})}return n.wgsl}function Ce(e,t){for(let n of e.warnings){let r=n.functionName?` (${n.functionName})`:"";console.error(`warning${r}: ${n.message}`)}if(t&&e.demotions.length>0){let n=new Map;for(let o of e.demotions)n.set(o.kind,(n.get(o.kind)??0)+1);let r=[...n.entries()].map(([o,s])=>`${o} (${s})`);console.error(`demotions: ${r.join(", ")}`)}}function mt(e,t){return new Promise(n=>{let r=ft(e,t,{stdio:["ignore","pipe","pipe"]}),o="",s="";r.stdout.on("data",i=>{o+=String(i)}),r.stderr.on("data",i=>{s+=String(i)}),r.on("close",i=>{n({success:i===0,stdout:o,stderr:s})}),r.on("error",i=>{n({success:!1,stdout:o,stderr:`${s}
|
|
7
|
+
${i.message}`})})})}async function nt(e,t={}){let{output:n,verbose:r=!1,keepWasm:o=!1,optimize:s=!1,denyF64Demotion:i=!1,allowI64Demotion:a=!1,warningsAsErrors:c=!1}=t;try{r&&console.log(`[1/4] Validating input file: ${e}`);let u=_e(e);if(!(await Me(u)).isFile())throw new Error(`Not a file: ${e}`);let d=u.endsWith(".wasm");!d&&!u.endsWith(".as")&&!u.endsWith(".ts")&&console.warn("Warning: Input file does not have .as, .ts, or .wasm extension");let m=u.replace(/\.(as|ts)$/,".wasm");if(d)r&&console.log("[2/4] Input is WASM, skipping compilation..."),m=u;else{r&&console.log("[2/4] Compiling AssemblyScript to WASM...");let v=await gt(),{success:V,stdout:R,stderr:B}=await mt(v,[u,"-o",m]);if(!V)throw new Error(`AssemblyScript compilation failed:
|
|
8
|
+
${B}`);r&&R&&console.log(R)}r&&console.log("[3/4] Reading WASM binary...");let g=await ct(m);r&&(console.log(` WASM size: ${g.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let b={};i&&(b.f64="deny"),a&&(b.i64="allow-lossy");let I=P(g,{optimize:s,demotionPolicy:b,warningsAsErrors:c});if(Ce(I.diagnostics,r),!I.ok){let v=I.diagnostics.errors[0];throw new Error(v?.message??"Compilation failed")}let E=I.wgsl;if(n){let v=_e(n),V=pt(v);await dt(V,{recursive:!0}),await ut(v,E,"utf-8"),console.log(r?`
|
|
9
|
+
\u2713 Successfully compiled to: ${v}`:`\u2713 Compiled to: ${n}`)}if(!o&&!d)try{await lt(m),r&&console.log(" Cleaned up intermediate WASM file")}catch{}return E}catch(u){throw u instanceof Error?u:new Error(`Unknown error: ${String(u)}`)}}function rt(e,t={}){let{verbose:n=!1,optimize:r=!1,denyF64Demotion:o=!1,allowI64Demotion:s=!1,warningsAsErrors:i=!1}=t,a={};o&&(a.f64="deny"),s&&(a.i64="allow-lossy");let c=P(e,{optimize:r,demotionPolicy:a,warningsAsErrors:i});if(Ce(c.diagnostics,n),!c.ok){let u=c.diagnostics.errors[0];throw new Error(u?.message??"Compilation failed")}return c.wgsl}async function gt(){let e=["node_modules/.bin/asc","./examples/node_modules/.bin/asc","../app/node_modules/.bin/asc","./node_modules/assemblyscript/bin/asc.js"];for(let t of e)try{if((await Me(t)).isFile())return t}catch{}return"asc"}export{Qe as a,X as b,nt as c,rt as d,P as e,gn as f,ot as g,hn as h,yn as i};
|
package/dist/compiler.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a,d as b}from"./chunk-
|
|
1
|
+
import{c as a,d as b}from"./chunk-VSCQDCQR.js";import"./chunk-PS4NV6ZB.js";import"./chunk-IZGS3OS2.js";import"./chunk-STDXBN5E.js";export{a as compileAssemblyScriptToWGSL,b as compileWasmToWGSL};
|
|
@@ -75,11 +75,18 @@ interface CompileError extends Error {
|
|
|
75
75
|
functionName?: string;
|
|
76
76
|
instructionName?: string;
|
|
77
77
|
offset?: number;
|
|
78
|
+
/**
|
|
79
|
+
* Stable Appendix B error code (e.g. "ERR_MEMORY_COUNT"). Optional for
|
|
80
|
+
* backwards compatibility; v0.2 validation paths SHOULD populate this so
|
|
81
|
+
* `compileWithDiagnostics` can surface it to callers.
|
|
82
|
+
*/
|
|
83
|
+
code?: string;
|
|
78
84
|
}
|
|
79
85
|
declare function createCompileError(message: string, context?: {
|
|
80
86
|
functionName?: string;
|
|
81
87
|
instructionName?: string;
|
|
82
88
|
offset?: number;
|
|
89
|
+
code?: string;
|
|
83
90
|
}): CompileError;
|
|
84
91
|
declare function isCompileError$1(error: unknown): error is CompileError;
|
|
85
92
|
/** Custom section from WebAssembly module */
|
|
@@ -296,6 +303,19 @@ interface DemotionPolicy {
|
|
|
296
303
|
f64: DemotionPolicyDecision;
|
|
297
304
|
i64: I64DemotionPolicyDecision;
|
|
298
305
|
}
|
|
306
|
+
/**
|
|
307
|
+
* Supported Gasm specification versions.
|
|
308
|
+
*
|
|
309
|
+
* - "0.1": Default, current behavior. See spec/gasm-v0.1.md.
|
|
310
|
+
* - "0.2": Opt-in v0.2 mode. See spec/gasm-v0.2.md. Until the v0.2
|
|
311
|
+
* conformance suite is complete, v0.2 mode is opt-in and existing
|
|
312
|
+
* compile() defaults preserve v0.1 behavior.
|
|
313
|
+
*/
|
|
314
|
+
type SpecVersion = "0.1" | "0.2";
|
|
315
|
+
declare const SPEC_VERSION_V01: SpecVersion;
|
|
316
|
+
declare const SPEC_VERSION_V02: SpecVersion;
|
|
317
|
+
declare function resolveSpecVersion(options?: CompileOptions): SpecVersion;
|
|
318
|
+
declare function isV02Mode(options?: CompileOptions): boolean;
|
|
299
319
|
interface CompileOptions {
|
|
300
320
|
workgroupSize?: [number, number, number];
|
|
301
321
|
optimize?: boolean;
|
|
@@ -354,6 +374,18 @@ interface CompileOptions {
|
|
|
354
374
|
* Default: false (lenient — only instruction-level checks)
|
|
355
375
|
*/
|
|
356
376
|
strictConformance?: boolean;
|
|
377
|
+
/**
|
|
378
|
+
* Target Gasm specification version.
|
|
379
|
+
*
|
|
380
|
+
* - "0.1" (default): Current v0.1 behavior is preserved for existing callers.
|
|
381
|
+
* - "0.2": Opt into v0.2 strict validation and lowering. Until the v0.2
|
|
382
|
+
* conformance suite is complete, this mode is intentionally opt-in.
|
|
383
|
+
*
|
|
384
|
+
* Setting this to "0.2" implicitly activates strict conformance and any
|
|
385
|
+
* additional v0.2-only rules added in subsequent PRs. The default WGSL
|
|
386
|
+
* header is NOT changed by this flag in PR-0.
|
|
387
|
+
*/
|
|
388
|
+
specVersion?: SpecVersion;
|
|
357
389
|
}
|
|
358
390
|
type DiagnosticSeverity = "warning" | "error";
|
|
359
391
|
interface Diagnostic {
|
|
@@ -387,4 +419,49 @@ interface CompileDiagnostics {
|
|
|
387
419
|
declare function compile(wasmBytes: Uint8Array): WasmModule | ReturnType<typeof createCompileError>;
|
|
388
420
|
declare function isCompileError(error: unknown): error is ReturnType<typeof createCompileError>;
|
|
389
421
|
|
|
390
|
-
|
|
422
|
+
/**
|
|
423
|
+
* Stable Appendix B error codes for the Gasm specification.
|
|
424
|
+
*
|
|
425
|
+
* These codes are intentionally a string union rather than a TypeScript
|
|
426
|
+
* `enum` so they can be inserted directly into `Diagnostic.code` and
|
|
427
|
+
* compared from tests as plain strings. The accompanying spec sections
|
|
428
|
+
* are referenced in `spec/gasm-v0.2.md` Appendix B and Section 10.
|
|
429
|
+
*
|
|
430
|
+
* PR-0 introduces this module so later PRs can attach exact codes to
|
|
431
|
+
* diagnostics without changing the public API again.
|
|
432
|
+
*/
|
|
433
|
+
declare const ErrorCodes: {
|
|
434
|
+
readonly ERR_MEMORY_COUNT: "ERR_MEMORY_COUNT";
|
|
435
|
+
readonly ERR_MEMORY_GROW: "ERR_MEMORY_GROW";
|
|
436
|
+
readonly ERR_TABLE_PRESENT: "ERR_TABLE_PRESENT";
|
|
437
|
+
readonly ERR_INDIRECT_CALL: "ERR_INDIRECT_CALL";
|
|
438
|
+
readonly ERR_START_FUNCTION: "ERR_START_FUNCTION";
|
|
439
|
+
readonly ERR_FUNCTION_IMPORT: "ERR_FUNCTION_IMPORT";
|
|
440
|
+
readonly ERR_NO_ENTRY_POINT: "ERR_NO_ENTRY_POINT";
|
|
441
|
+
readonly ERR_MUTABLE_GLOBAL: "ERR_MUTABLE_GLOBAL";
|
|
442
|
+
readonly ERR_MULTI_MEMORY: "ERR_MULTI_MEMORY";
|
|
443
|
+
readonly ERR_PASSIVE_SEGMENT: "ERR_PASSIVE_SEGMENT";
|
|
444
|
+
readonly ERR_WORKGROUP_MEMORY_SIZE: "ERR_WORKGROUP_MEMORY_SIZE";
|
|
445
|
+
readonly ERR_RECURSION: "ERR_RECURSION";
|
|
446
|
+
readonly ERR_NON_UNIFORM_BARRIER: "ERR_NON_UNIFORM_BARRIER";
|
|
447
|
+
readonly ERR_UNALIGNED_ACCESS: "ERR_UNALIGNED_ACCESS";
|
|
448
|
+
readonly ERR_OFFSET_OVERFLOW: "ERR_OFFSET_OVERFLOW";
|
|
449
|
+
readonly ERR_FUNCREF: "ERR_FUNCREF";
|
|
450
|
+
readonly ERR_EXTERNREF: "ERR_EXTERNREF";
|
|
451
|
+
readonly ERR_F64_DEMOTION_REQUIRED: "ERR_F64_DEMOTION_REQUIRED";
|
|
452
|
+
readonly ERR_ATOMIC_REGION_MISSING: "ERR_ATOMIC_REGION_MISSING";
|
|
453
|
+
readonly ERR_ATOMIC_REGION_UNALIGNED: "ERR_ATOMIC_REGION_UNALIGNED";
|
|
454
|
+
readonly ERR_ATOMIC_REGION_OVERFLOW: "ERR_ATOMIC_REGION_OVERFLOW";
|
|
455
|
+
readonly ERR_ATOMIC_REGION_UNKNOWN_ADDRESS: "ERR_ATOMIC_REGION_UNKNOWN_ADDRESS";
|
|
456
|
+
readonly ERR_UNSUPPORTED_INSTR: "ERR_UNSUPPORTED_INSTR";
|
|
457
|
+
readonly ERR_UNKNOWN_EXTENSION: "ERR_UNKNOWN_EXTENSION";
|
|
458
|
+
readonly ERR_DUPLICATE_EXTENSION: "ERR_DUPLICATE_EXTENSION";
|
|
459
|
+
readonly ERR_DUPLICATE_CUSTOM_SECTION: "ERR_DUPLICATE_CUSTOM_SECTION";
|
|
460
|
+
readonly ERR_DUPLICATE_WORKGROUP_SIZE: "ERR_DUPLICATE_WORKGROUP_SIZE";
|
|
461
|
+
readonly ERR_METADATA_SCHEMA: "ERR_METADATA_SCHEMA";
|
|
462
|
+
readonly ERR_PARSE: "ERR_PARSE";
|
|
463
|
+
readonly ERR_VALIDATION: "ERR_VALIDATION";
|
|
464
|
+
};
|
|
465
|
+
type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes];
|
|
466
|
+
|
|
467
|
+
export { type CompileDiagnostics as C, type DispatchInfo as D, ErrorCodes as E, type MathIntrinsicSpec as M, type SpecVersion as S, type VectorDimension as V, type WasmModule as W, type CompileOptions as a, type CompileError as b, SPEC_VERSION_V01 as c, SPEC_VERSION_V02 as d, isCompileError$1 as e, compile as f, isCompileError as g, type ErrorCode as h, isV02Mode as i, type MathLevel as j, getIntrinsicsAtLevel as k, getMathSpec as l, getVectorDimension as m, getWgslMapping as n, isMathIntrinsic as o, MATH_INTRINSICS as p, type DebugInfo as q, resolveSpecVersion as r, type SourceLanguage as s, type SourceMappingLevel as t, detectSourceLanguage as u, extractDebugInfo as v, parseNamesSection as w, parseProducersSection as x };
|
|
Binary file
|
package/dist/mod.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { W as WasmModule, C as CompileDiagnostics, D as DispatchInfo, a as CompileOptions } from './
|
|
2
|
-
export { b as CompileError,
|
|
1
|
+
import { W as WasmModule, C as CompileDiagnostics, D as DispatchInfo, a as CompileOptions } from './error_codes-D6RsiZ33.js';
|
|
2
|
+
export { b as CompileError, q as DebugInfo, h as ErrorCode, E as ErrorCodes, p as MATH_INTRINSICS, M as MathIntrinsicSpec, j as MathLevel, c as SPEC_VERSION_V01, d as SPEC_VERSION_V02, s as SourceLanguage, t as SourceMappingLevel, S as SpecVersion, V as VectorDimension, u as detectSourceLanguage, v as extractDebugInfo, k as getIntrinsicsAtLevel, l as getMathSpec, m as getVectorDimension, n as getWgslMapping, e as isCompileError, o as isMathIntrinsic, g as isParseError, i as isV02Mode, w as parseNamesSection, x as parseProducersSection, f as parseWasmModule, r as resolveSpecVersion } from './error_codes-D6RsiZ33.js';
|
|
3
3
|
import { IGPUExecutor, ExecutorConfig, BufferData, ExecuteOptions } from './executor.js';
|
|
4
4
|
export { ExecutionError, OutputBufferSpec, isExecutionError } from './executor.js';
|
|
5
5
|
export { BrowserGPUExecutor } from './browser-executor.js';
|
|
@@ -86,6 +86,9 @@ type CompileWithDiagnosticsResult = {
|
|
|
86
86
|
diagnostics: CompileDiagnostics;
|
|
87
87
|
};
|
|
88
88
|
declare function compileWithDiagnostics(wasmBytes: Uint8Array, options?: CompileOptions): CompileWithDiagnosticsResult;
|
|
89
|
+
declare function preloadCompiler(): Promise<void>;
|
|
90
|
+
declare function compileWithDiagnosticsAsync(wasmBytes: Uint8Array, options?: CompileOptions): Promise<CompileWithDiagnosticsResult>;
|
|
89
91
|
declare function compile(wasmBytes: Uint8Array, options?: CompileOptions): string;
|
|
92
|
+
declare function compileAsync(wasmBytes: Uint8Array, options?: CompileOptions): Promise<string>;
|
|
90
93
|
|
|
91
|
-
export { BufferData, CompileDiagnostics, CompileOptions, type CompileWithDiagnosticsResult, DenoGPUExecutor, DispatchInfo, ExecuteOptions, ExecutorConfig, IGPUExecutor, compile, compileWithDiagnostics, disassembleToWAT };
|
|
94
|
+
export { BufferData, CompileDiagnostics, CompileOptions, type CompileWithDiagnosticsResult, DenoGPUExecutor, DispatchInfo, ExecuteOptions, ExecutorConfig, IGPUExecutor, compile, compileAsync, compileWithDiagnostics, compileWithDiagnosticsAsync, disassembleToWAT, preloadCompiler };
|
package/dist/mod.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as s,b as w,c as x,d as y,e as z,f as A,g as B,h as C,i as D}from"./chunk-VSCQDCQR.js";import{D as o,E as p,F as q,G as r,b as a,d as b,e as c,f as d,i as e,j as f,k as g,l as h,m as i,o as j,u as k,v as l,w as m,x as n}from"./chunk-PS4NV6ZB.js";import{a as v}from"./chunk-IZGS3OS2.js";import{a as t,b as u}from"./chunk-STDXBN5E.js";export{v as BrowserGPUExecutor,w as DenoGPUExecutor,d as ErrorCodes,t as ExecutionError,e as MATH_INTRINSICS,o as SPEC_VERSION_V01,p as SPEC_VERSION_V02,C as compile,x as compileAssemblyScriptToWGSL,D as compileAsync,y as compileWasmToWGSL,z as compileWithDiagnostics,B as compileWithDiagnosticsAsync,m as detectSourceLanguage,s as disassembleToWAT,n as extractDebugInfo,j as getIntrinsicsAtLevel,g as getMathSpec,i as getVectorDimension,h as getWgslMapping,a as isCompileError,u as isExecutionError,f as isMathIntrinsic,c as isParseError,r as isV02Mode,k as parseNamesSection,l as parseProducersSection,b as parseWasmModule,A as preloadCompiler,q as resolveSpecVersion};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gasm-compiler/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Gasm Compiler — compile WebAssembly to WGSL (WebGPU Shading Language)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/mod.js",
|
|
@@ -8,8 +8,11 @@
|
|
|
8
8
|
"browser": "./dist/browser.js",
|
|
9
9
|
"exports": {
|
|
10
10
|
".": {
|
|
11
|
+
"browser": {
|
|
12
|
+
"types": "./dist/browser.d.ts",
|
|
13
|
+
"default": "./dist/browser.js"
|
|
14
|
+
},
|
|
11
15
|
"types": "./dist/mod.d.ts",
|
|
12
|
-
"browser": "./dist/browser.js",
|
|
13
16
|
"import": "./dist/mod.js",
|
|
14
17
|
"default": "./dist/mod.js"
|
|
15
18
|
},
|
|
@@ -64,10 +67,12 @@
|
|
|
64
67
|
"typescript": "^5.9.3"
|
|
65
68
|
},
|
|
66
69
|
"scripts": {
|
|
67
|
-
"build": "tsup",
|
|
68
|
-
"test": "deno test --allow-all",
|
|
70
|
+
"build": "pnpm --dir ../.. core-rs:build:wasm:release && deno run --allow-read --allow-write ../../scripts/generate_core_rs_wasm_embed.ts --release && tsup && deno run --allow-read --allow-write ../../scripts/fix_node_builtin_imports.ts && deno run --allow-read --allow-write --allow-run --allow-env ../../scripts/copy_core_rs_wasm.ts --release",
|
|
71
|
+
"test": "pnpm --dir ../.. core-rs:build:wasm && GASM_CORE_BACKEND=rust deno test --allow-all",
|
|
69
72
|
"test:e2e": "deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
|
|
70
73
|
"test:e2e:gpu": "ENABLE_GPU_TESTS=1 deno test --allow-all --unstable-webgpu --no-check tests/e2e_execution_test.ts",
|
|
71
|
-
"lint": "biome lint ."
|
|
74
|
+
"lint": "biome lint .",
|
|
75
|
+
"size": "pnpm --dir ../.. core-rs:size",
|
|
76
|
+
"pack:smoke": "pnpm --dir ../.. core-rs:pack-smoke"
|
|
72
77
|
}
|
|
73
78
|
}
|
package/dist/chunk-3GAG34KX.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{A as ee,B as te,C as ne,a as w,c as q,d as P,e as D,f as U,g as N,i as z,j as W,m as R,o as j,p as H,q as J,r as K,s as Q,x as X,y as Y,z as Z}from"./chunk-OJJM3SJ5.js";import{a as g}from"./chunk-STDXBN5E.js";import{resolve as de}from"path";import{stat as fe,readFile as De,writeFile as ze,unlink as We,mkdir as Ge}from"fs/promises";import{spawn as Te}from"child_process";import{dirname as qe}from"path";function re(e){let r=e.functions.map(n=>!("parallelLoopInfo"in n)||!n.parallelLoopInfo?n:he(n));return{...e,functions:r}}function he(e){let r=e.parallelLoopInfo.loopLocalIndex,{writes:n}=ge(e.body,r);if(n>0){let t=$(e.body,r);return{...e,body:t}}return e}function ge(e,r){let n=0,t=0;function o(s){switch(s.kind){case"simple":if(s.instructions)for(let i of s.instructions)i.opcode==="local.get"&&i.immediates?.[0]===r&&n++,(i.opcode==="local.set"||i.opcode==="local.tee")&&i.immediates?.[0]===r&&t++;break;case"block":for(let i of s.children)o(i);break;case"loop":o(s.body);break;case"if":o(s.thenBranch),s.elseBranch&&o(s.elseBranch);break;case"parallel_loop":o(s.body),s.epilogue&&o(s.epilogue);break;case"return":case"break":case"continue":break}}return o(e),{reads:n,writes:t}}function $(e,r){switch(e.kind){case"simple":{if(!e.instructions)return e;let n=e.instructions.filter(t=>!((t.opcode==="local.set"||t.opcode==="local.tee")&&t.immediates?.[0]===r));return n.length===0?{kind:"block",children:[]}:{...e,instructions:n}}case"block":{let n=e.children.map(t=>$(t,r)).filter(t=>!ye(t));return{...e,children:n}}case"loop":return{...e,body:$(e.body,r)};case"if":return{...e,thenBranch:$(e.thenBranch,r),elseBranch:e.elseBranch?$(e.elseBranch,r):void 0};case"parallel_loop":return{...e,body:$(e.body,r),epilogue:e.epilogue?$(e.epilogue,r):void 0};case"return":case"break":case"continue":return e}}function ye(e){return e.kind==="block"&&e.children.length===0||e.kind==="simple"&&(!e.instructions||e.instructions.length===0)}function oe(e){let r=e.functions.map(n=>be(n));return{...e,functions:r}}function be(e){let r=k(e.body,e);return{...e,body:r}}function k(e,r){switch(e.kind){case"loop":{let n=Se(e.body),t=[],o=ie(e.body,n,t,r);return t.length===0?{...e,body:k(e.body,r)}:{kind:"block",children:[{kind:"simple",instructions:t},{...e,body:k(o,r)}],label:void 0}}case"block":return{...e,children:e.children.map(n=>k(n,r))};case"if":return{...e,thenBranch:k(e.thenBranch,r),elseBranch:e.elseBranch?k(e.elseBranch,r):void 0};case"simple":return e;default:return e}}function Se(e){let r=new Set;function n(t){if(t.kind==="simple"&&t.instructions){for(let o of t.instructions)if(o.id!==void 0&&r.add(o.id),(o.opcode==="local.set"||o.opcode==="local.tee")&&o.immediates){let s=o.immediates[0];r.add(-s-1)}}t.kind==="block"&&t.children.forEach(n),t.kind==="loop"&&n(t.body),t.kind==="if"&&(n(t.thenBranch),t.elseBranch&&n(t.elseBranch))}return n(e),r}function ie(e,r,n,t){switch(e.kind){case"simple":{if(!e.instructions||e.instructions.length===0)return e;let o=[],s=new Set;for(let i of e.instructions)we(i,r,s)?(n.push(i),i.id!==void 0&&s.add(i.id)):(o.push(i),i.id!==void 0&&s.add(i.id));return{...e,instructions:o}}case"block":{let o=e.children.map(s=>ie(s,r,n,t));return{...e,children:o}}case"loop":return e;case"if":return e;default:return e}}function we(e,r,n){if(!Ie(e.opcode))return!1;if(e.opcode==="local.get"&&e.immediates){let o=-e.immediates[0]-1;if(r.has(o))return!1}if(e.args){for(let t of e.args)if(r.has(t))return!1}return!0}function Ie(e){return new Set(["i32.const","i64.const","f32.const","f64.const","local.get","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","f32.add","f32.sub","f32.mul","f32.div","f64.add","f64.sub","f64.mul","f64.div","i32.and","i32.or","i32.xor","i32.shl","i32.shr_s","i32.shr_u","i32.rotl","i32.rotr","i64.and","i64.or","i64.xor","i64.shl","i64.shr_s","i64.shr_u","i64.rotl","i64.rotr","i32.eqz","i32.eq","i32.ne","i32.lt_s","i32.lt_u","i32.gt_s","i32.gt_u","i32.le_s","i32.le_u","i32.ge_s","i32.ge_u","i64.eqz","i64.eq","i64.ne","i64.lt_s","i64.lt_u","i64.gt_s","i64.gt_u","i64.le_s","i64.le_u","i64.ge_s","i64.ge_u","f32.eq","f32.ne","f32.lt","f32.gt","f32.le","f32.ge","f64.eq","f64.ne","f64.lt","f64.gt","f64.le","f64.ge","i32.wrap_i64","i64.extend_i32_s","i64.extend_i32_u","f32.convert_i32_s","f32.convert_i32_u","f32.convert_i64_s","f32.convert_i64_u","f32.demote_f64","f64.convert_i32_s","f64.convert_i32_u","f64.convert_i64_s","f64.convert_i64_u","f64.promote_f32","i32.reinterpret_f32","i64.reinterpret_f64","f32.reinterpret_i32","f64.reinterpret_i64","i32.clz","i32.ctz","i32.popcnt","i64.clz","i64.ctz","i64.popcnt","f32.abs","f32.neg","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f64.abs","f64.neg","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f32.min","f32.max","f32.copysign","f64.min","f64.max","f64.copysign"]).has(e)}function se(e){for(let r of e.functions)ve(r);return e}function ve(e){x(e.body,e)}function x(e,r){switch(e.kind){case"simple":$e(e,r);break;case"block":for(let n of e.children)x(n,r);break;case"loop":x(e.body,r);break;case"if":x(e.thenBranch,r),e.elseBranch&&x(e.elseBranch,r);break;case"parallel_loop":x(e.body,r),e.epilogue&&x(e.epilogue,r);break}}function $e(e,r){let n=_e(e.instructions,r);n.length>0&&ke(e,r,n);let t=Ae(e.instructions,r);t.length>0&&Ee(e,r,t)}function ae(e,r){let n=O(e,r);if(!n)return null;if(n.opcode==="i32.shr_u"&&n.args.length===2){if(L(n.args[1],r)!==2)return null;let o=n.args[0];return xe(o,r)}return Me(e,r)}function xe(e,r){let n=O(e,r);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let t=L(n.args[1],r);if(t!==null&&t>=0&&t%4===0)return{baseVar:n.args[0],wordOffset:t/4};let o=L(n.args[0],r);return o!==null&&o>=0&&o%4===0?{baseVar:n.args[1],wordOffset:o/4}:null}return{baseVar:e,wordOffset:0}}function Me(e,r){let n=O(e,r);if(!n)return{baseVar:e,wordOffset:0};if(n.opcode==="i32.add"&&n.args.length===2){let t=L(n.args[1],r);if(t!==null&&t>=0)return{baseVar:n.args[0],wordOffset:t}}return{baseVar:e,wordOffset:0}}function O(e,r){if(r.inlinedExpressionMap){let n=r.inlinedExpressionMap.get(e);if(n)return n}return M(r.body,e)}function M(e,r){switch(e.kind){case"simple":for(let n of e.instructions)if(n.id===r)return n;return null;case"block":for(let n of e.children){let t=M(n,r);if(t)return t}return null;case"loop":return M(e.body,r);case"if":{let n=M(e.thenBranch,r);return n||(e.elseBranch?M(e.elseBranch,r):null)}case"parallel_loop":{let n=M(e.body,r);return n||(e.epilogue?M(e.epilogue,r):null)}default:return null}}function L(e,r){let n=O(e,r);return n&&n.opcode==="i32.const"&&n.immediates&&n.immediates.length>0?n.immediates[0]:null}function _e(e,r){let n=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.store_f32"&&i.args.length===2){let a=ae(i.args[0],r);a&&t.push({index:s,addr:a,valueArg:i.args[1]})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(h=>h.index);ce(m,e)&&n.push({instrIndices:m,baseVar:s,valueArgs:d.map(h=>h.valueArg),components:p})}a=c+1}}return n}function Ae(e,r){let n=[],t=[];for(let s=0;s<e.length;s++){let i=e[s];if(i.opcode==="wgsl.load_f32"&&i.args.length===1&&i.id!==void 0){let a=ae(i.args[0],r);a&&t.push({index:s,addr:a,resultVar:i.id})}}let o=new Map;for(let s of t){let i=o.get(s.addr.baseVar)||[];i.push(s),o.set(s.addr.baseVar,i)}for(let[s,i]of o){if(i.length<3)continue;i.sort((c,u)=>c.addr.wordOffset-u.addr.wordOffset);let a=0;for(;a<i.length;){let c=a;for(;c+1<i.length&&i[c+1].addr.wordOffset===i[c].addr.wordOffset+1;)c++;let u=c-a+1;if(u>=3){let p=u>=4?4:3,d=i.slice(a,a+p),m=d.map(h=>h.index);ce(m,e)&&n.push({instrIndices:m,baseVar:s,resultVars:d.map(h=>h.resultVar),components:p})}a=c+1}}return n}function ce(e,r){if(e.length<3)return!1;let n=Math.min(...e),t=Math.max(...e),o=e.length*4;if(t-n>=o)return!1;for(let s=n;s<=t;s++)if(r[s].opcode.startsWith("wgsl.store")&&!e.includes(s))return!1;return!0}function ke(e,r,n){n.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of n){let o=t.components===4?"wgsl.store_vec4f":"wgsl.store_vec3f",s=e.instructions[t.instrIndices[0]].args[0],i={type:"instr",opcode:o,args:[s,...t.valueArgs],synthetic:!0},a=[...t.instrIndices].sort((c,u)=>c-u);for(let c=a.length-1;c>=0;c--)e.instructions.splice(a[c],1);e.instructions.splice(a[0],0,i)}}function Ee(e,r,n){n.sort((t,o)=>o.instrIndices[0]-t.instrIndices[0]);for(let t of n){let o=t.components===4?"wgsl.load_vec4f":"wgsl.load_vec3f",s=0;for(let d of r.vars.keys())d>s&&(s=d);let i=s+1;r.vars.set(i,{id:i,type:"v128"});let a=e.instructions[t.instrIndices[0]].args[0],c={type:"instr",id:i,opcode:o,args:[a],synthetic:!0},u=t.resultVars.map((d,m)=>({type:"instr",id:d,opcode:"wgsl.extract_f32",args:[i],immediates:[m],synthetic:!0})),p=[...t.instrIndices].sort((d,m)=>d-m);for(let d=p.length-1;d>=0;d--)e.instructions.splice(p[d],1);e.instructions.splice(p[0],0,c,...u)}}function ue(e,r){let n={valid:!0,mathImports:[],errors:[],requiredLevel:null},t=r===!0||r==="M0"||r==="M1"||r==="M2",o=r===!0?"M2":r==="M0"||r==="M1"||r==="M2"?r:null,s=["M0","M1","M2"],i=0;for(let a of e.imports){if(a.kind!=="func")continue;let c=i++;if(!z(a.module,a.name))continue;let u=a.typeIndex;if(u===void 0){n.errors.push(w(`Math import ${a.name} has no type index`,{functionName:a.name})),n.valid=!1;continue}let p=e.types[u];if(!p){n.errors.push(w(`Math import ${a.name} references invalid type index ${u}`,{functionName:a.name})),n.valid=!1;continue}let d=W(a.name);if(!d){n.errors.push(w(`Unknown math intrinsic: ${a.name}`,{functionName:a.name})),n.valid=!1;continue}let m={funcIndex:c,module:a.module,name:a.name,level:d.level,params:p.params,results:p.results};if(n.mathImports.push(m),(n.requiredLevel===null||s.indexOf(d.level)>s.indexOf(n.requiredLevel))&&(n.requiredLevel=d.level),!t){n.errors.push(w(`Math intrinsic ${a.name} requires mathExtension option to be enabled`,{functionName:a.name})),n.valid=!1;continue}if(o&&!R(a.name,o)){n.errors.push(w(`Math intrinsic ${a.name} requires level ${d.level}, but only ${o} is enabled`,{functionName:a.name})),n.valid=!1;continue}let h=j(a.name,p.params,p.results);h&&(n.errors.push(w(h,{functionName:a.name})),n.valid=!1)}return n}var le={};for(let[e,r]of Object.entries(q))le[r]=e.replace(/_/g,".");function Ve(e){let r=[];r.push("(module");for(let t of e.memories)r.push(` (memory ${t.min}${t.max!==void 0?` ${t.max}`:""})`);for(let t of e.imports)if(t.kind==="func"&&t.typeIndex!==void 0){let o=e.types[t.typeIndex];if(o){let s=o.params.map((a,c)=>`(param $${c} ${a})`).join(" "),i=o.results.map(a=>`(result ${a})`).join(" ");r.push(` (import "${t.module}" "${t.name}" (func ${s}${i?" "+i:""}))`)}}let n=new Set;for(let t of e.globals){if(t.kind==="import")continue;let o=t.mutable?"(mut ":"",s=t.mutable?")":"",i="";t.initValue!==void 0&&(t.type==="i32"||t.type==="i64"?i=`${t.type}.const ${t.initValue}`:(t.type==="f32"||t.type==="f64")&&(i=`${t.type}.const ${t.initValue}`)),r.push(` (global $${t.index} ${o}${t.type}${s} ${i?`(${i})`:""})`)}for(let t of e.data){let o=Array.from(t.data.slice(0,Math.min(32,t.data.length))).map(i=>`\\${i.toString(16).padStart(2,"0")}`).join(""),s=t.data.length>32?"...":"";r.push(` (data (i32.const ${t.memoryIndex}) "${o}${s}") ;; ${t.data.length} bytes`)}for(let t of e.functions)r.push(""),r.push(...Ce(t,e));if(e.exports.length>0){r.push("");for(let t of e.exports)t.kind==="func"?r.push(` (export "${t.name}" (func $${t.index}))`):t.kind==="mem"?r.push(` (export "${t.name}" (memory ${t.index}))`):t.kind==="global"&&r.push(` (export "${t.name}" (global ${t.index}))`)}return e.startFunctionIndex!==void 0&&r.push(` (start $${e.startFunctionIndex})`),r.push(")"),r.join(`
|
|
2
|
-
`)}function Ce(e,r){let n=[],t=e.params.map((i,a)=>`(param $${a} ${i})`).join(" "),o=e.results.map(i=>`(result ${i})`).join(" ");if(n.push(` (func $${e.index} ${t}${o?" "+o:""}`),e.locals.length>0){let i=new Map;for(let a of e.locals)i.set(a.type,(i.get(a.type)||0)+1);for(let[a,c]of i)n.push(` (local ${a} (;${c}x;))`)}let s=Be(e.body,2);return n.push(...s),n.push(" )"),n}function Be(e,r){let n=[],t=" ".repeat(r);for(let o of e){let s=Le(o,r);n.push(`${t}${s}`)}return n}function Le(e,r){if(!e||typeof e!="object")return";; Error: Invalid instruction";let{opcode:n,immediates:t}=e,o=le[n]||`unknown_0x${n.toString(16)}`;if(!t||t.length===0)return o;switch(o){case"local.get":case"local.set":case"local.tee":return`${o} $${t[0]}`;case"global.get":case"global.set":return`${o} $${t[0]}`;case"i32.const":case"i64.const":return`${o} ${t[0]}`;case"f32.const":case"f64.const":return`${o} ${t[0]}`;case"call":return`${o} $${t[0]}`;case"call_indirect":return`${o} (type ${t[0]})`;case"br":case"br_if":return`${o} ${t[0]}`;case"br_table":let s=t[0].join(" "),i=t[1];return`${o} ${s} ${i}`;case"if":case"block":case"loop":let a=t[0];return`${o} ${a!==void 0&&a!=="void"?`(result ${a})`:""}`;case"i32.load":case"i64.load":case"f32.load":case"f64.load":case"i32.load8_s":case"i32.load8_u":case"i32.load16_s":case"i32.load16_u":case"i64.load8_s":case"i64.load8_u":case"i64.load16_s":case"i64.load16_u":case"i64.load32_s":case"i64.load32_u":case"i32.store":case"i64.store":case"f32.store":case"f64.store":case"i32.store8":case"i32.store16":case"i64.store8":case"i64.store16":case"i64.store32":let c=t[0],u=t[1],p=[];return u!==0&&p.push(`offset=${u}`),c!==void 0&&p.push(`align=${1<<c}`),`${o}${p.length>0?" "+p.join(" "):""}`;case"memory.size":case"memory.grow":return o;default:if(o.startsWith("v128.")){if(o.includes("load")||o.includes("store")){let d=t[0],m=t[1],h=[];return m!==0&&h.push(`offset=${m}`),d!==void 0&&h.push(`align=${1<<d}`),`${o}${h.length>0?" "+h.join(" "):""}`}if(o.includes("const")){let d=t.join(" ");return`${o} ${d}`}return o.includes("extract_lane")||o.includes("replace_lane")?`${o} ${t[0]}`:`${o}${t.length>0?" "+t.join(" "):""}`}return`${o}${t.length>0?" "+t.join(" "):""}`}}var it=globalThis.gpu,Oe=globalThis.navigator?.gpu,G=class{constructor(r={}){this.config=r}device=null;queue=null;initialized=!1;buffers=new Map;async ensureInitialized(){if(!this.initialized)try{let r=await Oe?.requestAdapter?.();if(!r)throw new g("No GPU adapter available","compilation","navigator.gpu.requestAdapter() returned null");if(this.device=await r.requestDevice?.(),!this.device)throw new g("Failed to request GPU device","compilation","adapter.requestDevice() returned null");this.queue=this.device.queue,this.initialized=!0}catch(r){throw r instanceof g?r:new g(`GPU initialization failed: ${r instanceof Error?r.message:String(r)}`,"compilation",String(r))}}createBuffer(r,n,t){if(!this.device)throw new g("Device not initialized","binding","Call ensureInitialized() first");let o=this.device.createBuffer({label:r,size:n.byteLength,usage:t});return this.queue.writeBuffer(o,0,n.buffer,n.byteOffset,n.byteLength),o}async readBuffer(r,n,t){if(!this.device||!this.queue)throw new g("Device not initialized","readback","Call ensureInitialized() first");let o=Math.max(4,Math.ceil(n/4)*4),s=this.device.createBuffer({size:o,usage:9}),i=this.device.createCommandEncoder();i.copyBufferToBuffer(r,0,s,0,Math.min(n,o)),this.queue.submit([i.finish()]);try{await s.mapAsync(1)}catch(u){throw s.destroy(),new g(`Failed to map staging buffer: ${u instanceof Error?u.message:String(u)}`,"readback",String(u))}let a=s.getMappedRange(),c;return t==="f32"?c=new Float32Array(new Uint8Array(a).buffer).slice():t==="i32"?c=new Int32Array(new Uint8Array(a).buffer).slice():c=new Uint32Array(new Uint8Array(a).buffer).slice(),s.unmap(),s.destroy(),{data:c,type:t}}async execute(r,n,t,o={}){let s=o.workgroupSize??[1,1,1],i=o.workgroupCount??[1,1,1],a=o.timeout??5e3;if(await this.ensureInitialized(),!this.device||!this.queue)throw new g("Device initialization failed","compilation");try{let c;try{let l=o.shaderLabel||"Gasm Compiler Compute Shader";c=this.device.createShaderModule({code:r,label:l});let f=await c.getCompilationInfo?.();if(f&&f.messages.length>0){let y=f.messages.filter(b=>b.type==="error");if(y.length>0){let b=y.map(I=>`${I.message} at ${I.lineNum}:${I.linePos}`).join("; ");throw new g(`WGSL compilation failed: ${b}`,"compilation")}}}catch(l){throw l instanceof g?l:new g(`Failed to create shader module: ${l instanceof Error?l.message:String(l)}`,"compilation",String(l))}let u=[],p=0,d=new Map,m=Object.entries(n).sort((l,f)=>l[0]==="memory"?-1:f[0]==="memory"?1:l[0].localeCompare(f[0]));for(let[l,{data:f,type:y}]of m){let b=this.createBuffer(`input_${l}`,f,140);d.set(l,b),u.push({binding:p++,resource:{buffer:b}})}let h=new Map,v=new Map;for(let l of t){if(d.has(l)){let me=d.get(l),T=n[l];h.set(l,me),v.set(l,{size:T.data.byteLength,type:T.type});continue}let f=o.outputBuffers?.[l]??{type:"f32",size:1},y=f.size??1,b=y*4,I=this.device.createBuffer({label:`output_${l}`,size:b,usage:132}),A;f.type==="f32"?A=new Float32Array(y).fill(0):f.type==="i32"?A=new Int32Array(y).fill(0):A=new Uint32Array(y).fill(0),this.queue.writeBuffer(I,0,A.buffer,A.byteOffset,A.byteLength),h.set(l,I),v.set(l,{size:b,type:f.type}),u.push({binding:p++,resource:{buffer:I}})}let _=Object.keys(n).length,E=this.device.createBindGroupLayout({entries:u.map((l,f)=>{let y=f===0&&n.memory!==void 0,b=f>=_;return{binding:f,visibility:4,buffer:{type:!y&&!b?"read-only-storage":"storage"}}})}),S=this.device.createBindGroup({layout:E,entries:u}),V=this.device.createPipelineLayout({bindGroupLayouts:[E]}),C;try{C=this.device.createComputePipeline({layout:V,compute:{module:c,entryPoint:"main"}})}catch(l){throw new g(`Failed to create compute pipeline: ${l instanceof Error?l.message:String(l)}`,"binding",String(l))}try{let l=this.device.createCommandEncoder(),f=l.beginComputePass();f.setPipeline(C),f.setBindGroup(0,S),f.dispatchWorkgroups(i[0],i[1],i[2]),f.end(),this.queue.submit([l.finish()])}catch(l){throw new g(`Compute shader dispatch failed: ${l instanceof Error?l.message:String(l)}`,"dispatch",String(l))}let B={};try{for(let l of t){let f=h.get(l),y=v.get(l);if(!f||!y)throw new g(`Output buffer "${l}" not found`,"readback");B[l]=await this.readBuffer(f,y.size,y.type)}}catch(l){throw l instanceof g?l:new g(`Failed to read back results: ${l instanceof Error?l.message:String(l)}`,"readback",String(l))}finally{let l=new Set;d.forEach(f=>{f.destroy(),l.add(f)}),h.forEach(f=>{l.has(f)||f.destroy()})}return B}catch(c){throw c instanceof g?c:new g(`Unexpected error during execution: ${c instanceof Error?c.message:String(c)}`,"dispatch",String(c))}}async destroy(){this.buffers.forEach(r=>r.destroy()),this.buffers.clear(),this.device&&typeof this.device.destroy=="function"&&this.device.destroy(),this.device=null,this.queue=null,this.initialized=!1}};function F(e,r={}){let n=te(),t=P(e);if(D(t))return n.errors.push({severity:"error",code:"ERR_PARSE",message:t.message,functionName:t.functionName}),{ok:!1,diagnostics:n};let o=t,s=U(o,{strictConformance:r.strictConformance});if(N(s))return n.errors.push({severity:"error",code:"ERR_VALIDATION",message:s.message,functionName:s.functionName}),{ok:!1,diagnostics:n};let i=s;if(r.mathExtension){let m=ue(o,r.mathExtension);if(!m.valid){for(let h of m.errors)n.errors.push({severity:"error",code:"ERR_MATH_VALIDATION",message:h.message,functionName:h.functionName});return{ok:!1,diagnostics:n}}}let a=ne(i,r);if(n.warnings.push(...a.diagnostics.warnings),n.errors.push(...a.diagnostics.errors),n.demotions.push(...a.diagnostics.demotions),n.featuresUsed=a.diagnostics.featuresUsed,n.errors.length>0)return{ok:!1,diagnostics:n};let c=X(i);r.optimize!==!1&&(c=Z(c,{verbose:r.verbose??!1}));let u=ee(c);u=H(u),r.optimize!==!1&&(u=J(u)),r.vectorPromotion&&(u=se(u));let p=K();if(r.optimize!==!1){let m=Q(u);u=m.module,p=m.dispatchInfo,u=re(u),u=oe(u)}return{ok:!0,wgsl:Y(u,r,e,p),diagnostics:n,dispatchInfo:p}}function Lt(e,r={}){let n=F(e,r);if(!n.ok){let t=n.diagnostics.errors[0];throw w(t?.message??"Compilation failed",{functionName:t?.functionName,instructionName:t?.code})}return n.wgsl}function pe(e,r){for(let n of e.warnings){let t=n.functionName?` (${n.functionName})`:"";console.error(`warning${t}: ${n.message}`)}if(r&&e.demotions.length>0){let n=new Map;for(let o of e.demotions)n.set(o.kind,(n.get(o.kind)??0)+1);let t=[...n.entries()].map(([o,s])=>`${o} (${s})`);console.error(`demotions: ${t.join(", ")}`)}}function Ue(e,r){return new Promise(n=>{let t=Te(e,r,{stdio:["ignore","pipe","pipe"]}),o="",s="";t.stdout.on("data",i=>{o+=String(i)}),t.stderr.on("data",i=>{s+=String(i)}),t.on("close",i=>{n({success:i===0,stdout:o,stderr:s})}),t.on("error",i=>{n({success:!1,stdout:o,stderr:`${s}
|
|
3
|
-
${i.message}`})})})}async function Fe(e,r={}){let{output:n,verbose:t=!1,keepWasm:o=!1,optimize:s=!1,denyF64Demotion:i=!1,allowI64Demotion:a=!1,warningsAsErrors:c=!1}=r;try{t&&console.log(`[1/4] Validating input file: ${e}`);let u=de(e);if(!(await fe(u)).isFile())throw new Error(`Not a file: ${e}`);let d=u.endsWith(".wasm");!d&&!u.endsWith(".as")&&!u.endsWith(".ts")&&console.warn("Warning: Input file does not have .as, .ts, or .wasm extension");let m=u.replace(/\.(as|ts)$/,".wasm");if(d)t&&console.log("[2/4] Input is WASM, skipping compilation..."),m=u;else{t&&console.log("[2/4] Compiling AssemblyScript to WASM...");let S=await Ne(),{success:V,stdout:C,stderr:B}=await Ue(S,[u,"-o",m]);if(!V)throw new Error(`AssemblyScript compilation failed:
|
|
4
|
-
${B}`);t&&C&&console.log(C)}t&&console.log("[3/4] Reading WASM binary...");let h=await De(m);t&&(console.log(` WASM size: ${h.length} bytes`),console.log("[4/4] Compiling WASM to WGSL using Gasm..."));let v={};i&&(v.f64="deny"),a&&(v.i64="allow-lossy");let _=F(h,{optimize:s,demotionPolicy:v,warningsAsErrors:c});if(pe(_.diagnostics,t),!_.ok){let S=_.diagnostics.errors[0];throw new Error(S?.message??"Compilation failed")}let E=_.wgsl;if(n){let S=de(n),V=qe(S);await Ge(V,{recursive:!0}),await ze(S,E,"utf-8"),console.log(t?`
|
|
5
|
-
\u2713 Successfully compiled to: ${S}`:`\u2713 Compiled to: ${n}`)}if(!o&&!d)try{await We(m),t&&console.log(" Cleaned up intermediate WASM file")}catch{}return E}catch(u){throw u instanceof Error?u:new Error(`Unknown error: ${String(u)}`)}}function Pe(e,r={}){let{verbose:n=!1,optimize:t=!1,denyF64Demotion:o=!1,allowI64Demotion:s=!1,warningsAsErrors:i=!1}=r,a={};o&&(a.f64="deny"),s&&(a.i64="allow-lossy");let c=F(e,{optimize:t,demotionPolicy:a,warningsAsErrors:i});if(pe(c.diagnostics,n),!c.ok){let u=c.diagnostics.errors[0];throw new Error(u?.message??"Compilation failed")}return c.wgsl}async function Ne(){let e=["node_modules/.bin/asc","./examples/node_modules/.bin/asc","../app/node_modules/.bin/asc","./node_modules/assemblyscript/bin/asc.js"];for(let r of e)try{if((await fe(r)).isFile())return r}catch{}return"asc"}export{Ve as a,G as b,Fe as c,Pe as d,F as e,Lt as f};
|