assemblyscript
Version:
A TypeScript-like language for WebAssembly.
605 lines (536 loc) • 888 kB
JavaScript
/**
* @license
* The AssemblyScript frontend
* Copyright 2025 Daniel Wirtz / The AssemblyScript Authors
* SPDX-License-Identifier: Apache-2.0
*/
var ye=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var gn=(e,n)=>()=>(e&&(n=e(e=0)),n);var on=(e,n)=>{for(var t in n)ye(e,t,{get:n[t],enumerable:!0})},be=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of et(n))!tt.call(e,o)&&o!==t&&ye(e,o,{get:()=>n[o],enumerable:!(r=nt(n,o))||r.enumerable});return e},Mn=(e,n,t)=>(be(e,n,"default"),t&&be(t,n,"default"));var Fe={};on(Fe,{promises:()=>it});var it,ve=gn(()=>{"use strict";it={}});var Ee={};on(Ee,{createRequire:()=>rt});function rt(){return function(n){throw new Error(`Cannot find module: '${n}'`)}}var Ae=gn(()=>{"use strict"});var Vn={};on(Vn,{argv:()=>st,cwd:()=>Pn,exit:()=>lt,hrtime:()=>ft,platform:()=>ot,umask:()=>at});function Pn(){return"."}function at(){return 0}function lt(e=0){throw Error(`exit ${e}`)}function ft(e){var n=ut.call(_e),t=Math.floor(n*.001),r=Math.floor(n*1e6-t*1e9);return e&&(t-=e[0],r-=e[1],r<0&&(t--,r+=1e9)),[t,r]}var ot,st,_e,ut,jn=gn(()=>{"use strict";ot="linux";st=[];_e=globalThis.performance||{},ut=_e.now||function(){return new Date().getTime()}});var Hn={};on(Hn,{basename:()=>ht,delimiter:()=>Ft,dirname:()=>gt,extname:()=>mt,format:()=>bt,isAbsolute:()=>dt,join:()=>xt,normalize:()=>Ce,parse:()=>yt,relative:()=>pt,resolve:()=>hn,sep:()=>Gn,win32:()=>vt});function q(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function Te(e,n){for(var t="",r=0,o=-1,i=0,s,u=0;u<=e.length;++u){if(u<e.length)s=e.charCodeAt(u);else{if(s===47)break;s=47}if(s===47){if(!(o===u-1||i===1))if(o!==u-1&&i===2){if(t.length<2||r!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){var c=t.lastIndexOf("/");if(c!==t.length-1){c===-1?(t="",r=0):(t=t.slice(0,c),r=t.length-1-t.lastIndexOf("/")),o=u,i=0;continue}}else if(t.length===2||t.length===1){t="",r=0,o=u,i=0;continue}}n&&(t.length>0?t+="/..":t="..",r=2)}else t.length>0?t+="/"+e.slice(o+1,u):t=e.slice(o+1,u),r=u-o-1;o=u,i=0}else s===46&&i!==-1?++i:i=-1}return t}function ct(e,n){var t=n.dir||n.root,r=n.base||(n.name||"")+(n.ext||"");return t?t===n.root?t+r:t+e+r:r}function hn(){for(var e="",n=!1,t,r=arguments.length-1;r>=-1&&!n;r--){var o;r>=0?o=arguments[r]:(t===void 0&&(t=Pn()),o=t),q(o),o.length!==0&&(e=o+"/"+e,n=o.charCodeAt(0)===47)}return e=Te(e,!n),n?e.length>0?"/"+e:"/":e.length>0?e:"."}function Ce(e){if(q(e),e.length===0)return".";var n=e.charCodeAt(0)===47,t=e.charCodeAt(e.length-1)===47;return e=Te(e,!n),e.length===0&&!n&&(e="."),e.length>0&&t&&(e+="/"),n?"/"+e:e}function dt(e){return q(e),e.length>0&&e.charCodeAt(0)===47}function xt(){if(arguments.length===0)return".";for(var e,n=0;n<arguments.length;++n){var t=arguments[n];q(t),t.length>0&&(e===void 0?e=t:e+="/"+t)}return e===void 0?".":Ce(e)}function pt(e,n){if(q(e),q(n),e===n||(e=hn(e),n=hn(n),e===n))return"";if(e===".")return n;for(var t=1;t<e.length&&e.charCodeAt(t)===47;++t);for(var r=e.length,o=r-t,i=1;i<n.length&&n.charCodeAt(i)===47;++i);for(var s=n.length,u=s-i,c=o<u?o:u,p=-1,f=0;f<=c;++f){if(f===c){if(u>c){if(n.charCodeAt(i+f)===47)return n.slice(i+f+1);if(f===0)return n.slice(i+f)}else o>c&&(e.charCodeAt(t+f)===47?p=f:f===0&&(p=0));break}var x=e.charCodeAt(t+f),y=n.charCodeAt(i+f);if(x!==y)break;x===47&&(p=f)}var h="";for(f=t+p+1;f<=r;++f)(f===r||e.charCodeAt(f)===47)&&(h.length===0?h+="..":h+="/..");return h.length>0?h+n.slice(i+p):(i+=p,n.charCodeAt(i)===47&&++i,n.slice(i))}function gt(e){if(q(e),e.length===0)return".";for(var n=e.charCodeAt(0),t=n===47,r=-1,o=!0,i=e.length-1;i>=1;--i)if(n=e.charCodeAt(i),n===47){if(!o){r=i;break}}else o=!1;return r===-1?t?"/":".":t&&r===1?"//":e.slice(0,r)}function ht(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');q(e);var t=0,r=-1,o=!0,i;if(n!==void 0&&n.length>0&&n.length<=e.length){if(n.length===e.length&&n===e)return"";var s=n.length-1,u=-1;for(i=e.length-1;i>=0;--i){var c=e.charCodeAt(i);if(c===47){if(!o){t=i+1;break}}else u===-1&&(o=!1,u=i+1),s>=0&&(c===n.charCodeAt(s)?--s===-1&&(r=i):(s=-1,r=u))}return t===r?r=u:r===-1&&(r=e.length),e.slice(t,r)}else{for(i=e.length-1;i>=0;--i)if(e.charCodeAt(i)===47){if(!o){t=i+1;break}}else r===-1&&(o=!1,r=i+1);return r===-1?"":e.slice(t,r)}}function mt(e){q(e);for(var n=-1,t=0,r=-1,o=!0,i=0,s=e.length-1;s>=0;--s){var u=e.charCodeAt(s);if(u===47){if(!o){t=s+1;break}continue}r===-1&&(o=!1,r=s+1),u===46?n===-1?n=s:i!==1&&(i=1):n!==-1&&(i=-1)}return n===-1||r===-1||i===0||i===1&&n===r-1&&n===t+1?"":e.slice(n,r)}function bt(e){if(e===null||typeof e!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return ct("/",e)}function yt(e){q(e);var n={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return n;var t=e.charCodeAt(0),r=t===47,o;r?(n.root="/",o=1):o=0;for(var i=-1,s=0,u=-1,c=!0,p=e.length-1,f=0;p>=o;--p){if(t=e.charCodeAt(p),t===47){if(!c){s=p+1;break}continue}u===-1&&(c=!1,u=p+1),t===46?i===-1?i=p:f!==1&&(f=1):i!==-1&&(f=-1)}return i===-1||u===-1||f===0||f===1&&i===u-1&&i===s+1?u!==-1&&(s===0&&r?n.base=n.name=e.slice(1,u):n.base=n.name=e.slice(s,u)):(s===0&&r?(n.name=e.slice(1,i),n.base=e.slice(1,u)):(n.name=e.slice(s,i),n.base=e.slice(s,u)),n.ext=e.slice(i,u)),s>0?n.dir=e.slice(0,s-1):r&&(n.dir="/"),n}var Gn,Ft,vt,Xn=gn(()=>{"use strict";jn();Gn="/",Ft=":",vt=null});var ze={};on(ze,{pathToFileURL:()=>At});function Et(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 n=hn(e);e.charCodeAt(e.length-1)===47&&n[n.length-1]!==Gn&&(n+="/");let t=new URL("file://");return t.pathname=Et(n),t}var Be=gn(()=>{"use strict";Xn()});var le={};on(le,{Stats:()=>Rn,checkDiagnostics:()=>kn,compileString:()=>Jt,configToArguments:()=>se,createMemoryStream:()=>oe,default:()=>le,defaultOptimizeLevel:()=>Xe,defaultShrinkLevel:()=>Ke,definitionFiles:()=>Zt,libraryFiles:()=>Y,libraryPrefix:()=>X,main:()=>qe,options:()=>$t,tscOptions:()=>Qt,version:()=>re});var _t=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",W,cn,v,G,mn;_t?(W=await import("fs"),cn=await import("module"),v=await import("path"),G=globalThis.process,mn=await import("url")):(W=await Promise.resolve().then(()=>(ve(),Fe)),cn=await Promise.resolve().then(()=>(Ae(),Ee)),v=await Promise.resolve().then(()=>(Xn(),Hn)),G=await Promise.resolve().then(()=>(jn(),Vn)),mn=await Promise.resolve().then(()=>(Be(),ze)));var wn=typeof process<"u"&&process||{},Tt=wn.env&&"CI"in wn.env,Ct="\x1B[90m",zt="\x1B[91m",Bt="\x1B[92m",wt="\x1B[93m",St="\x1B[94m",Dt="\x1B[95m",It="\x1B[96m",Ot="\x1B[97m",J="\x1B[0m",an=class{constructor(n){this.stream=n,this.enabled=!!(this.stream&&this.stream.isTTY||Tt)}gray(n){return this.enabled?Ct+n+J:n}red(n){return this.enabled?zt+n+J:n}green(n){return this.enabled?Bt+n+J:n}yellow(n){return this.enabled?wt+n+J:n}blue(n){return this.enabled?St+n+J:n}magenta(n){return this.enabled?Dt+n+J:n}cyan(n){return this.enabled?It+n+J:n}white(n){return this.enabled?Ot+n+J:n}},Sn=new an(wn.stdout),ti=new an(wn.stderr);function H(){}H.prototype={diff:function(n,t){var r,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=o.callback;typeof o=="function"&&(i=o,o={});var s=this;function u(_){return _=s.postProcess(_,o),i?(setTimeout(function(){i(_)},0),!0):_}n=this.castInput(n,o),t=this.castInput(t,o),n=this.removeEmpty(this.tokenize(n,o)),t=this.removeEmpty(this.tokenize(t,o));var c=t.length,p=n.length,f=1,x=c+p;o.maxEditLength!=null&&(x=Math.min(x,o.maxEditLength));var y=(r=o.timeout)!==null&&r!==void 0?r:1/0,h=Date.now()+y,a=[{oldPos:-1,lastComponent:void 0}],U=this.extractCommon(a[0],t,n,0,o);if(a[0].oldPos+1>=p&&U+1>=c)return u(we(s,a[0].lastComponent,t,n,s.useLongestToken));var k=-1/0,$=1/0;function nn(){for(var _=Math.max(k,-f);_<=Math.min($,f);_+=2){var T=void 0,w=a[_-1],R=a[_+1];w&&(a[_-1]=void 0);var en=!1;if(R){var K=R.oldPos-_;en=R&&0<=K&&K<c}var I=w&&w.oldPos+1<p;if(!en&&!I){a[_]=void 0;continue}if(!I||en&&w.oldPos<R.oldPos?T=s.addToPath(R,!0,!1,0,o):T=s.addToPath(w,!1,!0,1,o),U=s.extractCommon(T,t,n,_,o),T.oldPos+1>=p&&U+1>=c)return u(we(s,T.lastComponent,t,n,s.useLongestToken));a[_]=T,T.oldPos+1>=p&&($=Math.min($,_-1)),U+1>=c&&(k=Math.max(k,_+1))}f++}if(i)(function _(){setTimeout(function(){if(f>x||Date.now()>h)return i();nn()||_()},0)})();else for(;f<=x&&Date.now()<=h;){var M=nn();if(M)return M}},addToPath:function(n,t,r,o,i){var s=n.lastComponent;return s&&!i.oneChangePerToken&&s.added===t&&s.removed===r?{oldPos:n.oldPos+o,lastComponent:{count:s.count+1,added:t,removed:r,previousComponent:s.previousComponent}}:{oldPos:n.oldPos+o,lastComponent:{count:1,added:t,removed:r,previousComponent:s}}},extractCommon:function(n,t,r,o,i){for(var s=t.length,u=r.length,c=n.oldPos,p=c-o,f=0;p+1<s&&c+1<u&&this.equals(r[c+1],t[p+1],i);)p++,c++,f++,i.oneChangePerToken&&(n.lastComponent={count:1,previousComponent:n.lastComponent,added:!1,removed:!1});return f&&!i.oneChangePerToken&&(n.lastComponent={count:f,previousComponent:n.lastComponent,added:!1,removed:!1}),n.oldPos=c,p},equals:function(n,t,r){return r.comparator?r.comparator(n,t):n===t||r.ignoreCase&&n.toLowerCase()===t.toLowerCase()},removeEmpty:function(n){for(var t=[],r=0;r<n.length;r++)n[r]&&t.push(n[r]);return t},castInput:function(n){return n},tokenize:function(n){return Array.from(n)},join:function(n){return n.join("")},postProcess:function(n){return n}};function we(e,n,t,r,o){for(var i=[],s;n;)i.push(n),s=n.previousComponent,delete n.previousComponent,n=s;i.reverse();for(var u=0,c=i.length,p=0,f=0;u<c;u++){var x=i[u];if(x.removed)x.value=e.join(r.slice(f,f+x.count)),f+=x.count;else{if(!x.added&&o){var y=t.slice(p,p+x.count);y=y.map(function(h,a){var U=r[f+a];return U.length>h.length?U:h}),x.value=e.join(y)}else x.value=e.join(t.slice(p,p+x.count));p+=x.count,x.added||(f+=x.count)}}return i}var ri=new H;function Se(e,n){var t;for(t=0;t<e.length&&t<n.length;t++)if(e[t]!=n[t])return e.slice(0,t);return e.slice(0,t)}function De(e,n){var t;if(!e||!n||e[e.length-1]!=n[n.length-1])return"";for(t=0;t<e.length&&t<n.length;t++)if(e[e.length-(t+1)]!=n[n.length-(t+1)])return e.slice(-t);return e.slice(-t)}function Kn(e,n,t){if(e.slice(0,n.length)!=n)throw Error("string ".concat(JSON.stringify(e)," doesn't start with prefix ").concat(JSON.stringify(n),"; this is a bug"));return t+e.slice(n.length)}function qn(e,n,t){if(!n)return e+t;if(e.slice(-n.length)!=n)throw Error("string ".concat(JSON.stringify(e)," doesn't end with suffix ").concat(JSON.stringify(n),"; this is a bug"));return e.slice(0,-n.length)+t}function bn(e,n){return Kn(e,n,"")}function Dn(e,n){return qn(e,n,"")}function Ie(e,n){return n.slice(0,Lt(e,n))}function Lt(e,n){var t=0;e.length>n.length&&(t=e.length-n.length);var r=n.length;e.length<n.length&&(r=e.length);var o=Array(r),i=0;o[0]=0;for(var s=1;s<r;s++){for(n[s]==n[i]?o[s]=o[i]:o[s]=i;i>0&&n[s]!=n[i];)i=o[i];n[s]==n[i]&&i++}i=0;for(var u=t;u<e.length;u++){for(;i>0&&e[u]!=n[i];)i=o[i];e[u]==n[i]&&i++}return i}var In="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",kt=new RegExp("[".concat(In,"]+|\\s+|[^").concat(In,"]"),"ug"),On=new H;On.equals=function(e,n,t){return t.ignoreCase&&(e=e.toLowerCase(),n=n.toLowerCase()),e.trim()===n.trim()};On.tokenize=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t;if(n.intlSegmenter){if(n.intlSegmenter.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');t=Array.from(n.intlSegmenter.segment(e),function(i){return i.segment})}else t=e.match(kt)||[];var r=[],o=null;return t.forEach(function(i){/\s/.test(i)?o==null?r.push(i):r.push(r.pop()+i):/\s/.test(o)?r[r.length-1]==o?r.push(r.pop()+i):r.push(o+i):r.push(i),o=i}),r};On.join=function(e){return e.map(function(n,t){return t==0?n:n.replace(/^\s+/,"")}).join("")};On.postProcess=function(e,n){if(!e||n.oneChangePerToken)return e;var t=null,r=null,o=null;return e.forEach(function(i){i.added?r=i:i.removed?o=i:((r||o)&&Oe(t,o,r,i),t=i,r=null,o=null)}),(r||o)&&Oe(t,o,r,null),e};function Oe(e,n,t,r){if(n&&t){var o=n.value.match(/^\s*/)[0],i=n.value.match(/\s*$/)[0],s=t.value.match(/^\s*/)[0],u=t.value.match(/\s*$/)[0];if(e){var c=Se(o,s);e.value=qn(e.value,s,c),n.value=bn(n.value,c),t.value=bn(t.value,c)}if(r){var p=De(i,u);r.value=Kn(r.value,u,p),n.value=Dn(n.value,p),t.value=Dn(t.value,p)}}else if(t)e&&(t.value=t.value.replace(/^\s*/,"")),r&&(r.value=r.value.replace(/^\s*/,""));else if(e&&r){var f=r.value.match(/^\s*/)[0],x=n.value.match(/^\s*/)[0],y=n.value.match(/\s*$/)[0],h=Se(f,x);n.value=bn(n.value,h);var a=De(bn(f,h),y);n.value=Dn(n.value,a),r.value=Kn(r.value,f,a),e.value=qn(e.value,f,f.slice(0,f.length-a.length))}else if(r){var U=r.value.match(/^\s*/)[0],k=n.value.match(/\s*$/)[0],$=Ie(k,U);n.value=Dn(n.value,$)}else if(e){var nn=e.value.match(/\s*$/)[0],M=n.value.match(/^\s*/)[0],_=Ie(nn,M);n.value=bn(n.value,_)}}var Rt=new H;Rt.tokenize=function(e){var n=new RegExp("(\\r?\\n)|[".concat(In,"]+|[^\\S\\n\\r]+|[^").concat(In,"]"),"ug");return e.match(n)||[]};var Zn=new H;Zn.tokenize=function(e,n){n.stripTrailingCr&&(e=e.replace(/\r\n/g,`
`));var t=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var o=0;o<r.length;o++){var i=r[o];o%2&&!n.newlineIsToken?t[t.length-1]+=i:t.push(i)}return t};Zn.equals=function(e,n,t){return t.ignoreWhitespace?((!t.newlineIsToken||!e.includes(`
`))&&(e=e.trim()),(!t.newlineIsToken||!n.includes(`
`))&&(n=n.trim())):t.ignoreNewlineAtEof&&!t.newlineIsToken&&(e.endsWith(`
`)&&(e=e.slice(0,-1)),n.endsWith(`
`)&&(n=n.slice(0,-1))),H.prototype.equals.call(this,e,n,t)};var Nt=new H;Nt.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var Ut=new H;Ut.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Wn(e){"@babel/helpers - typeof";return Wn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Wn(e)}var yn=new H;yn.useLongestToken=!0;yn.tokenize=Zn.tokenize;yn.castInput=function(e,n){var t=n.undefinedReplacement,r=n.stringifyReplacer,o=r===void 0?function(i,s){return typeof s>"u"?t:s}:r;return typeof e=="string"?e:JSON.stringify(Yn(e,null,null,o),o," ")};yn.equals=function(e,n,t){return H.prototype.equals.call(yn,e.replace(/,([\r\n])/g,"$1"),n.replace(/,([\r\n])/g,"$1"),t)};function Yn(e,n,t,r,o){n=n||[],t=t||[],r&&(e=r(o,e));var i;for(i=0;i<n.length;i+=1)if(n[i]===e)return t[i];var s;if(Object.prototype.toString.call(e)==="[object Array]"){for(n.push(e),s=new Array(e.length),t.push(s),i=0;i<e.length;i+=1)s[i]=Yn(e[i],n,t,r,o);return n.pop(),t.pop(),s}if(e&&e.toJSON&&(e=e.toJSON()),Wn(e)==="object"&&e!==null){n.push(e),s={},t.push(s);var u=[],c;for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&u.push(c);for(u.sort(),i=0;i<u.length;i+=1)c=u[i],s[c]=Yn(e[c],n,t,r,c);n.pop(),t.pop()}else s=e;return s}var $n=new H;$n.tokenize=function(e){return e.slice()};$n.join=$n.removeEmpty=function(e){return e};function Pt(e){for(var n=0,t=0,r=e.length;t<r;++t){let o=e.charCodeAt(t);o<128?n+=1:o<2048?n+=2:(o&64512)===55296&&t+1<r&&(e.charCodeAt(t+1)&64512)===56320?(++t,n+=4):n+=3}return n}function Vt(e,n,t){var r=t-n;if(r<1)return"";for(var o=null,i=[],s=0,u;n<t;)u=e[n++],u<128?i[s++]=u:u>191&&u<224?i[s++]=(u&31)<<6|e[n++]&63:u>239&&u<365?(u=((u&7)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,i[s++]=55296+(u>>10),i[s++]=56320+(u&1023)):i[s++]=(u&15)<<12|(e[n++]&63)<<6|e[n++]&63,s>=8192&&((o||(o=[])).push(String.fromCharCode(...i)),s=0);return o?(s&&o.push(String.fromCharCode(...i.slice(0,s))),o.join("")):String.fromCharCode(...i.slice(0,s))}function jt(e,n,t){for(var r=t,o=0,i=e.length;o<i;++o){let s=e.charCodeAt(o),u;s<128?n[t++]=s:s<2048?(n[t++]=s>>6|192,n[t++]=s&63|128):(s&64512)===55296&&o+1<i&&((u=e.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(u&1023),++o,n[t++]=s>>18|240,n[t++]=s>>12&63|128,n[t++]=s>>6&63|128,n[t++]=s&63|128):(n[t++]=s>>12|224,n[t++]=s>>6&63|128,n[t++]=s&63|128)}return t-r}var Ln={length:Pt,read:Vt,write:jt};var Le=cn.createRequire(import.meta.url);function Re(e,n,t=!0){var r={},o=[],i=[],s=[],u={};Object.keys(n).forEach(f=>{if(!f.startsWith(" ")){var x=n[f];x.alias!=null&&(typeof x.alias=="string"?u[x.alias]=f:Array.isArray(x.alias)&&x.alias.forEach(y=>u[y]=f)),t&&x.default!=null&&(r[f]=x.default)}});for(var c=0,p=(e=e.slice()).length;c<p;++c){let f=e[c];if(f=="--"){++c;break}let x=/^(?:(-\w)(?:=(.*))?|(--\w{2,})(?:=(.*))?)$/.exec(f),y,h;if(x)n[f]?y=n[h=f]:x[1]!=null?(y=n[h=u[x[1].substring(1)]],y&&x[2]!=null&&(e[c--]=x[2])):x[3]!=null&&(y=n[h=x[3].substring(2)],y&&x[4]!=null&&(e[c--]=x[4]));else if(f.charCodeAt(0)==45)y=n[h=f];else{i.push(f);continue}if(y)if(y.value)Object.keys(y.value).forEach(a=>r[a]=y.value[a]);else if(y.type==null||y.type==="b")r[h]=!0;else if(c+1<e.length&&e[c+1].charCodeAt(0)!=45)switch(y.type){case"i":r[h]=parseInt(e[++c],10);break;case"I":r[h]=(r[h]||[]).concat(parseInt(e[++c],10));break;case"f":r[h]=parseFloat(e[++c]);break;case"F":r[h]=(r[h]||[]).concat(parseFloat(e[++c]));break;case"s":r[h]=String(e[++c]);break;case"S":r[h]=(r[h]||[]).concat(e[++c].split(","));break;default:o.push(f),--c}else switch(y.type){case"i":case"f":r[h]=y.default||0;break;case"s":r[h]=y.default||"";break;case"I":case"F":case"S":r[h]=y.default||[];break;default:o.push(f)}else o.push(f)}for(;c<p;)s.push(e[c++]);return t&&Qn(n,r),{options:r,unknown:o,arguments:i,trailing:s}}function Ne(e,n){n||(n={});var t=n.indent||2,r=n.padding||24,o=n.eol||`
`,i={},s=[];Object.keys(e).forEach(p=>{var f=e[p];if(f.description!=null){for(var x="";x.length<t;)x+=" ";for(x+="--"+p,f.alias&&(x+=", -"+f.alias);x.length<r;)x+=" ";var y;!n.noCategories&&f.category?(y=i[f.category])||(i[f.category]=y=[]):y=s,Array.isArray(f.description)?y.push(x+f.description[0]+f.description.slice(1).map(h=>{for(let a=0;a<r;++a)h=" "+h;return o+h}).join("")):y.push(x+f.description)}});var u=[],c=!1;return Object.keys(i).forEach(p=>{c=!0,u.push(o+" "+Sn.gray(p)+o),u.push(i[p].join(o))}),c&&s.length&&u.push(o+" "+Sn.gray("Other")+o),u.push(s.join(o)),u.join(o)}function ke(e,n){if(e!=null)switch(n){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(t=>Math.trunc(t)||0);case"F":return Array.isArray(e)||(e=[e]),e.map(t=>Number(t)||0);case"S":return Array.isArray(e)||(e=[e]),e.map(String)}}function Jn(e,n,t,r){let o={};for(let[i,{type:s,mutuallyExclusive:u,isPath:c,useNodeResolution:p,cliOnly:f}]of Object.entries(e)){let x=ke(n[i],s),y=ke(t[i],s);if(x==null){if(y!=null){if(f)continue;if(Array.isArray(y)){let h;c&&(y=y.map(a=>sn(a,r,p))),u!=null&&(h=n[u])?o[i]=y.filter(a=>!h.includes(a)):o[i]=y.slice()}else c&&(y=sn(y,r,p)),o[i]=y}}else if(y==null)Array.isArray(x)?o[i]=x.slice():o[i]=x;else if(Array.isArray(x)){if(f){o[i]=x.slice();continue}let h;c&&(y=y.map(a=>sn(a,r,p))),u!=null&&(h=n[u])?o[i]=[...x,...y.filter(a=>!x.includes(a)&&!h.includes(a))]:o[i]=[...x,...y.filter(a=>!x.includes(a))]}else o[i]=x}return o}function Gt(e){let n=v.parse(e);return n.root||(n.root="./"),v.format(n)}function sn(e,n,t=!1){return v.isAbsolute(e)?e:t&&!e.startsWith(".")&&Le.resolve?Le.resolve(e,{paths:[n]}):Gt(v.join(n,e))}function Qn(e,n){for(let[t,{default:r}]of Object.entries(e))n[t]==null&&r!=null&&(n[t]=r)}var Ue="0.28.8",Q={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}}},Me="~lib/",Pe={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