assemblyscript
Version:
A TypeScript-like language for WebAssembly.
820 lines (735 loc) • 881 kB
JavaScript
/**
* @license
* The AssemblyScript frontend
* Copyright 2026 Daniel Wirtz / The AssemblyScript Authors
* SPDX-License-Identifier: Apache-2.0
*/
var se=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var fn=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}};var Q=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},ae=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ue(t))!Me.call(e,s)&&s!==n&&se(e,s,{get:()=>t[s],enumerable:!(i=Ne(t,s))||i.enumerable});return e},wn=(e,t,n)=>(ae(e,t,"default"),n&&ae(n,t,"default"));var le={};Q(le,{promises:()=>Pe});var Pe,ue=fn(()=>{"use strict";Pe={}});var fe={};Q(fe,{createRequire:()=>Ve});function Ve(){return function(t){throw new Error(`Cannot find module: '${t}'`)}}var ce=fn(()=>{"use strict"});var On={};Q(On,{argv:()=>Xe,cwd:()=>In,exit:()=>He,hrtime:()=>qe,platform:()=>je,umask:()=>Ge});function In(){return"."}function Ge(){return 0}function He(e=0){throw Error(`exit ${e}`)}function qe(e){var t=Ke.call(de),n=Math.floor(t*.001),i=Math.floor(t*1e6-n*1e9);return e&&(n-=e[0],i-=e[1],i<0&&(n--,i+=1e9)),[n,i]}var je,Xe,de,Ke,Ln=fn(()=>{"use strict";je="linux";Xe=[];de=globalThis.performance||{},Ke=de.now||function(){return new Date().getTime()}});var Rn={};Q(Rn,{basename:()=>Qe,delimiter:()=>it,dirname:()=>Je,extname:()=>nt,format:()=>et,isAbsolute:()=>Ye,join:()=>$e,normalize:()=>pe,parse:()=>tt,relative:()=>Ze,resolve:()=>cn,sep:()=>kn,win32:()=>rt});function V(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function xe(e,t){for(var n="",i=0,s=-1,o=0,u,f=0;f<=e.length;++f){if(f<e.length)u=e.charCodeAt(f);else{if(u===47)break;u=47}if(u===47){if(!(s===f-1||o===1))if(s!==f-1&&o===2){if(n.length<2||i!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var p=n.lastIndexOf("/");if(p!==n.length-1){p===-1?(n="",i=0):(n=n.slice(0,p),i=n.length-1-n.lastIndexOf("/")),s=f,o=0;continue}}else if(n.length===2||n.length===1){n="",i=0,s=f,o=0;continue}}t&&(n.length>0?n+="/..":n="..",i=2)}else n.length>0?n+="/"+e.slice(s+1,f):n=e.slice(s+1,f),i=f-s-1;s=f,o=0}else u===46&&o!==-1?++o:o=-1}return n}function We(e,t){var n=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+i:n+e+i:i}function cn(){for(var e="",t=!1,n,i=arguments.length-1;i>=-1&&!t;i--){var s;i>=0?s=arguments[i]:(n===void 0&&(n=In()),s=n),V(s),s.length!==0&&(e=s+"/"+e,t=s.charCodeAt(0)===47)}return e=xe(e,!t),t?e.length>0?"/"+e:"/":e.length>0?e:"."}function pe(e){if(V(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;return e=xe(e,!t),e.length===0&&!t&&(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e}function Ye(e){return V(e),e.length>0&&e.charCodeAt(0)===47}function $e(){if(arguments.length===0)return".";for(var e,t=0;t<arguments.length;++t){var n=arguments[t];V(n),n.length>0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":pe(e)}function Ze(e,t){if(V(e),V(t),e===t||(e=cn(e),t=cn(t),e===t))return"";if(e===".")return t;for(var n=1;n<e.length&&e.charCodeAt(n)===47;++n);for(var i=e.length,s=i-n,o=1;o<t.length&&t.charCodeAt(o)===47;++o);for(var u=t.length,f=u-o,p=s<f?s:f,b=-1,c=0;c<=p;++c){if(c===p){if(f>p){if(t.charCodeAt(o+c)===47)return t.slice(o+c+1);if(c===0)return t.slice(o+c)}else s>p&&(e.charCodeAt(n+c)===47?b=c:c===0&&(b=0));break}var h=e.charCodeAt(n+c),F=t.charCodeAt(o+c);if(h!==F)break;h===47&&(b=c)}var m="";for(c=n+b+1;c<=i;++c)(c===i||e.charCodeAt(c)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(o+b):(o+=b,t.charCodeAt(o)===47&&++o,t.slice(o))}function Je(e){if(V(e),e.length===0)return".";for(var t=e.charCodeAt(0),n=t===47,i=-1,s=!0,o=e.length-1;o>=1;--o)if(t=e.charCodeAt(o),t===47){if(!s){i=o;break}}else s=!1;return i===-1?n?"/":".":n&&i===1?"//":e.slice(0,i)}function Qe(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');V(e);var n=0,i=-1,s=!0,o;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var u=t.length-1,f=-1;for(o=e.length-1;o>=0;--o){var p=e.charCodeAt(o);if(p===47){if(!s){n=o+1;break}}else f===-1&&(s=!1,f=o+1),u>=0&&(p===t.charCodeAt(u)?--u===-1&&(i=o):(u=-1,i=f))}return n===i?i=f:i===-1&&(i=e.length),e.slice(n,i)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!s){n=o+1;break}}else i===-1&&(s=!1,i=o+1);return i===-1?"":e.slice(n,i)}}function nt(e){V(e);for(var t=-1,n=0,i=-1,s=!0,o=0,u=e.length-1;u>=0;--u){var f=e.charCodeAt(u);if(f===47){if(!s){n=u+1;break}continue}i===-1&&(s=!1,i=u+1),f===46?t===-1?t=u:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||i===-1||o===0||o===1&&t===i-1&&t===n+1?"":e.slice(t,i)}function et(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return We("/",e)}function tt(e){V(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),i=n===47,s;i?(t.root="/",s=1):s=0;for(var o=-1,u=0,f=-1,p=!0,b=e.length-1,c=0;b>=s;--b){if(n=e.charCodeAt(b),n===47){if(!p){u=b+1;break}continue}f===-1&&(p=!1,f=b+1),n===46?o===-1?o=b:c!==1&&(c=1):o!==-1&&(c=-1)}return o===-1||f===-1||c===0||c===1&&o===f-1&&o===u+1?f!==-1&&(u===0&&i?t.base=t.name=e.slice(1,f):t.base=t.name=e.slice(u,f)):(u===0&&i?(t.name=e.slice(1,o),t.base=e.slice(1,f)):(t.name=e.slice(u,o),t.base=e.slice(u,f)),t.ext=e.slice(o,f)),u>0?t.dir=e.slice(0,u-1):i&&(t.dir="/"),t}var kn,it,rt,Nn=fn(()=>{"use strict";Ln();kn="/",it=":",rt=null});var ge={};Q(ge,{pathToFileURL:()=>at});function ot(e){return e.replace(/%/g,"%25").replace(/\\/g,"%5C").replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/\t/g,"%09")}function at(e){let t=cn(e);e.charCodeAt(e.length-1)===47&&t[t.length-1]!==kn&&(t+="/");let n=new URL("file://");return n.pathname=ot(t),n}var he=fn(()=>{"use strict";Nn()});var Wn={};Q(Wn,{Stats:()=>Cn,checkDiagnostics:()=>Tn,compileString:()=>St,configToArguments:()=>qn,createMemoryStream:()=>Hn,default:()=>Wn,defaultOptimizeLevel:()=>Be,defaultShrinkLevel:()=>Se,definitionFiles:()=>Bt,libraryFiles:()=>G,libraryPrefix:()=>P,main:()=>De,options:()=>zt,tscOptions:()=>Dt,version:()=>Xn});var st=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",j,an,v,M,dn;st?(j=await import("fs"),an=await import("module"),v=await import("path"),M=globalThis.process,dn=await import("url")):(j=await Promise.resolve().then(()=>(ue(),le)),an=await Promise.resolve().then(()=>(ce(),fe)),v=await Promise.resolve().then(()=>(Nn(),Rn)),M=await Promise.resolve().then(()=>(Ln(),On)),dn=await Promise.resolve().then(()=>(he(),ge)));var En=typeof process<"u"&&process||{},lt=En.env&&"CI"in En.env,ut="\x1B[90m",ft="\x1B[91m",ct="\x1B[92m",dt="\x1B[93m",xt="\x1B[94m",pt="\x1B[95m",gt="\x1B[96m",ht="\x1B[97m",W="\x1B[0m",nn=class{constructor(t){this.stream=t,this.enabled=!!(this.stream&&this.stream.isTTY||lt)}gray(t){return this.enabled?ut+t+W:t}red(t){return this.enabled?ft+t+W:t}green(t){return this.enabled?ct+t+W:t}yellow(t){return this.enabled?dt+t+W:t}blue(t){return this.enabled?xt+t+W:t}magenta(t){return this.enabled?pt+t+W:t}cyan(t){return this.enabled?gt+t+W:t}white(t){return this.enabled?ht+t+W:t}},An=new nn(En.stdout),Ot=new nn(En.stderr);function mt(e){for(var t=0,n=0,i=e.length;n<i;++n){let s=e.charCodeAt(n);s<128?t+=1:s<2048?t+=2:(s&64512)===55296&&n+1<i&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3}return t}function bt(e,t,n){var i=n-t;if(i<1)return"";for(var s=null,o=[],u=0,f;t<n;)f=e[t++],f<128?o[u++]=f:f>191&&f<224?o[u++]=(f&31)<<6|e[t++]&63:f>239&&f<365?(f=((f&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[u++]=55296+(f>>10),o[u++]=56320+(f&1023)):o[u++]=(f&15)<<12|(e[t++]&63)<<6|e[t++]&63,u>=8192&&((s||(s=[])).push(String.fromCharCode(...o)),u=0);return s?(u&&s.push(String.fromCharCode(...o.slice(0,u))),s.join("")):String.fromCharCode(...o.slice(0,u))}function Ft(e,t,n){for(var i=n,s=0,o=e.length;s<o;++s){let u=e.charCodeAt(s),f;u<128?t[n++]=u:u<2048?(t[n++]=u>>6|192,t[n++]=u&63|128):(u&64512)===55296&&s+1<o&&((f=e.charCodeAt(s+1))&64512)===56320?(u=65536+((u&1023)<<10)+(f&1023),++s,t[n++]=u>>18|240,t[n++]=u>>12&63|128,t[n++]=u>>6&63|128,t[n++]=u&63|128):(t[n++]=u>>12|224,t[n++]=u>>6&63|128,t[n++]=u&63|128)}return n-i}var _n={length:mt,read:bt,write:Ft};var me=an.createRequire(import.meta.url);function Fe(e,t,n=!0){var i={},s=[],o=[],u=[],f={};Object.keys(t).forEach(c=>{if(!c.startsWith(" ")){var h=t[c];h.alias!=null&&(typeof h.alias=="string"?f[h.alias]=c:Array.isArray(h.alias)&&h.alias.forEach(F=>f[F]=c)),n&&h.default!=null&&(i[c]=h.default)}});for(var p=0,b=(e=e.slice()).length;p<b;++p){let c=e[p];if(c=="--"){++p;break}let h=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(c),F,m;if(h)t[c]?F=t[m=c]:h[1]!=null?(F=t[m=f[h[1].substring(1)]],F&&h[2]!=null&&(e[p--]=h[2])):h[3]!=null&&(F=t[m=h[3].substring(2)],F&&h[4]!=null&&(e[p--]=h[4]));else if(c.charCodeAt(0)==45)F=t[m=c];else{o.push(c);continue}if(F)if(F.value)Object.keys(F.value).forEach(r=>i[r]=F.value[r]);else if(F.type==null||F.type==="b")i[m]=!0;else if(p+1<e.length&&e[p+1].charCodeAt(0)!=45)switch(F.type){case"i":i[m]=parseInt(e[++p],10);break;case"I":i[m]=(i[m]||[]).concat(parseInt(e[++p],10));break;case"f":i[m]=parseFloat(e[++p]);break;case"F":i[m]=(i[m]||[]).concat(parseFloat(e[++p]));break;case"s":i[m]=String(e[++p]);break;case"S":i[m]=(i[m]||[]).concat(e[++p].split(","));break;default:s.push(c),--p}else switch(F.type){case"i":case"f":i[m]=F.default||0;break;case"s":i[m]=F.default||"";break;case"I":case"F":case"S":i[m]=F.default||[];break;default:s.push(c)}else s.push(c)}for(;p<b;)u.push(e[p++]);return n&&Mn(t,i),{options:i,unknown:s,arguments:o,trailing:u}}function ye(e,t){t||(t={});var n=t.indent||2,i=t.padding||24,s=t.eol||`
`,o={},u=[];Object.keys(e).forEach(b=>{var c=e[b];if(c.description!=null){for(var h="";h.length<n;)h+=" ";for(h+="--"+b,c.alias&&(h+=", -"+c.alias);h.length<i;)h+=" ";var F;!t.noCategories&&c.category?(F=o[c.category])||(o[c.category]=F=[]):F=u,Array.isArray(c.description)?F.push(h+c.description[0]+c.description.slice(1).map(m=>{for(let r=0;r<i;++r)m=" "+m;return s+m}).join("")):F.push(h+c.description)}});var f=[],p=!1;return Object.keys(o).forEach(b=>{p=!0,f.push(s+" "+An.gray(b)+s),f.push(o[b].join(s))}),p&&u.length&&f.push(s+" "+An.gray("Other")+s),f.push(u.join(s)),f.join(s)}function be(e,t){if(e!=null)switch(t){case void 0:case"b":return!!e;case"i":return Math.trunc(e)||0;case"f":return Number(e)||0;case"s":return e===!0?"":e===!1?null:String(e);case"I":return Array.isArray(e)||(e=[e]),e.map(n=>Math.trunc(n)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(n=>Number(n)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Un(e,t,n,i){let s={};for(let[o,{type:u,mutuallyExclusive:f,isPath:p,useNodeResolution:b,cliOnly:c}]of Object.entries(e)){let h=be(t[o],u),F=be(n[o],u);if(h==null){if(F!=null){if(c)continue;if(Array.isArray(F)){let m;p&&(F=F.map(r=>en(r,i,b))),f!=null&&(m=t[f])?s[o]=F.filter(r=>!m.includes(r)):s[o]=F.slice()}else p&&(F=en(F,i,b)),s[o]=F}}else if(F==null)Array.isArray(h)?s[o]=h.slice():s[o]=h;else if(Array.isArray(h)){if(c){s[o]=h.slice();continue}let m;p&&(F=F.map(r=>en(r,i,b))),f!=null&&(m=t[f])?s[o]=[...h,...F.filter(r=>!h.includes(r)&&!m.includes(r))]:s[o]=[...h,...F.filter(r=>!h.includes(r))]}else s[o]=h}return s}function yt(e){let t=v.parse(e);return t.root||(t.root="./"),v.format(t)}function en(e,t,n=!1){return v.isAbsolute(e)?e:n&&!e.startsWith(".")&&me.resolve?me.resolve(e,{paths:[t]}):yt(v.join(t,e))}function Mn(e,t){for(let[n,{default:i}]of Object.entries(e))t[n]==null&&i!=null&&(t[n]=i)}var ve="0.28.20",Y={version:{category:"General",description:"Prints just the compiler's version and exits.",type:"b",alias:"v"},help:{category:"General",description:"Prints this message and exits.",type:"b",alias:"h"},config:{category:"General",description:"Configuration file to apply. CLI arguments take precedence.",type:"s",cliOnly:!0},target:{category:"General",description:"Configuration file target to use. Defaults to 'release'.",type:"s",cliOnly:!0},optimize:{category:"Optimization",description:["Optimizes the module. Typical shorthands are:",""," Default optimizations -O"," Make a release build -O --noAssert"," Make a debug build --debug"," Optimize for speed -Ospeed"," Optimize for size -Osize",""],type:"b",alias:"O"},optimizeLevel:{category:"Optimization",description:"How much to focus on optimizing code. [0-3]",type:"i"},shrinkLevel:{category:"Optimization",description:"How much to focus on shrinking code size. [0-2, s=1, z=2]",type:"i"},converge:{category:"Optimization",description:"Re-optimizes until no further improvements can be made.",type:"b",default:!1},noAssert:{category:"Optimization",description:"Replaces assertions with just their value without trapping.",type:"b",default:!1},outFile:{category:"Output",description:"Specifies the WebAssembly output file (.wasm).",type:"s",alias:"o",isPath:!0},textFile:{category:"Output",description:"Specifies the WebAssembly text output file (.wat).",type:"s",alias:"t",isPath:!0},bindings:{category:"Output",description:["Specifies the bindings to generate (.js + .d.ts).",""," esm JavaScript bindings & typings for ESM integration."," raw Like esm, but exports just the instantiate function."," Useful where modules are meant to be instantiated"," multiple times or non-ESM imports must be provided."],type:"S",alias:"b"},sourceMap:{category:"Debugging",description:["Enables source map generation. Optionally takes the URL","used to reference the source map from the binary file."],type:"s"},uncheckedBehavior:{category:"Debugging",description:["Changes the behavior of unchecked() expressions.","Using this option can potentially cause breakage.",""," default The default behavior: unchecked operations are"," only used inside of unchecked()."," never Unchecked operations are never used, even when"," inside of unchecked()."," always Unchecked operations are always used if possible,"," whether or not unchecked() is used."],type:"s",default:"default"},debug:{category:"Debugging",description:"Enables debug information in emitted binaries.",type:"b",default:!1},importMemory:{category:"Features",description:"Imports the memory from 'env.memory'.",type:"b",default:!1},noExportMemory:{category:"Features",description:"Does not export the memory as 'memory'.",type:"b",default:!1},initialMemory:{category:"Features",description:"Sets the initial memory size in pages.",type:"i",default:0},maximumMemory:{category:"Features",description:"Sets the maximum memory size in pages.",type:"i",default:0},sharedMemory:{category:"Features",description:"Declare memory as shared. Requires maximumMemory.",type:"b",default:!1},zeroFilledMemory:{category:"Features",description:"Assume imported memory is zeroed. Requires importMemory.",type:"b",default:!1},importTable:{category:"Features",description:"Imports the function table from 'env.table'.",type:"b",default:!1},exportTable:{category:"Features",description:"Exports the function table as 'table'.",type:"b",default:!1},exportStart:{category:"Features",description:["Exports the start function using the specified name instead","of calling it implicitly. Useful to obtain the exported memory","before executing any code accessing it."],type:"s"},runtime:{category:"Features",description:["Specifies the runtime variant to include in the program.",""," incremental TLSF + incremental GC (default)"," minimal TLSF + lightweight GC invoked externally"," stub Minimal runtime stub (never frees)"," ... Path to a custom runtime implementation",""],type:"s",default:"incremental"},exportRuntime:{category:"Features",description:["Always exports the runtime helpers (__new, __collect, __pin etc.).","Automatically determined when generation of --bindings is enabled."],type:"b",default:!1},stackSize:{category:"Features",description:["Overrides the stack size. Only relevant for incremental GC","or when using a custom runtime that requires stack space.","Defaults to 0 without and to 32768 with incremental GC."],default:0,type:"i"},enable:{category:"Features",description:["Enables WebAssembly features being disabled by default.",""," threads Threading and atomic operations."," simd SIMD types and operations."," reference-types Reference types and operations."," gc Garbage collection (WIP)."," stringref String reference types."," relaxed-simd Relaxed SIMD operations.",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," extended-const Extended const expressions."],type:"S",mutuallyExclusive:"disable"},disable:{category:"Features",description:["Disables WebAssembly features being enabled by default.",""," mutable-globals Mutable global imports and exports."," sign-extension Sign-extension operations"," nontrapping-f2i Non-trapping float to integer ops."," bulk-memory Bulk memory operations.",""],type:"S",mutuallyExclusive:"enable"},use:{category:"Features",description:["Aliases a global object under another name, e.g., to switch","the default 'Math' implementation used: --use Math=JSMath","Can also be used to introduce an integer constant."],type:"S",alias:"u"},lowMemoryLimit:{category:"Features",description:"Enforces very low (<64k) memory constraints.",default:0,type:"i"},memoryBase:{category:"Linking",description:"Sets the start offset of emitted memory segments.",type:"i",default:0},tableBase:{category:"Linking",description:"Sets the start offset of emitted table elements.",type:"i",default:0},transform:{category:"API",description:"Specifies the path to a custom transform to load.",type:"S",isPath:!0,useNodeResolution:!0},trapMode:{category:"Binaryen",description:["Sets the trap mode to use.",""," allow Allow trapping operations. This is the default."," clamp Replace trapping operations with clamping semantics."," js Replace trapping operations with JS semantics.",""],type:"s",default:"allow"},runPasses:{category:"Binaryen",description:["Specifies additional Binaryen passes to run after other","optimizations, if any. See: Binaryen/src/passes/pass.cpp"],type:"s"},noValidate:{category:"Binaryen",description:"Skips validating the module using Binaryen.",type:"b",default:!1},baseDir:{description:"Specifies the base directory of input and output files.",type:"s",default:"."},noColors:{description:"Disables terminal colors.",type:"b",default:!1},noUnsafe:{description:["Disallows the use of unsafe features in user code.","Does not affect library files and external modules."],type:"b",default:!1},disableWarning:{description:["Disables warnings matching the given diagnostic code.","If no diagnostic code is given, all warnings are disabled."],type:"I"},noEmit:{description:"Performs compilation as usual but does not emit code.",type:"b",default:!1},showConfig:{description:"Print computed compiler options and exit.",type:"b",default:!1},stats:{description:"Prints statistics on I/O and compile times.",type:"b",default:!1},pedantic:{description:"Make yourself sad for no good reason.",type:"b",default:!1},lib:{description:["Adds one or multiple paths to custom library components and","uses exports of all top-level files at this path as globals."],type:"S",isPath:!0},path:{description:["Adds one or multiple paths to package resolution, similar","to node_modules. Prefers an 'ascMain' entry in a package's","package.json and falls back to an inner 'assembly/' folder."],type:"S",isPath:!0},wasm:{description:"Uses the specified Wasm binary of the compiler.",type:"s"}," ...":{description:"Specifies node.js options (CLI only). See: node --help"},"-Os":{value:{optimizeLevel:0,shrinkLevel:1}},"-Oz":{value:{optimizeLevel:0,shrinkLevel:2}},"-O0":{value:{optimizeLevel:0,shrinkLevel:0}},"-O1":{value:{optimizeLevel:1,shrinkLevel:0}},"-O2":{value:{optimizeLevel:2,shrinkLevel:0}},"-O3":{value:{optimizeLevel:3,shrinkLevel:0}},"-O0s":{value:{optimizeLevel:0,shrinkLevel:1}},"-O1s":{value:{optimizeLevel:1,shrinkLevel:1}},"-O2s":{value:{optimizeLevel:2,shrinkLevel:1}},"-O3s":{value:{optimizeLevel:3,shrinkLevel:1}},"-O0z":{value:{optimizeLevel:0,shrinkLevel:2}},"-O1z":{value:{optimizeLevel:1,shrinkLevel:2}},"-O2z":{value:{optimizeLevel:2,shrinkLevel:2}},"-O3z":{value:{optimizeLevel:3,shrinkLevel:2}},"-Ospeed":{value:{optimizeLevel:3,shrinkLevel:0}},"-Osize":{value:{optimizeLevel:0,shrinkLevel:2,converge:!0}},"--measure":{value:{stats:!0}}},Ee="~lib/",Ae={array:`/// <reference path="./rt/index.d.ts" />
import { BLOCK_MAXSIZE } from "./rt/common";
import { Runtime } from "shared/runtime";
import { COMPARATOR, SORT } from "./util/sort";
import { REVERSE, FILL } from "./util/bytes";
import { joinBooleanArray, joinIntegerArray, joinFloatArray, joinStringArray, joinReferenceArray } from "./util/string";
import { idof, isArray as builtin_isArray } from "./builtins";
import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_EMPTYARRAY, E_HOLEYARRAY } from "./util/error";
// @ts-ignore: decorator
@inline @lazy const MIN_SIZE: usize = 8;
/** Ensures that the given array has _at least_ the specified backing size. */
function ensureCapacity(array: usize, newSize: usize, alignLog2: u32, canGrow: bool = true): void {
// Depends on the fact that Arrays mimic ArrayBufferView
let oldCapacity = <usize>changetype<ArrayBufferView>(array).byteLength;
if (newSize > oldCapacity >>> alignLog2) {
if (newSize > BLOCK_MAXSIZE >>> alignLog2) throw new RangeError(E_INVALIDLENGTH);
let oldData = changetype<usize>(changetype<ArrayBufferView>(array).buffer);
// Grows old capacity by factor of two.
// Make sure we don't reach BLOCK_MAXSIZE for new growed capacity.
let newCapacity = max(newSize, MIN_SIZE) << alignLog2;
if (canGrow) newCapacity = max(min(oldCapacity << 1, BLOCK_MAXSIZE), newCapacity);
let newData = __renew(oldData, newCapacity);
// __new / __renew already init memory range as zeros in Incremental runtime.
// So try to avoid this.
if (ASC_RUNTIME != Runtime.Incremental) {
memory.fill(newData + oldCapacity, 0, newCapacity - oldCapacity);
}
if (newData != oldData) { // oldData has been free'd
store<usize>(array, newData, offsetof<ArrayBufferView>("buffer"));
store<usize>(array, newData, offsetof<ArrayBufferView>("dataStart"));
__link(array, changetype<usize>(newData), false);
}
store<u32>(array, <u32>newCapacity, offsetof<ArrayBufferView>("byteLength"));
}
}
export class Array<T> {
[key: number]: T;
// Mimicking ArrayBufferView isn't strictly necessary here but is done to allow glue code
// to work with typed and normal arrays interchangeably. Technically, normal arrays do not need
// \`dataStart\` (equals \`buffer\`) and \`byteLength\` (equals computed \`buffer.byteLength\`), but the
// block is 16 bytes anyway so it's fine to have a couple extra fields in there.
private buffer: ArrayBuffer;
@unsafe readonly dataStart: usize;
private byteLength: i32; // Uses here as capacity
// Also note that Array<T> with non-nullable T must guard against uninitialized null values
// whenever an element is accessed. Otherwise, the compiler wouldn't be able to guarantee
// type-safety anymore. For lack of a better word, such an array is "holey".
private length_: i32;
static isArray<U>(value: U): bool {
return isReference<U>() ? changetype<usize>(value) != 0 && builtin_isArray(value) : false;
}
static create<T>(capacity: i32 = 0): Array<T> {
WARNING("'Array.create' is deprecated. Use 'new Array' instead, making sure initial elements are initialized.");
let array = new Array<T>(capacity);
array.length = 0;
return array;
}
constructor(length: i32 = 0) {
if (<u32>length > <u32>BLOCK_MAXSIZE >>> alignof<T>()) throw new RangeError(E_INVALIDLENGTH);
// reserve capacity for at least MIN_SIZE elements
let bufferSize = max(<usize>length, MIN_SIZE) << alignof<T>();
let buffer = changetype<ArrayBuffer>(__new(bufferSize, idof<ArrayBuffer>()));
if (ASC_RUNTIME != Runtime.Incremental) {
memory.fill(changetype<usize>(buffer), 0, bufferSize);
}
this.buffer = buffer; // links
this.dataStart = changetype<usize>(buffer);
this.byteLength = <i32>bufferSize;
this.length_ = length;
}
get length(): i32 {
return this.length_;
}
set length(newLength: i32) {
ensureCapacity(changetype<usize>(this), newLength, alignof<T>(), false);
this.length_ = newLength;
}
every(fn: (value: T, index: i32, array: Array<T>) => bool): bool {
for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) {
if (!fn(load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this)) return false;
}
return true;
}
findIndex(fn: (value: T, index: i32, array: Array<T>) => bool): i32 {
for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) {
if (fn(load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this)) return i;
}
return -1;
}
findLastIndex(fn: (value: T, index: i32, array: Array<T>) => bool): i32 {
for (let i = this.length_ - 1; i >= 0; --i) {
if (fn(load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this)) return i;
}
return -1;
}
@operator("[]") private __get(index: i32): T {
if (<u32>index >= <u32>this.length_) throw new RangeError(E_INDEXOUTOFRANGE);
let value = load<T>(this.dataStart + (<usize>index << alignof<T>()));
if (isReference<T>()) {
if (!isNullable<T>()) {
if (!changetype<usize>(value)) throw new Error(E_HOLEYARRAY);
}
}
return value;
}
@unsafe @operator("{}") private __uget(index: i32): T {
return load<T>(this.dataStart + (<usize>index << alignof<T>()));
}
@operator("[]=") private __set(index: i32, value: T): void {
if (<u32>index >= <u32>this.length_) {
if (index < 0) throw new RangeError(E_INDEXOUTOFRANGE);
ensureCapacity(changetype<usize>(this), index + 1, alignof<T>());
this.length_ = index + 1;
}
store<T>(this.dataStart + (<usize>index << alignof<T>()), value);
if (isManaged<T>()) {
__link(changetype<usize>(this), changetype<usize>(value), true);
}
}
at(index: i32): T {
let len = this.length_;
index += select(0, len, index >= 0);
if (<u32>index >= <u32>len) throw new RangeError(E_INDEXOUTOFRANGE);
let value = load<T>(this.dataStart + (<usize>index << alignof<T>()));
if (isReference<T>()) {
if (!isNullable<T>()) {
if (!changetype<usize>(value)) throw new Error(E_HOLEYARRAY);
}
}
return value;
}
fill(value: T, start: i32 = 0, end: i32 = i32.MAX_VALUE): Array<T> {
if (isManaged<T>()) {
FILL<usize>(this.dataStart, this.length_, changetype<usize>(value), start, end);
__link(changetype<usize>(this), changetype<usize>(value), false);
} else {
FILL<T>(this.dataStart, this.length_, value, start, end);
}
return this;
}
includes(value: T, fromIndex: i32 = 0): bool {
if (isFloat<T>()) {
let len = this.length_;
if (len == 0 || fromIndex >= len) return false;
if (fromIndex < 0) fromIndex = max(len + fromIndex, 0);
let ptr = this.dataStart;
while (fromIndex < len) {
let elem = load<T>(ptr + (<usize>fromIndex << alignof<T>()));
// @ts-ignore
if (elem == value || isNaN(elem) & isNaN(value)) return true;
++fromIndex;
}
return false;
} else {
return this.indexOf(value, fromIndex) >= 0;
}
}
indexOf(value: T, fromIndex: i32 = 0): i32 {
let len = this.length_;
if (len == 0 || fromIndex >= len) return -1;
if (fromIndex < 0) fromIndex = max(len + fromIndex, 0);
let ptr = this.dataStart;
while (fromIndex < len) {
if (load<T>(ptr + (<usize>fromIndex << alignof<T>())) == value) return fromIndex;
++fromIndex;
}
return -1;
}
lastIndexOf(value: T, fromIndex: i32 = this.length_): i32 {
let len = this.length_;
if (len == 0) return -1;
if (fromIndex < 0) fromIndex = len + fromIndex;
else if (fromIndex >= len) fromIndex = len - 1;
let ptr = this.dataStart;
while (fromIndex >= 0) {
if (load<T>(ptr + (<usize>fromIndex << alignof<T>())) == value) return fromIndex;
--fromIndex;
}
return -1;
}
push(value: T): i32 {
let oldLen = this.length_;
let len = oldLen + 1;
ensureCapacity(changetype<usize>(this), len, alignof<T>());
if (isManaged<T>()) {
store<usize>(this.dataStart + (<usize>oldLen << alignof<T>()), changetype<usize>(value));
__link(changetype<usize>(this), changetype<usize>(value), true);
} else {
store<T>(this.dataStart + (<usize>oldLen << alignof<T>()), value);
}
this.length_ = len;
return len;
}
concat(other: Array<T>): Array<T> {
let thisLen = this.length_;
let otherLen = other.length_;
let outLen = thisLen + otherLen;
if (<u32>outLen > <u32>BLOCK_MAXSIZE >>> alignof<T>()) throw new Error(E_INVALIDLENGTH);
let out = changetype<Array<T>>(__newArray(outLen, alignof<T>(), idof<Array<T>>()));
let outStart = out.dataStart;
let thisSize = <usize>thisLen << alignof<T>();
if (isManaged<T>()) {
let thisStart = this.dataStart;
for (let offset: usize = 0; offset < thisSize; offset += sizeof<T>()) {
let ref = load<usize>(thisStart + offset);
store<usize>(outStart + offset, ref);
__link(changetype<usize>(out), ref, true);
}
outStart += thisSize;
let otherStart = other.dataStart;
let otherSize = <usize>otherLen << alignof<T>();
for (let offset: usize = 0; offset < otherSize; offset += sizeof<T>()) {
let ref = load<usize>(otherStart + offset);
store<usize>(outStart + offset, ref);
__link(changetype<usize>(out), ref, true);
}
} else {
memory.copy(outStart, this.dataStart, thisSize);
memory.copy(outStart + thisSize, other.dataStart, <usize>otherLen << alignof<T>());
}
return out;
}
copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Array<T> {
let ptr = this.dataStart;
let len = this.length_;
end = min<i32>(end, len);
let to = target < 0 ? max(len + target, 0) : min(target, len);
let from = start < 0 ? max(len + start, 0) : min(start, len);
let last = end < 0 ? max(len + end, 0) : min(end, len);
let count = min(last - from, len - to);
memory.copy( // is memmove
ptr + (<usize>to << alignof<T>()),
ptr + (<usize>from << alignof<T>()),
<usize>count << alignof<T>()
);
return this;
}
pop(): T {
let len = this.length_;
if (len < 1) throw new RangeError(E_EMPTYARRAY);
let val = load<T>(this.dataStart + (<usize>(--len) << alignof<T>()));
this.length_ = len;
return val;
}
forEach(fn: (value: T, index: i32, array: Array<T>) => void): void {
for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) {
fn(load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this);
}
}
map<U>(fn: (value: T, index: i32, array: Array<T>) => U): Array<U> {
let len = this.length_;
let out = changetype<Array<U>>(__newArray(len, alignof<U>(), idof<Array<U>>()));
let outStart = out.dataStart;
for (let i = 0; i < min(len, this.length_); ++i) {
let result = fn(load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this);
store<U>(outStart + (<usize>i << alignof<U>()), result);
if (isManaged<U>()) {
__link(changetype<usize>(out), changetype<usize>(result), true);
}
}
return out;
}
filter(fn: (value: T, index: i32, array: Array<T>) => bool): Array<T> {
let result = changetype<Array<T>>(__newArray(0, alignof<T>(), idof<Array<T>>()));
for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) {
let value = load<T>(this.dataStart + (<usize>i << alignof<T>()));
if (fn(value, i, this)) result.push(value);
}
return result;
}
reduce<U>(
fn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array<T>) => U,
initialValue: U
): U {
let acc = initialValue;
for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) {
acc = fn(acc, load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this);
}
return acc;
}
reduceRight<U>(
fn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array<T>) => U,
initialValue: U
): U {
let acc = initialValue;
for (let i = this.length_ - 1; i >= 0; --i) {
acc = fn(acc, load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this);
}
return acc;
}
shift(): T {
let len = this.length_;
if (len < 1) throw new RangeError(E_EMPTYARRAY);
let base = this.dataStart;
let element = load<T>(base);
let lastIndex = len - 1;
memory.copy(
base,
base + sizeof<T>(),
<usize>lastIndex << alignof<T>()
);
if (isReference<T>()) {
store<usize>(base + (<usize>lastIndex << alignof<T>()), 0);
} else {
// @ts-ignore
store<T>(base + (<usize>lastIndex << alignof<T>()), <T>0);
}
this.length_ = lastIndex;
return element;
}
some(fn: (value: T, index: i32, array: Array<T>) => bool): bool {
for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) {
if (fn(load<T>(this.dataStart + (<usize>i << alignof<T>())), i, this)) return true;
}
return false;
}
unshift(value: T): i32 {
let len = this.length_ + 1;
ensureCapacity(changetype<usize>(this), len, alignof<T>());
let ptr = this.dataStart;
memory.copy(
ptr + sizeof<T>(),
ptr,
<usize>(len - 1) << alignof<T>()
);
store<T>(ptr, value);
if (isManaged<T>()) {
__link(changetype<usize>(this), changetype<usize>(value), true);
}
this.length_ = len;
return len;
}
slice(start: i32 = 0, end: i32 = i32.MAX_VALUE): Array<T> {
let len = this.length_;
start = start < 0 ? max(start + len, 0) : min(start, len);
end = end < 0 ? max(end + len, 0) : min(end , len);
len = max(end - start, 0);
let slice = changetype<Array<T>>(__newArray(len, alignof<T>(), idof<Array<T>>()));
let sliceBase = slice.dataStart;
let thisBase = this.dataStart + (<usize>start << alignof<T>());
if (isManaged<T>()) {
let off = <usize>0;
let end = <usize>len << alignof<usize>();
while (off < end) {
let ref = load<usize>(thisBase + off);
store<usize>(sliceBase + off, ref);
__link(changetype<usize>(slice), ref, true);
off += sizeof<usize>();
}
} else {
memory.copy(sliceBase, thisBase, len << alignof<T>());
}
return slice;
}
splice(start: i32, deleteCount: i32 = i32.MAX_VALUE): Array<T> {
let len = this.length_;
start = start < 0 ? max<i32>(len + start, 0) : min<i32>(start, len);
deleteCount = max<i32>(min<i32>(deleteCount, len - start), 0);
let result = changetype<Array<T>>(__newArray(deleteCount, alignof<T>(), idof<Array<T>>()));
let resultStart = result.dataStart;
let thisStart = this.dataStart;
let thisBase = thisStart + (<usize>start << alignof<T>());
memory.copy(
resultStart,
thisBase,
<usize>deleteCount << alignof<T>()
);
let offset = start + deleteCount;
if (len != offset) {
memory.copy(
thisBase,
thisStart + (<usize>offset << alignof<T>()),
<usize>(len - offset) << alignof<T>()
);
}
this.length_ = len - deleteCount;
return result;
}
reverse(): Array<T> {
REVERSE<T>(this.dataStart, this.length_);
return this;
}
sort(comparator: (a: T, b: T) => i32 = COMPARATOR<T>()): Array<T> {
SORT<T>(this.dataStart, this.length_, comparator);
return this;
}
join(separator: string = ","): string {
let ptr = this.dataStart;
let len = this.length_;
if (isBoolean<T>()) return joinBooleanArray(ptr, len, separator);
if (isInteger<T>()) return joinIntegerArray<T>(ptr, len, separator);
if (isFloat<T>()) return joinFloatArray<T>(ptr, len, separator);
if (ASC_SHRINK_LEVEL < 1) {
if (isString<T>()) return joinStringArray(ptr, len, separator);
}
// For rest objects and arrays use general join routine
if (isReference<T>()) return joinReferenceArray<T>(ptr, len, separator);
ERROR("unspported element type");
return <string>unreachable();
}
flat(): T {
if (!isArray<T>()) {
ERROR("Cannot call flat() on Array<T> where T is not an Array.");
}
// Get the length and data start values
let ptr = this.dataStart;
let len = this.length_;
// calculate the end size with an initial pass
let size = 0;
for (let i = 0; i < len; ++i) {
let child = load<usize>(ptr + (i << alignof<T>()));
size += child == 0 ? 0 : load<i32>(child, offsetof<T>("length_"));
}
// calculate the byteLength of the resulting backing ArrayBuffer
const align = alignof<valueof<T>>();
let byteLength = <usize>size << align;
let outBuffer = changetype<ArrayBuffer>(__new(byteLength, idof<ArrayBuffer>()));
// create the return value and initialize it
let outArray = changetype<T>(__new(offsetof<T>(), idof<T>()));
store<i32>(changetype<usize>(outArray), size, offsetof<T>("length_"));
// byteLength, dataStart, and buffer are all readonly
store<i32>(changetype<usize>(outArray), byteLength, offsetof<T>("byteLength"));
store<usize>(changetype<usize>(outArray), changetype<usize>(outBuffer), offsetof<T>("dataStart"));
store<usize>(changetype<usize>(outArray), changetype<usize>(outBuffer), offsetof<T>("buffer"));
__link(changetype<usize>(outArray), changetype<usize>(outBuffer), false);
// set the elements
let resultOffset: usize = 0;
for (let i = 0; i < len; ++i) { // for each child
let child = load<usize>(ptr + (<usize>i << alignof<T>()));
// ignore null arrays
if (!child) continue;
// copy the underlying buffer data to the result buffer
let childDataLength = <usize>load<i32>(child, offsetof<T>("length_")) << align;
memory.copy(
changetype<usize>(outBuffer) + resultOffset,
load<usize>(child, offsetof<T>("dataStart")),
childDataLength
);
// advance the result length
resultOffset += childDataLength;
}
// if the \`valueof<T>\` type is managed, we must link each reference
if (isManaged<valueof<T>>()) {
for (let i = 0; i < size; ++i) {
let ref = load<usize>(changetype<usize>(outBuffer) + (<usize>i << usize(alignof<valueof<T>>())));
__link(changetype<usize>(outBuffer), ref, true);
}
}
return outArray;
}
toString(): string {
return this.join();
}
// RT integration
@unsafe private __visit(cookie: u32): void {
if (isManaged<T>()) {
let cur = this.dataStart;
let end = cur + (<usize>this.length_ << alignof<T>());
while (cur < end) {
let val = load<usize>(cur);
if (val) __visit(val, cookie);
cur += sizeof<usize>();
}
}
__visit(changetype<usize>(this.buffer), cookie);
}
}
`,arraybuffer:`/// <reference path="./rt/index.d.ts" />
import { OBJECT, BLOCK_MAXSIZE, TOTAL_OVERHEAD } from "./rt/common";
import { Runtime } from "shared/runtime";
import { idof } from "./builtins";
import { E_INVALIDLENGTH } from "./util/error";
export abstract class ArrayBufferView {
readonly buffer: ArrayBuffer;
@unsafe readonly dataStart: usize;
readonly byteLength: i32;
get byteOffset(): i32 {
return <i32>(this.dataStart - changetype<usize>(this.buffer));
}
protected constructor(length: i32, alignLog2: i32) {
if (<u32>length > <u32>BLOCK_MAXSIZE >>> alignLog2) throw new RangeError(E_INVALIDLENGTH);
let buffer = changetype<ArrayBuffer>(__new(length = length << alignLog2, idof<ArrayBuffer>()));
if (ASC_RUNTIME != Runtime.Incremental) {
memory.fill(changetype<usize>(buffer), 0, <usize>length);
}
this.buffer = buffer; // links
this.dataStart = changetype<usize>(buffer);
this.byteLength = length;
}
}
@final export class ArrayBuffer {
static isView<T>(value: T): bool {
if (isNullable<T>()) {
if (changetype<usize>(value) == 0) return false;
}
if (value instanceof Int8Array) return true;
if (value instanceof Uint8Array) return true;
if (value instanceof Uint8ClampedArray) return true;
if (value instanceof Int16Array) return true;
if (value instanceof Uint16Array) return true;
if (value instanceof Int32Array) return true;
if (value instanceof Uint32Array) return true;
if (value instanceof Int64Array) return true;
if (value instanceof Uint64Array) return true;
if (value instanceof Float32Array) return true;
if (value instanceof Float64Array) return true;
if (value instanceof DataView) return true;
return false;
}
constructor(length: i32) {
if (<u32>length > <u32>BLOCK_MAXSIZE) throw new RangeError(E_INVALIDLENGTH);
let buffer = changetype<ArrayBuffer>(__new(<usize>length, idof<ArrayBuffer>()));
if (ASC_RUNTIME != Runtime.Incremental) {
memory.fill(changetype<usize>(buffer), 0, <usize>length);
}
return buffer;
}
get byteLength(): i32 {
return changetype<OBJECT>(changetype<usize>(this) - TOTAL_OVERHEAD).rtSize;
}
slice(begin: i32 = 0, end: i32 = BLOCK_MAXSIZE): ArrayBuffer {
let length = this.byteLength;
begin = begin < 0 ? max(length + begin, 0) : min(begin, length);
end = end < 0 ? max(length + end , 0) : min(end , length);
let outSize = <usize>max(end - begin, 0);
let out = changetype<ArrayBuffer>(__new(outSize, idof<ArrayBuffer>()));
memory.copy(changetype<usize>(out), changetype<usize>(this) + <usize>begin, outSize);
return out;
}
toString(): string {
return "[object ArrayBuffer]";
}
}
`,atomics:`import { ArrayBufferView } from "./arraybuffer";
import { E_INDEXOUTOFRANGE } from "./util/error";
export namespace Atomics {
// @ts-ignore: decorator
@inline
export function load<T extends ArrayBufferView>(array: T, index: i32): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.load<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset
);
}
// @ts-ignore: decorator
@inline
export function store<T extends ArrayBufferView>(array: T, index: i32, value: valueof<T>): void {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
atomic.store<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
value
);
}
// @ts-ignore: decorator
@inline
export function add<T extends ArrayBufferView>(array: T, index: i32, value: valueof<T>): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.add<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
value
);
}
// @ts-ignore: decorator
@inline
export function sub<T extends ArrayBufferView>(array: T, index: i32, value: valueof<T>): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.sub<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
value
);
}
// @ts-ignore: decorator
@inline
export function and<T extends ArrayBufferView>(array: T, index: i32, value: valueof<T>): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.and<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
value
);
}
// @ts-ignore: decorator
@inline
export function or<T extends ArrayBufferView>(array: T, index: i32, value: valueof<T>): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.or<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
value
);
}
// @ts-ignore: decorator
@inline
export function xor<T extends ArrayBufferView>(array: T, index: i32, value: valueof<T>): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.xor<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
value
);
}
// @ts-ignore: decorator
@inline
export function exchange<T extends ArrayBufferView>(array: T, index: i32, value: valueof<T>): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.xchg<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
value
);
}
// @ts-ignore: decorator
@inline
export function compareExchange<T extends ArrayBufferView>(
array: T,
index: i32,
expectedValue: valueof<T>,
replacementValue: valueof<T>
): valueof<T> {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.cmpxchg<valueof<T>>(
changetype<usize>(array.buffer) + (index << align) + array.byteOffset,
expectedValue,
replacementValue
);
}
// @ts-ignore: decorator
@inline
export function wait<T extends ArrayBufferView>(array: T, value: valueof<T>, timeout: i64 = -1): AtomicWaitResult {
return atomic.wait<valueof<T>>(changetype<usize>(array.buffer) + array.byteOffset, value, timeout);
}
// @ts-ignore: decorator
@inline
export function notify<T extends ArrayBufferView>(array: T, index: i32, count: i32 = -1): i32 {
const align = alignof<valueof<T>>();
if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE);
return atomic.notify(changetype<usize>(array.buffer) + (index << align) + array.byteOffset, count);
}
export function isLockFree(size: usize): bool {
return size == 1 || size == 2 || size == 4;
}
}
`,"bindings/asyncify":`@unmanaged
export class StackDescriptor {
/** The index in linear memory of the start of the \u201Casyncify stack\u201D. */
stackStart: usize;
/** The index of the end of that stack region, which implies how big it is. */
stackEnd: usize;
}
/** Starts to unwind the call stack. */
export declare function start_unwind(data: StackDescriptor): void;
/** Stops unwinding the call stack. */
export declare function stop_unwind(): void;
/** Starts to rewind the call stack. */
export declare function start_rewind(data: StackDescriptor): void;
/** Stops rewinding the call stack. */
export declare function stop_rewind(): void;
`,"bindings/dom":`@external("env", "globalThis")
export declare const globalThis: externref;
export declare namespace Math {
@external("env", "Math.E")
export const E: f64;
@external("env", "Math.LN2")
export const LN2: f64;
@external("env", "Math.LN10")
export const LN10: f64;
@external("env", "Math.LOG2E")
export const LOG2E: f64;
@external("env", "Math.LOG10E")
export const LOG10E: f64;
@external("env", "Math.PI")
export const PI: f64;
@external("env", "Math.SQRT1_2")
export const SQRT1_2: f64;
@external("env", "Math.SQRT2")
export const SQRT2: f64;
@external("env", "Math.abs")
export function abs(x: f64): f64;
@external("env", "Math.acos")
export function acos(x: f64): f64;
@external("env", "Math.acosh")
export function acosh(x: f64): f64;
@external("env", "Math.asin")
export function asin(x: f64): f64;
@external("env", "Math.asinh")
export function asinh(x: f64): f64;
@external("env", "Math.atan")
export function atan(x: f64): f64;
@external("env", "Math.atan2")
export function atan2(y: f64, x: f64): f64;
@external("env", "Math.atanh")
export function atanh(x: f64): f64;
@external("env", "Math.cbrt")
export function cbrt(x: f64): f64;
@external("env", "Math.ceil")
export function ceil(x: f64): f64;
@external("env", "Math.clz32")
export function clz32(x: f64): f64;
@external("env", "Math.cos")
export function cos(x: f64): f64;
@external("env", "Math.cosh")
export function cosh(x: f64): f64;
@external("env", "Math.exp")
export function exp(x: f64): f64;
@external("env", "Math.expm1")
export function expm1(x: f64): f64;
@external("env", "Math.floor")
export function floor(x: f64): f64;
@external("env", "Math.fround")
export function fround(x: f64): f32;
@external("env", "Math.hypot")
export function hypot(value1: f64, value2: f64): f64; // TODO: rest
@external("env", "Math.imul")
export function imul(a: f64, b: f64): f64;
@external("env", "Math.log")
export function log(x: f64): f64;
@external("env", "Math.log10")
export function log10(x: f64): f64;
@external("env", "Math.log1p")
export function log1p(x: f64): f64;
@external("env", "Math.log2")
export function log2(x: f64): f64;
@exter