Index: binaries/data/mods/asc/README.md =================================================================== --- /dev/null +++ binaries/data/mods/asc/README.md @@ -0,0 +1,5 @@ +These files are basically copied from the AssemblyScript node_modules. + +I simply took the index.js files and renamed them, likewise with asc.js + +TODO: implementing a node-like module resolution would fix this. Index: binaries/data/mods/asc/assemblyscript.js =================================================================== --- /dev/null +++ binaries/data/mods/asc/assemblyscript.js @@ -0,0 +1,302 @@ +/** + * @license + * The AssemblyScript compiler + * Copyright 2022 Daniel Wirtz / The AssemblyScript Authors + * SPDX-License-Identifier: Apache-2.0 + */ +var qs=Object.defineProperty;var Wu=Object.getOwnPropertyDescriptor;var Od=Object.getOwnPropertyNames;var wd=Object.prototype.hasOwnProperty;var Qs=(r,e)=>{for(var t in e)qs(r,t,{get:e[t],enumerable:!0})},Zs=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Od(e))!wd.call(r,n)&&(t||n!=="default")&&qs(r,n,{get:()=>e[n],enumerable:!(i=Wu(e,n))||i.enumerable});return r};var Yu=(r,e,t,i)=>{for(var n=i>1?void 0:i?Wu(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&qs(e,t,n),n};var Vu={};Qs(Vu,{ASTBuilder:()=>Ks,ArrayLiteralExpression:()=>ga,ArrowKind:()=>Ni,AssertionExpression:()=>Ta,AssertionKind:()=>Gr,AtomicRMWOp:()=>Cu,BinaryExpression:()=>ba,BinaryModule:()=>Bu,BinaryOp:()=>$r,BlockStatement:()=>Qa,BrOnOp:()=>Jc,BreakStatement:()=>Za,CallExpression:()=>Ia,Class:()=>Ci,ClassDeclaration:()=>Kn,ClassExpression:()=>va,ClassPrototype:()=>xs,CommaExpression:()=>xa,CommentKind:()=>Ea,CommentNode:()=>ya,CommonFlags:()=>Pe,CommonNames:()=>O,CompiledExpression:()=>Ka,Compiler:()=>oi,ConditionKind:()=>Ll,ConstantValueKind:()=>Dl,Constraints:()=>ql,ConstructorExpression:()=>Sa,ContinueStatement:()=>ja,DEFAULT_STACK_SIZE:()=>gS,DeclarationStatement:()=>We,DeclaredElement:()=>Gt,DecoratorFlags:()=>Z,DecoratorKind:()=>Et,DecoratorNode:()=>da,DiagnosticCategory:()=>Vn,DiagnosticCode:()=>tt,DiagnosticEmitter:()=>ze,DiagnosticMessage:()=>Ri,DoStatement:()=>Ja,Element:()=>Is,ElementAccessExpression:()=>Ra,ElementKind:()=>J,EmptyStatement:()=>$a,Enum:()=>Ul,EnumDeclaration:()=>eo,EnumValue:()=>Bl,EnumValueDeclaration:()=>to,ExportDefaultStatement:()=>so,ExportImportStatement:()=>ro,ExportMember:()=>io,ExportNames:()=>ln,ExportStatement:()=>no,Expression:()=>fe,ExpressionId:()=>nr,ExpressionRunnerFlags:()=>Us,ExpressionStatement:()=>ao,ExternalKind:()=>Xl,FEATURE_BULK_MEMORY:()=>SS,FEATURE_EXCEPTION_HANDLING:()=>NS,FEATURE_EXTENDED_CONST:()=>MS,FEATURE_FUNCTION_REFERENCES:()=>OS,FEATURE_GC:()=>kS,FEATURE_MEMORY64:()=>PS,FEATURE_MULTI_VALUE:()=>FS,FEATURE_MUTABLE_GLOBALS:()=>vS,FEATURE_NONTRAPPING_F2I:()=>xS,FEATURE_REFERENCE_TYPES:()=>CS,FEATURE_RELAXED_SIMD:()=>wS,FEATURE_SIGN_EXTENSION:()=>IS,FEATURE_SIMD:()=>RS,FEATURE_TAIL_CALLS:()=>LS,FEATURE_THREADS:()=>AS,FalseExpression:()=>Ya,Feature:()=>Ot,FeatureFlags:()=>jl,Field:()=>jn,FieldDeclaration:()=>oo,FieldFlags:()=>Nl,FieldPrototype:()=>Gl,File:()=>Ts,FloatLiteralExpression:()=>Aa,Flow:()=>Ue,FlowFlags:()=>ds,ForOfStatement:()=>uo,ForStatement:()=>lo,Function:()=>je,FunctionDeclaration:()=>Wr,FunctionExpression:()=>Na,FunctionPrototype:()=>Xe,FunctionTypeNode:()=>fa,GETTER_PREFIX:()=>On,Global:()=>ti,INDEX_SUFFIX:()=>Le,INNER_DELIMITER:()=>na,INSTANCE_DELIMITER:()=>vi,IdentifierExpression:()=>it,IdentifierHandling:()=>No,IfStatement:()=>po,ImportDeclaration:()=>co,ImportStatement:()=>Yn,IndexSignature:()=>$n,IndexSignatureNode:()=>qa,InstanceOfExpression:()=>La,IntegerLiteralExpression:()=>Ca,Interface:()=>es,InterfaceDeclaration:()=>_o,InterfacePrototype:()=>Vl,JSBuilder:()=>Ar,LIBRARY_PREFIX:()=>Ze,LIBRARY_SUBST:()=>Mn,LiteralExpression:()=>yt,LiteralKind:()=>we,Local:()=>De,LocalFlags:()=>Es,MemorySegment:()=>un,MethodDeclaration:()=>fo,Module:()=>lt,ModuleDeclaration:()=>bo,NamedTypeNode:()=>Wn,Namespace:()=>vs,NamespaceDeclaration:()=>ho,NewExpression:()=>Fa,Node:()=>k,NodeKind:()=>dt,NullExpression:()=>ka,ObjectLiteralExpression:()=>Pa,OmittedExpression:()=>Oa,OperatorKind:()=>Ce,Options:()=>ws,PARENT_SUBST:()=>Zd,PATH_DELIMITER:()=>Qe,Parameter:()=>Ac,ParameterKind:()=>Br,ParameterNode:()=>ma,ParenthesizedExpression:()=>wa,Parser:()=>gs,Precedence:()=>he,Program:()=>bs,Property:()=>Jn,PropertyAccessExpression:()=>Ma,PropertyPrototype:()=>ri,Range:()=>se,RefAsOp:()=>jc,RefIsOp:()=>Ms,RegexpLiteralExpression:()=>Ua,Relooper:()=>Ln,ReportMode:()=>Qn,Resolver:()=>Zn,ReturnStatement:()=>mo,Runtime:()=>Pn,RuntimeFeatures:()=>Ql,SETTER_PREFIX:()=>wn,SIMDExtractOp:()=>Fu,SIMDLoadOp:()=>Ou,SIMDLoadStoreLaneOp:()=>wu,SIMDReplaceOp:()=>ku,SIMDShiftOp:()=>Pu,SIMDTernaryOp:()=>Mu,STATIC_DELIMITER:()=>xi,STUB_DELIMITER:()=>sa,SideEffects:()=>pn,Signature:()=>ve,Source:()=>zr,SourceKind:()=>Vr,State:()=>Co,Statement:()=>ue,StringLiteralExpression:()=>Ba,SuperExpression:()=>Ga,SwitchBuilder:()=>Ds,SwitchCase:()=>Eo,SwitchStatement:()=>yo,TSDBuilder:()=>Nr,Target:()=>Mr,TemplateLiteralExpression:()=>Va,TernaryExpression:()=>Da,ThisExpression:()=>za,ThrowStatement:()=>go,Token:()=>Yr,Tokenizer:()=>qn,TrueExpression:()=>Wa,TryStatement:()=>To,Type:()=>u,TypeDeclaration:()=>Io,TypeDefinition:()=>bt,TypeFlags:()=>wt,TypeKind:()=>ir,TypeName:()=>_a,TypeNode:()=>Hn,TypeParameterNode:()=>ha,TypeRef:()=>C,TypedElement:()=>Vt,Typeinfo:()=>bi,TypeinfoFlags:()=>Ii,UnaryExpression:()=>Xn,UnaryOp:()=>Ji,UnaryPostfixExpression:()=>Ha,UnaryPrefixExpression:()=>Xa,VariableDeclaration:()=>vo,VariableLikeDeclarationStatement:()=>Ai,VariableLikeElement:()=>ur,VariableStatement:()=>xo,VoidStatement:()=>So,WhileStatement:()=>Ro,addGlobalAlias:()=>fS,allocPtrArray:()=>me,buildJS:()=>uR,buildTSD:()=>lR,compile:()=>oR,createType:()=>Oe,diagnosticCategoryToColor:()=>ju,diagnosticCategoryToString:()=>Gn,diagnosticCodeToString:()=>Fn,disableFeature:()=>DS,enableFeature:()=>US,expandType:()=>Kl,featureToString:()=>wr,findDecorator:()=>gt,findUsedLocals:()=>st,formatDiagnostic:()=>Ju,formatDiagnosticMessage:()=>Ju,getBinaryLeft:()=>Me,getBinaryOp:()=>Jr,getBinaryRight:()=>Se,getBinaryenModuleRef:()=>pR,getBlockChildAt:()=>rn,getBlockChildCount:()=>tn,getBlockName:()=>en,getBreakCondition:()=>N2,getBreakName:()=>A2,getCallOperandAt:()=>Fe,getCallOperandCount:()=>at,getCallTarget:()=>ji,getConstValueF32:()=>Ye,getConstValueF64:()=>He,getConstValueI32:()=>ie,getConstValueI64High:()=>$e,getConstValueI64Low:()=>Be,getConstValueV128:()=>Jl,getDefaultParameterName:()=>Nc,getDependee:()=>sR,getDiagnosticCategory:()=>XS,getDiagnosticCode:()=>HS,getDiagnosticMessage:()=>KS,getDiagnosticRange:()=>qS,getDiagnosticRelatedRange:()=>QS,getDropValue:()=>C2,getExpressionId:()=>te,getExpressionType:()=>oe,getFunctionBody:()=>P2,getFunctionName:()=>O2,getFunctionParams:()=>w2,getFunctionResults:()=>M2,getFunctionVars:()=>U2,getGlobalGetName:()=>$i,getGlobalInit:()=>G2,getGlobalName:()=>D2,getGlobalType:()=>B2,getIfCondition:()=>ms,getIfFalse:()=>jr,getIfTrue:()=>Zi,getLoadBytes:()=>Cl,getLoadOffset:()=>g2,getLoadPtr:()=>T2,getLocalGetIndex:()=>ot,getLocalSetIndex:()=>fs,getLocalSetValue:()=>lr,getLoopBody:()=>R2,getLoopName:()=>S2,getMemoryGrowDelta:()=>k2,getRangeEnd:()=>jS,getRangeSource:()=>JS,getRangeStart:()=>ZS,getReturnValue:()=>F2,getSelectCondition:()=>L2,getSelectElse:()=>Pl,getSelectThen:()=>kl,getSideEffects:()=>ai,getSource:()=>YS,getSourceNormalizedPath:()=>$S,getStoreBytes:()=>b2,getStoreOffset:()=>I2,getStorePtr:()=>v2,getStoreValue:()=>x2,getTagName:()=>V2,getTagParams:()=>z2,getTagResults:()=>W2,getUnaryOp:()=>Qi,getUnaryValue:()=>hs,initializeProgram:()=>aR,isConstNonZero:()=>Je,isConstZero:()=>ge,isDeclaredElement:()=>nn,isError:()=>rR,isGlobalMutable:()=>$l,isIllegalVariableIdentifier:()=>Lo,isInfo:()=>eR,isLoadSigned:()=>Fl,isLocalTee:()=>qi,isTypeOmitted:()=>xe,isTypedElement:()=>Fo,isWarning:()=>tR,mangleInternalName:()=>Te,mangleInternalPath:()=>Li,mustPreserveSideEffects:()=>zs,needsExplicitUnreachable:()=>Bs,newOptions:()=>$2,newProgram:()=>zS,nextDiagnostic:()=>WS,nextFile:()=>nR,operatorTokenToString:()=>ye,optimize:()=>_R,parse:()=>iR,readString:()=>Ve,removeGlobalAlias:()=>hS,setBasenameHint:()=>GS,setBundleVersion:()=>bS,setExportMemory:()=>iS,setExportRuntime:()=>yS,setExportStart:()=>mS,setExportTable:()=>uS,setImportMemory:()=>nS,setImportTable:()=>lS,setInitialMemory:()=>sS,setLowMemoryLimit:()=>ES,setMaximumMemory:()=>aS,setMemoryBase:()=>cS,setNoAssert:()=>rS,setNoUnsafe:()=>dS,setOptimizeLevelHints:()=>BS,setPedantic:()=>VS,setRuntime:()=>tS,setSharedMemory:()=>oS,setSourceMap:()=>pS,setStackSize:()=>TS,setTableBase:()=>_S,setTarget:()=>eS,tokenFromKeyword:()=>$u,tokenIsAlsoIdentifier:()=>ep,typesToRefs:()=>Dr,typesToString:()=>zn,util:()=>ca,validate:()=>cR});var q=typeof window<"u"&&window||typeof global<"u"&&global||self;if(typeof q.ASC_TARGET>"u"){let r=function(){Error.captureStackTrace?Error.captureStackTrace(this,r):this.stack=this.name+": "+this.message+` +`+new Error().stack},e=function(n){this.message=n||"assertion failed",Error.captureStackTrace?Error.captureStackTrace(this,e):this.stack=this.name+": "+this.message+` +`+new Error().stack},t=function(n,s){if(n==s){if(n!=0)return 0;n=1/n,s=1/s}else{var a=n!=n,o=s!=s;if(a|o)return a-o;n==null&&(n=String(n)),s==null&&(s=String(s))}return n>s?1:-1};q.ASC_TARGET=0,q.ASC_RUNTIME=0,q.ASC_NO_ASSERT=!1,q.ASC_MEMORY_BASE=0,q.ASC_OPTIMIZE_LEVEL=3,q.ASC_SHRINK_LEVEL=0,q.ASC_FEATURE_MUTABLE_GLOBAL=!1,q.ASC_FEATURE_SIGN_EXTENSION=!1,q.ASC_FEATURE_BULK_MEMORY=!1,q.ASC_FEATURE_SIMD=!1,q.ASC_FEATURE_THREADS=!1,js=new Float64Array(1),Hu=new Uint32Array(js.buffer),Object.defineProperties(q.i8=function(s){return s<<24>>24},{MIN_VALUE:{value:-128},MAX_VALUE:{value:127}}),Object.defineProperties(q.i16=function(s){return s<<16>>16},{MIN_VALUE:{value:-32768},MAX_VALUE:{value:32767}}),Object.defineProperties(q.i32=q.isize=function(s){return s|0},{MIN_VALUE:{value:-2147483648},MAX_VALUE:{value:2147483647}}),Object.defineProperties(q.u8=function(s){return s&255},{MIN_VALUE:{value:0},MAX_VALUE:{value:255}}),Object.defineProperties(q.u16=function(s){return s&65535},{MIN_VALUE:{value:0},MAX_VALUE:{value:65535}}),Object.defineProperties(q.u32=q.usize=function(s){return s>>>0},{MIN_VALUE:{value:0},MAX_VALUE:{value:4294967295}}),Object.defineProperties(q.bool=function(s){return!!s},{MIN_VALUE:{value:!1},MAX_VALUE:{value:!0}}),Object.defineProperties(q.f32=function(s){return Math.fround(s)},{EPSILON:{value:11920928955078125e-23},MIN_VALUE:{value:1401298464324817e-60},MAX_VALUE:{value:34028234663852886e22},MIN_NORMAL_VALUE:{value:11754943508222875e-54},MIN_SAFE_INTEGER:{value:-16777215},MAX_SAFE_INTEGER:{value:16777215},POSITIVE_INFINITY:{value:1/0},NEGATIVE_INFINITY:{value:-1/0},NaN:{value:NaN}}),Object.defineProperties(q.f64=function(s){return+s},{EPSILON:{value:2220446049250313e-31},MIN_VALUE:{value:5e-324},MAX_VALUE:{value:17976931348623157e292},MIN_NORMAL_VALUE:{value:22250738585072014e-324},MIN_SAFE_INTEGER:{value:-9007199254740991},MAX_SAFE_INTEGER:{value:9007199254740991},POSITIVE_INFINITY:{value:1/0},NEGATIVE_INFINITY:{value:-1/0},NaN:{value:NaN}}),q.clz=Math.clz32,q.ctz=function(s){return 32-Math.clz32(~s&s-1)},q.popcnt=function(s){return s-=s>>>1&1431655765,s=(s&858993459)+(s>>>2&858993459),(s+(s>>>4)&252645135)*16843009>>>24},q.rotl=function(s,a){return a&=31,s<>>32-a},q.rotr=function(s,a){return a&=31,s>>>a|s<<32-a},q.abs=Math.abs,q.max=Math.max,q.min=Math.min,q.ceil=Math.ceil,q.floor=Math.floor,q.nearest=function(s){let o=Math.abs(s);return o<4503599627370496?Math.abs(o+4503599627370496-4503599627370496)*Math.sign(s):s},q.select=function(s,a,o){return o?s:a},q.sqrt=Math.sqrt,q.trunc=Math.trunc,q.copysign=function(s,a){return Math.abs(s)*Math.sign(a)},q.bswap=function(s){var a=s>>8&16711935,o=(s&16711935)<<8;return s=a|o,a=s>>16&65535,o=(s&65535)<<16,a|o},q.bswap16=function(s){return s<<8&65280|s>>8&255|s&4294901760},r.prototype=Object.create(Error.prototype),r.prototype.name="UnreachableError",r.prototype.message="unreachable",q.unreachable=function(){throw new r},e.prototype=Object.create(Error.prototype),e.prototype.name="AssertionError",q.assert=function(s,a){if(s)return s;throw new e(a)},q.changetype=function(s){return s},String.fromCharCodes=function(s){let o=s.length;if(o<=8192)return String.fromCharCode.apply(String,s);let l=0,p="";for(;l=0?s:s+this.length)},configurable:!0}),String.prototype.replaceAll||Object.defineProperty(String.prototype,"replaceAll",{value:function(s,a){var o=this.split(s).join(a);return s.length||(o=a+o+a),o},configurable:!0});let i=Array.prototype.sort;Array.prototype.sort=function(s){return i.call(this,s||t)},[Array,Uint8ClampedArray,Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array].forEach(n=>{n.prototype.at||Object.defineProperty(n.prototype,"at",{value:function(a){return this[a>=0?a:a+this.length]},configurable:!0}),n.prototype.findLastIndex||Object.defineProperty(n.prototype,"findLastIndex",{value:function(a){for(let o=this.length-1;o>=0;--o)if(a(this[o],o,this))return o;return-1},configurable:!0}),n!=Array&&Object.defineProperty(n,"wrap",{value:function(a,o,l){return new n(a,o,l)},configurable:!0})}),q.isInteger=Number.isInteger,q.isFloat=function(s){return typeof s=="number"},q.isNullable=function(s){return!0},q.isReference=function(s){return typeof s=="object"||typeof s=="string"},q.isFunction=function(s){return typeof s=="function"},q.isString=function(s){return typeof s=="string"||s instanceof String},q.isArray=Array.isArray,q.isArrayLike=function(s){return s&&typeof s=="object"&&typeof s.length=="number"&&s.length>=0&&Math.trunc(s.length)===s.length},q.isDefined=function(s){return typeof s<"u"},q.isConstant=function(s){return!1},q.unchecked=function(s){return s},q.fmod=function(s,a){return s%a},q.fmodf=function(s,a){return Math.fround(s%a)},q.JSMath=Math,Object.defineProperties(q.JSMath,{sincos_sin:{value:0,writable:!0},sincos_cos:{value:0,writable:!0},signbit:{value:function(s){return js[0]=s,Boolean(Hu[1]>>>31)}},sincos:{value:function(s){this.sincos_sin=Math.sin(s),this.sincos_cos=Math.cos(s)}},exp2:{value:function(s){return Math.pow(2,s)}}}),q.unmanaged=function(){},q.trace=function(n,s){s&&(n+=Array.prototype.slice.call(arguments,2,2+s)),console.error("trace: "+n)}}else console.warn("compiler mismatch: std/portable included twice");var js,Hu;var Ei={};Qs(Ei,{default:()=>yi});Zs(Ei,iC);import*as iC from"binaryen";import{default as yi}from"binaryen";var tt=(I=>(I[I.Not_implemented_0=100]="Not_implemented_0",I[I.Operation_is_unsafe=101]="Operation_is_unsafe",I[I.User_defined_0=102]="User_defined_0",I[I.Feature_0_is_not_enabled=103]="Feature_0_is_not_enabled",I[I.Low_memory_limit_exceeded_by_static_data_0_1=104]="Low_memory_limit_exceeded_by_static_data_0_1",I[I.Module_requires_at_least_0_pages_of_initial_memory=105]="Module_requires_at_least_0_pages_of_initial_memory",I[I.Module_requires_at_least_0_pages_of_maximum_memory=106]="Module_requires_at_least_0_pages_of_maximum_memory",I[I.Shared_memory_requires_maximum_memory_to_be_defined=107]="Shared_memory_requires_maximum_memory_to_be_defined",I[I.Shared_memory_requires_feature_threads_to_be_enabled=108]="Shared_memory_requires_feature_threads_to_be_enabled",I[I.Transform_0_1=109]="Transform_0_1",I[I.Start_function_name_0_is_invalid_or_conflicts_with_another_export=110]="Start_function_name_0_is_invalid_or_conflicts_with_another_export",I[I.Element_0_not_found=111]="Element_0_not_found",I[I.Conversion_from_type_0_to_1_requires_an_explicit_cast=200]="Conversion_from_type_0_to_1_requires_an_explicit_cast",I[I.Conversion_from_type_0_to_1_will_require_an_explicit_cast_when_switching_between_32_64_bit=201]="Conversion_from_type_0_to_1_will_require_an_explicit_cast_when_switching_between_32_64_bit",I[I.Type_0_cannot_be_changed_to_type_1=202]="Type_0_cannot_be_changed_to_type_1",I[I.Operation_0_cannot_be_applied_to_type_1=203]="Operation_0_cannot_be_applied_to_type_1",I[I.Type_0_cannot_be_nullable=204]="Type_0_cannot_be_nullable",I[I.Mutable_value_cannot_be_inlined=206]="Mutable_value_cannot_be_inlined",I[I.Unmanaged_classes_cannot_extend_managed_classes_and_vice_versa=207]="Unmanaged_classes_cannot_extend_managed_classes_and_vice_versa",I[I.Unmanaged_classes_cannot_implement_interfaces=208]="Unmanaged_classes_cannot_implement_interfaces",I[I.Invalid_regular_expression_flags=209]="Invalid_regular_expression_flags",I[I.Expression_is_never_null=210]="Expression_is_never_null",I[I.Class_0_is_final_and_cannot_be_extended=211]="Class_0_is_final_and_cannot_be_extended",I[I.Decorator_0_is_not_valid_here=212]="Decorator_0_is_not_valid_here",I[I.Duplicate_decorator=213]="Duplicate_decorator",I[I.Type_0_is_illegal_in_this_context=214]="Type_0_is_illegal_in_this_context",I[I.Optional_parameter_must_have_an_initializer=215]="Optional_parameter_must_have_an_initializer",I[I.Class_0_cannot_declare_a_constructor_when_instantiated_from_an_object_literal=216]="Class_0_cannot_declare_a_constructor_when_instantiated_from_an_object_literal",I[I.Function_0_cannot_be_inlined_into_itself=217]="Function_0_cannot_be_inlined_into_itself",I[I.Cannot_access_method_0_without_calling_it_as_it_requires_this_to_be_set=218]="Cannot_access_method_0_without_calling_it_as_it_requires_this_to_be_set",I[I.Optional_properties_are_not_supported=219]="Optional_properties_are_not_supported",I[I.Expression_must_be_a_compile_time_constant=220]="Expression_must_be_a_compile_time_constant",I[I.Type_0_is_not_a_function_index_or_function_reference=221]="Type_0_is_not_a_function_index_or_function_reference",I[I._0_must_be_a_value_between_1_and_2_inclusive=222]="_0_must_be_a_value_between_1_and_2_inclusive",I[I._0_must_be_a_power_of_two=223]="_0_must_be_a_power_of_two",I[I._0_is_not_a_valid_operator=224]="_0_is_not_a_valid_operator",I[I.Expression_cannot_be_represented_by_a_type=225]="Expression_cannot_be_represented_by_a_type",I[I.Expression_resolves_to_unusual_type_0=226]="Expression_resolves_to_unusual_type_0",I[I.Array_literal_expected=227]="Array_literal_expected",I[I.Function_0_is_virtual_and_will_not_be_inlined=228]="Function_0_is_virtual_and_will_not_be_inlined",I[I.Property_0_only_has_a_setter_and_is_missing_a_getter=229]="Property_0_only_has_a_setter_and_is_missing_a_getter",I[I._0_keyword_cannot_be_used_here=230]="_0_keyword_cannot_be_used_here",I[I.A_class_with_a_constructor_explicitly_returning_something_else_than_this_must_be_final=231]="A_class_with_a_constructor_explicitly_returning_something_else_than_this_must_be_final",I[I.Property_0_is_always_assigned_before_being_used=233]="Property_0_is_always_assigned_before_being_used",I[I.Expression_does_not_compile_to_a_value_at_runtime=234]="Expression_does_not_compile_to_a_value_at_runtime",I[I.Only_variables_functions_and_enums_become_WebAssembly_module_exports=235]="Only_variables_functions_and_enums_become_WebAssembly_module_exports",I[I.Importing_the_table_disables_some_indirect_call_optimizations=901]="Importing_the_table_disables_some_indirect_call_optimizations",I[I.Exporting_the_table_disables_some_indirect_call_optimizations=902]="Exporting_the_table_disables_some_indirect_call_optimizations",I[I.Expression_compiles_to_a_dynamic_check_at_runtime=903]="Expression_compiles_to_a_dynamic_check_at_runtime",I[I.Indexed_access_may_involve_bounds_checking=904]="Indexed_access_may_involve_bounds_checking",I[I.Explicitly_returning_constructor_drops_this_allocation=905]="Explicitly_returning_constructor_drops_this_allocation",I[I.Unnecessary_definite_assignment=906]="Unnecessary_definite_assignment",I[I.Unterminated_string_literal=1002]="Unterminated_string_literal",I[I.Identifier_expected=1003]="Identifier_expected",I[I._0_expected=1005]="_0_expected",I[I.A_file_cannot_have_a_reference_to_itself=1006]="A_file_cannot_have_a_reference_to_itself",I[I.Trailing_comma_not_allowed=1009]="Trailing_comma_not_allowed",I[I.Unexpected_token=1012]="Unexpected_token",I[I.A_rest_parameter_must_be_last_in_a_parameter_list=1014]="A_rest_parameter_must_be_last_in_a_parameter_list",I[I.Parameter_cannot_have_question_mark_and_initializer=1015]="Parameter_cannot_have_question_mark_and_initializer",I[I.A_required_parameter_cannot_follow_an_optional_parameter=1016]="A_required_parameter_cannot_follow_an_optional_parameter",I[I._0_modifier_cannot_appear_on_class_elements_of_this_kind=1031]="_0_modifier_cannot_appear_on_class_elements_of_this_kind",I[I.Statements_are_not_allowed_in_ambient_contexts=1036]="Statements_are_not_allowed_in_ambient_contexts",I[I.Initializers_are_not_allowed_in_ambient_contexts=1039]="Initializers_are_not_allowed_in_ambient_contexts",I[I._0_modifier_cannot_be_used_here=1042]="_0_modifier_cannot_be_used_here",I[I.A_rest_parameter_cannot_be_optional=1047]="A_rest_parameter_cannot_be_optional",I[I.A_rest_parameter_cannot_have_an_initializer=1048]="A_rest_parameter_cannot_have_an_initializer",I[I.A_set_accessor_must_have_exactly_one_parameter=1049]="A_set_accessor_must_have_exactly_one_parameter",I[I.A_set_accessor_parameter_cannot_have_an_initializer=1052]="A_set_accessor_parameter_cannot_have_an_initializer",I[I.A_get_accessor_cannot_have_parameters=1054]="A_get_accessor_cannot_have_parameters",I[I.Enum_member_must_have_initializer=1061]="Enum_member_must_have_initializer",I[I.Type_parameters_cannot_appear_on_a_constructor_declaration=1092]="Type_parameters_cannot_appear_on_a_constructor_declaration",I[I.Type_annotation_cannot_appear_on_a_constructor_declaration=1093]="Type_annotation_cannot_appear_on_a_constructor_declaration",I[I.An_accessor_cannot_have_type_parameters=1094]="An_accessor_cannot_have_type_parameters",I[I.A_set_accessor_cannot_have_a_return_type_annotation=1095]="A_set_accessor_cannot_have_a_return_type_annotation",I[I.Type_parameter_list_cannot_be_empty=1098]="Type_parameter_list_cannot_be_empty",I[I.Type_argument_list_cannot_be_empty=1099]="Type_argument_list_cannot_be_empty",I[I.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement=1104]="A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement",I[I.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement=1105]="A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement",I[I.A_return_statement_can_only_be_used_within_a_function_body=1108]="A_return_statement_can_only_be_used_within_a_function_body",I[I.Expression_expected=1109]="Expression_expected",I[I.Type_expected=1110]="Type_expected",I[I.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement=1113]="A_default_clause_cannot_appear_more_than_once_in_a_switch_statement",I[I.Duplicate_label_0=1114]="Duplicate_label_0",I[I.An_export_assignment_cannot_have_modifiers=1120]="An_export_assignment_cannot_have_modifiers",I[I.Octal_literals_are_not_allowed_in_strict_mode=1121]="Octal_literals_are_not_allowed_in_strict_mode",I[I.Digit_expected=1124]="Digit_expected",I[I.Hexadecimal_digit_expected=1125]="Hexadecimal_digit_expected",I[I.Unexpected_end_of_text=1126]="Unexpected_end_of_text",I[I.Invalid_character=1127]="Invalid_character",I[I._case_or_default_expected=1130]="_case_or_default_expected",I[I._super_must_be_followed_by_an_argument_list_or_member_access=1034]="_super_must_be_followed_by_an_argument_list_or_member_access",I[I.A_declare_modifier_cannot_be_used_in_an_already_ambient_context=1038]="A_declare_modifier_cannot_be_used_in_an_already_ambient_context",I[I.Type_argument_expected=1140]="Type_argument_expected",I[I.String_literal_expected=1141]="String_literal_expected",I[I.Line_break_not_permitted_here=1142]="Line_break_not_permitted_here",I[I.Declaration_expected=1146]="Declaration_expected",I[I._const_declarations_must_be_initialized=1155]="_const_declarations_must_be_initialized",I[I.Unterminated_regular_expression_literal=1161]="Unterminated_regular_expression_literal",I[I.Interface_declaration_cannot_have_implements_clause=1176]="Interface_declaration_cannot_have_implements_clause",I[I.Binary_digit_expected=1177]="Binary_digit_expected",I[I.Octal_digit_expected=1178]="Octal_digit_expected",I[I.An_implementation_cannot_be_declared_in_ambient_contexts=1183]="An_implementation_cannot_be_declared_in_ambient_contexts",I[I.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer=1190]="The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer",I[I.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive=1198]="An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive",I[I.Unterminated_Unicode_escape_sequence=1199]="Unterminated_Unicode_escape_sequence",I[I.Decorators_are_not_valid_here=1206]="Decorators_are_not_valid_here",I[I._abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration=1242]="_abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration",I[I.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract=1245]="Method_0_cannot_have_an_implementation_because_it_is_marked_abstract",I[I.A_definite_assignment_assertion_is_not_permitted_in_this_context=1255]="A_definite_assignment_assertion_is_not_permitted_in_this_context",I[I.A_class_may_only_extend_another_class=1311]="A_class_may_only_extend_another_class",I[I.A_parameter_property_cannot_be_declared_using_a_rest_parameter=1317]="A_parameter_property_cannot_be_declared_using_a_rest_parameter",I[I.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal=1351]="An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal",I[I.Duplicate_identifier_0=2300]="Duplicate_identifier_0",I[I.Cannot_find_name_0=2304]="Cannot_find_name_0",I[I.Module_0_has_no_exported_member_1=2305]="Module_0_has_no_exported_member_1",I[I.An_interface_can_only_extend_an_interface=2312]="An_interface_can_only_extend_an_interface",I[I.Generic_type_0_requires_1_type_argument_s=2314]="Generic_type_0_requires_1_type_argument_s",I[I.Type_0_is_not_generic=2315]="Type_0_is_not_generic",I[I.Type_0_is_not_assignable_to_type_1=2322]="Type_0_is_not_assignable_to_type_1",I[I.Property_0_is_private_in_type_1_but_not_in_type_2=2325]="Property_0_is_private_in_type_1_but_not_in_type_2",I[I.Index_signature_is_missing_in_type_0=2329]="Index_signature_is_missing_in_type_0",I[I._this_cannot_be_referenced_in_current_location=2332]="_this_cannot_be_referenced_in_current_location",I[I._this_cannot_be_referenced_in_constructor_arguments=2333]="_this_cannot_be_referenced_in_constructor_arguments",I[I._super_can_only_be_referenced_in_a_derived_class=2335]="_super_can_only_be_referenced_in_a_derived_class",I[I._super_cannot_be_referenced_in_constructor_arguments=2336]="_super_cannot_be_referenced_in_constructor_arguments",I[I.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors=2337]="Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors",I[I.Property_0_does_not_exist_on_type_1=2339]="Property_0_does_not_exist_on_type_1",I[I.Property_0_is_private_and_only_accessible_within_class_1=2341]="Property_0_is_private_and_only_accessible_within_class_1",I[I.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures=2349]="Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures",I[I.This_expression_is_not_constructable=2351]="This_expression_is_not_constructable",I[I.A_function_whose_declared_type_is_not_void_must_return_a_value=2355]="A_function_whose_declared_type_is_not_void_must_return_a_value",I[I.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access=2357]="The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access",I[I.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access=2364]="The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access",I[I.Operator_0_cannot_be_applied_to_types_1_and_2=2365]="Operator_0_cannot_be_applied_to_types_1_and_2",I[I.A_super_call_must_be_the_first_statement_in_the_constructor=2376]="A_super_call_must_be_the_first_statement_in_the_constructor",I[I.Constructors_for_derived_classes_must_contain_a_super_call=2377]="Constructors_for_derived_classes_must_contain_a_super_call",I[I.Getter_and_setter_accessors_do_not_agree_in_visibility=2379]="Getter_and_setter_accessors_do_not_agree_in_visibility",I[I._get_and_set_accessor_must_have_the_same_type=2380]="_get_and_set_accessor_must_have_the_same_type",I[I.Overload_signatures_must_all_be_public_private_or_protected=2385]="Overload_signatures_must_all_be_public_private_or_protected",I[I.Constructor_implementation_is_missing=2390]="Constructor_implementation_is_missing",I[I.Function_implementation_is_missing_or_not_immediately_following_the_declaration=2391]="Function_implementation_is_missing_or_not_immediately_following_the_declaration",I[I.Multiple_constructor_implementations_are_not_allowed=2392]="Multiple_constructor_implementations_are_not_allowed",I[I.Duplicate_function_implementation=2393]="Duplicate_function_implementation",I[I.This_overload_signature_is_not_compatible_with_its_implementation_signature=2394]="This_overload_signature_is_not_compatible_with_its_implementation_signature",I[I.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local=2395]="Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local",I[I.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2=2416]="Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2",I[I.A_class_can_only_implement_an_interface=2422]="A_class_can_only_implement_an_interface",I[I.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged=2434]="A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged",I[I.Types_have_separate_declarations_of_a_private_property_0=2442]="Types_have_separate_declarations_of_a_private_property_0",I[I.Property_0_is_protected_in_type_1_but_public_in_type_2=2444]="Property_0_is_protected_in_type_1_but_public_in_type_2",I[I.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses=2445]="Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses",I[I.Variable_0_used_before_its_declaration=2448]="Variable_0_used_before_its_declaration",I[I.Cannot_redeclare_block_scoped_variable_0=2451]="Cannot_redeclare_block_scoped_variable_0",I[I.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly=2453]="The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly",I[I.Type_0_has_no_property_1=2460]="Type_0_has_no_property_1",I[I.The_0_operator_cannot_be_applied_to_type_1=2469]="The_0_operator_cannot_be_applied_to_type_1",I[I.In_const_enum_declarations_member_initializer_must_be_constant_expression=2474]="In_const_enum_declarations_member_initializer_must_be_constant_expression",I[I.Export_declaration_conflicts_with_exported_declaration_of_0=2484]="Export_declaration_conflicts_with_exported_declaration_of_0",I[I._0_is_referenced_directly_or_indirectly_in_its_own_base_expression=2506]="_0_is_referenced_directly_or_indirectly_in_its_own_base_expression",I[I.Cannot_create_an_instance_of_an_abstract_class=2511]="Cannot_create_an_instance_of_an_abstract_class",I[I.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_2=2515]="Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_2",I[I.Object_is_possibly_null=2531]="Object_is_possibly_null",I[I.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property=2540]="Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property",I[I.The_target_of_an_assignment_must_be_a_variable_or_a_property_access=2541]="The_target_of_an_assignment_must_be_a_variable_or_a_property_access",I[I.Index_signature_in_type_0_only_permits_reading=2542]="Index_signature_in_type_0_only_permits_reading",I[I.Expected_0_arguments_but_got_1=2554]="Expected_0_arguments_but_got_1",I[I.Expected_at_least_0_arguments_but_got_1=2555]="Expected_at_least_0_arguments_but_got_1",I[I.Expected_0_type_arguments_but_got_1=2558]="Expected_0_type_arguments_but_got_1",I[I.Property_0_has_no_initializer_and_is_not_assigned_in_the_constructor_before_this_is_used_or_returned=2564]="Property_0_has_no_initializer_and_is_not_assigned_in_the_constructor_before_this_is_used_or_returned",I[I.Property_0_is_used_before_being_assigned=2565]="Property_0_is_used_before_being_assigned",I[I.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums=2651]="A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums",I[I.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration=2673]="Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration",I[I.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration=2674]="Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration",I[I.The_this_types_of_each_signature_are_incompatible=2685]="The_this_types_of_each_signature_are_incompatible",I[I.Namespace_0_has_no_exported_member_1=2694]="Namespace_0_has_no_exported_member_1",I[I.Required_type_parameters_may_not_follow_optional_type_parameters=2706]="Required_type_parameters_may_not_follow_optional_type_parameters",I[I.Duplicate_property_0=2718]="Duplicate_property_0",I[I.Property_0_is_missing_in_type_1_but_required_in_type_2=2741]="Property_0_is_missing_in_type_1_but_required_in_type_2",I[I.Type_0_has_no_call_signatures=2757]="Type_0_has_no_call_signatures",I[I.File_0_not_found=6054]="File_0_not_found",I[I.Numeric_separators_are_not_allowed_here=6188]="Numeric_separators_are_not_allowed_here",I[I.Multiple_consecutive_numeric_separators_are_not_permitted=6189]="Multiple_consecutive_numeric_separators_are_not_permitted",I[I._super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class=17009]="_super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class",I[I._super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class=17011]="_super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class",I))(tt||{});function Fn(r){switch(r){case 100:return"Not implemented: {0}";case 101:return"Operation is unsafe.";case 102:return"User-defined: {0}";case 103:return"Feature '{0}' is not enabled.";case 104:return"Low memory limit exceeded by static data: {0} > {1}";case 105:return"Module requires at least '{0}' pages of initial memory.";case 106:return"Module requires at least '{0}' pages of maximum memory.";case 107:return"Shared memory requires maximum memory to be defined.";case 108:return"Shared memory requires feature 'threads' to be enabled.";case 109:return"Transform '{0}': {1}";case 110:return"Start function name '{0}' is invalid or conflicts with another export.";case 111:return"Element '{0}' not found.";case 200:return"Conversion from type '{0}' to '{1}' requires an explicit cast.";case 201:return"Conversion from type '{0}' to '{1}' will require an explicit cast when switching between 32/64-bit.";case 202:return"Type '{0}' cannot be changed to type '{1}'.";case 203:return"Operation '{0}' cannot be applied to type '{1}'.";case 204:return"Type '{0}' cannot be nullable.";case 206:return"Mutable value cannot be inlined.";case 207:return"Unmanaged classes cannot extend managed classes and vice-versa.";case 208:return"Unmanaged classes cannot implement interfaces.";case 209:return"Invalid regular expression flags.";case 210:return"Expression is never 'null'.";case 211:return"Class '{0}' is final and cannot be extended.";case 212:return"Decorator '{0}' is not valid here.";case 213:return"Duplicate decorator.";case 214:return"Type '{0}' is illegal in this context.";case 215:return"Optional parameter must have an initializer.";case 216:return"Class '{0}' cannot declare a constructor when instantiated from an object literal.";case 217:return"Function '{0}' cannot be inlined into itself.";case 218:return"Cannot access method '{0}' without calling it as it requires 'this' to be set.";case 219:return"Optional properties are not supported.";case 220:return"Expression must be a compile-time constant.";case 221:return"Type '{0}' is not a function index or function reference.";case 222:return"'{0}' must be a value between '{1}' and '{2}' inclusive.";case 223:return"'{0}' must be a power of two.";case 224:return"'{0}' is not a valid operator.";case 225:return"Expression cannot be represented by a type.";case 226:return"Expression resolves to unusual type '{0}'.";case 227:return"Array literal expected.";case 228:return"Function '{0}' is virtual and will not be inlined.";case 229:return"Property '{0}' only has a setter and is missing a getter.";case 230:return"'{0}' keyword cannot be used here.";case 231:return"A class with a constructor explicitly returning something else than 'this' must be '@final'.";case 233:return"Property '{0}' is always assigned before being used.";case 234:return"Expression does not compile to a value at runtime.";case 235:return"Only variables, functions and enums become WebAssembly module exports.";case 901:return"Importing the table disables some indirect call optimizations.";case 902:return"Exporting the table disables some indirect call optimizations.";case 903:return"Expression compiles to a dynamic check at runtime.";case 904:return"Indexed access may involve bounds checking.";case 905:return"Explicitly returning constructor drops 'this' allocation.";case 906:return"Unnecessary definite assignment.";case 1002:return"Unterminated string literal.";case 1003:return"Identifier expected.";case 1005:return"'{0}' expected.";case 1006:return"A file cannot have a reference to itself.";case 1009:return"Trailing comma not allowed.";case 1012:return"Unexpected token.";case 1014:return"A rest parameter must be last in a parameter list.";case 1015:return"Parameter cannot have question mark and initializer.";case 1016:return"A required parameter cannot follow an optional parameter.";case 1031:return"'{0}' modifier cannot appear on class elements of this kind.";case 1036:return"Statements are not allowed in ambient contexts.";case 1039:return"Initializers are not allowed in ambient contexts.";case 1042:return"'{0}' modifier cannot be used here.";case 1047:return"A rest parameter cannot be optional.";case 1048:return"A rest parameter cannot have an initializer.";case 1049:return"A 'set' accessor must have exactly one parameter.";case 1052:return"A 'set' accessor parameter cannot have an initializer.";case 1054:return"A 'get' accessor cannot have parameters.";case 1061:return"Enum member must have initializer.";case 1092:return"Type parameters cannot appear on a constructor declaration.";case 1093:return"Type annotation cannot appear on a constructor declaration.";case 1094:return"An accessor cannot have type parameters.";case 1095:return"A 'set' accessor cannot have a return type annotation.";case 1098:return"Type parameter list cannot be empty.";case 1099:return"Type argument list cannot be empty.";case 1104:return"A 'continue' statement can only be used within an enclosing iteration statement.";case 1105:return"A 'break' statement can only be used within an enclosing iteration or switch statement.";case 1108:return"A 'return' statement can only be used within a function body.";case 1109:return"Expression expected.";case 1110:return"Type expected.";case 1113:return"A 'default' clause cannot appear more than once in a 'switch' statement.";case 1114:return"Duplicate label '{0}'.";case 1120:return"An export assignment cannot have modifiers.";case 1121:return"Octal literals are not allowed in strict mode.";case 1124:return"Digit expected.";case 1125:return"Hexadecimal digit expected.";case 1126:return"Unexpected end of text.";case 1127:return"Invalid character.";case 1130:return"'case' or 'default' expected.";case 1034:return"'super' must be followed by an argument list or member access.";case 1038:return"A 'declare' modifier cannot be used in an already ambient context.";case 1140:return"Type argument expected.";case 1141:return"String literal expected.";case 1142:return"Line break not permitted here.";case 1146:return"Declaration expected.";case 1155:return"'const' declarations must be initialized.";case 1161:return"Unterminated regular expression literal.";case 1176:return"Interface declaration cannot have 'implements' clause.";case 1177:return"Binary digit expected.";case 1178:return"Octal digit expected.";case 1183:return"An implementation cannot be declared in ambient contexts.";case 1190:return"The variable declaration of a 'for...of' statement cannot have an initializer.";case 1198:return"An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive.";case 1199:return"Unterminated Unicode escape sequence.";case 1206:return"Decorators are not valid here.";case 1242:return"'abstract' modifier can only appear on a class, method, or property declaration.";case 1245:return"Method '{0}' cannot have an implementation because it is marked abstract.";case 1255:return"A definite assignment assertion '!' is not permitted in this context.";case 1311:return"A class may only extend another class.";case 1317:return"A parameter property cannot be declared using a rest parameter.";case 1351:return"An identifier or keyword cannot immediately follow a numeric literal.";case 2300:return"Duplicate identifier '{0}'.";case 2304:return"Cannot find name '{0}'.";case 2305:return"Module '{0}' has no exported member '{1}'.";case 2312:return"An interface can only extend an interface.";case 2314:return"Generic type '{0}' requires {1} type argument(s).";case 2315:return"Type '{0}' is not generic.";case 2322:return"Type '{0}' is not assignable to type '{1}'.";case 2325:return"Property '{0}' is private in type '{1}' but not in type '{2}'.";case 2329:return"Index signature is missing in type '{0}'.";case 2332:return"'this' cannot be referenced in current location.";case 2333:return"'this' cannot be referenced in constructor arguments.";case 2335:return"'super' can only be referenced in a derived class.";case 2336:return"'super' cannot be referenced in constructor arguments.";case 2337:return"Super calls are not permitted outside constructors or in nested functions inside constructors.";case 2339:return"Property '{0}' does not exist on type '{1}'.";case 2341:return"Property '{0}' is private and only accessible within class '{1}'.";case 2349:return"Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures.";case 2351:return"This expression is not constructable.";case 2355:return"A function whose declared type is not 'void' must return a value.";case 2357:return"The operand of an increment or decrement operator must be a variable or a property access.";case 2364:return"The left-hand side of an assignment expression must be a variable or a property access.";case 2365:return"Operator '{0}' cannot be applied to types '{1}' and '{2}'.";case 2376:return"A 'super' call must be the first statement in the constructor.";case 2377:return"Constructors for derived classes must contain a 'super' call.";case 2379:return"Getter and setter accessors do not agree in visibility.";case 2380:return"'get' and 'set' accessor must have the same type.";case 2385:return"Overload signatures must all be public, private or protected.";case 2390:return"Constructor implementation is missing.";case 2391:return"Function implementation is missing or not immediately following the declaration.";case 2392:return"Multiple constructor implementations are not allowed.";case 2393:return"Duplicate function implementation.";case 2394:return"This overload signature is not compatible with its implementation signature.";case 2395:return"Individual declarations in merged declaration '{0}' must be all exported or all local.";case 2416:return"Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'.";case 2422:return"A class can only implement an interface.";case 2434:return"A namespace declaration cannot be located prior to a class or function with which it is merged.";case 2442:return"Types have separate declarations of a private property '{0}'.";case 2444:return"Property '{0}' is protected in type '{1}' but public in type '{2}'.";case 2445:return"Property '{0}' is protected and only accessible within class '{1}' and its subclasses.";case 2448:return"Variable '{0}' used before its declaration.";case 2451:return"Cannot redeclare block-scoped variable '{0}'";case 2453:return"The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly.";case 2460:return"Type '{0}' has no property '{1}'.";case 2469:return"The '{0}' operator cannot be applied to type '{1}'.";case 2474:return"In 'const' enum declarations member initializer must be constant expression.";case 2484:return"Export declaration conflicts with exported declaration of '{0}'.";case 2506:return"'{0}' is referenced directly or indirectly in its own base expression.";case 2511:return"Cannot create an instance of an abstract class.";case 2515:return"Non-abstract class '{0}' does not implement inherited abstract member '{1}' from '{2}'.";case 2531:return"Object is possibly 'null'.";case 2540:return"Cannot assign to '{0}' because it is a constant or a read-only property.";case 2541:return"The target of an assignment must be a variable or a property access.";case 2542:return"Index signature in type '{0}' only permits reading.";case 2554:return"Expected {0} arguments, but got {1}.";case 2555:return"Expected at least {0} arguments, but got {1}.";case 2558:return"Expected {0} type arguments, but got {1}.";case 2564:return"Property '{0}' has no initializer and is not assigned in the constructor before 'this' is used or returned.";case 2565:return"Property '{0}' is used before being assigned.";case 2651:return"A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums.";case 2673:return"Constructor of class '{0}' is private and only accessible within the class declaration.";case 2674:return"Constructor of class '{0}' is protected and only accessible within the class declaration.";case 2685:return"The 'this' types of each signature are incompatible.";case 2694:return"Namespace '{0}' has no exported member '{1}'.";case 2706:return"Required type parameters may not follow optional type parameters.";case 2718:return"Duplicate property '{0}'.";case 2741:return"Property '{0}' is missing in type '{1}' but required in type '{2}'.";case 2757:return"Type '{0}' has no call signatures.";case 6054:return"File '{0}' not found.";case 6188:return"Numeric separators are not allowed here.";case 6189:return"Multiple consecutive numeric separators are not permitted.";case 17009:return"'super' must be called before accessing 'this' in the constructor of a derived class.";case 17011:return"'super' must be called before accessing a property of 'super' in the constructor of a derived class.";default:return""}}var ca={};Qs(ca,{COLOR_BLUE:()=>$d,COLOR_CYAN:()=>la,COLOR_GRAY:()=>jd,COLOR_GREEN:()=>Jd,COLOR_MAGENTA:()=>oa,COLOR_RED:()=>Dn,COLOR_RESET:()=>Si,COLOR_WHITE:()=>eE,COLOR_YELLOW:()=>aa,CharCode:()=>rt,SURROGATE_HIGH:()=>gi,SURROGATE_LOW:()=>Fr,colorize:()=>tE,combineSurrogates:()=>ta,dirname:()=>Qu,escapeString:()=>de,indent:()=>V,isAlpha:()=>ra,isAlphaOrDecimal:()=>Ku,isColorsEnabled:()=>Ur,isDecimal:()=>Pt,isHex:()=>Yd,isHighSurrogate:()=>kr,isIdentifier:()=>ke,isIdentifierPart:()=>Or,isIdentifierStart:()=>Ti,isLineBreak:()=>mt,isLowSurrogate:()=>Pr,isOctal:()=>ia,isPowerOf2:()=>ht,isSurrogate:()=>Vd,isSurrogateHigh:()=>zd,isSurrogateLow:()=>Wd,isWhiteSpace:()=>ea,normalizePath:()=>rr,readF32:()=>Dd,readF64:()=>Bd,readI16:()=>Ud,readI32:()=>Lr,readI64:()=>Xu,readI8:()=>Md,readV128:()=>Gd,resolvePath:()=>Un,setColorsEnabled:()=>Bn,uniqueMap:()=>re,v128_zero:()=>pa,writeF32:()=>$t,writeF64:()=>er,writeI16:()=>kt,writeI32:()=>ce,writeI32AsI64:()=>kn,writeI64:()=>Cr,writeI64AsI32:()=>Js,writeI8:()=>pe,writeV128:()=>$s});function Md(r,e){return r[e]}function pe(r,e,t){e[t]=r}function Ud(r,e){return i32(r[e])|i32(r[e+1])<<8}function kt(r,e,t){e[t]=r,e[t+1]=r>>>8}function Lr(r,e){return i32(r[e])|i32(r[e+1])<<8|i32(r[e+2])<<16|i32(r[e+3])<<24}function ce(r,e,t){e[t]=r,e[t+1]=r>>>8,e[t+2]=r>>>16,e[t+3]=r>>>24}function kn(r,e,t,i=!1){ce(r,e,t),ce(i||r>=0?0:-1,e,t+4)}function Xu(r,e){var t=Lr(r,e),i=Lr(r,e+4);return i64_new(t,i)}function Cr(r,e,t){ce(i64_low(r),e,t),ce(i64_high(r),e,t+4)}function Js(r,e,t,i=!1){assert(i?i64_is_u32(r):i64_is_i32(r)),ce(i64_low(r),e,t)}function Dd(r,e){return i32_as_f32(Lr(r,e))}function $t(r,e,t){ce(f32_as_i32(r),e,t)}function Bd(r,e){return i64_as_f64(Xu(r,e))}function er(r,e,t){var i=f64_as_i64(r);ce(i64_low(i),e,t),ce(i64_high(i),e,t+4)}function Gd(r,e){return r.slice(e,e+16)}function $s(r,e,t){assert(r.length==16),e.set(r,t)}function re(r=null,e=null){var t=new Map;if(r)for(let i=Map_keys(r),n=0,s=i.length;n(A[A.NULL=0]="NULL",A[A.LINEFEED=10]="LINEFEED",A[A.CARRIAGERETURN=13]="CARRIAGERETURN",A[A.LINESEPARATOR=8232]="LINESEPARATOR",A[A.PARAGRAPHSEPARATOR=8233]="PARAGRAPHSEPARATOR",A[A.NEXTLINE=133]="NEXTLINE",A[A.SPACE=32]="SPACE",A[A.NONBREAKINGSPACE=160]="NONBREAKINGSPACE",A[A.ENQUAD=8192]="ENQUAD",A[A.EMQUAD=8193]="EMQUAD",A[A.ENSPACE=8194]="ENSPACE",A[A.EMSPACE=8195]="EMSPACE",A[A.THREEPEREMSPACE=8196]="THREEPEREMSPACE",A[A.FOURPEREMSPACE=8197]="FOURPEREMSPACE",A[A.SIXPEREMSPACE=8198]="SIXPEREMSPACE",A[A.FIGURESPACE=8199]="FIGURESPACE",A[A.PUNCTUATIONSPACE=8200]="PUNCTUATIONSPACE",A[A.THINSPACE=8201]="THINSPACE",A[A.HAIRSPACE=8202]="HAIRSPACE",A[A.ZEROWIDTHSPACE=8203]="ZEROWIDTHSPACE",A[A.NARROWNOBREAKSPACE=8239]="NARROWNOBREAKSPACE",A[A.IDEOGRAPHICSPACE=12288]="IDEOGRAPHICSPACE",A[A.MATHEMATICALSPACE=8287]="MATHEMATICALSPACE",A[A.OGHAM=5760]="OGHAM",A[A._=95]="_",A[A._0=48]="_0",A[A._1=49]="_1",A[A._2=50]="_2",A[A._3=51]="_3",A[A._4=52]="_4",A[A._5=53]="_5",A[A._6=54]="_6",A[A._7=55]="_7",A[A._8=56]="_8",A[A._9=57]="_9",A[A.a=97]="a",A[A.b=98]="b",A[A.c=99]="c",A[A.d=100]="d",A[A.e=101]="e",A[A.f=102]="f",A[A.g=103]="g",A[A.h=104]="h",A[A.i=105]="i",A[A.j=106]="j",A[A.k=107]="k",A[A.l=108]="l",A[A.m=109]="m",A[A.n=110]="n",A[A.o=111]="o",A[A.p=112]="p",A[A.q=113]="q",A[A.r=114]="r",A[A.s=115]="s",A[A.t=116]="t",A[A.u=117]="u",A[A.v=118]="v",A[A.w=119]="w",A[A.x=120]="x",A[A.y=121]="y",A[A.z=122]="z",A[A.A=65]="A",A[A.B=66]="B",A[A.C=67]="C",A[A.D=68]="D",A[A.E=69]="E",A[A.F=70]="F",A[A.G=71]="G",A[A.H=72]="H",A[A.I=73]="I",A[A.J=74]="J",A[A.K=75]="K",A[A.L=76]="L",A[A.M=77]="M",A[A.N=78]="N",A[A.O=79]="O",A[A.P=80]="P",A[A.Q=81]="Q",A[A.R=82]="R",A[A.S=83]="S",A[A.T=84]="T",A[A.U=85]="U",A[A.V=86]="V",A[A.W=87]="W",A[A.X=88]="X",A[A.Y=89]="Y",A[A.Z=90]="Z",A[A.AMPERSAND=38]="AMPERSAND",A[A.ASTERISK=42]="ASTERISK",A[A.AT=64]="AT",A[A.BACKSLASH=92]="BACKSLASH",A[A.BACKTICK=96]="BACKTICK",A[A.BAR=124]="BAR",A[A.CARET=94]="CARET",A[A.CLOSEBRACE=125]="CLOSEBRACE",A[A.CLOSEBRACKET=93]="CLOSEBRACKET",A[A.CLOSEPAREN=41]="CLOSEPAREN",A[A.COLON=58]="COLON",A[A.COMMA=44]="COMMA",A[A.DOLLAR=36]="DOLLAR",A[A.DOT=46]="DOT",A[A.DOUBLEQUOTE=34]="DOUBLEQUOTE",A[A.EQUALS=61]="EQUALS",A[A.EXCLAMATION=33]="EXCLAMATION",A[A.GREATERTHAN=62]="GREATERTHAN",A[A.HASH=35]="HASH",A[A.LESSTHAN=60]="LESSTHAN",A[A.MINUS=45]="MINUS",A[A.OPENBRACE=123]="OPENBRACE",A[A.OPENBRACKET=91]="OPENBRACKET",A[A.OPENPAREN=40]="OPENPAREN",A[A.PERCENT=37]="PERCENT",A[A.PLUS=43]="PLUS",A[A.QUESTION=63]="QUESTION",A[A.SEMICOLON=59]="SEMICOLON",A[A.SINGLEQUOTE=39]="SINGLEQUOTE",A[A.SLASH=47]="SLASH",A[A.TILDE=126]="TILDE",A[A.BACKSPACE=8]="BACKSPACE",A[A.FORMFEED=12]="FORMFEED",A[A.BYTEORDERMARK=65279]="BYTEORDERMARK",A[A.TAB=9]="TAB",A[A.VERTICALTAB=11]="VERTICALTAB",A))(rt||{});function mt(r){switch(r){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}function ea(r){switch(r){case 32:case 9:case 11:case 12:case 160:case 133:case 5760:case 8239:case 8287:case 12288:case 65279:return!0;default:return r>=8192&&r<=8203}}var gi=55296,Fr=56320;function Vd(r){return(r&63488)==gi}function zd(r){return r=Fr}function kr(r){return(r&64512)==gi}function Pr(r){return(r&64512)==Fr}function ta(r,e){return 65536+((r&1023)<<10)|e&1023}function ra(r){let e=r|32;return e>=97&&e<=122}function Pt(r){return r>=48&&r<=57}function ia(r){return r>=48&&r<=55}function Yd(r){let e=r|32;return Pt(r)||e>=97&&e<=102}function Ku(r){return ra(r)||Pt(r)}function Ti(r){return ra(r)||r==95||r==36||r>=170&&r<=65500&&qu(r,Hd)}function Or(r){return Ku(r)||r==95||r==36||r>=170&&r<=65500&&qu(r,Xd)}function ke(r){var e=r.length;if(!e||!Ti(r.charCodeAt(0)))return!1;for(let t=1;t>>1),n-=n&1,s=e[n],s<=r&&r<=e[n+1])return!0;r=4;)r.push(Qd),e-=4;e>=2&&(r.push(qd),e-=2),e&&r.push(Kd)}function de(r,e){var t=new Array,i=0,n=0;for(let s=r.length;ni&&t.push(r.substring(i,i=n+1)),t.push("\\0"),i=++n;break}case 8:{n>i&&t.push(r.substring(i,n)),i=++n,t.push("\\b");break}case 9:{n>i&&t.push(r.substring(i,n)),i=++n,t.push("\\t");break}case 10:{n>i&&t.push(r.substring(i,n)),i=++n,t.push("\\n");break}case 11:{n>i&&t.push(r.substring(i,n)),i=++n,t.push("\\v");break}case 12:{n>i&&t.push(r.substring(i,n)),i=++n,t.push("\\f");break}case 13:{n>i&&t.push(r.substring(i,n)),t.push("\\r"),i=++n;break}case 34:{e==34?(n>i&&t.push(r.substring(i,n)),t.push('\\"'),i=++n):++n;break}case 39:{e==39?(n>i&&t.push(r.substring(i,n)),t.push("\\'"),i=++n):++n;break}case 92:{n>i&&t.push(r.substring(i,n)),t.push("\\\\"),i=++n;break}case 96:{e==96?(n>i&&t.push(r.substring(i,n)),t.push("\\`"),i=++n):++n;break}default:{++n;break}}return n>i&&t.push(r.substring(i,n)),t.join("")}var Ot=(S=>(S[S.NONE=0]="NONE",S[S.SIGN_EXTENSION=1]="SIGN_EXTENSION",S[S.MUTABLE_GLOBALS=2]="MUTABLE_GLOBALS",S[S.NONTRAPPING_F2I=4]="NONTRAPPING_F2I",S[S.BULK_MEMORY=8]="BULK_MEMORY",S[S.SIMD=16]="SIMD",S[S.THREADS=32]="THREADS",S[S.EXCEPTION_HANDLING=64]="EXCEPTION_HANDLING",S[S.TAIL_CALLS=128]="TAIL_CALLS",S[S.REFERENCE_TYPES=256]="REFERENCE_TYPES",S[S.MULTI_VALUE=512]="MULTI_VALUE",S[S.GC=1024]="GC",S[S.MEMORY64=2048]="MEMORY64",S[S.FUNCTION_REFERENCES=4096]="FUNCTION_REFERENCES",S[S.RELAXED_SIMD=8192]="RELAXED_SIMD",S[S.EXTENDED_CONST=16384]="EXTENDED_CONST",S))(Ot||{});function wr(r){switch(r){case 1:return"sign-extension";case 2:return"mutable-globals";case 4:return"nontrapping-f2i";case 8:return"bulk-memory";case 16:return"simd";case 32:return"threads";case 64:return"exception-handling";case 128:return"tail-calls";case 256:return"reference-types";case 512:return"multi-value";case 1024:return"gc";case 2048:return"memory64"}return assert(!1),""}var Mr=(i=>(i[i.JS=0]="JS",i[i.WASM32=1]="WASM32",i[i.WASM64=2]="WASM64",i))(Mr||{});var Pn=(i=>(i[i.Stub=0]="Stub",i[i.Minimal=1]="Minimal",i[i.Incremental=2]="Incremental",i))(Pn||{});var bi=class{constructor(){this.flags=Ii.NONE;this.base=0}};bi=Yu([unmanaged],bi);var Ii=(z=>(z[z.NONE=0]="NONE",z[z.ARRAYBUFFERVIEW=1]="ARRAYBUFFERVIEW",z[z.ARRAY=2]="ARRAY",z[z.STATICARRAY=4]="STATICARRAY",z[z.SET=8]="SET",z[z.MAP=16]="MAP",z[z.POINTERFREE=32]="POINTERFREE",z[z.VALUE_ALIGN_0=64]="VALUE_ALIGN_0",z[z.VALUE_ALIGN_1=128]="VALUE_ALIGN_1",z[z.VALUE_ALIGN_2=256]="VALUE_ALIGN_2",z[z.VALUE_ALIGN_3=512]="VALUE_ALIGN_3",z[z.VALUE_ALIGN_4=1024]="VALUE_ALIGN_4",z[z.VALUE_SIGNED=2048]="VALUE_SIGNED",z[z.VALUE_FLOAT=4096]="VALUE_FLOAT",z[z.VALUE_NULLABLE=8192]="VALUE_NULLABLE",z[z.VALUE_MANAGED=16384]="VALUE_MANAGED",z[z.KEY_ALIGN_0=32768]="KEY_ALIGN_0",z[z.KEY_ALIGN_1=65536]="KEY_ALIGN_1",z[z.KEY_ALIGN_2=131072]="KEY_ALIGN_2",z[z.KEY_ALIGN_3=262144]="KEY_ALIGN_3",z[z.KEY_ALIGN_4=524288]="KEY_ALIGN_4",z[z.KEY_SIGNED=1048576]="KEY_SIGNED",z[z.KEY_FLOAT=2097152]="KEY_FLOAT",z[z.KEY_NULLABLE=4194304]="KEY_NULLABLE",z[z.KEY_MANAGED=8388608]="KEY_MANAGED",z))(Ii||{});var Pe=(D=>(D[D.NONE=0]="NONE",D[D.IMPORT=1]="IMPORT",D[D.EXPORT=2]="EXPORT",D[D.DECLARE=4]="DECLARE",D[D.CONST=8]="CONST",D[D.LET=16]="LET",D[D.STATIC=32]="STATIC",D[D.READONLY=64]="READONLY",D[D.ABSTRACT=128]="ABSTRACT",D[D.PUBLIC=256]="PUBLIC",D[D.PRIVATE=512]="PRIVATE",D[D.PROTECTED=1024]="PROTECTED",D[D.GET=2048]="GET",D[D.SET=4096]="SET",D[D.DEFINITELY_ASSIGNED=8192]="DEFINITELY_ASSIGNED",D[D.AMBIENT=16384]="AMBIENT",D[D.GENERIC=32768]="GENERIC",D[D.GENERIC_CONTEXT=65536]="GENERIC_CONTEXT",D[D.INSTANCE=131072]="INSTANCE",D[D.CONSTRUCTOR=262144]="CONSTRUCTOR",D[D.MODULE_EXPORT=524288]="MODULE_EXPORT",D[D.MODULE_IMPORT=1048576]="MODULE_IMPORT",D[D.RESOLVED=2097152]="RESOLVED",D[D.COMPILED=4194304]="COMPILED",D[D.ERRORED=8388608]="ERRORED",D[D.INLINED=16777216]="INLINED",D[D.SCOPED=33554432]="SCOPED",D[D.STUB=67108864]="STUB",D[D.VIRTUAL=134217728]="VIRTUAL",D[D.CLOSURE=268435456]="CLOSURE",D[D.QUOTED=536870912]="QUOTED",D))(Pe||{}),Qe="/",Zd="..",On="get:",wn="set:",vi="#",xi=".",na="~",Mn="~lib",Ze=Mn+Qe,Le=Qe+"index",sa="@",O;(B=>(B.EMPTY="",B.i8="i8",B.i16="i16",B.i32="i32",B.i64="i64",B.isize="isize",B.u8="u8",B.u16="u16",B.u32="u32",B.u64="u64",B.usize="usize",B.bool="bool",B.f32="f32",B.f64="f64",B.v128="v128",B.funcref="funcref",B.externref="externref",B.anyref="anyref",B.eqref="eqref",B.i31ref="i31ref",B.dataref="dataref",B.i8x16="i8x16",B.u8x16="u8x16",B.i16x8="i16x8",B.u16x8="u16x8",B.i32x4="i32x4",B.u32x4="u32x4",B.i64x2="i64x2",B.u64x2="u64x2",B.f32x4="f32x4",B.f64x2="f64x2",B.void_="void",B.number="number",B.boolean="boolean",B.string="string",B.native="native",B.indexof="indexof",B.valueof="valueof",B.returnof="returnof",B.nonnull="nonnull",B.null_="null",B.true_="true",B.false_="false",B.this_="this",B.super_="super",B.constructor="constructor",B.ASC_TARGET="ASC_TARGET",B.ASC_RUNTIME="ASC_RUNTIME",B.ASC_NO_ASSERT="ASC_NO_ASSERT",B.ASC_MEMORY_BASE="ASC_MEMORY_BASE",B.ASC_TABLE_BASE="ASC_TABLE_BASE",B.ASC_OPTIMIZE_LEVEL="ASC_OPTIMIZE_LEVEL",B.ASC_SHRINK_LEVEL="ASC_SHRINK_LEVEL",B.ASC_LOW_MEMORY_LIMIT="ASC_LOW_MEMORY_LIMIT",B.ASC_EXPORT_RUNTIME="ASC_EXPORT_RUNTIME",B.ASC_WASI="ASC_WASI",B.ASC_FEATURE_SIGN_EXTENSION="ASC_FEATURE_SIGN_EXTENSION",B.ASC_FEATURE_MUTABLE_GLOBALS="ASC_FEATURE_MUTABLE_GLOBALS",B.ASC_FEATURE_NONTRAPPING_F2I="ASC_FEATURE_NONTRAPPING_F2I",B.ASC_FEATURE_BULK_MEMORY="ASC_FEATURE_BULK_MEMORY",B.ASC_FEATURE_SIMD="ASC_FEATURE_SIMD",B.ASC_FEATURE_THREADS="ASC_FEATURE_THREADS",B.ASC_FEATURE_EXCEPTION_HANDLING="ASC_FEATURE_EXCEPTION_HANDLING",B.ASC_FEATURE_TAIL_CALLS="ASC_FEATURE_TAIL_CALLS",B.ASC_FEATURE_REFERENCE_TYPES="ASC_FEATURE_REFERENCE_TYPES",B.ASC_FEATURE_MULTI_VALUE="ASC_FEATURE_MULTI_VALUE",B.ASC_FEATURE_GC="ASC_FEATURE_GC",B.ASC_FEATURE_MEMORY64="ASC_FEATURE_MEMORY64",B.ASC_FEATURE_FUNCTION_REFERENCES="ASC_FEATURE_FUNCTION_REFERENCES",B.ASC_FEATURE_RELAXED_SIMD="ASC_FEATURE_RELAXED_SIMD",B.ASC_FEATURE_EXTENDED_CONST="ASC_FEATURE_EXTENDED_CONST",B.ASC_VERSION_MAJOR="ASC_VERSION_MAJOR",B.ASC_VERSION_MINOR="ASC_VERSION_MINOR",B.ASC_VERSION_PATCH="ASC_VERSION_PATCH",B.I8="I8",B.I16="I16",B.I32="I32",B.I64="I64",B.Isize="Isize",B.U8="U8",B.U16="U16",B.U32="U32",B.U64="U64",B.Usize="Usize",B.Bool="Bool",B.F32="F32",B.F64="F64",B.V128="V128",B.Funcref="Funcref",B.Externref="Externref",B.Anyref="Anyref",B.Eqref="Eqref",B.I31ref="I31ref",B.Dataref="Dataref",B.String="String",B.Object="Object",B.Array="Array",B.StaticArray="StaticArray",B.Set="Set",B.Map="Map",B.Function="Function",B.ArrayBufferView="ArrayBufferView",B.ArrayBuffer="ArrayBuffer",B.Math="Math",B.Mathf="Mathf",B.NativeMath="NativeMath",B.NativeMathf="NativeMathf",B.Int8Array="Int8Array",B.Int16Array="Int16Array",B.Int32Array="Int32Array",B.Int64Array="Int64Array",B.Uint8Array="Uint8Array",B.Uint8ClampedArray="Uint8ClampedArray",B.Uint16Array="Uint16Array",B.Uint32Array="Uint32Array",B.Uint64Array="Uint64Array",B.Float32Array="Float32Array",B.Float64Array="Float64Array",B.TemplateStringsArray="TemplateStringsArray",B.Error="Error",B.abort="abort",B.trace="trace",B.seed="seed",B.pow="pow",B.ipow32="ipow32",B.ipow64="ipow64",B.mod="mod",B.alloc="__alloc",B.realloc="__realloc",B.free="__free",B.new_="__new",B.renew="__renew",B.link="__link",B.collect="__collect",B.typeinfo="__typeinfo",B.instanceof_="__instanceof",B.visit="__visit",B.newBuffer="__newBuffer",B.newArray="__newArray",B.BLOCK="~lib/rt/common/BLOCK",B.OBJECT="~lib/rt/common/OBJECT"))(O||={});var tr=47;function rr(r){for(var e=0,t=r.length;e+10||t=0;)if(r.charCodeAt(n)==tr){(e-n!=3||r.charCodeAt(n+1)!=46||r.charCodeAt(n+2)!=46)&&(r=i?r.substring(0,n):r.substring(0,n)+r.substring(e+3),t-=e+3-n,e=n-1);break}if(n<0&&e>0&&(e!=2||r.charCodeAt(0)!=46||r.charCodeAt(1)!=46)){r=r.substring(e+4),t=r.length;continue}}}e++}return t>0?r:"."}function Un(r,e){return r.startsWith("std/")?r:rr(Qu(e)+Qe+r)}function Qu(r){var e=r.length;if(e<=1){if(e==0)return".";if(r.charCodeAt(0)==tr)return r}for(;--e>0;)if(r.charCodeAt(e)==tr)return r.substring(0,e);return"."}var jd="\x1B[90m",Dn="\x1B[91m",Jd="\x1B[92m",aa="\x1B[93m",$d="\x1B[94m",oa="\x1B[95m",la="\x1B[96m",eE="\x1B[97m",Si="\x1B[0m",ua=!0;function Ur(){return ua}function Bn(r){var e=r;return ua=r,e}function tE(r,e){return ua?e+r+Si:r}var pa=new Uint8Array(16);var Vn=(n=>(n[n.PEDANTIC=0]="PEDANTIC",n[n.INFO=1]="INFO",n[n.WARNING=2]="WARNING",n[n.ERROR=3]="ERROR",n))(Vn||{});function Gn(r){switch(r){case 0:return"PEDANTIC";case 1:return"INFO";case 2:return"WARNING";case 3:return"ERROR";default:return assert(!1),""}}function ju(r){switch(r){case 0:return oa;case 1:return la;case 2:return aa;case 3:return Dn;default:return assert(!1),""}}var Ri=class{constructor(e,t,i){this.range=null;this.relatedRange=null;this.code=e,this.category=t,this.message=i}static create(e,t,i=null,n=null,s=null){var a=Fn(e);return i!=null&&(a=a.replace("{0}",i)),n!=null&&(a=a.replace("{1}",n)),s!=null&&(a=a.replace("{2}",s)),new Ri(e,t,a)}equals(e){if(this.code!=e.code)return!1;var t=this.range,i=e.range;if(t){if(!i||!t.equals(i))return!1}else if(i)return!1;var n=this.relatedRange,s=e.relatedRange;if(n){if(!s||!n.equals(s))return!1}else if(s)return!1;return this.message==e.message}withRange(e){return this.range=e,this}withRelatedRange(e){return this.relatedRange=e,this}toString(){var e=this.range;if(e){let t=e.source;return Gn(this.category)+" "+this.code.toString()+': "'+this.message+'" in '+t.normalizedPath+"("+t.lineAt(e.start).toString()+","+t.columnAt().toString()+"+"+(e.end-e.start).toString()+")"}return Gn(this.category)+" "+this.code.toString()+": "+this.message}};function Ju(r,e=!1,t=!1){var i=Bn(e),n=[];Ur()&&n.push(ju(r.category)),n.push(Gn(r.category)),Ur()&&n.push(Si),n.push(r.code<1e3?" AS":" TS"),n.push(r.code.toString()),n.push(": "),n.push(r.message);var s=r.range;if(s){let a=s.source;t&&(n.push(` +`),n.push(Zu(s))),n.push(` +`),n.push(" in "),n.push(a.normalizedPath),n.push("("),n.push(a.lineAt(s.start).toString()),n.push(","),n.push(a.columnAt().toString()),n.push(")");let o=r.relatedRange;if(o){let l=o.source;t&&(n.push(` +`),n.push(Zu(o))),n.push(` +`),n.push(" in "),n.push(l.normalizedPath),n.push("("),n.push(l.lineAt(o.start).toString()),n.push(","),n.push(l.columnAt().toString()),n.push(")")}}return Bn(i),n.join("")}function Zu(r){for(var e=r.source.text,t=e.length,i=r.start,n=r.end;i>0&&!mt(e.charCodeAt(i-1));)i--;for(;n(F[F.I8=0]="I8",F[F.I16=1]="I16",F[F.I32=2]="I32",F[F.I64=3]="I64",F[F.ISIZE=4]="ISIZE",F[F.U8=5]="U8",F[F.U16=6]="U16",F[F.U32=7]="U32",F[F.U64=8]="U64",F[F.USIZE=9]="USIZE",F[F.BOOL=10]="BOOL",F[F.F32=11]="F32",F[F.F64=12]="F64",F[F.V128=13]="V128",F[F.FUNCREF=14]="FUNCREF",F[F.EXTERNREF=15]="EXTERNREF",F[F.ANYREF=16]="ANYREF",F[F.EQREF=17]="EQREF",F[F.I31REF=18]="I31REF",F[F.DATAREF=19]="DATAREF",F[F.VOID=20]="VOID",F))(ir||{}),wt=(b=>(b[b.NONE=0]="NONE",b[b.SIGNED=1]="SIGNED",b[b.UNSIGNED=2]="UNSIGNED",b[b.INTEGER=4]="INTEGER",b[b.FLOAT=8]="FLOAT",b[b.VARYING=16]="VARYING",b[b.SHORT=32]="SHORT",b[b.LONG=64]="LONG",b[b.VALUE=128]="VALUE",b[b.REFERENCE=256]="REFERENCE",b[b.NULLABLE=512]="NULLABLE",b[b.VECTOR=1024]="VECTOR",b[b.EXTERNAL=2048]="EXTERNAL",b[b.CLASS=4096]="CLASS",b[b.FUNCTION=8192]="FUNCTION",b))(wt||{}),$=class{constructor(e,t,i){this._nonNullableType=null;this._nullableType=null;this.kind=e,this.flags=t,this.size=i,this.byteSize=ceil(i/8),this.classReference=null,this.signatureReference=null,t&512?this._nullableType=this:this._nonNullableType=this}get intType(){if(this==$.auto)return this;switch(this.kind){case 0:return $.i8;case 1:return $.i16;case 11:case 2:return $.i32;case 12:case 3:return $.i64;case 4:return this.size==64?$.isize64:$.isize32;case 5:return $.u8;case 6:return $.u16;case 7:return $.u32;case 8:return $.u64;case 9:return this.size==64?$.usize64:$.usize32;case 10:default:return $.i32}}get exceptVoid(){return this.kind==20?$.auto:this}get alignLog2(){return 31-clz(this.byteSize)}get isValue(){return this.is(128)}get isIntegerValue(){return this.is(132)}get isShortIntegerValue(){return this.is(164)}get isLongIntegerValue(){return this.is(196)}get isSignedIntegerValue(){return this.is(133)}get isUnsignedIntegerValue(){return this.is(134)}get isVaryingIntegerValue(){return this.is(148)}get isIntegerInclReference(){return this.is(4)}get isFloatValue(){return this.is(136)}get isNumericValue(){return this.isIntegerValue||this.isFloatValue}get isBooleanValue(){return this==$.bool}get isVectorValue(){return this.is(1152)}get isReference(){return this.is(256)}get isNullableReference(){return this.is(768)}get isInternalReference(){return this.is(260)}get isExternalReference(){return this.is(2304)}get isClass(){return this.isInternalReference?this.classReference!=null:!1}getClass(){return this.isInternalReference?this.classReference:null}getClassOrWrapper(e){let t=this.getClass();if(t)return t;{let i=this.getSignature();if(i){let n=i.type,s=assert(e.resolver.resolveClass(e.functionPrototype,[n]));return s.wrappedType=n,s}else{let n=e.wrapperClasses;if(n.has(this))return assert(n.get(this))}}return null}get isFunction(){return this.isInternalReference?this.signatureReference!=null:!1}getSignature(){return this.isInternalReference?this.signatureReference:null}get isManaged(){if(this.isInternalReference){let e=this.classReference;return e?!e.hasDecorator(16):this.signatureReference!=null}return!1}get isUnmanaged(){var e=this.classReference;return e!=null&&e.hasDecorator(16)}get nonNullableType(){return this.isExternalReference?this:assert(this._nonNullableType)}get nullableType(){return this._nullableType}computeSmallIntegerShift(e){return e.size-this.size}computeSmallIntegerMask(e){var t=this.is(2)?this.size:this.size-1;return-1>>>e.size-t}is(e){return(this.flags&e)==e}isAny(e){return(this.flags&e)!=0}asNullable(){assert(this.isInternalReference);var e=this._nullableType;return e||(assert(!this.isNullableReference),this._nullableType=e=new $(this.kind,this.flags|512,this.size),e.classReference=this.classReference,e.signatureReference=this.signatureReference,e._nonNullableType=this),e}equals(e){return this.kind!=e.kind?!1:this.isReference?this.classReference==e.classReference&&this.signatureReference==e.signatureReference&&this.isNullableReference==e.isNullableReference:!0}isAssignableTo(e,t=!1){var i,n,s,a;if(this.isReference){if(e.isReference&&(!this.isNullableReference||e.isNullableReference)){if(i=this.getClass()){if(n=e.getClass())return i.isAssignableTo(n)}else if(s=this.getSignature()){if(a=e.getSignature())return s.isAssignableTo(a)}else if(this.isExternalReference&&(this.kind==e.kind||e.kind==16&&this.kind!=15))return!0}}else if(!e.isReference){if(this.isIntegerValue)if(e.isIntegerValue){if(!t||this.isBooleanValue||this.isSignedIntegerValue==e.isSignedIntegerValue)return this.size<=e.size}else{if(e.kind==11)return this.size<=23;if(e.kind==12)return this.size<=52}else if(this.isFloatValue){if(e.isFloatValue)return this.size<=e.size}else if(this.isVectorValue&&e.isVectorValue)return this.size==e.size}return!1}isStrictlyAssignableTo(e,t=!1){return this.isReference?this.isAssignableTo(e):e.isReference?!1:this.isIntegerValue?e.isIntegerValue&&e.size==this.size&&(!t||this.isSignedIntegerValue==e.isSignedIntegerValue):this.kind==e.kind}isChangeableTo(e){if(this.is(4)&&e.is(4)){let t=this.size;return t==e.size&&(t>=32||this.is(1)==e.is(1))}return this.kind==e.kind}static commonDenominator(e,t,i){return t.isAssignableTo(e,i)?e:e.isAssignableTo(t,i)?t:null}toString(e=!1){let t=e?"|null":" | null";if(this.isReference){let i=this.getClass();if(i)return this.isNullableReference?i.internalName+t:i.internalName;{let n=this.getSignature();if(n)return this.isNullableReference?"("+n.toString(e)+")"+t:n.toString(e)}}switch(this.kind){case 0:return"i8";case 1:return"i16";case 2:return"i32";case 3:return"i64";case 4:return"isize";case 5:return"u8";case 6:return"u16";case 7:return"u32";case 8:return"u64";case 9:return"usize";case 10:return"bool";case 11:return"f32";case 12:return"f64";case 13:return"v128";case 14:return"funcref";case 15:return"externref";case 16:return"anyref";case 17:return"eqref";case 18:return"i31ref";case 19:return"dataref";default:assert(!1);case 20:return"void"}}toRef(){switch(this.kind){default:assert(!1);case 0:case 1:case 2:case 5:case 6:case 7:case 10:return C.I32;case 4:case 9:if(this.size!=64)return C.I32;case 3:case 8:return C.I64;case 11:return C.F32;case 12:return C.F64;case 13:return C.V128;case 14:return C.Funcref;case 15:return C.Externref;case 16:return C.Anyref;case 17:return C.Eqref;case 18:return C.I31ref;case 19:return C.Dataref;case 20:return C.None}}},u=$;u.i8=new $(0,165,8),u.i16=new $(1,165,16),u.i32=new $(2,133,32),u.i64=new $(3,197,64),u.isize32=new $(4,149,32),u.isize64=new $(4,213,64),u.u8=new $(5,166,8),u.u16=new $(6,166,16),u.u32=new $(7,134,32),u.u64=new $(8,198,64),u.usize32=new $(9,150,32),u.usize64=new $(9,214,64),u.bool=new $(10,166,1),u.f32=new $(11,137,32),u.f64=new $(12,201,64),u.v128=new $(13,1152,128),u.funcref=new $(14,2816,0),u.externref=new $(15,2816,0),u.anyref=new $(16,2816,0),u.eqref=new $(17,2816,0),u.i31ref=new $(18,2304,0),u.dataref=new $(19,2816,0),u.void=new $(20,0,0),u.auto=new $($.i32.kind,$.i32.flags,$.i32.size);function Dr(r){var e=r.length,t=new Array(e);for(let i=0;i=o&&p!=l&&t.push("?")}return t.push(e?"%29=>":") => "),t.push(this.returnType.toString(e)),t.join("")}clone(){var e=this.parameterTypes,t=e.length,i=new Array(t);for(let n=0;n(G[G.SOURCE=0]="SOURCE",G[G.NAMEDTYPE=1]="NAMEDTYPE",G[G.FUNCTIONTYPE=2]="FUNCTIONTYPE",G[G.TYPENAME=3]="TYPENAME",G[G.TYPEPARAMETER=4]="TYPEPARAMETER",G[G.PARAMETER=5]="PARAMETER",G[G.IDENTIFIER=6]="IDENTIFIER",G[G.ASSERTION=7]="ASSERTION",G[G.BINARY=8]="BINARY",G[G.CALL=9]="CALL",G[G.CLASS=10]="CLASS",G[G.COMMA=11]="COMMA",G[G.ELEMENTACCESS=12]="ELEMENTACCESS",G[G.FALSE=13]="FALSE",G[G.FUNCTION=14]="FUNCTION",G[G.INSTANCEOF=15]="INSTANCEOF",G[G.LITERAL=16]="LITERAL",G[G.NEW=17]="NEW",G[G.NULL=18]="NULL",G[G.OMITTED=19]="OMITTED",G[G.PARENTHESIZED=20]="PARENTHESIZED",G[G.PROPERTYACCESS=21]="PROPERTYACCESS",G[G.TERNARY=22]="TERNARY",G[G.SUPER=23]="SUPER",G[G.THIS=24]="THIS",G[G.TRUE=25]="TRUE",G[G.CONSTRUCTOR=26]="CONSTRUCTOR",G[G.UNARYPOSTFIX=27]="UNARYPOSTFIX",G[G.UNARYPREFIX=28]="UNARYPREFIX",G[G.COMPILED=29]="COMPILED",G[G.BLOCK=30]="BLOCK",G[G.BREAK=31]="BREAK",G[G.CONTINUE=32]="CONTINUE",G[G.DO=33]="DO",G[G.EMPTY=34]="EMPTY",G[G.EXPORT=35]="EXPORT",G[G.EXPORTDEFAULT=36]="EXPORTDEFAULT",G[G.EXPORTIMPORT=37]="EXPORTIMPORT",G[G.EXPRESSION=38]="EXPRESSION",G[G.FOR=39]="FOR",G[G.FOROF=40]="FOROF",G[G.IF=41]="IF",G[G.IMPORT=42]="IMPORT",G[G.RETURN=43]="RETURN",G[G.SWITCH=44]="SWITCH",G[G.THROW=45]="THROW",G[G.TRY=46]="TRY",G[G.VARIABLE=47]="VARIABLE",G[G.VOID=48]="VOID",G[G.WHILE=49]="WHILE",G[G.MODULE=50]="MODULE",G[G.CLASSDECLARATION=51]="CLASSDECLARATION",G[G.ENUMDECLARATION=52]="ENUMDECLARATION",G[G.ENUMVALUEDECLARATION=53]="ENUMVALUEDECLARATION",G[G.FIELDDECLARATION=54]="FIELDDECLARATION",G[G.FUNCTIONDECLARATION=55]="FUNCTIONDECLARATION",G[G.IMPORTDECLARATION=56]="IMPORTDECLARATION",G[G.INTERFACEDECLARATION=57]="INTERFACEDECLARATION",G[G.METHODDECLARATION=58]="METHODDECLARATION",G[G.NAMESPACEDECLARATION=59]="NAMESPACEDECLARATION",G[G.TYPEDECLARATION=60]="TYPEDECLARATION",G[G.VARIABLEDECLARATION=61]="VARIABLEDECLARATION",G[G.DECORATOR=62]="DECORATOR",G[G.EXPORTMEMBER=63]="EXPORTMEMBER",G[G.SWITCHCASE=64]="SWITCHCASE",G[G.INDEXSIGNATURE=65]="INDEXSIGNATURE",G[G.COMMENT=66]="COMMENT",G))(dt||{}),k=class{constructor(e,t){this.kind=e;this.range=t}static createSimpleTypeName(e,t){return new _a(k.createIdentifierExpression(e,t),null,t)}static createNamedType(e,t,i,n){return new Wn(e,t,i,n)}static createFunctionType(e,t,i,n,s){return new fa(e,t,i,n,s)}static createOmittedType(e){return new Wn(k.createSimpleTypeName("",e),null,!1,e)}static createTypeParameter(e,t,i,n){return new ha(e,t,i,n)}static createParameter(e,t,i,n,s){return new ma(e,t,i,n,s)}static createDecorator(e,t,i){return new da(Et.fromNode(e),e,t,i)}static createComment(e,t,i){return new ya(e,t,i)}static createIdentifierExpression(e,t,i=!1){return new it(e,i,t)}static createEmptyIdentifierExpression(e){return new it("",!1,e)}static createArrayLiteralExpression(e,t){return new ga(e,t)}static createAssertionExpression(e,t,i,n){return new Ta(e,t,i,n)}static createBinaryExpression(e,t,i,n){return new ba(e,t,i,n)}static createCallExpression(e,t,i,n){return new Ia(e,t,i,n)}static createClassExpression(e){return new va(e)}static createCommaExpression(e,t){return new xa(e,t)}static createConstructorExpression(e){return new Sa(e)}static createElementAccessExpression(e,t,i){return new Ra(e,t,i)}static createFalseExpression(e){return new Ya(e)}static createFloatLiteralExpression(e,t){return new Aa(e,t)}static createFunctionExpression(e){return new Na(e)}static createInstanceOfExpression(e,t,i){return new La(e,t,i)}static createIntegerLiteralExpression(e,t){return new Ca(e,t)}static createNewExpression(e,t,i,n){return new Fa(e,t,i,n)}static createNullExpression(e){return new ka(e)}static createObjectLiteralExpression(e,t,i){return new Pa(e,t,i)}static createOmittedExpression(e){return new Oa(e)}static createParenthesizedExpression(e,t){return new wa(e,t)}static createPropertyAccessExpression(e,t,i){return new Ma(e,t,i)}static createRegexpLiteralExpression(e,t,i){return new Ua(e,t,i)}static createTernaryExpression(e,t,i,n){return new Da(e,t,i,n)}static createStringLiteralExpression(e,t){return new Ba(e,t)}static createSuperExpression(e){return new Ga(e)}static createTemplateLiteralExpression(e,t,i,n,s){return new Va(e,t,i,n,s)}static createThisExpression(e){return new za(e)}static createTrueExpression(e){return new Wa(e)}static createUnaryPostfixExpression(e,t,i){return new Ha(e,t,i)}static createUnaryPrefixExpression(e,t,i){return new Xa(e,t,i)}static createCompiledExpression(e,t,i){return new Ka(e,t,i)}static createBlockStatement(e,t){return new Qa(e,t)}static createBreakStatement(e,t){return new Za(e,t)}static createClassDeclaration(e,t,i,n,s,a,o,l){return new Kn(e,t,i,n,s,a,o,l)}static createContinueStatement(e,t){return new ja(e,t)}static createDoStatement(e,t,i){return new Ja(e,t,i)}static createEmptyStatement(e){return new $a(e)}static createEnumDeclaration(e,t,i,n,s){return new eo(e,t,i,n,s)}static createEnumValueDeclaration(e,t,i,n){return new to(e,t,i,n)}static createExportStatement(e,t,i,n){return new no(e,t,i,n)}static createExportDefaultStatement(e,t){return new so(e,t)}static createExportImportStatement(e,t,i){return new ro(e,t,i)}static createExportMember(e,t,i){return t||(t=e),new io(e,t,i)}static createExpressionStatement(e){return new ao(e)}static createIfStatement(e,t,i,n){return new po(e,t,i,n)}static createImportStatement(e,t,i){return new Yn(e,null,t,i)}static createWildcardImportStatement(e,t,i){return new Yn(null,e,t,i)}static createImportDeclaration(e,t,i){return t||(t=e),new co(t,e,i)}static createInterfaceDeclaration(e,t,i,n,s,a,o,l){return new _o(e,t,i,n,s,a,o,l)}static createFieldDeclaration(e,t,i,n,s,a){return new oo(e,t,i,n,s,-1,a)}static createForStatement(e,t,i,n,s){return new lo(e,t,i,n,s)}static createForOfStatement(e,t,i,n){return new uo(e,t,i,n)}static createFunctionDeclaration(e,t,i,n,s,a,o,l){return new Wr(e,t,i,n,s,a,o,l)}static createIndexSignature(e,t,i,n){return new qa(e,t,i,n)}static createMethodDeclaration(e,t,i,n,s,a,o){return new fo(e,t,i,n,s,a,o)}static createNamespaceDeclaration(e,t,i,n,s){return new ho(e,t,i,n,s)}static createReturnStatement(e,t){return new mo(e,t)}static createSwitchStatement(e,t,i){return new yo(e,t,i)}static createSwitchCase(e,t,i){return new Eo(e,t,i)}static createThrowStatement(e,t){return new go(e,t)}static createTryStatement(e,t,i,n,s){return new To(e,t,i,n,s)}static createTypeDeclaration(e,t,i,n,s,a){return new Io(e,t,i,n,s,a)}static createModuleDeclaration(e,t,i){return new bo(e,t,i)}static createVariableStatement(e,t,i){return new xo(e,t,i)}static createVariableDeclaration(e,t,i,n,s,a){return new vo(e,t,i,n,s,a)}static createVoidStatement(e,t){return new So(e,t)}static createWhileStatement(e,t,i){return new Ro(e,t,i)}isLiteralKind(e){return this.kind==16&&changetype(this).literalKind==e}get isNumericLiteral(){if(this.kind==16)switch(changetype(this).literalKind){case we.FLOAT:case we.INTEGER:return!0}return!1}get compilesToConst(){switch(this.kind){case 16:{switch(changetype(this).literalKind){case we.FLOAT:case we.INTEGER:case we.STRING:return!0}break}case 18:case 25:case 13:return!0}return!1}isAccessOn(e){let t=changetype(this);return t.kind==9&&(t=t.expression),t.kind==21&&t.expression.kind==e}get isAccessOnThis(){return this.isAccessOn(24)}get isAccessOnSuper(){return this.isAccessOn(23)}},Hn=class extends k{constructor(e,t,i){super(e,i);this.isNullable=t}hasGenericComponent(e){if(this.kind==1){let t=changetype(this);if(!t.name.next){let i=t.typeArguments;if(i&&i.length>0){for(let n=0,s=i.length;n0}},fa=class extends Hn{constructor(e,t,i,n,s){super(2,n,s);this.parameters=e;this.returnType=t;this.explicitThisType=i}},ha=class extends k{constructor(e,t,i,n){super(4,n);this.name=e;this.extendsType=t;this.defaultType=i}},Br=(i=>(i[i.DEFAULT=0]="DEFAULT",i[i.OPTIONAL=1]="OPTIONAL",i[i.REST=2]="REST",i))(Br||{}),ma=class extends k{constructor(e,t,i,n,s){super(5,s);this.parameterKind=e;this.name=t;this.type=i;this.initializer=n;this.implicitFieldDeclaration=null;this.flags=0}is(e){return(this.flags&e)==e}isAny(e){return(this.flags&e)!=0}set(e){this.flags|=e}},Et=(g=>(g[g.CUSTOM=0]="CUSTOM",g[g.GLOBAL=1]="GLOBAL",g[g.OPERATOR=2]="OPERATOR",g[g.OPERATOR_BINARY=3]="OPERATOR_BINARY",g[g.OPERATOR_PREFIX=4]="OPERATOR_PREFIX",g[g.OPERATOR_POSTFIX=5]="OPERATOR_POSTFIX",g[g.UNMANAGED=6]="UNMANAGED",g[g.FINAL=7]="FINAL",g[g.INLINE=8]="INLINE",g[g.EXTERNAL=9]="EXTERNAL",g[g.EXTERNAL_JS=10]="EXTERNAL_JS",g[g.BUILTIN=11]="BUILTIN",g[g.LAZY=12]="LAZY",g[g.UNSAFE=13]="UNSAFE",g))(Et||{});(e=>{function r(t){if(t.kind==6){let i=t.text;switch(assert(i.length),i.charCodeAt(0)){case 98:{if(i=="builtin")return 11;break}case 101:{if(i=="external")return 9;break}case 102:{if(i=="final")return 7;break}case 103:{if(i=="global")return 1;break}case 105:{if(i=="inline")return 8;break}case 108:{if(i=="lazy")return 12;break}case 111:{if(i=="operator")return 2;break}case 117:{if(i=="unmanaged")return 6;if(i=="unsafe")return 13;break}}}else if(t.kind==21){let i=t,n=i.expression;if(n.kind==6){let s=n.text;assert(s.length);let a=i.property.text;if(assert(a.length),s=="operator")switch(a.charCodeAt(0)){case 98:{if(a=="binary")return 3;break}case 112:{if(a=="prefix")return 4;if(a=="postfix")return 5;break}}else if(s=="external")switch(a.charCodeAt(0)){case 106:{if(a=="js")return 10;break}}}}return 0}e.fromNode=r})(Et||={});var da=class extends k{constructor(e,t,i,n){super(62,n);this.decoratorKind=e;this.name=t;this.args=i}},Ea=(i=>(i[i.LINE=0]="LINE",i[i.TRIPLE=1]="TRIPLE",i[i.BLOCK=2]="BLOCK",i))(Ea||{}),ya=class extends k{constructor(e,t,i){super(66,i);this.commentKind=e;this.text=t}},fe=class extends k{},it=class extends fe{constructor(e,t,i){super(6,i);this.text=e;this.isQuoted=t}},we=(o=>(o[o.FLOAT=0]="FLOAT",o[o.INTEGER=1]="INTEGER",o[o.STRING=2]="STRING",o[o.TEMPLATE=3]="TEMPLATE",o[o.REGEXP=4]="REGEXP",o[o.ARRAY=5]="ARRAY",o[o.OBJECT=6]="OBJECT",o))(we||{}),yt=class extends fe{constructor(e,t){super(16,t);this.literalKind=e}},ga=class extends yt{constructor(e,t){super(5,t);this.elementExpressions=e}},Gr=(n=>(n[n.PREFIX=0]="PREFIX",n[n.AS=1]="AS",n[n.NONNULL=2]="NONNULL",n[n.CONST=3]="CONST",n))(Gr||{}),Ta=class extends fe{constructor(e,t,i,n){super(7,n);this.assertionKind=e;this.expression=t;this.toType=i}},ba=class extends fe{constructor(e,t,i,n){super(8,n);this.operator=e;this.left=t;this.right=i}},Ia=class extends fe{constructor(e,t,i,n){super(9,n);this.expression=e;this.typeArguments=t;this.args=i}get typeArgumentsRange(){var e=this.typeArguments,t;return e&&(t=e.length)?se.join(e[0].range,e[t-1].range):this.expression.range}get argumentsRange(){var e=this.args,t=e.length;return t?se.join(e[0].range,e[t-1].range):this.expression.range}},va=class extends fe{constructor(e){super(10,e.range);this.declaration=e}},xa=class extends fe{constructor(e,t){super(11,t);this.expressions=e}},Sa=class extends it{constructor(e){super("constructor",!1,e);this.kind=26}},Ra=class extends fe{constructor(e,t,i){super(12,i);this.expression=e;this.elementExpression=t}},Aa=class extends yt{constructor(e,t){super(0,t);this.value=e}},Na=class extends fe{constructor(e){super(14,e.range);this.declaration=e}},La=class extends fe{constructor(e,t,i){super(15,i);this.expression=e;this.isType=t}},Ca=class extends yt{constructor(e,t){super(1,t);this.value=e}},Fa=class extends fe{constructor(e,t,i,n){super(17,n);this.typeName=e;this.typeArguments=t;this.args=i}get typeArgumentsRange(){var e=this.typeArguments,t;return e&&(t=e.length)>0?se.join(e[0].range,e[t-1].range):this.typeName.range}get argumentsRange(){var e=this.args,t=e.length;return t?se.join(e[0].range,e[t-1].range):this.typeName.range}},ka=class extends it{constructor(e){super("null",!1,e);this.kind=18}},Pa=class extends yt{constructor(e,t,i){super(6,i);this.names=e;this.values=t}},Oa=class extends fe{constructor(e){super(19,e)}},wa=class extends fe{constructor(e,t){super(20,t);this.expression=e}},Ma=class extends fe{constructor(e,t,i){super(21,i);this.expression=e;this.property=t}},Ua=class extends yt{constructor(e,t,i){super(4,i);this.pattern=e;this.patternFlags=t}},Da=class extends fe{constructor(e,t,i,n){super(22,n);this.condition=e;this.ifThen=t;this.ifElse=i}},Ba=class extends yt{constructor(e,t){super(2,t);this.value=e}},Ga=class extends it{constructor(e){super("super",!1,e);this.kind=23}},Va=class extends yt{constructor(e,t,i,n,s){super(3,s);this.tag=e;this.parts=t;this.rawParts=i;this.expressions=n}},za=class extends it{constructor(e){super("this",!1,e);this.kind=24}},Wa=class extends it{constructor(e){super("true",!1,e);this.kind=25}},Ya=class extends it{constructor(e){super("false",!1,e);this.kind=13}},Xn=class extends fe{constructor(e,t,i,n){super(e,n);this.operator=t;this.operand=i}},Ha=class extends Xn{constructor(e,t,i){super(27,e,t,i)}},Xa=class extends Xn{constructor(e,t,i){super(28,e,t,i)}},Ka=class extends fe{constructor(e,t,i){super(29,i);this.expr=e;this.type=t}},ue=class extends k{},Vr=(n=>(n[n.USER=0]="USER",n[n.USER_ENTRY=1]="USER_ENTRY",n[n.LIBRARY=2]="LIBRARY",n[n.LIBRARY_ENTRY=3]="LIBRARY_ENTRY",n))(Vr||{}),zr=class extends k{constructor(e,t,i){super(0,new se(0,i.length));this.sourceKind=e;this.normalizedPath=t;this.text=i;this.statements=new Array;this.debugInfoIndex=-1;this.exportPaths=null;this.lineCache=null;this.lineColumn=1;var n=Li(t);this.internalPath=n;var s=n.lastIndexOf(Qe);this.simplePath=s>=0?n.substring(s+1):n,this.range.source=this}get isNative(){return this.internalPath==Mn}get isLibrary(){var e=this.sourceKind;return e==2||e==3}lineAt(e){assert(e>=0&&e<2147483647);var t=this.lineCache;if(!t){this.lineCache=t=[0];let s=this.text,a=0,o=s.length;for(;a>1),a=unchecked(t[s]);if(e0}},ja=class extends ue{constructor(e,t){super(32,t);this.label=e}},Ja=class extends ue{constructor(e,t,i){super(33,i);this.statement=e;this.condition=t}},$a=class extends ue{constructor(e){super(34,e)}},eo=class extends We{constructor(e,t,i,n,s){super(52,e,t,i,s);this.values=n}},to=class extends Ai{constructor(e,t,i,n){super(53,e,null,t,null,i,n)}},ro=class extends ue{constructor(e,t,i){super(37,i);this.name=e;this.externalName=t}},io=class extends k{constructor(e,t,i){super(63,i);this.localName=e;this.exportedName=t}},no=class extends ue{constructor(e,t,i,n){super(35,n);this.members=e;this.path=t;this.isDeclare=i;if(t){let s=rr(t.value);t.value.startsWith(".")?s=Un(s,n.source.internalPath):s.startsWith(Ze)||(s=Ze+s),this.internalPath=s}else this.internalPath=null}},so=class extends ue{constructor(e,t){super(36,t);this.declaration=e}},ao=class extends ue{constructor(e){super(38,e.range);this.expression=e}},oo=class extends Ai{constructor(e,t,i,n,s,a,o){super(54,e,t,i,n,s,o);this.parameterIndex=a}},lo=class extends ue{constructor(e,t,i,n,s){super(39,s);this.initializer=e;this.condition=t;this.incrementor=i;this.statement=n}},uo=class extends ue{constructor(e,t,i,n){super(40,n);this.variable=e;this.iterable=t;this.statement=i}},Ni=(i=>(i[i.NONE=0]="NONE",i[i.ARROW_PARENTHESIZED=1]="ARROW_PARENTHESIZED",i[i.ARROW_SINGLE=2]="ARROW_SINGLE",i))(Ni||{}),Wr=class extends We{constructor(e,t,i,n,s,a,o,l){super(55,e,t,i,l);this.typeParameters=n;this.signature=s;this.body=a;this.arrowKind=o}get isGeneric(){var e=this.typeParameters;return e!=null&&e.length>0}clone(){return new Wr(this.name,this.decorators,this.flags,this.typeParameters,this.signature,this.body,this.arrowKind,this.range)}},po=class extends ue{constructor(e,t,i,n){super(41,n);this.condition=e;this.ifTrue=t;this.ifFalse=i}},co=class extends We{constructor(e,t,i){super(56,e,null,0,i);this.foreignName=t}},Yn=class extends ue{constructor(e,t,i,n){super(42,n);this.declarations=e;this.namespaceName=t;this.path=i;var s=rr(i.value);i.value.startsWith(".")?s=Un(s,n.source.internalPath):s.startsWith(Ze)||(s=Ze+s),this.internalPath=Li(s)}},_o=class extends Kn{constructor(e,t,i,n,s,a,o,l){super(e,t,i,n,s,a,o,l);this.kind=57}},fo=class extends Wr{constructor(e,t,i,n,s,a,o){super(e,t,i,n,s,a,0,o);this.kind=58}},ho=class extends We{constructor(e,t,i,n,s){super(59,e,t,i,s);this.members=n}},mo=class extends ue{constructor(e,t){super(43,t);this.value=e}},Eo=class extends k{constructor(e,t,i){super(64,i);this.label=e;this.statements=t}},yo=class extends ue{constructor(e,t,i){super(44,i);this.condition=e;this.cases=t}},go=class extends ue{constructor(e,t){super(45,t);this.value=e}},To=class extends ue{constructor(e,t,i,n,s){super(46,s);this.statements=e;this.catchVariable=t;this.catchStatements=i;this.finallyStatements=n}},bo=class extends ue{constructor(e,t,i){super(50,i);this.moduleName=e;this.flags=t}},Io=class extends We{constructor(e,t,i,n,s,a){super(60,e,t,i,a);this.typeParameters=n;this.type=s}},vo=class extends Ai{constructor(e,t,i,n,s,a){super(61,e,t,i,n,s,a)}},xo=class extends ue{constructor(e,t,i){super(47,i);this.decorators=e;this.declarations=t}},So=class extends ue{constructor(e,t){super(48,t);this.expression=e}},Ro=class extends ue{constructor(e,t,i){super(49,i);this.condition=e;this.statement=t}};function gt(r,e){if(e)for(let t=0,i=e.length;t0)}return!1}var Yr=(N=>(N[N.ABSTRACT=0]="ABSTRACT",N[N.AS=1]="AS",N[N.ASYNC=2]="ASYNC",N[N.AWAIT=3]="AWAIT",N[N.BREAK=4]="BREAK",N[N.CASE=5]="CASE",N[N.CATCH=6]="CATCH",N[N.CLASS=7]="CLASS",N[N.CONST=8]="CONST",N[N.CONTINUE=9]="CONTINUE",N[N.CONSTRUCTOR=10]="CONSTRUCTOR",N[N.DEBUGGER=11]="DEBUGGER",N[N.DECLARE=12]="DECLARE",N[N.DEFAULT=13]="DEFAULT",N[N.DELETE=14]="DELETE",N[N.DO=15]="DO",N[N.ELSE=16]="ELSE",N[N.ENUM=17]="ENUM",N[N.EXPORT=18]="EXPORT",N[N.EXTENDS=19]="EXTENDS",N[N.FALSE=20]="FALSE",N[N.FINALLY=21]="FINALLY",N[N.FOR=22]="FOR",N[N.FROM=23]="FROM",N[N.FUNCTION=24]="FUNCTION",N[N.GET=25]="GET",N[N.IF=26]="IF",N[N.IMPLEMENTS=27]="IMPLEMENTS",N[N.IMPORT=28]="IMPORT",N[N.IN=29]="IN",N[N.INSTANCEOF=30]="INSTANCEOF",N[N.INTERFACE=31]="INTERFACE",N[N.IS=32]="IS",N[N.KEYOF=33]="KEYOF",N[N.LET=34]="LET",N[N.MODULE=35]="MODULE",N[N.NAMESPACE=36]="NAMESPACE",N[N.NEW=37]="NEW",N[N.NULL=38]="NULL",N[N.OF=39]="OF",N[N.PACKAGE=40]="PACKAGE",N[N.PRIVATE=41]="PRIVATE",N[N.PROTECTED=42]="PROTECTED",N[N.PUBLIC=43]="PUBLIC",N[N.READONLY=44]="READONLY",N[N.RETURN=45]="RETURN",N[N.SET=46]="SET",N[N.STATIC=47]="STATIC",N[N.SUPER=48]="SUPER",N[N.SWITCH=49]="SWITCH",N[N.THIS=50]="THIS",N[N.THROW=51]="THROW",N[N.TRUE=52]="TRUE",N[N.TRY=53]="TRY",N[N.TYPE=54]="TYPE",N[N.TYPEOF=55]="TYPEOF",N[N.VAR=56]="VAR",N[N.VOID=57]="VOID",N[N.WHILE=58]="WHILE",N[N.WITH=59]="WITH",N[N.YIELD=60]="YIELD",N[N.OPENBRACE=61]="OPENBRACE",N[N.CLOSEBRACE=62]="CLOSEBRACE",N[N.OPENPAREN=63]="OPENPAREN",N[N.CLOSEPAREN=64]="CLOSEPAREN",N[N.OPENBRACKET=65]="OPENBRACKET",N[N.CLOSEBRACKET=66]="CLOSEBRACKET",N[N.DOT=67]="DOT",N[N.DOT_DOT_DOT=68]="DOT_DOT_DOT",N[N.SEMICOLON=69]="SEMICOLON",N[N.COMMA=70]="COMMA",N[N.LESSTHAN=71]="LESSTHAN",N[N.GREATERTHAN=72]="GREATERTHAN",N[N.LESSTHAN_EQUALS=73]="LESSTHAN_EQUALS",N[N.GREATERTHAN_EQUALS=74]="GREATERTHAN_EQUALS",N[N.EQUALS_EQUALS=75]="EQUALS_EQUALS",N[N.EXCLAMATION_EQUALS=76]="EXCLAMATION_EQUALS",N[N.EQUALS_EQUALS_EQUALS=77]="EQUALS_EQUALS_EQUALS",N[N.EXCLAMATION_EQUALS_EQUALS=78]="EXCLAMATION_EQUALS_EQUALS",N[N.EQUALS_GREATERTHAN=79]="EQUALS_GREATERTHAN",N[N.PLUS=80]="PLUS",N[N.MINUS=81]="MINUS",N[N.ASTERISK_ASTERISK=82]="ASTERISK_ASTERISK",N[N.ASTERISK=83]="ASTERISK",N[N.SLASH=84]="SLASH",N[N.PERCENT=85]="PERCENT",N[N.PLUS_PLUS=86]="PLUS_PLUS",N[N.MINUS_MINUS=87]="MINUS_MINUS",N[N.LESSTHAN_LESSTHAN=88]="LESSTHAN_LESSTHAN",N[N.GREATERTHAN_GREATERTHAN=89]="GREATERTHAN_GREATERTHAN",N[N.GREATERTHAN_GREATERTHAN_GREATERTHAN=90]="GREATERTHAN_GREATERTHAN_GREATERTHAN",N[N.AMPERSAND=91]="AMPERSAND",N[N.BAR=92]="BAR",N[N.CARET=93]="CARET",N[N.EXCLAMATION=94]="EXCLAMATION",N[N.TILDE=95]="TILDE",N[N.AMPERSAND_AMPERSAND=96]="AMPERSAND_AMPERSAND",N[N.BAR_BAR=97]="BAR_BAR",N[N.QUESTION=98]="QUESTION",N[N.COLON=99]="COLON",N[N.EQUALS=100]="EQUALS",N[N.PLUS_EQUALS=101]="PLUS_EQUALS",N[N.MINUS_EQUALS=102]="MINUS_EQUALS",N[N.ASTERISK_EQUALS=103]="ASTERISK_EQUALS",N[N.ASTERISK_ASTERISK_EQUALS=104]="ASTERISK_ASTERISK_EQUALS",N[N.SLASH_EQUALS=105]="SLASH_EQUALS",N[N.PERCENT_EQUALS=106]="PERCENT_EQUALS",N[N.LESSTHAN_LESSTHAN_EQUALS=107]="LESSTHAN_LESSTHAN_EQUALS",N[N.GREATERTHAN_GREATERTHAN_EQUALS=108]="GREATERTHAN_GREATERTHAN_EQUALS",N[N.GREATERTHAN_GREATERTHAN_GREATERTHAN_EQUALS=109]="GREATERTHAN_GREATERTHAN_GREATERTHAN_EQUALS",N[N.AMPERSAND_EQUALS=110]="AMPERSAND_EQUALS",N[N.BAR_EQUALS=111]="BAR_EQUALS",N[N.CARET_EQUALS=112]="CARET_EQUALS",N[N.AT=113]="AT",N[N.IDENTIFIER=114]="IDENTIFIER",N[N.STRINGLITERAL=115]="STRINGLITERAL",N[N.INTEGERLITERAL=116]="INTEGERLITERAL",N[N.FLOATLITERAL=117]="FLOATLITERAL",N[N.TEMPLATELITERAL=118]="TEMPLATELITERAL",N[N.INVALID=119]="INVALID",N[N.ENDOFFILE=120]="ENDOFFILE",N))(Yr||{}),No=(i=>(i[i.DEFAULT=0]="DEFAULT",i[i.PREFER=1]="PREFER",i[i.ALWAYS=2]="ALWAYS",i))(No||{});function $u(r){let e=r.length;switch(assert(e),r.charCodeAt(0)){case 97:{if(e==5){if(r=="async")return 2;if(r=="await")return 3;break}if(r=="as")return 1;if(r=="abstract")return 0;break}case 98:{if(r=="break")return 4;break}case 99:{if(e==5){if(r=="const")return 8;if(r=="class")return 7;if(r=="catch")return 6;break}if(r=="case")return 5;if(r=="continue")return 9;if(r=="constructor")return 10;break}case 100:{if(e==7){if(r=="default")return 13;if(r=="declare")return 12;break}if(r=="do")return 15;if(r=="delete")return 14;if(r=="debugger")return 11;break}case 101:{if(e==4){if(r=="else")return 16;if(r=="enum")return 17;break}if(r=="export")return 18;if(r=="extends")return 19;break}case 102:{if(e<=5){if(r=="false")return 20;if(r=="for")return 22;if(r=="from")return 23;break}if(r=="function")return 24;if(r=="finally")return 21;break}case 103:{if(r=="get")return 25;break}case 105:{if(e==2){if(r=="if")return 26;if(r=="in")return 29;if(r=="is")return 32;break}switch(r.charCodeAt(3)){case 108:{if(r=="implements")return 27;break}case 111:{if(r=="import")return 28;break}case 116:{if(r=="instanceof")return 30;break}case 101:{if(r=="interface")return 31;break}}break}case 107:{if(r=="keyof")return 33;break}case 108:{if(r=="let")return 34;break}case 109:{if(r=="module")return 35;break}case 110:{if(r=="new")return 37;if(r=="null")return 38;if(r=="namespace")return 36;break}case 111:{if(r=="of")return 39;break}case 112:{if(e==7){if(r=="private")return 41;if(r=="package")return 40;break}if(r=="public")return 43;if(r=="protected")return 42;break}case 114:{if(r=="return")return 45;if(r=="readonly")return 44;break}case 115:{if(e==6){if(r=="switch")return 49;if(r=="static")return 47;break}if(r=="set")return 46;if(r=="super")return 48;break}case 116:{if(e==4){if(r=="true")return 52;if(r=="this")return 50;if(r=="type")return 54;break}if(r=="try")return 53;if(r=="throw")return 51;if(r=="typeof")return 55;break}case 118:{if(r=="var")return 56;if(r=="void")return 57;break}case 119:{if(r=="while")return 58;if(r=="with")return 59;break}case 121:{if(r=="yield")return 60;break}}return 119}function ep(r){switch(r){case 0:case 1:case 10:case 12:case 14:case 23:case 22:case 25:case 30:case 32:case 33:case 35:case 36:case 38:case 44:case 46:case 54:case 57:return!0;default:return!1}}function Lo(r){switch(assert(r.length),r.charCodeAt(0)){case 100:return r=="delete";case 102:return r=="for";case 105:return r=="instanceof";case 110:return r=="null";case 118:return r=="void"}return!1}function ye(r){switch(r){case 14:return"delete";case 29:return"in";case 30:return"instanceof";case 37:return"new";case 55:return"typeof";case 57:return"void";case 60:return"yield";case 68:return"...";case 70:return",";case 71:return"<";case 72:return">";case 73:return"<=";case 74:return">=";case 75:return"==";case 76:return"!=";case 77:return"===";case 78:return"!==";case 80:return"+";case 81:return"-";case 82:return"**";case 83:return"*";case 84:return"/";case 85:return"%";case 86:return"++";case 87:return"--";case 88:return"<<";case 89:return">>";case 90:return">>>";case 91:return"&";case 92:return"|";case 93:return"^";case 94:return"!";case 95:return"~";case 96:return"&&";case 97:return"||";case 100:return"=";case 101:return"+=";case 102:return"-=";case 103:return"*=";case 104:return"**=";case 105:return"/=";case 106:return"%=";case 107:return"<<=";case 108:return">>=";case 109:return">>>=";case 110:return"&=";case 111:return"|=";case 112:return"^=";default:return assert(!1),""}}var se=class{constructor(e,t){this.debugInfoRef=0;this.start=e,this.end=t}static join(e,t){if(e.source!=t.source)throw new Error("source mismatch");let i=new se(e.startt.end?e.end:t.end);return i.source=e.source,i}equals(e){return this.source==e.source&&this.start==e.start&&this.end==e.end}get atStart(){let e=new se(this.start,this.start);return e.source=this.source,e}get atEnd(){let e=new se(this.end,this.end);return e.source=this.source,e}toString(){return this.source.text.substring(this.start,this.end)}},qn=class extends ze{constructor(e,t=null){super(t);this.end=0;this.pos=0;this.token=-1;this.tokenPos=0;this.nextToken=-1;this.nextTokenPos=0;this.nextTokenOnNewLine=!1;this.onComment=null;this.readingTemplateString=!1;this.readStringStart=0;this.readStringEnd=0;t||(t=[]),this.diagnostics=t,this.source=e;var i=e.text,n=i.length,s=0;if(s1&&s2&&s1&&s1&&s1&&s2&&s1&&s1&&s1&&s2&&s+11&&s1&&s2&&s1&&s2&&s1&&s2&&s3&&s1&&s1&&s=n){o+=i.substring(a,s),this.error(1002,this.range(a-1,n)),this.readStringEnd=n;break}let l=i.charCodeAt(s);if(l==e){this.readStringEnd=s,o+=i.substring(a,s++);break}if(l==92){o+=i.substring(a,s),this.pos=s,o+=this.readEscapeSequence(t),s=this.pos,a=s;continue}if(e==96){if(l==36&&s+1=i)return this.error(1126,this.range(i)),"";var n=this.source.text,s=n.charCodeAt(this.pos++);switch(s){case 48:return e&&this.pos=i){this.error(1161,this.range(t,i));break}if(e.charCodeAt(this.pos)==92){++this.pos,n=!0;continue}let s=e.charCodeAt(this.pos);if(!n&&s==47)break;if(mt(s)){this.error(1161,this.range(t,this.pos));break}++this.pos,n=!1}return e.substring(t,this.pos)}readRegexpFlags(){for(var e=this.source.text,t=this.pos,i=this.end,n=0;this.pos57))break;t++}return!0}readInteger(){var e=this.source.text,t=this.pos;if(t+2=48&&l<=57)a=i64_add(i64_shl(a,o),i64_new(l-48));else if(l>=65&&l<=70)a=i64_add(i64_shl(a,o),i64_new(10+l-65));else if(l>=97&&l<=102)a=i64_add(i64_shl(a,o),i64_new(10+l-97));else if(l==95)s==t&&this.error(s==n?6188:6189,this.range(t)),s=t+1;else break;++t}return t==n?this.error(1125,this.range(n)):s==t&&this.error(6188,this.range(s-1)),this.pos=t,a}readDecimalInteger(){for(var e=this.source.text,t=this.pos,i=this.end,n=t,s=n,a=i64_new(0),o=i64_new(10);t=48&&l<=57)a=i64_add(i64_mul(a,o),i64_new(l-48));else if(l==95)s==t?this.error(s==n?6188:6189,this.range(t)):t-1==n&&e.charCodeAt(t-1)==48&&this.error(6188,this.range(t)),s=t+1;else break;++t}return t==n?this.error(1124,this.range(n)):s==t&&this.error(6188,this.range(s-1)),this.pos=t,a}readOctalInteger(){for(var e=this.source.text,t=this.pos,i=this.end,n=t,s=n,a=i64_new(0),o=i64_new(3);t=48&&l<=55)a=i64_add(i64_shl(a,o),i64_new(l-48));else if(l==95)s==t&&this.error(s==n?6188:6189,this.range(t)),s=t+1;else break;++t}return t==n?this.error(1178,this.range(n)):s==t&&this.error(6188,this.range(s-1)),this.pos=t,a}readBinaryInteger(){for(var e=this.source.text,t=this.pos,i=this.end,n=t,s=n,a=i64_new(0),o=i64_new(1);t=48&&o<=57)i=(i<<4)+o-48;else if(o>=65&&o<=70)i=(i<<4)+o+(10-65);else if(o>=97&&o<=102)i=(i<<4)+o+(10-97);else return~t?(this.pos=--s,n.substring(t,s)):(this.pos=s,this.error(1125,this.range(s-1,s)),"");if(--e==0)break}return e?(this.pos=s,~t?n.substring(t,s):(this.error(1126,this.range(s)),"")):(this.pos=s,String.fromCodePoint(i))}checkForIdentifierStartAfterNumericLiteral(){var e=this.pos;e1114111&&(e==-1&&this.error(1198,this.range(t,this.pos)),s=!0);var a=this.end,o=this.source.text;return this.pos>=a?(e==-1&&this.error(1126,this.range(t,a)),s=!0):o.charCodeAt(this.pos)==125?++this.pos:(e==-1&&this.error(1199,this.range(t,this.pos)),s=!0),s?~e?o.substring(e,this.pos):"":String.fromCodePoint(n)}},Co=class{constructor(e,t,i){this.pos=e;this.token=t;this.tokenPos=i}},Ao=null;var Qn=(t=>(t[t.REPORT=0]="REPORT",t[t.SWALLOW=1]="SWALLOW",t))(Qn||{}),Zn=class extends ze{constructor(e){super(e.diagnostics);this.currentThisExpression=null;this.currentElementExpression=null;this.discoveredOverload=!1;this.resolveClassPending=new Set;this.program=e}resolveType(e,t,i=null,n=0){switch(e.kind){case 1:return this.resolveNamedType(e,t,i,n);case 2:return this.resolveFunctionType(e,t,i,n);default:assert(!1)}return null}resolveNamedType(e,t,i=null,n=0){var s=e.name,a=e.typeArguments,o=!s.next;if(o){let c=s.identifier.text;if(i&&i.has(c)){let _=assert(i.get(c));if(a&&a.length>0&&n==0&&this.error(2315,e.range,_.toString()),e.isNullable){if(_.isInternalReference)return _.asNullable();n==0&&this.error(204,e.range,_.toString())}return _}}var l=this.resolveTypeName(s,t,n);if(!l)return null;var p=l.shadowType;if(p)l=p;else{if(l.kind==2)return a&&a.length>0&&n==0&&this.error(2315,e.range,l.internalName),e.isNullable&&n==0&&this.error(204,e.range,l.name+"/i32"),u.i32;if(l.kind==6||l.kind==8){let c=this.resolveClassInclTypeArguments(l,a,t,re(i),e,n);return c?e.isNullable?c.type.asNullable():c.type:null}}if(l.kind==16){let c=l;if(l.is(2097152)){a&&a.length>0&&n==0&&this.error(2315,e.range,l.internalName);let g=c.type;if(e.isNullable){if(g.isInternalReference)return g.asNullable();n==0&&this.error(204,s.range,s.identifier.text)}return g}if(o){let g=s.identifier.text;if(g==O.native)return this.resolveBuiltinNativeType(e,t,i,n);if(g==O.indexof)return this.resolveBuiltinIndexofType(e,t,i,n);if(g==O.valueof)return this.resolveBuiltinValueofType(e,t,i,n);if(g==O.returnof)return this.resolveBuiltinReturnTypeType(e,t,i,n);if(g==O.nonnull)return this.resolveBuiltinNotNullableType(e,t,i,n)}let _=c.typeParameterNodes,f=null;if(_){if(f=this.resolveTypeArguments(_,a,t,i=re(i),e,n),!f)return null}else a&&a.length>0&&this.error(2315,e.range,s.identifier.text);let E=this.resolveType(c.typeNode,l,i,n);if(!E)return null;if(e.isNullable){if(E.isInternalReference)return E.asNullable();n==0&&this.error(204,s.range,s.identifier.text)}return E}return n==0&&this.error(2304,s.range,s.identifier.text),null}resolveFunctionType(e,t,i=null,n=0){var s=e.explicitThisType,a=null;if(s&&(a=this.resolveType(s,t,i,n),!a))return null;var o=e.parameters,l=o.length,p=new Array(l),c=0,_=!1;for(let b=0;bl)return a==0&&this.error(2558,p?se.join(t[0].range,t[p-1].range):s.range,(p0){let l=t.classReference;if(l){let p=this.resolveTypeName(a.name,i.actualFunction);if(!p||p.kind!=6)return;if(l.prototype==p){let c=l.typeArguments;if(c&&c.length==o.length){for(let _=0,f=c.length;_0){let l=t.signatureReference;if(l){let p=l.parameterTypes,c=l.thisType;if(p.length==o.length&&!c==!a.explicitThisType){for(let _=0,f=p.length;_1)++p;else{let E=this.resolveExpression(f,t,l);if(!E)return null;if(l==u.auto)l=E;else if(E!=l){let g=u.commonDenominator(l,E,!1);g&&(l=g)}}}if(l==u.auto)if(p==o)l=this.program.options.usizeType;else return n==0&&this.error(2453,e.range,"T"),null;return p>0&&l.isInternalReference&&(l=l.asNullable()),assert(this.resolveClass(this.program.arrayPrototype,[l]))}case 6:return i.isClass?i.classReference:(n==0&&this.error(225,e.range),null)}return assert(!1),null}resolveLiteralExpression(e,t,i=u.auto,n=0){var s=this.lookupLiteralExpression(e,t,i,n);if(!s)return null;var a=this.getTypeOfElement(s);return a||n==0&&this.error(225,e.range),a}lookupCallExpression(e,t,i=u.void,n=0){var s=this.resolveCallExpression(e,t,i,n);if(!s)return null;var a=this.getElementOfType(s);return a||n==0&&this.error(214,e.range,s.toString()),a}resolveCallExpression(e,t,i=u.void,n=0){var s=e.expression,a=this.lookupExpression(s,t,i,n);if(!a)return null;switch(a.kind){case 4:{let o=a;if(o.internalName==h.unchecked&&e.args.length>0)return this.resolveExpression(e.args[0],t,i,n);let l=this.maybeInferCall(e,o,t,n);return l?l.signature.returnType:null}case 0:case 1:case 11:{let o=a.type,l=this.getElementOfType(o);if(!l||l.kind!=7)break;a=l}case 7:{let o=a.getTypeArgumentsTo(this.program.functionPrototype);if(o&&o.length>0){let l=o[0];return assert(l.signatureReference).returnType}break}}return n==0&&this.error(2349,s.range,a.internalName),null}lookupCommaExpression(e,t,i=u.auto,n=0){var s=e.expressions;return this.lookupExpression(s[assert(s.length)-1],t,i,n)}resolveCommaExpression(e,t,i=u.auto,n=0){var s=e.expressions;return this.resolveExpression(s[assert(s.length)-1],t,i,n)}lookupInstanceOfExpression(e,t,i=u.auto,n=0){return assert(u.bool.getClassOrWrapper(this.program))}resolveInstanceOfExpression(e,t,i=u.auto,n=0){return u.bool}lookupTernaryExpression(e,t,i,n=0){var s=this.resolveTernaryExpression(e,t,i,n);if(!s)return null;var a=this.getElementOfType(s);return a||n==0&&this.error(214,e.range,s.toString()),a}resolveTernaryExpression(e,t,i,n=0){var s=this.resolveExpression(e.ifThen,t,i,n);if(!s)return null;var a=this.resolveExpression(e.ifElse,t,s,n);if(!a)return null;var o=u.commonDenominator(s,a,!1);return o||n==0&&this.error(2365,e.range,"?:",s.toString(),a.toString()),o}lookupNewExpression(e,t,i,n=0){var s=this.resolveTypeName(e.typeName,t.actualFunction,n);return s?s.kind==6?this.resolveClassInclTypeArguments(s,e.typeArguments,t.actualFunction,re(t.contextualTypeArguments),e,n):(n==0&&this.error(2351,e.range),null):null}resolveNewExpression(e,t,i,n=0){var s=this.lookupNewExpression(e,t,i,n);if(!s)return null;var a=this.getTypeOfElement(s);return a||n==0&&this.error(225,e.range),a}lookupFunctionExpression(e,t,i,n=0){var s=this.resolveFunctionExpression(e,t,i,n);if(!s)return null;var a=this.getElementOfType(s);return a||n==0&&this.error(214,e.range,s.toString()),a}resolveFunctionExpression(e,t,i,n=0){return this.resolveFunctionType(e.declaration.signature,t.actualFunction,t.contextualTypeArguments,n)}resolveFunction(e,t,i=re(),n=0){var s=e.parent.kind==12?e.parent.parent:e.parent,a=null,o=t?zn(t):"";if(e.is(131072)){assert(s.kind==7||s.kind==9),a=s;let F=e.getResolvedInstance(o);if(F)return F;let w=a.typeArguments;if(w){let U=assert(a.prototype.typeParameterNodes),Y=U.length;assert(Y==U.length);for(let z=0;z0){assert(p&&c==p.length);for(let F=0;F");var P=new je(L,e,t,x,i);if(e.setResolvedInstance(o,P),a){let F=P.declaration.name.text,w=a.base;for(;w;){let U=w.members;if(U&&U.has(F)){this.discoveredOverload=!0;break}w=w.base}}return P}resolveFunctionInclTypeArguments(e,t,i,n,s,a=0){var o=e.parent.kind==12?e.parent.parent:e.parent,l=null;if(e.is(32768)){if(e.is(131072)){assert(o.kind==7);let p=o,c=p.typeArguments;if(c){let _=assert(p.prototype.typeParameterNodes),f=c.length;assert(f==_.length);for(let E=0;E0)return a==0&&this.error(2315,s.range,e.internalName),null;return this.resolveFunction(e,l,n,a)}resolveOverloads(e){var t=e.prototype.overloads;if(!t)return null;var i=assert(e.getClassOrInterface()),n=new Set;for(let s=Set_values(t),a=0,o=s.length;a"),e.kind==8?a=new es(o,e,t):a=new Ci(o,e,t),e.setResolvedInstance(s,a);var l=this.resolveClassPending;if(l.add(a),t){let f=assert(e.typeParameterNodes),E=f.length,g=t.length;assert(g==E);for(let b=0;b0))}a.contextualTypeArguments=i;var p=!1,c=e.basePrototype;if(c){let f=c;do{if(f==e)return this.error(2506,e.identifierNode.range,e.internalName),null;f=f.basePrototype}while(f);let E=assert(e.extendsNode),g=this.resolveClassInclTypeArguments(c,E.typeArguments,e.parent,re(i),E,n);if(!g)return null;a.setBase(g),l.has(g)&&(p=!0)}var _=e.interfacePrototypes;if(_)for(let f=0,E=_.length;f0)for(let E=Map_keys(s),g=0,b=E.length;g0)return a==0&&this.error(2315,s.range,e.internalName),null;return this.resolveClass(e,o,n,a)}resolveProperty(e,t=0){var i=e.instance;if(i)return i;e.instance=i=new Jn(e,e);var n=e.getterPrototype;if(n){let a=this.resolveFunction(n,null,re(),t);a&&(i.getterInstance=a,i.setType(a.signature.returnType))}var s=e.setterPrototype;if(s){let a=this.resolveFunction(s,null,re(),t);a&&(i.setterInstance=a,i.is(2097152)||(assert(a.signature.parameterTypes.length==1),i.setType(a.signature.parameterTypes[0])))}return i}ensureOneTypeArgument(e,t=0){var i=e.typeArguments;let n=0;return!i||(n=i.length)!=1?(t==0&&this.error(2558,e.range,"1",n.toString()),null):i[0]}};var ts=class{constructor(){this.stack=new Array;this._currentExpression=0}get currentExpression(){var e=this._currentExpression;if(!e)throw new Error("not walking expressions");return e}get parentExpressionOrNull(){var e=this.stack,t=e.length;return t?e[t-1]:0}visitBlock(e){}visitIf(e){}visitLoop(e){}visitBreak(e){}visitSwitch(e){}visitCallPre(e){}visitCall(e){}visitCallIndirectPre(e){}visitCallIndirect(e){}visitLocalGet(e){}visitLocalSet(e){}visitGlobalGet(e){}visitGlobalSet(e){}visitLoad(e){}visitStore(e){}visitConst(e){}visitUnary(e){}visitBinary(e){}visitSelect(e){}visitDrop(e){}visitReturn(e){}visitMemorySize(e){}visitMemoryGrow(e){}visitNop(e){}visitUnreachable(e){}visitAtomicRMW(e){}visitAtomicCmpxchg(e){}visitAtomicWait(e){}visitAtomicNotify(e){}visitAtomicFence(e){}visitSIMDExtract(e){}visitSIMDReplace(e){}visitSIMDShuffle(e){}visitSIMDTernary(e){}visitSIMDShift(e){}visitSIMDLoad(e){}visitSIMDLoadStoreLane(e){}visitMemoryInit(e){}visitDataDrop(e){}visitMemoryCopy(e){}visitMemoryFill(e){}visitPop(e){}visitRefNull(e){}visitRefIs(e){}visitRefFunc(e){}visitRefEq(e){}visitTry(e){}visitThrow(e){}visitRethrow(e){}visitTupleMake(e){}visitTupleExtract(e){}visitI31New(e){}visitI31Get(e){}visitCallRef(e){}visitRefTest(e){}visitRefCast(e){}visitBrOn(e){}visitRttCanon(e){}visitRttSub(e){}visitStructNew(e){}visitStructGet(e){}visitStructSet(e){}visitArrayNew(e){}visitArrayGet(e){}visitArraySet(e){}visitArrayLen(e){}visitRefAs(e){}visitName(e){}visitLabel(e){}visitIndex(e){}visitTag(e){}visit(e){let t=this._currentExpression;switch(this._currentExpression=assert(e),nt(e)){case 1:{this.stack.push(e);let i=Fi(e);i&&this.visitLabel(i);for(let n=0,s=Xr(e);n(P[P.NONE=0]="NONE",P[P.RETURNS=1]="RETURNS",P[P.RETURNS_WRAPPED=2]="RETURNS_WRAPPED",P[P.RETURNS_NONNULL=4]="RETURNS_NONNULL",P[P.THROWS=8]="THROWS",P[P.BREAKS=16]="BREAKS",P[P.CONTINUES=32]="CONTINUES",P[P.ACCESSES_THIS=64]="ACCESSES_THIS",P[P.CALLS_SUPER=128]="CALLS_SUPER",P[P.TERMINATES=256]="TERMINATES",P[P.CONDITIONALLY_RETURNS=512]="CONDITIONALLY_RETURNS",P[P.CONDITIONALLY_THROWS=1024]="CONDITIONALLY_THROWS",P[P.CONDITIONALLY_BREAKS=2048]="CONDITIONALLY_BREAKS",P[P.CONDITIONALLY_CONTINUES=4096]="CONDITIONALLY_CONTINUES",P[P.CONDITIONALLY_ACCESSES_THIS=8192]="CONDITIONALLY_ACCESSES_THIS",P[P.MAY_RETURN_NONTHIS=16384]="MAY_RETURN_NONTHIS",P[P.UNCHECKED_CONTEXT=32768]="UNCHECKED_CONTEXT",P[P.CTORPARAM_CONTEXT=65536]="CTORPARAM_CONTEXT",P[P.ANY_CATEGORICAL=511]="ANY_CATEGORICAL",P[P.ANY_CONDITIONAL=15872]="ANY_CONDITIONAL",P))(ds||{}),Es=(s=>(s[s.NONE=0]="NONE",s[s.CONSTANT=1]="CONSTANT",s[s.WRAPPED=2]="WRAPPED",s[s.NONNULL=4]="NONNULL",s[s.INITIALIZED=8]="INITIALIZED",s))(Es||{}),Nl=(t=>(t[t.NONE=0]="NONE",t[t.INITIALIZED=1]="INITIALIZED",t))(Nl||{}),Ll=(i=>(i[i.UNKNOWN=0]="UNKNOWN",i[i.TRUE=1]="TRUE",i[i.FALSE=2]="FALSE",i))(Ll||{}),Ue=class{constructor(e){this.parentFunction=e;this.parent=null;this.outer=null;this.flags=0;this.continueLabel=null;this.breakLabel=null;this.scopedLocals=null;this.localFlags=[];this.thisFieldFlags=null;this.inlineFunction=null;this.inlineReturnLabel=null}static createParent(e){var t=new Ue(e);return e.is(262144)&&t.initThisFieldFlags(),t}static createInline(e,t){var i=new Ue(e);return i.inlineFunction=t,i.inlineReturnLabel=t.internalName+"|inlined."+(t.nextInlineId++).toString(),t.is(262144)&&i.initThisFieldFlags(),i}get isInline(){return this.inlineFunction!=null}get actualFunction(){var e=this.inlineFunction;return e||this.parentFunction}get returnType(){return this.actualFunction.signature.returnType}get contextualTypeArguments(){return this.actualFunction.contextualTypeArguments}is(e){return(this.flags&e)==e}isAny(e){return(this.flags&e)!=0}set(e){this.flags|=e}unset(e){this.flags&=~e}deriveConditionalFlags(){let e=this.flags&15872;return this.is(1)&&(e|=512),this.is(8)&&(e|=1024),this.is(16)&&(e|=2048),this.is(32)&&(e|=4096),this.is(64)&&(e|=8192),e}fork(e=!1){var t=new Ue(this.parentFunction);if(t.parent=this,t.outer=this.outer,e?t.flags=this.flags&-6193:(t.flags=this.flags,t.continueLabel=this.continueLabel,t.breakLabel=this.breakLabel),t.localFlags=this.localFlags.slice(),this.actualFunction.is(262144)){let i=assert(this.thisFieldFlags);t.thisFieldFlags=re(i)}else assert(!this.thisFieldFlags);return t.inlineFunction=this.inlineFunction,t.inlineReturnLabel=this.inlineReturnLabel,t}getTempLocal(e,t=null){var i=this.parentFunction,n;switch(e.toRef()){case C.I32:{n=i.tempI32s;break}case C.I64:{n=i.tempI64s;break}case C.F32:{n=i.tempF32s;break}case C.F64:{n=i.tempF64s;break}case C.V128:{n=i.tempV128s;break}case C.Funcref:{n=i.tempFuncrefs;break}case C.Externref:{n=i.tempExternrefs;break}case C.Anyref:{n=i.tempAnyrefs;break}case C.Eqref:{n=i.tempEqrefs;break}case C.I31ref:{n=i.tempI31refs;break}case C.Dataref:{n=i.tempDatarefs;break}default:throw new Error("concrete type expected")}var s;if(t){if(n&&n.length>0){for(let a=0,o=n.length;a0?(s=assert(n.pop()),s.type=e,s.flags=0):s=i.addLocal(e);return this.unsetLocalFlag(s.index,-1),s}freeTempLocal(e){if(!e.is(16777216)){assert(e.index>=0);var t=this.parentFunction,i;switch(assert(e.type!=null),e.resetTemporaryName(),e.type.toRef()){case C.I32:{let n=t.tempI32s;n?i=n:t.tempI32s=i=[];break}case C.I64:{let n=t.tempI64s;n?i=n:t.tempI64s=i=[];break}case C.F32:{let n=t.tempF32s;n?i=n:t.tempF32s=i=[];break}case C.F64:{let n=t.tempF64s;n?i=n:t.tempF64s=i=[];break}case C.V128:{let n=t.tempV128s;n?i=n:t.tempV128s=i=[];break}case C.Funcref:{let n=t.tempFuncrefs;n?i=n:t.tempFuncrefs=i=[];break}case C.Externref:{let n=t.tempExternrefs;n?i=n:t.tempExternrefs=i=[];break}case C.Anyref:{let n=t.tempAnyrefs;n?i=n:t.tempAnyrefs=i=[];break}case C.Eqref:{let n=t.tempEqrefs;n?i=n:t.tempEqrefs=i=[];break}case C.I31ref:{let n=t.tempI31refs;n?i=n:t.tempI31refs=i=[];break}case C.Dataref:{let n=t.tempDatarefs;n?i=n:t.tempDatarefs=i=[];break}default:throw new Error("concrete type expected")}assert(e.index>=0),i.push(e)}}getScopedLocal(e){var t=this.scopedLocals;return t&&t.has(e)?assert(t.get(e)):null}addScopedLocal(e,t,i=null){var n=this.getTempLocal(t,i);n.setTemporaryName(e);var s=this.scopedLocals;return s?assert(!s.has(e)):this.scopedLocals=s=new Map,n.set(33554432),s.set(e,n),n}addScopedDummyLocal(e,t,i){var n=new De(e,-1,t,this.parentFunction),s=this.scopedLocals;return s?s.has(e)&&this.parentFunction.program.error(2451,i.range,e):this.scopedLocals=s=new Map,n.set(33554432),s.set(e,n),n}addScopedAlias(e,t,i,n=null){var s=this.scopedLocals;if(!s)this.scopedLocals=s=new Map;else if(s.has(e)){let o=assert(s.get(e));return n&&(o.declaration.range.source.isNative?this.parentFunction.program.error(2300,n.range,e):this.parentFunction.program.errorRelated(2300,n.range,o.declaration.name.range,e)),o}assert(i1?e.breakLabel=t[i-2].toString():(e.breakLabel=null,e.breakStack=null)}inherit(e){assert(e.parentFunction==this.parentFunction),assert(e.parent==this);var t=e.flags;this.breakLabel!=e.breakLabel&&(t&2064&&(t&=-257),t&=-2065),this.continueLabel!=e.continueLabel&&(t&=-4129),this.flags=this.flags|t,this.localFlags=e.localFlags,this.thisFieldFlags=e.thisFieldFlags}inheritBranch(e,t=0){switch(assert(e.parentFunction==this.parentFunction),t){case 1:this.inherit(e);case 2:return}var i=this.flags,n=e.flags,s=0;i&1?s|=1:n&1?s|=512:s|=(i|n)&512,s|=i&n&2,s|=i&n&4,i&8?s|=8:n&8?s|=1024:s|=(i|n)&1024,i&16?s|=16:e.breakLabel==this.breakLabel?n&16?s|=2048:s|=(i|n)&2048:s|=i&2048,i&32?s|=32:e.continueLabel==this.continueLabel?n&32?s|=4096:s|=(i|n)&4096:s|=i&4096,i&64?n&64?s|=64:s|=8192:n&64&&(s|=8192),s|=(i|n)&16384,s|=i&n&128,i&256&&(s|=256),this.flags=s|i&98304;var a=this.localFlags,o=a.length,l=e.localFlags,p=l.length,c=max(o,p);for(let _=0;_n):this.canOverflow(Me(e),t)&&!(te(i=Se(e))==14&&ie(i)>=n)}case 4:case 5:case 6:return this.canOverflow(Me(e),t)||this.canOverflow(Se(e),t)}break}case 15:{switch(Qi(e)){case 20:case 21:return!1;case 0:case 2:case 4:return t.size<7;case 47:return t.size<(t.isUnsignedIntegerValue?32:8);case 49:return t.size<(t.isUnsignedIntegerValue?64:8);case 48:return t.size<(t.isUnsignedIntegerValue?32:16);case 50:return t.size<(t.isUnsignedIntegerValue?64:16);case 51:return t.size<(t.isUnsignedIntegerValue?64:32)}break}case 14:{let n=0;switch(oe(e)){case C.I32:{n=ie(e);break}case C.I64:{n=Be(e);break}case C.F32:{n=i32(Ye(e));break}case C.F64:{n=i32(He(e));break}case C.V128:return!1;default:assert(!1)}switch(t.kind){case 0:return ni8.MAX_VALUE;case 1:return ni16.MAX_VALUE;case 5:return n<0||n>u8.MAX_VALUE;case 6:return n<0||n>u16.MAX_VALUE;case 10:return(n&-2)!=0}break}case 12:{let n,s=Fl(e);switch(Cl(e)){case 1:{n=s?u.i8:u.u8;break}case 2:{n=s?u.i16:u.u16;break}default:{n=s?u.i32:u.u32;break}}return _s(n,t)}case 1:{if(!en(e)){let n=assert(tn(e)),s=rn(e,n-1);return this.canOverflow(s,t)}break}case 2:return this.canOverflow(Zi(e),t)||this.canOverflow(assert(jr(e)),t);case 17:return this.canOverflow(kl(e),t)||this.canOverflow(Pl(e),t);case 6:{let s=this.parentFunction.program.instancesByName,a=assert(ji(e));if(s.has(a)){let o=assert(s.get(a));assert(o.kind==5);let l=o,p=l.signature.returnType;return!l.flow.is(2)||_s(p,t)}return!1}case 23:return!1}return!0}toString(){for(var e=0,t=this.parent;t;)t=t.parent,++e;var i=new Array;return this.is(1)&&i.push("RETURNS"),this.is(2)&&i.push("RETURNS_WRAPPED"),this.is(4)&&i.push("RETURNS_NONNULL"),this.is(8)&&i.push("THROWS"),this.is(16)&&i.push("BREAKS"),this.is(32)&&i.push("CONTINUES"),this.is(64)&&i.push("ACCESSES_THIS"),this.is(128)&&i.push("CALLS_SUPER"),this.is(256)&&i.push("TERMINATES"),this.is(512)&&i.push("CONDITIONALLY_RETURNS"),this.is(1024)&&i.push("CONDITIONALLY_THROWS"),this.is(2048)&&i.push("CONDITIONALLY_BREAKS"),this.is(4096)&&i.push("CONDITIONALLY_CONTINUES"),this.is(8192)&&i.push("CONDITIONALLY_ACCESSES_THIS"),this.is(16384)&&i.push("MAY_RETURN_NONTHIS"),"Flow("+this.actualFunction.toString()+")["+e.toString()+"] "+i.join(" ")}};function _s(r,e){return e.isShortIntegerValue&&(!r.isIntegerValue||r.size>e.size||r.isSignedIntegerValue!=e.isSignedIntegerValue)}var ys=class{constructor(e,t){this.source=e;this.reportNode=t}},gs=class extends ze{constructor(e=null,t=null){super(e);this.backlog=new Array;this.seenlog=new Set;this.donelog=new Set;this.onComment=null;this.currentSource=null;this.dependees=new Map;this.currentModuleName=null;this.tryParseSignatureIsSignature=!1;this.parseParametersThis=null;this.sources=t||new Array}parseFile(e,t,i){var n=rr(t),s=Li(n);if(!this.donelog.has(s)){if(this.donelog.add(s),this.seenlog.add(s),e==null){let p=this.dependees,c=null;p.has(s)&&(c=assert(p.get(s))),this.error(6054,c?c.reportNode.range:null,t);return}var a=new zr(i?1:t.startsWith(Ze)?t.indexOf(Qe,Ze.length)<0?3:2:0,n,e);this.sources.push(a),this.currentSource=a,this.currentModuleName=null;var o=new qn(a,this.diagnostics);o.onComment=this.onComment;for(var l=a.statements;!o.skip(120);){let p=this.parseTopLevelStatement(o,null);p?l.push(p):this.skipStatement(o)}}}parseTopLevelStatement(e,t=null){for(var i=t?t.flags&16384:0,n=-1,s=null;e.skip(113);){n<0&&(n=e.tokenPos);let b=this.parseDecorator(e);if(!b){this.skipStatement(e);continue}s?s.push(b):s=[b]}var a=0,o=0,l=0,p=0;e.skip(18)&&(n<0&&(n=e.tokenPos),i|=2,a=e.tokenPos,o=e.pos,e.skip(13)&&(l=e.tokenPos,p=e.pos));var c=0,_=0,f=t!=null&&t.is(16384);e.skip(12)?f?this.error(1038,e.range()):(n<0&&(n=e.tokenPos),c=n,_=e.pos,i|=16388):f&&(i|=16384);var E=null,g=e.peek();switch(n<0&&(n=e.nextTokenPos),g){case 8:{e.next(),i|=8,e.skip(17)?E=this.parseEnum(e,i,s,n):E=this.parseVariable(e,i,s,n),s=null;break}case 34:i|=16;case 56:{e.next(),E=this.parseVariable(e,i,s,n),s=null;break}case 17:{e.next(),E=this.parseEnum(e,i,s,n),s=null;break}case 24:{e.next(),E=this.parseFunction(e,i,s,n),s=null;break}case 0:{let b=e.mark();e.next();let S=e.tokenPos,v=e.pos,x=e.peek(!0);if(e.nextTokenOnNewLine){e.reset(b),E=this.parseStatement(e,!0);break}if(x!=7){x==31&&this.error(1242,e.range(S,v)),e.reset(b),E=this.parseStatement(e,!0);break}else e.discard(b);i|=128}case 7:case 31:{e.next(),E=this.parseClassOrInterface(e,i,s,n),s=null;break}case 36:{let b=e.mark();e.next(),e.peek(!1,1)==114?(e.discard(b),E=this.parseNamespace(e,i,s,n),s=null):(e.reset(b),E=this.parseStatement(e,!0));break}case 28:{e.next(),i|=1,i&2?E=this.parseExportImport(e,n):E=this.parseImport(e);break}case 54:{let b=e.mark();e.next(),e.peek(!1,1)==114?(e.discard(b),E=this.parseTypeDeclaration(e,i,s,n),s=null):(e.reset(b),E=this.parseStatement(e,!0));break}case 35:{let b=e.mark();e.next(),e.peek(!0)==115&&!e.nextTokenOnNewLine?(e.discard(b),E=this.parseModuleDeclaration(e,i)):(e.reset(b),E=this.parseStatement(e,!0));break}default:{i&2?p&&e.skipIdentifier(1)?(_&&this.error(1120,e.range(c,_)),E=this.parseExportDefaultAlias(e,n,l,p),l=p=0):E=this.parseExport(e,n,(i&4)!=0):(o&&this.error(1042,e.range(a,o),"export"),_&&this.error(1042,e.range(c,_),"declare"),t||(E=this.parseStatement(e,!0)));break}}if(s)for(let b=0,S=s.length;b"),null}l||(l=[]),a=k.createNamedType(o,l,!1,e.range(s,e.pos))}else return i||this.error(1110,e.range()),null;for(;e.skip(92);)if(e.skip(38))a.isNullable=!0;else{let o=e.pos,l=this.parseType(e,!1,!0);return i||this.error(1005,l?l.range:e.range(o),"null"),null}for(;e.skip(65);){let o=e.tokenPos;if(!e.skip(66))return i||this.error(1005,e.range(),"]"),null;let l=e.range(o,e.pos),p=!1;if(e.skip(92))if(e.skip(38))p=!0;else return i||this.error(1005,e.range(),"null"),null;if(a=k.createNamedType(k.createSimpleTypeName("Array",l),[a],p,e.range(s,e.pos)),p)break}return a}tryParseFunctionType(e){var t=e.mark(),i=e.tokenPos,n=null,s=null,a=!1,o=null,l=0;if(e.skip(64))a=!0,e.discard(t),n=[];else{a=!1;do{let c=-1,_=0;if(e.skip(68)&&(c=e.tokenPos,a=!0,e.discard(t),_=2),e.skip(50))if(c<0&&(c=e.tokenPos),e.skip(99)){a=!0,e.discard(t);let f=this.parseType(e,!1);if(!f)return null;if(f.kind!=1)return this.error(1003,f.range),this.tryParseSignatureIsSignature=!0,null;s=f}else return e.reset(t),this.tryParseSignatureIsSignature=!1,null;else if(e.skipIdentifier()){c<0&&(c=e.tokenPos);let f=k.createIdentifierExpression(e.readIdentifier(),e.range(e.tokenPos,e.pos));if(e.skip(98)&&(a=!0,e.discard(t),_==2?this.error(1047,e.range()):_=1),e.skip(99)){a=!0,e.discard(t);let E=this.parseType(e);if(!E)return this.tryParseSignatureIsSignature=a,null;let g=k.createParameter(_,f,E,null,e.range(c,e.pos));n?n.push(g):n=[g]}else if(a||e.peek()==70&&(a=!0,e.discard(t)),a){let E=k.createParameter(_,f,k.createOmittedType(e.range(e.pos)),null,e.range(c,e.pos));n?n.push(E):n=[E],this.error(1110,E.type.range)}else n||(o=f,l=_)}else return a?this.error(1003,e.range()):e.reset(t),this.tryParseSignatureIsSignature=a,null}while(e.skip(70));if(!e.skip(64))return a?this.error(1005,e.range(),")"):e.reset(t),this.tryParseSignatureIsSignature=a,null}var p;if(e.skip(79)){if(!a&&(a=!0,e.discard(t),o)){let c=k.createParameter(l,o,k.createOmittedType(o.range.atEnd),null,o.range);n?n.push(c):n=[c],this.error(1110,c.type.range)}if(p=this.parseType(e),!p)return this.tryParseSignatureIsSignature=a,null}else return a?this.error(1005,e.range(),"=>"):e.reset(t),this.tryParseSignatureIsSignature=a,null;return this.tryParseSignatureIsSignature=!0,n||(n=[]),k.createFunctionType(n,p,s,!1,e.range(i,e.pos))}parseDecorator(e){var t=e.tokenPos;if(e.skipIdentifier()){let i=e.readIdentifier(),n=k.createIdentifierExpression(i,e.range(t,e.pos));for(;e.skip(67);)if(e.skipIdentifier(1))i=e.readIdentifier(),n=k.createPropertyAccessExpression(n,k.createIdentifierExpression(i,e.range()),e.range(t,e.pos));else return this.error(1003,e.range()),null;let s;if(e.skip(63)){if(s=this.parseArguments(e),s)return k.createDecorator(n,s,e.range(t,e.pos))}else return k.createDecorator(n,null,e.range(t,e.pos))}else this.error(1003,e.range());return null}parseVariable(e,t,i,n,s=!1){var a=new Array;do{let l=this.parseVariableDeclaration(e,t,i,s);if(!l)return null;l.overriddenModuleName=this.currentModuleName,a.push(l)}while(e.skip(70));var o=k.createVariableStatement(i,a,e.range(n,e.pos));return e.skip(69),o}parseVariableDeclaration(e,t,i,n=!1){if(!e.skipIdentifier())return this.error(1003,e.range()),null;var s=k.createIdentifierExpression(e.readIdentifier(),e.range());Lo(s.text)&&this.error(1003,s.range);var a=t;e.skip(94)&&(a|=8192);var o=null;e.skip(99)&&(o=this.parseType(e,!0));var l=null;if(e.skip(100)){if(a&16384&&this.error(1039,e.range()),l=this.parseExpression(e,he.COMMA+1),!l)return null}else n||(a&8?a&16384||this.error(1155,s.range):o||this.error(1110,e.range(e.pos)));var p=se.join(s.range,e.range());return l&&(a&8192)!=0&&this.error(1255,p),k.createVariableDeclaration(s,i,a,o,l,p)}parseEnum(e,t,i,n){if(e.next()!=114)return this.error(1003,e.range()),null;var s=k.createIdentifierExpression(e.readIdentifier(),e.range());if(e.next()!=61)return this.error(1005,e.range(),"{"),null;for(var a=new Array;!e.skip(62);){let l=this.parseEnumValue(e,0);if(!l)return null;if(a.push(l),!e.skip(70)){if(e.skip(62))break;return this.error(1005,e.range(),"}"),null}}var o=k.createEnumDeclaration(s,i,t,a,e.range(n,e.pos));return o.overriddenModuleName=this.currentModuleName,e.skip(69),o}parseEnumValue(e,t){if(!e.skipIdentifier())return this.error(1003,e.range()),null;var i=k.createIdentifierExpression(e.readIdentifier(),e.range()),n=null;return e.skip(100)&&(n=this.parseExpression(e,he.COMMA+1),!n)?null:k.createEnumValueDeclaration(i,t,n,se.join(i.range,e.range()))}parseReturn(e){var t=e.tokenPos,i=null;if(e.peek(!0)!=69&&e.nextToken!=62&&!e.nextTokenOnNewLine&&!(i=this.parseExpression(e)))return null;var n=k.createReturnStatement(i,e.range(t,e.pos));return e.skip(69),n}parseTypeParameters(e){for(var t=new Array,i=!1,n=e.tokenPos;!e.skip(72);){let s=this.parseTypeParameter(e);if(!s)return null;if(s.defaultType?i=!0:i&&(this.error(2706,s.range),s.defaultType=null),t.push(s),!e.skip(70)){if(e.skip(72))break;return this.error(1005,e.range(),">"),null}}return t.length||this.error(1098,e.range(n,e.pos)),t}parseTypeParameter(e){if(e.next()==114){let t=k.createIdentifierExpression(e.readIdentifier(),e.range()),i=null;if(e.skip(19)){let s=this.parseType(e);if(!s)return null;if(s.kind!=1)return this.error(1003,s.range),null;i=s}let n=null;if(e.skip(100)){let s=this.parseType(e);if(!s)return null;if(s.kind!=1)return this.error(1003,s.range),null;n=s}return k.createTypeParameter(t,i,n,se.join(t.range,e.range()))}else this.error(1003,e.range());return null}parseParameters(e,t=!1){var i=new Array,n=null,s=!1,a=!1,o=null;if(this.parseParametersThis=null,e.skip(50)){if(e.skip(99)){if(o=this.parseType(e),!o)return null;o.kind==1?this.parseParametersThis=o:this.error(1003,o.range)}else return this.error(1005,e.range(),":"),null;if(!e.skip(70))return e.skip(64)?i:(this.error(1005,e.range(),")"),null)}for(;!e.skip(64);){let l=this.parseParameter(e,t);if(!l)return null;switch(n&&!a&&(this.error(1014,n.name.range),a=!0),l.parameterKind){default:{s&&this.error(1016,l.name.range);break}case 1:{s=!0;break}case 2:{n=l;break}}if(i.push(l),!e.skip(70)){if(e.skip(64))break;return this.error(1005,e.range(),")"),null}}return i}parseParameter(e,t=!1){var i=!1,n=!1,s=null,a=0;if(t&&(e.skip(43)?(s=e.range(),a|=256):e.skip(42)?(s=e.range(),a|=1024):e.skip(41)&&(s=e.range(),a|=512),e.peek()==44)){let o=e.mark();e.next(),e.peek()!=99?(e.discard(o),s||(s=e.range()),a|=64):e.reset(o)}if(e.skip(68)&&(a?this.error(1317,e.range()):s=e.range(),i=!0),e.skipIdentifier()){i||(s=e.range());let o=k.createIdentifierExpression(e.readIdentifier(),e.range()),l=null;if((n=e.skip(98))&&i&&this.error(1047,o.range),e.skip(99)){if(l=this.parseType(e),!l)return null}else l=k.createOmittedType(e.range(e.pos));let p=null;if(e.skip(100)&&(i&&this.error(1048,o.range),n?this.error(1015,o.range):n=!0,p=this.parseExpression(e,he.COMMA+1),!p))return null;let c=k.createParameter(i?2:n?1:0,o,l,p,se.join(assert(s),e.range()));return c.flags|=a,c}else this.error(1003,e.range());return null}parseFunction(e,t,i,n){if(!e.skipIdentifier())return this.error(1003,e.range(e.pos)),null;var s=k.createIdentifierExpression(e.readIdentifier(),e.range()),a=-1,o=null;if(e.skip(71)){if(a=e.tokenPos,o=this.parseTypeParameters(e),!o)return null;t|=32768}if(!e.skip(63))return this.error(1005,e.range(e.pos),"("),null;a<0&&(a=e.tokenPos);var l=this.parseParameters(e);if(!l)return null;var p=this.parseParametersThis,c=(t&4096)!=0;c&&(l.length!=1&&this.error(1049,s.range),l.length>0&&l[0].initializer&&this.error(1052,s.range)),t&2048&&l.length&&this.error(1054,s.range);var _=null;if(e.skip(99)&&(_=this.parseType(e,!0,c),!_))return null;_||(_=k.createOmittedType(e.range(e.pos)),c||this.error(1110,_.range));var f=k.createFunctionType(l,_,p,!1,e.range(a,e.pos)),E=null;if(e.skip(61)){if(t&16384&&this.error(1183,e.range()),E=this.parseBlockStatement(e,!1),!E)return null}else t&16384||this.error(2391,e.range(e.pos));var g=k.createFunctionDeclaration(s,i,t,o,f,E,0,e.range(n,e.pos));return g.overriddenModuleName=this.currentModuleName,e.skip(69),g}parseFunctionExpression(e){var t=e.tokenPos,i,n=0;if(e.token==24){if(e.skipIdentifier()?i=k.createIdentifierExpression(e.readIdentifier(),e.range()):i=k.createEmptyIdentifierExpression(e.range(e.pos)),!e.skip(63))return this.error(1005,e.range(e.pos),"("),null}else n=1,assert(e.token==63),i=k.createEmptyIdentifierExpression(e.range(e.tokenPos));var s=e.pos,a=this.parseParameters(e);return a?this.parseFunctionExpressionCommon(e,i,a,this.parseParametersThis,n,t,s):null}parseFunctionExpressionCommon(e,t,i,n,s,a=-1,o=-1){a<0&&(a=t.range.start),o<0&&(o=a);var l=null;if(s!=2&&e.skip(99)){if(l=this.parseType(e),!l)return null}else l=k.createOmittedType(e.range(e.pos));if(s&&!e.skip(79))return this.error(1005,e.range(e.pos),"=>"),null;var p=k.createFunctionType(i,l,n,!1,e.range(o,e.pos)),c=null;if(s)if(e.skip(61))c=this.parseBlockStatement(e,!1);else{let f=this.parseExpression(e,he.COMMA+1);f&&(c=k.createExpressionStatement(f))}else{if(!e.skip(61))return this.error(1005,e.range(e.pos),"{"),null;c=this.parseBlockStatement(e,!1)}if(!c)return null;var _=k.createFunctionDeclaration(t,null,0,null,p,c,s,e.range(a,e.pos));return k.createFunctionExpression(_)}parseClassOrInterface(e,t,i,n){var s=e.token==31;if(!e.skipIdentifier())return this.error(1003,e.range()),null;var a=k.createIdentifierExpression(e.readIdentifier(),e.range()),o=null;if(e.skip(71)){if(o=this.parseTypeParameters(e),!o)return null;t|=32768}var l=null;if(e.skip(19)){let f=this.parseType(e);if(!f)return null;if(f.kind!=1)return this.error(1003,f.range),null;l=f}var p=null;if(e.skip(27)){s&&this.error(1176,e.range());do{let f=this.parseType(e);if(!f)return null;if(f.kind!=1)return this.error(1003,f.range),null;s||(p||(p=[]),p.push(f))}while(e.skip(70))}if(!e.skip(61))return this.error(1005,e.range(),"{"),null;var c=new Array,_;if(s?(assert(!p),_=k.createInterfaceDeclaration(a,i,t,o,l,null,c,e.range(n,e.pos))):_=k.createClassDeclaration(a,i,t,o,l,p,c,e.range(n,e.pos)),!e.skip(62))do{let f=this.parseClassMember(e,_);if(f)f.kind==65?_.indexSignature=f:(assert(f instanceof We),c.push(f));else if(this.skipStatement(e),e.skip(120))return this.error(1005,e.range(),"}"),null}while(!e.skip(62));return _.range.end=e.pos,_.overriddenModuleName=this.currentModuleName,_}parseClassExpression(e){var t=e.tokenPos,i;if(e.skipIdentifier()?i=k.createIdentifierExpression(e.readIdentifier(),e.range()):i=k.createEmptyIdentifierExpression(e.range(e.pos)),!e.skip(61))return this.error(1005,e.range(e.pos),"{"),null;var n=new Array,s=k.createClassDeclaration(i,null,0,null,null,null,n,e.range(t,e.pos));if(!e.skip(62))do{let a=this.parseClassMember(e,s);if(a)a.kind==65?s.indexSignature=a:(assert(s instanceof We),n.push(a));else if(this.skipStatement(e),e.skip(120))return this.error(1005,e.range(),"}"),null}while(!e.skip(62));return s.range.end=e.pos,k.createClassExpression(s)}parseClassMember(e,t){var i=t.kind==57,n=0,s=null;if(e.skip(113)){n=e.tokenPos;do{let ee=this.parseDecorator(e);if(!ee)break;s||(s=new Array),s.push(ee)}while(e.skip(113));i&&s&&this.error(1206,se.join(s[0].range,s[s.length-1].range))}var a=t.flags&16384;i&&(a|=134217728);var o=0,l=0,p=t.is(16384);e.skip(12)?(i?this.error(1042,e.range(),"declare"):p?this.error(1038,e.range()):(a|=16388,o=e.tokenPos,l=e.pos),n||(n=e.tokenPos)):p&&(a|=16384);var c=0,_=0;e.skip(43)?(i?this.error(1042,e.range(),"public"):(a|=256,c=e.tokenPos,_=e.pos),n||(n=e.tokenPos)):e.skip(41)?(i?this.error(1042,e.range(),"private"):(a|=512,c=e.tokenPos,_=e.pos),n||(n=e.tokenPos)):e.skip(42)&&(i?this.error(1042,e.range(),"protected"):(a|=1024,c=e.tokenPos,_=e.pos),n||(n=e.tokenPos));var f=0,E=0,g=0,b=0;e.skip(47)?(i?this.error(1042,e.range(),"static"):(a|=32,f=e.tokenPos,E=e.pos),n||(n=e.tokenPos)):(a|=131072,e.skip(0)&&(i||!t.is(128)?this.error(1042,e.range(),"abstract"):(a|=128,g=e.tokenPos,b=e.pos),n||(n=e.tokenPos)),t.flags&32768&&(a|=65536));var S=0,v=0;if(e.peek()==44){let ee=e.mark();e.next(),e.peek()!=99?(e.discard(ee),a|=64,S=e.tokenPos,v=e.pos,n||(n=S)):e.reset(ee)}var x=e.mark(),L=!1,P=!1,F=0,w=0,U=!1,Y=0,z=0;i||(e.skip(25)?e.peek(!0,1)==114&&!e.nextTokenOnNewLine?(a|=2048,P=!0,F=e.tokenPos,w=e.pos,n||(n=F),a&64&&this.error(1042,e.range(S,v),"readonly")):e.reset(x):e.skip(46)?e.peek(!0,1)==114&&!e.nextTokenOnNewLine?(a|=4096,U=!0,Y=e.tokenPos,z=e.pos,n||(n=Y),a&64&&this.error(1042,e.range(S,v),"readonly")):e.reset(x):e.skip(10)&&(a|=262144,L=!0,n||(n=e.tokenPos),a&32&&this.error(1042,e.range(f,E),"static"),a&128&&this.error(1042,e.range(g,b),"abstract"),a&64&&this.error(1042,e.range(S,v),"readonly")));var H=P||U,Q;if(L)Q=k.createConstructorExpression(e.range());else{if(!H&&e.skip(65)){n||(n=e.tokenPos),a&256?this.error(1042,e.range(c,_),"public"):a&1024?this.error(1042,e.range(c,_),"protected"):a&512&&this.error(1042,e.range(c,_),"protected"),a&32&&this.error(1042,e.range(f,E),"static"),a&128&&this.error(1042,e.range(g,b),"abstract");let ee=this.parseIndexSignature(e,a,s);return ee?(e.skip(69),ee):(a&64&&this.error(1042,e.range(S,v),"readonly"),null)}if(!e.skipIdentifier(2))return this.error(1003,e.range()),null;n||(n=e.tokenPos),Q=k.createIdentifierExpression(e.readIdentifier(),e.range())}var le=null;if(e.skip(71)){let ee=e.tokenPos;if(le=this.parseTypeParameters(e),!le)return null;L?this.error(1092,e.range(ee,e.pos)):H?this.error(1094,e.range(ee,e.pos)):a|=32768}if(e.skip(63)){a&4&&this.error(1031,e.range(o,l),"declare");let ee=e.tokenPos,j=this.parseParameters(e,L);if(!j)return null;let D=this.parseParametersThis;if(L)for(let ft=0,mi=j.length;ft0&&j[0].initializer&&this.error(1052,Q.range)):Q.text=="constructor"&&this.error(230,Q.range,"constructor");let _e=null;if(e.skip(99)){if(Q.kind==26?this.error(1093,e.range()):U&&this.error(1095,e.range()),_e=this.parseType(e,U||Q.kind==26),!_e)return null}else _e=k.createOmittedType(e.range(e.pos)),!U&&Q.kind!=26&&this.error(1110,_e.range);let Ct=k.createFunctionType(j,_e,D,!1,e.range(ee,e.pos)),qe=null;if(e.skip(61)){if(a&16384?this.error(1183,e.range()):a&128?this.error(1245,e.range(),Q.text):i&&this.error(1005,e.range(),";"),qe=this.parseBlockStatement(e,!1),!qe)return null}else!i&&!(a&16512)&&this.error(2391,e.range());let Jt=k.createMethodDeclaration(Q,s,a,le,Ct,qe,e.range(n,e.pos));return i&&e.skip(70)||e.skip(69),Jt}else if(L)this.error(2390,Q.range);else if(H)this.error(2391,Q.range);else{a&4&&this.error(100,e.range(o,l),"Ambient fields"),a&128&&this.error(1042,e.range(g,b),"abstract"),a&2048&&this.error(1042,e.range(F,w),"get"),a&4096&&this.error(1042,e.range(Y,z),"set");let ee=null;if(e.skip(98)&&this.error(219,e.range(n,e.pos)),e.skip(94)&&(a|=8192),e.skip(99)){if(ee=this.parseType(e),!ee)return null}else this.error(1110,e.range());let j=null;if(e.skip(100)&&(a&16384&&this.error(1039,e.range()),j=this.parseExpression(e),!j))return null;let D=e.range(n,e.pos);(a&8192)!=0&&(i||j||(a&32)!=0)&&this.error(1255,D);let _e=k.createFieldDeclaration(Q,s,a,ee,j,D);return i&&e.skip(70)||e.skip(69),_e}return null}parseIndexSignature(e,t,i){i&&i.length>0&&this.error(1206,se.join(i[0].range,i[i.length-1].range));var n=e.tokenPos;if(e.skipIdentifier())if(e.readIdentifier()=="key")if(e.skip(99)){let a=this.parseType(e);if(!a)return null;if(a.kind!=1)return this.error(1110,e.range()),null;if(e.skip(66))if(e.skip(99)){let o=this.parseType(e);return o?o.kind!=1?(this.error(1003,o.range),null):k.createIndexSignature(a,o,t,e.range(n,e.pos)):null}else this.error(1005,e.range(),":");else this.error(1005,e.range(),"]")}else this.error(1005,e.range(),":");else this.error(1005,e.range(),"key");else this.error(1003,e.range());return null}parseNamespace(e,t,i,n){if(e.skipIdentifier()){let s=k.createIdentifierExpression(e.readIdentifier(),e.range());if(e.skip(61)){let a=new Array,o=k.createNamespaceDeclaration(s,i,t,a,e.range(n,e.pos));for(;!e.skip(62);){let l=this.parseTopLevelStatement(e,o);if(l)a.push(l);else if(this.skipStatement(e),e.skip(120))return this.error(1005,e.range(),"}"),null}return o.range.end=e.pos,o.overriddenModuleName=this.currentModuleName,e.skip(69),o}else this.error(1005,e.range(),"{")}else this.error(1003,e.range());return null}parseExport(e,t,i){var n=null,s=assert(this.currentSource);if(e.skip(61)){let a=new Array;for(;!e.skip(62);){let l=this.parseExportMember(e);if(!l)return null;if(a.push(l),!e.skip(70)){if(e.skip(62))break;return this.error(1005,e.range(),"}"),null}}if(e.skip(23))if(e.skip(115))n=k.createStringLiteralExpression(e.readString(),e.range());else return this.error(1141,e.range()),null;let o=k.createExportStatement(a,n,i,e.range(t,e.pos));if(n){let l=assert(o.internalPath);this.seenlog.has(l)||(this.dependees.set(l,new ys(s,n)),this.backlog.push(l),this.seenlog.add(l))}return e.skip(69),o}else if(e.skip(83))if(e.skip(23))if(e.skip(115)){n=k.createStringLiteralExpression(e.readString(),e.range());let a=k.createExportStatement(null,n,i,e.range(t,e.pos)),o=assert(a.internalPath),l=e.source,p=l.exportPaths;return p?p.includes(o)||p.push(o):l.exportPaths=[o],this.seenlog.has(o)||(this.dependees.set(o,new ys(s,n)),this.backlog.push(o)),e.skip(69),a}else this.error(1141,e.range());else this.error(1005,e.range(),"from");else this.error(1005,e.range(),"{");return null}parseExportMember(e){if(e.skipIdentifier(2)){let t=k.createIdentifierExpression(e.readIdentifier(),e.range()),i=null;if(e.skip(1))if(e.skipIdentifier(2))i=k.createIdentifierExpression(e.readIdentifier(),e.range());else return this.error(1003,e.range()),null;return i?k.createExportMember(t,i,se.join(t.range,i.range)):k.createExportMember(t,null,t.range)}else this.error(1003,e.range());return null}parseExportDefaultAlias(e,t,i,n){var s=e.readIdentifier(),a=e.range(),o=k.createExportStatement([k.createExportMember(k.createIdentifierExpression(s,a),k.createIdentifierExpression("default",e.range(i,n)),a)],null,!1,e.range(t,e.pos));return e.skip(69),o}parseImport(e){var t=e.tokenPos,i=null,n=null,s=!1;if(e.skip(61))for(i=new Array;!e.skip(62);){let a=this.parseImportDeclaration(e);if(!a)return null;if(i.push(a),!e.skip(70)){if(e.skip(62))break;return this.error(1005,e.range(),"}"),null}}else if(e.skip(83))if(e.skip(1))if(e.skipIdentifier())n=k.createIdentifierExpression(e.readIdentifier(),e.range());else return this.error(1003,e.range()),null;else return this.error(1005,e.range(),"as"),null;else if(e.skip(114,1)){let a=e.readIdentifier(),o=e.range();if(i=[k.createImportDeclaration(k.createIdentifierExpression("default",o),k.createIdentifierExpression(a,o),o)],e.skip(70))return this.error(100,e.range(),"Mixed default and named imports"),null}else s=!0;if(s||e.skip(23))if(e.skip(115)){let a=k.createStringLiteralExpression(e.readString(),e.range()),o;n?(assert(!i),o=k.createWildcardImportStatement(n,a,e.range(t,e.pos))):o=k.createImportStatement(i,a,e.range(t,e.pos));let l=o.internalPath;return this.seenlog.has(l)||(this.dependees.set(l,new ys(assert(this.currentSource),a)),this.backlog.push(l)),e.skip(69),o}else this.error(1141,e.range());else this.error(1005,e.range(),"from");return null}parseImportDeclaration(e){if(e.skipIdentifier(2)){let t=k.createIdentifierExpression(e.readIdentifier(),e.range()),i=null;if(e.skip(1))if(e.skipIdentifier())i=k.createIdentifierExpression(e.readIdentifier(),e.range());else return this.error(1003,e.range()),null;return i?k.createImportDeclaration(t,i,se.join(t.range,i.range)):k.createImportDeclaration(t,null,t.range)}else this.error(1003,e.range());return null}parseExportImport(e,t){if(e.skipIdentifier()){let i=k.createIdentifierExpression(e.readIdentifier(),e.range());if(e.skip(100))if(e.skipIdentifier()){let n=k.createIdentifierExpression(e.readIdentifier(),e.range()),s=k.createExportImportStatement(n,i,e.range(t,e.pos));return e.skip(69),s}else this.error(1003,e.range());else this.error(1005,e.range(),"=")}else this.error(1003,e.range());return null}parseStatement(e,t=!1){var i=e.mark(),n=e.next(),s=null;switch(n){case 4:{s=this.parseBreak(e);break}case 8:{s=this.parseVariable(e,8,null,e.tokenPos);break}case 9:{s=this.parseContinue(e);break}case 15:{s=this.parseDoStatement(e);break}case 22:{s=this.parseForStatement(e);break}case 26:{s=this.parseIfStatement(e);break}case 34:{s=this.parseVariable(e,16,null,e.tokenPos);break}case 56:{s=this.parseVariable(e,0,null,e.tokenPos);break}case 61:{s=this.parseBlockStatement(e,t);break}case 45:{t&&this.error(1108,e.range()),s=this.parseReturn(e);break}case 69:return k.createEmptyStatement(e.range(e.tokenPos));case 49:{s=this.parseSwitchStatement(e);break}case 51:{s=this.parseThrowStatement(e);break}case 53:{s=this.parseTryStatement(e);break}case 57:{s=this.parseVoidStatement(e);break}case 58:{s=this.parseWhileStatement(e);break}case 54:if(e.peek(!1,1)==114){s=this.parseTypeDeclaration(e,0,null,e.tokenPos);break}default:{e.reset(i),s=this.parseExpressionStatement(e);break}}return s?e.discard(i):(e.reset(i),this.skipStatement(e)),s}parseBlockStatement(e,t){for(var i=e.tokenPos,n=new Array;!e.skip(62);){let a=e.mark(),o=this.parseStatement(e,t);if(o)e.discard(a),n.push(o);else{if(e.token==120)return null;e.reset(a),this.skipStatement(e)}}var s=k.createBlockStatement(n,e.range(i,e.pos));return e.skip(69),s}parseBreak(e){var t=null;e.peek(!0)==114&&!e.nextTokenOnNewLine&&(e.next(1),t=k.createIdentifierExpression(e.readIdentifier(),e.range()));var i=k.createBreakStatement(t,e.range());return e.skip(69),i}parseContinue(e){var t=null;e.peek(!0)==114&&!e.nextTokenOnNewLine&&(e.next(1),t=k.createIdentifierExpression(e.readIdentifier(),e.range()));var i=k.createContinueStatement(t,e.range());return e.skip(69),i}parseDoStatement(e){var t=e.tokenPos,i=this.parseStatement(e);if(!i)return null;if(e.skip(58))if(e.skip(63)){let n=this.parseExpression(e);if(!n)return null;if(e.skip(64)){let s=k.createDoStatement(i,n,e.range(t,e.pos));return e.skip(69),s}else this.error(1005,e.range(),")")}else this.error(1005,e.range(),"(");else this.error(1005,e.range(),"while");return null}parseExpressionStatement(e){var t=this.parseExpression(e);if(!t)return null;var i=k.createExpressionStatement(t);return e.skip(69),i}parseForStatement(e){var t=e.tokenPos;if(e.skip(63)){let i=null;if(e.skip(8))i=this.parseVariable(e,8,null,e.tokenPos,!0);else if(e.skip(34))i=this.parseVariable(e,16,null,e.tokenPos,!0);else if(e.skip(56))i=this.parseVariable(e,0,null,e.tokenPos,!0);else if(!e.skip(69)&&(i=this.parseExpressionStatement(e),!i))return null;if(i){if(e.skip(39)){if(i.kind==38)return i.expression.kind!=6?(this.error(1003,i.range),null):this.parseForOfStatement(e,t,i);if(i.kind==47){let n=i.declarations;for(let s=0,a=n.length;s"),null;let s=this.parseExpression(e,he.CALL);return s?k.createAssertionExpression(0,s,n,e.range(i,e.pos)):null}case 114:{let n=e.readIdentifier();if(n=="null")return k.createNullExpression(e.range());let s=k.createIdentifierExpression(n,e.range(i,e.pos));return e.skip(118)?this.parseTemplateLiteral(e,s):e.peek(!0)==79&&!e.nextTokenOnNewLine?this.parseFunctionExpressionCommon(e,k.createEmptyIdentifierExpression(e.range(i)),[k.createParameter(0,s,k.createOmittedType(s.range.atEnd),null,s.range)],null,2,i):this.maybeParseCallExpression(e,s,!0)}case 48:{e.peek()!=67&&e.nextToken!=63&&this.error(1034,e.range());let n=k.createSuperExpression(e.range(i,e.pos));return this.maybeParseCallExpression(e,n)}case 115:return k.createStringLiteralExpression(e.readString(),e.range(i,e.pos));case 118:return this.parseTemplateLiteral(e);case 116:{let n=e.readInteger();return e.checkForIdentifierStartAfterNumericLiteral(),k.createIntegerLiteralExpression(n,e.range(i,e.pos))}case 117:{let n=e.readFloat();return e.checkForIdentifierStartAfterNumericLiteral(),k.createFloatLiteralExpression(n,e.range(i,e.pos))}case 84:{let n=e.readRegexpPattern();return e.skip(84)?k.createRegexpLiteralExpression(n,e.readRegexpFlags(),e.range(i,e.pos)):(this.error(1005,e.range(),"/"),null)}case 24:{let n=this.parseFunctionExpression(e);return n?this.maybeParseCallExpression(e,n):null}case 7:return this.parseClassExpression(e);default:return t==120?this.error(1126,e.range(i)):this.error(1109,e.range()),null}}tryParseTypeArgumentsBeforeArguments(e){var t=e.mark();if(!e.skip(71))return null;var i=e.tokenPos,n=null;do{if(e.peek()==72)break;let s=this.parseType(e,!0,!0);if(!s)return e.reset(t),null;n?n.push(s):n=[s]}while(e.skip(70));if(e.skip(72)){let s=e.pos;if(e.skip(63))return n||this.error(1099,e.range(i,s)),n}return e.reset(t),null}parseArguments(e){for(var t=new Array;!e.skip(64);){let i=this.parseExpression(e,he.COMMA+1);if(!i)return null;if(t.push(i),!e.skip(70)){if(e.skip(64))break;return this.error(1005,e.range(),")"),null}}return t}parseExpression(e,t=he.COMMA){assert(t!=he.NONE);var i=this.parseExpressionStart(e);if(!i)return null;for(var n=i.range.start,s;(s=iE(e.peek()))>=t;){let a=e.next();switch(a){case 1:{if(e.skip(8))i=k.createAssertionExpression(3,i,null,e.range(n,e.pos));else{let o=this.parseType(e);if(!o)return null;i=k.createAssertionExpression(1,i,o,e.range(n,e.pos))}break}case 94:{i=k.createAssertionExpression(2,i,null,e.range(n,e.pos)),i=this.maybeParseCallExpression(e,i);break}case 30:{let o=this.parseType(e);if(!o)return null;i=k.createInstanceOfExpression(i,o,e.range(n,e.pos));break}case 65:{let o=this.parseExpression(e);if(!o)return null;if(!e.skip(66))return this.error(1005,e.range(),"]"),null;i=k.createElementAccessExpression(i,o,e.range(n,e.pos)),i=this.maybeParseCallExpression(e,i);break}case 86:case 87:{i.kind!=6&&i.kind!=12&&i.kind!=21&&this.error(2357,i.range),i=k.createUnaryPostfixExpression(a,i,e.range(n,e.pos));break}case 98:{let o=this.parseExpression(e);if(!o)return null;if(!e.skip(99))return this.error(1005,e.range(),":"),null;let l=this.parseExpression(e,t>he.COMMA?he.COMMA+1:he.COMMA);if(!l)return null;i=k.createTernaryExpression(i,o,l,e.range(n,e.pos));break}case 70:{let o=[i];do{if(i=this.parseExpression(e,he.COMMA+1),!i)return null;o.push(i)}while(e.skip(70));i=k.createCommaExpression(o,e.range(n,e.pos));break}case 67:{if(e.skipIdentifier(2)){let o=k.createIdentifierExpression(e.readIdentifier(),e.range());i=k.createPropertyAccessExpression(i,o,e.range(n,e.pos))}else{let o=this.parseExpression(e,s+1);if(!o)return null;if(o.kind==9){if(i=this.joinPropertyCall(e,n,i,o),!i)return null}else return this.error(1003,o.range),null}if(e.skip(118)){if(i=this.parseTemplateLiteral(e,i),!i)return null}else i=this.maybeParseCallExpression(e,i,!0);break}case 100:case 101:case 102:case 104:case 103:case 105:case 106:case 107:case 108:case 109:case 110:case 112:case 111:case 82:{let o=this.parseExpression(e,s);if(!o)return null;i=k.createBinaryExpression(a,i,o,e.range(n,e.pos));break}case 71:case 72:case 73:case 74:case 75:case 77:case 78:case 76:case 80:case 81:case 83:case 84:case 85:case 88:case 89:case 90:case 91:case 92:case 93:case 96:case 97:{let o=this.parseExpression(e,s+1);if(!o)return null;i=k.createBinaryExpression(a,i,o,e.range(n,e.pos));break}default:assert(!1)}}return i}parseTemplateLiteral(e,t=null){var i=t?t.range.start:e.tokenPos,n=new Array,s=new Array,a=new Array;for(n.push(e.readString(0,t!=null)),s.push(e.source.text.substring(e.readStringStart,e.readStringEnd));e.readingTemplateString;){let o=this.parseExpression(e);if(!o)return null;if(a.push(o),!e.skip(62))return this.error(1005,e.range(),"}"),null;n.push(e.readString(96,t!=null)),s.push(e.source.text.substring(e.readStringStart,e.readStringEnd))}return k.createTemplateLiteralExpression(t,n,s,a,e.range(i,e.pos))}joinPropertyCall(e,t,i,n){var s=n.expression;switch(s.kind){case 6:{n.expression=k.createPropertyAccessExpression(i,s,e.range(t,e.pos));break}case 9:{let a=this.joinPropertyCall(e,t,i,s);if(!a)return null;n.expression=a,n.range=e.range(t,e.pos);break}default:return this.error(1003,n.range),null}return n}maybeParseCallExpression(e,t,i=!1){for(var n=null;e.skip(63)||i&&(n=this.tryParseTypeArgumentsBeforeArguments(e));){let s=this.parseArguments(e);if(!s)break;t=k.createCallExpression(t,n,s,e.range(t.range.start,e.pos)),i=!1}return t}skipStatement(e){e.peek(!0),e.nextTokenOnNewLine&&e.next();do{let t=e.peek(!0);if(t==120||t==69){e.next();break}if(e.nextTokenOnNewLine)break;switch(e.next()){case 114:{e.readIdentifier();break}case 115:case 118:{e.readString();break}case 116:{e.readInteger(),e.checkForIdentifierStartAfterNumericLiteral();break}case 117:{e.readFloat(),e.checkForIdentifierStartAfterNumericLiteral();break}case 61:{this.skipBlock(e);break}}}while(!0);e.readingTemplateString=!1}skipBlock(e){var t=1,i=!0;do switch(e.next()){case 120:{this.error(1005,e.range(),"}"),i=!1;break}case 61:{++t;break}case 62:{--t,t||(i=!1);break}case 114:{e.readIdentifier();break}case 115:{e.readString();break}case 118:{for(e.readString();e.readingTemplateString;)this.skipBlock(e),e.readString(96);break}case 116:{e.readInteger(),e.checkForIdentifierStartAfterNumericLiteral();break}case 117:{e.readFloat(),e.checkForIdentifierStartAfterNumericLiteral();break}}while(i)}},he=(w=>(w[w.NONE=0]="NONE",w[w.COMMA=1]="COMMA",w[w.SPREAD=2]="SPREAD",w[w.YIELD=3]="YIELD",w[w.ASSIGNMENT=4]="ASSIGNMENT",w[w.CONDITIONAL=5]="CONDITIONAL",w[w.LOGICAL_OR=6]="LOGICAL_OR",w[w.LOGICAL_AND=7]="LOGICAL_AND",w[w.BITWISE_OR=8]="BITWISE_OR",w[w.BITWISE_XOR=9]="BITWISE_XOR",w[w.BITWISE_AND=10]="BITWISE_AND",w[w.EQUALITY=11]="EQUALITY",w[w.RELATIONAL=12]="RELATIONAL",w[w.SHIFT=13]="SHIFT",w[w.ADDITIVE=14]="ADDITIVE",w[w.MULTIPLICATIVE=15]="MULTIPLICATIVE",w[w.EXPONENTIATED=16]="EXPONENTIATED",w[w.UNARY_PREFIX=17]="UNARY_PREFIX",w[w.UNARY_POSTFIX=18]="UNARY_POSTFIX",w[w.CALL=19]="CALL",w[w.MEMBERACCESS=20]="MEMBERACCESS",w[w.GROUPING=21]="GROUPING",w))(he||{});function iE(r){switch(r){case 70:return 1;case 100:case 101:case 102:case 104:case 103:case 105:case 106:case 107:case 108:case 109:case 110:case 112:case 111:return 4;case 98:return 5;case 97:return 6;case 96:return 7;case 92:return 8;case 93:return 9;case 91:return 10;case 75:case 76:case 77:case 78:return 11;case 1:case 29:case 30:case 71:case 72:case 73:case 74:return 12;case 88:case 89:case 90:return 13;case 80:case 81:return 14;case 83:case 84:case 85:return 15;case 82:return 16;case 86:case 87:return 18;case 67:case 65:case 94:return 20}return 0}var vc=16,ei=vc-1,wl=class{constructor(e,t,i,n,s){this.localFile=e;this.localIdentifier=t;this.foreignIdentifier=i;this.foreignPath=n;this.foreignPathAlt=s}},Ml=class{constructor(e,t,i,n){this.localIdentifier=e;this.foreignIdentifier=t;this.foreignPath=i;this.foreignPathAlt=n}},xc=class{constructor(e,t,i){this.foreignPath=e;this.foreignPathAlt=t;this.pathLiteral=i}},Ce=(D=>(D[D.INVALID=0]="INVALID",D[D.INDEXED_GET=1]="INDEXED_GET",D[D.INDEXED_SET=2]="INDEXED_SET",D[D.UNCHECKED_INDEXED_GET=3]="UNCHECKED_INDEXED_GET",D[D.UNCHECKED_INDEXED_SET=4]="UNCHECKED_INDEXED_SET",D[D.ADD=5]="ADD",D[D.SUB=6]="SUB",D[D.MUL=7]="MUL",D[D.DIV=8]="DIV",D[D.REM=9]="REM",D[D.POW=10]="POW",D[D.BITWISE_AND=11]="BITWISE_AND",D[D.BITWISE_OR=12]="BITWISE_OR",D[D.BITWISE_XOR=13]="BITWISE_XOR",D[D.BITWISE_SHL=14]="BITWISE_SHL",D[D.BITWISE_SHR=15]="BITWISE_SHR",D[D.BITWISE_SHR_U=16]="BITWISE_SHR_U",D[D.EQ=17]="EQ",D[D.NE=18]="NE",D[D.GT=19]="GT",D[D.GE=20]="GE",D[D.LT=21]="LT",D[D.LE=22]="LE",D[D.PLUS=23]="PLUS",D[D.MINUS=24]="MINUS",D[D.NOT=25]="NOT",D[D.BITWISE_NOT=26]="BITWISE_NOT",D[D.PREFIX_INC=27]="PREFIX_INC",D[D.PREFIX_DEC=28]="PREFIX_DEC",D[D.POSTFIX_INC=29]="POSTFIX_INC",D[D.POSTFIX_DEC=30]="POSTFIX_DEC",D))(Ce||{});(n=>{function r(s,a){switch(assert(a.length),s){case 2:case 3:{switch(a.charCodeAt(0)){case 91:{if(a=="[]")return 1;if(a=="[]=")return 2;break}case 123:{if(a=="{}")return 3;if(a=="{}=")return 4;break}case 43:{if(a=="+")return 5;break}case 45:{if(a=="-")return 6;break}case 42:{if(a=="*")return 7;if(a=="**")return 10;break}case 47:{if(a=="/")return 8;break}case 37:{if(a=="%")return 9;break}case 38:{if(a=="&")return 11;break}case 124:{if(a=="|")return 12;break}case 94:{if(a=="^")return 13;break}case 61:{if(a=="==")return 17;break}case 33:{if(a=="!=")return 18;break}case 62:{if(a==">")return 19;if(a==">=")return 20;if(a==">>")return 15;if(a==">>>")return 16;break}case 60:{if(a=="<")return 21;if(a=="<=")return 22;if(a=="<<")return 14;break}}break}case 4:{switch(a.charCodeAt(0)){case 43:{if(a=="+")return 23;if(a=="++")return 27;break}case 45:{if(a=="-")return 24;if(a=="--")return 28;break}case 33:{if(a=="!")return 25;break}case 126:{if(a=="~")return 26;break}}break}case 5:{switch(a.charCodeAt(0)){case 43:{if(a=="++")return 29;break}case 45:{if(a=="--")return 30;break}}break}}return 0}n.fromDecorator=r;function e(s){switch(s){case 80:case 101:return 5;case 81:case 102:return 6;case 83:case 103:return 7;case 84:case 105:return 8;case 85:case 106:return 9;case 82:case 104:return 10;case 91:case 110:return 11;case 92:case 111:return 12;case 93:case 112:return 13;case 88:case 107:return 14;case 89:case 108:return 15;case 90:case 109:return 16;case 75:return 17;case 76:return 18;case 72:return 19;case 74:return 20;case 71:return 21;case 73:return 22}return 0}n.fromBinaryToken=e;function t(s){switch(s){case 80:return 23;case 81:return 24;case 94:return 25;case 95:return 26;case 86:return 27;case 87:return 28}return 0}n.fromUnaryPrefixToken=t;function i(s){switch(s){case 86:return 29;case 87:return 30}return 0}n.fromUnaryPostfixToken=i})(Ce||={});var bs=class extends ze{constructor(e,t=null){super(t);this.options=e;this.sources=[];this.diagnosticsOffset=0;this.nextClassId=0;this.nextSignatureId=0;this.initialized=!1;this.filesByName=new Map;this.elementsByName=new Map;this.elementsByDeclaration=new Map;this.instancesByName=new Map;this.wrapperClasses=new Map;this.managedClasses=new Map;this.uniqueSignatures=new Array(0);this.moduleExports=new Map;this.moduleImports=new Map;this._arrayBufferViewInstance=null;this._arrayBufferInstance=null;this._arrayPrototype=null;this._staticArrayPrototype=null;this._setPrototype=null;this._mapPrototype=null;this._functionPrototype=null;this._int8ArrayPrototype=null;this._int16ArrayPrototype=null;this._int32ArrayPrototype=null;this._int64ArrayPrototype=null;this._uint8ArrayPrototype=null;this._uint8ClampedArrayPrototype=null;this._uint16ArrayPrototype=null;this._uint32ArrayPrototype=null;this._uint64ArrayPrototype=null;this._float32ArrayPrototype=null;this._float64ArrayPrototype=null;this._stringInstance=null;this._objectInstance=null;this._templateStringsArrayInstance=null;this._allocInstance=null;this._reallocInstance=null;this._freeInstance=null;this._newInstance=null;this._renewInstance=null;this._linkInstance=null;this._collectInstance=null;this._visitInstance=null;this._typeinfoInstance=null;this._instanceofInstance=null;this._newBufferInstance=null;this._newArrayInstance=null;this._BLOCKInstance=null;this._OBJECTInstance=null;this.nativeDummySignature=null;var i=new zr(3,Ze+"native.ts","[native code]");this.nativeSource=i,this.parser=new gs(this.diagnostics,this.sources),this.resolver=new Zn(this);var n=new Ts(this,i);this.nativeFile=n,this.filesByName.set(n.internalName,n)}get nativeRange(){return this.nativeSource.range}get arrayBufferViewInstance(){var e=this._arrayBufferViewInstance;return e||(this._arrayBufferViewInstance=e=this.requireClass(O.ArrayBufferView)),e}get arrayBufferInstance(){var e=this._arrayBufferInstance;return e||(this._arrayBufferInstance=e=this.requireClass(O.ArrayBuffer)),e}get arrayPrototype(){var e=this._arrayPrototype;return e||(this._arrayPrototype=e=this.require(O.Array,J.CLASS_PROTOTYPE)),e}get staticArrayPrototype(){var e=this._staticArrayPrototype;return e||(this._staticArrayPrototype=e=this.require(O.StaticArray,J.CLASS_PROTOTYPE)),e}get setPrototype(){var e=this._setPrototype;return e||(this._setPrototype=e=this.require(O.Set,J.CLASS_PROTOTYPE)),e}get mapPrototype(){var e=this._mapPrototype;return e||(this._mapPrototype=e=this.require(O.Map,J.CLASS_PROTOTYPE)),e}get functionPrototype(){var e=this._functionPrototype;return e||(this._functionPrototype=e=this.require(O.Function,J.CLASS_PROTOTYPE)),e}get int8ArrayPrototype(){var e=this._int8ArrayPrototype;return e||(this._int8ArrayPrototype=e=this.require(O.Int8Array,J.CLASS_PROTOTYPE)),e}get int16ArrayPrototype(){var e=this._int16ArrayPrototype;return e||(this._int16ArrayPrototype=e=this.require(O.Int16Array,J.CLASS_PROTOTYPE)),e}get int32ArrayPrototype(){var e=this._int32ArrayPrototype;return e||(this._int32ArrayPrototype=e=this.require(O.Int32Array,J.CLASS_PROTOTYPE)),e}get int64ArrayPrototype(){var e=this._int64ArrayPrototype;return e||(this._int64ArrayPrototype=e=this.require(O.Int64Array,J.CLASS_PROTOTYPE)),e}get uint8ArrayPrototype(){var e=this._uint8ArrayPrototype;return e||(this._uint8ArrayPrototype=e=this.require(O.Uint8Array,J.CLASS_PROTOTYPE)),e}get uint8ClampedArrayPrototype(){var e=this._uint8ClampedArrayPrototype;return e||(this._uint8ClampedArrayPrototype=e=this.require(O.Uint8ClampedArray,J.CLASS_PROTOTYPE)),e}get uint16ArrayPrototype(){var e=this._uint16ArrayPrototype;return e||(this._uint16ArrayPrototype=e=this.require(O.Uint16Array,J.CLASS_PROTOTYPE)),e}get uint32ArrayPrototype(){var e=this._uint32ArrayPrototype;return e||(this._uint32ArrayPrototype=e=this.require(O.Uint32Array,J.CLASS_PROTOTYPE)),e}get uint64ArrayPrototype(){var e=this._uint64ArrayPrototype;return e||(this._uint64ArrayPrototype=e=this.require(O.Uint64Array,J.CLASS_PROTOTYPE)),e}get float32ArrayPrototype(){var e=this._float32ArrayPrototype;return e||(this._float32ArrayPrototype=e=this.require(O.Float32Array,J.CLASS_PROTOTYPE)),e}get float64ArrayPrototype(){var e=this._float64ArrayPrototype;return e||(this._float64ArrayPrototype=e=this.require(O.Float64Array,J.CLASS_PROTOTYPE)),e}get stringInstance(){var e=this._stringInstance;return e||(this._stringInstance=e=this.requireClass(O.String)),e}get objectInstance(){var e=this._objectInstance;return e||(this._objectInstance=e=this.requireClass(O.Object)),e}get templateStringsArrayInstance(){var e=this._templateStringsArrayInstance;return e||(this._templateStringsArrayInstance=e=this.requireClass(O.TemplateStringsArray)),e}get abortInstance(){var e=this.lookup(O.abort);return!e||e.kind!=J.FUNCTION_PROTOTYPE?null:this.resolver.resolveFunction(e,null)}get allocInstance(){var e=this._allocInstance;return e||(this._allocInstance=e=this.requireFunction(O.alloc)),e}get reallocInstance(){var e=this._reallocInstance;return e||(this._reallocInstance=e=this.requireFunction(O.realloc)),e}get freeInstance(){var e=this._freeInstance;return e||(this._freeInstance=e=this.requireFunction(O.free)),e}get newInstance(){var e=this._newInstance;return e||(this._newInstance=e=this.requireFunction(O.new_)),e}get renewInstance(){var e=this._renewInstance;return e||(this._renewInstance=e=this.requireFunction(O.renew)),e}get linkInstance(){var e=this._linkInstance;return e||(this._linkInstance=e=this.requireFunction(O.link)),e}get collectInstance(){var e=this._collectInstance;return e||(this._collectInstance=e=this.requireFunction(O.collect)),e}get visitInstance(){var e=this._visitInstance;return e||(this._visitInstance=e=this.requireFunction(O.visit)),e}get typeinfoInstance(){var e=this._typeinfoInstance;return e||(this._typeinfoInstance=e=this.requireFunction(O.typeinfo)),e}get instanceofInstance(){var e=this._instanceofInstance;return e||(this._instanceofInstance=e=this.requireFunction(O.instanceof_)),e}get newBufferInstance(){var e=this._newBufferInstance;return e||(this._newBufferInstance=e=this.requireFunction(O.newBuffer)),e}get newArrayInstance(){var e=this._newArrayInstance;return e||(this._newArrayInstance=e=this.requireFunction(O.newArray)),e}get BLOCKInstance(){var e=this._BLOCKInstance;return e||(this._BLOCKInstance=e=this.requireClass(O.BLOCK)),e}get OBJECTInstance(){var e=this._OBJECTInstance;return e||(this._OBJECTInstance=e=this.requireClass(O.OBJECT)),e}get isWasi(){return this.elementsByName.has(O.ASC_WASI)}getSource(e){var t=this.sources;for(let i=0;i=a||(i&o)!=0)throw new Error("invalid block size");return i}makeNativeVariableDeclaration(e,t=0){var i=this.nativeSource.range;return k.createVariableDeclaration(k.createIdentifierExpression(e,i),null,t,null,null,i)}makeNativeTypeDeclaration(e,t=0){var i=this.nativeSource.range,n=k.createIdentifierExpression(e,i);return k.createTypeDeclaration(n,null,t,null,k.createOmittedType(i),i)}makeNativeFunctionDeclaration(e,t=0){var i=this.nativeSource.range,n=this.nativeDummySignature;return n||(this.nativeDummySignature=n=k.createFunctionType([],k.createNamedType(k.createSimpleTypeName(O.void_,i),null,!1,i),null,!1,i)),k.createFunctionDeclaration(k.createIdentifierExpression(e,i),null,t,null,n,null,0,i)}makeNativeNamespaceDeclaration(e,t=0){var i=this.nativeSource.range;return k.createNamespaceDeclaration(k.createIdentifierExpression(e,i),null,t,[],i)}makeNativeFunction(e,t,i=this.nativeFile,n=0,s=Z.NONE){return new je(e,new Xe(e,i,this.makeNativeFunctionDeclaration(e,n),s),null,t)}getElementByDeclaration(e){var t=this.elementsByDeclaration;return t.has(e)?assert(t.get(e)):null}initialize(){if(!this.initialized){this.initialized=!0;var e=this.options;this.registerNativeType(O.i8,u.i8),this.registerNativeType(O.i16,u.i16),this.registerNativeType(O.i32,u.i32),this.registerNativeType(O.i64,u.i64),this.registerNativeType(O.isize,e.isizeType),this.registerNativeType(O.u8,u.u8),this.registerNativeType(O.u16,u.u16),this.registerNativeType(O.u32,u.u32),this.registerNativeType(O.u64,u.u64),this.registerNativeType(O.usize,e.usizeType),this.registerNativeType(O.bool,u.bool),this.registerNativeType(O.f32,u.f32),this.registerNativeType(O.f64,u.f64),this.registerNativeType(O.void_,u.void),this.registerNativeType(O.number,u.f64),this.registerNativeType(O.boolean,u.bool),this.nativeFile.add(O.native,new bt(O.native,this.nativeFile,this.makeNativeTypeDeclaration(O.native,32770),Z.BUILTIN)),this.nativeFile.add(O.indexof,new bt(O.indexof,this.nativeFile,this.makeNativeTypeDeclaration(O.indexof,32770),Z.BUILTIN)),this.nativeFile.add(O.valueof,new bt(O.valueof,this.nativeFile,this.makeNativeTypeDeclaration(O.valueof,32770),Z.BUILTIN)),this.nativeFile.add(O.returnof,new bt(O.returnof,this.nativeFile,this.makeNativeTypeDeclaration(O.returnof,32770),Z.BUILTIN)),this.nativeFile.add(O.nonnull,new bt(O.nonnull,this.nativeFile,this.makeNativeTypeDeclaration(O.nonnull,32770),Z.BUILTIN)),this.registerNativeType(O.v128,u.v128),this.registerNativeType(O.funcref,u.funcref),this.registerNativeType(O.externref,u.externref),this.registerNativeType(O.anyref,u.anyref),this.registerNativeType(O.eqref,u.eqref),this.registerNativeType(O.i31ref,u.i31ref),this.registerNativeType(O.dataref,u.dataref),this.registerConstantInteger(O.ASC_TARGET,u.i32,i64_new(e.isWasm64?2:1)),this.registerConstantInteger(O.ASC_RUNTIME,u.i32,i64_new(e.runtime)),this.registerConstantInteger(O.ASC_NO_ASSERT,u.bool,i64_new(e.noAssert?1:0,0)),this.registerConstantInteger(O.ASC_MEMORY_BASE,u.i32,i64_new(e.memoryBase,0)),this.registerConstantInteger(O.ASC_TABLE_BASE,u.i32,i64_new(e.tableBase,0)),this.registerConstantInteger(O.ASC_OPTIMIZE_LEVEL,u.i32,i64_new(e.optimizeLevelHint,0)),this.registerConstantInteger(O.ASC_SHRINK_LEVEL,u.i32,i64_new(e.shrinkLevelHint,0)),this.registerConstantInteger(O.ASC_LOW_MEMORY_LIMIT,u.i32,i64_new(e.lowMemoryLimit,0)),this.registerConstantInteger(O.ASC_EXPORT_RUNTIME,u.bool,i64_new(e.exportRuntime?1:0,0)),this.registerConstantInteger(O.ASC_VERSION_MAJOR,u.i32,i64_new(e.bundleMajorVersion)),this.registerConstantInteger(O.ASC_VERSION_MINOR,u.i32,i64_new(e.bundleMinorVersion)),this.registerConstantInteger(O.ASC_VERSION_PATCH,u.i32,i64_new(e.bundlePatchVersion)),this.registerConstantInteger(O.ASC_FEATURE_SIGN_EXTENSION,u.bool,i64_new(e.hasFeature(1)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_MUTABLE_GLOBALS,u.bool,i64_new(e.hasFeature(2)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_NONTRAPPING_F2I,u.bool,i64_new(e.hasFeature(4)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_BULK_MEMORY,u.bool,i64_new(e.hasFeature(8)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_SIMD,u.bool,i64_new(e.hasFeature(16)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_THREADS,u.bool,i64_new(e.hasFeature(32)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_EXCEPTION_HANDLING,u.bool,i64_new(e.hasFeature(64)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_TAIL_CALLS,u.bool,i64_new(e.hasFeature(128)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_REFERENCE_TYPES,u.bool,i64_new(e.hasFeature(256)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_MULTI_VALUE,u.bool,i64_new(e.hasFeature(512)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_GC,u.bool,i64_new(e.hasFeature(1024)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_MEMORY64,u.bool,i64_new(e.hasFeature(2048)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_FUNCTION_REFERENCES,u.bool,i64_new(e.hasFeature(4096)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_RELAXED_SIMD,u.bool,i64_new(e.hasFeature(8192)?1:0,0)),this.registerConstantInteger(O.ASC_FEATURE_EXTENDED_CONST,u.bool,i64_new(e.hasFeature(16384)?1:0,0));var t=new Array,i=new Map,n=new Map,s=new Array,a=new Array;for(let l=0,p=this.sources.length;l=48&&b<=57)this.registerConstantInteger(E,u.i32,i64_new(parseInt(g,10)));else{let S=this.elementsByName;S.has(g)?S.set(E,assert(S.get(g))):this.error(111,null,g)}}}for(let l=Map_values(this.filesByName),p=0,c=l.length;p(x[x.GLOBAL=0]="GLOBAL",x[x.LOCAL=1]="LOCAL",x[x.ENUM=2]="ENUM",x[x.ENUMVALUE=3]="ENUMVALUE",x[x.FUNCTION_PROTOTYPE=4]="FUNCTION_PROTOTYPE",x[x.FUNCTION=5]="FUNCTION",x[x.CLASS_PROTOTYPE=6]="CLASS_PROTOTYPE",x[x.CLASS=7]="CLASS",x[x.INTERFACE_PROTOTYPE=8]="INTERFACE_PROTOTYPE",x[x.INTERFACE=9]="INTERFACE",x[x.FIELD_PROTOTYPE=10]="FIELD_PROTOTYPE",x[x.FIELD=11]="FIELD",x[x.PROPERTY_PROTOTYPE=12]="PROPERTY_PROTOTYPE",x[x.PROPERTY=13]="PROPERTY",x[x.NAMESPACE=14]="NAMESPACE",x[x.FILE=15]="FILE",x[x.TYPEDEFINITION=16]="TYPEDEFINITION",x[x.INDEXSIGNATURE=17]="INDEXSIGNATURE",x))(J||{}),Z=(E=>(E[E.NONE=0]="NONE",E[E.GLOBAL=1]="GLOBAL",E[E.OPERATOR_BINARY=2]="OPERATOR_BINARY",E[E.OPERATOR_PREFIX=4]="OPERATOR_PREFIX",E[E.OPERATOR_POSTFIX=8]="OPERATOR_POSTFIX",E[E.UNMANAGED=16]="UNMANAGED",E[E.FINAL=32]="FINAL",E[E.INLINE=64]="INLINE",E[E.EXTERNAL=128]="EXTERNAL",E[E.EXTERNAL_JS=256]="EXTERNAL_JS",E[E.BUILTIN=512]="BUILTIN",E[E.LAZY=1024]="LAZY",E[E.UNSAFE=2048]="UNSAFE",E))(Z||{});(e=>{function r(t){switch(t){case 1:return 1;case 2:case 3:return 2;case 4:return 4;case 5:return 8;case 6:return 16;case 7:return 32;case 8:return 64;case 9:return 128;case 10:return 256;case 11:return 512;case 12:return 1024;case 13:return 2048;default:return 0}}e.fromKind=r})(Z||={});var Is=class{constructor(e,t,i,n,s){this.kind=e;this.name=t;this.internalName=i;this.program=n;this.flags=0;this.decoratorFlags=0;this.members=null;this.shadowType=null;this.program=n,this.name=t,this.internalName=i,s?this.parent=s:(assert(this.kind==15),this.parent=this)}get file(){var e=this;do if(e=e.parent,e.kind==15)return e;while(!0)}is(e){return(this.flags&e)==e}isAny(e){return(this.flags&e)!=0}set(e){this.flags|=e}unset(e){this.flags&=~e}hasDecorator(e){return(this.decoratorFlags&e)==e}hasAnyDecorator(e){return(this.decoratorFlags&e)!=0}getMember(e){var t=this.members;return t&&t.has(e)?assert(t.get(e)):null}lookup(e,t=!1){return this.parent.lookup(e,t)}add(e,t,i=null){var n=t.declaration,s=this.members;if(!s)this.members=s=new Map;else if(s.has(e)){let o=assert(s.get(e));if(o.parent==this){let l=zl(o,t);if(l)t=l;else{let p=i||t.identifierNode;return nn(o.kind)?this.program.errorRelated(2300,p.range,o.identifierNode.range,p.text):this.program.error(2300,p.range,p.text),!1}}}s.set(e,t);var a=this.program;return(t.kind!=4||!t.isBound)&&(a.elementsByName.set(t.internalName,t),a.elementsByDeclaration.set(n,t)),!0}get isPublic(){return!this.isAny(1536)}get isImplicitlyPublic(){return this.isPublic&&!this.is(256)}visibilityEquals(e){if(this.isPublic==e.isPublic)return!0;let t=1536;return(this.flags&t)==(e.flags&t)}toString(){return this.internalName+", kind="+this.kind.toString()}},Sc=new Set;function nn(r){return Sc.has(r)}var Gt=class extends Is{constructor(e,t,i,n,s,a){super(e,t,i,n,s);this.declaration=a;Sc.add(e),this.declaration=a,this.flags=a.flags}get isDeclaredInLibrary(){return this.declaration.range.source.isLibrary}get identifierNode(){return this.declaration.name}get identifierAndSignatureRange(){var e=this.declaration,t=e.name;if(e.kind==55||e.kind==58){let i=e.signature;return se.join(t.range,i.range)}return t.range}get decoratorNodes(){return this.declaration.decorators}isCompatibleOverride(e){var t=this,i=t.kind;if(i==e.kind)switch(i){case 5:return t.signature.isAssignableTo(e.signature,!0);case 13:{let n=t,s=e,a=n.getterInstance,o=s.getterInstance;if(a){if(!o||!a.signature.isAssignableTo(o.signature,!0))return!1}else if(o)return!1;let l=n.setterInstance,p=s.setterInstance;if(l){if(!p||!l.signature.isAssignableTo(p.signature,!0))return!1}else if(p)return!1;return!0}}return!1}},Rc=new Set;function Fo(r){return Rc.has(r)}var Vt=class extends Gt{constructor(e,t,i,n,s,a){super(e,t,i,n,s,a);this.type=u.void;Rc.add(e)}setType(e){assert(!this.is(2097152)),this.type=e,this.set(2097152)}},Ts=class extends Is{constructor(e,t){super(15,t.normalizedPath,t.internalPath,e,null);this.source=t;this.exports=null;this.exportsStar=null;this.aliasNamespaces=new Array;this.source=t,assert(!e.filesByName.has(this.internalName)),e.filesByName.set(this.internalName,this);var i=this.program.makeNativeFunction("start:"+this.internalName,new ve(e,null,u.void),this);i.internalName=i.name,this.startFunction=i}add(e,t,i=null){return t.hasDecorator(1)&&(t=this.program.ensureGlobal(e,t)),super.add(e,t,i)?(t=assert(this.getMember(e)),t.is(2)&&!i&&this.ensureExport(t.name,t),!0):!1}getMember(e){var t=super.getMember(e);if(t)return t;var i=this.exportsStar;if(i){for(let n=0,s=i.length;n(i[i.NONE=0]="NONE",i[i.INTEGER=1]="INTEGER",i[i.FLOAT=2]="FLOAT",i))(Dl||{}),ur=class extends Vt{constructor(e,t,i,n=i.program.makeNativeVariableDeclaration(t)){super(e,t,Te(t,i,n.is(131072)),i.program,i,n);this.constantValueKind=0;this.constantIntegerValue=i64_zero;this.constantFloatValue=0;this.flags=n.flags}get typeNode(){return this.declaration.type}get initializerNode(){return this.declaration.initializer}setConstantIntegerValue(e,t){assert(t.isIntegerInclReference),this.type=t,this.constantValueKind=1,this.constantIntegerValue=e,this.set(18874376)}setConstantFloatValue(e,t){assert(t.isFloatValue),this.type=t,this.constantValueKind=2,this.constantFloatValue=e,this.set(18874376)}},Bl=class extends ur{constructor(e,t,i,n=0){super(3,e,t,i);this.isImmutable=!1;this.decoratorFlags=n,this.setType(u.i32)}get valueNode(){return this.declaration.initializer}},ti=class extends ur{constructor(e,t,i,n=t.program.makeNativeVariableDeclaration(e)){super(0,e,t,n);this.decoratorFlags=i}},Ac=class{constructor(e,t,i=null){this.name=e;this.type=t;this.initializer=i}},De=class extends ur{constructor(e,t,i,n,s=n.program.makeNativeVariableDeclaration(e)){super(1,e,n,s);this.index=t;this.originalName=e,this.index=t,assert(i!=u.void),this.setType(i)}setTemporaryName(e){this.name=e,this.internalName=Te(e,this.parent,!1)}resetTemporaryName(){var e=this.originalName;this.name=e,this.internalName=Te(e,this.parent,!1)}},Xe=class extends Gt{constructor(e,t,i,n=0){super(4,e,Te(e,t,i.is(131072)),t.program,t,i);this.operatorKind=0;this.instances=null;this.overloads=null;this.boundPrototypes=null;this.decoratorFlags=n}get typeParameterNodes(){return this.declaration.typeParameters}get functionTypeNode(){return this.declaration.signature}get bodyNode(){return this.declaration.body}get arrowKind(){return this.declaration.arrowKind}get isBound(){var e=this.parent,t=e.kind;return t==12&&(t=e.parent.kind),t==7||t==9}toBound(e){assert(this.is(131072)),assert(!this.isBound);var t=this.boundPrototypes;if(!t)this.boundPrototypes=t=new Map;else if(t.has(e))return assert(t.get(e));var i=this.declaration;assert(i.kind==58);var n=new Xe(this.name,e,i,this.decoratorFlags);return n.flags=this.flags,n.operatorKind=this.operatorKind,n.overloads=this.overloads,t.set(e,n),n}getResolvedInstance(e){var t=this.instances;return t&&t.has(e)?assert(t.get(e)):null}setResolvedInstance(e,t){var i=this.instances;i?assert(!i.has(e)):this.instances=i=new Map,i.set(e,t)}},je=class extends Vt{constructor(e,t,i,n,s=null){super(5,e,Te(e,t.parent,t.is(131072)),t.program,t.parent,t.declaration);this.localsByName=new Map;this.localsByIndex=[];this.additionalLocals=[];this.debugLocations=[];this.ref=0;this.varargsStub=null;this.virtualStub=null;this.memorySegment=null;this.nextInlineId=0;this.nextAnonymousId=0;this.tempI32s=null;this.tempI64s=null;this.tempF32s=null;this.tempF64s=null;this.tempV128s=null;this.tempFuncrefs=null;this.tempExternrefs=null;this.tempAnyrefs=null;this.tempEqrefs=null;this.tempI31refs=null;this.tempDatarefs=null;this.nextBreakId=0;this.breakStack=null;this.breakLabel=null;this.prototype=t,this.typeArguments=i,this.signature=n,this.flags=t.flags|2097152,this.decoratorFlags=t.decoratorFlags,this.contextualTypeArguments=s,this.original=this;var a=t.program;if(this.type=n.type,!t.is(16384)){let o=0,l=n.thisType;if(l){let c=new De(O.this_,o++,l,this);this.localsByName.set(O.this_,c),this.localsByIndex[c.index]=c}let p=n.parameterTypes;for(let c=0,_=p.length;c<_;++c){let f=p[c],E=this.getParameterName(c),g=new De(E,o++,f,this);this.localsByName.set(E,g),this.localsByIndex[g.index]=g}}this.flow=Ue.createParent(this),Ss(a,this)}getParameterName(e){var t=this.declaration.signature.parameters;return t.length>e?t[e].name.text:Nc(e)}getClassOrInterface(){var e=this.parent;return e.kind==13&&(e=e.parent),e.kind==7||e.kind==9?e:null}newStub(e){var t=new je(this.original.name+sa+e,this.prototype,this.typeArguments,this.signature.clone(),this.contextualTypeArguments);return t.original=this.original,t.set(this.flags&-4194305|67108864),t}addLocal(e,t=null,i=null){var n=this.signature.parameterTypes.length+this.additionalLocals.length;this.is(131072)&&++n;var s=t??"var$"+n.toString();i||(i=this.program.makeNativeVariableDeclaration(s));var a=new De(s,n,e,this,i);if(t){if(this.localsByName.has(t))throw new Error("duplicate local name");this.localsByName.set(t,a)}return this.localsByIndex[a.index]=a,this.additionalLocals.push(e),a}lookup(e,t=!1){if(!t){let i=this.localsByName;if(i.has(e))return assert(i.get(e))}return super.lookup(e,t)}finalize(e,t){this.ref=t;var i=this.breakStack;if(assert(!i||!i.length),this.breakStack=i=null,this.breakLabel=null,this.tempI32s=this.tempI64s=this.tempF32s=this.tempF64s=null,this.program.options.sourceMap){let n=this.debugLocations;for(let s=0,a=n.length;s0)throw new Error("type argument count mismatch");Ss(s,this)}get id(){return this._id}get isBuiltinArray(){return this.prototype.isBuiltinArray}get isArrayLike(){if(this.isBuiltinArray)return!0;var e=this.getMember("length");return e?(e.kind==11||e.kind==12&&e.getterPrototype!=null)&&(this.lookupOverload(1)!=null||this.lookupOverload(3)!=null):!1}setBase(e){assert(!this.base),this.base=e;var t=e.extendees;t||(e.extendees=t=new Set),t.add(this);var i=e.contextualTypeArguments;if(i){let n=this.contextualTypeArguments;for(let s=Map_keys(i),a=0,o=s.length;a=0?this.ptrBinaryAdd:this.ptrBinarySub,t.global_get(h.stack_pointer,this.ptrType),this.ptrConst(abs(e))));return e>0?i:t.block(null,[i,this.makeStackCheck()],C.None)}makeStackFill(e,t){assert(e>0);var i=this.module;if(this.options.hasFeature(8)&&e>16)t.push(i.memory_fill(i.global_get(h.stack_pointer,this.ptrType),i.i32(0),this.ptrConst(e)));else{let n=e;for(;n>=8;)t.push(i.store(8,i.global_get(h.stack_pointer,this.ptrType),i.i64(0),C.I64,e-n)),n-=8;n&&(assert(n==4),t.push(i.store(4,i.global_get(h.stack_pointer,this.ptrType),i.i32(0),C.I32,e-n)))}}makeStackCheck(){var e=this.module;return this.hasStackCheckFunction||(this.hasStackCheckFunction=!0,e.addFunction("~stack_check",C.None,C.None,null,e.if(e.binary(17,e.global_get(h.stack_pointer,this.ptrType),e.global_get(h.data_end,this.ptrType)),this.compiler.makeStaticAbort(this.compiler.ensureStaticString("stack overflow"),this.compiler.program.nativeSource)))),e.call("~stack_check",null,C.None)}updateCallOperands(e){var t=this.module,i=0;for(let n=0,s=e.length;n0||this.shrinkLevelHint>0}hasFeature(e){return(this.features&e)!=0}},ql=(o=>(o[o.NONE=0]="NONE",o[o.CONV_IMPLICIT=1]="CONV_IMPLICIT",o[o.CONV_EXPLICIT=2]="CONV_EXPLICIT",o[o.MUST_WRAP=4]="MUST_WRAP",o[o.WILL_DROP=8]="WILL_DROP",o[o.PREFER_STATIC=16]="PREFER_STATIC",o[o.IS_THIS=32]="IS_THIS",o))(ql||{}),Ql=(l=>(l[l.NONE=0]="NONE",l[l.DATA=1]="DATA",l[l.STACK=2]="STACK",l[l.HEAP=4]="HEAP",l[l.RTTI=8]="RTTI",l[l.visitGlobals=16]="visitGlobals",l[l.visitMembers=32]="visitMembers",l[l.setArgumentsLength=64]="setArgumentsLength",l))(Ql||{}),ln;(n=>(n.argumentsLength="__argumentsLength",n.setArgumentsLength="__setArgumentsLength",n.memory="memory",n.table="table"))(ln||={});var wc=["__new","__pin","__unpin","__collect"],Mc=["__rtti_base"],oi=class extends ze{constructor(e){super(e.diagnostics);this.currentParent=null;this.currentType=u.void;this.memorySegments=[];this.stringSegments=new Map;this.functionTable=[];this.builtinArgumentsLength=0;this.runtimeFeatures=0;this.inlineStack=[];this.lazyFunctions=new Set;this.pendingClassInstanceOf=new Set;this.virtualStubs=new Set;this.pendingElements=new Set;this.doneModuleExports=new Set;this.hasCustomFunctionExports=!1;this.f32ModInstance=null;this.f64ModInstance=null;this.f32PowInstance=null;this.f64PowInstance=null;this.i32PowInstance=null;this.i64PowInstance=null;this._reusableCallExpression=null;this.program=e;var t=e.options,i=lt.create(t.stackSize>0,t.sizeTypeRef);this.module=i,t.memoryBase?(this.memoryOffset=i64_new(t.memoryBase),i.setLowMemoryUnused(!1)):!t.lowMemoryLimit&&t.optimizeLevelHint>=2?(this.memoryOffset=i64_new(1024),i.setLowMemoryUnused(!0)):(this.memoryOffset=i64_new(8),i.setLowMemoryUnused(!1));var n=0;t.hasFeature(1)&&(n|=32),t.hasFeature(2)&&(n|=2),t.hasFeature(4)&&(n|=4),t.hasFeature(8)&&(n|=16),t.hasFeature(16)&&(n|=8),t.hasFeature(32)&&(n|=1),t.hasFeature(64)&&(n|=64),t.hasFeature(128)&&(n|=128),t.hasFeature(256)&&(n|=256),t.hasFeature(512)&&(n|=512),t.hasFeature(1024)&&(n|=1024),t.hasFeature(2048)&&(n|=2048),t.hasFeature(4096)&&(n|=4096),t.hasFeature(8192)&&(n|=16384),t.hasFeature(16384)&&(n|=32768),i.setFeatures(n);var s=e.makeNativeFunction(h.start,new ve(e,[],u.void));s.internalName=h.start,this.currentFlow=s.flow,this.currentBody=new Array,this.shadowStack=new Hl(this)}get resolver(){return this.program.resolver}get options(){return this.program.options}static compile(e){return new oi(e).compile()}compile(){var e=this.options,t=this.module,i=this.program,n=this.resolver,s=e.stackSize>0;this.program.initialize();var a=this.currentFlow.actualFunction;assert(a.internalName==h.start);var o=this.currentBody;assert(o.length==0),e.isWasm64?(t.addGlobal(h.data_end,C.I64,!0,t.i64(0)),t.addGlobal(h.heap_base,C.I64,!0,t.i64(0)),t.addGlobal(h.rtti_base,C.I64,!0,t.i64(0))):(t.addGlobal(h.data_end,C.I32,!0,t.i32(0)),t.addGlobal(h.heap_base,C.I32,!0,t.i32(0)),t.addGlobal(h.rtti_base,C.I32,!0,t.i32(0)));var l=i.filesByName;for(let U=Map_values(l),Y=0,z=U.length;Yf.size||n.discoveredOverload);f.clear();for(let U=Set_values(_),Y=0,z=U.length;Y"),e.set(8388608),t.delete(e),!1;e.setType(this.currentType)}else return this.error(1110,e.identifierNode.range.atEnd),e.set(8388608),t.delete(e),!1;if(e.is(16384)&&e.hasDecorator(512)){let E=e.internalName;return E==h.data_end?this.runtimeFeatures|=1:E==h.stack_pointer?this.runtimeFeatures|=2:E==h.heap_base?this.runtimeFeatures|=4:E==h.rtti_base&&(this.runtimeFeatures|=8),t.delete(e),!0}var o=e.type,l=o.toRef(),p=e.is(8)||e.is(96),c=e.hasDecorator(64);if(e.is(16384))return p||this.options.hasFeature(2)?(Uc(e,e.declaration),this.program.markModuleImport(pr,zt,e),i.addGlobalImport(e.internalName,pr,zt,l,!p),t.delete(e),!0):(this.error(103,e.declaration.range,"mutable-globals"),e.set(8388608),t.delete(e),!1);var _=!1;if(a){if(!n){let E=this.currentFlow;e.hasDecorator(1024)&&(this.currentFlow=e.file.startFunction.flow),n=this.compileExpression(a,o,21),this.currentFlow=E}if(!i.isConstExpression(n))if(p){let E=i.runExpression(n,1);E?n=E:_=!0}else _=!0;if(_&&te(n)==10){let E=assert($i(n));if(!$l(i.getGlobal(E))){let g=this.program.elementsByName;g.has(E)&&assert(g.get(E)).is(16384)&&(_=!1)}}if(c)if(_)this.warning(206,a.range);else{switch(assert(te(n)==14),oe(n)){case C.I32:{e.constantValueKind=1,e.constantIntegerValue=i64_new(ie(n),0);break}case C.I64:{e.constantValueKind=1,e.constantIntegerValue=i64_new(Be(n),$e(n));break}case C.F32:{e.constantValueKind=2,e.constantFloatValue=Ye(n);break}case C.F64:{e.constantValueKind=2,e.constantFloatValue=He(n);break}default:return assert(!1),e.set(8388608),t.delete(e),!1}e.set(16777216)}}else e.is(16777216)?n=this.compileInlineConstant(e,e.type,16):n=this.makeZero(o,e.declaration);var f=e.internalName;return _?(c&&this.error(212,gt(8,e.decoratorNodes).range,"inline"),i.addGlobal(f,l,!0,this.makeZero(o,e.declaration)),this.currentBody.push(i.global_set(f,n))):c||i.addGlobal(f,l,!p,n),t.delete(e),!0}compileEnum(e){if(e.is(4194304))return!e.is(8388608);e.set(4194304);var t=this.pendingElements;t.add(e);var i=this.module,n=this.currentParent;this.currentParent=e;var s=null,a=!1,o=e.is(8)||e.hasDecorator(64),l=e.members;if(l)for(let p=Map_values(l),c=0,_=p.length;c<_;++c){let f=unchecked(p[c]);if(f.kind!=3)continue;let E=!1,g=f,b=g.valueNode;g.set(4194304);let S=this.currentFlow;e.hasDecorator(1024)&&(this.currentFlow=e.file.startFunction.flow);let v;if(b){if(v=this.compileExpression(b,u.i32,1),te(v)!=14){let x=i.runExpression(v,1);x?v=x:(e.is(8)&&this.error(2474,b.range),E=!0)}}else if(s==null)v=i.i32(0);else if(a&&this.error(1061,g.identifierNode.range.atEnd),o){let x=i64_add(s.constantIntegerValue,i64_new(1));assert(!i64_high(x)),v=i.i32(i64_low(x))}else{v=i.binary(0,i.global_get(s.internalName,C.I32),i.i32(1));let x=i.runExpression(v,1);x?v=x:(e.is(8)&&this.error(2474,f.declaration.range),E=!0)}this.currentFlow=S,E?(i.addGlobal(g.internalName,C.I32,!0,i.i32(0)),this.currentBody.push(this.makeGlobalAssignment(g,v,u.i32,!1)),a=!0):(o?(g.setConstantIntegerValue(i64_new(ie(v)),u.i32),g.is(524288)&&i.addGlobal(g.internalName,C.I32,!1,v)):i.addGlobal(g.internalName,C.I32,!1,v),g.isImmutable=!0,a=!1),s=g}return this.currentParent=n,t.delete(e),!0}compileFunction(e,t=!1){if(e.is(4194304))return!e.is(8388608);if(!t){if(e.hasDecorator(512))return!0;if(e.hasDecorator(1024))return this.lazyFunctions.add(e),!0}var i=e.prototype.functionTypeNode.parameters,n=i.length;if(n>=2){let f=new Set;f.add(i[0].name.text);for(let E=1;E=l;--f)t[f+1]=t[f];t[l]=i.flatten(_,C.None),a.is(16384)&&this.options.pedantic&&this.pedantic(905,e.identifierNode.range)}a.is(16384)&&!c.hasDecorator(32)&&this.error(231,c.identifierNode.range),a.is(256)||(t.push(i.local_get(o.index,this.options.sizeTypeRef)),a.set(261)),c.base&&!a.is(128)&&this.error(2377,e.prototype.declaration.range)}else if(s!=u.void&&!a.is(256))return this.error(2355,e.prototype.functionTypeNode.returnType.range),!1;return!0}compileClass(e){if(e.is(4194304))return!0;e.set(4194304);var t=e.prototype,i=t.members;if(i)for(let s=Map_values(i),a=0,o=s.length;a=0?"case"+_.toString():"break")+"|"+a);var f=t.block("case0|"+a,p,C.None),E=511,g=0;for(let b=0;b=0&&(s.flags|=E&-17),s.flags|=g&-2049,f}compileThrowStatement(e){var t=this.currentFlow;t.set(264);var i=new Array,n=e.value,s=null;if(n.kind==17){let a=n.args;a.length&&(s=a[0])}return i.push(this.makeAbort(s,e)),t.freeScopedLocals(),this.module.flatten(i)}compileTryStatement(e){return this.error(100,e.range,"Exceptions"),this.module.unreachable()}compileVariableStatement(e){var t=this.module,i=e.declarations,n=i.length,s=this.currentFlow,a=new Array,o=this.resolver;for(let l=0;l");continue}_=this.currentType}else{this.error(1110,p.name.range.atEnd);continue}let b=p.is(8),S=!1;if(b)if(f){let v=t.runExpression(f,1);if(v){f=v;let x=null;switch(oe(f)){case C.I32:{x=new De(c,-1,_,s.parentFunction),x.setConstantIntegerValue(i64_new(ie(f),0),_);break}case C.I64:{x=new De(c,-1,_,s.parentFunction),x.setConstantIntegerValue(i64_new(Be(f),$e(f)),_);break}case C.F32:{x=new De(c,-1,_,s.parentFunction),x.setConstantFloatValue(Ye(f),_);break}case C.F64:{x=new De(c,-1,_,s.parentFunction),x.setConstantFloatValue(He(f),_);break}}if(x){let L=s.scopedLocals;if(!L)s.scopedLocals=L=new Map;else if(L.has(c)){let P=assert(L.get(c));return this.errorRelated(2300,p.name.range,P.declaration.name.range,c),this.module.unreachable()}L.set(c,x),S=!0}}}else this.error(1155,p.range);if(!S){let v;if(p.isAny(24)||s.isInline){let x=s.getScopedLocal(c);x?(x.declaration.range.source.isNative?this.error(2300,p.name.range,c):this.errorRelated(2300,p.name.range,x.declaration.name.range,c),v=x):v=s.addScopedLocal(c,_),b&&s.setLocalFlag(v.index,1)}else{let x=s.lookupLocal(c);if(x){this.errorRelated(2300,p.name.range,x.declaration.name.range,c);continue}v=s.parentFunction.addLocal(_,c,p),b&&s.setLocalFlag(v.index,1)}f?a.push(this.makeLocalAssignment(v,f,_,!1)):v.type.isShortIntegerValue&&s.setLocalFlag(v.index,2)}}return this.currentType=u.void,a.length==0?0:t.flatten(a)}compileVoidStatement(e){return this.compileExpression(e.expression,u.void,10)}compileWhileStatement(e){return this.doCompileWhileStatement(e,null)}doCompileWhileStatement(e,t){var i=this.module,n=this.currentFlow,s=n.pushBreakLabel(),a=new Array,o=n.fork(!0);t&&o.unifyLocalFlags(t);var l=o.fork();this.currentFlow=o;var p="while-break|"+s;o.breakLabel=p;var c="while-continue|"+s;o.continueLabel=c;var _=o.fork();this.currentFlow=_;var f=this.makeIsTrueish(this.compileExpression(e.condition,u.bool),this.currentType,e.condition),E=this.evaluateCondition(f);if(E==2)return a.push(i.drop(f)),assert(!o.hasScopedLocals),n.popBreakLabel(),this.currentFlow=n,i.flatten(a);var g=o.getTempLocal(u.bool);a.push(i.local_set(g.index,f,!1)),_.freeScopedLocals(),o.inherit(_),this.currentFlow=o;var b=o.fork();b.inheritNonnullIfTrue(f),this.currentFlow=b;var S=new Array,v=e.statement;if(v.kind==30?this.compileStatements(v.statements,!1,S):S.push(this.compileStatement(v)),b.is(256))S.push(i.unreachable()),E==1?o.inherit(b):o.inheritBranch(b);else if(E==1&&!b.isAny(2064))S.push(i.br(c)),o.set(256);else{let L=b.is(16);if(L?S.push(i.unreachable()):S.push(i.br(c)),E==1?o.inherit(b):o.inheritBranch(b),!L&&Ue.hasIncompatibleLocalStates(l,o))return o.freeTempLocal(g),n.popBreakLabel(),this.currentFlow=n,this.doCompileWhileStatement(e,o)}a.push(i.if(i.local_get(g.index,C.I32),i.flatten(S))),o.freeTempLocal(g),this.currentFlow=o,assert(!o.hasScopedLocals),n.inherit(o),n.popBreakLabel(),this.currentFlow=n;var x=i.block(p,[i.loop(c,i.flatten(a))]);return E==1&&n.is(256)&&(x=i.block(null,[x,i.unreachable()])),x}compileInlineConstant(e,t,i){assert(e.is(18874368));var n=e.type;switch(this.currentType=n,n.kind){case 10:return this.module.i32(e.constantValueKind==1?i64_ne(e.constantIntegerValue,i64_zero):0);case 0:case 1:{let s=n.computeSmallIntegerShift(u.i32);return this.module.i32(e.constantValueKind==1?i64_low(e.constantIntegerValue)<>s:0)}case 5:case 6:{let s=e.type.computeSmallIntegerMask(u.i32);return this.module.i32(e.constantValueKind==1?i64_low(e.constantIntegerValue)&s:0)}case 2:case 7:return this.module.i32(e.constantValueKind==1?i64_low(e.constantIntegerValue):0);case 4:case 9:if(!e.program.options.isWasm64)return this.module.i32(e.constantValueKind==1?i64_low(e.constantIntegerValue):0);case 3:case 8:return e.constantValueKind==1?this.module.i64(i64_low(e.constantIntegerValue),i64_high(e.constantIntegerValue)):this.module.i64(0);case 12:{if(!(e.hasDecorator(512)&&t==u.f32))return this.module.f64(e.constantFloatValue);this.currentType=u.f32}case 11:return this.module.f32(e.constantFloatValue);default:return assert(!1),this.module.unreachable()}}compileExpression(e,t,i=0){for(;e.kind==20;)e=e.expression;this.currentType=t,t==u.void&&(i|=8);var n;switch(e.kind){case 7:{n=this.compileAssertionExpression(e,t,i);break}case 8:{n=this.compileBinaryExpression(e,t,i);break}case 9:{n=this.compileCallExpression(e,t,i);break}case 11:{n=this.compileCommaExpression(e,t,i);break}case 12:{n=this.compileElementAccessExpression(e,t,i);break}case 14:{n=this.compileFunctionExpression(e,t,i);break}case 6:case 13:case 18:case 24:case 23:case 25:{n=this.compileIdentifierExpression(e,t,i);break}case 15:{n=this.compileInstanceOfExpression(e,t,i);break}case 16:{n=this.compileLiteralExpression(e,t,i);break}case 17:{n=this.compileNewExpression(e,t,i);break}case 21:{n=this.compilePropertyAccessExpression(e,t,i);break}case 22:{n=this.compileTernaryExpression(e,t,i);break}case 27:{n=this.compileUnaryPostfixExpression(e,t,i);break}case 28:{n=this.compileUnaryPrefixExpression(e,t,i);break}case 29:{let o=e;n=o.expr,this.currentType=o.type;break}case 10:{this.error(100,e.range,"Block-scoped class declarations or expressions"),n=this.module.unreachable();break}default:assert(!1),n=this.module.unreachable()}var s=this.currentType,a=(i&4)!=0;return s!=t.nonNullableType&&(i&2?(n=this.convertExpression(n,s,t,!0,e),this.currentType=s=t):i&1&&(n=this.convertExpression(n,s,t,!1,e),this.currentType=s=t)),a&&(n=this.ensureSmallIntegerWrap(n,s)),this.options.sourceMap&&this.addDebugLocation(n,e.range),n}convertExpression(e,t,i,n,s){var a=this.module;if(t.kind==20)return assert(i.kind!=20),this.error(2322,s.range,t.toString(),i.toString()),a.unreachable();if(i.kind==20)return a.drop(e);if(t.isReference||i.isReference)return this.currentFlow.isNonnull(e,t)?t=t.nonNullableType:n&&t.isNullableReference&&!i.isNullableReference&&(this.options.noAssert||(e=this.makeRuntimeNonNullCheck(e,t,s)),t=t.nonNullableType),t.isAssignableTo(i)?(assert(i.isExternalReference||t.kind==i.kind),this.currentType=i,e):n&&i.nonNullableType.isAssignableTo(t)?i.isExternalReference?(this.error(100,s.range,"ref.cast"),this.currentType=i,a.unreachable()):(assert(t.kind==i.kind),this.options.noAssert||(e=this.makeRuntimeUpcastCheck(e,t,i,s)),this.currentType=i,e):(this.error(2322,s.range,t.toString(),i.toString()),this.currentType=i,a.unreachable());if(assert(!t.isReference&&!i.isReference),t.isAssignableTo(i)||n||this.error(200,s.range,t.toString(),i.toString()),t.isFloatValue)if(i.isFloatValue)t.kind==11?i.kind==12&&(e=a.unary(43,e)):i.kind==11&&(e=a.unary(44,e));else if(i.isIntegerValue)if(t.kind==11)if(i.isBooleanValue)e=this.makeIsTrueish(e,u.f32,s);else if(i.isSignedIntegerValue){let o=this.options.hasFeature(4);i.isLongIntegerValue?e=a.unary(o?56:26,e):e=a.unary(o?52:25,e)}else{let o=this.options.hasFeature(4);i.isLongIntegerValue?e=a.unary(o?57:28,e):e=a.unary(o?53:27,e)}else if(i.isBooleanValue)e=this.makeIsTrueish(e,u.f64,s);else if(i.isSignedIntegerValue){let o=this.options.hasFeature(4);i.isLongIntegerValue?e=a.unary(o?58:30,e):e=a.unary(o?54:29,e)}else{let o=this.options.hasFeature(4);i.isLongIntegerValue?e=a.unary(o?59:32,e):e=a.unary(o?55:31,e)}else assert(i.flags==0,"void type expected"),e=a.drop(e);else t.isIntegerValue&&i.isFloatValue?i.kind==11?t.isLongIntegerValue?e=a.unary(t.isSignedIntegerValue?39:41,e):e=a.unary(t.isSignedIntegerValue?35:37,e):t.isLongIntegerValue?e=a.unary(t.isSignedIntegerValue?40:42,e):e=a.unary(t.isSignedIntegerValue?36:38,e):t==u.v128&&i.isBooleanValue?e=this.makeIsTrueish(e,u.v128,s):t.isLongIntegerValue?i.isBooleanValue?e=a.binary(41,e,a.i64(0)):i.isLongIntegerValue||(e=a.unary(24,e)):i.isLongIntegerValue?e=a.unary(t.isSignedIntegerValue?22:23,this.ensureSmallIntegerWrap(e,t)):t.isShortIntegerValue?t.size",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_,f=this.makeGt(o,p,_),this.currentType=u.bool;break}case 73:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(22);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!0),!_||!_.isNumericValue)return this.error(2365,e.range,"<=",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_,f=this.makeLe(o,p,_),this.currentType=u.bool;break}case 74:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(20);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!0),!_||!_.isNumericValue)return this.error(2365,e.range,">=",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_,f=this.makeGe(o,p,_),this.currentType=u.bool;break}case 77:case 75:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(17);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_)return this.error(2365,e.range,ye(e.operator),l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_,f=this.makeEq(o,p,_,e),this.currentType=u.bool;break}case 78:case 76:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClass();if(x){let L=x.lookupOverload(18);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_)return this.error(2365,e.range,ye(e.operator),l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_,f=this.makeNe(o,p,_,e),this.currentType=u.bool;break}case 100:return this.compileAssignment(s,a,t);case 101:E=!0;case 80:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(5);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isNumericValue)return this.error(2469,e.range,"+",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isNumericValue)return this.error(2365,e.range,"+",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeAdd(o,p,_);break}case 102:E=!0;case 81:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(6);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isNumericValue)return this.error(2469,e.range,"-",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!l.isNumericValue)return this.error(2365,e.range,"-",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeSub(o,p,_);break}case 103:E=!0;case 83:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(7);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isNumericValue)return this.error(2469,e.range,"*",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isNumericValue)return this.error(2365,e.range,"*",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeMul(o,p,_);break}case 104:E=!0;case 82:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(10);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isNumericValue)return this.error(2469,e.range,"**",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isNumericValue)return this.error(2365,e.range,"**",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makePow(o,p,_,e);break}case 105:E=!0;case 84:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(8);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isNumericValue)return this.error(2469,e.range,"/",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isNumericValue)return this.error(2365,e.range,"/",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeDiv(o,p,_);break}case 106:E=!0;case 85:{o=this.compileExpression(s,t),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(9);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isNumericValue)return this.error(2469,e.range,"%",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isNumericValue)return this.error(2365,e.range,"%",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeRem(o,p,_,e);break}case 107:E=!0;case 88:{o=this.compileExpression(s,t.intType),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(14);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(!l.isIntegerValue)return this.error(2469,e.range,"<<",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=this.currentType,f=this.makeShl(o,p,c);break}case 108:E=!0;case 89:{o=this.compileExpression(s,t.intType),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(15);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(!l.isIntegerValue)return this.error(2469,e.range,">>",l.toString()),this.module.unreachable();p=this.compileExpression(a,l,1),c=this.currentType,f=this.makeShr(o,p,c);break}case 109:E=!0;case 90:{o=this.compileExpression(s,t.intType),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(16);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(!l.isIntegerValue)return this.error(2469,e.range,">>>",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=this.currentType,f=this.makeShru(o,p,c);break}case 110:E=!0;case 91:{o=this.compileExpression(s,t.intType),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(11);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isIntegerValue)return this.error(2469,e.range,"&",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isIntegerValue)return this.error(2365,e.range,"&",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeAnd(o,p,_);break}case 111:E=!0;case 92:{o=this.compileExpression(s,t.intType),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(12);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isIntegerValue)return this.error(2469,e.range,"|",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isIntegerValue)return this.error(2365,e.range,"|",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeOr(o,p,_);break}case 112:E=!0;case 93:{o=this.compileExpression(s,t.intType),l=this.currentType;let x=l.getClassOrWrapper(this.program);if(x){let L=x.lookupOverload(13);if(L){f=this.compileBinaryOverload(L,s,o,l,a,e);break}}if(E){if(!l.isIntegerValue)return this.error(2469,e.range,"^",l.toString()),n.unreachable();p=this.compileExpression(a,l,1),c=_=this.currentType}else{if(p=this.compileExpression(a,l),c=this.currentType,_=u.commonDenominator(l,c,!1),!_||!_.isIntegerValue)return this.error(2365,e.range,"^",l.toString(),c.toString()),this.currentType=t,n.unreachable();o=this.convertExpression(o,l,_,!1,s),l=_,p=this.convertExpression(p,c,_,!1,a),c=_}f=this.makeXor(o,p,_);break}case 96:{let x=this.currentFlow,L=i&4;o=this.compileExpression(s,t.exceptVoid,L),l=this.currentType;let P=x.fork();if(this.currentFlow=P,P.inheritNonnullIfTrue(o),t==u.bool||t==u.void){o=this.makeIsTrueish(o,l,s);let F=this.evaluateCondition(o);F==2?f=o:(p=this.compileExpression(a,l,L),c=this.currentType,P.freeScopedLocals(),p=this.makeIsTrueish(p,c,a),F==1?f=p:f=n.if(o,p,n.i32(0))),this.currentFlow=x,this.currentType=u.bool}else{if(p=this.compileExpression(a,l,L|1),c=this.currentType,P.freeScopedLocals(),this.currentFlow=x,f=n.tryCopyTrivialExpression(o))f=n.if(this.makeIsTrueish(o,this.currentType,s),p,f);else{let F=x.getTempLocal(l);x.canOverflow(o,l)||x.setLocalFlag(F.index,2),x.isNonnull(o,l)&&x.setLocalFlag(F.index,4),f=n.if(this.makeIsTrueish(n.local_tee(F.index,o,l.isManaged),l,s),p,n.local_get(F.index,l.toRef())),x.freeTempLocal(F)}this.currentType=l}break}case 97:{let x=this.currentFlow,L=i&4;o=this.compileExpression(s,t.exceptVoid,L),l=this.currentType;let P=x.fork();if(this.currentFlow=P,P.inheritNonnullIfFalse(o),t==u.bool||t==u.void){o=this.makeIsTrueish(o,l,s);let F=this.evaluateCondition(o);F==1?f=o:(p=this.compileExpression(a,l,L),c=this.currentType,P.freeScopedLocals(),p=this.makeIsTrueish(p,c,a),F==2?f=p:f=n.if(o,n.i32(1),p)),this.currentFlow=x,this.currentType=u.bool}else{if(p=this.compileExpression(a,l,L|1),c=this.currentType,P.freeScopedLocals(),this.currentFlow=x,f=n.tryCopyTrivialExpression(o))f=n.if(this.makeIsTrueish(o,l,s),f,p);else{let F=x.getTempLocal(l);x.canOverflow(o,l)||x.setLocalFlag(F.index,2),x.isNonnull(o,l)&&x.setLocalFlag(F.index,4),f=n.if(this.makeIsTrueish(n.local_tee(F.index,o,l.isManaged),l,s),n.local_get(F.index,l.toRef()),p),x.freeTempLocal(F)}this.currentType=l}break}default:assert(!1),f=this.module.unreachable()}if(!E)return f;var b=this.resolver,S=b.lookupExpression(s,this.currentFlow);if(!S)return n.unreachable();var v=b.getTypeOfElement(S);return v||(v=u.void),this.currentType.isStrictlyAssignableTo(v)?this.makeAssignment(S,f,this.currentType,a,b.currentThisExpression,b.currentElementExpression,t!=u.void):(this.error(2322,e.range,this.currentType.toString(),v.toString()),n.unreachable())}makeLt(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:return n.binary(17,e,t);case 3:return n.binary(42,e,t);case 4:return n.binary(this.options.isWasm64?42:17,e,t);case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 7:return n.binary(18,e,t);case 9:return n.binary(this.options.isWasm64?43:18,e,t);case 8:return n.binary(43,e,t);case 11:return n.binary(59,e,t);case 12:return n.binary(72,e,t)}return assert(!1),n.unreachable()}makeGt(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:return n.binary(21,e,t);case 4:return n.binary(this.options.isWasm64?46:21,e,t);case 3:return n.binary(46,e,t);case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 7:return n.binary(22,e,t);case 9:return n.binary(this.options.isWasm64?47:22,e,t);case 8:return n.binary(47,e,t);case 11:return n.binary(61,e,t);case 12:return n.binary(74,e,t)}return assert(!1),n.unreachable()}makeLe(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:return n.binary(19,e,t);case 4:return n.binary(this.options.isWasm64?44:19,e,t);case 3:return n.binary(44,e,t);case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 7:return n.binary(20,e,t);case 9:return n.binary(this.options.isWasm64?45:20,e,t);case 8:return n.binary(45,e,t);case 11:return n.binary(60,e,t);case 12:return n.binary(73,e,t)}return assert(!1),n.unreachable()}makeGe(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:return n.binary(23,e,t);case 4:return n.binary(this.options.isWasm64?48:23,e,t);case 3:return n.binary(48,e,t);case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 7:return n.binary(24,e,t);case 9:return n.binary(this.options.isWasm64?49:24,e,t);case 8:return n.binary(49,e,t);case 11:return n.binary(62,e,t);case 12:return n.binary(75,e,t)}return assert(!1),n.unreachable()}makeEq(e,t,i,n){var s=this.module;switch(i.kind){case 0:case 1:case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:case 7:return s.binary(15,e,t);case 4:case 9:return s.binary(this.options.isWasm64?40:15,e,t);case 3:case 8:return s.binary(40,e,t);case 11:return s.binary(57,e,t);case 12:return s.binary(70,e,t);case 13:return s.unary(70,s.binary(76,e,t));case 17:case 18:case 19:return s.ref_eq(e,t);case 14:case 15:case 16:return this.error(203,n.range,"ref.eq",i.toString()),s.unreachable()}return assert(!1),s.unreachable()}makeNe(e,t,i,n){var s=this.module;switch(i.kind){case 0:case 1:case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:case 7:return s.binary(16,e,t);case 9:case 4:return s.binary(this.options.isWasm64?41:16,e,t);case 3:case 8:return s.binary(41,e,t);case 11:return s.binary(58,e,t);case 12:return s.binary(71,e,t);case 13:return s.unary(67,s.binary(77,e,t));case 17:case 18:case 19:return s.unary(20,s.ref_eq(e,t));case 14:case 15:case 16:return this.error(203,n.range,"ref.eq",i.toString()),s.unreachable()}return assert(!1),s.unreachable()}makeAdd(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:case 5:case 6:case 10:case 2:case 7:return n.binary(0,e,t);case 9:case 4:return n.binary(this.options.isWasm64?25:0,e,t);case 3:case 8:return n.binary(25,e,t);case 11:return n.binary(50,e,t);case 12:return n.binary(63,e,t)}return assert(!1),n.unreachable()}makeSub(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:case 5:case 6:case 10:case 2:case 7:return n.binary(1,e,t);case 9:case 4:return n.binary(this.options.isWasm64?26:1,e,t);case 3:case 8:return n.binary(26,e,t);case 11:return n.binary(51,e,t);case 12:return n.binary(64,e,t)}return assert(!1),n.unreachable()}makeMul(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:case 5:case 6:case 10:case 2:case 7:return n.binary(2,e,t);case 9:case 4:return n.binary(this.options.isWasm64?27:2,e,t);case 3:case 8:return n.binary(27,e,t);case 11:return n.binary(52,e,t);case 12:return n.binary(65,e,t)}return assert(!1),n.unreachable()}makePow(e,t,i,n){let s=this.module;switch(i.kind){case 10:return s.select(s.i32(1),s.binary(15,t,s.i32(0)),e,C.I32);case 0:case 5:case 1:case 6:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:case 7:{let a=this.i32PowInstance;if(!a){let l=this.program.lookup(O.ipow32);if(!l)return this.error(2304,n.range,"ipow32"),s.unreachable();assert(l.kind==4),this.i32PowInstance=a=this.resolver.resolveFunction(l,null)}if(!a||!this.compileFunction(a))return s.unreachable();let o=this.makeCallDirect(a,[e,t],n);return i.size<32&&(o=this.ensureSmallIntegerWrap(o,i)),o}case 3:case 8:{let a=this.i64PowInstance;if(!a){let o=this.program.lookup(O.ipow64);if(!o)return this.error(2304,n.range,"ipow64"),s.unreachable();assert(o.kind==4),this.i64PowInstance=a=this.resolver.resolveFunction(o,null)}return!a||!this.compileFunction(a)?s.unreachable():this.makeCallDirect(a,[e,t],n)}case 4:case 9:{let a=this.options.isWasm64,o=a?this.i64PowInstance:this.i32PowInstance;if(!o){let l=this.program.lookup(a?O.ipow64:O.ipow32);if(!l)return this.error(2304,n.range,a?"ipow64":"ipow32"),s.unreachable();assert(l.kind==4),o=this.resolver.resolveFunction(l,null),a?this.i64PowInstance=o:this.i32PowInstance=o}return!o||!this.compileFunction(o)?s.unreachable():this.makeCallDirect(o,[e,t],n)}case 11:{let a=this.f32PowInstance;if(!a){let o=this.program.lookup(O.Mathf);if(!o)return this.error(2304,n.range,"Mathf"),s.unreachable();let l=o.members;if(!l||!l.has(O.pow))return this.error(2304,n.range,"Mathf.pow"),s.unreachable();let p=assert(l.get(O.pow));assert(p.kind==4),this.f32PowInstance=a=this.resolver.resolveFunction(p,null)}return!a||!this.compileFunction(a)?s.unreachable():this.makeCallDirect(a,[e,t],n)}case 12:{let a=this.f64PowInstance;if(!a){let o=this.program.lookup(O.Math);if(!o)return this.error(2304,n.range,"Math"),s.unreachable();let l=o.members;if(!l||!l.has(O.pow))return this.error(2304,n.range,"Math.pow"),s.unreachable();let p=assert(l.get(O.pow));assert(p.kind==4),this.f64PowInstance=a=this.resolver.resolveFunction(p,null)}return!a||!this.compileFunction(a)?s.unreachable():this.makeCallDirect(a,[e,t],n)}}return assert(!1),s.unreachable()}makeDiv(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:return n.binary(3,e,t);case 4:return n.binary(this.options.isWasm64?28:3,e,t);case 3:return n.binary(28,e,t);case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 7:return n.binary(4,e,t);case 9:return n.binary(this.options.isWasm64?29:4,e,t);case 8:return n.binary(29,e,t);case 11:return n.binary(53,e,t);case 12:return n.binary(66,e,t)}return assert(!1),n.unreachable()}makeRem(e,t,i,n){var s=this.module;switch(i.kind){case 0:case 1:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 2:return s.binary(5,e,t);case 4:return s.binary(this.options.isWasm64?30:5,e,t);case 3:return s.binary(30,e,t);case 5:case 6:case 10:e=this.ensureSmallIntegerWrap(e,i),t=this.ensureSmallIntegerWrap(t,i);case 7:return s.binary(6,e,t);case 9:return s.binary(this.options.isWasm64?31:6,e,t);case 8:return s.binary(31,e,t);case 11:{let a=this.f32ModInstance;if(!a){let o=this.program.lookup(O.Mathf);if(!o)return this.error(2304,n.range,"Mathf"),s.unreachable();let l=o.members;if(!l||!l.has(O.mod))return this.error(2304,n.range,"Mathf.mod"),s.unreachable();let p=assert(l.get(O.mod));assert(p.kind==4),this.f32ModInstance=a=this.resolver.resolveFunction(p,null)}return!a||!this.compileFunction(a)?s.unreachable():this.makeCallDirect(a,[e,t],n)}case 12:{let a=this.f64ModInstance;if(!a){let o=this.program.lookup(O.Math);if(!o)return this.error(2304,n.range,"Math"),s.unreachable();let l=o.members;if(!l||!l.has(O.mod))return this.error(2304,n.range,"Math.mod"),s.unreachable();let p=assert(l.get(O.mod));assert(p.kind==4),this.f64ModInstance=a=this.resolver.resolveFunction(p,null)}return!a||!this.compileFunction(a)?s.unreachable():this.makeCallDirect(a,[e,t],n)}}return assert(!1),s.unreachable()}makeShl(e,t,i){var n=this.module;switch(i.kind){case 10:return e;case 0:case 1:case 5:case 6:return n.binary(10,e,n.binary(7,t,n.i32(i.size-1)));case 2:case 7:return n.binary(10,e,t);case 3:case 8:return n.binary(35,e,t);case 9:case 4:return n.binary(this.options.isWasm64?35:10,e,t)}return assert(!1),n.unreachable()}makeShr(e,t,i){var n=this.module;switch(i.kind){case 10:return e;case 0:case 1:return n.binary(11,this.ensureSmallIntegerWrap(e,i),n.binary(7,t,n.i32(i.size-1)));case 5:case 6:return n.binary(12,this.ensureSmallIntegerWrap(e,i),n.binary(7,t,n.i32(i.size-1)));case 2:return n.binary(11,e,t);case 3:return n.binary(36,e,t);case 4:return n.binary(this.options.isWasm64?36:11,e,t);case 7:return n.binary(12,e,t);case 8:return n.binary(37,e,t);case 9:return n.binary(this.options.isWasm64?37:12,e,t)}return assert(!1),n.unreachable()}makeShru(e,t,i){var n=this.module;switch(i.kind){case 10:return e;case 0:case 1:case 5:case 6:return n.binary(12,this.ensureSmallIntegerWrap(e,i),n.binary(7,t,n.i32(i.size-1)));case 2:case 7:return n.binary(12,e,t);case 3:case 8:return n.binary(37,e,t);case 9:case 4:return n.binary(this.options.isWasm64?37:12,e,t)}return assert(!1),n.unreachable()}makeAnd(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:case 2:case 5:case 6:case 10:case 7:return n.binary(7,e,t);case 3:case 8:return n.binary(32,e,t);case 9:case 4:return n.binary(this.options.isWasm64?32:7,e,t)}return assert(!1),n.unreachable()}makeOr(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:case 5:case 6:case 10:return n.binary(8,e,t);case 2:case 7:return n.binary(8,e,t);case 3:case 8:return n.binary(33,e,t);case 9:case 4:return n.binary(this.options.isWasm64?33:8,e,t)}return assert(!1),n.unreachable()}makeXor(e,t,i){var n=this.module;switch(i.kind){case 0:case 1:case 5:case 6:case 10:return n.binary(9,e,t);case 2:case 7:return n.binary(9,e,t);case 3:case 8:return n.binary(34,e,t);case 4:case 9:return n.binary(this.options.isWasm64?34:9,e,t)}return assert(!1),n.unreachable()}compileUnaryOverload(e,t,i,n){return this.makeCallDirect(e,[i],n,!1)}compileBinaryOverload(e,t,i,n,s,a){var o,l=e.signature,p=l.parameterTypes;e.is(131072)?(i=this.convertExpression(i,n,assert(l.thisType),!1,t),o=p[0]):(i=this.convertExpression(i,n,p[0],!1,t),o=p[1]);var c=this.compileExpression(s,o,1);return this.makeCallDirect(e,[i,c],a)}compileAssignment(e,t,i){var n=this.program,s=n.resolver,a=this.currentFlow,o=s.lookupExpression(e,a);if(!o)return this.module.unreachable();var l=s.currentThisExpression,p=s.currentElementExpression,c;switch(o.kind){case 0:if(!this.compileGlobal(o))return this.module.unreachable();case 1:case 11:{if(this.pendingElements.has(o))return this.error(2448,e.range,o.internalName),this.module.unreachable();c=o.type,o.hasDecorator(2048)&&this.checkUnsafe(e);break}case 12:{let E=o,g=s.resolveProperty(E);if(!g)return this.module.unreachable();o=g}case 13:{let E=o,g=E.setterInstance;if(!g)return this.error(2540,e.range,E.internalName),this.module.unreachable();assert(g.signature.parameterTypes.length==1),c=g.signature.parameterTypes[0],g.hasDecorator(2048)&&this.checkUnsafe(e);break}case 17:{let E=o.parent;assert(E.kind==7);let g=E,b=a.is(32768),S=g.lookupOverload(2,b);if(!S)return g.lookupOverload(1,b)?this.error(2542,e.range,g.internalName):this.error(2329,e.range,g.internalName),this.module.unreachable();assert(S.signature.parameterTypes.length==2),c=S.signature.parameterTypes[1],S.hasDecorator(2048)&&this.checkUnsafe(e),!b&&this.options.pedantic&&this.pedantic(904,e.range);break}default:return this.error(2540,e.range,o.internalName),this.module.unreachable()}assert(c!=u.void);var _=this.compileExpression(t,c),f=this.currentType;return this.makeAssignment(o,this.convertExpression(_,f,c,!1,t),f,t,l,p,i!=u.void)}makeAssignment(e,t,i,n,s,a,o){var l=this.module,p=this.currentFlow;switch(e.kind){case 1:{let c=e;return p.isLocalFlag(c.index,1,!0)?(this.error(2540,n.range,e.internalName),this.currentType=o?c.type:u.void,l.unreachable()):this.makeLocalAssignment(c,t,i,o)}case 0:{let c=e;return this.compileGlobal(c)?e.isAny(72)?(this.error(2540,n.range,e.internalName),this.currentType=o?c.type:u.void,l.unreachable()):this.makeGlobalAssignment(c,t,i,o):l.unreachable()}case 11:{let c=e,_=c.initializerNode,f=p.actualFunction.is(262144);if(c.is(64)&&(!f||_))return this.error(2540,n.range,c.internalName),l.unreachable();s=assert(s),f&&s.kind==24&&p.setThisFieldFlag(c,1);let E=c.parent;return assert(E.kind==7),this.makeFieldAssignment(c,t,i,this.compileExpression(s,E.type,33),o)}case 13:{let c=e,_=c.setterInstance;if(!_)return this.error(2540,n.range,e.internalName),l.unreachable();if(assert(_.signature.parameterTypes.length==1),c.is(131072)){let f=assert(_.signature.thisType),E=this.compileExpression(assert(s),f,33);if(!o)return this.makeCallDirect(_,[E,t],n);let g=assert(e.getterInstance);assert(g.signature.thisType==f);let b=g.signature.returnType,S=b.toRef(),v=p.getTempLocal(b),x=l.block(null,[this.makeCallDirect(_,[l.local_tee(v.index,E,b.isManaged),t],n),this.makeCallDirect(g,[l.local_get(v.index,S)],n)],S);return p.freeTempLocal(v),x}else{if(!o)return this.makeCallDirect(_,[t],n);let f=assert(e.getterInstance);return l.block(null,[this.makeCallDirect(_,[t],n),this.makeCallDirect(f,null,n)],f.signature.returnType.toRef())}}case 17:{let _=e.parent;assert(_.kind==7);let f=_;assert(f.kind==7);let E=p.is(32768),g=f.lookupOverload(1,E);if(!g)return this.error(2329,n.range,f.internalName),l.unreachable();let b=f.lookupOverload(2,E);if(!b)return this.error(2542,n.range,f.internalName),this.currentType=o?g.signature.returnType:u.void,l.unreachable();assert(b.signature.parameterTypes.length==2);let S=f.type,v=this.compileExpression(assert(s),S,33),x=this.compileExpression(assert(a),u.i32,1),L=this.currentType;if(o){let P=p.getTempLocal(S),F=p.getTempLocal(L),w=g.signature.returnType,U=l.block(null,[this.makeCallDirect(b,[l.local_tee(P.index,v,S.isManaged),l.local_tee(F.index,x,L.isManaged),t],n),this.makeCallDirect(g,[l.local_get(P.index,P.type.toRef()),l.local_get(F.index,F.type.toRef())],n)],w.toRef());return p.freeTempLocal(F),p.freeTempLocal(P),U}else return this.makeCallDirect(b,[v,x,t],n)}}return assert(!1),l.unreachable()}makeLocalAssignment(e,t,i,n){var s=this.module,a=this.currentFlow,o=e.type;assert(o!=u.void);var l=e.index;return o.isNullableReference&&(!i.isNullableReference||a.isNonnull(t,o)?a.setLocalFlag(l,4):a.unsetLocalFlag(l,4)),a.setLocalFlag(l,8),o.isShortIntegerValue&&(a.canOverflow(t,o)?a.unsetLocalFlag(l,2):a.setLocalFlag(l,2)),n?(this.currentType=o,s.local_tee(l,t,o.isManaged)):(this.currentType=u.void,s.local_set(l,t,o.isManaged))}makeGlobalAssignment(e,t,i,n){var s=this.module,a=e.type;assert(a!=u.void);var o=a.toRef();return t=this.ensureSmallIntegerWrap(t,a),n?(this.currentType=a,s.block(null,[s.global_set(e.internalName,t),s.global_get(e.internalName,o)],o)):(this.currentType=u.void,s.global_set(e.internalName,t))}makeFieldAssignment(e,t,i,n,s){var a=this.module,o=this.currentFlow,l=e.type,p=l.toRef();assert(e.parent.kind==7);var c=e.parent.type;if(!e.is(4194304)){e.set(4194304);let _=e.typeNode;_&&this.checkTypeSupported(e.type,_)}if(s){this.compileField(e);let _=o.getTempLocal(c),f=a.block(null,[a.call(e.internalSetterName,[a.local_tee(_.index,n,c.isManaged),t],C.None),a.call(e.internalGetterName,[a.local_get(_.index,c.toRef())],p)],p);return o.freeTempLocal(_),this.currentType=l,f}else{this.compileFieldSetter(e);let _=a.call(e.internalSetterName,[n,t],C.None);return this.currentType=u.void,_}}compileCallExpression(e,t,i){var n=this.module,s=this.currentFlow;if(e.expression.kind==23){let c=this.currentFlow,_=c.actualFunction;if(!_.is(262144))return this.error(2337,e.range),n.unreachable();let f=assert(_.parent);assert(f.kind==7);let E=f,g=E.base;if(!g)return this.error(2335,e.expression.range),n.unreachable();let b=assert(c.lookupLocal(O.this_)),S=this.options.sizeTypeRef,v=this.ensureConstructor(g,e);this.checkFieldInitialization(g,e);let x=this.compileCallDirect(v,e.args,e,n.local_get(b.index,S));return c.isAny(8256)?(this.error(17009,e.range),n.unreachable()):(c.set(192),this.currentType=u.void,n.local_set(b.index,x,E.type.isManaged))}var a=this.resolver.lookupExpression(e.expression,s);if(!a)return n.unreachable();var o=this.resolver.currentThisExpression,l,p;switch(a.kind){case 4:{let c=a;if(c.hasDecorator(512))return this.compileCallExpressionBuiltin(c,e,t);let _=this.resolver.maybeInferCall(e,c,s);if(!_)return this.module.unreachable();a=_}case 5:{let c=a,_=0;return c.is(131072)&&(_=this.compileExpression(assert(o),assert(c.signature.thisType),33)),this.compileCallDirect(c,e.args,e,_,i)}case 1:{let c=a;if(l=c.type.signatureReference,l){if(c.is(16777216)){let _=c.constantIntegerValue;this.options.isWasm64?p=n.i64(i64_low(_),i64_high(_)):(assert(!i64_high(_)),p=n.i32(i64_low(_)))}else p=n.local_get(c.index,this.options.sizeTypeRef);break}return this.error(2349,e.range,c.type.toString()),n.unreachable()}case 0:{let c=a;if(l=c.type.signatureReference,l){p=n.global_get(c.internalName,c.type.toRef());break}return this.error(2349,e.range,c.type.toString()),n.unreachable()}case 11:{let c=a,_=c.type;if(l=_.signatureReference,l){let f=c.parent;assert(f.kind==7);let E=this.options.usizeType;p=n.load(E.byteSize,!1,this.compileExpression(assert(o),f.type,33),E.toRef(),c.memoryOffset);break}return this.error(2349,e.range,_.toString()),n.unreachable()}case 12:{let c=this.resolver.resolveProperty(a);if(!c)return n.unreachable();a=c}case 13:{let c=a,_=c.getterInstance,f=assert(this.resolver.getTypeOfElement(a));if(!_)return this.error(2349,e.range,f.toString()),n.unreachable();let E=0;if(c.is(131072)&&(E=this.compileExpression(assert(o),assert(_.signature.thisType),33)),p=this.compileCallDirect(_,[],e.expression,E),l=this.currentType.signatureReference,!l)return this.error(2349,e.range,this.currentType.toString()),n.unreachable();break}case 7:{let _=a.getTypeArgumentsTo(this.program.functionPrototype);if(_&&_.length>0){let f=_[0];l=f.getSignature(),p=this.compileExpression(e.expression,f,1);break}}default:{let c=this.resolver.getTypeOfElement(a);return c?this.error(2757,e.range,c.toString()):this.error(225,e.range),n.unreachable()}}return this.compileCallIndirect(assert(l),p,e.args,e,0,t==u.void)}compileCallExpressionLike(e,t,i,n,s,a=0){var o=this._reusableCallExpression;return o?(o.expression=e,o.typeArguments=t,o.args=i,o.range=n):this._reusableCallExpression=o=k.createCallExpression(e,t,i,n),this.compileCallExpression(o,s,a)}compileCallExpressionBuiltin(e,t,i){e.hasDecorator(2048)&&this.checkUnsafe(t);var n=null,s=e.typeParameterNodes,a=t.typeArguments;t.typeArguments&&(e.is(32768)||this.error(2315,t.range,e.internalName),n=this.resolver.resolveTypeArguments(assert(s),a,this.currentFlow.actualFunction.parent,re(this.currentFlow.contextualTypeArguments),t));var o=t.expression,l=new Zl(this,e,n,t.args,o.kind==21?o.expression:null,i,t,!1),p=e.internalName;if(d.has(p))return assert(d.get(p))(l);var c=e.parent;if(c.kind==7&&c.prototype==this.program.functionPrototype){let f=e.name;if(Os.has(f))return assert(Os.get(f))(l)}return assert(!1),this.module.unreachable()}checkCallSignature(e,t,i,n){var s=e.thisType;if(i!=(s!=null))return this.error(2685,n.range),!1;var a=e.hasRest;if(a)return this.error(100,n.range,"Rest parameters"),!1;var o=e.requiredParameters,l=e.parameterTypes.length;return tl&&!a?(this.error(2554,n.range,l.toString(),t.toString()),!1):!0}checkUnsafe(e,t=null){this.options.noUnsafe&&!e.range.source.isLibrary&&(t?this.errorRelated(101,e.range,t.range):this.error(101,e.range))}compileCallDirect(e,t,i,n=0,s=0){var a=t.length,o=e.signature;if(!this.checkCallSignature(o,a,n!=0,i))return this.currentType=o.returnType,this.module.unreachable();e.hasDecorator(2048)&&this.checkUnsafe(i);let l=this.currentFlow.actualFunction;if(l.is(262144)&&i.isAccessOnThis){let E=l.parent;assert(E.kind==7),this.checkFieldInitialization(E,i)}if(e.hasDecorator(64)&&(!e.is(134217728)||i.isAccessOnSuper)){assert(!e.is(67108864));let E=this.inlineStack;if(E.includes(e))this.warning(217,i.range,e.internalName);else{E.push(e);let g=o.parameterTypes;assert(a<=g.length);let b=new Array(a);for(let v=0;v=0;--S){let v=t[S],x=l[S],L=_.addScopedLocal(e.getParameterName(S),x,E);st(v,E),c.canOverflow(v,x)||_.setLocalFlag(L.index,2),_.isNonnull(v,x)&&_.setLocalFlag(L.index,4),f.unshift(s.local_set(L.index,v,x.isManaged))}if(i){let S=assert(e.parent);assert(S.kind==7);let v=S,x=assert(e.signature.thisType),L=_.addScopedLocal(O.this_,x,E);f.unshift(s.local_set(L.index,i,x.isManaged));let P=v.base;P&&_.addScopedAlias(O.super_,P.type,L.index)}else assert(!e.signature.thisType);this.currentFlow=_;var g=e.is(262144);g&&_.set(65536);for(let S=a;S=t.length-n);n=p),!this.compileFunction(e))return s.unreachable();var E=e.signature.returnType;if(a=c),o0,l=!o||t!=u.void,p=new Xe(l?(o?n.name.text+"|":"anonymous|")+(a.nextAnonymousId++).toString():n.name.text,a,n,0),c,_=re(s.contextualTypeArguments),f=this.module,E=t.signatureReference;if(E){let S=p.functionTypeNode,v=S.parameters,x=v.length,L=E.parameterTypes,P=L.length;if(x>P)return this.error(2554,e.range,P.toString(),x.toString()),f.unreachable();for(let H=0;H=0),c.isNullableReference&&s.isLocalFlag(_,4,!1)&&(c=c.nonNullableType),this.currentType=c,l.parent!=s.parentFunction?(this.error(100,e.range,"Closures"),n.unreachable()):n.local_get(_,c.toRef())}case 0:{let p=l;if(!this.compileGlobal(p))return n.unreachable();let c=p.type;return this.pendingElements.has(p)?(this.error(2448,e.range,p.internalName),this.currentType=c,n.unreachable()):(assert(c!=u.void),p.is(16777216)?this.compileInlineConstant(p,t,i):(this.currentType=c,n.global_get(p.internalName,c.toRef())))}case 3:{let p=l;return l.is(4194304)?(this.currentType=u.i32,p.is(16777216)?(assert(p.constantValueKind==1),n.i32(i64_low(p.constantIntegerValue))):n.global_get(p.internalName,C.I32)):(this.error(2651,e.range),this.currentType=u.i32,n.unreachable())}case 4:{let p=l,c=p.typeParameterNodes;if(c&&c.length!=0){this.error(1140,e.range);break}let _=this.resolver.resolveFunction(p,null,re(s.contextualTypeArguments));if(!_||!this.compileFunction(_))return n.unreachable();if(_.hasDecorator(512))return this.error(100,e.range,"First-class built-ins"),this.currentType=_.type,n.unreachable();if(t.isExternalReference)return this.currentType=u.funcref,n.ref_func(_.internalName,C.Funcref);let f=this.ensureRuntimeFunction(_);return this.currentType=_.signature.type,this.options.isWasm64?n.i64(i64_low(f),i64_high(f)):n.i32(i64_low(f))}}return this.error(234,e.range),n.unreachable()}compileInstanceOfExpression(e,t,i){var n=this.currentFlow,s=e.isType;if(s.kind==1){let o=s;if(!(o.isNullable||o.hasTypeArguments)){let l=this.resolver.resolveTypeName(o.name,n.actualFunction,1);if(l&&l.kind==6){let p=l;if(p.is(32768))return this.makeInstanceofClass(e,p)}}}var a=this.resolver.resolveType(e.isType,n.actualFunction,re(n.contextualTypeArguments));return a?this.makeInstanceofType(e,a):(this.currentType=u.bool,this.module.unreachable())}makeInstanceofType(e,t){var i=this.module,n=this.currentFlow,s=this.compileExpression(e.expression,t),a=this.currentType;if(this.currentType=u.bool,t.isValue)return i.maybeDropCondition(s,i.i32(a==t?1:0));if(a.isValue)return i.maybeDropCondition(s,i.i32(0));var o=a.toRef();if(a.isNullableReference&&!t.isNullableReference){if(a.nonNullableType.isAssignableTo(t))return i.binary(o==C.I64?41:16,s,this.makeZero(a,e.expression));if(t.isAssignableTo(a)){let l=this.program;if(a.isUnmanaged||t.isUnmanaged)this.error(2365,e.range,"instanceof",a.toString(),t.toString());else{let p=n.getTempLocal(a),c=assert(l.instanceofInstance);this.compileFunction(c);let _=i.if(i.unary(o==C.I64?21:20,i.local_tee(p.index,s,a.isManaged)),i.i32(0),this.makeCallDirect(c,[i.local_get(p.index,o),i.i32(t.classReference.id)],e));return n.freeTempLocal(p),this.options.pedantic&&this.pedantic(903,e.range),_}}}else{if(a.isAssignableTo(t))return i.maybeDropCondition(s,i.i32(1));if(t.isAssignableTo(a)){let l=this.program;if(a.isUnmanaged||t.isUnmanaged)this.error(2365,e.range,"instanceof",a.toString(),t.toString());else{let p=n.getTempLocal(a),c=assert(l.instanceofInstance);this.compileFunction(c);let _=i.if(i.unary(o==C.I64?21:20,i.local_tee(p.index,s,a.isManaged)),i.i32(0),this.makeCallDirect(c,[i.local_get(p.index,o),i.i32(t.classReference.id)],e));return n.freeTempLocal(p),_}}}return i.maybeDropCondition(s,i.i32(0))}makeInstanceofClass(e,t){var i=this.module,n=this.compileExpression(e.expression,u.auto),s=this.currentType,a=s.toRef();this.currentType=u.bool;var o=s.getClass();if(o){if(o.extends(t))return s.isNullableReference?i.binary(a==C.I64?41:16,n,this.makeZero(s,e.expression)):i.maybeDropCondition(n,i.i32(1));if(t.extends(o.prototype))return this.pendingClassInstanceOf.add(t),i.call(t.internalName+"~instanceof",[n],C.I32)}return i.maybeDropCondition(n,i.i32(0))}compileLiteralExpression(e,t,i,n=!1){var s=this.module;switch(e.literalKind){case 5:return assert(!n),this.compileArrayLiteral(e,t,i);case 0:{let a=e.value;return n&&(a=-a),t==u.f32?s.f32(a):(this.currentType=u.f64,s.f64(a))}case 1:{let a=e.value;n&&(a=i64_sub(i64_new(0),a));let o=this.resolver.determineIntegerLiteralType(a,t);switch(this.currentType=o,o.kind){case 4:if(!this.options.isWasm64)return s.i32(i64_low(a));case 3:return s.i64(i64_low(a),i64_high(a));case 9:if(!this.options.isWasm64)return s.i32(i64_low(a));case 8:return s.i64(i64_low(a),i64_high(a));case 11:return s.f32(i64_to_f32(a));case 12:return s.f64(i64_to_f64(a));default:return s.i32(i64_low(a))}}case 2:return assert(!n),this.compileStringLiteral(e,i);case 3:return assert(!n),this.compileTemplateLiteral(e,i);case 6:return assert(!n),this.compileObjectLiteral(e,t);case 4:return this.error(100,e.range,"Regular expressions"),this.currentType=t,s.unreachable()}return assert(!1),s.unreachable()}compileStringLiteral(e,t){return this.ensureStaticString(e.value)}compileTemplateLiteral(e,t){var i=e.tag,n=e.parts,s=n.length,a=e.expressions,o=a.length;assert(o==s-1);var l=this.module,p=this.program.stringInstance,c=p.type;if(!i){if(s==1)return this.ensureStaticString(n[0]);if(s==2){let j=a[0],D=n[0].length,_e=n[1].length;if(!D&&!_e)return this.makeToString(this.compileExpression(j,c),this.currentType,j);let Ct=D!=0;if(Ct^_e!=0){let qe,Jt,ft=this.makeToString(this.compileExpression(j,c),this.currentType,j);Ct?(qe=this.ensureStaticString(n[0]),Jt=ft):(qe=ft,Jt=this.ensureStaticString(n[1]));let mi=assert(p.getMethod("concat"));return this.makeCallDirect(mi,[qe,Jt],j)}}if(s==3&&!n[0].length&&!n[1].length&&!n[2].length){let j=a[0],D=a[1],_e=this.makeToString(this.compileExpression(j,c),this.currentType,j),Ct=this.makeToString(this.compileExpression(D,c),this.currentType,D),qe=assert(p.getMethod("concat"));return this.makeCallDirect(qe,[_e,Ct],e)}let P=s+o,F=new Array(P);F[0]=this.ensureStaticString(n[0]);for(let j=1;j",t.toString()),i.unreachable();var s=n.type;if(this.currentType=s.nonNullableType,n.kind==9)return this.error(100,e.range,"Interface hidden classes"),i.unreachable();if(n.is(128))return this.error(2511,e.range),i.unreachable();var a=n.prototype.constructorPrototype;if(a)return this.errorRelated(216,e.range,a.identifierNode.range,s.toString()),i.unreachable();var o=s.isManaged;o||this.checkUnsafe(e,gt(6,n.decoratorNodes));var l=e.names,p=l.length,c=e.values,_=n.members,f=!1,E=new Array,g=this.currentFlow,b=g.getTempLocal(s),S=s.toRef();assert(p==c.length);var v=new Set;if(_)for(let L=Map_keys(_),P=0,F=L.length;P",s.toString()),f=!0;continue}switch(U.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:{E.push(i.call(w.internalSetterName,[i.local_get(b.index,S),this.makeZero(U,e)],C.None)),this.compileFieldSetter(w);continue}}this.error(2741,e.range,w.name,"",s.toString()),f=!0}}if(f)return i.unreachable();var x=this.ensureConstructor(n,e);return E.unshift(i.local_set(b.index,this.compileInstantiate(x,[],0,e),s.isManaged)),E.push(i.local_get(b.index,S)),o||g.freeTempLocal(b),this.currentType=s.nonNullableType,i.flatten(E,S)}compileNewExpression(e,t,i){var n=this.module,s=this.currentFlow,a=this.resolver.resolveTypeName(e.typeName,s.actualFunction);if(!a)return n.unreachable();if(a.kind!=6)return this.error(2351,e.typeName.range),this.module.unreachable();if(a.is(128))return this.error(2511,e.typeName.range),this.module.unreachable();var o=a,l=null,p=e.typeArguments,c;if(!p&&(c=t.classReference)&&c.prototype==o&&c.is(32768)?l=this.resolver.resolveClass(o,c.typeArguments,re(s.contextualTypeArguments)):l=this.resolver.resolveClassInclTypeArguments(o,p,s.actualFunction.parent,re(s.contextualTypeArguments),e),!l)return n.unreachable();t==u.void&&(i|=8);var _=this.ensureConstructor(l,e);return _.hasDecorator(64)||this.checkFieldInitialization(l,e),this.compileInstantiate(_,e.args,i,e)}ensureConstructor(e,t){var i=e.constructorInstance;if(i){if(i.is(4194304))return i;i.hasDecorator(64)||this.compileFunction(i)}else{let n=e.base,s=re(e.contextualTypeArguments);if(n){let x=this.ensureConstructor(n,t);this.checkFieldInitialization(n,t),i=new je(O.constructor,new Xe(O.constructor,e,x.declaration.clone()),null,x.signature,s)}else i=new je(O.constructor,new Xe(O.constructor,e,this.program.makeNativeFunctionDeclaration(O.constructor,393216)),null,new ve(this.program,null,e.type,e.type),s);i.set(4194304),i.prototype.setResolvedInstance("",i),e.is(524288)&&i.set(524288),e.constructorInstance=i;let a=e.members;a||(e.members=a=new Map),a.set("constructor",i.prototype);let o=this.currentFlow,l=i.flow;this.currentFlow=l;let p=i.signature,c=this.module,_=this.options.sizeTypeRef,f=new Array;if(f.push(this.makeConditionalAllocation(e,0)),n){let x=p.parameterTypes,L=x.length,P=new Array(1+L);P[0]=c.local_get(0,_);for(let F=1;F<=L;++F)P[F]=c.local_get(F,x[F-1].toRef());f.push(c.local_set(0,this.makeCallDirect(assert(n.constructorInstance),P,t,!1),n.type.isManaged))}this.makeFieldInitializationInConstructor(e,f),f.push(c.local_get(0,_)),l.freeScopedLocals(),this.currentFlow=o;let E=i.localsByIndex,g=new Array,b=1+p.parameterTypes.length,S=E.length;if(S>b)for(let x=b;x=0);let _=p.parent;assert(_.kind==7),l=assert(l);let f=this.compileExpression(l,_.type,33),E=this.currentType;if(s.actualFunction.is(262144)&&l.kind==24&&!s.isThisFieldFlag(p,1)&&!p.is(8192)&&this.errorRelated(2565,e.range,p.identifierNode.range,p.internalName),E.isNullableReference&&(s.isNonnull(f,E)||this.error(2531,l.range)),!p.is(4194304)){p.set(4194304);let b=p.typeNode;b&&this.checkTypeSupported(p.type,b)}this.currentType=c;let g=n.load(c.byteSize,c.isSignedIntegerValue,f,c.toRef(),p.memoryOffset);return p.is(8192)&&c.isReference&&!c.isNullableReference&&(g=this.makeRuntimeNonNullCheck(g,c,e)),g}case 12:{let p=o,c=this.resolver.resolveProperty(p);if(!c)return n.unreachable();o=c}case 13:{let c=o.getterInstance;if(!c)return n.unreachable();let _=0;return c.is(131072)&&(_=this.compileExpression(assert(l),assert(c.signature.thisType),33)),this.compileCallDirect(c,[],e,_)}case 4:{let p=o,c=this.resolver.resolveFunction(p,null);if(!c||!this.compileFunction(c))return n.unreachable();this.currentType=c.type;let _=this.ensureRuntimeFunction(c);return this.options.isWasm64?n.i64(i64_low(_),i64_high(_)):n.i32(i64_low(_))}}return this.error(234,e.range),this.module.unreachable()}compileTernaryExpression(e,t,i){var n=this.module,s=e.ifThen,a=e.ifElse,o=this.makeIsTrueish(this.compileExpression(e.condition,u.bool),this.currentType,e.condition),l=this.evaluateCondition(o);if(l==1)return n.maybeDropCondition(o,this.compileExpression(s,t));if(l==2)return n.maybeDropCondition(o,this.compileExpression(a,t));var p=this.currentFlow,c=p.fork();c.inheritNonnullIfTrue(o),this.currentFlow=c;var _=this.compileExpression(s,t),f=this.currentType,E=p.fork();E.inheritNonnullIfFalse(o),this.currentFlow=E;var g=this.compileExpression(a,t==u.auto?f:t),b=this.currentType;if(t==u.void)f!=u.void&&(_=n.drop(_),f=u.void),b!=u.void&&(g=n.drop(g),b=u.void),this.currentType=u.void;else{let S=u.commonDenominator(f,b,!1);if(!S)return this.error(2322,a.range,b.toString(),f.toString()),this.currentType=t,n.unreachable();_=this.convertExpression(_,f,S,!1,s),f=S,g=this.convertExpression(g,b,S,!1,a),b=S,this.currentType=S}return c.freeScopedLocals(),E.freeScopedLocals(),this.currentFlow=p,p.inheritMutual(c,E),n.if(o,_,g)}compileUnaryPostfixExpression(e,t,i){var n=this.module,s=this.currentFlow,a=this.compileExpression(e.operand,t.exceptVoid,0);if(te(a)==23)return a;var o=null;t!=u.void&&(o=s.getTempLocal(this.currentType),a=n.local_tee(o.index,a,this.currentType.isManaged));var l;switch(e.operator){case 86:{let E=this.currentType.getClassOrWrapper(this.program);if(E){let g=E.lookupOverload(29);if(g){let b=g.is(131072);if(o&&!b&&(a=lr(a),s.freeTempLocal(o),o=null),l=this.compileUnaryOverload(g,e.operand,a,e),b)break;return l}}if(!this.currentType.isValue)return this.error(2469,e.range,"++",this.currentType.toString()),o&&s.freeTempLocal(o),n.unreachable();switch(this.currentType.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:{l=n.binary(0,a,n.i32(1));break}case 9:case 4:{let g=this.options;l=n.binary(g.isWasm64?25:0,a,this.makeOne(this.currentType));break}case 3:case 8:{l=n.binary(25,a,n.i64(1));break}case 11:{l=n.binary(50,a,n.f32(1));break}case 12:{l=n.binary(63,a,n.f64(1));break}default:return this.error(2469,e.range,"++",this.currentType.toString()),n.unreachable()}break}case 87:{let E=this.currentType.getClassOrWrapper(this.program);if(E){let g=E.lookupOverload(30);if(g){let b=g.is(131072);if(o&&!b&&(a=lr(a),s.freeTempLocal(o),o=null),l=this.compileUnaryOverload(g,e.operand,a,e),g.is(131072))break;return l}}if(!this.currentType.isValue)return this.error(2469,e.range,"--",this.currentType.toString()),o&&s.freeTempLocal(o),n.unreachable();switch(this.currentType.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:{l=n.binary(1,a,n.i32(1));break}case 9:case 4:{let g=this.options;l=n.binary(g.isWasm64?26:1,a,this.makeOne(this.currentType));break}case 3:case 8:{l=n.binary(26,a,n.i64(1));break}case 11:{l=n.binary(51,a,n.f32(1));break}case 12:{l=n.binary(64,a,n.f64(1));break}default:return this.error(2469,e.range,"--",this.currentType.toString()),n.unreachable()}break}default:return assert(!1),n.unreachable()}var p=this.resolver,c=p.lookupExpression(e.operand,s);if(!c)return o&&s.freeTempLocal(o),n.unreachable();if(!o)return this.makeAssignment(c,l,this.currentType,e.operand,p.currentThisExpression,p.currentElementExpression,!1);var _=this.makeAssignment(c,l,this.currentType,e.operand,p.currentThisExpression,p.currentElementExpression,!1);this.currentType=o.type,s.freeTempLocal(o);var f=o.type.toRef();return n.block(null,[_,n.local_get(o.index,f)],f)}compileUnaryPrefixExpression(e,t,i){var n=this.module,s=!1,a;switch(e.operator){case 80:{a=this.compileExpression(e.operand,t.exceptVoid,0);let p=this.currentType.getClassOrWrapper(this.program);if(p){let c=p.lookupOverload(23);if(c)return this.compileUnaryOverload(c,e.operand,a,e)}if(!this.currentType.isValue)return this.error(2469,e.range,"+",this.currentType.toString()),n.unreachable();break}case 81:{let p=e.operand;if(p.isNumericLiteral){a=this.compileLiteralExpression(p,t,0,!0),this.options.sourceMap&&this.addDebugLocation(a,e.range);break}a=this.compileExpression(e.operand,t.exceptVoid,0);let c=this.currentType.getClassOrWrapper(this.program);if(c){let _=c.lookupOverload(24);if(_)return this.compileUnaryOverload(_,e.operand,a,e)}if(!this.currentType.isValue)return this.error(2469,e.range,"-",this.currentType.toString()),n.unreachable();switch(this.currentType.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:{a=n.binary(1,n.i32(0),a);break}case 9:case 4:{a=n.binary(this.options.isWasm64?26:1,this.makeZero(this.currentType,e.operand),a);break}case 3:case 8:{a=n.binary(26,n.i64(0),a);break}case 11:{a=n.unary(6,a);break}case 12:{a=n.unary(7,a);break}default:this.error(2469,e.range,"-",this.currentType.toString()),a=n.unreachable()}break}case 86:{s=!0,a=this.compileExpression(e.operand,t.exceptVoid,0);let p=this.currentType.getClassOrWrapper(this.program);if(p){let c=p.lookupOverload(27);if(c){if(a=this.compileUnaryOverload(c,e.operand,a,e),c.is(131072))break;return a}}if(!this.currentType.isValue)return this.error(2469,e.range,"++",this.currentType.toString()),n.unreachable();switch(this.currentType.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:{a=n.binary(0,a,this.module.i32(1));break}case 9:case 4:{a=n.binary(this.options.isWasm64?25:0,a,this.makeOne(this.currentType));break}case 3:case 8:{a=n.binary(25,a,n.i64(1));break}case 11:{a=n.binary(50,a,n.f32(1));break}case 12:{a=n.binary(63,a,n.f64(1));break}default:this.error(2469,e.range,"++",this.currentType.toString()),a=n.unreachable()}break}case 87:{s=!0,a=this.compileExpression(e.operand,t.exceptVoid,0);let p=this.currentType.getClassOrWrapper(this.program);if(p){let c=p.lookupOverload(28);if(c){if(a=this.compileUnaryOverload(c,e.operand,a,e),c.is(131072))break;return a}}if(!this.currentType.isValue)return this.error(2469,e.range,"--",this.currentType.toString()),n.unreachable();switch(this.currentType.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:{a=n.binary(1,a,n.i32(1));break}case 9:case 4:{a=n.binary(this.options.isWasm64?26:1,a,this.makeOne(this.currentType));break}case 3:case 8:{a=n.binary(26,a,n.i64(1));break}case 11:{a=n.binary(51,a,n.f32(1));break}case 12:{a=n.binary(64,a,n.f64(1));break}default:this.error(2469,e.range,"--",this.currentType.toString()),a=n.unreachable()}break}case 94:{a=this.compileExpression(e.operand,t.exceptVoid,0);let p=this.currentType.getClassOrWrapper(this.program);if(p){let c=p.lookupOverload(25);if(c)return this.compileUnaryOverload(c,e.operand,a,e)}a=n.unary(20,this.makeIsTrueish(a,this.currentType,e.operand)),this.currentType=u.bool;break}case 95:{a=this.compileExpression(e.operand,t==u.void?u.i32:t.isFloatValue?u.i64:t,0);let p=this.currentType.getClassOrWrapper(this.program);if(p){let c=p.lookupOverload(26);if(c)return this.compileUnaryOverload(c,e.operand,a,e)}if(!this.currentType.isValue)return this.error(2469,e.range,"~",this.currentType.toString()),n.unreachable();switch(a=this.convertExpression(a,this.currentType,this.currentType.intType,!1,e.operand),this.currentType.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:{a=n.binary(9,a,n.i32(-1));break}case 9:case 4:{a=n.binary(this.options.isWasm64?34:9,a,this.makeNegOne(this.currentType));break}case 3:case 8:{a=n.binary(34,a,n.i64(-1,-1));break}default:this.error(2469,e.range,"~",this.currentType.toString()),a=n.unreachable()}break}case 55:return this.compileTypeof(e,t,i);case 68:return this.error(100,e.range,"Spread operator"),n.unreachable();default:return assert(!1),n.unreachable()}if(!s)return a;var o=this.resolver,l=o.lookupExpression(e.operand,this.currentFlow);return l?this.makeAssignment(l,a,this.currentType,e.operand,o.currentThisExpression,o.currentElementExpression,t!=u.void):n.unreachable()}compileTypeof(e,t,i){var n=e.operand,s=0,a=this.program.stringInstance,o;if(n.kind==18)o="object";else{let l=this.resolver.lookupExpression(n,this.currentFlow,u.auto,1);if(l)switch(l.kind){case 6:case 14:case 2:{o="object";break}case 4:{o="function";break}default:{s=this.compileExpression(n,u.auto);let p=this.currentType;if(s=this.convertExpression(s,p,u.void,!0,n),p.isReference)if(p.getSignature())o="function";else{let _=p.getClass();_?_.prototype==a.prototype?o="string":o="object":o="externref"}else p==u.bool?o="boolean":p.isNumericValue?o="number":o="undefined";break}}else{switch(n.kind){case 6:break;case 21:case 12:if(n=(n.kind==21,n.expression),!this.resolver.resolveExpression(n,this.currentFlow,u.auto,0))return this.currentType=a.type,this.module.unreachable();default:s=this.compileExpression(n,u.auto),s=this.convertExpression(s,this.currentType,u.void,!0,n)}o="undefined"}}return this.currentType=a.type,s?this.module.block(null,[s,this.ensureStaticString(o)],this.options.sizeTypeRef):this.ensureStaticString(o)}ensureSmallIntegerWrap(e,t){var i=this.module,n=this.currentFlow;switch(t.kind){case 0:{n.canOverflow(e,t)&&(e=this.options.hasFeature(1)?i.unary(47,e):i.binary(11,i.binary(10,e,i.i32(24)),i.i32(24)));break}case 1:{n.canOverflow(e,t)&&(e=this.options.hasFeature(1)?i.unary(48,e):i.binary(11,i.binary(10,e,i.i32(16)),i.i32(16)));break}case 5:{n.canOverflow(e,t)&&(e=i.binary(7,e,i.i32(255)));break}case 6:{n.canOverflow(e,t)&&(e=i.binary(7,e,i.i32(65535)));break}case 10:{n.canOverflow(e,t)&&(e=i.binary(16,e,i.i32(0)));break}}return e}addDebugLocation(e,t){var i=this.currentFlow.parentFunction,n=t.source;n.debugInfoIndex<0&&(n.debugInfoIndex=this.module.addDebugInfoFile(n.normalizedPath)),t.debugInfoRef=e,i.debugLocations.push(t)}checkFeatureEnabled(e,t){return this.options.hasFeature(e)?!0:(this.error(103,t.range,wr(e)),!1)}checkTypeSupported(e,t){switch(e.kind){case 13:return this.checkFeatureEnabled(16,t);case 14:case 15:return this.checkFeatureEnabled(256,t);case 16:case 17:case 18:case 19:return this.checkFeatureEnabled(256,t)&&this.checkFeatureEnabled(1024,t)}let i=e.getClass();if(i)do{let n=i.typeArguments;if(n){for(let s=0,a=n.length;so?p=a[o]:p=t,this.checkTypeSupported(s[o],p)||(i=!1)}return this.checkTypeSupported(e.returnType,t.returnType)||(i=!1),i}evaluateCondition(e){let t=oe(e);if(t==C.Unreachable)return 0;assert(t==C.I32);var i=this.module,n=i.runExpression(e,0);return n?ie(n)?1:2:0}makeZero(e,t){var i=this.module;switch(e.kind){default:assert(!1);case 0:case 1:case 2:case 5:case 6:case 7:case 10:return i.i32(0);case 4:case 9:if(e.size!=64)return i.i32(0);case 3:case 8:return i.i64(0);case 11:return i.f32(0);case 12:return i.f64(0);case 13:return i.v128(pa);case 14:case 15:case 16:case 17:case 19:return i.ref_null(e.toRef());case 18:return i.i31_new(i.i32(0))}}makeOne(e){var t=this.module;switch(e.kind){default:assert(!1);case 0:case 1:case 2:case 5:case 6:case 7:case 10:return t.i32(1);case 4:case 9:if(e.size!=64)return t.i32(1);case 3:case 8:return t.i64(1);case 11:return t.f32(1);case 12:return t.f64(1);case 18:return t.i31_new(t.i32(1))}}makeNegOne(e){var t=this.module;switch(e.kind){default:assert(!1);case 0:case 1:case 2:case 5:case 6:case 7:return t.i32(-1);case 4:case 9:if(e.size!=64)return t.i32(-1);case 3:case 8:return t.i64(-1,-1);case 11:return t.f32(-1);case 12:return t.f64(-1)}}makeIsTrueish(e,t,i){var n=this.module;switch(t.kind){case 0:case 1:case 5:case 6:e=this.ensureSmallIntegerWrap(e,t);case 10:case 2:case 7:return e;case 3:case 8:return n.binary(41,e,n.i64(0));case 9:case 4:return t.size==64?n.binary(41,e,n.i64(0)):e;case 11:return n.binary(20,n.binary(1,n.binary(10,n.unary(33,e),n.i32(1)),n.i32(2)),n.i32(4278190078));case 12:return n.binary(45,n.binary(26,n.binary(35,n.unary(34,e),n.i64(1)),n.i64(2)),n.i64(4294967294,4292870143));case 13:return n.unary(67,e);case 14:case 15:case 16:case 17:case 19:case 18:return n.unary(20,n.ref_is(0,e));default:return assert(!1),n.i32(0)}}makeToString(e,t,i){var n=this.program.stringInstance.type;if(t==n)return e;var s=t.getClassOrWrapper(this.program);if(s){let a=s.getMethod("toString");if(a){let o=a.signature;if(!this.checkCallSignature(o,0,!0,i))return this.currentType=n,this.module.unreachable();if(!t.isStrictlyAssignableTo(assert(o.thisType)))return this.errorRelated(2685,i.range,a.identifierAndSignatureRange),this.currentType=n,this.module.unreachable();let l=o.returnType;return l.isStrictlyAssignableTo(n)?this.makeCallDirect(a,[e],i):(this.errorRelated(2322,i.range,a.identifierAndSignatureRange,l.toString(),n.toString()),this.currentType=n,this.module.unreachable())}}return this.error(2322,i.range,t.toString(),n.toString()),this.currentType=n,this.module.unreachable()}makeAllocation(e){var t=this.program;assert(e.program==t);var i=this.module,n=this.options;if(this.currentType=e.type,e.hasDecorator(16)){let s=t.allocInstance;return this.compileFunction(s),i.call(s.internalName,[n.isWasm64?i.i64(e.nextMemoryOffset):i.i32(e.nextMemoryOffset)],n.sizeTypeRef)}else{let s=t.newInstance;return this.compileFunction(s),i.call(s.internalName,[n.isWasm64?i.i64(e.nextMemoryOffset):i.i32(e.nextMemoryOffset),i.i32(e.id)],n.sizeTypeRef)}}makeConditionalAllocation(e,t){var i=this.module,n=e.type,s=n.toRef();return assert(s==this.options.sizeTypeRef),i.if(i.unary(s==C.I64?21:20,i.local_get(t,s)),i.local_set(t,this.makeAllocation(e),e.type.isManaged))}makeFieldInitializationInConstructor(e,t=[]){var i=e.members;if(!i)return t;var n=this.module,s=this.currentFlow,a=s.isInline,o=a?s.lookupLocal(O.this_).index:0,l=this.options.sizeTypeRef,p=null;for(let c=Map_values(i),_=0,f=c.length;_0){let a=s[0];a.isLiteralKind(2)?(zt=a.value,s.length>=2&&(a=s[1],a.isLiteralKind(2)?(pr=zt,zt=a.value,s.length>2&&i.error(2554,n.range,"2",s.length.toString())):i.error(1141,a.range))):i.error(1141,a.range)}else i.error(2555,n.range,"1","0")}}var pr,zt;var h;(m=>(m.start="~start",m.started="~started",m.argumentsLength="~argumentsLength",m.setArgumentsLength="~setArgumentsLength",m.abort="~lib/builtins/abort",m.trace="~lib/builtins/trace",m.seed="~lib/builtins/seed",m.isInteger="~lib/builtins/isInteger",m.isFloat="~lib/builtins/isFloat",m.isBoolean="~lib/builtins/isBoolean",m.isSigned="~lib/builtins/isSigned",m.isReference="~lib/builtins/isReference",m.isString="~lib/builtins/isString",m.isArray="~lib/builtins/isArray",m.isArrayLike="~lib/builtins/isArrayLike",m.isFunction="~lib/builtins/isFunction",m.isNullable="~lib/builtins/isNullable",m.isDefined="~lib/builtins/isDefined",m.isConstant="~lib/builtins/isConstant",m.isManaged="~lib/builtins/isManaged",m.isVoid="~lib/builtins/isVoid",m.add="~lib/builtins/add",m.sub="~lib/builtins/sub",m.mul="~lib/builtins/mul",m.div="~lib/builtins/div",m.clz="~lib/builtins/clz",m.ctz="~lib/builtins/ctz",m.popcnt="~lib/builtins/popcnt",m.rotl="~lib/builtins/rotl",m.rotr="~lib/builtins/rotr",m.abs="~lib/builtins/abs",m.max="~lib/builtins/max",m.min="~lib/builtins/min",m.ceil="~lib/builtins/ceil",m.floor="~lib/builtins/floor",m.copysign="~lib/builtins/copysign",m.nearest="~lib/builtins/nearest",m.reinterpret="~lib/builtins/reinterpret",m.sqrt="~lib/builtins/sqrt",m.trunc="~lib/builtins/trunc",m.eq="~lib/builtins/eq",m.ne="~lib/builtins/ne",m.load="~lib/builtins/load",m.store="~lib/builtins/store",m.atomic_load="~lib/builtins/atomic.load",m.atomic_store="~lib/builtins/atomic.store",m.atomic_add="~lib/builtins/atomic.add",m.atomic_sub="~lib/builtins/atomic.sub",m.atomic_and="~lib/builtins/atomic.and",m.atomic_or="~lib/builtins/atomic.or",m.atomic_xor="~lib/builtins/atomic.xor",m.atomic_xchg="~lib/builtins/atomic.xchg",m.atomic_cmpxchg="~lib/builtins/atomic.cmpxchg",m.atomic_wait="~lib/builtins/atomic.wait",m.atomic_notify="~lib/builtins/atomic.notify",m.atomic_fence="~lib/builtins/atomic.fence",m.sizeof="~lib/builtins/sizeof",m.alignof="~lib/builtins/alignof",m.offsetof="~lib/builtins/offsetof",m.nameof="~lib/builtins/nameof",m.lengthof="~lib/builtins/lengthof",m.select="~lib/builtins/select",m.unreachable="~lib/builtins/unreachable",m.changetype="~lib/builtins/changetype",m.assert="~lib/builtins/assert",m.call_indirect="~lib/builtins/call_indirect",m.unchecked="~lib/builtins/unchecked",m.instantiate="~lib/builtins/instantiate",m.idof="~lib/builtins/idof",m.i8="~lib/builtins/i8",m.i16="~lib/builtins/i16",m.i32="~lib/builtins/i32",m.i64="~lib/builtins/i64",m.isize="~lib/builtins/isize",m.u8="~lib/builtins/u8",m.u16="~lib/builtins/u16",m.u32="~lib/builtins/u32",m.u64="~lib/builtins/u64",m.usize="~lib/builtins/usize",m.bool="~lib/builtins/bool",m.f32="~lib/builtins/f32",m.f64="~lib/builtins/f64",m.v128="~lib/builtins/v128",m.i32_clz="~lib/builtins/i32.clz",m.i64_clz="~lib/builtins/i64.clz",m.i32_ctz="~lib/builtins/i32.ctz",m.i64_ctz="~lib/builtins/i64.ctz",m.i32_popcnt="~lib/builtins/i32.popcnt",m.i64_popcnt="~lib/builtins/i64.popcnt",m.i32_rotl="~lib/builtins/i32.rotl",m.i64_rotl="~lib/builtins/i64.rotl",m.i32_rotr="~lib/builtins/i32.rotr",m.i64_rotr="~lib/builtins/i64.rotr",m.f32_abs="~lib/builtins/f32.abs",m.f64_abs="~lib/builtins/f64.abs",m.f32_max="~lib/builtins/f32.max",m.f64_max="~lib/builtins/f64.max",m.f32_min="~lib/builtins/f32.min",m.f64_min="~lib/builtins/f64.min",m.f32_ceil="~lib/builtins/f32.ceil",m.f64_ceil="~lib/builtins/f64.ceil",m.f32_floor="~lib/builtins/f32.floor",m.f64_floor="~lib/builtins/f64.floor",m.f32_copysign="~lib/builtins/f32.copysign",m.f64_copysign="~lib/builtins/f64.copysign",m.f32_nearest="~lib/builtins/f32.nearest",m.f64_nearest="~lib/builtins/f64.nearest",m.i32_reinterpret_f32="~lib/builtins/i32.reinterpret_f32",m.i64_reinterpret_f64="~lib/builtins/i64.reinterpret_f64",m.f32_reinterpret_i32="~lib/builtins/f32.reinterpret_i32",m.f64_reinterpret_i64="~lib/builtins/f64.reinterpret_i64",m.f32_sqrt="~lib/builtins/f32.sqrt",m.f64_sqrt="~lib/builtins/f64.sqrt",m.f32_trunc="~lib/builtins/f32.trunc",m.f64_trunc="~lib/builtins/f64.trunc",m.i32_add="~lib/builtins/i32.add",m.i64_add="~lib/builtins/i64.add",m.f32_add="~lib/builtins/f32.add",m.f64_add="~lib/builtins/f64.add",m.i32_sub="~lib/builtins/i32.sub",m.i64_sub="~lib/builtins/i64.sub",m.f32_sub="~lib/builtins/f32.sub",m.f64_sub="~lib/builtins/f64.sub",m.i32_mul="~lib/builtins/i32.mul",m.i64_mul="~lib/builtins/i64.mul",m.f32_mul="~lib/builtins/f32.mul",m.f64_mul="~lib/builtins/f64.mul",m.i32_div_s="~lib/builtins/i32.div_s",m.i32_div_u="~lib/builtins/i32.div_u",m.i64_div_s="~lib/builtins/i64.div_s",m.i64_div_u="~lib/builtins/i64.div_u",m.f32_div="~lib/builtins/f32.div",m.f64_div="~lib/builtins/f64.div",m.i32_eq="~lib/builtins/i32.eq",m.i64_eq="~lib/builtins/i64.eq",m.f32_eq="~lib/builtins/f32.eq",m.f64_eq="~lib/builtins/f64.eq",m.i32_ne="~lib/builtins/i32.ne",m.i64_ne="~lib/builtins/i64.ne",m.f32_ne="~lib/builtins/f32.ne",m.f64_ne="~lib/builtins/f64.ne",m.i32_load8_s="~lib/builtins/i32.load8_s",m.i32_load8_u="~lib/builtins/i32.load8_u",m.i32_load16_s="~lib/builtins/i32.load16_s",m.i32_load16_u="~lib/builtins/i32.load16_u",m.i32_load="~lib/builtins/i32.load",m.i64_load8_s="~lib/builtins/i64.load8_s",m.i64_load8_u="~lib/builtins/i64.load8_u",m.i64_load16_s="~lib/builtins/i64.load16_s",m.i64_load16_u="~lib/builtins/i64.load16_u",m.i64_load32_s="~lib/builtins/i64.load32_s",m.i64_load32_u="~lib/builtins/i64.load32_u",m.i64_load="~lib/builtins/i64.load",m.f32_load="~lib/builtins/f32.load",m.f64_load="~lib/builtins/f64.load",m.i32_store8="~lib/builtins/i32.store8",m.i32_store16="~lib/builtins/i32.store16",m.i32_store="~lib/builtins/i32.store",m.i64_store8="~lib/builtins/i64.store8",m.i64_store16="~lib/builtins/i64.store16",m.i64_store32="~lib/builtins/i64.store32",m.i64_store="~lib/builtins/i64.store",m.f32_store="~lib/builtins/f32.store",m.f64_store="~lib/builtins/f64.store",m.i32_atomic_load8_u="~lib/builtins/i32.atomic.load8_u",m.i32_atomic_load16_u="~lib/builtins/i32.atomic.load16_u",m.i32_atomic_load="~lib/builtins/i32.atomic.load",m.i64_atomic_load8_u="~lib/builtins/i64.atomic.load8_u",m.i64_atomic_load16_u="~lib/builtins/i64.atomic.load16_u",m.i64_atomic_load32_u="~lib/builtins/i64.atomic.load32_u",m.i64_atomic_load="~lib/builtins/i64.atomic.load",m.i32_atomic_store8="~lib/builtins/i32.atomic.store8",m.i32_atomic_store16="~lib/builtins/i32.atomic.store16",m.i32_atomic_store="~lib/builtins/i32.atomic.store",m.i64_atomic_store8="~lib/builtins/i64.atomic.store8",m.i64_atomic_store16="~lib/builtins/i64.atomic.store16",m.i64_atomic_store32="~lib/builtins/i64.atomic.store32",m.i64_atomic_store="~lib/builtins/i64.atomic.store",m.i32_atomic_rmw8_add_u="~lib/builtins/i32.atomic.rmw8.add_u",m.i32_atomic_rmw16_add_u="~lib/builtins/i32.atomic.rmw16.add_u",m.i32_atomic_rmw_add="~lib/builtins/i32.atomic.rmw.add",m.i64_atomic_rmw8_add_u="~lib/builtins/i64.atomic.rmw8.add_u",m.i64_atomic_rmw16_add_u="~lib/builtins/i64.atomic.rmw16.add_u",m.i64_atomic_rmw32_add_u="~lib/builtins/i64.atomic.rmw32.add_u",m.i64_atomic_rmw_add="~lib/builtins/i64.atomic.rmw.add",m.i32_atomic_rmw8_sub_u="~lib/builtins/i32.atomic.rmw8.sub_u",m.i32_atomic_rmw16_sub_u="~lib/builtins/i32.atomic.rmw16.sub_u",m.i32_atomic_rmw_sub="~lib/builtins/i32.atomic.rmw.sub",m.i64_atomic_rmw8_sub_u="~lib/builtins/i64.atomic.rmw8.sub_u",m.i64_atomic_rmw16_sub_u="~lib/builtins/i64.atomic.rmw16.sub_u",m.i64_atomic_rmw32_sub_u="~lib/builtins/i64.atomic.rmw32.sub_u",m.i64_atomic_rmw_sub="~lib/builtins/i64.atomic.rmw.sub",m.i32_atomic_rmw8_and_u="~lib/builtins/i32.atomic.rmw8.and_u",m.i32_atomic_rmw16_and_u="~lib/builtins/i32.atomic.rmw16.and_u",m.i32_atomic_rmw_and="~lib/builtins/i32.atomic.rmw.and",m.i64_atomic_rmw8_and_u="~lib/builtins/i64.atomic.rmw8.and_u",m.i64_atomic_rmw16_and_u="~lib/builtins/i64.atomic.rmw16.and_u",m.i64_atomic_rmw32_and_u="~lib/builtins/i64.atomic.rmw32.and_u",m.i64_atomic_rmw_and="~lib/builtins/i64.atomic.rmw.and",m.i32_atomic_rmw8_or_u="~lib/builtins/i32.atomic.rmw8.or_u",m.i32_atomic_rmw16_or_u="~lib/builtins/i32.atomic.rmw16.or_u",m.i32_atomic_rmw_or="~lib/builtins/i32.atomic.rmw.or",m.i64_atomic_rmw8_or_u="~lib/builtins/i64.atomic.rmw8.or_u",m.i64_atomic_rmw16_or_u="~lib/builtins/i64.atomic.rmw16.or_u",m.i64_atomic_rmw32_or_u="~lib/builtins/i64.atomic.rmw32.or_u",m.i64_atomic_rmw_or="~lib/builtins/i64.atomic.rmw.or",m.i32_atomic_rmw8_xor_u="~lib/builtins/i32.atomic.rmw8.xor_u",m.i32_atomic_rmw16_xor_u="~lib/builtins/i32.atomic.rmw16.xor_u",m.i32_atomic_rmw_xor="~lib/builtins/i32.atomic.rmw.xor",m.i64_atomic_rmw8_xor_u="~lib/builtins/i64.atomic.rmw8.xor_u",m.i64_atomic_rmw16_xor_u="~lib/builtins/i64.atomic.rmw16.xor_u",m.i64_atomic_rmw32_xor_u="~lib/builtins/i64.atomic.rmw32.xor_u",m.i64_atomic_rmw_xor="~lib/builtins/i64.atomic.rmw.xor",m.i32_atomic_rmw8_xchg_u="~lib/builtins/i32.atomic.rmw8.xchg_u",m.i32_atomic_rmw16_xchg_u="~lib/builtins/i32.atomic.rmw16.xchg_u",m.i32_atomic_rmw_xchg="~lib/builtins/i32.atomic.rmw.xchg",m.i64_atomic_rmw8_xchg_u="~lib/builtins/i64.atomic.rmw8.xchg_u",m.i64_atomic_rmw16_xchg_u="~lib/builtins/i64.atomic.rmw16.xchg_u",m.i64_atomic_rmw32_xchg_u="~lib/builtins/i64.atomic.rmw32.xchg_u",m.i64_atomic_rmw_xchg="~lib/builtins/i64.atomic.rmw.xchg",m.i32_atomic_rmw8_cmpxchg_u="~lib/builtins/i32.atomic.rmw8.cmpxchg_u",m.i32_atomic_rmw16_cmpxchg_u="~lib/builtins/i32.atomic.rmw16.cmpxchg_u",m.i32_atomic_rmw_cmpxchg="~lib/builtins/i32.atomic.rmw.cmpxchg",m.i64_atomic_rmw8_cmpxchg_u="~lib/builtins/i64.atomic.rmw8.cmpxchg_u",m.i64_atomic_rmw16_cmpxchg_u="~lib/builtins/i64.atomic.rmw16.cmpxchg_u",m.i64_atomic_rmw32_cmpxchg_u="~lib/builtins/i64.atomic.rmw32.cmpxchg_u",m.i64_atomic_rmw_cmpxchg="~lib/builtins/i64.atomic.rmw.cmpxchg",m.i32_wait="~lib/builtins/i32.wait",m.i64_wait="~lib/builtins/i64.wait",m.v128_splat="~lib/builtins/v128.splat",m.v128_extract_lane="~lib/builtins/v128.extract_lane",m.v128_replace_lane="~lib/builtins/v128.replace_lane",m.v128_shuffle="~lib/builtins/v128.shuffle",m.v128_swizzle="~lib/builtins/v128.swizzle",m.v128_load_splat="~lib/builtins/v128.load_splat",m.v128_load_ext="~lib/builtins/v128.load_ext",m.v128_load_zero="~lib/builtins/v128.load_zero",m.v128_load_lane="~lib/builtins/v128.load_lane",m.v128_store_lane="~lib/builtins/v128.store_lane",m.v128_load="~lib/builtins/v128.load",m.v128_load8x8_s="~lib/builtins/v128.load8x8_s",m.v128_load8x8_u="~lib/builtins/v128.load8x8_u",m.v128_load16x4_s="~lib/builtins/v128.load16x4_s",m.v128_load16x4_u="~lib/builtins/v128.load16x4_u",m.v128_load32x2_s="~lib/builtins/v128.load32x2_s",m.v128_load32x2_u="~lib/builtins/v128.load32x2_u",m.v128_load8_splat="~lib/builtins/v128.load8_splat",m.v128_load16_splat="~lib/builtins/v128.load16_splat",m.v128_load32_splat="~lib/builtins/v128.load32_splat",m.v128_load64_splat="~lib/builtins/v128.load64_splat",m.v128_load32_zero="~lib/builtins/v128.load32_zero",m.v128_load64_zero="~lib/builtins/v128.load64_zero",m.v128_load8_lane="~lib/builtins/v128.load8_lane",m.v128_load16_lane="~lib/builtins/v128.load16_lane",m.v128_load32_lane="~lib/builtins/v128.load32_lane",m.v128_load64_lane="~lib/builtins/v128.load64_lane",m.v128_store8_lane="~lib/builtins/v128.store8_lane",m.v128_store16_lane="~lib/builtins/v128.store16_lane",m.v128_store32_lane="~lib/builtins/v128.store32_lane",m.v128_store64_lane="~lib/builtins/v128.store64_lane",m.v128_store="~lib/builtins/v128.store",m.v128_add="~lib/builtins/v128.add",m.v128_sub="~lib/builtins/v128.sub",m.v128_mul="~lib/builtins/v128.mul",m.v128_div="~lib/builtins/v128.div",m.v128_neg="~lib/builtins/v128.neg",m.v128_add_sat="~lib/builtins/v128.add_sat",m.v128_sub_sat="~lib/builtins/v128.sub_sat",m.v128_shl="~lib/builtins/v128.shl",m.v128_shr="~lib/builtins/v128.shr",m.v128_and="~lib/builtins/v128.and",m.v128_or="~lib/builtins/v128.or",m.v128_xor="~lib/builtins/v128.xor",m.v128_andnot="~lib/builtins/v128.andnot",m.v128_not="~lib/builtins/v128.not",m.v128_bitselect="~lib/builtins/v128.bitselect",m.v128_any_true="~lib/builtins/v128.any_true",m.v128_all_true="~lib/builtins/v128.all_true",m.v128_bitmask="~lib/builtins/v128.bitmask",m.v128_popcnt="~lib/builtins/v128.popcnt",m.v128_min="~lib/builtins/v128.min",m.v128_max="~lib/builtins/v128.max",m.v128_pmin="~lib/builtins/v128.pmin",m.v128_pmax="~lib/builtins/v128.pmax",m.v128_dot="~lib/builtins/v128.dot",m.v128_avgr="~lib/builtins/v128.avgr",m.v128_abs="~lib/builtins/v128.abs",m.v128_sqrt="~lib/builtins/v128.sqrt",m.v128_ceil="~lib/builtins/v128.ceil",m.v128_floor="~lib/builtins/v128.floor",m.v128_trunc="~lib/builtins/v128.trunc",m.v128_nearest="~lib/builtins/v128.nearest",m.v128_eq="~lib/builtins/v128.eq",m.v128_ne="~lib/builtins/v128.ne",m.v128_lt="~lib/builtins/v128.lt",m.v128_le="~lib/builtins/v128.le",m.v128_gt="~lib/builtins/v128.gt",m.v128_ge="~lib/builtins/v128.ge",m.v128_convert="~lib/builtins/v128.convert",m.v128_convert_low="~lib/builtins/v128.convert_low",m.v128_trunc_sat="~lib/builtins/v128.trunc_sat",m.v128_trunc_sat_zero="~lib/builtins/v128.trunc_sat_zero",m.v128_narrow="~lib/builtins/v128.narrow",m.v128_extend_low="~lib/builtins/v128.extend_low",m.v128_extend_high="~lib/builtins/v128.extend_high",m.v128_extadd_pairwise="~lib/builtins/v128.extadd_pairwise",m.v128_demote_zero="~lib/builtins/v128.demote_zero",m.v128_promote_low="~lib/builtins/v128.promote_low",m.v128_q15mulr_sat="~lib/builtins/v128.q15mulr_sat",m.v128_extmul_low="~lib/builtins/v128.extmul_low",m.v128_extmul_high="~lib/builtins/v128.extmul_high",m.i8x16="~lib/builtins/i8x16",m.i16x8="~lib/builtins/i16x8",m.i32x4="~lib/builtins/i32x4",m.i64x2="~lib/builtins/i64x2",m.f32x4="~lib/builtins/f32x4",m.f64x2="~lib/builtins/f64x2",m.i8x16_splat="~lib/builtins/i8x16.splat",m.i8x16_extract_lane_s="~lib/builtins/i8x16.extract_lane_s",m.i8x16_extract_lane_u="~lib/builtins/i8x16.extract_lane_u",m.i8x16_replace_lane="~lib/builtins/i8x16.replace_lane",m.i8x16_add="~lib/builtins/i8x16.add",m.i8x16_sub="~lib/builtins/i8x16.sub",m.i8x16_mul="~lib/builtins/i8x16.mul",m.i8x16_min_s="~lib/builtins/i8x16.min_s",m.i8x16_min_u="~lib/builtins/i8x16.min_u",m.i8x16_max_s="~lib/builtins/i8x16.max_s",m.i8x16_max_u="~lib/builtins/i8x16.max_u",m.i8x16_avgr_u="~lib/builtins/i8x16.avgr_u",m.i8x16_abs="~lib/builtins/i8x16.abs",m.i8x16_neg="~lib/builtins/i8x16.neg",m.i8x16_add_sat_s="~lib/builtins/i8x16.add_sat_s",m.i8x16_add_sat_u="~lib/builtins/i8x16.add_sat_u",m.i8x16_sub_sat_s="~lib/builtins/i8x16.sub_sat_s",m.i8x16_sub_sat_u="~lib/builtins/i8x16.sub_sat_u",m.i8x16_shl="~lib/builtins/i8x16.shl",m.i8x16_shr_s="~lib/builtins/i8x16.shr_s",m.i8x16_shr_u="~lib/builtins/i8x16.shr_u",m.i8x16_all_true="~lib/builtins/i8x16.all_true",m.i8x16_bitmask="~lib/builtins/i8x16.bitmask",m.i8x16_popcnt="~lib/builtins/i8x16.popcnt",m.i8x16_eq="~lib/builtins/i8x16.eq",m.i8x16_ne="~lib/builtins/i8x16.ne",m.i8x16_lt_s="~lib/builtins/i8x16.lt_s",m.i8x16_lt_u="~lib/builtins/i8x16.lt_u",m.i8x16_le_s="~lib/builtins/i8x16.le_s",m.i8x16_le_u="~lib/builtins/i8x16.le_u",m.i8x16_gt_s="~lib/builtins/i8x16.gt_s",m.i8x16_gt_u="~lib/builtins/i8x16.gt_u",m.i8x16_ge_s="~lib/builtins/i8x16.ge_s",m.i8x16_ge_u="~lib/builtins/i8x16.ge_u",m.i8x16_narrow_i16x8_s="~lib/builtins/i8x16.narrow_i16x8_s",m.i8x16_narrow_i16x8_u="~lib/builtins/i8x16.narrow_i16x8_u",m.i8x16_shuffle="~lib/builtins/i8x16.shuffle",m.i8x16_swizzle="~lib/builtins/i8x16.swizzle",m.i16x8_splat="~lib/builtins/i16x8.splat",m.i16x8_extract_lane_s="~lib/builtins/i16x8.extract_lane_s",m.i16x8_extract_lane_u="~lib/builtins/i16x8.extract_lane_u",m.i16x8_replace_lane="~lib/builtins/i16x8.replace_lane",m.i16x8_add="~lib/builtins/i16x8.add",m.i16x8_sub="~lib/builtins/i16x8.sub",m.i16x8_mul="~lib/builtins/i16x8.mul",m.i16x8_min_s="~lib/builtins/i16x8.min_s",m.i16x8_min_u="~lib/builtins/i16x8.min_u",m.i16x8_max_s="~lib/builtins/i16x8.max_s",m.i16x8_max_u="~lib/builtins/i16x8.max_u",m.i16x8_avgr_u="~lib/builtins/i16x8.avgr_u",m.i16x8_abs="~lib/builtins/i16x8.abs",m.i16x8_neg="~lib/builtins/i16x8.neg",m.i16x8_add_sat_s="~lib/builtins/i16x8.add_sat_s",m.i16x8_add_sat_u="~lib/builtins/i16x8.add_sat_u",m.i16x8_sub_sat_s="~lib/builtins/i16x8.sub_sat_s",m.i16x8_sub_sat_u="~lib/builtins/i16x8.sub_sat_u",m.i16x8_shl="~lib/builtins/i16x8.shl",m.i16x8_shr_s="~lib/builtins/i16x8.shr_s",m.i16x8_shr_u="~lib/builtins/i16x8.shr_u",m.i16x8_all_true="~lib/builtins/i16x8.all_true",m.i16x8_bitmask="~lib/builtins/i16x8.bitmask",m.i16x8_eq="~lib/builtins/i16x8.eq",m.i16x8_ne="~lib/builtins/i16x8.ne",m.i16x8_lt_s="~lib/builtins/i16x8.lt_s",m.i16x8_lt_u="~lib/builtins/i16x8.lt_u",m.i16x8_le_s="~lib/builtins/i16x8.le_s",m.i16x8_le_u="~lib/builtins/i16x8.le_u",m.i16x8_gt_s="~lib/builtins/i16x8.gt_s",m.i16x8_gt_u="~lib/builtins/i16x8.gt_u",m.i16x8_ge_s="~lib/builtins/i16x8.ge_s",m.i16x8_ge_u="~lib/builtins/i16x8.ge_u",m.i16x8_narrow_i32x4_s="~lib/builtins/i16x8.narrow_i32x4_s",m.i16x8_narrow_i32x4_u="~lib/builtins/i16x8.narrow_i32x4_u",m.i16x8_extend_low_i8x16_s="~lib/builtins/i16x8.extend_low_i8x16_s",m.i16x8_extend_low_i8x16_u="~lib/builtins/i16x8.extend_low_i8x16_u",m.i16x8_extend_high_i8x16_s="~lib/builtins/i16x8.extend_high_i8x16_s",m.i16x8_extend_high_i8x16_u="~lib/builtins/i16x8.extend_high_i8x16_u",m.i16x8_extadd_pairwise_i8x16_s="~lib/builtins/i16x8.extadd_pairwise_i8x16_s",m.i16x8_extadd_pairwise_i8x16_u="~lib/builtins/i16x8.extadd_pairwise_i8x16_u",m.i16x8_q15mulr_sat_s="~lib/builtins/i16x8.q15mulr_sat_s",m.i16x8_extmul_low_i8x16_s="~lib/builtins/i16x8.extmul_low_i8x16_s",m.i16x8_extmul_low_i8x16_u="~lib/builtins/i16x8.extmul_low_i8x16_u",m.i16x8_extmul_high_i8x16_s="~lib/builtins/i16x8.extmul_high_i8x16_s",m.i16x8_extmul_high_i8x16_u="~lib/builtins/i16x8.extmul_high_i8x16_u",m.i32x4_splat="~lib/builtins/i32x4.splat",m.i32x4_extract_lane="~lib/builtins/i32x4.extract_lane",m.i32x4_replace_lane="~lib/builtins/i32x4.replace_lane",m.i32x4_add="~lib/builtins/i32x4.add",m.i32x4_sub="~lib/builtins/i32x4.sub",m.i32x4_mul="~lib/builtins/i32x4.mul",m.i32x4_min_s="~lib/builtins/i32x4.min_s",m.i32x4_min_u="~lib/builtins/i32x4.min_u",m.i32x4_max_s="~lib/builtins/i32x4.max_s",m.i32x4_max_u="~lib/builtins/i32x4.max_u",m.i32x4_dot_i16x8_s="~lib/builtins/i32x4.dot_i16x8_s",m.i32x4_abs="~lib/builtins/i32x4.abs",m.i32x4_neg="~lib/builtins/i32x4.neg",m.i32x4_shl="~lib/builtins/i32x4.shl",m.i32x4_shr_s="~lib/builtins/i32x4.shr_s",m.i32x4_shr_u="~lib/builtins/i32x4.shr_u",m.i32x4_all_true="~lib/builtins/i32x4.all_true",m.i32x4_bitmask="~lib/builtins/i32x4.bitmask",m.i32x4_eq="~lib/builtins/i32x4.eq",m.i32x4_ne="~lib/builtins/i32x4.ne",m.i32x4_lt_s="~lib/builtins/i32x4.lt_s",m.i32x4_lt_u="~lib/builtins/i32x4.lt_u",m.i32x4_le_s="~lib/builtins/i32x4.le_s",m.i32x4_le_u="~lib/builtins/i32x4.le_u",m.i32x4_gt_s="~lib/builtins/i32x4.gt_s",m.i32x4_gt_u="~lib/builtins/i32x4.gt_u",m.i32x4_ge_s="~lib/builtins/i32x4.ge_s",m.i32x4_ge_u="~lib/builtins/i32x4.ge_u",m.i32x4_trunc_sat_f32x4_s="~lib/builtins/i32x4.trunc_sat_f32x4_s",m.i32x4_trunc_sat_f32x4_u="~lib/builtins/i32x4.trunc_sat_f32x4_u",m.i32x4_trunc_sat_f64x2_s_zero="~lib/builtins/i32x4.trunc_sat_f64x2_s_zero",m.i32x4_trunc_sat_f64x2_u_zero="~lib/builtins/i32x4.trunc_sat_f64x2_u_zero",m.i32x4_extend_low_i16x8_s="~lib/builtins/i32x4.extend_low_i16x8_s",m.i32x4_extend_low_i16x8_u="~lib/builtins/i32x4.extend_low_i16x8_u",m.i32x4_extend_high_i16x8_s="~lib/builtins/i32x4.extend_high_i16x8_s",m.i32x4_extend_high_i16x8_u="~lib/builtins/i32x4.extend_high_i16x8_u",m.i32x4_extadd_pairwise_i16x8_s="~lib/builtins/i32x4.extadd_pairwise_i16x8_s",m.i32x4_extadd_pairwise_i16x8_u="~lib/builtins/i32x4.extadd_pairwise_i16x8_u",m.i32x4_extmul_low_i16x8_s="~lib/builtins/i32x4.extmul_low_i16x8_s",m.i32x4_extmul_low_i16x8_u="~lib/builtins/i32x4.extmul_low_i16x8_u",m.i32x4_extmul_high_i16x8_s="~lib/builtins/i32x4.extmul_high_i16x8_s",m.i32x4_extmul_high_i16x8_u="~lib/builtins/i32x4.extmul_high_i16x8_u",m.i64x2_splat="~lib/builtins/i64x2.splat",m.i64x2_extract_lane="~lib/builtins/i64x2.extract_lane",m.i64x2_replace_lane="~lib/builtins/i64x2.replace_lane",m.i64x2_add="~lib/builtins/i64x2.add",m.i64x2_sub="~lib/builtins/i64x2.sub",m.i64x2_mul="~lib/builtins/i64x2.mul",m.i64x2_abs="~lib/builtins/i64x2.abs",m.i64x2_neg="~lib/builtins/i64x2.neg",m.i64x2_shl="~lib/builtins/i64x2.shl",m.i64x2_shr_s="~lib/builtins/i64x2.shr_s",m.i64x2_shr_u="~lib/builtins/i64x2.shr_u",m.i64x2_all_true="~lib/builtins/i64x2.all_true",m.i64x2_bitmask="~lib/builtins/i64x2.bitmask",m.i64x2_eq="~lib/builtins/i64x2.eq",m.i64x2_ne="~lib/builtins/i64x2.ne",m.i64x2_lt_s="~lib/builtins/i64x2.lt_s",m.i64x2_lt_u="~lib/builtins/i64x2.lt_u",m.i64x2_le_s="~lib/builtins/i64x2.le_s",m.i64x2_le_u="~lib/builtins/i64x2.le_u",m.i64x2_gt_s="~lib/builtins/i64x2.gt_s",m.i64x2_gt_u="~lib/builtins/i64x2.gt_u",m.i64x2_ge_s="~lib/builtins/i64x2.ge_s",m.i64x2_ge_u="~lib/builtins/i64x2.ge_u",m.i64x2_extend_low_i32x4_s="~lib/builtins/i64x2.extend_low_i32x4_s",m.i64x2_extend_low_i32x4_u="~lib/builtins/i64x2.extend_low_i32x4_u",m.i64x2_extend_high_i32x4_s="~lib/builtins/i64x2.extend_high_i32x4_s",m.i64x2_extend_high_i32x4_u="~lib/builtins/i64x2.extend_high_i32x4_u",m.i64x2_extmul_low_i32x4_s="~lib/builtins/i64x2.extmul_low_i32x4_s",m.i64x2_extmul_low_i32x4_u="~lib/builtins/i64x2.extmul_low_i32x4_u",m.i64x2_extmul_high_i32x4_s="~lib/builtins/i64x2.extmul_high_i32x4_s",m.i64x2_extmul_high_i32x4_u="~lib/builtins/i64x2.extmul_high_i32x4_u",m.f32x4_splat="~lib/builtins/f32x4.splat",m.f32x4_extract_lane="~lib/builtins/f32x4.extract_lane",m.f32x4_replace_lane="~lib/builtins/f32x4.replace_lane",m.f32x4_add="~lib/builtins/f32x4.add",m.f32x4_sub="~lib/builtins/f32x4.sub",m.f32x4_mul="~lib/builtins/f32x4.mul",m.f32x4_div="~lib/builtins/f32x4.div",m.f32x4_neg="~lib/builtins/f32x4.neg",m.f32x4_min="~lib/builtins/f32x4.min",m.f32x4_max="~lib/builtins/f32x4.max",m.f32x4_pmin="~lib/builtins/f32x4.pmin",m.f32x4_pmax="~lib/builtins/f32x4.pmax",m.f32x4_abs="~lib/builtins/f32x4.abs",m.f32x4_sqrt="~lib/builtins/f32x4.sqrt",m.f32x4_ceil="~lib/builtins/f32x4.ceil",m.f32x4_floor="~lib/builtins/f32x4.floor",m.f32x4_trunc="~lib/builtins/f32x4.trunc",m.f32x4_nearest="~lib/builtins/f32x4.nearest",m.f32x4_eq="~lib/builtins/f32x4.eq",m.f32x4_ne="~lib/builtins/f32x4.ne",m.f32x4_lt="~lib/builtins/f32x4.lt",m.f32x4_le="~lib/builtins/f32x4.le",m.f32x4_gt="~lib/builtins/f32x4.gt",m.f32x4_ge="~lib/builtins/f32x4.ge",m.f32x4_convert_i32x4_s="~lib/builtins/f32x4.convert_i32x4_s",m.f32x4_convert_i32x4_u="~lib/builtins/f32x4.convert_i32x4_u",m.f32x4_demote_f64x2_zero="~lib/builtins/f32x4.demote_f64x2_zero",m.f64x2_splat="~lib/builtins/f64x2.splat",m.f64x2_extract_lane="~lib/builtins/f64x2.extract_lane",m.f64x2_replace_lane="~lib/builtins/f64x2.replace_lane",m.f64x2_add="~lib/builtins/f64x2.add",m.f64x2_sub="~lib/builtins/f64x2.sub",m.f64x2_mul="~lib/builtins/f64x2.mul",m.f64x2_div="~lib/builtins/f64x2.div",m.f64x2_neg="~lib/builtins/f64x2.neg",m.f64x2_min="~lib/builtins/f64x2.min",m.f64x2_max="~lib/builtins/f64x2.max",m.f64x2_pmin="~lib/builtins/f64x2.pmin",m.f64x2_pmax="~lib/builtins/f64x2.pmax",m.f64x2_abs="~lib/builtins/f64x2.abs",m.f64x2_sqrt="~lib/builtins/f64x2.sqrt",m.f64x2_ceil="~lib/builtins/f64x2.ceil",m.f64x2_floor="~lib/builtins/f64x2.floor",m.f64x2_trunc="~lib/builtins/f64x2.trunc",m.f64x2_nearest="~lib/builtins/f64x2.nearest",m.f64x2_eq="~lib/builtins/f64x2.eq",m.f64x2_ne="~lib/builtins/f64x2.ne",m.f64x2_lt="~lib/builtins/f64x2.lt",m.f64x2_le="~lib/builtins/f64x2.le",m.f64x2_gt="~lib/builtins/f64x2.gt",m.f64x2_ge="~lib/builtins/f64x2.ge",m.f64x2_convert_low_i32x4_s="~lib/builtins/f64x2.convert_low_i32x4_s",m.f64x2_convert_low_i32x4_u="~lib/builtins/f64x2.convert_low_i32x4_u",m.f64x2_promote_low_f32x4="~lib/builtins/f64x2.promote_low_f32x4",m.i31_new="~lib/builtins/i31.new",m.i31_get="~lib/builtins/i31.get",m.data_end="~lib/memory/__data_end",m.stack_pointer="~lib/memory/__stack_pointer",m.heap_base="~lib/memory/__heap_base",m.rtti_base="~lib/rt/__rtti_base",m.visit_globals="~lib/rt/__visit_globals",m.visit_members="~lib/rt/__visit_members",m.tostack="~lib/rt/__tostack",m.isNaN="~lib/number/isNaN",m.isFinite="~lib/number/isFinite",m.ERROR="~lib/diagnostics/ERROR",m.WARNING="~lib/diagnostics/WARNING",m.INFO="~lib/diagnostics/INFO",m.Function="~lib/function/Function",m.memory_size="~lib/memory/memory.size",m.memory_grow="~lib/memory/memory.grow",m.memory_copy="~lib/memory/memory.copy",m.memory_fill="~lib/memory/memory.fill",m.memory_data="~lib/memory/memory.data",m.Int8Array="~lib/typedarray/Int8Array",m.Uint8Array="~lib/typedarray/Uint8Array",m.Uint8ClampedArray="~lib/typedarray/Uint8ClampedArray",m.Int16Array="~lib/typedarray/Int16Array",m.Uint16Array="~lib/typedarray/Uint16Array",m.Int32Array="~lib/typedarray/Int32Array",m.Uint32Array="~lib/typedarray/Uint32Array",m.Int64Array="~lib/typedarray/Int64Array",m.Uint64Array="~lib/typedarray/Uint64Array",m.Float32Array="~lib/typedarray/Float32Array",m.Float64Array="~lib/typedarray/Float64Array",m.String_raw="~lib/string/String.raw",m.String_eq="~lib/string/String.__eq",m.String_ne="~lib/string/String.__ne",m.String_not="~lib/string/String.__not",m.wasiAbort="~lib/wasi/index/abort",m.wasiTrace="~lib/wasi/index/trace",m.wasiSeed="~lib/wasi/index/seed"))(h||={});var Zl=class{constructor(e,t,i,n,s,a,o,l){this.compiler=e;this.prototype=t;this.typeArguments=i;this.operands=n;this.thisOperand=s;this.contextualType=a;this.reportNode=o;this.contextIsExact=l}},d=new Map,Os=new Map;function nE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isIntegerValue?1:0)):t.unreachable()}d.set(h.isInteger,nE);function sE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isFloatValue?1:0)):t.unreachable()}d.set(h.isFloat,sE);function aE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isBooleanValue?1:0)):t.unreachable()}d.set(h.isBoolean,aE);function oE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isSignedIntegerValue?1:0)):t.unreachable()}d.set(h.isSigned,oE);function lE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isReference?1:0)):t.unreachable()}d.set(h.isReference,lE);function uE(r){var e=r.compiler,t=e.module,i=Re(r);if(e.currentType=u.bool,!i)return t.unreachable();var n=i.getClass();return be(r,t.i32(n&&n.isAssignableTo(e.program.stringInstance)?1:0))}d.set(h.isString,uE);function pE(r){var e=r.compiler,t=e.module,i=Re(r);if(e.currentType=u.bool,!i)return t.unreachable();var n=i.getClass();return be(r,t.i32(n&&n.extends(e.program.arrayPrototype)?1:0))}d.set(h.isArray,pE);function cE(r){var e=r.compiler,t=e.module,i=Re(r);if(e.currentType=u.bool,!i)return t.unreachable();var n=i.getClass();return be(r,t.i32(n&&n.isArrayLike?1:0))}d.set(h.isArrayLike,cE);function _E(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isFunction?1:0)):t.unreachable()}d.set(h.isFunction,_E);function fE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isNullableReference?1:0)):t.unreachable()}d.set(h.isNullable,fE);function hE(r){var e=r.compiler,t=e.module;if(e.currentType=u.bool,T(r)|W(r,1))return t.unreachable();var i=e.resolver.lookupExpression(r.operands[0],e.currentFlow,u.auto,1);return t.i32(i?1:0)}d.set(h.isDefined,hE);function mE(r){var e=r.compiler,t=e.module;if(e.currentType=u.bool,T(r)|W(r,1))return t.unreachable();var i=e.compileExpression(r.operands[0],u.auto);return e.currentType=u.bool,zs(i,t.ref)?t.block(null,[t.maybeDrop(i),t.i32(0)],oe(i)):t.i32(t.isConstExpression(i)?1:0)}d.set(h.isConstant,mE);function dE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.isManaged?1:0)):t.unreachable()}d.set(h.isManaged,dE);function EE(r){var e=r.compiler,t=e.module,i=Re(r);return e.currentType=u.bool,i?be(r,t.i32(i.kind==20?1:0)):t.unreachable()}d.set(h.isVoid,EE);function yE(r){var e=r.compiler,t=e.module,i=Re(r);if(e.currentType=u.i32,!i)return t.unreachable();var n=i.signatureReference;return n?be(r,t.i32(n.parameterTypes.length)):(e.error(2757,r.reportNode.range,i.toString()),t.unreachable())}d.set(h.lengthof,yE);function gE(r){var e=r.compiler,t=e.module;if(e.currentType=e.options.usizeType,K(r)|W(r,0))return t.unreachable();var i=r.typeArguments[0],n=i.byteSize;return n?Gs(e,i64_new(n),r.contextualType):(e.error(203,r.reportNode.typeArgumentsRange,"sizeof",i.toString()),t.unreachable())}d.set(h.sizeof,gE);function TE(r){var e=r.compiler,t=e.module;if(e.currentType=e.options.usizeType,K(r)|W(r,0))return t.unreachable();var i=r.typeArguments[0],n=i.byteSize;return ht(n)?Gs(e,i64_new(ctz(n)),r.contextualType):(e.error(203,r.reportNode.typeArgumentsRange,"alignof",i.toString()),t.unreachable())}d.set(h.alignof,TE);function bE(r){var e=r.compiler,t=e.module;if(e.currentType=e.options.usizeType,K(r)|Ee(r,0,1))return t.unreachable();var i=r.operands,n=r.contextualType,s=r.typeArguments[0],a=s.getClassOrWrapper(e.program);if(!a)return e.error(203,r.reportNode.typeArgumentsRange,"offsetof",s.toString()),e.options.isWasm64?n.isIntegerValue&&n.size<=32&&(e.currentType=u.u32):n.isIntegerValue&&n.size==64&&(e.currentType=u.u64),t.unreachable();if(i.length){let o=i[0];if(!o.isLiteralKind(2))return e.error(1141,i[0].range),t.unreachable();let l=o.value,p=a.members;if(p&&p.has(l)){let c=assert(p.get(l));if(c.kind==11)return Gs(e,i64_new(c.memoryOffset),n)}return e.error(2460,o.range,a.internalName,l),t.unreachable()}return Gs(e,i64_new(a.nextMemoryOffset),n)}d.set(h.offsetof,bE);function IE(r){var e=r.compiler,t=e.module,i=Re(r);if(!i)return e.currentType=e.program.stringInstance.type,t.unreachable();var n;if(i.isInternalReference){let s=i.getClass();s?n=s.name:(assert(i.getSignature()),n="Function")}else n=i.toString();return be(r,e.ensureStaticString(n))}d.set(h.nameof,IE);function vE(r){var e=r.compiler,t=e.module,i=Re(r);if(e.currentType=u.u32,!i)return t.unreachable();let n=i.getSignature();if(n)return be(r,t.i32(n.id));let s=i.getClassOrWrapper(e.program);return s&&!s.hasDecorator(16)?be(r,t.i32(s.id)):(e.error(203,r.reportNode.typeArgumentsRange,"idof",i.toString()),t.unreachable())}d.set(h.idof,vE);function eu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.typeArguments,n=i?e.compileExpression(r.operands[0],i[0],5):e.compileExpression(r.operands[0],u.i32,4),s=e.currentType;if(s.isValue)switch(s.kind){case 10:case 0:case 5:case 1:case 6:case 2:case 7:return t.unary(0,n);case 9:case 4:return t.unary(e.options.isWasm64?1:0,n);case 3:case 8:return t.unary(1,n)}return e.error(203,r.reportNode.typeArgumentsRange,"clz",s.toString()),t.unreachable()}d.set(h.clz,eu);function tu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],5):e.compileExpression(i[0],u.i32,4),a=e.currentType;if(a.isValue)switch(a.kind){case 10:case 0:case 5:case 1:case 6:case 2:case 7:return t.unary(2,s);case 9:case 4:return t.unary(e.options.isWasm64?3:2,s);case 3:case 8:return t.unary(3,s)}return e.error(203,r.reportNode.typeArgumentsRange,"ctz",a.toString()),t.unreachable()}d.set(h.ctz,tu);function ru(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],5):e.compileExpression(i[0],u.i32,4),a=e.currentType;if(a.isValue)switch(e.currentType.kind){case 10:return s;case 0:case 5:case 1:case 6:case 2:case 7:return t.unary(4,s);case 3:case 8:return t.unary(5,s);case 4:case 9:return t.unary(e.options.isWasm64?5:4,s)}return e.error(203,r.reportNode.typeArgumentsRange,"popcnt",a.toString()),t.unreachable()}d.set(h.popcnt,ru);function iu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],5):e.compileExpression(i[0],u.i32,4),a=e.currentType;if(a.isValue){let o=e.compileExpression(i[1],a,1);switch(a.kind){case 10:return s;case 0:case 1:case 5:case 6:{let l=e.currentFlow,p=l.getTempLocal(a,st(o));l.setLocalFlag(p.index,2);let c=l.getTempLocal(a);l.setLocalFlag(c.index,2);let _=t.binary(8,t.binary(10,t.local_tee(p.index,s,!1),t.binary(7,t.local_tee(c.index,o,!1),t.i32(a.size-1))),t.binary(12,t.local_get(p.index,C.I32),t.binary(7,t.binary(1,t.i32(0),t.local_get(c.index,C.I32)),t.i32(a.size-1))));return l.freeTempLocal(c),l.freeTempLocal(p),_}case 2:case 7:return t.binary(13,s,o);case 9:case 4:return t.binary(e.options.isWasm64?38:13,s,o);case 3:case 8:return t.binary(38,s,o)}}return e.error(203,r.reportNode.typeArgumentsRange,"rotl",a.toString()),t.unreachable()}d.set(h.rotl,iu);function nu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],5):e.compileExpression(i[0],u.i32,4),a=e.currentType;if(a.isValue){let o=e.compileExpression(i[1],a,1);switch(a.kind){case 10:return s;case 0:case 1:case 5:case 6:{let l=e.currentFlow,p=l.getTempLocal(a,st(o));l.setLocalFlag(p.index,2);let c=l.getTempLocal(a);l.setLocalFlag(c.index,2);let _=t.binary(8,t.binary(12,t.local_tee(p.index,s,!1),t.binary(7,t.local_tee(c.index,o,!1),t.i32(a.size-1))),t.binary(10,t.local_get(p.index,C.I32),t.binary(7,t.binary(1,t.i32(0),t.local_get(c.index,C.I32)),t.i32(a.size-1))));return l.freeTempLocal(c),l.freeTempLocal(p),_}case 2:case 7:return t.binary(14,s,o);case 9:case 4:return t.binary(e.options.isWasm64?39:14,s,o);case 3:case 8:return t.binary(39,s,o)}}return e.error(203,r.reportNode.typeArgumentsRange,"rotr",a.toString()),t.unreachable()}d.set(h.rotr,nu);function su(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],5):e.compileExpression(i[0],u.auto,4),a=e.currentType;if(a.isValue)switch(a.kind){case 0:case 1:case 2:{let o=e.currentFlow,l=o.getTempLocal(u.i32),p=o.getTempLocal(u.i32),c=t.binary(9,t.binary(0,t.local_tee(p.index,t.binary(11,t.local_tee(l.index,s,!1),t.i32(31)),!1),t.local_get(l.index,C.I32)),t.local_get(p.index,C.I32));return o.freeTempLocal(p),o.freeTempLocal(l),c}case 4:{let o=e.options,l=e.currentFlow,p=o.isWasm64,c=l.getTempLocal(o.usizeType),_=l.getTempLocal(o.usizeType),f=t.binary(p?34:9,t.binary(p?25:0,t.local_tee(_.index,t.binary(p?36:11,t.local_tee(c.index,s,!1),p?t.i64(63):t.i32(31)),!1),t.local_get(c.index,o.sizeTypeRef)),t.local_get(_.index,o.sizeTypeRef));return l.freeTempLocal(_),l.freeTempLocal(c),f}case 3:{let o=e.currentFlow,l=o.getTempLocal(u.i64),p=o.getTempLocal(u.i64),c=t.binary(34,t.binary(25,t.local_tee(p.index,t.binary(36,t.local_tee(l.index,s,!1),t.i64(63)),!1),t.local_get(l.index,C.I64)),t.local_get(p.index,C.I64));return o.freeTempLocal(p),o.freeTempLocal(l),c}case 9:case 5:case 6:case 7:case 8:case 10:return s;case 11:return t.unary(8,s);case 12:return t.unary(9,s)}return e.error(203,r.reportNode.typeArgumentsRange,"abs",a.toString()),t.unreachable()}d.set(h.abs,su);function au(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],5):e.compileExpression(i[0],u.auto,4),o=e.currentType;if(o.isValue){let l;!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o,4),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,5))):l=e.compileExpression(i[1],o,5);let p=-1;switch(o.kind){case 0:case 1:case 2:{p=21;break}case 5:case 6:case 7:case 10:{p=22;break}case 3:{p=46;break}case 8:{p=47;break}case 4:{p=e.options.isWasm64?46:21;break}case 9:{p=e.options.isWasm64?47:22;break}case 11:return t.binary(56,a,l);case 12:return t.binary(69,a,l)}if(p!=-1){let c=e.currentFlow,_=o.toRef(),f=c.getTempLocal(o,st(l));c.setLocalFlag(f.index,2);let E=c.getTempLocal(o);c.setLocalFlag(E.index,2);let g=t.select(t.local_tee(f.index,a,!1),t.local_tee(E.index,l,!1),t.binary(p,t.local_get(f.index,_),t.local_get(E.index,_)),_);return c.freeTempLocal(E),c.freeTempLocal(f),g}}return e.error(203,r.reportNode.typeArgumentsRange,"max",o.toString()),t.unreachable()}d.set(h.max,au);function ou(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],5):e.compileExpression(i[0],u.auto,4),o=e.currentType;if(o.isValue){let l;!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o,4),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,5))):l=e.compileExpression(i[1],o,5);let p=-1;switch(o.kind){case 0:case 1:case 2:{p=17;break}case 5:case 6:case 7:case 10:{p=18;break}case 3:{p=42;break}case 8:{p=43;break}case 4:{p=e.options.isWasm64?42:17;break}case 9:{p=e.options.isWasm64?43:18;break}case 11:return t.binary(55,a,l);case 12:return t.binary(68,a,l)}if(p!=-1){let c=e.currentFlow,_=o.toRef(),f=c.getTempLocal(o,st(l));c.setLocalFlag(f.index,2);let E=c.getTempLocal(o);c.setLocalFlag(E.index,2);let g=t.select(t.local_tee(f.index,a,!1),t.local_tee(E.index,l,!1),t.binary(p,t.local_get(f.index,_),t.local_get(E.index,_)),_);return c.freeTempLocal(E),c.freeTempLocal(f),g}}return e.error(203,r.reportNode.typeArgumentsRange,"min",o.toString()),t.unreachable()}d.set(h.min,ou);function lu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.auto,0),a=e.currentType;if(a.isValue)switch(a.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:return s;case 11:return t.unary(10,s);case 12:return t.unary(11,s)}return e.error(203,r.reportNode.typeArgumentsRange,"ceil",a.toString()),t.unreachable()}d.set(h.ceil,lu);function uu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.auto,0),a=e.currentType;if(a.isValue)switch(a.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:return s;case 11:return t.unary(12,s);case 12:return t.unary(13,s)}return e.error(203,r.reportNode.typeArgumentsRange,"floor",a.toString()),t.unreachable()}d.set(h.floor,uu);function pu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.f64,0),a=e.currentType;if(a.isValue){let o=e.compileExpression(i[1],a,1);switch(a.kind){case 11:return t.binary(54,s,o);case 12:return t.binary(67,s,o)}}return e.error(203,r.reportNode.typeArgumentsRange,"copysign",a.toString()),t.unreachable()}d.set(h.copysign,pu);function cu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.auto,0),a=e.currentType;if(a.isValue)switch(a.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:return s;case 11:return t.unary(16,s);case 12:return t.unary(17,s)}return e.error(203,r.reportNode.typeArgumentsRange,"nearest",a.toString()),t.unreachable()}d.set(h.nearest,cu);function cn(r){var e=r.compiler,t=e.module;if(K(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0];if(s.isValue)switch(s.kind){case 2:case 7:{let a=e.compileExpression(i[0],u.f32,1);return e.currentType=s,t.unary(33,a)}case 3:case 8:{let a=e.compileExpression(i[0],u.f64,1);return e.currentType=s,t.unary(34,a)}case 4:case 9:{let a=e.compileExpression(i[0],e.options.isWasm64?u.f64:u.f32,1);return e.currentType=s,t.unary(e.options.isWasm64?34:33,a)}case 11:{let a=e.compileExpression(i[0],u.i32,1);return e.currentType=u.f32,t.unary(45,a)}case 12:{let a=e.compileExpression(i[0],u.i64,1);return e.currentType=u.f64,t.unary(46,a)}}return e.error(203,r.reportNode.typeArgumentsRange,"reinterpret",s.toString()),t.unreachable()}d.set(h.reinterpret,cn);function _u(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.f64,0),a=e.currentType;if(a.isValue)switch(a.kind){case 11:return t.unary(18,s);case 12:return t.unary(19,s)}return e.error(203,r.reportNode.typeArgumentsRange,"sqrt",a.toString()),t.unreachable()}d.set(h.sqrt,_u);function fu(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.auto,0),a=e.currentType;if(a.isValue)switch(a.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:return s;case 11:return t.unary(14,s);case 12:return t.unary(15,s)}return e.error(203,r.reportNode.typeArgumentsRange,"trunc",a.toString()),t.unreachable()}d.set(h.trunc,fu);function xE(r){var e=r.compiler,t=e.module;if(ae(r)|W(r,1))return e.currentType=u.bool,t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.auto),a=e.currentType;if(e.currentType=u.bool,a.isValue)switch(a.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return t.maybeDropCondition(s,t.i32(0));case 11:{if(te(s)==8)return t.binary(58,s,t.local_get(ot(s),C.F32));let o=e.currentFlow,l=o.getTempLocal(u.f32),p=t.binary(58,t.local_tee(l.index,s,!1),t.local_get(l.index,C.F32));return o.freeTempLocal(l),p}case 12:{if(te(s)==8)return t.binary(71,s,t.local_get(ot(s),C.F64));let o=e.currentFlow,l=o.getTempLocal(u.f64),p=t.binary(71,t.local_tee(l.index,s,!1),t.local_get(l.index,C.F64));return o.freeTempLocal(l),p}}return e.error(203,r.reportNode.typeArgumentsRange,"isNaN",a.toString()),t.unreachable()}d.set(h.isNaN,xE);function SE(r){var e=r.compiler,t=e.module;if(ae(r)|W(r,1))return e.currentType=u.bool,t.unreachable();var i=r.operands,n=r.typeArguments,s=n?e.compileExpression(i[0],n[0],1):e.compileExpression(i[0],u.auto),a=e.currentType;if(e.currentType=u.bool,a.isValue)switch(a.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return t.maybeDropCondition(s,t.i32(1));case 11:{if(te(s)==8)return t.binary(57,t.binary(51,s,t.local_get(ot(s),C.F32)),t.f32(0));let o=e.currentFlow,l=o.getTempLocal(u.f32),p=t.binary(57,t.binary(51,t.local_tee(l.index,s,!1),t.local_get(l.index,C.F32)),t.f32(0));return o.freeTempLocal(l),p}case 12:{if(te(s)==8)return t.binary(70,t.binary(64,s,t.local_get(ot(s),C.F64)),t.f64(0));let o=e.currentFlow,l=o.getTempLocal(u.f64),p=t.binary(70,t.binary(64,t.local_tee(l.index,s,!1),t.local_get(l.index,C.F64)),t.f64(0));return o.freeTempLocal(l),p}}return e.error(203,r.reportNode.typeArgumentsRange,"isFinite",a.toString()),t.unreachable()}d.set(h.isFinite,SE);function Ie(r){var e=r.compiler,t=e.module;if(K(r,!0)|Ee(r,1,3))return t.unreachable();var i=r.operands,n=r.typeArguments,s=r.contextualType,a=n[0],o=s!=u.auto&&a.isIntegerValue&&s.isIntegerValue&&s.size>a.size?s:a,l=e.compileExpression(i[0],e.options.usizeType,1),p=i.length,c=0,_=a.byteSize;return p>=2&&(c=Ke(i[1],e),c<0||p==3&&(_=vt(i[2],_,e),_<0))?(e.currentType=o,t.unreachable()):(e.currentType=o,t.load(a.byteSize,a.isSignedIntegerValue,l,o.toRef(),c,_))}d.set(h.load,Ie);function et(r){var e=r.compiler,t=e.module;if(e.currentType=u.void,K(r)|Ee(r,2,4))return t.unreachable();var i=r.operands,n=i.length,s=r.typeArguments,a=r.contextualType,o=s[0],l=e.compileExpression(i[0],e.options.usizeType,1),p=r.contextIsExact?e.compileExpression(i[1],a,1):e.compileExpression(i[1],o,o.isIntegerValue?0:1),c=e.currentType;o.isIntegerValue&&(!c.isIntegerValue||c.size=3){if(_=Ke(i[2],e),_<0)return e.currentType=u.void,t.unreachable();if(n==4&&(f=vt(i[3],f,e),f<0))return e.currentType=u.void,t.unreachable()}return e.currentType=u.void,t.store(o.byteSize,l,p,c.toRef(),_,f)}d.set(h.store,et);function _n(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],1):e.compileExpression(i[0],u.auto),o=e.currentType;if(o.isValue){let l;if(!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,1))):l=e.compileExpression(i[1],o,1),o.isNumericValue)return e.makeAdd(a,l,o)}return e.error(203,r.reportNode.typeArgumentsRange,"add",o.toString()),t.unreachable()}d.set(h.add,_n);function fn(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],1):e.compileExpression(i[0],u.auto),o=e.currentType;if(o.isValue){let l;if(!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,1))):l=e.compileExpression(i[1],o,1),o.isNumericValue)return e.makeSub(a,l,o)}return e.error(203,r.reportNode.typeArgumentsRange,"sub",o.toString()),t.unreachable()}d.set(h.sub,fn);function hn(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],1):e.compileExpression(i[0],u.auto),o=e.currentType;if(o.isValue){let l;if(!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,1))):l=e.compileExpression(i[1],o,1),o.isNumericValue)return e.makeMul(a,l,o)}return e.error(203,r.reportNode.typeArgumentsRange,"mul",o.toString()),t.unreachable()}d.set(h.mul,hn);function cr(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],1):e.compileExpression(i[0],u.auto),o=e.currentType;if(o.isValue){let l;if(!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,1))):l=e.compileExpression(i[1],o,1),o.isNumericValue)return e.makeDiv(a,l,o)}return e.error(203,r.reportNode.typeArgumentsRange,"div",o.toString()),t.unreachable()}d.set(h.div,cr);function mn(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],1):e.compileExpression(i[0],u.auto),o=e.currentType;if(o.isValue){let l;if(!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,1))):l=e.compileExpression(i[1],o,1),o.isNumericValue)return e.currentType=u.i32,e.makeEq(a,l,o,r.reportNode)}return e.error(203,r.reportNode.typeArgumentsRange,"eq",o.toString()),t.unreachable()}d.set(h.eq,mn);function dn(r){var e=r.compiler,t=e.module;if(ae(r,!0)|W(r,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=i[0],a=n?e.compileExpression(s,n[0],1):e.compileExpression(i[0],u.auto),o=e.currentType;if(o.isValue){let l;if(!n&&s.isNumericLiteral?(l=e.compileExpression(i[1],o),e.currentType!=o&&(a=e.compileExpression(s,o=e.currentType,1))):l=e.compileExpression(i[1],o,1),o.isNumericValue)return e.currentType=u.i32,e.makeNe(a,l,o,r.reportNode)}return e.error(203,r.reportNode.typeArgumentsRange,"ne",o.toString()),t.unreachable()}d.set(h.ne,dn);function Wt(r){var e=r.compiler,t=e.module;if(X(r,32)|K(r,!0)|Ee(r,1,2))return t.unreachable();var i=r.operands,n=r.typeArguments,s=r.contextualType,a=n[0],o=a.isIntegerValue&&s.isIntegerValue&&s.size>a.size?s:a;if(!a.isIntegerValue)return e.error(203,r.reportNode.typeArgumentsRange,"atomic.load",a.toString()),e.currentType=o,t.unreachable();var l=e.compileExpression(i[0],e.options.usizeType,1),p=i.length==2?Ke(i[1],e):0;return p<0?(e.currentType=o,t.unreachable()):(e.currentType=o,t.atomic_load(a.byteSize,l,o.toRef(),p))}d.set(h.atomic_load,Wt);function Yt(r){var e=r.compiler,t=e.module;if(X(r,32)|K(r)|Ee(r,2,3))return t.unreachable();var i=r.operands,n=r.typeArguments,s=r.contextualType,a=n[0];if(!a.isIntegerValue)return e.error(203,r.reportNode.typeArgumentsRange,"atomic.store",a.toString()),e.currentType=u.void,t.unreachable();var o=e.compileExpression(i[0],e.options.usizeType,1),l=r.contextIsExact?e.compileExpression(i[1],s,1):e.compileExpression(i[1],a,a.isIntegerValue?0:1),p=e.currentType;a.isIntegerValue&&(!p.isIntegerValue||p.size0){let l=i[0];if(!l.isValue)return e.error(203,r.reportNode.typeArgumentsRange,"memory.data",l.toString()),e.currentType=a,t.unreachable();let p=n[0];if(p.kind!=16||p.literalKind!=5)return e.error(227,n[0].range),e.currentType=a,t.unreachable();let c=p.elementExpressions,_=c.length,f=new Array(_),E=!0;for(let S=0;S<_;++S){let v=c[S];if(v.kind!=19){let x=e.compileExpression(v,l,1),L=t.runExpression(x,1);L?x=L:E=!1,f[S]=x}else f[S]=e.makeZero(l,v)}if(!E)return e.error(220,p.range),e.currentType=a,t.unreachable();let g=l.byteSize;if(s==2&&(g=vt(n[1],g,e),g<0))return e.currentType=a,t.unreachable();let b=new Uint8Array(_*l.byteSize);assert(e.writeStaticBuffer(b,0,l,f)==b.byteLength),o=e.addAlignedMemorySegment(b,g).offset}else{let l=e.compileExpression(n[0],u.i32,1),p=t.runExpression(l,1);if(!p)return e.error(220,n[0].range),e.currentType=a,t.unreachable();let c=ie(p);if(c<1)return e.error(222,n[0].range,"1",i32.MAX_VALUE.toString()),e.currentType=a,t.unreachable();let _=16;if(s==2&&(_=vt(n[1],_,e),_<0))return e.currentType=a,t.unreachable();o=e.addAlignedMemorySegment(new Uint8Array(c),_).offset}return e.currentType=a,a==u.usize32?(assert(!i64_high(o)),t.i32(i64_low(o))):t.i64(i64_low(o),i64_high(o))}d.set(h.memory_data,OE);function wE(r){var e=r.compiler,t=e.module;if(T(r)|W(r,1))return t.unreachable();var i=r.operands,n=e.compileExpression(i[0],u.i32,1);return e.currentType=u.i31ref,t.i31_new(n)}d.set(h.i31_new,wE);function ME(r){var e=r.compiler,t=e.module;if(T(r)|W(r,1))return t.unreachable();var i=r.operands,n=e.compileExpression(i[0],u.i31ref,1);return r.contextualType.is(2)?(e.currentType=u.u32,t.i31_get(n,!1)):(e.currentType=u.i32,t.i31_get(n,!0))}d.set(h.i31_get,ME);function UE(r){var e=r.compiler,t=e.module;if(K(r,!0)|W(r,1))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.auto),o=e.currentType;return e.currentType=s,o.isChangeableTo(s)?a:(e.error(202,r.reportNode.range,o.toString(),s.toString()),t.unreachable())}d.set(h.changetype,UE);function DE(r){var e=r.compiler,t=e.module,i=r.typeArguments;if(ae(r,!0)|Ee(r,1,2))return i&&(assert(i.length),e.currentType=i[0].nonNullableType),t.unreachable();var n=r.operands,s=r.contextualType,a=i?e.compileExpression(n[0],i[0],5):e.compileExpression(n[0],u.bool,4),o=e.currentType;if(e.currentType=o.nonNullableType,e.options.noAssert)return a;var l=t.runExpression(a,0);if(l)switch(oe(l)){case C.I32:{if(ie(l))return a;break}case C.I64:{if(Be(l)|$e(l))return a;break}case C.F32:{if(Ye(l))return a;break}case C.F64:{if(He(l))return a;break}}var p=e.makeAbort(n.length==2?n[1]:null,r.reportNode);if(e.currentType=o.nonNullableType,s==u.void)switch(e.currentType=u.void,o.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:return t.if(t.unary(20,a),p);case 3:case 8:return t.if(t.unary(21,a),p);case 4:case 9:return t.if(t.unary(e.options.isWasm64?21:20,a),p);case 11:return t.if(t.binary(57,a,t.f32(0)),p);case 12:return t.if(t.binary(70,a,t.f64(0)),p);case 14:case 15:case 16:case 17:case 19:case 18:return t.if(t.ref_is(0,a),p)}else{e.currentType=o.nonNullableType;let c=e.currentFlow;switch(e.currentType.kind){case 0:case 1:case 2:case 5:case 6:case 7:case 10:{let _=c.getTempLocal(o);c.setLocalFlag(_.index,2);let f=t.if(t.local_tee(_.index,a,!1),t.local_get(_.index,C.I32),p);return c.freeTempLocal(_),f}case 3:case 8:{let _=c.getTempLocal(u.i64),f=t.if(t.unary(21,t.local_tee(_.index,a,!1)),p,t.local_get(_.index,C.I64));return c.freeTempLocal(_),f}case 4:case 9:{let _=c.getTempLocal(e.options.usizeType),f=t.if(t.unary(e.options.isWasm64?21:20,t.local_tee(_.index,a,o.isManaged)),p,t.local_get(_.index,e.options.sizeTypeRef));return c.freeTempLocal(_),f}case 11:{let _=c.getTempLocal(u.f32),f=t.if(t.binary(57,t.local_tee(_.index,a,!1),t.f32(0)),p,t.local_get(_.index,C.F32));return c.freeTempLocal(_),f}case 12:{let _=c.getTempLocal(u.f64),f=t.if(t.binary(70,t.local_tee(_.index,a,!1),t.f64(0)),p,t.local_get(_.index,C.F64));return c.freeTempLocal(_),f}case 14:case 15:case 16:case 17:case 19:case 18:{let _=c.getTempLocal(o),f=t.if(t.ref_is(0,t.local_tee(_.index,a,!1)),p,t.local_get(_.index,o.toRef()));return c.freeTempLocal(_),f}}}return e.error(203,r.reportNode.typeArgumentsRange,"assert",e.currentType.toString()),p}d.set(h.assert,DE);function BE(r){var e=r.compiler,t=e.module;if(T(r)|W(r,1))return t.unreachable();var i=e.currentFlow,n=i.is(32768);i.set(32768);var s=e.compileExpression(r.operands[0],r.contextualType);return n||i.unset(32768),s}d.set(h.unchecked,BE);function GE(r){var e=r.compiler,t=e.module;if(ae(r,!0)|Ee(r,1,i32.MAX_VALUE))return t.unreachable();var i=r.operands,n=r.typeArguments,s;n?(assert(n.length),s=n[0]):s=r.contextualType;var a=e.compileExpression(i[0],u.u32,1),o=i.length-1,l=new Array(o),p=new Array(o);for(let c=0;cc)&&(e.error(222,i[1].range,"Lane index","0",c.toString()),l=0),s.kind){case 0:return t.simd_extract(0,a,l);case 5:return t.simd_extract(1,a,l);case 1:return t.simd_extract(2,a,l);case 6:return t.simd_extract(3,a,l);case 2:case 7:return t.simd_extract(4,a,l);case 3:case 8:return t.simd_extract(5,a,l);case 4:case 9:return t.simd_extract(e.options.isWasm64?5:4,a,l);case 11:return t.simd_extract(6,a,l);case 12:return t.simd_extract(7,a,l)}}return e.error(203,r.reportNode.typeArgumentsRange,"v128.extract_lane",s.toString()),t.unreachable()}d.set(h.v128_extract_lane,xt);function fr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,3))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.u8,1),l=e.compileExpression(i[2],s,1);e.currentType=u.v128;var p=0,c=t.runExpression(o,1);if(c?p=ie(c):e.error(220,i[1].range),s.isValue){let _=16/assert(s.byteSize)-1;switch((p<0||p>_)&&(e.error(222,i[1].range,"Lane index","0",_.toString()),p=0),s.kind){case 0:case 5:return t.simd_replace(0,a,p,l);case 1:case 6:return t.simd_replace(1,a,p,l);case 2:case 7:return t.simd_replace(2,a,p,l);case 3:case 8:return t.simd_replace(3,a,p,l);case 4:case 9:return t.simd_replace(e.options.isWasm64?3:2,a,p,l);case 11:return t.simd_replace(4,a,p,l);case 12:return t.simd_replace(5,a,p,l)}}return e.error(203,r.reportNode.typeArgumentsRange,"v128.replace_lane",s.toString()),t.unreachable()}d.set(h.v128_replace_lane,fr);function Wc(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0];if(s.isValue){let a=s.byteSize,o=16/a;if(assert(Number.isInteger(o)&&ht(o)),W(r,2+o))return e.currentType=u.v128,t.unreachable();let l=e.compileExpression(i[0],u.v128,1),p=e.compileExpression(i[1],u.v128,1);switch(s.kind){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 11:case 12:{let c=new Uint8Array(16),_=(o<<1)-1;for(let f=0;f_)&&(e.error(222,E.range,"Lane index","0",_.toString()),S=0)):e.error(220,E.range),a){case 1:{pe(S,c,f);break}case 2:{let v=f<<1,x=S<<1;pe(x,c,v),pe(x+1,c,v+1);break}case 4:{let v=f<<2,x=S<<2;pe(x,c,v),pe(x+1,c,v+1),pe(x+2,c,v+2),pe(x+3,c,v+3);break}case 8:{let v=f<<3,x=S<<3;pe(x,c,v),pe(x+1,c,v+1),pe(x+2,c,v+2),pe(x+3,c,v+3),pe(x+4,c,v+4),pe(x+5,c,v+5),pe(x+6,c,v+6),pe(x+7,c,v+7);break}default:assert(!1)}}return e.currentType=u.v128,t.simd_shuffle(l,p,c)}}}return e.error(203,r.reportNode.typeArgumentsRange,"v128.shuffle",s.toString()),e.currentType=u.v128,t.unreachable()}d.set(h.v128_shuffle,Wc);function Yc(r){var e=r.compiler,t=e.module;if(X(r,16)|T(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=e.compileExpression(i[0],u.v128,1),s=e.compileExpression(i[1],u.v128,1);return t.binary(195,n,s)}d.set(h.v128_swizzle,Yc);function En(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r,!0)|Ee(r,1,3))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],e.options.usizeType,1),o=i.length,l=0,p=s.byteSize;if(o>=2){if(l=Ke(i[1],e),l<0)return e.currentType=u.v128,t.unreachable();if(o==3&&(p=vt(i[2],p,e),p<0))return e.currentType=u.v128,t.unreachable()}if(e.currentType=u.v128,s.isValue)switch(s.kind){case 0:case 5:return t.simd_load(0,a,l,p);case 1:case 6:return t.simd_load(1,a,l,p);case 2:case 7:case 11:return t.simd_load(2,a,l,p);case 4:case 9:if(!e.options.isWasm64)return t.simd_load(2,a,l,p);case 3:case 8:case 12:return t.simd_load(3,a,l,p)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.load_splat",s.toString()),t.unreachable()}d.set(h.v128_load_splat,En);function hr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r,!0)|Ee(r,1,3))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],e.options.usizeType,1),o=i.length,l=0,p=s.byteSize;if(o>=2){if(l=Ke(i[1],e),l<0)return e.currentType=u.v128,t.unreachable();if(o==3&&(p=vt(i[2],p,e),p<0))return e.currentType=u.v128,t.unreachable()}if(e.currentType=u.v128,s.isValue)switch(s.kind){case 0:return t.simd_load(4,a,l,p);case 5:return t.simd_load(5,a,l,p);case 1:return t.simd_load(6,a,l,p);case 6:return t.simd_load(7,a,l,p);case 4:if(e.options.isWasm64)break;case 2:return t.simd_load(8,a,l,p);case 9:if(e.options.isWasm64)break;case 7:return t.simd_load(9,a,l,p)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.load_ext",s.toString()),t.unreachable()}d.set(h.v128_load_ext,hr);function du(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r,!0)|Ee(r,1,3))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],e.options.usizeType,1),o=i.length,l=0,p=s.byteSize;if(o>=2){if(l=Ke(i[1],e),l<0)return e.currentType=u.v128,t.unreachable();if(o==3&&(p=vt(i[2],p,e),p<0))return e.currentType=u.v128,t.unreachable()}if(e.currentType=u.v128,s.isValue)switch(s.kind){case 2:case 7:case 11:return t.simd_load(10,a,l,p);case 3:case 8:case 12:return t.simd_load(11,a,l,p);case 4:case 9:return t.simd_load(e.options.isWasm64?11:10,a,l,p)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.load_zero",s.toString()),t.unreachable()}d.set(h.v128_load_zero,du);function yn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r,!0)|Ee(r,3,5))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],e.options.usizeType,1),o=e.compileExpression(i[1],u.v128,1),l=e.compileExpression(i[2],u.u8,1),p=0,c=t.runExpression(l,1);c?p=ie(c):e.error(220,i[2].range);var _=i.length,f=0,E=s.byteSize;if(_>=4){if(f=Ke(i[3],e),f<0)return e.currentType=u.v128,t.unreachable();if(_==5&&(E=vt(i[4],E,e),E<0))return e.currentType=u.v128,t.unreachable()}if(e.currentType=u.v128,s.isValue){let g=16/assert(s.byteSize)-1;switch((p<0||p>g)&&(e.error(222,i[1].range,"Lane index","0",g.toString()),p=0),s.kind){case 0:case 5:return t.simd_loadstorelane(0,a,f,E,p,o);case 1:case 6:return t.simd_loadstorelane(1,a,f,E,p,o);case 2:case 7:case 11:return t.simd_loadstorelane(2,a,f,E,p,o);case 3:case 8:case 12:return t.simd_loadstorelane(3,a,f,E,p,o);case 4:case 9:return t.simd_loadstorelane(e.options.isWasm64?3:2,a,f,E,p,o)}}return e.error(203,r.reportNode.typeArgumentsRange,"v128.load_lane",s.toString()),t.unreachable()}d.set(h.v128_load_lane,yn);function gn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r,!0)|Ee(r,3,5))return t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],e.options.usizeType,1),o=e.compileExpression(i[1],u.v128,1),l=e.compileExpression(i[2],u.u8,1),p=0,c=t.runExpression(l,1);c?p=ie(c):e.error(220,i[2].range);var _=i.length,f=0,E=s.byteSize;if(_>=4){if(f=Ke(i[3],e),f<0)return e.currentType=u.v128,t.unreachable();if(_==5&&(E=vt(i[4],E,e),E<0))return e.currentType=u.v128,t.unreachable()}if(e.currentType=u.v128,s.isValue){let g=16/assert(s.byteSize)-1;switch((p<0||p>g)&&(e.error(222,i[1].range,"Lane index","0",g.toString()),p=0),s.kind){case 0:case 5:return t.simd_loadstorelane(4,a,f,E,p,o);case 1:case 6:return t.simd_loadstorelane(5,a,f,E,p,o);case 2:case 7:case 11:return t.simd_loadstorelane(6,a,f,E,p,o);case 3:case 8:case 12:return t.simd_loadstorelane(7,a,f,E,p,o);case 4:case 9:return t.simd_loadstorelane(e.options.isWasm64?7:6,a,f,E,p,o)}}return e.error(203,r.reportNode.typeArgumentsRange,"v128.store_lane",s.toString()),t.unreachable()}d.set(h.v128_store_lane,gn);function mr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:case 5:return t.binary(128,a,o);case 1:case 6:return t.binary(139,a,o);case 2:case 7:return t.binary(156,a,o);case 3:case 8:return t.binary(168,a,o);case 4:case 9:return t.binary(e.options.isWasm64?168:156,a,o);case 11:return t.binary(175,a,o);case 12:return t.binary(183,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.add",s.toString()),t.unreachable()}d.set(h.v128_add,mr);function dr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:case 5:return t.binary(131,a,o);case 1:case 6:return t.binary(142,a,o);case 2:case 7:return t.binary(157,a,o);case 3:case 8:return t.binary(169,a,o);case 4:case 9:return t.binary(e.options.isWasm64?169:157,a,o);case 11:return t.binary(176,a,o);case 12:return t.binary(184,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.sub",s.toString()),t.unreachable()}d.set(h.v128_sub,dr);function ci(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 1:case 6:return t.binary(145,a,o);case 2:case 7:return t.binary(158,a,o);case 3:case 8:return t.binary(170,a,o);case 4:case 9:return t.binary(e.options.isWasm64?170:158,a,o);case 11:return t.binary(177,a,o);case 12:return t.binary(185,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.mul",s.toString()),t.unreachable()}d.set(h.v128_mul,ci);function Eu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.binary(178,a,o);case 12:return t.binary(186,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.div",s.toString()),t.unreachable()}d.set(h.v128_div,Eu);function Tn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(129,a,o);case 5:return t.binary(130,a,o);case 1:return t.binary(140,a,o);case 6:return t.binary(141,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.add_sat",s.toString()),t.unreachable()}d.set(h.v128_add_sat,Tn);function bn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(132,a,o);case 5:return t.binary(133,a,o);case 1:return t.binary(143,a,o);case 6:return t.binary(144,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.sub_sat",s.toString()),t.unreachable()}d.set(h.v128_sub_sat,bn);function St(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(134,a,o);case 5:return t.binary(135,a,o);case 1:return t.binary(146,a,o);case 6:return t.binary(147,a,o);case 4:if(e.options.isWasm64)break;case 2:return t.binary(159,a,o);case 9:if(e.options.isWasm64)break;case 7:return t.binary(160,a,o);case 11:return t.binary(179,a,o);case 12:return t.binary(187,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.min",s.toString()),t.unreachable()}d.set(h.v128_min,St);function Rt(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(136,a,o);case 5:return t.binary(137,a,o);case 1:return t.binary(148,a,o);case 6:return t.binary(149,a,o);case 4:if(e.options.isWasm64)break;case 2:return t.binary(161,a,o);case 9:if(e.options.isWasm64)break;case 7:return t.binary(162,a,o);case 11:return t.binary(180,a,o);case 12:return t.binary(188,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.max",s.toString()),t.unreachable()}d.set(h.v128_max,Rt);function yu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.binary(181,a,o);case 12:return t.binary(189,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.pmin",s.toString()),t.unreachable()}d.set(h.v128_pmin,yu);function gu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.binary(182,a,o);case 12:return t.binary(190,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.pmax",s.toString()),t.unreachable()}d.set(h.v128_pmax,gu);function Hc(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 1:return t.binary(163,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.dot",s.toString()),t.unreachable()}d.set(h.v128_dot,Hc);function Tu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 5:return t.binary(138,a,o);case 6:return t.binary(150,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.avgr",s.toString()),t.unreachable()}d.set(h.v128_avgr,Tu);function Er(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:case 5:return t.binary(76,a,o);case 1:case 6:return t.binary(86,a,o);case 2:case 7:return t.binary(96,a,o);case 3:case 8:return t.binary(106,a,o);case 4:case 9:return t.binary(e.options.isWasm64?106:96,a,o);case 11:return t.binary(112,a,o);case 12:return t.binary(118,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.eq",s.toString()),t.unreachable()}d.set(h.v128_eq,Er);function yr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:case 5:return t.binary(77,a,o);case 1:case 6:return t.binary(87,a,o);case 2:case 7:return t.binary(97,a,o);case 3:case 8:return t.binary(107,a,o);case 4:case 9:return t.binary(e.options.isWasm64?107:97,a,o);case 11:return t.binary(113,a,o);case 12:return t.binary(119,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.ne",s.toString()),t.unreachable()}d.set(h.v128_ne,yr);function ut(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(78,a,o);case 5:return t.binary(79,a,o);case 1:return t.binary(88,a,o);case 6:return t.binary(89,a,o);case 2:return t.binary(98,a,o);case 7:return t.binary(99,a,o);case 3:return t.binary(108,a,o);case 4:return t.binary(e.options.isWasm64?108:98,a,o);case 9:{if(e.options.isWasm64)break;return t.binary(99,a,o)}case 11:return t.binary(114,a,o);case 12:return t.binary(120,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.lt",s.toString()),t.unreachable()}d.set(h.v128_lt,ut);function pt(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(82,a,o);case 5:return t.binary(83,a,o);case 1:return t.binary(92,a,o);case 6:return t.binary(93,a,o);case 2:return t.binary(102,a,o);case 7:return t.binary(103,a,o);case 3:return t.binary(110,a,o);case 4:return t.binary(e.options.isWasm64?110:102,a,o);case 9:{if(e.options.isWasm64)break;return t.binary(103,a,o)}case 11:return t.binary(116,a,o);case 12:return t.binary(122,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.le",s.toString()),t.unreachable()}d.set(h.v128_le,pt);function ct(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(80,a,o);case 5:return t.binary(81,a,o);case 1:return t.binary(90,a,o);case 6:return t.binary(91,a,o);case 2:return t.binary(100,a,o);case 7:return t.binary(101,a,o);case 3:return t.binary(109,a,o);case 4:return t.binary(e.options.isWasm64?109:100,a,o);case 9:{if(e.options.isWasm64)break;return t.binary(101,a,o)}case 11:return t.binary(115,a,o);case 12:return t.binary(121,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.gt",s.toString()),t.unreachable()}d.set(h.v128_gt,ct);function _t(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(84,a,o);case 5:return t.binary(85,a,o);case 1:return t.binary(94,a,o);case 6:return t.binary(95,a,o);case 2:return t.binary(104,a,o);case 7:return t.binary(105,a,o);case 3:return t.binary(111,a,o);case 4:return t.binary(e.options.isWasm64?111:104,a,o);case 9:{if(e.options.isWasm64)break;return t.binary(105,a,o)}case 11:return t.binary(117,a,o);case 12:return t.binary(123,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.ge",s.toString()),t.unreachable()}d.set(h.v128_ge,_t);function In(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 1:return t.binary(191,a,o);case 6:return t.binary(192,a,o);case 2:return t.binary(193,a,o);case 7:return t.binary(194,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.narrow",s.toString()),t.unreachable()}d.set(h.v128_narrow,In);function gr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 0:case 5:return t.unary(69,a);case 1:case 6:return t.unary(74,a);case 2:case 7:return t.unary(78,a);case 3:case 8:return t.unary(82,a);case 4:case 9:return t.unary(e.options.isWasm64?82:78,a);case 11:return t.unary(86,a);case 12:return t.unary(93,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.neg",s.toString()),t.unreachable()}d.set(h.v128_neg,gr);function Tr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.unary(68,a);case 1:return t.unary(73,a);case 2:return t.unary(77,a);case 3:return t.unary(81,a);case 4:return t.unary(e.options.isWasm64?81:77,a);case 5:case 6:case 7:case 8:case 9:return a;case 11:return t.unary(85,a);case 12:return t.unary(92,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.abs",s.toString()),t.unreachable()}d.set(h.v128_abs,Tr);function bu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.unary(87,a);case 12:return t.unary(94,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.sqrt",s.toString()),t.unreachable()}d.set(h.v128_sqrt,bu);function Iu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.unary(88,a);case 12:return t.unary(95,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.ceil",s.toString()),t.unreachable()}d.set(h.v128_ceil,Iu);function vu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.unary(89,a);case 12:return t.unary(96,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.floor",s.toString()),t.unreachable()}d.set(h.v128_floor,vu);function xu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.unary(90,a);case 12:return t.unary(97,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.trunc",s.toString()),t.unreachable()}d.set(h.v128_trunc,xu);function Su(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 11:return t.unary(91,a);case 12:return t.unary(98,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.nearest",s.toString()),t.unreachable()}d.set(h.v128_nearest,Su);function Ru(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 4:if(e.options.isWasm64)break;case 2:return t.unary(105,a);case 9:if(e.options.isWasm64)break;case 7:return t.unary(106,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.convert",s.toString()),t.unreachable()}d.set(h.v128_convert,Ru);function Au(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 4:if(e.options.isWasm64)break;case 2:return t.unary(119,a);case 9:if(e.options.isWasm64)break;case 7:return t.unary(120,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.convert_low",s.toString()),t.unreachable()}d.set(h.v128_convert_low,Au);function Nu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 4:if(e.options.isWasm64)break;case 2:return t.unary(103,a);case 9:if(e.options.isWasm64)break;case 7:return t.unary(104,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.trunc_sat",s.toString()),t.unreachable()}d.set(h.v128_trunc_sat,Nu);function Lu(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 4:if(e.options.isWasm64)break;case 2:return t.unary(121,a);case 9:if(e.options.isWasm64)break;case 7:return t.unary(122,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.trunc_sat_zero",s.toString()),t.unreachable()}d.set(h.v128_trunc_sat_zero,Lu);function br(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.unary(107,a);case 5:return t.unary(109,a);case 1:return t.unary(111,a);case 6:return t.unary(113,a);case 4:if(e.options.isWasm64)break;case 2:return t.unary(115,a);case 9:if(e.options.isWasm64)break;case 7:return t.unary(117,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.extend_low",s.toString()),t.unreachable()}d.set(h.v128_extend_low,br);function Ir(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.unary(108,a);case 5:return t.unary(110,a);case 1:return t.unary(112,a);case 6:return t.unary(114,a);case 4:if(e.options.isWasm64)break;case 2:return t.unary(116,a);case 9:if(e.options.isWasm64)break;case 7:return t.unary(118,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.extend_high",s.toString()),t.unreachable()}d.set(h.v128_extend_high,Ir);function vn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments[0],s=e.compileExpression(i[0],u.v128,1),a=e.compileExpression(i[1],u.i32,1);if(e.currentType=u.v128,n.isValue)switch(n.kind){case 0:case 5:return t.simd_shift(0,s,a);case 1:case 6:return t.simd_shift(3,s,a);case 2:case 7:return t.simd_shift(6,s,a);case 3:case 8:return t.simd_shift(9,s,a);case 4:case 9:return t.simd_shift(e.options.isWasm64?9:6,s,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.shl",n.toString()),t.unreachable()}d.set(h.v128_shl,vn);function At(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments[0],s=e.compileExpression(i[0],u.v128,1),a=e.compileExpression(i[1],u.i32,1);if(e.currentType=u.v128,n.isValue)switch(n.kind){case 0:return t.simd_shift(1,s,a);case 5:return t.simd_shift(2,s,a);case 1:return t.simd_shift(4,s,a);case 6:return t.simd_shift(5,s,a);case 2:return t.simd_shift(7,s,a);case 7:return t.simd_shift(8,s,a);case 3:return t.simd_shift(10,s,a);case 8:return t.simd_shift(11,s,a);case 4:return t.simd_shift(e.options.isWasm64?10:7,s,a);case 9:return t.simd_shift(e.options.isWasm64?11:8,s,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.shr",n.toString()),t.unreachable()}d.set(h.v128_shr,At);function Vs(r,e){var t=r.compiler,i=t.module;if(X(r,16)|T(r)|W(r,2))return t.currentType=u.v128,i.unreachable();var n=r.operands,s=t.compileExpression(n[0],u.v128,1),a=t.compileExpression(n[1],u.v128,1);return i.binary(e,s,a)}function _y(r){return Vs(r,124)}d.set(h.v128_and,_y);function fy(r){return Vs(r,125)}d.set(h.v128_or,fy);function hy(r){return Vs(r,126)}d.set(h.v128_xor,hy);function my(r){return Vs(r,127)}d.set(h.v128_andnot,my);function dy(r,e){var t=r.compiler,i=t.module;if(X(r,16)|T(r)|W(r,1))return t.currentType=u.v128,i.unreachable();var n=r.operands,s=t.compileExpression(n[0],u.v128,1);return i.unary(e,s)}function Ey(r){return dy(r,66)}d.set(h.v128_not,Ey);function yy(r,e){var t=r.compiler,i=t.module;if(X(r,16)|T(r)|W(r,3))return t.currentType=u.v128,i.unreachable();var n=r.operands,s=t.compileExpression(n[0],u.v128,1),a=t.compileExpression(n[1],u.v128,1),o=t.compileExpression(n[2],u.v128,1);return i.simd_ternary(e,s,a,o)}function gy(r){return yy(r,0)}d.set(h.v128_bitselect,gy);function Ty(r){var e=r.compiler,t=e.module;if(X(r,16)|T(r)|W(r,1))return e.currentType=u.bool,t.unreachable();var i=r.operands,n=e.compileExpression(i[0],u.v128,1);return e.currentType=u.bool,t.unary(67,n)}d.set(h.v128_any_true,Ty);function xn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.bool,t.unreachable();var i=r.operands,n=r.typeArguments[0],s=e.compileExpression(i[0],u.v128,1);if(e.currentType=u.bool,n.isValue)switch(n.kind){case 0:case 5:return t.unary(70,s);case 1:case 6:return t.unary(75,s);case 2:case 7:return t.unary(79,s);case 3:case 8:return t.unary(83,s);case 4:case 9:return t.unary(e.options.isWasm64?83:79,s)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.all_true",n.toString()),t.unreachable()}d.set(h.v128_all_true,xn);function Sn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.i32,t.unreachable();var i=r.operands,n=r.typeArguments[0],s=e.compileExpression(i[0],u.v128,1);if(e.currentType=u.i32,n.isValue)switch(n.kind){case 0:case 5:return t.unary(71,s);case 1:case 6:return t.unary(76,s);case 2:case 7:return t.unary(80,s);case 3:case 8:return t.unary(84,s);case 4:case 9:return t.unary(e.options.isWasm64?84:80,s)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.bitmask",n.toString()),t.unreachable()}d.set(h.v128_bitmask,Sn);function Xc(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments[0],s=e.compileExpression(i[0],u.v128,1);if(e.currentType=u.v128,n.isValue)switch(n.kind){case 0:case 5:return t.unary(72,s)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.popcnt",n.toString()),t.unreachable()}d.set(h.v128_popcnt,Xc);function Rn(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments[0],s=e.compileExpression(i[0],u.v128,1);if(e.currentType=u.v128,n.isValue)switch(n.kind){case 0:return t.unary(99,s);case 5:return t.unary(100,s);case 1:return t.unary(101,s);case 6:return t.unary(102,s)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.extadd_pairwise",n.toString()),t.unreachable()}d.set(h.v128_extadd_pairwise,Rn);function Kc(r){var e=r.compiler,t=e.module;if(X(r,16)|ae(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n?n[0]:u.f64,a=e.compileExpression(i[0],u.v128,1);if(e.currentType=u.v128,s.isValue)switch(s.kind){case 12:return t.unary(123,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.demote_zero",s.toString()),t.unreachable()}d.set(h.v128_demote_zero,Kc);function qc(r){var e=r.compiler,t=e.module;if(X(r,16)|ae(r)|W(r,1))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n?n[0]:u.f32,a=e.compileExpression(i[0],u.v128,1);if(e.currentType=u.v128,s.isValue)switch(s.kind){case 11:return t.unary(124,a)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.promote_low",s.toString()),t.unreachable()}d.set(h.v128_promote_low,qc);function Qc(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 1:return t.binary(151,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.q15mulr_sat",s.toString()),t.unreachable()}d.set(h.v128_q15mulr_sat,Qc);function vr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(152,a,o);case 5:return t.binary(154,a,o);case 1:return t.binary(164,a,o);case 6:return t.binary(166,a,o);case 2:return t.binary(171,a,o);case 7:return t.binary(173,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.extmul_low",s.toString()),t.unreachable()}d.set(h.v128_extmul_low,vr);function xr(r){var e=r.compiler,t=e.module;if(X(r,16)|K(r)|W(r,2))return e.currentType=u.v128,t.unreachable();var i=r.operands,n=r.typeArguments,s=n[0],a=e.compileExpression(i[0],u.v128,1),o=e.compileExpression(i[1],u.v128,1);if(s.isValue)switch(s.kind){case 0:return t.binary(153,a,o);case 5:return t.binary(155,a,o);case 1:return t.binary(165,a,o);case 6:return t.binary(167,a,o);case 2:return t.binary(172,a,o);case 7:return t.binary(174,a,o)}return e.error(203,r.reportNode.typeArgumentsRange,"v128.extmul_high",s.toString()),t.unreachable()}d.set(h.v128_extmul_high,xr);function by(r){var e=r.compiler,t=e.module;if(T(r)|W(r,1))return e.currentType=u.void,t.unreachable();var i=r.operands,n=e.compileExpression(i[0],u.u32,1);return e.runtimeFeatures|=16,e.currentType=u.void,t.call(h.visit_globals,[n],C.None)}d.set(h.visit_globals,by);function Iy(r){var e=r.compiler,t=e.module;if(T(r)|W(r,2))return e.currentType=u.void,t.unreachable();var i=r.operands,n=e.compileExpression(i[0],e.options.usizeType,1),s=e.compileExpression(i[1],u.u32,1);return e.runtimeFeatures|=32,e.currentType=u.void,t.call(h.visit_members,[n,s],C.None)}d.set(h.visit_members,Iy);function vy(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,eu(r)}d.set(h.i32_clz,vy);function xy(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,eu(r)}d.set(h.i64_clz,xy);function Sy(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,tu(r)}d.set(h.i32_ctz,Sy);function Ry(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,tu(r)}d.set(h.i64_ctz,Ry);function Ay(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,ru(r)}d.set(h.i32_popcnt,Ay);function Ny(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,ru(r)}d.set(h.i64_popcnt,Ny);function Ly(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,iu(r)}d.set(h.i32_rotl,Ly);function Cy(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,iu(r)}d.set(h.i64_rotl,Cy);function Fy(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,nu(r)}d.set(h.i32_rotr,Fy);function ky(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,nu(r)}d.set(h.i64_rotr,ky);function Py(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,su(r)}d.set(h.f32_abs,Py);function Oy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,su(r)}d.set(h.f64_abs,Oy);function wy(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,au(r)}d.set(h.f32_max,wy);function My(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,au(r)}d.set(h.f64_max,My);function Uy(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,ou(r)}d.set(h.f32_min,Uy);function Dy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,ou(r)}d.set(h.f64_min,Dy);function By(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,lu(r)}d.set(h.f32_ceil,By);function Gy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,lu(r)}d.set(h.f64_ceil,Gy);function Vy(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,uu(r)}d.set(h.f32_floor,Vy);function zy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,uu(r)}d.set(h.f64_floor,zy);function Wy(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,pu(r)}d.set(h.f32_copysign,Wy);function Yy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,pu(r)}d.set(h.f64_copysign,Yy);function Hy(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,cu(r)}d.set(h.f32_nearest,Hy);function Xy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,cu(r)}d.set(h.f64_nearest,Xy);function Ky(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.f32,cn(r)}d.set(h.i32_reinterpret_f32,Ky);function qy(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.f64,cn(r)}d.set(h.i64_reinterpret_f64,qy);function Qy(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.i32,cn(r)}d.set(h.f32_reinterpret_i32,Qy);function Zy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.i64,cn(r)}d.set(h.f64_reinterpret_i64,Zy);function jy(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,_u(r)}d.set(h.f32_sqrt,jy);function Jy(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,_u(r)}d.set(h.f64_sqrt,Jy);function $y(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,fu(r)}d.set(h.f32_trunc,$y);function eg(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,fu(r)}d.set(h.f64_trunc,eg);function tg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,_n(r)}d.set(h.i32_add,tg);function rg(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,_n(r)}d.set(h.i64_add,rg);function ig(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,_n(r)}d.set(h.f32_add,ig);function ng(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,_n(r)}d.set(h.f64_add,ng);function sg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,fn(r)}d.set(h.i32_sub,sg);function ag(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,fn(r)}d.set(h.i64_sub,ag);function og(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,fn(r)}d.set(h.f32_sub,og);function lg(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,fn(r)}d.set(h.f64_sub,lg);function ug(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,hn(r)}d.set(h.i32_mul,ug);function pg(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,hn(r)}d.set(h.i64_mul,pg);function cg(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,hn(r)}d.set(h.f32_mul,cg);function _g(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,hn(r)}d.set(h.f64_mul,_g);function fg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,cr(r)}d.set(h.i32_div_s,fg);function hg(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.u32,cr(r)}d.set(h.i32_div_u,hg);function mg(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,cr(r)}d.set(h.i64_div_s,mg);function dg(r){return T(r),r.typeArguments=[u.u64],r.contextualType=u.u64,cr(r)}d.set(h.i64_div_u,dg);function Eg(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,cr(r)}d.set(h.f32_div,Eg);function yg(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,cr(r)}d.set(h.f64_div,yg);function gg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,mn(r)}d.set(h.i32_eq,gg);function Tg(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i32,mn(r)}d.set(h.i64_eq,Tg);function bg(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.i32,mn(r)}d.set(h.f32_eq,bg);function Ig(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.i32,mn(r)}d.set(h.f64_eq,Ig);function vg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,dn(r)}d.set(h.i32_ne,vg);function xg(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i32,dn(r)}d.set(h.i64_ne,xg);function Sg(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.i32,dn(r)}d.set(h.f32_ne,Sg);function Rg(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.i32,dn(r)}d.set(h.f64_ne,Rg);function Ag(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i32,Ie(r)}d.set(h.i32_load8_s,Ag);function Ng(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,Ie(r)}d.set(h.i32_load8_u,Ng);function Lg(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i32,Ie(r)}d.set(h.i32_load16_s,Lg);function Cg(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,Ie(r)}d.set(h.i32_load16_u,Cg);function Fg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,Ie(r)}d.set(h.i32_load,Fg);function kg(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i64,Ie(r)}d.set(h.i64_load8_s,kg);function Pg(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,Ie(r)}d.set(h.i64_load8_u,Pg);function Og(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i64,Ie(r)}d.set(h.i64_load16_s,Og);function wg(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,Ie(r)}d.set(h.i64_load16_u,wg);function Mg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i64,Ie(r)}d.set(h.i64_load32_s,Mg);function Ug(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,Ie(r)}d.set(h.i64_load32_u,Ug);function Dg(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,Ie(r)}d.set(h.i64_load,Dg);function Bg(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,Ie(r)}d.set(h.f32_load,Bg);function Gg(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,Ie(r)}d.set(h.f64_load,Gg);function Vg(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i32,r.contextIsExact=!0,et(r)}d.set(h.i32_store8,Vg);function zg(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i32,r.contextIsExact=!0,et(r)}d.set(h.i32_store16,zg);function Wg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,et(r)}d.set(h.i32_store,Wg);function Yg(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i64,r.contextIsExact=!0,et(r)}d.set(h.i64_store8,Yg);function Hg(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i64,r.contextIsExact=!0,et(r)}d.set(h.i64_store16,Hg);function Xg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i64,r.contextIsExact=!0,et(r)}d.set(h.i64_store32,Xg);function Kg(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,et(r)}d.set(h.i64_store,Kg);function qg(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,r.contextIsExact=!0,et(r)}d.set(h.f32_store,qg);function Qg(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,r.contextIsExact=!0,et(r)}d.set(h.f64_store,Qg);function Zg(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,Wt(r)}d.set(h.i32_atomic_load8_u,Zg);function jg(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,Wt(r)}d.set(h.i32_atomic_load16_u,jg);function Jg(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,Wt(r)}d.set(h.i32_atomic_load,Jg);function $g(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,Wt(r)}d.set(h.i64_atomic_load8_u,$g);function eT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,Wt(r)}d.set(h.i64_atomic_load16_u,eT);function tT(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,Wt(r)}d.set(h.i64_atomic_load32_u,tT);function rT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,Wt(r)}d.set(h.i64_atomic_load,rT);function iT(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i32,r.contextIsExact=!0,Yt(r)}d.set(h.i32_atomic_store8,iT);function nT(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i32,r.contextIsExact=!0,Yt(r)}d.set(h.i32_atomic_store16,nT);function sT(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,Yt(r)}d.set(h.i32_atomic_store,sT);function aT(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i64,r.contextIsExact=!0,Yt(r)}d.set(h.i64_atomic_store8,aT);function oT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,Yt(r)}d.set(h.i64_atomic_store16,oT);function lT(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i64,r.contextIsExact=!0,Yt(r)}d.set(h.i64_atomic_store32,lT);function uT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,Yt(r)}d.set(h.i64_atomic_store,uT);function pT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,r.contextIsExact=!0,Ht(r)}d.set(h.i32_atomic_rmw8_add_u,pT);function cT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,r.contextIsExact=!0,Ht(r)}d.set(h.i32_atomic_rmw16_add_u,cT);function _T(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,Ht(r)}d.set(h.i32_atomic_rmw_add,_T);function fT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,r.contextIsExact=!0,Ht(r)}d.set(h.i64_atomic_rmw8_add_u,fT);function hT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,Ht(r)}d.set(h.i64_atomic_rmw16_add_u,hT);function mT(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,r.contextIsExact=!0,Ht(r)}d.set(h.i64_atomic_rmw32_add_u,mT);function dT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,Ht(r)}d.set(h.i64_atomic_rmw_add,dT);function ET(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,r.contextIsExact=!0,Xt(r)}d.set(h.i32_atomic_rmw8_sub_u,ET);function yT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,r.contextIsExact=!0,Xt(r)}d.set(h.i32_atomic_rmw16_sub_u,yT);function gT(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,Xt(r)}d.set(h.i32_atomic_rmw_sub,gT);function TT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,r.contextIsExact=!0,Xt(r)}d.set(h.i64_atomic_rmw8_sub_u,TT);function bT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,Xt(r)}d.set(h.i64_atomic_rmw16_sub_u,bT);function IT(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,r.contextIsExact=!0,Xt(r)}d.set(h.i64_atomic_rmw32_sub_u,IT);function vT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,Xt(r)}d.set(h.i64_atomic_rmw_sub,vT);function xT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,r.contextIsExact=!0,Kt(r)}d.set(h.i32_atomic_rmw8_and_u,xT);function ST(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,r.contextIsExact=!0,Kt(r)}d.set(h.i32_atomic_rmw16_and_u,ST);function RT(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,Kt(r)}d.set(h.i32_atomic_rmw_and,RT);function AT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,r.contextIsExact=!0,Kt(r)}d.set(h.i64_atomic_rmw8_and_u,AT);function NT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,Kt(r)}d.set(h.i64_atomic_rmw16_and_u,NT);function LT(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,r.contextIsExact=!0,Kt(r)}d.set(h.i64_atomic_rmw32_and_u,LT);function CT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,Kt(r)}d.set(h.i64_atomic_rmw_and,CT);function FT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,r.contextIsExact=!0,qt(r)}d.set(h.i32_atomic_rmw8_or_u,FT);function kT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,r.contextIsExact=!0,qt(r)}d.set(h.i32_atomic_rmw16_or_u,kT);function PT(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,qt(r)}d.set(h.i32_atomic_rmw_or,PT);function OT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,r.contextIsExact=!0,qt(r)}d.set(h.i64_atomic_rmw8_or_u,OT);function wT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,qt(r)}d.set(h.i64_atomic_rmw16_or_u,wT);function MT(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,r.contextIsExact=!0,qt(r)}d.set(h.i64_atomic_rmw32_or_u,MT);function UT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,qt(r)}d.set(h.i64_atomic_rmw_or,UT);function DT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,r.contextIsExact=!0,Qt(r)}d.set(h.i32_atomic_rmw8_xor_u,DT);function BT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,r.contextIsExact=!0,Qt(r)}d.set(h.i32_atomic_rmw16_xor_u,BT);function GT(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,Qt(r)}d.set(h.i32_atomic_rmw_xor,GT);function VT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,r.contextIsExact=!0,Qt(r)}d.set(h.i64_atomic_rmw8_xor_u,VT);function zT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,Qt(r)}d.set(h.i64_atomic_rmw16_xor_u,zT);function WT(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,r.contextIsExact=!0,Qt(r)}d.set(h.i64_atomic_rmw32_xor_u,WT);function YT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,Qt(r)}d.set(h.i64_atomic_rmw_xor,YT);function HT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,r.contextIsExact=!0,Zt(r)}d.set(h.i32_atomic_rmw8_xchg_u,HT);function XT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,r.contextIsExact=!0,Zt(r)}d.set(h.i32_atomic_rmw16_xchg_u,XT);function KT(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,Zt(r)}d.set(h.i32_atomic_rmw_xchg,KT);function qT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,r.contextIsExact=!0,Zt(r)}d.set(h.i64_atomic_rmw8_xchg_u,qT);function QT(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,Zt(r)}d.set(h.i64_atomic_rmw16_xchg_u,QT);function ZT(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,r.contextIsExact=!0,Zt(r)}d.set(h.i64_atomic_rmw32_xchg_u,ZT);function jT(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,Zt(r)}d.set(h.i64_atomic_rmw_xchg,jT);function JT(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,r.contextIsExact=!0,jt(r)}d.set(h.i32_atomic_rmw8_cmpxchg_u,JT);function $T(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,r.contextIsExact=!0,jt(r)}d.set(h.i32_atomic_rmw16_cmpxchg_u,$T);function eb(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,r.contextIsExact=!0,jt(r)}d.set(h.i32_atomic_rmw_cmpxchg,eb);function tb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i64,r.contextIsExact=!0,jt(r)}d.set(h.i64_atomic_rmw8_cmpxchg_u,tb);function rb(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i64,r.contextIsExact=!0,jt(r)}d.set(h.i64_atomic_rmw16_cmpxchg_u,rb);function ib(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.i64,r.contextIsExact=!0,jt(r)}d.set(h.i64_atomic_rmw32_cmpxchg_u,ib);function nb(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,r.contextIsExact=!0,jt(r)}d.set(h.i64_atomic_rmw_cmpxchg,nb);function sb(r){return T(r),r.typeArguments=[u.i32],hu(r)}d.set(h.i32_wait,sb);function ab(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i32,hu(r)}d.set(h.i64_wait,ab);function ob(r){return T(r),r.typeArguments=[u.v128],r.contextualType=u.v128,Ie(r)}d.set(h.v128_load,ob);function lb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,hr(r)}d.set(h.v128_load8x8_s,lb);function ub(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,hr(r)}d.set(h.v128_load8x8_u,ub);function pb(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,hr(r)}d.set(h.v128_load16x4_s,pb);function cb(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,hr(r)}d.set(h.v128_load16x4_u,cb);function _b(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,hr(r)}d.set(h.v128_load32x2_s,_b);function fb(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,hr(r)}d.set(h.v128_load32x2_u,fb);function hb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,En(r)}d.set(h.v128_load8_splat,hb);function mb(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,En(r)}d.set(h.v128_load16_splat,mb);function db(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,En(r)}d.set(h.v128_load32_splat,db);function Eb(r){return T(r),r.typeArguments=[u.u64],r.contextualType=u.v128,En(r)}d.set(h.v128_load64_splat,Eb);function yb(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,du(r)}d.set(h.v128_load32_zero,yb);function gb(r){return T(r),r.typeArguments=[u.u64],r.contextualType=u.v128,du(r)}d.set(h.v128_load64_zero,gb);function Tb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,yn(r)}d.set(h.v128_load8_lane,Tb);function bb(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,yn(r)}d.set(h.v128_load16_lane,bb);function Ib(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,yn(r)}d.set(h.v128_load32_lane,Ib);function vb(r){return T(r),r.typeArguments=[u.u64],r.contextualType=u.v128,yn(r)}d.set(h.v128_load64_lane,vb);function xb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,gn(r)}d.set(h.v128_store8_lane,xb);function Sb(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,gn(r)}d.set(h.v128_store16_lane,Sb);function Rb(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,gn(r)}d.set(h.v128_store32_lane,Rb);function Ab(r){return T(r),r.typeArguments=[u.u64],r.contextualType=u.v128,gn(r)}d.set(h.v128_store64_lane,Ab);function Nb(r){return T(r),r.typeArguments=[u.v128],r.contextualType=u.v128,r.contextIsExact=!0,et(r)}d.set(h.v128_store,Nb);function Lb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,_r(r)}d.set(h.i8x16_splat,Lb);function Cb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i32,xt(r)}d.set(h.i8x16_extract_lane_s,Cb);function Fb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.i32,xt(r)}d.set(h.i8x16_extract_lane_u,Fb);function kb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,fr(r)}d.set(h.i8x16_replace_lane,kb);function Pb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,mr(r)}d.set(h.i8x16_add,Pb);function Ob(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,dr(r)}d.set(h.i8x16_sub,Ob);function wb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,St(r)}d.set(h.i8x16_min_s,wb);function Mb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,St(r)}d.set(h.i8x16_min_u,Mb);function Ub(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Rt(r)}d.set(h.i8x16_max_s,Ub);function Db(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,Rt(r)}d.set(h.i8x16_max_u,Db);function Bb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,Tu(r)}d.set(h.i8x16_avgr_u,Bb);function Gb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Tr(r)}d.set(h.i8x16_abs,Gb);function Vb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,gr(r)}d.set(h.i8x16_neg,Vb);function zb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Tn(r)}d.set(h.i8x16_add_sat_s,zb);function Wb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,Tn(r)}d.set(h.i8x16_add_sat_u,Wb);function Yb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,bn(r)}d.set(h.i8x16_sub_sat_s,Yb);function Hb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,bn(r)}d.set(h.i8x16_sub_sat_u,Hb);function Xb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,vn(r)}d.set(h.i8x16_shl,Xb);function Kb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,At(r)}d.set(h.i8x16_shr_s,Kb);function qb(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,At(r)}d.set(h.i8x16_shr_u,qb);function Qb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i32,xn(r)}d.set(h.i8x16_all_true,Qb);function Zb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.i32,Sn(r)}d.set(h.i8x16_bitmask,Zb);function jb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Xc(r)}d.set(h.i8x16_popcnt,jb);function Jb(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Er(r)}d.set(h.i8x16_eq,Jb);function $b(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,yr(r)}d.set(h.i8x16_ne,$b);function eI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,ut(r)}d.set(h.i8x16_lt_s,eI);function tI(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,ut(r)}d.set(h.i8x16_lt_u,tI);function rI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,pt(r)}d.set(h.i8x16_le_s,rI);function iI(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,pt(r)}d.set(h.i8x16_le_u,iI);function nI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,ct(r)}d.set(h.i8x16_gt_s,nI);function sI(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,ct(r)}d.set(h.i8x16_gt_u,sI);function aI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,_t(r)}d.set(h.i8x16_ge_s,aI);function oI(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,_t(r)}d.set(h.i8x16_ge_u,oI);function lI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,In(r)}d.set(h.i8x16_narrow_i16x8_s,lI);function uI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,In(r)}d.set(h.i8x16_narrow_i16x8_u,uI);function pI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Wc(r)}d.set(h.i8x16_shuffle,pI);function cI(r){return T(r),r.typeArguments=null,r.contextualType=u.v128,Yc(r)}d.set(h.i8x16_swizzle,cI);function _I(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,_r(r)}d.set(h.i16x8_splat,_I);function fI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i32,xt(r)}d.set(h.i16x8_extract_lane_s,fI);function hI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.i32,xt(r)}d.set(h.i16x8_extract_lane_u,hI);function mI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,fr(r)}d.set(h.i16x8_replace_lane,mI);function dI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,mr(r)}d.set(h.i16x8_add,dI);function EI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,dr(r)}d.set(h.i16x8_sub,EI);function yI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,ci(r)}d.set(h.i16x8_mul,yI);function gI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,St(r)}d.set(h.i16x8_min_s,gI);function TI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,St(r)}d.set(h.i16x8_min_u,TI);function bI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Rt(r)}d.set(h.i16x8_max_s,bI);function II(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,Rt(r)}d.set(h.i16x8_max_u,II);function vI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,Tu(r)}d.set(h.i16x8_avgr_u,vI);function xI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Tr(r)}d.set(h.i16x8_abs,xI);function SI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,gr(r)}d.set(h.i16x8_neg,SI);function RI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Tn(r)}d.set(h.i16x8_add_sat_s,RI);function AI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,Tn(r)}d.set(h.i16x8_add_sat_u,AI);function NI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,bn(r)}d.set(h.i16x8_sub_sat_s,NI);function LI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,bn(r)}d.set(h.i16x8_sub_sat_u,LI);function CI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,vn(r)}d.set(h.i16x8_shl,CI);function FI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,At(r)}d.set(h.i16x8_shr_s,FI);function kI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,At(r)}d.set(h.i16x8_shr_u,kI);function PI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i32,xn(r)}d.set(h.i16x8_all_true,PI);function OI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.i32,Sn(r)}d.set(h.i16x8_bitmask,OI);function wI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Er(r)}d.set(h.i16x8_eq,wI);function MI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,yr(r)}d.set(h.i16x8_ne,MI);function UI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,ut(r)}d.set(h.i16x8_lt_s,UI);function DI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,ut(r)}d.set(h.i16x8_lt_u,DI);function BI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,pt(r)}d.set(h.i16x8_le_s,BI);function GI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,pt(r)}d.set(h.i16x8_le_u,GI);function VI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,ct(r)}d.set(h.i16x8_gt_s,VI);function zI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,ct(r)}d.set(h.i16x8_gt_u,zI);function WI(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,_t(r)}d.set(h.i16x8_ge_s,WI);function YI(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,_t(r)}d.set(h.i16x8_ge_u,YI);function HI(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,In(r)}d.set(h.i16x8_narrow_i32x4_s,HI);function XI(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,In(r)}d.set(h.i16x8_narrow_i32x4_u,XI);function KI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,br(r)}d.set(h.i16x8_extend_low_i8x16_s,KI);function qI(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,br(r)}d.set(h.i16x8_extend_low_i8x16_u,qI);function QI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Ir(r)}d.set(h.i16x8_extend_high_i8x16_s,QI);function ZI(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,Ir(r)}d.set(h.i16x8_extend_high_i8x16_u,ZI);function jI(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,Rn(r)}d.set(h.i16x8_extadd_pairwise_i8x16_s,jI);function JI(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,Rn(r)}d.set(h.i16x8_extadd_pairwise_i8x16_u,JI);function $I(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Qc(r)}d.set(h.i16x8_q15mulr_sat_s,$I);function ev(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,vr(r)}d.set(h.i16x8_extmul_low_i8x16_s,ev);function tv(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,vr(r)}d.set(h.i16x8_extmul_low_i8x16_u,tv);function rv(r){return T(r),r.typeArguments=[u.i8],r.contextualType=u.v128,xr(r)}d.set(h.i16x8_extmul_high_i8x16_s,rv);function iv(r){return T(r),r.typeArguments=[u.u8],r.contextualType=u.v128,xr(r)}d.set(h.i16x8_extmul_high_i8x16_u,iv);function nv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,_r(r)}d.set(h.i32x4_splat,nv);function sv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,xt(r)}d.set(h.i32x4_extract_lane,sv);function av(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,fr(r)}d.set(h.i32x4_replace_lane,av);function ov(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,mr(r)}d.set(h.i32x4_add,ov);function lv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,dr(r)}d.set(h.i32x4_sub,lv);function uv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,ci(r)}d.set(h.i32x4_mul,uv);function pv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,St(r)}d.set(h.i32x4_min_s,pv);function cv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,St(r)}d.set(h.i32x4_min_u,cv);function _v(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Rt(r)}d.set(h.i32x4_max_s,_v);function fv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,Rt(r)}d.set(h.i32x4_max_u,fv);function hv(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Hc(r)}d.set(h.i32x4_dot_i16x8_s,hv);function mv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Tr(r)}d.set(h.i32x4_abs,mv);function dv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,gr(r)}d.set(h.i32x4_neg,dv);function Ev(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,vn(r)}d.set(h.i32x4_shl,Ev);function yv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,At(r)}d.set(h.i32x4_shr_s,yv);function gv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,At(r)}d.set(h.i32x4_shr_u,gv);function Tv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,xn(r)}d.set(h.i32x4_all_true,Tv);function bv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.i32,Sn(r)}d.set(h.i32x4_bitmask,bv);function Iv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Er(r)}d.set(h.i32x4_eq,Iv);function vv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,yr(r)}d.set(h.i32x4_ne,vv);function xv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,ut(r)}d.set(h.i32x4_lt_s,xv);function Sv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,ut(r)}d.set(h.i32x4_lt_u,Sv);function Rv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,pt(r)}d.set(h.i32x4_le_s,Rv);function Av(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,pt(r)}d.set(h.i32x4_le_u,Av);function Nv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,ct(r)}d.set(h.i32x4_gt_s,Nv);function Lv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,ct(r)}d.set(h.i32x4_gt_u,Lv);function Cv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,_t(r)}d.set(h.i32x4_ge_s,Cv);function Fv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,_t(r)}d.set(h.i32x4_ge_u,Fv);function kv(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Nu(r)}d.set(h.i32x4_trunc_sat_f32x4_s,kv);function Pv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,Nu(r)}d.set(h.i32x4_trunc_sat_f32x4_u,Pv);function Ov(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Lu(r)}d.set(h.i32x4_trunc_sat_f64x2_s_zero,Ov);function wv(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,Lu(r)}d.set(h.i32x4_trunc_sat_f64x2_u_zero,wv);function Mv(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,br(r)}d.set(h.i32x4_extend_low_i16x8_s,Mv);function Uv(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,br(r)}d.set(h.i32x4_extend_low_i16x8_u,Uv);function Dv(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Ir(r)}d.set(h.i32x4_extend_high_i16x8_s,Dv);function Bv(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,Ir(r)}d.set(h.i32x4_extend_high_i16x8_u,Bv);function Gv(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,Rn(r)}d.set(h.i32x4_extadd_pairwise_i16x8_s,Gv);function Vv(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,Rn(r)}d.set(h.i32x4_extadd_pairwise_i16x8_u,Vv);function zv(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,vr(r)}d.set(h.i32x4_extmul_low_i16x8_s,zv);function Wv(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,vr(r)}d.set(h.i32x4_extmul_low_i16x8_u,Wv);function Yv(r){return T(r),r.typeArguments=[u.i16],r.contextualType=u.v128,xr(r)}d.set(h.i32x4_extmul_high_i16x8_s,Yv);function Hv(r){return T(r),r.typeArguments=[u.u16],r.contextualType=u.v128,xr(r)}d.set(h.i32x4_extmul_high_i16x8_u,Hv);function Xv(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,_r(r)}d.set(h.i64x2_splat,Xv);function Kv(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i64,xt(r)}d.set(h.i64x2_extract_lane,Kv);function qv(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,fr(r)}d.set(h.i64x2_replace_lane,qv);function Qv(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,mr(r)}d.set(h.i64x2_add,Qv);function Zv(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,dr(r)}d.set(h.i64x2_sub,Zv);function jv(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,ci(r)}d.set(h.i64x2_mul,jv);function Jv(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,Tr(r)}d.set(h.i64x2_abs,Jv);function $v(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,gr(r)}d.set(h.i64x2_neg,$v);function ex(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,vn(r)}d.set(h.i64x2_shl,ex);function tx(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,At(r)}d.set(h.i64x2_shr_s,tx);function rx(r){return T(r),r.typeArguments=[u.u64],r.contextualType=u.v128,At(r)}d.set(h.i64x2_shr_u,rx);function ix(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i32,xn(r)}d.set(h.i64x2_all_true,ix);function nx(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.i32,Sn(r)}d.set(h.i64x2_bitmask,nx);function sx(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,Er(r)}d.set(h.i64x2_eq,sx);function ax(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,yr(r)}d.set(h.i64x2_ne,ax);function ox(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,ut(r)}d.set(h.i64x2_lt_s,ox);function lx(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,pt(r)}d.set(h.i64x2_le_s,lx);function ux(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,ct(r)}d.set(h.i64x2_gt_s,ux);function px(r){return T(r),r.typeArguments=[u.i64],r.contextualType=u.v128,_t(r)}d.set(h.i64x2_ge_s,px);function cx(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,br(r)}d.set(h.i64x2_extend_low_i32x4_s,cx);function _x(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,br(r)}d.set(h.i64x2_extend_low_i32x4_u,_x);function fx(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Ir(r)}d.set(h.i64x2_extend_high_i32x4_s,fx);function hx(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,Ir(r)}d.set(h.i64x2_extend_high_i32x4_u,hx);function mx(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,vr(r)}d.set(h.i64x2_extmul_low_i32x4_s,mx);function dx(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,vr(r)}d.set(h.i64x2_extmul_low_i32x4_u,dx);function Ex(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,xr(r)}d.set(h.i64x2_extmul_high_i32x4_s,Ex);function yx(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,xr(r)}d.set(h.i64x2_extmul_high_i32x4_u,yx);function gx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,_r(r)}d.set(h.f32x4_splat,gx);function Tx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.f32,xt(r)}d.set(h.f32x4_extract_lane,Tx);function bx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,fr(r)}d.set(h.f32x4_replace_lane,bx);function Ix(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,mr(r)}d.set(h.f32x4_add,Ix);function vx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,dr(r)}d.set(h.f32x4_sub,vx);function xx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,ci(r)}d.set(h.f32x4_mul,xx);function Sx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,Eu(r)}d.set(h.f32x4_div,Sx);function Rx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,gr(r)}d.set(h.f32x4_neg,Rx);function Ax(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,St(r)}d.set(h.f32x4_min,Ax);function Nx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,Rt(r)}d.set(h.f32x4_max,Nx);function Lx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,yu(r)}d.set(h.f32x4_pmin,Lx);function Cx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,gu(r)}d.set(h.f32x4_pmax,Cx);function Fx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,Tr(r)}d.set(h.f32x4_abs,Fx);function kx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,bu(r)}d.set(h.f32x4_sqrt,kx);function Px(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,Iu(r)}d.set(h.f32x4_ceil,Px);function Ox(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,vu(r)}d.set(h.f32x4_floor,Ox);function wx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,xu(r)}d.set(h.f32x4_trunc,wx);function Mx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,Su(r)}d.set(h.f32x4_nearest,Mx);function Ux(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,Er(r)}d.set(h.f32x4_eq,Ux);function Dx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,yr(r)}d.set(h.f32x4_ne,Dx);function Bx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,ut(r)}d.set(h.f32x4_lt,Bx);function Gx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,pt(r)}d.set(h.f32x4_le,Gx);function Vx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,ct(r)}d.set(h.f32x4_gt,Vx);function zx(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,_t(r)}d.set(h.f32x4_ge,zx);function Wx(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Ru(r)}d.set(h.f32x4_convert_i32x4_s,Wx);function Yx(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,Ru(r)}d.set(h.f32x4_convert_i32x4_u,Yx);function Hx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,Kc(r)}d.set(h.f32x4_demote_f64x2_zero,Hx);function Xx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,_r(r)}d.set(h.f64x2_splat,Xx);function Kx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.f64,xt(r)}d.set(h.f64x2_extract_lane,Kx);function qx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,fr(r)}d.set(h.f64x2_replace_lane,qx);function Qx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,mr(r)}d.set(h.f64x2_add,Qx);function Zx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,dr(r)}d.set(h.f64x2_sub,Zx);function jx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,ci(r)}d.set(h.f64x2_mul,jx);function Jx(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,Eu(r)}d.set(h.f64x2_div,Jx);function $x(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,gr(r)}d.set(h.f64x2_neg,$x);function e2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,St(r)}d.set(h.f64x2_min,e2);function t2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,Rt(r)}d.set(h.f64x2_max,t2);function r2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,yu(r)}d.set(h.f64x2_pmin,r2);function i2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,gu(r)}d.set(h.f64x2_pmax,i2);function n2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,Tr(r)}d.set(h.f64x2_abs,n2);function s2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,bu(r)}d.set(h.f64x2_sqrt,s2);function a2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,Iu(r)}d.set(h.f64x2_ceil,a2);function o2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,vu(r)}d.set(h.f64x2_floor,o2);function l2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,xu(r)}d.set(h.f64x2_trunc,l2);function u2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,Su(r)}d.set(h.f64x2_nearest,u2);function p2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,Er(r)}d.set(h.f64x2_eq,p2);function c2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,yr(r)}d.set(h.f64x2_ne,c2);function _2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,ut(r)}d.set(h.f64x2_lt,_2);function f2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,pt(r)}d.set(h.f64x2_le,f2);function h2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,ct(r)}d.set(h.f64x2_gt,h2);function m2(r){return T(r),r.typeArguments=[u.f64],r.contextualType=u.v128,_t(r)}d.set(h.f64x2_ge,m2);function d2(r){return T(r),r.typeArguments=[u.i32],r.contextualType=u.v128,Au(r)}d.set(h.f64x2_convert_low_i32x4_s,d2);function E2(r){return T(r),r.typeArguments=[u.u32],r.contextualType=u.v128,Au(r)}d.set(h.f64x2_convert_low_i32x4_u,E2);function y2(r){return T(r),r.typeArguments=[u.f32],r.contextualType=u.v128,qc(r)}d.set(h.f64x2_promote_low_f32x4,y2);function Dc(r){var e=r.module,t=new Array,i=r.options.sizeTypeRef,n=assert(r.program.visitInstance);r.compileFunction(n,!0);for(let s=Map_values(r.program.elementsByName),a=0,o=s.length;a=0),_=!0,l.push(i.if(i.local_tee(2,i.load(a,!1,i.local_get(0,s),s,x),!1),i.call(o.internalName,[i.local_get(2,s),i.local_get(1,C.I32)],C.None)))}}}e.visitRef=i.addFunction(e.internalName+"~visit",Oe([s,C.I32]),C.None,_?[s]:null,i.flatten(l,C.None)),p&&p.type.isManaged&&Zc(r,p)}}function Bc(r){var e=r.program,t=r.module,i=e.options.usizeType,n=i.toRef(),s=e.managedClasses,a=assert(e.visitInstance);r.compileFunction(a,!0);var o=new Array,l=new Array,p=0;for(let _=Map_keys(s),f=0,E=_.length;f0)for(let o=Map_values(a),l=0,p=o.length;l0){if(i.length>1)return e.error(2558,r.reportNode.typeArgumentsRange,"1",i.length.toString()),null;ui=e.compileExpression(t[0],i[0],1)}else ui=e.compileExpression(t[0],u.auto);return e.currentType}return i&&i.length>1&&e.error(2558,r.reportNode.typeArgumentsRange,"1",i.length.toString()),e.error(2554,r.reportNode.argumentsRange,"1",t.length.toString()),null}function be(r,e){var t=r.compiler.module;return ui&&zs(ui,t.ref)&&(e=t.block(null,[t.maybeDrop(ui),e],oe(e))),e}function Ke(r,e){var t=e.module,i;if(e.options.isWasm64){let n=e.compileExpression(r,u.usize64,1),s=t.runExpression(n,1);s?(assert($e(s)==0),i=Be(s)):(e.error(220,r.range),i=-1)}else{let n=e.compileExpression(r,u.usize32,1),s=t.runExpression(n,1);s?i=ie(s):(e.error(220,r.range),i=-1)}return i}function vt(r,e,t){var i=Ke(r,t);return i<0?i:i<1||e>16?(t.error(222,r.range,"Alignment","1",e.toString()),-1):ht(i)?i:(t.error(223,r.range,"Alignment"),-1)}function X(r,e){var t=r.compiler;return t.options.hasFeature(e)?0:(t.error(103,r.reportNode.range,wr(e)),1)}function K(r,e=!1){var t=r.compiler,i=r.typeArguments;if(i){let n=i.length;if(n==1)return 0;assert(n),e&&(t.currentType=i[0]),t.error(2558,r.reportNode.typeArgumentsRange,"1",n.toString())}else t.error(2558,r.reportNode.range,"1","0");return 1}function ae(r,e=!1){var t=r.typeArguments;if(t){let i=r.compiler,n=t.length;return n==1?0:(assert(n),e&&(i.currentType=t[0]),i.error(2558,r.reportNode.typeArgumentsRange,"1",n.toString()),1)}return 0}function T(r){var e=r.typeArguments;if(e){let t=r.prototype;return t.program.error(2315,r.reportNode.typeArgumentsRange,t.internalName),1}return 0}function W(r,e){var t=r.operands;return t.length!=e?(r.compiler.error(2554,r.reportNode.range,e.toString(),t.length.toString()),1):0}function Ee(r,e,t){var i=r.operands,n=i.length;return nt?(r.compiler.error(2554,r.reportNode.range,t.toString(),n.toString()),1):0}function Gs(r,e,t){var i=r.module;if(t!=u.auto&&t.isIntegerValue)switch(t.kind){case 2:{if(i64_is_i32(e))return r.currentType=u.i32,i.i32(i64_low(e));break}case 7:{if(i64_is_u32(e))return r.currentType=u.u32,i.i32(i64_low(e));break}case 3:case 8:return r.currentType=t,i.i64(i64_low(e),i64_high(e))}return r.options.isWasm64?(r.currentType=u.usize64,i.i64(i64_low(e),i64_high(e))):(r.currentType=u.usize32,assert(!i64_high(e)),i.i32(i64_low(e)))}var C;(g=>(g.None=0,g.Unreachable=1,g.I32=2,g.I64=3,g.F32=4,g.F64=5,g.V128=6,g.Funcref=7,g.Externref=8,g.Anyref=9,g.Eqref=10,g.I31ref=11,g.Dataref=12,g.Auto=-1))(C||={});var jl=(v=>(v[v.MVP=0]="MVP",v[v.Atomics=1]="Atomics",v[v.MutableGlobals=2]="MutableGlobals",v[v.TruncSat=4]="TruncSat",v[v.SIMD=8]="SIMD",v[v.BulkMemory=16]="BulkMemory",v[v.SignExt=32]="SignExt",v[v.ExceptionHandling=64]="ExceptionHandling",v[v.TailCall=128]="TailCall",v[v.ReferenceTypes=256]="ReferenceTypes",v[v.MultiValue=512]="MultiValue",v[v.GC=1024]="GC",v[v.Memory64=2048]="Memory64",v[v.FunctionReferences=4096]="FunctionReferences",v[v.RelaxedSIMD=16384]="RelaxedSIMD",v[v.ExtendedConst=32768]="ExtendedConst",v[v.All=65535]="All",v))(jl||{}),nr=(M=>(M[M.Invalid=0]="Invalid",M[M.Block=1]="Block",M[M.If=2]="If",M[M.Loop=3]="Loop",M[M.Break=4]="Break",M[M.Switch=5]="Switch",M[M.Call=6]="Call",M[M.CallIndirect=7]="CallIndirect",M[M.LocalGet=8]="LocalGet",M[M.LocalSet=9]="LocalSet",M[M.GlobalGet=10]="GlobalGet",M[M.GlobalSet=11]="GlobalSet",M[M.Load=12]="Load",M[M.Store=13]="Store",M[M.Const=14]="Const",M[M.Unary=15]="Unary",M[M.Binary=16]="Binary",M[M.Select=17]="Select",M[M.Drop=18]="Drop",M[M.Return=19]="Return",M[M.MemorySize=20]="MemorySize",M[M.MemoryGrow=21]="MemoryGrow",M[M.Nop=22]="Nop",M[M.Unreachable=23]="Unreachable",M[M.AtomicRMW=24]="AtomicRMW",M[M.AtomicCmpxchg=25]="AtomicCmpxchg",M[M.AtomicWait=26]="AtomicWait",M[M.AtomicNotify=27]="AtomicNotify",M[M.AtomicFence=28]="AtomicFence",M[M.SIMDExtract=29]="SIMDExtract",M[M.SIMDReplace=30]="SIMDReplace",M[M.SIMDShuffle=31]="SIMDShuffle",M[M.SIMDTernary=32]="SIMDTernary",M[M.SIMDShift=33]="SIMDShift",M[M.SIMDLoad=34]="SIMDLoad",M[M.SIMDLoadStoreLane=35]="SIMDLoadStoreLane",M[M.MemoryInit=36]="MemoryInit",M[M.DataDrop=37]="DataDrop",M[M.MemoryCopy=38]="MemoryCopy",M[M.MemoryFill=39]="MemoryFill",M[M.Pop=40]="Pop",M[M.RefNull=41]="RefNull",M[M.RefIs=42]="RefIs",M[M.RefFunc=43]="RefFunc",M[M.RefEq=44]="RefEq",M[M.TableGet=45]="TableGet",M[M.TableSet=46]="TableSet",M[M.TableSize=47]="TableSize",M[M.TableGrow=48]="TableGrow",M[M.Try=49]="Try",M[M.Throw=50]="Throw",M[M.Rethrow=51]="Rethrow",M[M.TupleMake=52]="TupleMake",M[M.TupleExtract=53]="TupleExtract",M[M.I31New=54]="I31New",M[M.I31Get=55]="I31Get",M[M.CallRef=56]="CallRef",M[M.RefTest=57]="RefTest",M[M.RefCast=58]="RefCast",M[M.BrOn=59]="BrOn",M[M.RttCanon=60]="RttCanon",M[M.RttSub=61]="RttSub",M[M.StructNew=62]="StructNew",M[M.StructGet=63]="StructGet",M[M.StructSet=64]="StructSet",M[M.ArrayNew=65]="ArrayNew",M[M.ArrayInit=66]="ArrayInit",M[M.ArrayGet=67]="ArrayGet",M[M.ArraySet=68]="ArraySet",M[M.ArrayLen=69]="ArrayLen",M[M.ArrayCopy=70]="ArrayCopy",M[M.RefAs=71]="RefAs",M))(nr||{}),Xl=(s=>(s[s.Function=0]="Function",s[s.Table=1]="Table",s[s.Memory=2]="Memory",s[s.Global=3]="Global",s[s.Tag=4]="Tag",s))(Xl||{}),Ji=(R=>(R[R.ClzI32=0]="ClzI32",R[R.ClzI64=1]="ClzI64",R[R.CtzI32=2]="CtzI32",R[R.CtzI64=3]="CtzI64",R[R.PopcntI32=4]="PopcntI32",R[R.PopcntI64=5]="PopcntI64",R[R.NegF32=6]="NegF32",R[R.NegF64=7]="NegF64",R[R.AbsF32=8]="AbsF32",R[R.AbsF64=9]="AbsF64",R[R.CeilF32=10]="CeilF32",R[R.CeilF64=11]="CeilF64",R[R.FloorF32=12]="FloorF32",R[R.FloorF64=13]="FloorF64",R[R.TruncF32=14]="TruncF32",R[R.TruncF64=15]="TruncF64",R[R.NearestF32=16]="NearestF32",R[R.NearestF64=17]="NearestF64",R[R.SqrtF32=18]="SqrtF32",R[R.SqrtF64=19]="SqrtF64",R[R.EqzI32=20]="EqzI32",R[R.EqzI64=21]="EqzI64",R[R.ExtendI32ToI64=22]="ExtendI32ToI64",R[R.ExtendU32ToU64=23]="ExtendU32ToU64",R[R.WrapI64ToI32=24]="WrapI64ToI32",R[R.TruncF32ToI32=25]="TruncF32ToI32",R[R.TruncF32ToI64=26]="TruncF32ToI64",R[R.TruncF32ToU32=27]="TruncF32ToU32",R[R.TruncF32ToU64=28]="TruncF32ToU64",R[R.TruncF64ToI32=29]="TruncF64ToI32",R[R.TruncF64ToI64=30]="TruncF64ToI64",R[R.TruncF64ToU32=31]="TruncF64ToU32",R[R.TruncF64ToU64=32]="TruncF64ToU64",R[R.ReinterpretF32ToI32=33]="ReinterpretF32ToI32",R[R.ReinterpretF64ToI64=34]="ReinterpretF64ToI64",R[R.ConvertI32ToF32=35]="ConvertI32ToF32",R[R.ConvertI32ToF64=36]="ConvertI32ToF64",R[R.ConvertU32ToF32=37]="ConvertU32ToF32",R[R.ConvertU32ToF64=38]="ConvertU32ToF64",R[R.ConvertI64ToF32=39]="ConvertI64ToF32",R[R.ConvertI64ToF64=40]="ConvertI64ToF64",R[R.ConvertU64ToF32=41]="ConvertU64ToF32",R[R.ConvertU64ToF64=42]="ConvertU64ToF64",R[R.PromoteF32ToF64=43]="PromoteF32ToF64",R[R.DemoteF64ToF32=44]="DemoteF64ToF32",R[R.ReinterpretI32ToF32=45]="ReinterpretI32ToF32",R[R.ReinterpretI64ToF64=46]="ReinterpretI64ToF64",R[R.Extend8I32=47]="Extend8I32",R[R.Extend16I32=48]="Extend16I32",R[R.Extend8I64=49]="Extend8I64",R[R.Extend16I64=50]="Extend16I64",R[R.Extend32I64=51]="Extend32I64",R[R.TruncSatF32ToI32=52]="TruncSatF32ToI32",R[R.TruncSatF32ToU32=53]="TruncSatF32ToU32",R[R.TruncSatF64ToI32=54]="TruncSatF64ToI32",R[R.TruncSatF64ToU32=55]="TruncSatF64ToU32",R[R.TruncSatF32ToI64=56]="TruncSatF32ToI64",R[R.TruncSatF32ToU64=57]="TruncSatF32ToU64",R[R.TruncSatF64ToI64=58]="TruncSatF64ToI64",R[R.TruncSatF64ToU64=59]="TruncSatF64ToU64",R[R.SplatI8x16=60]="SplatI8x16",R[R.SplatI16x8=61]="SplatI16x8",R[R.SplatI32x4=62]="SplatI32x4",R[R.SplatI64x2=63]="SplatI64x2",R[R.SplatF32x4=64]="SplatF32x4",R[R.SplatF64x2=65]="SplatF64x2",R[R.NotV128=66]="NotV128",R[R.AnyTrueV128=67]="AnyTrueV128",R[R.AbsI8x16=68]="AbsI8x16",R[R.NegI8x16=69]="NegI8x16",R[R.AllTrueI8x16=70]="AllTrueI8x16",R[R.BitmaskI8x16=71]="BitmaskI8x16",R[R.PopcntI8x16=72]="PopcntI8x16",R[R.AbsI16x8=73]="AbsI16x8",R[R.NegI16x8=74]="NegI16x8",R[R.AllTrueI16x8=75]="AllTrueI16x8",R[R.BitmaskI16x8=76]="BitmaskI16x8",R[R.AbsI32x4=77]="AbsI32x4",R[R.NegI32x4=78]="NegI32x4",R[R.AllTrueI32x4=79]="AllTrueI32x4",R[R.BitmaskI32x4=80]="BitmaskI32x4",R[R.AbsI64x2=81]="AbsI64x2",R[R.NegI64x2=82]="NegI64x2",R[R.AllTrueI64x2=83]="AllTrueI64x2",R[R.BitmaskI64x2=84]="BitmaskI64x2",R[R.AbsF32x4=85]="AbsF32x4",R[R.NegF32x4=86]="NegF32x4",R[R.SqrtF32x4=87]="SqrtF32x4",R[R.CeilF32x4=88]="CeilF32x4",R[R.FloorF32x4=89]="FloorF32x4",R[R.TruncF32x4=90]="TruncF32x4",R[R.NearestF32x4=91]="NearestF32x4",R[R.AbsF64x2=92]="AbsF64x2",R[R.NegF64x2=93]="NegF64x2",R[R.SqrtF64x2=94]="SqrtF64x2",R[R.CeilF64x2=95]="CeilF64x2",R[R.FloorF64x2=96]="FloorF64x2",R[R.TruncF64x2=97]="TruncF64x2",R[R.NearestF64x2=98]="NearestF64x2",R[R.ExtaddPairwiseI8x16ToI16x8=99]="ExtaddPairwiseI8x16ToI16x8",R[R.ExtaddPairwiseU8x16ToU16x8=100]="ExtaddPairwiseU8x16ToU16x8",R[R.ExtaddPairwiseI16x8ToI32x4=101]="ExtaddPairwiseI16x8ToI32x4",R[R.ExtaddPairwiseU16x8ToU32x4=102]="ExtaddPairwiseU16x8ToU32x4",R[R.TruncSatF32x4ToI32x4=103]="TruncSatF32x4ToI32x4",R[R.TruncSatF32x4ToU32x4=104]="TruncSatF32x4ToU32x4",R[R.ConvertI32x4ToF32x4=105]="ConvertI32x4ToF32x4",R[R.ConvertU32x4ToF32x4=106]="ConvertU32x4ToF32x4",R[R.ExtendLowI8x16ToI16x8=107]="ExtendLowI8x16ToI16x8",R[R.ExtendHighI8x16ToI16x8=108]="ExtendHighI8x16ToI16x8",R[R.ExtendLowU8x16ToU16x8=109]="ExtendLowU8x16ToU16x8",R[R.ExtendHighU8x16ToU16x8=110]="ExtendHighU8x16ToU16x8",R[R.ExtendLowI16x8ToI32x4=111]="ExtendLowI16x8ToI32x4",R[R.ExtendHighI16x8ToI32x4=112]="ExtendHighI16x8ToI32x4",R[R.ExtendLowU16x8ToU32x4=113]="ExtendLowU16x8ToU32x4",R[R.ExtendHighU16x8ToU32x4=114]="ExtendHighU16x8ToU32x4",R[R.ExtendLowI32x4ToI64x2=115]="ExtendLowI32x4ToI64x2",R[R.ExtendHighI32x4ToI64x2=116]="ExtendHighI32x4ToI64x2",R[R.ExtendLowU32x4ToU64x2=117]="ExtendLowU32x4ToU64x2",R[R.ExtendHighU32x4ToU64x2=118]="ExtendHighU32x4ToU64x2",R[R.ConvertLowI32x4ToF64x2=119]="ConvertLowI32x4ToF64x2",R[R.ConvertLowU32x4ToF64x2=120]="ConvertLowU32x4ToF64x2",R[R.TruncSatF64x2ToI32x4Zero=121]="TruncSatF64x2ToI32x4Zero",R[R.TruncSatF64x2ToU32x4Zero=122]="TruncSatF64x2ToU32x4Zero",R[R.DemoteZeroF64x2ToF32x4=123]="DemoteZeroF64x2ToF32x4",R[R.PromoteLowF32x4ToF64x2=124]="PromoteLowF32x4ToF64x2",R[R._last=124]="_last",R[R.ClzSize=125]="ClzSize",R[R.CtzSize=126]="CtzSize",R[R.PopcntSize=127]="PopcntSize",R[R.EqzSize=128]="EqzSize",R))(Ji||{}),$r=(y=>(y[y.AddI32=0]="AddI32",y[y.SubI32=1]="SubI32",y[y.MulI32=2]="MulI32",y[y.DivI32=3]="DivI32",y[y.DivU32=4]="DivU32",y[y.RemI32=5]="RemI32",y[y.RemU32=6]="RemU32",y[y.AndI32=7]="AndI32",y[y.OrI32=8]="OrI32",y[y.XorI32=9]="XorI32",y[y.ShlI32=10]="ShlI32",y[y.ShrI32=11]="ShrI32",y[y.ShrU32=12]="ShrU32",y[y.RotlI32=13]="RotlI32",y[y.RotrI32=14]="RotrI32",y[y.EqI32=15]="EqI32",y[y.NeI32=16]="NeI32",y[y.LtI32=17]="LtI32",y[y.LtU32=18]="LtU32",y[y.LeI32=19]="LeI32",y[y.LeU32=20]="LeU32",y[y.GtI32=21]="GtI32",y[y.GtU32=22]="GtU32",y[y.GeI32=23]="GeI32",y[y.GeU32=24]="GeU32",y[y.AddI64=25]="AddI64",y[y.SubI64=26]="SubI64",y[y.MulI64=27]="MulI64",y[y.DivI64=28]="DivI64",y[y.DivU64=29]="DivU64",y[y.RemI64=30]="RemI64",y[y.RemU64=31]="RemU64",y[y.AndI64=32]="AndI64",y[y.OrI64=33]="OrI64",y[y.XorI64=34]="XorI64",y[y.ShlI64=35]="ShlI64",y[y.ShrI64=36]="ShrI64",y[y.ShrU64=37]="ShrU64",y[y.RotlI64=38]="RotlI64",y[y.RotrI64=39]="RotrI64",y[y.EqI64=40]="EqI64",y[y.NeI64=41]="NeI64",y[y.LtI64=42]="LtI64",y[y.LtU64=43]="LtU64",y[y.LeI64=44]="LeI64",y[y.LeU64=45]="LeU64",y[y.GtI64=46]="GtI64",y[y.GtU64=47]="GtU64",y[y.GeI64=48]="GeI64",y[y.GeU64=49]="GeU64",y[y.AddF32=50]="AddF32",y[y.SubF32=51]="SubF32",y[y.MulF32=52]="MulF32",y[y.DivF32=53]="DivF32",y[y.CopysignF32=54]="CopysignF32",y[y.MinF32=55]="MinF32",y[y.MaxF32=56]="MaxF32",y[y.EqF32=57]="EqF32",y[y.NeF32=58]="NeF32",y[y.LtF32=59]="LtF32",y[y.LeF32=60]="LeF32",y[y.GtF32=61]="GtF32",y[y.GeF32=62]="GeF32",y[y.AddF64=63]="AddF64",y[y.SubF64=64]="SubF64",y[y.MulF64=65]="MulF64",y[y.DivF64=66]="DivF64",y[y.CopysignF64=67]="CopysignF64",y[y.MinF64=68]="MinF64",y[y.MaxF64=69]="MaxF64",y[y.EqF64=70]="EqF64",y[y.NeF64=71]="NeF64",y[y.LtF64=72]="LtF64",y[y.LeF64=73]="LeF64",y[y.GtF64=74]="GtF64",y[y.GeF64=75]="GeF64",y[y.EqI8x16=76]="EqI8x16",y[y.NeI8x16=77]="NeI8x16",y[y.LtI8x16=78]="LtI8x16",y[y.LtU8x16=79]="LtU8x16",y[y.GtI8x16=80]="GtI8x16",y[y.GtU8x16=81]="GtU8x16",y[y.LeI8x16=82]="LeI8x16",y[y.LeU8x16=83]="LeU8x16",y[y.GeI8x16=84]="GeI8x16",y[y.GeU8x16=85]="GeU8x16",y[y.EqI16x8=86]="EqI16x8",y[y.NeI16x8=87]="NeI16x8",y[y.LtI16x8=88]="LtI16x8",y[y.LtU16x8=89]="LtU16x8",y[y.GtI16x8=90]="GtI16x8",y[y.GtU16x8=91]="GtU16x8",y[y.LeI16x8=92]="LeI16x8",y[y.LeU16x8=93]="LeU16x8",y[y.GeI16x8=94]="GeI16x8",y[y.GeU16x8=95]="GeU16x8",y[y.EqI32x4=96]="EqI32x4",y[y.NeI32x4=97]="NeI32x4",y[y.LtI32x4=98]="LtI32x4",y[y.LtU32x4=99]="LtU32x4",y[y.GtI32x4=100]="GtI32x4",y[y.GtU32x4=101]="GtU32x4",y[y.LeI32x4=102]="LeI32x4",y[y.LeU32x4=103]="LeU32x4",y[y.GeI32x4=104]="GeI32x4",y[y.GeU32x4=105]="GeU32x4",y[y.EqI64x2=106]="EqI64x2",y[y.NeI64x2=107]="NeI64x2",y[y.LtI64x2=108]="LtI64x2",y[y.GtI64x2=109]="GtI64x2",y[y.LeI64x2=110]="LeI64x2",y[y.GeI64x2=111]="GeI64x2",y[y.EqF32x4=112]="EqF32x4",y[y.NeF32x4=113]="NeF32x4",y[y.LtF32x4=114]="LtF32x4",y[y.GtF32x4=115]="GtF32x4",y[y.LeF32x4=116]="LeF32x4",y[y.GeF32x4=117]="GeF32x4",y[y.EqF64x2=118]="EqF64x2",y[y.NeF64x2=119]="NeF64x2",y[y.LtF64x2=120]="LtF64x2",y[y.GtF64x2=121]="GtF64x2",y[y.LeF64x2=122]="LeF64x2",y[y.GeF64x2=123]="GeF64x2",y[y.AndV128=124]="AndV128",y[y.OrV128=125]="OrV128",y[y.XorV128=126]="XorV128",y[y.AndnotV128=127]="AndnotV128",y[y.AddI8x16=128]="AddI8x16",y[y.AddSatI8x16=129]="AddSatI8x16",y[y.AddSatU8x16=130]="AddSatU8x16",y[y.SubI8x16=131]="SubI8x16",y[y.SubSatI8x16=132]="SubSatI8x16",y[y.SubSatU8x16=133]="SubSatU8x16",y[y.MinI8x16=134]="MinI8x16",y[y.MinU8x16=135]="MinU8x16",y[y.MaxI8x16=136]="MaxI8x16",y[y.MaxU8x16=137]="MaxU8x16",y[y.AvgrU8x16=138]="AvgrU8x16",y[y.AddI16x8=139]="AddI16x8",y[y.AddSatI16x8=140]="AddSatI16x8",y[y.AddSatU16x8=141]="AddSatU16x8",y[y.SubI16x8=142]="SubI16x8",y[y.SubSatI16x8=143]="SubSatI16x8",y[y.SubSatU16x8=144]="SubSatU16x8",y[y.MulI16x8=145]="MulI16x8",y[y.MinI16x8=146]="MinI16x8",y[y.MinU16x8=147]="MinU16x8",y[y.MaxI16x8=148]="MaxI16x8",y[y.MaxU16x8=149]="MaxU16x8",y[y.AvgrU16x8=150]="AvgrU16x8",y[y.Q15mulrSatI16x8=151]="Q15mulrSatI16x8",y[y.ExtmulLowI16x8=152]="ExtmulLowI16x8",y[y.ExtmulHighI16x8=153]="ExtmulHighI16x8",y[y.ExtmulLowU16x8=154]="ExtmulLowU16x8",y[y.ExtmulHighU16x8=155]="ExtmulHighU16x8",y[y.AddI32x4=156]="AddI32x4",y[y.SubI32x4=157]="SubI32x4",y[y.MulI32x4=158]="MulI32x4",y[y.MinI32x4=159]="MinI32x4",y[y.MinU32x4=160]="MinU32x4",y[y.MaxI32x4=161]="MaxI32x4",y[y.MaxU32x4=162]="MaxU32x4",y[y.DotI16x8=163]="DotI16x8",y[y.ExtmulLowI32x4=164]="ExtmulLowI32x4",y[y.ExtmulHighI32x4=165]="ExtmulHighI32x4",y[y.ExtmulLowU32x4=166]="ExtmulLowU32x4",y[y.ExtmulHighU32x4=167]="ExtmulHighU32x4",y[y.AddI64x2=168]="AddI64x2",y[y.SubI64x2=169]="SubI64x2",y[y.MulI64x2=170]="MulI64x2",y[y.ExtmulLowI64x2=171]="ExtmulLowI64x2",y[y.ExtmulHighI64x2=172]="ExtmulHighI64x2",y[y.ExtmulLowU64x2=173]="ExtmulLowU64x2",y[y.ExtmulHighU64x2=174]="ExtmulHighU64x2",y[y.AddF32x4=175]="AddF32x4",y[y.SubF32x4=176]="SubF32x4",y[y.MulF32x4=177]="MulF32x4",y[y.DivF32x4=178]="DivF32x4",y[y.MinF32x4=179]="MinF32x4",y[y.MaxF32x4=180]="MaxF32x4",y[y.PminF32x4=181]="PminF32x4",y[y.PmaxF32x4=182]="PmaxF32x4",y[y.AddF64x2=183]="AddF64x2",y[y.SubF64x2=184]="SubF64x2",y[y.MulF64x2=185]="MulF64x2",y[y.DivF64x2=186]="DivF64x2",y[y.MinF64x2=187]="MinF64x2",y[y.MaxF64x2=188]="MaxF64x2",y[y.PminF64x2=189]="PminF64x2",y[y.PmaxF64x2=190]="PmaxF64x2",y[y.NarrowI16x8ToI8x16=191]="NarrowI16x8ToI8x16",y[y.NarrowU16x8ToU8x16=192]="NarrowU16x8ToU8x16",y[y.NarrowI32x4ToI16x8=193]="NarrowI32x4ToI16x8",y[y.NarrowU32x4ToU16x8=194]="NarrowU32x4ToU16x8",y[y.SwizzleI8x16=195]="SwizzleI8x16",y[y._last=195]="_last",y[y.AddSize=196]="AddSize",y[y.SubSize=197]="SubSize",y[y.MulSize=198]="MulSize",y[y.DivISize=199]="DivISize",y[y.DivUSize=200]="DivUSize",y[y.RemISize=201]="RemISize",y[y.RemUSize=202]="RemUSize",y[y.AndSize=203]="AndSize",y[y.OrSize=204]="OrSize",y[y.XorSize=205]="XorSize",y[y.ShlSize=206]="ShlSize",y[y.ShrISize=207]="ShrISize",y[y.ShrUSize=208]="ShrUSize",y[y.RotlSize=209]="RotlSize",y[y.RotrSize=210]="RotrSize",y[y.EqSize=211]="EqSize",y[y.NeSize=212]="NeSize",y[y.LtISize=213]="LtISize",y[y.LtUSize=214]="LtUSize",y[y.LeISize=215]="LeISize",y[y.LeUSize=216]="LeUSize",y[y.GtISize=217]="GtISize",y[y.GtUSize=218]="GtUSize",y[y.GeISize=219]="GeISize",y[y.GeUSize=220]="GeUSize",y))($r||{}),Cu=(a=>(a[a.Add=0]="Add",a[a.Sub=1]="Sub",a[a.And=2]="And",a[a.Or=3]="Or",a[a.Xor=4]="Xor",a[a.Xchg=5]="Xchg",a))(Cu||{}),Fu=(l=>(l[l.ExtractLaneI8x16=0]="ExtractLaneI8x16",l[l.ExtractLaneU8x16=1]="ExtractLaneU8x16",l[l.ExtractLaneI16x8=2]="ExtractLaneI16x8",l[l.ExtractLaneU16x8=3]="ExtractLaneU16x8",l[l.ExtractLaneI32x4=4]="ExtractLaneI32x4",l[l.ExtractLaneI64x2=5]="ExtractLaneI64x2",l[l.ExtractLaneF32x4=6]="ExtractLaneF32x4",l[l.ExtractLaneF64x2=7]="ExtractLaneF64x2",l))(Fu||{}),ku=(a=>(a[a.ReplaceLaneI8x16=0]="ReplaceLaneI8x16",a[a.ReplaceLaneI16x8=1]="ReplaceLaneI16x8",a[a.ReplaceLaneI32x4=2]="ReplaceLaneI32x4",a[a.ReplaceLaneI64x2=3]="ReplaceLaneI64x2",a[a.ReplaceLaneF32x4=4]="ReplaceLaneF32x4",a[a.ReplaceLaneF64x2=5]="ReplaceLaneF64x2",a))(ku||{}),Pu=(f=>(f[f.ShlI8x16=0]="ShlI8x16",f[f.ShrI8x16=1]="ShrI8x16",f[f.ShrU8x16=2]="ShrU8x16",f[f.ShlI16x8=3]="ShlI16x8",f[f.ShrI16x8=4]="ShrI16x8",f[f.ShrU16x8=5]="ShrU16x8",f[f.ShlI32x4=6]="ShlI32x4",f[f.ShrI32x4=7]="ShrI32x4",f[f.ShrU32x4=8]="ShrU32x4",f[f.ShlI64x2=9]="ShlI64x2",f[f.ShrI64x2=10]="ShrI64x2",f[f.ShrU64x2=11]="ShrU64x2",f))(Pu||{}),Ou=(f=>(f[f.Load8Splat=0]="Load8Splat",f[f.Load16Splat=1]="Load16Splat",f[f.Load32Splat=2]="Load32Splat",f[f.Load64Splat=3]="Load64Splat",f[f.Load8x8S=4]="Load8x8S",f[f.Load8x8U=5]="Load8x8U",f[f.Load16x4S=6]="Load16x4S",f[f.Load16x4U=7]="Load16x4U",f[f.Load32x2S=8]="Load32x2S",f[f.Load32x2U=9]="Load32x2U",f[f.Load32Zero=10]="Load32Zero",f[f.Load64Zero=11]="Load64Zero",f))(Ou||{}),wu=(l=>(l[l.Load8Lane=0]="Load8Lane",l[l.Load16Lane=1]="Load16Lane",l[l.Load32Lane=2]="Load32Lane",l[l.Load64Lane=3]="Load64Lane",l[l.Store8Lane=4]="Store8Lane",l[l.Store16Lane=5]="Store16Lane",l[l.Store32Lane=6]="Store32Lane",l[l.Store64Lane=7]="Store64Lane",l))(wu||{}),Mu=(e=>(e[e.Bitselect=0]="Bitselect",e))(Mu||{}),Ms=(n=>(n[n.RefIsNull=0]="RefIsNull",n[n.RefIsFunc=1]="RefIsFunc",n[n.RefIsData=2]="RefIsData",n[n.RefIsI31=3]="RefIsI31",n))(Ms||{}),jc=(n=>(n[n.RefAsNonNull=0]="RefAsNonNull",n[n.RefAsFunc=1]="RefAsFunc",n[n.RefAsData=2]="RefAsData",n[n.RefAsI31=3]="RefAsI31",n))(jc||{}),Jc=(s=>(s[s.BrOnNull=0]="BrOnNull",s[s.BrOnCast=1]="BrOnCast",s[s.BrOnFunc=2]="BrOnFunc",s[s.BrOnData=3]="BrOnData",s[s.BrOnI31=4]="BrOnI31",s))(Jc||{}),Us=(i=>(i[i.Default=0]="Default",i[i.PreserveSideeffects=1]="PreserveSideeffects",i[i.TraverseCalls=2]="TraverseCalls",i))(Us||{}),un=class{constructor(e,t){this.buffer=e;this.offset=t}},Ys=class{constructor(e,t,i){this.ref=e;this.useShadowStack=t;this.sizeType=i;this.hasTemporaryFunction=!1;this.cachedStringsToPointers=new Map;this.cachedPointersToStrings=new Map;assert(i==C.I32||i==C.I64),this.lit=Nt(Uu())}static create(e,t){return new Ys(r_(),e,t)}static createFrom(e,t,i){var n=An(e),s=new Ys(nh(n,e.length),t,i);return ne(changetype(n)),s}i32(e){var t=this.lit;return n_(t,e),_i(this.ref,t)}i64(e,t=0){var i=this.lit;return s_(i,e,t),_i(this.ref,i)}usize(e){return i64_is(e)?this.sizeType==C.I64?this.i64(i64_low(e),i64_high(e)):(assert(i64_is_u32(e)),this.i32(i64_low(e))):this.sizeType==C.I64?this.i64(i32(e)):this.i32(i32(e))}f32(e){var t=this.lit;return a_(t,e),_i(this.ref,t)}f64(e){var t=this.lit;return o_(t,e),_i(this.ref,t)}v128(e){assert(e.length==16);var t=this.lit;for(let i=0;i<16;++i)Ae(t+i,e[i]);return l_(t,t),_i(this.ref,t)}ref_null(e){return lf(this.ref,e)}ref_eq(e,t){return _f(this.ref,e,t)}unary(e,t){if(e>124){let i=this.sizeType==C.I64;switch(e){case 125:return this.unary(i?1:0,t);case 126:return this.unary(i?3:2,t);case 127:return this.unary(i?5:4,t);case 128:return this.unary(i?21:20,t)}assert(!1)}return B_(this.ref,e,t)}binary(e,t,i){if(e>195){let n=this.sizeType==C.I64;switch(e){case 196:return this.binary(n?25:0,t,i);case 197:return this.binary(n?26:1,t,i);case 198:return this.binary(n?27:2,t,i);case 199:return this.binary(n?28:3,t,i);case 200:return this.binary(n?29:4,t,i);case 201:return this.binary(n?30:5,t,i);case 202:return this.binary(n?31:6,t,i);case 203:return this.binary(n?32:7,t,i);case 204:return this.binary(n?33:8,t,i);case 205:return this.binary(n?34:9,t,i);case 206:return this.binary(n?35:10,t,i);case 207:return this.binary(n?36:11,t,i);case 208:return this.binary(n?37:12,t,i);case 209:return this.binary(n?38:13,t,i);case 210:return this.binary(n?39:14,t,i);case 211:return this.binary(n?40:15,t,i);case 212:return this.binary(n?41:16,t,i);case 213:return this.binary(n?42:17,t,i);case 214:return this.binary(n?43:18,t,i);case 215:return this.binary(n?44:19,t,i);case 216:return this.binary(n?45:20,t,i);case 217:return this.binary(n?46:21,t,i);case 218:return this.binary(n?47:22,t,i);case 219:return this.binary(n?48:23,t,i);case 220:return this.binary(n?49:24,t,i)}assert(!1)}return V_(this.ref,e,t,i)}memory_size(){return x_(this.ref)}memory_grow(e){return S_(this.ref,e)}table_size(e){var t=this.allocStringCached(e);return mf(this.ref,t)}table_grow(e,t,i=0){var n=this.allocStringCached(e);return df(this.ref,n,i,t)}local_get(e,t){return g_(this.ref,e,t)}tostack(e){if(this.useShadowStack){let t=It(e);return assert(t==C.I32||t==C.Unreachable),this.call(h.tostack,[e],t)}return e}local_tee(e,t,i,n=C.Auto){return n==C.Auto&&(n=It(t)),i&&this.useShadowStack&&(t=this.tostack(t)),b_(this.ref,e,t,n)}global_get(e,t){var i=this.allocStringCached(e);return I_(this.ref,i,t)}table_get(e,t,i){var n=this.allocStringCached(e);return ff(this.ref,n,t,i)}load(e,t,i,n,s=0,a=e){return R_(this.ref,e,t,s,a,n,i)}store(e,t,i,n,s=0,a=e){return F_(this.ref,e,s,a,t,i,n)}atomic_load(e,t,i,n=0){return C_(this.ref,e,n,i,t)}atomic_store(e,t,i,n,s=0){return k_(this.ref,e,s,t,i,n)}atomic_rmw(e,t,i,n,s,a){return K_(this.ref,e,t,i,n,s,a)}atomic_cmpxchg(e,t,i,n,s,a){return q_(this.ref,e,t,i,n,s,a)}atomic_wait(e,t,i,n){return Q_(this.ref,e,t,i,n)}atomic_notify(e,t){return Z_(this.ref,e,t)}atomic_fence(){return j_(this.ref)}local_set(e,t,i){return i&&this.useShadowStack&&(t=this.tostack(t)),T_(this.ref,e,t)}global_set(e,t){var i=this.allocStringCached(e);return v_(this.ref,i,t)}table_set(e,t,i){var n=this.allocStringCached(e);return hf(this.ref,n,t,i)}block(e,t,i=C.None){var n=this.allocStringCached(e),s=me(t),a=p_(this.ref,n,s,t.length,i);return ne(s),a}flatten(e,t=C.None){var i=e.length;if(i==0)return this.nop();if(i==1){let n=e[0];switch(te(n)){case 19:case 50:case 23:return n}let s=oe(n);return s!=C.Unreachable&&s!=t?this.unreachable():n}return this.block(null,e,t)}br(e,t=0,i=0){var n=this.allocStringCached(e);return f_(this.ref,n,t,i)}drop(e){return Du(this.ref,e)}maybeDrop(e){var t=It(e);return t!=C.None&&t!=C.Unreachable?Du(this.ref,e):e}maybeDropCondition(e,t){return(ai(e,this.ref)&~(pn.ReadsLocal|pn.ReadsGlobal))!=0?this.block(null,[this.drop(e),t],oe(t)):t}loop(e,t){var i=this.allocStringCached(e);return __(this.ref,i,t)}if(e,t,i=0){return c_(this.ref,e,t,i)}nop(){return H_(this.ref)}return(e=0){return Y_(this.ref,e)}select(e,t,i,n){return W_(this.ref,i,e,t,n)}switch(e,t,i,n=0){var s=e.length,a=new Array(s);for(let c=0;c=0;--v)ne(p[v])}addFunctionTable(e,t,i,n,s){var a=this.allocStringCached(e),o=n.length,l=new Array(o);for(let _=0;_=0;--a)ne(n[a])}optimize(e,t,i=!1,n=!1){if((e>=3||t>=2)&&(e=4),this.setOptimizeLevel(e),this.setShrinkLevel(t),this.setDebugInfo(i),this.setZeroFilledMemory(n),this.setFastMath(!0),this.clearPassArguments(),e>=2&&t==0?(this.setAlwaysInlineMaxSize(12),this.setFlexibleInlineMaxSize(70),this.setOneCallerInlineMaxSize(200),this.setAllowInliningFunctionsWithLoops(e>=3)):(this.setAlwaysInlineMaxSize(e<=1||t>=2?2:6),this.setFlexibleInlineMaxSize(65),this.setOneCallerInlineMaxSize(80),this.setAllowInliningFunctionsWithLoops(!1)),e>0||t>0){let s=new Array;s.push("duplicate-function-elimination"),s.push("remove-unused-module-elements"),e>=2&&(s.push("once-reduction"),s.push("inlining"),s.push("simplify-globals-optimizing")),(e>=3||t>=1)&&(s.push("rse"),s.push("vacuum"),s.push("code-folding"),s.push("ssa-nomerge"),s.push("local-cse"),s.push("remove-unused-brs"),s.push("remove-unused-names"),s.push("merge-blocks"),s.push("precompute-propagate"),s.push("simplify-globals-optimizing")),e>=3&&(s.push("simplify-locals-nostructure"),s.push("flatten"),s.push("vacuum"),s.push("simplify-locals-notee-nostructure"),s.push("vacuum"),s.push("licm"),s.push("merge-locals"),s.push("reorder-locals"),s.push("dae-optimizing")),s.push("optimize-instructions"),(e>=3||t>=1)&&s.push("dce"),s.push("remove-unused-brs"),s.push("remove-unused-names"),e>=3||t>=2?(s.push("inlining"),s.push("precompute-propagate"),s.push("simplify-globals-optimizing")):s.push("precompute"),(e>=2||t>=1)&&s.push("pick-load-signs"),s.push("simplify-locals-notee-nostructure"),s.push("vacuum"),(e>=2||t>=1)&&s.push("local-cse"),s.push("reorder-locals"),s.push("coalesce-locals"),s.push("simplify-locals"),s.push("coalesce-locals"),s.push("reorder-locals"),s.push("vacuum"),(e>=2||t>=1)&&(s.push("rse"),s.push("vacuum")),(e>=3||t>=1)&&(s.push("merge-locals"),s.push("vacuum")),(e>=2||t>=1)&&(s.push("simplify-globals-optimizing"),s.push("simplify-globals-optimizing")),s.push("remove-unused-brs"),s.push("remove-unused-names"),s.push("merge-blocks"),e>=3&&s.push("optimize-instructions"),(e>=2||t>=1)&&(s.push("simplify-globals-optimizing"),s.push("dae-optimizing")),(e>=2||t>=2)&&s.push("inlining-optimizing"),this.getLowMemoryUnused()&&(e>=3||t>=1?s.push("optimize-added-constants-propagate"):s.push("optimize-added-constants")),s.push("duplicate-import-elimination"),e>=2||t>=2?s.push("simplify-globals-optimizing"):(s.push("simplify-globals"),s.push("vacuum")),e>=2&&(this.getFeatures()&1024)!=0&&(s.push("heap2local"),s.push("merge-locals"),s.push("local-subtyping")),e>=2||t>=1?(s.push("precompute-propagate"),s.push("simplify-globals-optimizing"),s.push("simplify-globals-optimizing")):s.push("precompute"),s.push("directize"),s.push("dae-optimizing"),s.push("inlining-optimizing"),(e>=2||t>=1)&&(s.push("code-folding"),s.push("ssa-nomerge"),s.push("rse"),s.push("code-pushing"),e>=3&&(s.push("simplify-globals"),s.push("vacuum"),s.push("precompute-propagate"),s.push("inlining-optimizing"),s.push("directize"),s.push("dae-optimizing"),s.push("local-cse"),s.push("merge-locals"),s.push("coalesce-locals"),s.push("simplify-locals"),s.push("vacuum"),s.push("inlining"),s.push("precompute-propagate"),s.push("rse"),s.push("vacuum"),s.push("ssa-nomerge"),s.push("simplify-locals"),s.push("coalesce-locals")),s.push("remove-unused-brs"),s.push("remove-unused-names"),s.push("merge-blocks"),s.push("vacuum"),s.push("optimize-instructions"),s.push("simplify-globals-optimizing")),s.push("duplicate-function-elimination"),s.push("memory-packing"),s.push("remove-unused-module-elements"),this.runPasses(s)}}validate(){return th(this.ref)==1}interpret(){sh(this.ref)}toBinary(e=null){var t=this.lit;assert(Uu()>=12);var i=Ws(e),n=0,s=0;ih(t,this.ref,i),n=assert(Nn(t));var a=Nn(t+4);s=Nn(t+8);var o=new Bu(K2(n,a),Ve(s));return i&&ne(i),ne(n),s&&ne(s),o}toText(e=!0){throw new Error("not implemented")}allocStringCached(e){if(e==null)return 0;var t=this.cachedStringsToPointers;if(t.has(e))return changetype(t.get(e));var i=Ws(e);return t.set(e,i),i}readStringCached(e){if(e==0)return null;var t=this.cachedPointersToStrings;if(t.has(e))return changetype(t.get(e));var i=Ve(e);return t.set(e,i),i}dispose(){assert(this.ref);for(let e=Map_values(this.cachedStringsToPointers),t=0,i=e.length;t(v[v.None=0]="None",v[v.Branches=1]="Branches",v[v.Calls=2]="Calls",v[v.ReadsLocal=4]="ReadsLocal",v[v.WritesLocal=8]="WritesLocal",v[v.ReadsGlobal=16]="ReadsGlobal",v[v.WritesGlobal=32]="WritesGlobal",v[v.ReadsMemory=64]="ReadsMemory",v[v.WritesMemory=128]="WritesMemory",v[v.ReadsTable=256]="ReadsTable",v[v.WritesTable=512]="WritesTable",v[v.ImplicitTrap=1024]="ImplicitTrap",v[v.IsAtomic=2048]="IsAtomic",v[v.Throws=4096]="Throws",v[v.DanglingPop=8192]="DanglingPop",v[v.TrapsNeverHappen=16384]="TrapsNeverHappen",v[v.Any=32767]="Any",v))(pn||{});function ai(r,e){return ch(r,e)}function zs(r,e){return(ai(r,e)&-21)!=0}function An(r){if(!r)return 0;var e=r.length,t=Nt(e);for(let i=0;i>>0;n<=127?e+=1:n<=2047?e+=2:kr(n)&&t+1>>0,i=t;if(e==r.length)for(let n=0,s=r.length;n>>0;Ae(i++,a)}else for(let n=0,s=r.length;n>>0,o;a<=127?Ae(i++,a):a<=2047?(Ae(i++,192|a>>>6),Ae(i++,128|a&63)):kr(a)&&n+1>>18),Ae(i++,128|a>>>12&63),Ae(i++,128|a>>>6&63),Ae(i++,128|a&63)):(Ae(i++,224|a>>>12),Ae(i++,128|a>>>6&63),Ae(i++,128|a&63))}return Ae(i,0),t}function K2(r,e){var t=new Uint8Array(e);for(let i=0;i>>10),e.push(Fr|a&1023)}}return String.fromCharCodes(e)}var Bu=class{constructor(e,t){this.output=e;this.sourceMap=t}};function Bs(r){if(It(r)!=C.Unreachable)return!1;switch(nt(r)){case 23:case 19:return!1;case 4:return qr(r)!=0;case 1:if(!Fi(r)){let e=Xr(r);return e>0&&Bs(Kr(r,e-1))}}return!0}lt.prototype.toText=function(e=!0){return e?yi.wrapModule(this.ref).emitStackIR(!0):yi.wrapModule(this.ref).emitText()};var{_BinaryenTypeCreate:$c,_BinaryenTypeArity:e_,_BinaryenTypeExpand:t_,_BinaryenModuleCreate:r_,_BinaryenModuleDispose:i_,_BinaryenSizeofLiteral:Uu,_BinaryenLiteralInt32:n_,_BinaryenLiteralInt64:s_,_BinaryenLiteralFloat32:a_,_BinaryenLiteralFloat64:o_,_BinaryenLiteralVec128:l_,_BinaryenLiteralFloat32Bits:AO,_BinaryenLiteralFloat64Bits:NO,_BinaryenExpressionGetId:nt,_BinaryenExpressionGetType:It,_BinaryenExpressionSetType:LO,_BinaryenExpressionPrint:CO,_BinaryenExpressionCopy:u_,_BinaryenExpressionFinalize:tp,_BinaryenBlock:p_,_BinaryenBlockGetName:Fi,_BinaryenBlockSetName:FO,_BinaryenBlockGetNumChildren:Xr,_BinaryenBlockGetChildAt:Kr,_BinaryenBlockSetChildAt:rp,_BinaryenBlockAppendChild:kO,_BinaryenBlockInsertChildAt:PO,_BinaryenBlockRemoveChildAt:OO,_BinaryenIf:c_,_BinaryenIfGetCondition:ki,_BinaryenIfSetCondition:ip,_BinaryenIfGetIfTrue:Pi,_BinaryenIfSetIfTrue:np,_BinaryenIfGetIfFalse:Oi,_BinaryenIfSetIfFalse:sp,_BinaryenLoop:__,_BinaryenLoopGetName:rs,_BinaryenLoopSetName:wO,_BinaryenLoopGetBody:wi,_BinaryenLoopSetBody:ap,_BinaryenBreak:f_,_BinaryenBreakGetName:is,_BinaryenBreakSetName:MO,_BinaryenBreakGetCondition:qr,_BinaryenBreakSetCondition:op,_BinaryenBreakGetValue:ko,_BinaryenBreakSetValue:lp,_BinaryenSwitch:h_,_BinaryenSwitchGetNumNames:up,_BinaryenSwitchGetNameAt:pp,_BinaryenSwitchSetNameAt:UO,_BinaryenSwitchAppendName:DO,_BinaryenSwitchInsertNameAt:BO,_BinaryenSwitchRemoveNameAt:GO,_BinaryenSwitchGetDefaultName:cp,_BinaryenSwitchSetDefaultName:VO,_BinaryenSwitchGetCondition:Po,_BinaryenSwitchSetCondition:_p,_BinaryenSwitchGetValue:Oo,_BinaryenSwitchSetValue:fp,_BinaryenCall:m_,_BinaryenCallGetTarget:Qr,_BinaryenCallSetTarget:zO,_BinaryenCallGetNumOperands:Ut,_BinaryenCallGetOperandAt:Dt,_BinaryenCallSetOperandAt:ns,_BinaryenCallAppendOperand:WO,_BinaryenCallInsertOperandAt:YO,_BinaryenCallRemoveOperandAt:HO,_BinaryenCallIsReturn:XO,_BinaryenCallSetReturn:KO,_BinaryenReturnCall:d_,_BinaryenCallIndirect:E_,_BinaryenCallIndirectGetTable:qO,_BinaryenCallIndirectSetTable:QO,_BinaryenCallIndirectGetTarget:wo,_BinaryenCallIndirectSetTarget:hp,_BinaryenCallIndirectGetNumOperands:Mi,_BinaryenCallIndirectGetOperandAt:Ui,_BinaryenCallIndirectSetOperandAt:ss,_BinaryenCallIndirectAppendOperand:ZO,_BinaryenCallIndirectInsertOperandAt:jO,_BinaryenCallIndirectRemoveOperandAt:JO,_BinaryenCallIndirectIsReturn:$O,_BinaryenCallIndirectSetReturn:ew,_BinaryenReturnCallIndirect:y_,_BinaryenLocalGet:g_,_BinaryenLocalGetGetIndex:Zr,_BinaryenLocalGetSetIndex:tw,_BinaryenLocalSet:T_,_BinaryenLocalSetIsTee:Ns,_BinaryenLocalSetGetIndex:Bt,_BinaryenLocalSetSetIndex:rw,_BinaryenLocalSetGetValue:sr,_BinaryenLocalSetSetValue:as,_BinaryenLocalTee:b_,_BinaryenGlobalGet:I_,_BinaryenGlobalGetGetName:os,_BinaryenGlobalGetSetName:iw,_BinaryenGlobalSet:v_,_BinaryenGlobalSetGetName:mp,_BinaryenGlobalSetSetName:nw,_BinaryenGlobalSetGetValue:Mo,_BinaryenGlobalSetSetValue:dp,_BinaryenMemorySize:x_,_BinaryenMemoryGrow:S_,_BinaryenMemoryGrowGetDelta:Di,_BinaryenMemoryGrowSetDelta:Ep,_BinaryenLoad:R_,_BinaryenLoadIsAtomic:sw,_BinaryenLoadSetAtomic:aw,_BinaryenLoadIsSigned:A_,_BinaryenLoadSetSigned:ow,_BinaryenLoadGetOffset:N_,_BinaryenLoadSetOffset:lw,_BinaryenLoadGetBytes:L_,_BinaryenLoadSetBytes:uw,_BinaryenLoadGetAlign:pw,_BinaryenLoadSetAlign:cw,_BinaryenLoadGetPtr:Bi,_BinaryenLoadSetPtr:yp,_BinaryenAtomicLoad:C_,_BinaryenStore:F_,_BinaryenStoreIsAtomic:_w,_BinaryenStoreSetAtomic:fw,_BinaryenStoreGetBytes:Rs,_BinaryenStoreSetBytes:hw,_BinaryenStoreGetOffset:As,_BinaryenStoreSetOffset:mw,_BinaryenStoreGetAlign:dw,_BinaryenStoreSetAlign:Ew,_BinaryenStoreGetPtr:ar,_BinaryenStoreSetPtr:ls,_BinaryenStoreGetValue:Gi,_BinaryenStoreSetValue:gp,_BinaryenStoreGetValueType:yw,_BinaryenStoreSetValueType:gw,_BinaryenAtomicStore:k_,_BinaryenConst:_i,_BinaryenConstGetValueI32:P_,_BinaryenConstSetValueI32:Tw,_BinaryenConstGetValueI64Low:O_,_BinaryenConstSetValueI64Low:bw,_BinaryenConstGetValueI64High:w_,_BinaryenConstSetValueI64High:Iw,_BinaryenConstGetValueF32:M_,_BinaryenConstSetValueF32:vw,_BinaryenConstGetValueF64:U_,_BinaryenConstSetValueF64:xw,_BinaryenConstGetValueV128:D_,_BinaryenConstSetValueV128:Sw,_BinaryenUnary:B_,_BinaryenUnaryGetOp:G_,_BinaryenUnarySetOp:Rw,_BinaryenUnaryGetValue:Vi,_BinaryenUnarySetValue:Tp,_BinaryenBinary:V_,_BinaryenBinaryGetOp:z_,_BinaryenBinarySetOp:Aw,_BinaryenBinaryGetLeft:zi,_BinaryenBinarySetLeft:bp,_BinaryenBinaryGetRight:Wi,_BinaryenBinarySetRight:Ip,_BinaryenSelect:W_,_BinaryenSelectGetIfTrue:Yi,_BinaryenSelectSetIfTrue:vp,_BinaryenSelectGetIfFalse:Hi,_BinaryenSelectSetIfFalse:xp,_BinaryenSelectGetCondition:Xi,_BinaryenSelectSetCondition:Sp,_BinaryenDrop:Du,_BinaryenDropGetValue:Ki,_BinaryenDropSetValue:Rp,_BinaryenReturn:Y_,_BinaryenReturnGetValue:or,_BinaryenReturnSetValue:us,_BinaryenNop:H_,_BinaryenUnreachable:X_,_BinaryenAtomicRMW:K_,_BinaryenAtomicRMWGetOp:Nw,_BinaryenAtomicRMWSetOp:Lw,_BinaryenAtomicRMWGetBytes:Cw,_BinaryenAtomicRMWSetBytes:Fw,_BinaryenAtomicRMWGetOffset:kw,_BinaryenAtomicRMWSetOffset:Pw,_BinaryenAtomicRMWGetPtr:Uo,_BinaryenAtomicRMWSetPtr:Ap,_BinaryenAtomicRMWGetValue:Do,_BinaryenAtomicRMWSetValue:Np,_BinaryenAtomicCmpxchg:q_,_BinaryenAtomicCmpxchgGetBytes:Ow,_BinaryenAtomicCmpxchgSetBytes:ww,_BinaryenAtomicCmpxchgGetOffset:Mw,_BinaryenAtomicCmpxchgSetOffset:Uw,_BinaryenAtomicCmpxchgGetPtr:Bo,_BinaryenAtomicCmpxchgSetPtr:Lp,_BinaryenAtomicCmpxchgGetExpected:Go,_BinaryenAtomicCmpxchgSetExpected:Cp,_BinaryenAtomicCmpxchgGetReplacement:Vo,_BinaryenAtomicCmpxchgSetReplacement:Fp,_BinaryenAtomicWait:Q_,_BinaryenAtomicWaitGetPtr:zo,_BinaryenAtomicWaitSetPtr:kp,_BinaryenAtomicWaitGetExpected:Wo,_BinaryenAtomicWaitSetExpected:Pp,_BinaryenAtomicWaitGetTimeout:Yo,_BinaryenAtomicWaitSetTimeout:Op,_BinaryenAtomicWaitGetExpectedType:Dw,_BinaryenAtomicWaitSetExpectedType:Bw,_BinaryenAtomicNotify:Z_,_BinaryenAtomicNotifyGetPtr:Ho,_BinaryenAtomicNotifySetPtr:wp,_BinaryenAtomicNotifyGetNotifyCount:Xo,_BinaryenAtomicNotifySetNotifyCount:Mp,_BinaryenAtomicFence:j_,_BinaryenAtomicFenceGetOrder:Gw,_BinaryenAtomicFenceSetOrder:Vw,_BinaryenSIMDExtract:J_,_BinaryenSIMDExtractGetOp:zw,_BinaryenSIMDExtractSetOp:Ww,_BinaryenSIMDExtractGetVec:Ko,_BinaryenSIMDExtractSetVec:Up,_BinaryenSIMDExtractGetIndex:Yw,_BinaryenSIMDExtractSetIndex:Hw,_BinaryenSIMDReplace:$_,_BinaryenSIMDReplaceGetOp:Xw,_BinaryenSIMDReplaceSetOp:Kw,_BinaryenSIMDReplaceGetVec:qo,_BinaryenSIMDReplaceSetVec:Dp,_BinaryenSIMDReplaceGetIndex:qw,_BinaryenSIMDReplaceSetIndex:Qw,_BinaryenSIMDReplaceGetValue:Qo,_BinaryenSIMDReplaceSetValue:Bp,_BinaryenSIMDShuffle:ef,_BinaryenSIMDShuffleGetLeft:Zo,_BinaryenSIMDShuffleSetLeft:Gp,_BinaryenSIMDShuffleGetRight:jo,_BinaryenSIMDShuffleSetRight:Vp,_BinaryenSIMDShuffleGetMask:Zw,_BinaryenSIMDShuffleSetMask:jw,_BinaryenSIMDTernary:tf,_BinaryenSIMDTernaryGetOp:Jw,_BinaryenSIMDTernarySetOp:$w,_BinaryenSIMDTernaryGetA:Jo,_BinaryenSIMDTernarySetA:zp,_BinaryenSIMDTernaryGetB:$o,_BinaryenSIMDTernarySetB:Wp,_BinaryenSIMDTernaryGetC:el,_BinaryenSIMDTernarySetC:Yp,_BinaryenSIMDShift:rf,_BinaryenSIMDShiftGetOp:eM,_BinaryenSIMDShiftSetOp:tM,_BinaryenSIMDShiftGetVec:tl,_BinaryenSIMDShiftSetVec:Hp,_BinaryenSIMDShiftGetShift:rl,_BinaryenSIMDShiftSetShift:Xp,_BinaryenSIMDLoad:nf,_BinaryenSIMDLoadGetOp:rM,_BinaryenSIMDLoadSetOp:iM,_BinaryenSIMDLoadGetOffset:nM,_BinaryenSIMDLoadSetOffset:sM,_BinaryenSIMDLoadGetAlign:aM,_BinaryenSIMDLoadSetAlign:oM,_BinaryenSIMDLoadGetPtr:il,_BinaryenSIMDLoadSetPtr:Kp,_BinaryenSIMDLoadStoreLane:sf,_BinaryenSIMDLoadStoreLaneGetOp:lM,_BinaryenSIMDLoadStoreLaneSetOp:uM,_BinaryenSIMDLoadStoreLaneGetOffset:pM,_BinaryenSIMDLoadStoreLaneSetOffset:cM,_BinaryenSIMDLoadStoreLaneGetAlign:_M,_BinaryenSIMDLoadStoreLaneSetAlign:fM,_BinaryenSIMDLoadStoreLaneGetIndex:hM,_BinaryenSIMDLoadStoreLaneSetIndex:mM,_BinaryenSIMDLoadStoreLaneGetPtr:nl,_BinaryenSIMDLoadStoreLaneSetPtr:qp,_BinaryenSIMDLoadStoreLaneGetVec:sl,_BinaryenSIMDLoadStoreLaneSetVec:Qp,_BinaryenSIMDLoadStoreLaneIsStore:dM,_BinaryenMemoryInit:EM,_BinaryenMemoryInitGetSegment:yM,_BinaryenMemoryInitSetSegment:gM,_BinaryenMemoryInitGetDest:al,_BinaryenMemoryInitSetDest:Zp,_BinaryenMemoryInitGetOffset:ol,_BinaryenMemoryInitSetOffset:jp,_BinaryenMemoryInitGetSize:ll,_BinaryenMemoryInitSetSize:Jp,_BinaryenDataDrop:TM,_BinaryenDataDropGetSegment:bM,_BinaryenDataDropSetSegment:IM,_BinaryenMemoryCopy:af,_BinaryenMemoryCopyGetDest:ul,_BinaryenMemoryCopySetDest:$p,_BinaryenMemoryCopyGetSource:pl,_BinaryenMemoryCopySetSource:ec,_BinaryenMemoryCopyGetSize:cl,_BinaryenMemoryCopySetSize:tc,_BinaryenMemoryFill:of,_BinaryenMemoryFillGetDest:_l,_BinaryenMemoryFillSetDest:rc,_BinaryenMemoryFillGetValue:fl,_BinaryenMemoryFillSetValue:ic,_BinaryenMemoryFillGetSize:hl,_BinaryenMemoryFillSetSize:nc,_BinaryenRefNull:lf,_BinaryenRefIs:uf,_BinaryenRefIsGetOp:vM,_BinaryenRefIsSetOp:xM,_BinaryenRefIsGetValue:ml,_BinaryenRefIsSetValue:sc,_BinaryenRefAs:pf,_BinaryenRefAsGetOp:SM,_BinaryenRefAsSetOp:RM,_BinaryenRefAsGetValue:AM,_BinaryenRefAsSetValue:NM,_BinaryenRefFunc:cf,_BinaryenRefFuncGetFunc:ac,_BinaryenRefFuncSetFunc:LM,_BinaryenRefEq:_f,_BinaryenRefEqGetLeft:dl,_BinaryenRefEqSetLeft:oc,_BinaryenRefEqGetRight:El,_BinaryenRefEqSetRight:lc,_BinaryenTableGet:ff,_BinaryenTableGetGetTable:CM,_BinaryenTableGetSetTable:FM,_BinaryenTableGetGetIndex:kM,_BinaryenTableGetSetIndex:PM,_BinaryenTableSet:hf,_BinaryenTableSetGetTable:OM,_BinaryenTableSetSetTable:wM,_BinaryenTableSetGetIndex:MM,_BinaryenTableSetSetIndex:UM,_BinaryenTableSetGetValue:DM,_BinaryenTableSetSetValue:BM,_BinaryenTableSize:mf,_BinaryenTableSizeGetTable:GM,_BinaryenTableSizeSetTable:VM,_BinaryenTableGrow:df,_BinaryenTableGrowGetTable:zM,_BinaryenTableGrowSetTable:WM,_BinaryenTableGrowGetValue:YM,_BinaryenTableGrowSetValue:HM,_BinaryenTableGrowGetDelta:XM,_BinaryenTableGrowSetDelta:KM,_BinaryenTry:Ef,_BinaryenTryGetName:qM,_BinaryenTrySetName:QM,_BinaryenTryGetBody:yl,_BinaryenTrySetBody:uc,_BinaryenTryGetNumCatchTags:ZM,_BinaryenTryGetNumCatchBodies:gl,_BinaryenTryGetCatchTagAt:jM,_BinaryenTrySetCatchTagAt:JM,_BinaryenTryAppendCatchTag:$M,_BinaryenTryInsertCatchTagAt:eU,_BinaryenTryRemoveCatchTagAt:tU,_BinaryenTryGetCatchBodyAt:Tl,_BinaryenTrySetCatchBodyAt:pc,_BinaryenTryAppendCatchBody:rU,_BinaryenTryInsertCatchBodyAt:iU,_BinaryenTryRemoveCatchBodyAt:nU,_BinaryenTryHasCatchAll:sU,_BinaryenTryGetDelegateTarget:aU,_BinaryenTrySetDelegateTarget:oU,_BinaryenTryIsDelegate:lU,_BinaryenThrow:yf,_BinaryenThrowGetTag:cc,_BinaryenThrowSetTag:uU,_BinaryenThrowGetNumOperands:bl,_BinaryenThrowGetOperandAt:Il,_BinaryenThrowSetOperandAt:_c,_BinaryenThrowAppendOperand:pU,_BinaryenThrowInsertOperandAt:cU,_BinaryenThrowRemoveOperandAt:_U,_BinaryenRethrow:gf,_BinaryenRethrowGetTarget:fU,_BinaryenRethrowSetDepth:hU,_BinaryenTupleMake:Tf,_BinaryenTupleMakeGetNumOperands:vl,_BinaryenTupleMakeGetOperandAt:xl,_BinaryenTupleMakeSetOperandAt:fc,_BinaryenTupleMakeAppendOperand:mU,_BinaryenTupleMakeInsertOperandAt:dU,_BinaryenTupleMakeRemoveOperandAt:EU,_BinaryenTupleExtract:bf,_BinaryenTupleExtractGetTuple:Sl,_BinaryenTupleExtractSetTuple:hc,_BinaryenTupleExtractGetIndex:yU,_BinaryenTupleExtractSetIndex:gU,_BinaryenPop:If,_BinaryenI31New:vf,_BinaryenI31NewGetValue:Rl,_BinaryenI31NewSetValue:mc,_BinaryenI31Get:xf,_BinaryenI31GetGetI31:Al,_BinaryenI31GetSetI31:dc,_BinaryenI31GetIsSigned:TU,_BinaryenI31GetSetSigned:bU,_BinaryenAddFunction:ni,_BinaryenGetFunction:si,_BinaryenRemoveFunction:on,_BinaryenGetNumFunctions:Ec,_BinaryenGetFunctionByIndex:yc,_BinaryenFunctionGetName:ii,_BinaryenFunctionGetParams:sn,_BinaryenFunctionGetResults:an,_BinaryenFunctionGetNumVars:Ls,_BinaryenFunctionGetVar:Cs,_BinaryenFunctionGetNumLocals:Yl,_BinaryenFunctionHasLocalName:IU,_BinaryenFunctionGetLocalName:vU,_BinaryenFunctionSetLocalName:xU,_BinaryenFunctionGetBody:Mt,_BinaryenFunctionSetBody:ps,_BinaryenFunctionOptimize:SU,_BinaryenFunctionRunPasses:Sf,_BinaryenFunctionSetDebugLocation:Rf,_BinaryenAddFunctionImport:Af,_BinaryenAddTableImport:Nf,_BinaryenAddMemoryImport:Lf,_BinaryenAddGlobalImport:Cf,_BinaryenAddTagImport:Ff,_BinaryenAddFunctionExport:Fs,_BinaryenAddTableExport:kf,_BinaryenAddMemoryExport:Pf,_BinaryenAddGlobalExport:Of,_BinaryenAddTagExport:wf,_BinaryenGetExport:ks,_BinaryenRemoveExport:Ps,_BinaryenGetNumExports:RU,_BinaryenGetExportByIndex:AU,_BinaryenExportGetKind:kc,_BinaryenExportGetName:Pc,_BinaryenExportGetValue:Oc,_BinaryenAddGlobal:Mf,_BinaryenGetGlobal:Uf,_BinaryenRemoveGlobal:Df,_BinaryenGetNumGlobals:gc,_BinaryenGetGlobalByIndex:Tc,_BinaryenGlobalGetName:Bf,_BinaryenGlobalGetType:Gf,_BinaryenGlobalIsMutable:Vf,_BinaryenGlobalGetInitExpr:cs,_BinaryenAddTag:zf,_BinaryenGetTag:Wf,_BinaryenRemoveTag:Yf,_BinaryenTagGetName:Hf,_BinaryenTagGetParams:Xf,_BinaryenTagGetResults:Kf,_BinaryenAddTable:qf,_BinaryenRemoveTable:NU,_BinaryenGetNumTables:LU,_BinaryenGetTable:Qf,_BinaryenGetTableByIndex:CU,_BinaryenTableGetName:FU,_BinaryenTableSetName:kU,_BinaryenTableGetInitial:PU,_BinaryenTableSetInitial:Zf,_BinaryenTableHasMax:OU,_BinaryenTableGetMax:wU,_BinaryenTableSetMax:jf,_BinaryenAddActiveElementSegment:Jf,_BinaryenAddPassiveElementSegment:MU,_BinaryenRemoveElementSegment:UU,_BinaryenGetNumElementSegments:DU,_BinaryenGetElementSegment:BU,_BinaryenGetElementSegmentByIndex:GU,_BinaryenSetMemory:$f,_BinaryenGetNumMemorySegments:VU,_BinaryenGetMemorySegmentByteOffset:zU,_BinaryenGetMemorySegmentByteLength:WU,_BinaryenCopyMemorySegmentData:YU,_BinaryenSetStart:eh,_BinaryenModuleParse:HU,_BinaryenModulePrint:XU,_BinaryenModulePrintAsmjs:KU,_BinaryenModuleValidate:th,_BinaryenModuleOptimize:qU,_BinaryenModuleRunPasses:rh,_BinaryenModuleAutoDrop:QU,_BinaryenModuleAllocateAndWrite:ih,_BinaryenModuleRead:nh,_BinaryenModuleInterpret:sh,_BinaryenModuleAddDebugInfoFileName:ah,_BinaryenModuleGetDebugInfoFileName:oh,_BinaryenModuleGetFeatures:lh,_BinaryenModuleSetFeatures:uh,_BinaryenAddCustomSection:ph,_BinaryenExpressionGetSideEffects:ch,_RelooperCreate:_h,_RelooperAddBlock:fh,_RelooperAddBranch:hh,_RelooperAddBlockWithSwitch:mh,_RelooperAddBranchForSwitch:dh,_RelooperRenderAndDispose:Eh,_ExpressionRunnerCreate:yh,_ExpressionRunnerSetLocalValue:ZU,_ExpressionRunnerSetGlobalValue:jU,_ExpressionRunnerRunAndDispose:gh,_BinaryenGetOptimizeLevel:Th,_BinaryenSetOptimizeLevel:bh,_BinaryenGetShrinkLevel:Ih,_BinaryenSetShrinkLevel:vh,_BinaryenGetDebugInfo:xh,_BinaryenSetDebugInfo:Sh,_BinaryenGetLowMemoryUnused:Rh,_BinaryenSetLowMemoryUnused:Ah,_BinaryenGetZeroFilledMemory:Nh,_BinaryenSetZeroFilledMemory:Lh,_BinaryenGetFastMath:Ch,_BinaryenSetFastMath:Fh,_BinaryenGetPassArgument:kh,_BinaryenSetPassArgument:Ph,_BinaryenClearPassArguments:Oh,_BinaryenGetAlwaysInlineMaxSize:wh,_BinaryenSetAlwaysInlineMaxSize:Mh,_BinaryenGetFlexibleInlineMaxSize:Uh,_BinaryenSetFlexibleInlineMaxSize:Dh,_BinaryenGetOneCallerInlineMaxSize:Bh,_BinaryenSetOneCallerInlineMaxSize:Gh,_BinaryenGetAllowInliningFunctionsWithLoops:Vh,_BinaryenSetAllowInliningFunctionsWithLoops:zh,_malloc:Nt,_free:ne,__i32_store8:Ae,__i32_store16:JU,__i32_store:Hs,__f32_store:$U,__f64_store:eD,__i32_load8_s:tD,__i32_load8_u:Sr,__i32_load16_s:rD,__i32_load16_u:iD,__i32_load:Nn,__f32_load:nD,__f64_load:sD}=yi;var Xs=new Float64Array(1),Wh=new Float32Array(Xs.buffer),fi=new Int32Array(Xs.buffer);globalThis.f32_as_i32=function(e){return Wh[0]=e,fi[0]};globalThis.i32_as_f32=function(e){return fi[0]=e,Wh[0]};globalThis.f64_as_i64=function(e){return Xs[0]=e,i64_new(fi[0],fi[1])};globalThis.i64_as_f64=function(e){return fi[0]=i64_low(e),fi[1]=i64_high(e),Xs[0]};import Ne from"long";globalThis.i64_zero=Ne.ZERO;globalThis.i64_one=Ne.ONE;globalThis.i64_neg_one=Ne.fromInt(-1);globalThis.i64_is=function(e){return Ne.isLong(e)};globalThis.i64_new=function(e,t){return Ne.fromBits(e,t)};globalThis.i64_low=function(e){return e.low};globalThis.i64_high=function(e){return e.high};globalThis.i64_not=function(e){return e.not()};globalThis.i64_clz=function(e){return e.clz()};globalThis.i64_ctz=function(e){return e.ctz()};globalThis.i64_add=function(e,t){return e.add(t)};globalThis.i64_sub=function(e,t){return e.sub(t)};globalThis.i64_mul=function(e,t){return e.mul(t)};globalThis.i64_pow=function(e,t){var i=t.low,n=t.high;if(n<=0){if(n<0)return e.eq(globalThis.i64_neg_one)?i&1?e:Ne.ONE:e.eq(Ne.ONE)?e:Ne.ZERO;if(i==0)return Ne.ONE;if(i==1)return e;if(i==2)return e.mul(e)}for(var s=Ne.ONE;i|n;)i&1&&(s=s.mul(e)),t=t.shru(1),e=e.mul(e),i=t.low,n=t.high;return s};globalThis.i64_div=function(e,t){return e.div(t)};globalThis.i64_div_u=function(e,t){return e.toUnsigned().div(t.toUnsigned()).toSigned()};globalThis.i64_rem=function(e,t){return e.mod(t)};globalThis.i64_rem_u=function(e,t){return e.toUnsigned().mod(t.toUnsigned()).toSigned()};globalThis.i64_and=function(e,t){return e.and(t)};globalThis.i64_or=function(e,t){return e.or(t)};globalThis.i64_xor=function(e,t){return e.xor(t)};globalThis.i64_shl=function(e,t){return e.shl(t)};globalThis.i64_shr=function(e,t){return e.shr(t)};globalThis.i64_shr_u=function(e,t){return e.shru(t)};globalThis.i64_eq=function(e,t){return e.eq(t)};globalThis.i64_ne=function(e,t){return e.ne(t)};globalThis.i64_gt=function(e,t){return e.gt(t)};globalThis.i64_align=function(e,t){assert(t&&(t&t-1)==0);var i=Ne.fromInt(t-1);return e.add(i).and(i.not())};globalThis.i64_is_i8=function(e){return e.high===0&&e.low>=0&&e.low<=i8.MAX_VALUE||e.high===-1&&e.low>=i8.MIN_VALUE&&e.low<0};globalThis.i64_is_i16=function(e){return e.high===0&&e.low>=0&&e.low<=i16.MAX_VALUE||e.high===-1&&e.low>=i16.MIN_VALUE&&e.low<0};globalThis.i64_is_i32=function(e){return e.high===0&&e.low>=0||e.high===-1&&e.low<0};globalThis.i64_is_u8=function(e){return e.high===0&&e.low>>>0<=u8.MAX_VALUE};globalThis.i64_is_u16=function(e){return e.high===0&&e.low>>>0<=u16.MAX_VALUE};globalThis.i64_is_u32=function(e){return e.high===0};globalThis.i64_is_bool=function(e){return(e.high|e.low&-2)===0};var Q2=Ne.fromNumber(f32.MIN_SAFE_INTEGER),Z2=Ne.fromNumber(f32.MAX_SAFE_INTEGER);globalThis.i64_is_f32=function(e){return e.gte(Q2)&&e.lte(Z2)};var j2=Ne.fromNumber(f64.MIN_SAFE_INTEGER),J2=Ne.fromNumber(f64.MAX_SAFE_INTEGER);globalThis.i64_is_f64=function(e){return e.gte(j2)&&e.lte(J2)};globalThis.i64_to_f32=function(e){return globalThis.Math.fround(e.toNumber())};globalThis.i64_to_f64=function(e){return e.toNumber()};globalThis.i64_to_string=function(e,t){return t?e.toUnsigned().toString():e.toString()};globalThis.Map_keys=function(e){return Array.from(e.keys())};globalThis.Map_values=function(e){return Array.from(e.values())};globalThis.Set_values=function(e){return Array.from(e.values())};var Cn=class{constructor(e,t=!1){this.seen=new Map;this.program=e,this.includePrivate=t}walk(){for(let e=Map_values(this.program.filesByName),t=0,i=e.length;t ( +`),V(i,++this.indentLevel),i.push("// "),i.push(t.internalName),i.push(` +`);var n=t.members;if(n)for(let s=Map_values(n),a=0,o=s.length;a { +`),V(p,1),p.push(`// @external.js +`),Hh(n,1,p),p.push(` +})()`)):(e!="env"&&(p.push("__module"),p.push(c.toString()),p.push(".")),p.push(t),p.push("("),p.push(l.join(", ")),p.push(")")),n=p.join(""),p.length=0,Hh(n,this.indentLevel,p,!0),n=p.join(""),V(s,this.indentLevel),a.returnType!=u.void?(s.push("return "),this.makeLowerToValue(n,a.returnType,s),s.push(`; +`)):(s.push(n),s.push(`; +`)),V(s,--this.indentLevel),s.push("}")}s.push(`, +`)}visitFunction(e,t){if(!t.is(512)){var i=this.sb,n=t.signature;if(this.exports.push(e),!Gu(n,Lt.EXPORT)){V(i,this.indentLevel),i.push(e),i.push("(");let s=n.parameterTypes,a=0;for(let p=0,c=s.length;p0&&i.push(", "),i.push(t.getParameterName(p));i.push(`) { +`),V(i,++this.indentLevel),i.push("// "),i.push(t.internalName),i.push(n.toString()),i.push(` +`);let o=new Array;for(let p=0,c=s.length;p0;E&&(this.needsRetain=!0,this.needsRelease=!0,i.push("__retain("),o.push(f)),this.makeLowerToValue(f,_,i),E&&i.push(")"),i.push(`; +`)}}o.length&&(V(i,this.indentLevel++),i.push(`try { +`)),n.requiredParameters0&&l.push(", "),l.push(t.getParameterName(p));if(l.push(")"),n.returnType!=u.void?(V(i,this.indentLevel),i.push("return "),this.makeLiftFromValue(l.join(""),n.returnType,i)):(V(i,this.indentLevel),i.push(l.join(""))),i.push(`; +`),o.length){V(i,this.indentLevel-1),i.push(`} finally { +`);for(let p=0,c=o.length;po;l?(V(s,this.indentLevel),s.push(`}; +`)):s.length=o-2;var p=this.importMappings,c=new Array;for(let g=Map_keys(p),b=0,S=g.length;bo;_?(V(s,this.indentLevel),s.push(`}, exports); +`)):this.needsLiftBuffer||this.needsLowerBuffer||this.needsLiftString||this.needsLowerString||this.needsLiftArray||this.needsLowerArray||this.needsLiftTypedArray||this.needsLowerTypedArray||this.needsLiftStaticArray?s.length=o-2:s.length=o-4;var f=this.deferredCode;if(f.length)for(let g=0,b=f.length;g>> 2]); + } +`)}if(this.needsLowerBuffer){let g=i.arrayBufferInstance.id;s.push(` function __lowerBuffer(value) { + if (value == null) return 0; + const pointer = exports.__new(value.byteLength, ${g}) >>> 0; + new Uint8Array(memory.buffer).set(new Uint8Array(value), pointer); + return pointer; + } +`)}if(this.needsLiftString){let g=i.OBJECTInstance,b=g.offsetof("rtSize")-g.nextMemoryOffset,S=1024;s.push(` function __liftString(pointer) { + if (!pointer) return null; + const + end = pointer + new Uint32Array(memory.buffer)[pointer - ${-b} >>> 2] >>> 1, + memoryU16 = new Uint16Array(memory.buffer); + let + start = pointer >>> 1, + string = ""; + while (end - start > ${S}) string += String.fromCharCode(...memoryU16.subarray(start, start += ${S})); + return string + String.fromCharCode(...memoryU16.subarray(start, end)); + } +`)}if(this.needsLowerString){let g=i.stringInstance.id;s.push(` function __lowerString(value) { + if (value == null) return 0; + const + length = value.length, + pointer = exports.__new(length << 1, ${g}) >>> 0, + memoryU16 = new Uint16Array(memory.buffer); + for (let i = 0; i < length; ++i) memoryU16[(pointer >>> 1) + i] = value.charCodeAt(i); + return pointer; + } +`)}if(this.needsLiftArray){let g=i.arrayBufferViewInstance.offsetof("dataStart"),b=i.arrayBufferViewInstance.nextMemoryOffset;s.push(` function __liftArray(liftElement, align, pointer) { + if (!pointer) return null; + const + memoryU32 = new Uint32Array(memory.buffer), + dataStart = memoryU32[pointer + ${g} >>> 2], + length = memoryU32[pointer + ${b} >>> 2], + values = new Array(length); + for (let i = 0; i < length; ++i) values[i] = liftElement(dataStart + (i << align >>> 0)); + return values; + } +`)}if(this.needsLowerArray){let g=i.arrayBufferInstance.id,b=i.arrayBufferViewInstance,S=b.nextMemoryOffset+4,v=b.offsetof("buffer"),x=b.offsetof("dataStart"),L=b.offsetof("byteLength"),P=L+4;s.push(` function __lowerArray(lowerElement, id, align, values) { + if (values == null) return 0; + const + length = values.length, + buffer = exports.__pin(exports.__new(length << align, ${g})) >>> 0, + header = exports.__pin(exports.__new(${S}, id)) >>> 0, + memoryU32 = new Uint32Array(memory.buffer); + memoryU32[header + ${v} >>> 2] = buffer; + memoryU32[header + ${x} >>> 2] = buffer; + memoryU32[header + ${L} >>> 2] = length << align; + memoryU32[header + ${P} >>> 2] = length; + for (let i = 0; i < length; ++i) lowerElement(buffer + (i << align >>> 0), values[i]); + exports.__unpin(buffer); + exports.__unpin(header); + return header; + } +`)}if(this.needsLiftTypedArray){let g=i.arrayBufferViewInstance,b=g.offsetof("dataStart"),S=g.offsetof("byteLength");s.push(` function __liftTypedArray(constructor, pointer) { + if (!pointer) return null; + const memoryU32 = new Uint32Array(memory.buffer); + return new constructor( + memory.buffer, + memoryU32[pointer + ${b} >>> 2], + memoryU32[pointer + ${S} >>> 2] / constructor.BYTES_PER_ELEMENT + ).slice(); + } +`)}if(this.needsLowerTypedArray){let g=i.arrayBufferInstance.id,b=i.arrayBufferViewInstance,S=b.nextMemoryOffset,v=b.offsetof("buffer"),x=b.offsetof("dataStart"),L=b.offsetof("byteLength");s.push(` function __lowerTypedArray(constructor, id, align, values) { + if (values == null) return 0; + const + length = values.length, + buffer = exports.__pin(exports.__new(length << align, ${g})) >>> 0, + header = exports.__new(${S}, id) >>> 0, + memoryU32 = new Uint32Array(memory.buffer); + memoryU32[header + ${v} >>> 2] = buffer; + memoryU32[header + ${x} >>> 2] = buffer; + memoryU32[header + ${L} >>> 2] = length << align; + new constructor(memory.buffer, buffer, length).set(values); + exports.__unpin(buffer); + return header; + } +`)}if(this.needsLiftStaticArray){let g=i.OBJECTInstance,b=g.offsetof("rtSize")-g.nextMemoryOffset;s.push(` function __liftStaticArray(liftElement, align, pointer) { + if (!pointer) return null; + const + length = new Uint32Array(memory.buffer)[pointer - ${-b} >>> 2] >>> align, + values = new Array(length); + for (let i = 0; i < length; ++i) values[i] = liftElement(pointer + (i << align >>> 0)); + return values; + } +`)}this.needsLowerStaticArray&&s.push(` function __lowerStaticArray(lowerElement, id, align, values) { + if (values == null) return 0; + const + length = values.length, + buffer = exports.__pin(exports.__new(length << align, id)) >>> 0; + for (let i = 0; i < length; i++) lowerElement(buffer + (i << align >>> 0), values[i]); + exports.__unpin(buffer); + return buffer; + } +`),this.needsLiftInternref&&(this.needsRetain=!0,this.needsRelease=!0,s.push(` const registry = new FinalizationRegistry(__release); + class Internref extends Number {} + function __liftInternref(pointer) { + if (!pointer) return null; + const sentinel = new Internref(__retain(pointer)); + registry.register(sentinel, pointer); + return sentinel; + } +`)),this.needsLowerInternref&&s.push(` function __lowerInternref(value) { + if (value == null) return 0; + if (value instanceof Internref) return value.valueOf(); + throw TypeError("internref expected"); + } +`),(this.needsRetain||this.needsRelease)&&s.push(` const refcounts = new Map(); +`),this.needsRetain&&s.push(` function __retain(pointer) { + if (pointer) { + const refcount = refcounts.get(pointer); + if (refcount) refcounts.set(pointer, refcount + 1); + else refcounts.set(exports.__pin(pointer), 1); + } + return pointer; + } +`),this.needsRelease&&s.push(` function __release(pointer) { + if (pointer) { + const refcount = refcounts.get(pointer); + if (refcount === 1) exports.__unpin(pointer), refcounts.delete(pointer); + else if (refcount) refcounts.set(pointer, refcount - 1); + else throw Error(\`invalid refcount '\${refcount}' for reference '\${pointer}'\`); + } + } +`),this.needsNotNull&&s.push(` function __notnull() { + throw TypeError("value must not be null"); + } +`);var E=n.exportStart;if(E&&s.push(` exports.${E}(); +`),_?s.push(` return adaptedExports; +} +`):s.push(` return exports; +} +`),--this.indentLevel,assert(this.indentLevel==0),this.esm){s.push(`export const { + `);for(let S=0,v=e.length;S0&&s.push(`, + `),s.push(e[S]);s.push(` +} = await (async url => instantiate( + await ( + globalThis.fetch && globalThis.WebAssembly.compileStreaming + ? globalThis.WebAssembly.compileStreaming(globalThis.fetch(url)) + : globalThis.WebAssembly.compile(await (await import("node:fs/promises")).readFile(url)) + ), { +`);let g=!1,b=new Array;for(let S=Map_keys(p),v=0,x=S.length;v>> 0"),i.push(")")}else i.push(e),t.isUnsignedIntegerValue&&t.size==32?i.push(" >>> 0"):t==u.bool&&i.push(" != 0")}makeLowerToValue(e,t,i=this.sb){if(t.isInternalReference){let n=assert(t.getClass());if(n.extends(this.program.arrayBufferInstance.prototype))i.push("__lowerBuffer("),this.needsLowerBuffer=!0;else if(n.extends(this.program.stringInstance.prototype))i.push("__lowerString("),this.needsLowerString=!0;else if(n.extends(this.program.arrayPrototype)){let s=n.getArrayValueType();i.push("__lowerArray("),this.makeLowerToMemory(s,i),i.push(", "),i.push(n.id.toString()),i.push(", "),i.push(n.getArrayValueType().alignLog2.toString()),i.push(", "),this.needsLowerArray=!0}else if(n.extends(this.program.staticArrayPrototype)){let s=n.getArrayValueType();i.push("__lowerStaticArray("),this.makeLowerToMemory(s,i),i.push(", "),i.push(n.id.toString()),i.push(", "),i.push(n.getArrayValueType().alignLog2.toString()),i.push(", "),this.needsLowerStaticArray=!0}else if(n.extends(this.program.arrayBufferViewInstance.prototype)){let s=n.getArrayValueType();i.push("__lowerTypedArray("),s==u.u64?i.push("BigUint64Array"):s==u.i64?i.push("BigInt64Array"):i.push(n.name),i.push(", "),i.push(n.id.toString()),i.push(", "),i.push(n.getArrayValueType().alignLog2.toString()),i.push(", "),this.needsLowerTypedArray=!0}else if(this.isPlainObject(n)){if(i.push("__lowerRecord"),i.push(n.id.toString()),i.push("("),!this.deferredLowers.has(n)){this.deferredLowers.add(n);let s=this.indentLevel;this.indentLevel=1,this.deferredCode.push(this.makeLowerRecord(n)),this.indentLevel=s}}else i.push("__lowerInternref("),this.needsLowerInternref=!0;i.push(e),i.push(")"),t.is(512)||(this.needsNotNull=!0,i.push(" || __notnull()"))}else i.push(e),t.isIntegerValue&&t.size==64?i.push(" || 0n"):t==u.bool&&i.push(" ? 1 : 0")}makeLiftFromMemory(e,t=this.sb,i=null){if(i||(t.push("pointer => "),i="pointer"),e.isInternalReference){let n=new Array;n.push("new Uint32Array(memory.buffer)["),n.push(i),n.push(" >>> 2]"),this.makeLiftFromValue(n.join(""),e,t)}else{if(e==u.i8)t.push("new Int8Array(memory.buffer)[");else if(e==u.u8||e==u.bool)t.push("new Uint8Array(memory.buffer)[");else if(e==u.i16)t.push("new Int16Array(memory.buffer)[");else if(e==u.u16)t.push("new Uint16Array(memory.buffer)[");else if(e==u.i32||e==u.isize32)t.push("new Int32Array(memory.buffer)[");else if(e==u.u32||e==u.usize32)t.push("new Uint32Array(memory.buffer)[");else if(e==u.i64||e==u.isize64)t.push("new BigInt64Array(memory.buffer)[");else if(e==u.u64||e==u.usize64)t.push("new BigUint64Array(memory.buffer)[");else if(e==u.f32)t.push("new Float32Array(memory.buffer)[");else if(e==u.f64)t.push("new Float64Array(memory.buffer)[");else{t.push('{ throw Error("unsupported type"); }');return}t.push(i),t.push(" >>> "),t.push(e.alignLog2.toString()),t.push("]"),e==u.bool&&t.push(" != 0")}}makeLowerToMemory(e,t=this.sb,i=null,n=null){let s=!0;if((!i||!n)&&(t.push("(pointer, value) => { "),i="pointer",n="value",s=!1),e.isInternalReference)t.push("new Uint32Array(memory.buffer)[");else if(e==u.i8)t.push("new Int8Array(memory.buffer)[");else if(e==u.u8||e==u.bool)t.push("new Uint8Array(memory.buffer)[");else if(e==u.i16)t.push("new Int16Array(memory.buffer)[");else if(e==u.u16)t.push("new Uint16Array(memory.buffer)[");else if(e==u.i32||e==u.isize32)t.push("new Int32Array(memory.buffer)[");else if(e==u.u32||e==u.usize32)t.push("new Uint32Array(memory.buffer)[");else if(e==u.i64||e==u.isize64)t.push("new BigInt64Array(memory.buffer)[");else if(e==u.u64||e==u.usize64)t.push("new BigUint64Array(memory.buffer)[");else if(e==u.f32)t.push("new Float32Array(memory.buffer)[");else if(e==u.f64)t.push("new Float64Array(memory.buffer)[");else{s?t.push('(() => { throw Error("unsupported type") })()'):t.push('throw Error("unsupported type"); }');return}t.push(i),t.push(" >>> "),t.push(e.alignLog2.toString()),t.push("] = "),this.makeLowerToValue(n,e,t),s||t.push("; }")}makeLiftRecord(e){assert(this.isPlainObject(e));var t=new Array;V(t,this.indentLevel),t.push("function __liftRecord"),t.push(e.id.toString()),t.push(`(pointer) { +`),V(t,++this.indentLevel),t.push("// "),t.push(e.type.toString()),t.push(` +`),V(t,this.indentLevel),t.push(`// Hint: Opt-out from lifting as a record by providing an empty constructor +`),V(t,this.indentLevel),t.push(`if (!pointer) return null; +`),V(t,this.indentLevel++),t.push(`return { +`);var i=e.members;if(i)for(let n=Map_keys(i),s=0,a=n.length;s(t[t.IMPORT=0]="IMPORT",t[t.EXPORT=1]="EXPORT",t))(Lt||{});function Rr(r,e){if(e==0){if(r.isIntegerValue&&r.size==64||r==u.bool)return!1}else if(r.isUnsignedIntegerValue&&r.size==32||r==u.bool)return!1;return!r.isInternalReference}function Gu(r,e){var t=r.parameterTypes,i=e==0?1:0;for(let n=0,s=t.length;n=l&&i.push("?"),i.push(": "),i.push(this.toTypeScriptType(s[p],hi.IMPORT));i.push("): "),i.push(this.toTypeScriptType(o,hi.EXPORT)),i.push(`; +`)}visitClass(e,t){}visitInterface(e,t){}visitField(e,t){}visitNamespace(e,t){}visitAlias(e,t,i){}build(){var e=this.sb;this.esm||(e.push(`declare namespace __AdaptedExports { +`),++this.indentLevel),this.walk(),this.esm||(--this.indentLevel,e.push(`} +`));var t=this.deferredTypings;for(let i=0,n=t.length;i; +`)}return e.join("")}isPlainObject(e){if(e.base)return!1;var t=e.members;if(t)for(let i=Map_values(t),n=0,s=i.length;n")}else if(n.extends(this.program.arrayBufferViewInstance.prototype)){let s=n.getArrayValueType();s==u.i8?i.push("Int8Array"):s==u.u8?n.extends(this.program.uint8ClampedArrayPrototype)?i.push("Uint8ClampedArray"):i.push("Uint8Array"):s==u.i16?i.push("Int16Array"):s==u.u16?i.push("Uint16Array"):s==u.i32?i.push("Int32Array"):s==u.u32?i.push("Uint32Array"):s==u.i64?i.push("BigInt64Array"):s==u.u64?i.push("BigUint64Array"):s==u.f32?i.push("Float32Array"):s==u.f64?i.push("Float64Array"):i.push("unknown")}else{let s=this.seenObjectTypes,a;s.has(n)?(a=assert(s.get(n)),i.push(a),this.isPlainObject(n)&&i.push(t==hi.EXPORT?"":"")):(this.isPlainObject(n)?(a="__Record"+n.id.toString(),i.push(a),i.push(t==hi.EXPORT?"":""),this.deferredTypings.push(this.makeRecordType(n,t))):(a="__Internref"+n.id.toString(),i.push(a),this.deferredTypings.push(this.makeInternrefType(n))),s.set(n,a))}return e.is(512)&&i.push(" | null"),i.join("")}else{if(e==u.bool)return"boolean";if(e==u.void)return"void";if(e.isNumericValue)return e.isLongIntegerValue?"bigint":"number"}return"unknown"}makeRecordType(e,t){var i=new Array,n=e.members;if(i.push("/** "),i.push(e.internalName),i.push(` */ +declare interface __Record`),i.push(e.id.toString()),i.push(` { +`),n)for(let s=Map_keys(n),a=0,o=s.length;a(t[t.IMPORT=0]="IMPORT",t[t.EXPORT=1]="EXPORT",t))(hi||{});function $2(){return new ws}function eS(r,e){r.target=e}function tS(r,e){r.runtime=e}function rS(r,e){r.noAssert=e}function iS(r,e){r.exportMemory=e}function nS(r,e){r.importMemory=e}function sS(r,e){r.initialMemory=e}function aS(r,e){r.maximumMemory=e}function oS(r,e){r.sharedMemory=e}function lS(r,e){r.importTable=e}function uS(r,e){r.exportTable=e}function pS(r,e){r.sourceMap=e}function cS(r,e){r.memoryBase=e}function _S(r,e){r.tableBase=e}function fS(r,e,t){var i=r.globalAliases;i||(r.globalAliases=i=new Map),i.set(e,t)}function hS(r,e){var t=r.globalAliases;t&&t.delete(e)}function mS(r,e){r.exportStart=e}function dS(r,e){r.noUnsafe=e}function ES(r,e){r.lowMemoryLimit=e}function yS(r,e){r.exportRuntime=e}var gS=16384;function TS(r,e){r.stackSize=e}function bS(r,e,t,i){r.bundleMajorVersion=e,r.bundleMinorVersion=t,r.bundlePatchVersion=i}var IS=1,vS=2,xS=4,SS=8,RS=16,AS=32,NS=64,LS=128,CS=256,FS=512,kS=1024,PS=2048,OS=4096,wS=8192,MS=16384;function US(r,e){r.features|=e}function DS(r,e){r.features&=~e}function BS(r,e,t){r.optimizeLevelHint=e,r.shrinkLevelHint=t}function GS(r,e){r.basenameHint=e}function VS(r,e){r.pedantic=e}function zS(r){return new bs(r)}function WS(r){return r.diagnosticsOffset")}e.isNullable&&n.push(" | null")}}visitFunctionTypeNode(e){var t=e.isNullable,i=this.sb;i.push(t?"((":"(");var n=e.explicitThisType;n&&(i.push("this: "),this.visitTypeNode(n));var s=e.parameters,a=s.length;if(a){n&&i.push(", "),this.serializeParameter(s[0]);for(let l=1;l "),this.visitTypeNode(o)):i.push(") => void"),t&&i.push(") | null")}visitTypeParameter(e){this.visitIdentifierExpression(e.name);var t=e.extendsType;t&&(this.sb.push(" extends "),this.visitTypeNode(t));var i=e.defaultType;i&&(this.sb.push("="),this.visitTypeNode(i))}visitIdentifierExpression(e){e.isQuoted?this.visitStringLiteral(e.text):this.sb.push(e.text)}visitArrayLiteralExpression(e){var t=this.sb;t.push("[");var i=e.elementExpressions,n=i.length;if(n){let s=i[0];s&&this.visitNode(s);for(let a=1;a"),this.visitNode(e.expression);break}case 1:{this.visitNode(e.expression),t.push(" as "),this.visitTypeNode(assert(e.toType));break}case 2:{this.visitNode(e.expression),t.push("!");break}case 3:{this.visitNode(e.expression),t.push(" as const");break}default:assert(!1)}}visitBinaryExpression(e){var t=this.sb;this.visitNode(e.left),t.push(" "),t.push(ye(e.operator)),t.push(" "),this.visitNode(e.right)}visitCallExpression(e){this.visitNode(e.expression),this.visitArguments(e.typeArguments,e.args)}visitArguments(e,t){var i=this.sb;if(e){let s=e.length;if(s){i.push("<"),this.visitTypeNode(e[0]);for(let a=1;a(")}}else i.push("(");var n=t.length;if(n){this.visitNode(t[0]);for(let s=1;s=0&&(i.charCodeAt(n)==125||i.charCodeAt(n)==59)?t.push(` +`):t.push(`; +`)}}visitBlockStatement(e){var t=this.sb,i=e.statements,n=i.length;if(n){t.push(`{ +`);let s=++this.indentLevel;for(let a=0;a0){n.push("<"),this.visitTypeParameter(s[0]);for(let _=1,f=s.length;_")}var a=e.extendsType;a&&(n.push(" extends "),this.visitTypeNode(a));var o=e.implementsTypes;if(o){let _=o.length;if(_){n.push(" implements "),this.visitTypeNode(o[0]);for(let f=1;f<_;++f)n.push(", "),this.visitTypeNode(o[f])}}var l=e.indexSignature,p=e.members,c=p.length;if(l||c){n.push(` { +`);let _=++this.indentLevel;l&&(V(n,_),this.visitNodeAndTerminate(l));for(let f=0,E=p.length;f0){let s=i.length;t.push(`export { +`);let a=++this.indentLevel;V(t,a),this.visitExportMember(i[0]);for(let o=1;o")}}if(e.arrowKind==2){let o=i.parameters;assert(o.length==1),assert(!i.explicitThisType),this.serializeParameter(o[0])}else{t.push("(");let o=i.parameters,l=o.length,p=i.explicitThisType;if(p&&(t.push("this: "),this.visitTypeNode(p)),l){p&&t.push(", "),this.serializeParameter(o[0]);for(let c=1;c "),this.visitNode(s)):(assert(!xe(a)),t.push(" => "),this.visitTypeNode(a)):(!xe(a)&&!e.isAny(266240)?(t.push("): "),this.visitTypeNode(a)):t.push(")"),s&&(t.push(" "),this.visitNode(s)))}visitIfStatement(e){var t=this.sb;t.push("if ("),this.visitNode(e.condition),t.push(") ");var i=e.ifTrue;this.visitNode(i),i.kind!=30&&t.push(`; +`);var n=e.ifFalse;n&&(i.kind==30?t.push(" else "):t.push("else "),this.visitNode(n))}visitImportDeclaration(e){var t=e.foreignName,i=e.name;this.visitIdentifierExpression(t),t.text!=i.text&&(this.sb.push(" as "),this.visitIdentifierExpression(i))}visitImportStatement(e){var t=this.sb;t.push("import ");var i=e.declarations,n=e.namespaceName;if(i){let s=i.length;if(s){t.push(`{ +`);let a=++this.indentLevel;V(t,a),this.visitImportDeclaration(i[0]);for(let o=1;o0){n.push("<"),this.visitTypeParameter(s[0]);for(let p=1,c=s.length;p")}var a=e.extendsType;a&&(n.push(" extends "),this.visitTypeNode(a)),n.push(` { +`);var o=++this.indentLevel,l=e.members;for(let p=0,c=l.length;p")}}i.push(" = "),this.visitTypeNode(e.type)}visitModuleDeclaration(e){var t=this.sb;e.flags&4&&t.push("declare "),t.push('module "'),t.push(de(e.moduleName,34)),t.push('"')}visitVariableDeclaration(e){this.visitIdentifierExpression(e.name);var t=e.type,i=this.sb;e.flags&8192&&i.push("!"),t&&(i.push(": "),this.visitTypeNode(t));var n=e.initializer;n&&(i.push(" = "),this.visitNode(n))}visitVariableStatement(e){var t=e.decorators;if(t)for(let o=0,l=t.length;o()=>(t&&(n=t(t=0)),n);var on=(t,n)=>{for(var e in n)ce(t,e,{get:n[e],enumerable:!0})},Ln=(t,n,e,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of We(n))!qe.call(t,o)&&(e||o!=="default")&&ce(t,o,{get:()=>n[o],enumerable:!(i=Ke(n,o))||i.enumerable});return t};var pe={};on(pe,{promises:()=>Ye});var Ye,de=xn(()=>{Ye={}});var xe={};on(xe,{createRequire:()=>Ze});function Ze(){return function(n){throw new Error(`Cannot find module: '${n}'`)}}var he=xn(()=>{});var kn={};on(kn,{argv:()=>Qe,cwd:()=>Nn,exit:()=>nt,hrtime:()=>tt,platform:()=>$e,umask:()=>Je});function Nn(){return"."}function Je(){return 0}function nt(t=0){throw Error(`exit ${t}`)}function tt(t){var n=et.call(ge),e=Math.floor(n*.001),i=Math.floor(n*1e6-e*1e9);return t&&(e-=t[0],i-=t[1],i<0&&(e--,i+=1e9)),[e,i]}var $e,Qe,ge,et,Rn=xn(()=>{$e="linux";Qe=[];ge=globalThis.performance||{},et=ge.now||function(){return new Date().getTime()}});var Mn={};on(Mn,{basename:()=>lt,delimiter:()=>pt,dirname:()=>st,extname:()=>ft,format:()=>ut,isAbsolute:()=>it,join:()=>ot,normalize:()=>ve,parse:()=>ct,relative:()=>at,resolve:()=>hn,sep:()=>Un,win32:()=>dt});function j(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function me(t,n){for(var e="",i=0,o=-1,r=0,l,f=0;f<=t.length;++f){if(f2){var u=e.lastIndexOf("/");if(u!==e.length-1){u===-1?(e="",i=0):(e=e.slice(0,u),i=e.length-1-e.lastIndexOf("/")),o=f,r=0;continue}}else if(e.length===2||e.length===1){e="",i=0,o=f,r=0;continue}}n&&(e.length>0?e+="/..":e="..",i=2)}else e.length>0?e+="/"+t.slice(o+1,f):e=t.slice(o+1,f),i=f-o-1;o=f,r=0}else l===46&&r!==-1?++r:r=-1}return e}function rt(t,n){var e=n.dir||n.root,i=n.base||(n.name||"")+(n.ext||"");return e?e===n.root?e+i:e+t+i:i}function hn(){for(var t="",n=!1,e,i=arguments.length-1;i>=-1&&!n;i--){var o;i>=0?o=arguments[i]:(e===void 0&&(e=Nn()),o=e),j(o),o.length!==0&&(t=o+"/"+t,n=o.charCodeAt(0)===47)}return t=me(t,!n),n?t.length>0?"/"+t:"/":t.length>0?t:"."}function ve(t){if(j(t),t.length===0)return".";var n=t.charCodeAt(0)===47,e=t.charCodeAt(t.length-1)===47;return t=me(t,!n),t.length===0&&!n&&(t="."),t.length>0&&e&&(t+="/"),n?"/"+t:t}function it(t){return j(t),t.length>0&&t.charCodeAt(0)===47}function ot(){if(arguments.length===0)return".";for(var t,n=0;n0&&(t===void 0?t=e:t+="/"+e)}return t===void 0?".":ve(t)}function at(t,n){if(j(t),j(n),t===n||(t=hn(t),n=hn(n),t===n))return"";if(t===".")return n;for(var e=1;eu){if(n.charCodeAt(r+c)===47)return n.slice(r+c+1);if(c===0)return n.slice(r+c)}else o>u&&(t.charCodeAt(e+c)===47?x=c:c===0&&(x=0));break}var m=t.charCodeAt(e+c),y=n.charCodeAt(r+c);if(m!==y)break;m===47&&(x=c)}var g="";for(c=e+x+1;c<=i;++c)(c===i||t.charCodeAt(c)===47)&&(g.length===0?g+="..":g+="/..");return g.length>0?g+n.slice(r+x):(r+=x,n.charCodeAt(r)===47&&++r,n.slice(r))}function st(t){if(j(t),t.length===0)return".";for(var n=t.charCodeAt(0),e=n===47,i=-1,o=!0,r=t.length-1;r>=1;--r)if(n=t.charCodeAt(r),n===47){if(!o){i=r;break}}else o=!1;return i===-1?e?"/":".":e&&i===1?"//":t.slice(0,i)}function lt(t,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');j(t);var e=0,i=-1,o=!0,r;if(n!==void 0&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return"";var l=n.length-1,f=-1;for(r=t.length-1;r>=0;--r){var u=t.charCodeAt(r);if(u===47){if(!o){e=r+1;break}}else f===-1&&(o=!1,f=r+1),l>=0&&(u===n.charCodeAt(l)?--l===-1&&(i=r):(l=-1,i=f))}return e===i?i=f:i===-1&&(i=t.length),t.slice(e,i)}else{for(r=t.length-1;r>=0;--r)if(t.charCodeAt(r)===47){if(!o){e=r+1;break}}else i===-1&&(o=!1,i=r+1);return i===-1?"":t.slice(e,i)}}function ft(t){j(t);for(var n=-1,e=0,i=-1,o=!0,r=0,l=t.length-1;l>=0;--l){var f=t.charCodeAt(l);if(f===47){if(!o){e=l+1;break}continue}i===-1&&(o=!1,i=l+1),f===46?n===-1?n=l:r!==1&&(r=1):n!==-1&&(r=-1)}return n===-1||i===-1||r===0||r===1&&n===i-1&&n===e+1?"":t.slice(n,i)}function ut(t){if(t===null||typeof t!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return rt("/",t)}function ct(t){j(t);var n={root:"",dir:"",base:"",ext:"",name:""};if(t.length===0)return n;var e=t.charCodeAt(0),i=e===47,o;i?(n.root="/",o=1):o=0;for(var r=-1,l=0,f=-1,u=!0,x=t.length-1,c=0;x>=o;--x){if(e=t.charCodeAt(x),e===47){if(!u){l=x+1;break}continue}f===-1&&(u=!1,f=x+1),e===46?r===-1?r=x:c!==1&&(c=1):r!==-1&&(c=-1)}return r===-1||f===-1||c===0||c===1&&r===f-1&&r===l+1?f!==-1&&(l===0&&i?n.base=n.name=t.slice(1,f):n.base=n.name=t.slice(l,f)):(l===0&&i?(n.name=t.slice(1,r),n.base=t.slice(1,f)):(n.name=t.slice(l,r),n.base=t.slice(l,f)),n.ext=t.slice(r,f)),l>0?n.dir=t.slice(0,l-1):i&&(n.dir="/"),n}var Un,pt,dt,Pn=xn(()=>{Rn();Un="/",pt=":",dt=null});var ye={};on(ye,{pathToFileURL:()=>ht});function xt(t){return t.replace(/%/g,"%25").replace(/\\/g,"%5C").replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/\t/g,"%09")}function ht(t){let n=hn(t);t.charCodeAt(t.length-1)===47&&n[n.length-1]!==Un&&(n+="/");let e=new URL("file://");return e.pathname=xt(n),e}var be=xn(()=>{Pn()});var ee={};on(ee,{Stats:()=>ne,checkDiagnostics:()=>Sn,compileString:()=>Ht,configToArguments:()=>Qn,createMemoryStream:()=>$n,default:()=>ee,defaultOptimizeLevel:()=>ke,defaultShrinkLevel:()=>Re,definitionFiles:()=>Gt,libraryFiles:()=>W,libraryPrefix:()=>H,main:()=>Ue,options:()=>Vt,tscOptions:()=>jt,version:()=>Zn});var gt=Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]",X,un,A,G,gn;gt?(X=await import("fs"),un=await import("module"),A=await import("path"),G=globalThis.process,gn=await import("url")):(X=await Promise.resolve().then(()=>(de(),pe)),un=await Promise.resolve().then(()=>(he(),xe)),A=await Promise.resolve().then(()=>(Pn(),Mn)),G=await Promise.resolve().then(()=>(Rn(),kn)),gn=await Promise.resolve().then(()=>(be(),ye)));var Cn=typeof process<"u"&&process||{},mt=Cn.env&&"CI"in Cn.env,vt="\x1B[90m",yt="\x1B[91m",bt="\x1B[92m",Ft="\x1B[93m",Et="\x1B[94m",At="\x1B[95m",_t="\x1B[96m",Tt="\x1B[97m",Q="\x1B[0m",cn=class{constructor(n){this.stream=n,this.enabled=Boolean(this.stream&&this.stream.isTTY||mt)}gray(n){return this.enabled?vt+n+Q:n}red(n){return this.enabled?yt+n+Q:n}green(n){return this.enabled?bt+n+Q:n}yellow(n){return this.enabled?Ft+n+Q:n}blue(n){return this.enabled?Et+n+Q:n}magenta(n){return this.enabled?At+n+Q:n}cyan(n){return this.enabled?_t+n+Q:n}white(n){return this.enabled?Tt+n+Q:n}},zn=new cn(Cn.stdout),Wt=new cn(Cn.stderr);function K(){}K.prototype={diff:function(n,e){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=i.callback;typeof i=="function"&&(o=i,i={}),this.options=i;var r=this;function l(B){return o?(setTimeout(function(){o(void 0,B)},0),!0):B}n=this.castInput(n),e=this.castInput(e),n=this.removeEmpty(this.tokenize(n)),e=this.removeEmpty(this.tokenize(e));var f=e.length,u=n.length,x=1,c=f+u,m=[{newPos:-1,components:[]}],y=this.extractCommon(m[0],e,n,0);if(m[0].newPos+1>=f&&y+1>=u)return l([{value:this.join(e),count:e.length}]);function g(){for(var B=-1*x;B<=x;B+=2){var I=void 0,q=m[B-1],Y=m[B+1],R=(Y?Y.newPos:0)-B;q&&(m[B-1]=void 0);var O=q&&q.newPos+1=f&&R+1>=u)return l(Ct(r,I.components,e,n,r.useLongestToken));m[B]=I}x++}if(o)(function B(){setTimeout(function(){if(x>c)return o();g()||B()},0)})();else for(;x<=c;){var s=g();if(s)return s}},pushComponent:function(n,e,i){var o=n[n.length-1];o&&o.added===e&&o.removed===i?n[n.length-1]={count:o.count+1,added:e,removed:i}:n.push({count:1,added:e,removed:i})},extractCommon:function(n,e,i,o){for(var r=e.length,l=i.length,f=n.newPos,u=f-o,x=0;f+1g.length?B:g}),x.value=t.join(c)}else x.value=t.join(e.slice(f,f+x.count));f+=x.count,x.added||(u+=x.count)}}var y=n[l-1];return l>1&&typeof y.value=="string"&&(y.added||y.removed)&&t.equals("",y.value)&&(n[l-2].value+=y.value,n.pop()),n}function zt(t){return{newPos:t.newPos,components:t.components.slice(0)}}var Yt=new K;var Fe=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Ee=/\S/,Ae=new K;Ae.equals=function(t,n){return this.options.ignoreCase&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||this.options.ignoreWhitespace&&!Ee.test(t)&&!Ee.test(n)};Ae.tokenize=function(t){for(var n=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),e=0;e"u"?e:l}:i;return typeof t=="string"?t:JSON.stringify(Vn(t,null,null,o),o," ")};mn.equals=function(t,n){return K.prototype.equals.call(mn,t.replace(/,([\r\n])/g,"$1"),n.replace(/,([\r\n])/g,"$1"))};function Vn(t,n,e,i,o){n=n||[],e=e||[],i&&(t=i(o,t));var r;for(r=0;r191&&f<224?r[l++]=(f&31)<<6|t[n++]&63:f>239&&f<365?(f=((f&7)<<18|(t[n++]&63)<<12|(t[n++]&63)<<6|t[n++]&63)-65536,r[l++]=55296+(f>>10),r[l++]=56320+(f&1023)):r[l++]=(f&15)<<12|(t[n++]&63)<<6|t[n++]&63,l>=8192&&((o||(o=[])).push(String.fromCharCode(...r)),l=0);return o?(l&&o.push(String.fromCharCode(...r.slice(0,l))),o.join("")):String.fromCharCode(...r.slice(0,l))}function Lt(t,n,e){for(var i=e,o=0,r=t.length;o>6|192,n[e++]=l&63|128):(l&64512)===55296&&o+1>18|240,n[e++]=l>>12&63|128,n[e++]=l>>6&63|128,n[e++]=l&63|128):(n[e++]=l>>12|224,n[e++]=l>>6&63|128,n[e++]=l&63|128)}return e-i}var wn={length:It,read:Ot,write:Lt};var Te=un.createRequire(import.meta.url);function ze(t,n,e=!0){var i={},o=[],r=[],l=[],f={};Object.keys(n).forEach(c=>{if(!c.startsWith(" ")){var m=n[c];m.alias!=null&&(typeof m.alias=="string"?f[m.alias]=c:Array.isArray(m.alias)&&m.alias.forEach(y=>f[y]=c)),e&&m.default!=null&&(i[c]=m.default)}});for(var u=0,x=(t=t.slice()).length;ui[s]=y.value[s]);else if(y.type==null||y.type==="b")i[g]=!0;else if(u+1{var c=t[x];if(c.description!=null){for(var m="";m.length{for(let s=0;s{u=!0,f.push(o+" "+zn.gray(x)+o),f.push(r[x].join(o))}),u&&l.length&&f.push(o+" "+zn.gray("Other")+o),f.push(l.join(o)),f.join(o)}function Ce(t,n){if(t!=null)switch(n){case void 0:case"b":return Boolean(t);case"i":return Math.trunc(t)||0;case"f":return Number(t)||0;case"s":return t===!0?"":String(t);case"I":return Array.isArray(t)||(t=[t]),t.map(e=>Math.trunc(e)||0);case"F":return Array.isArray(t)||(t=[t]),t.map(e=>Number(e)||0);case"S":return Array.isArray(t)||(t=[t]),t.map(String)}}function Hn(t,n,e,i){let o={};for(let[r,{type:l,mutuallyExclusive:f,isPath:u,useNodeResolution:x,cliOnly:c}]of Object.entries(t)){let m=Ce(n[r],l),y=Ce(e[r],l);if(m==null){if(y!=null){if(c)continue;if(Array.isArray(y)){let g;u&&(y=y.map(s=>an(s,i,x))),f!=null&&(g=n[f])?o[r]=y.filter(s=>!g.includes(s)):o[r]=y.slice()}else u&&(y=an(y,i,x)),o[r]=y}}else if(y==null)Array.isArray(m)?o[r]=m.slice():o[r]=m;else if(Array.isArray(m)){if(c){o[r]=m.slice();continue}let g;u&&(y=y.map(s=>an(s,i,x))),f!=null&&(g=n[f])?o[r]=[...m,...y.filter(s=>!m.includes(s)&&!g.includes(s))]:o[r]=[...m,...y.filter(s=>!m.includes(s))]}else o[r]=m}return o}function Nt(t){let n=A.parse(t);return n.root||(n.root="./"),A.format(n)}function an(t,n,e=!1){return A.isAbsolute(t)?t:e&&!t.startsWith(".")&&Te.resolve?Te.resolve(t,{paths:[n]}):Nt(A.join(n,t))}function jn(t,n){for(let[e,{default:i}]of Object.entries(t))n[e]==null&&i!=null&&(n[e]=i)}var we="0.20.6",nn={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"},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 for WASI or 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:"Exports the runtime helpers (__new, __collect etc.).",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 16384 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).",""],TODO_doesNothingYet:[" exception-handling Exception handling."," tail-calls Tail call operations."," multi-value Multi value types."," memory64 Memory64 operations."," function-references Function reference types."," relaxed-simd Relaxed SIMD 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},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}}},Se="~lib/",De={array:`/// + +import { BLOCK_MAXSIZE } from "./rt/common"; +import { Runtime } from "shared/runtime"; +import { COMPARATOR, SORT } from "./util/sort"; +import { REVERSE } 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_ILLEGALGENTYPE, 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 + var oldCapacity = changetype(array).byteLength; + if (newSize > oldCapacity >>> alignLog2) { + if (newSize > BLOCK_MAXSIZE >>> alignLog2) throw new RangeError(E_INVALIDLENGTH); + let oldData = changetype(changetype(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(array, newData, offsetof("buffer")); + store(array, newData, offsetof("dataStart")); + __link(array, changetype(newData), false); + } + store(array, newCapacity, offsetof("byteLength")); + } +} + +export class Array { + [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 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(value: U): bool { + return isReference() ? changetype(value) != 0 && builtin_isArray(value) : false; + } + + static create(capacity: i32 = 0): Array { + WARNING("'Array.create' is deprecated. Use 'new Array' instead, making sure initial elements are initialized."); + var array = new Array(capacity); + array.length = 0; + return array; + } + + constructor(length: i32 = 0) { + if (length > BLOCK_MAXSIZE >>> alignof()) throw new RangeError(E_INVALIDLENGTH); + // reserve capacity for at least MIN_SIZE elements + var bufferSize = max(length, MIN_SIZE) << alignof(); + var buffer = changetype(__new(bufferSize, idof())); + if (ASC_RUNTIME != Runtime.Incremental) { + memory.fill(changetype(buffer), 0, bufferSize); + } + this.buffer = buffer; // links + this.dataStart = changetype(buffer); + this.byteLength = bufferSize; + this.length_ = length; + } + + get length(): i32 { + return this.length_; + } + + set length(newLength: i32) { + ensureCapacity(changetype(this), newLength, alignof(), false); + this.length_ = newLength; + } + + every(fn: (value: T, index: i32, array: Array) => bool): bool { + for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) { + if (!fn(load(this.dataStart + (i << alignof())), i, this)) return false; + } + return true; + } + + findIndex(fn: (value: T, index: i32, array: Array) => bool): i32 { + for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) { + if (fn(load(this.dataStart + (i << alignof())), i, this)) return i; + } + return -1; + } + + findLastIndex(fn: (value: T, index: i32, array: Array) => bool): i32 { + for (let i = this.length_ - 1; i >= 0; --i) { + if (fn(load(this.dataStart + (i << alignof())), i, this)) return i; + } + return -1; + } + + @operator("[]") private __get(index: i32): T { + if (index >= this.length_) throw new RangeError(E_INDEXOUTOFRANGE); + var value = load(this.dataStart + (index << alignof())); + if (isReference()) { + if (!isNullable()) { + if (!changetype(value)) throw new Error(E_HOLEYARRAY); + } + } + return value; + } + + @unsafe @operator("{}") private __uget(index: i32): T { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") private __set(index: i32, value: T): void { + if (index >= this.length_) { + if (index < 0) throw new RangeError(E_INDEXOUTOFRANGE); + ensureCapacity(changetype(this), index + 1, alignof()); + this.length_ = index + 1; + } + this.__uset(index, value); + } + + @unsafe @operator("{}=") private __uset(index: i32, value: T): void { + store(this.dataStart + (index << alignof()), value); + if (isManaged()) { + __link(changetype(this), changetype(value), true); + } + } + + at(index: i32): T { + var len = this.length_; + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + var value = load(this.dataStart + (index << alignof())); + if (isReference()) { + if (!isNullable()) { + if (!changetype(value)) throw new Error(E_HOLEYARRAY); + } + } + return value; + } + + fill(value: T, start: i32 = 0, end: i32 = i32.MAX_VALUE): this { + var ptr = this.dataStart; + var len = this.length_; + start = start < 0 ? max(len + start, 0) : min(start, len); + end = end < 0 ? max(len + end, 0) : min(end, len); + if (isManaged()) { + for (; start < end; ++start) { + store(ptr + (start << alignof()), changetype(value)); + __link(changetype(this), changetype(value), true); + } + } else if (sizeof() == 1) { + if (start < end) { + memory.fill( + ptr + start, + u8(value), + (end - start) + ); + } + } else { + for (; start < end; ++start) { + store(ptr + (start << alignof()), value); + } + } + return this; + } + + includes(value: T, fromIndex: i32 = 0): bool { + if (isFloat()) { + 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(ptr + (fromIndex << alignof())); + // @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 { + var len = this.length_; + if (len == 0 || fromIndex >= len) return -1; + if (fromIndex < 0) fromIndex = max(len + fromIndex, 0); + var ptr = this.dataStart; + while (fromIndex < len) { + if (load(ptr + (fromIndex << alignof())) == value) return fromIndex; + ++fromIndex; + } + return -1; + } + + lastIndexOf(value: T, fromIndex: i32 = this.length_): i32 { + var len = this.length_; + if (len == 0) return -1; + if (fromIndex < 0) fromIndex = len + fromIndex; + else if (fromIndex >= len) fromIndex = len - 1; + var ptr = this.dataStart; + while (fromIndex >= 0) { + if (load(ptr + (fromIndex << alignof())) == value) return fromIndex; + --fromIndex; + } + return -1; + } + + push(value: T): i32 { + var oldLen = this.length_; + var len = oldLen + 1; + ensureCapacity(changetype(this), len, alignof()); + if (isManaged()) { + store(this.dataStart + (oldLen << alignof()), changetype(value)); + __link(changetype(this), changetype(value), true); + } else { + store(this.dataStart + (oldLen << alignof()), value); + } + this.length_ = len; + return len; + } + + concat(other: Array): Array { + var thisLen = this.length_; + var otherLen = other.length_; + var outLen = thisLen + otherLen; + if (outLen > BLOCK_MAXSIZE >>> alignof()) throw new Error(E_INVALIDLENGTH); + var out = changetype>(__newArray(outLen, alignof(), idof>())); + var outStart = out.dataStart; + var thisSize = thisLen << alignof(); + if (isManaged()) { + let thisStart = this.dataStart; + for (let offset: usize = 0; offset < thisSize; offset += sizeof()) { + let ref = load(thisStart + offset); + store(outStart + offset, ref); + __link(changetype(out), ref, true); + } + outStart += thisSize; + let otherStart = other.dataStart; + let otherSize = otherLen << alignof(); + for (let offset: usize = 0; offset < otherSize; offset += sizeof()) { + let ref = load(otherStart + offset); + store(outStart + offset, ref); + __link(changetype(out), ref, true); + } + } else { + memory.copy(outStart, this.dataStart, thisSize); + memory.copy(outStart + thisSize, other.dataStart, otherLen << alignof()); + } + return out; + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): this { + var ptr = this.dataStart; + var len = this.length_; + + end = min(end, len); + + var to = target < 0 ? max(len + target, 0) : min(target, len); + var from = start < 0 ? max(len + start, 0) : min(start, len); + var last = end < 0 ? max(len + end, 0) : min(end, len); + var count = min(last - from, len - to); + + memory.copy( // is memmove + ptr + (to << alignof()), + ptr + (from << alignof()), + count << alignof() + ); + return this; + } + + pop(): T { + var len = this.length_; + if (len < 1) throw new RangeError(E_EMPTYARRAY); + var val = load(this.dataStart + ((--len) << alignof())); + this.length_ = len; + return val; + } + + forEach(fn: (value: T, index: i32, array: Array) => void): void { + for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) { + fn(load(this.dataStart + (i << alignof())), i, this); + } + } + + map(fn: (value: T, index: i32, array: Array) => U): Array { + var len = this.length_; + var out = changetype>(__newArray(len, alignof(), idof>())); + var outStart = out.dataStart; + for (let i = 0; i < min(len, this.length_); ++i) { + let result = fn(load(this.dataStart + (i << alignof())), i, this); + store(outStart + (i << alignof()), result); + if (isManaged()) { + __link(changetype(out), changetype(result), true); + } + } + return out; + } + + filter(fn: (value: T, index: i32, array: Array) => bool): Array { + var result = changetype>(__newArray(0, alignof(), idof>())); + for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) { + let value = load(this.dataStart + (i << alignof())); + if (fn(value, i, this)) result.push(value); + } + return result; + } + + reduce( + fn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array) => U, + initialValue: U + ): U { + var acc = initialValue; + for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) { + acc = fn(acc, load(this.dataStart + (i << alignof())), i, this); + } + return acc; + } + + reduceRight( + fn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array) => U, + initialValue: U + ): U { + var acc = initialValue; + for (let i = this.length_ - 1; i >= 0; --i) { + acc = fn(acc, load(this.dataStart + (i << alignof())), i, this); + } + return acc; + } + + shift(): T { + var len = this.length_; + if (len < 1) throw new RangeError(E_EMPTYARRAY); + var base = this.dataStart; + var element = load(base); + var lastIndex = len - 1; + memory.copy( + base, + base + sizeof(), + lastIndex << alignof() + ); + if (isReference()) { + store(base + (lastIndex << alignof()), 0); + } else { + // @ts-ignore + store(base + (lastIndex << alignof()), 0); + } + this.length_ = lastIndex; + return element; + } + + some(fn: (value: T, index: i32, array: Array) => bool): bool { + for (let i = 0, len = this.length_; i < min(len, this.length_); ++i) { + if (fn(load(this.dataStart + (i << alignof())), i, this)) return true; + } + return false; + } + + unshift(value: T): i32 { + var len = this.length_ + 1; + ensureCapacity(changetype(this), len, alignof()); + var ptr = this.dataStart; + memory.copy( + ptr + sizeof(), + ptr, + (len - 1) << alignof() + ); + store(ptr, value); + if (isManaged()) { + __link(changetype(this), changetype(value), true); + } + this.length_ = len; + return len; + } + + slice(start: i32 = 0, end: i32 = i32.MAX_VALUE): Array { + var 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); + var slice = changetype>(__newArray(len, alignof(), idof>())); + var sliceBase = slice.dataStart; + var thisBase = this.dataStart + (start << alignof()); + if (isManaged()) { + let off = 0; + let end = len << alignof(); + while (off < end) { + let ref = load(thisBase + off); + store(sliceBase + off, ref); + __link(changetype(slice), ref, true); + off += sizeof(); + } + } else { + memory.copy(sliceBase, thisBase, len << alignof()); + } + return slice; + } + + splice(start: i32, deleteCount: i32 = i32.MAX_VALUE): Array { + var len = this.length_; + start = start < 0 ? max(len + start, 0) : min(start, len); + deleteCount = max(min(deleteCount, len - start), 0); + var result = changetype>(__newArray(deleteCount, alignof(), idof>())); + var resultStart = result.dataStart; + var thisStart = this.dataStart; + var thisBase = thisStart + (start << alignof()); + memory.copy( + resultStart, + thisBase, + deleteCount << alignof() + ); + var offset = start + deleteCount; + if (len != offset) { + memory.copy( + thisBase, + thisStart + (offset << alignof()), + (len - offset) << alignof() + ); + } + this.length_ = len - deleteCount; + return result; + } + + reverse(): this { + REVERSE(this.dataStart, this.length_); + return this; + } + + sort(comparator: (a: T, b: T) => i32 = COMPARATOR()): this { + SORT(this.dataStart, this.length_, comparator); + return this; + } + + join(separator: string = ","): string { + var ptr = this.dataStart; + var len = this.length_; + if (isBoolean()) return joinBooleanArray(ptr, len, separator); + if (isInteger()) return joinIntegerArray(ptr, len, separator); + if (isFloat()) return joinFloatArray(ptr, len, separator); + + if (ASC_SHRINK_LEVEL < 1) { + if (isString()) return joinStringArray(ptr, len, separator); + } + // For rest objects and arrays use general join routine + if (isReference()) return joinReferenceArray(ptr, len, separator); + ERROR("unspported element type"); + return unreachable(); + } + + flat(): T { + if (!isArray()) { + throw new TypeError(E_ILLEGALGENTYPE); + } + // Get the length and data start values + var ptr = this.dataStart; + var len = this.length_; + + // calculate the end size with an initial pass + var size = 0; + for (let i = 0; i < len; ++i) { + let child = load(ptr + (i << alignof())); + size += child == 0 ? 0 : load(child, offsetof("length_")); + } + + // calculate the byteLength of the resulting backing ArrayBuffer + const align = alignof>(); + var byteLength = size << align; + var outBuffer = changetype(__new(byteLength, idof())); + + // create the return value and initialize it + var outArray = changetype(__new(offsetof(), idof())); + store(changetype(outArray), size, offsetof("length_")); + + // byteLength, dataStart, and buffer are all readonly + store(changetype(outArray), byteLength, offsetof("byteLength")); + store(changetype(outArray), changetype(outBuffer), offsetof("dataStart")); + store(changetype(outArray), changetype(outBuffer), offsetof("buffer")); + __link(changetype(outArray), changetype(outBuffer), false); + + // set the elements + var resultOffset: usize = 0; + for (let i = 0; i < len; ++i) { // for each child + let child = load(ptr + (i << alignof())); + + // ignore null arrays + if (!child) continue; + + // copy the underlying buffer data to the result buffer + let childDataLength = load(child, offsetof("length_")) << align; + memory.copy( + changetype(outBuffer) + resultOffset, + load(child, offsetof("dataStart")), + childDataLength + ); + + // advance the result length + resultOffset += childDataLength; + } + + // if the \`valueof\` type is managed, we must link each reference + if (isManaged>()) { + for (let i = 0; i < size; ++i) { + let ref = load(changetype(outBuffer) + (i << usize(alignof>()))); + __link(changetype(outBuffer), ref, true); + } + } + + return outArray; + } + + toString(): string { + return this.join(); + } + + // RT integration + + @unsafe private __visit(cookie: u32): void { + if (isManaged()) { + let cur = this.dataStart; + let end = cur + (this.length_ << alignof()); + while (cur < end) { + let val = load(cur); + if (val) __visit(val, cookie); + cur += sizeof(); + } + } + __visit(changetype(this.buffer), cookie); + } +} +`,arraybuffer:`/// + +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 (this.dataStart - changetype(this.buffer)); + } + + protected constructor(length: i32, alignLog2: i32) { + if (length > BLOCK_MAXSIZE >>> alignLog2) throw new RangeError(E_INVALIDLENGTH); + var buffer = changetype(__new(length = length << alignLog2, idof())); + if (ASC_RUNTIME != Runtime.Incremental) { + memory.fill(changetype(buffer), 0, length); + } + this.buffer = buffer; // links + this.dataStart = changetype(buffer); + this.byteLength = length; + } +} + +@final export class ArrayBuffer { + + static isView(value: T): bool { + if (isNullable()) { + if (changetype(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 (length > BLOCK_MAXSIZE) throw new RangeError(E_INVALIDLENGTH); + var buffer = changetype(__new(length, idof())); + if (ASC_RUNTIME != Runtime.Incremental) { + memory.fill(changetype(buffer), 0, length); + } + return buffer; + } + + get byteLength(): i32 { + return changetype(changetype(this) - TOTAL_OVERHEAD).rtSize; + } + + slice(begin: i32 = 0, end: i32 = BLOCK_MAXSIZE): ArrayBuffer { + var length = this.byteLength; + begin = begin < 0 ? max(length + begin, 0) : min(begin, length); + end = end < 0 ? max(length + end , 0) : min(end , length); + var outSize = max(end - begin, 0); + var out = changetype(__new(outSize, idof())); + memory.copy(changetype(out), changetype(this) + 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(array: T, index: i32): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.load>( + changetype(array.buffer) + (index << align) + array.byteOffset + ); + } + + // @ts-ignore: decorator + @inline + export function store(array: T, index: i32, value: valueof): void { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + atomic.store>( + changetype(array.buffer) + (index << align) + array.byteOffset, + value + ); + } + + // @ts-ignore: decorator + @inline + export function add(array: T, index: i32, value: valueof): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.add>( + changetype(array.buffer) + (index << align) + array.byteOffset, + value + ); + } + + // @ts-ignore: decorator + @inline + export function sub(array: T, index: i32, value: valueof): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.sub>( + changetype(array.buffer) + (index << align) + array.byteOffset, + value + ); + } + + // @ts-ignore: decorator + @inline + export function and(array: T, index: i32, value: valueof): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.and>( + changetype(array.buffer) + (index << align) + array.byteOffset, + value + ); + } + + // @ts-ignore: decorator + @inline + export function or(array: T, index: i32, value: valueof): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.or>( + changetype(array.buffer) + (index << align) + array.byteOffset, + value + ); + } + + // @ts-ignore: decorator + @inline + export function xor(array: T, index: i32, value: valueof): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.xor>( + changetype(array.buffer) + (index << align) + array.byteOffset, + value + ); + } + + // @ts-ignore: decorator + @inline + export function exchange(array: T, index: i32, value: valueof): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.xchg>( + changetype(array.buffer) + (index << align) + array.byteOffset, + value + ); + } + + // @ts-ignore: decorator + @inline + export function compareExchange( + array: T, + index: i32, + expectedValue: valueof, + replacementValue: valueof + ): valueof { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.cmpxchg>( + changetype(array.buffer) + (index << align) + array.byteOffset, + expectedValue, + replacementValue + ); + } + + // @ts-ignore: decorator + @inline + export function wait(array: T, value: valueof, timeout: i64 = -1): AtomicWaitResult { + return atomic.wait>(changetype(array.buffer) + array.byteOffset, value, timeout); + } + + // @ts-ignore: decorator + @inline + export function notify(array: T, index: i32, count: i32 = -1): i32 { + const align = alignof>(); + if (index < 0 || (index << align) >= array.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return atomic.notify(changetype(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; + @external("env", "Math.max") + export function max(value1: f64, value2: f64): f64; // TODO: rest + @external("env", "Math.min") + export function min(value1: f64, value2: f64): f64; // TODO: rest + @external("env", "Math.pow") + export function pow(base: f64, exponent: f64): f64; + @external("env", "Math.random") + export function random(): f64; + @external("env", "Math.round") + export function round(x: f64): f64; + @external("env", "Math.sign") + export function sign(x: f64): f64; + @external("env", "Math.sin") + export function sin(x: f64): f64; + @external("env", "Math.sinh") + export function sinh(x: f64): f64; + @external("env", "Math.sqrt") + export function sqrt(x: f64): f64; + @external("env", "Math.tan") + export function tan(x: f64): f64; + @external("env", "Math.tanh") + export function tanh(x: f64): f64; + @external("env", "Math.trunc") + export function trunc(x: f64): f64; +} + +export declare namespace Reflect { + @external("env", "Reflect.get") + export function get(target: externref, propertyKey: string): externref; + @external("env", "Reflect.getWithReceiver") + @external.js("return Reflect.get(target, propertyKey, receiver);") + export function getWithReceiver(target: externref, propertyKey: string, receiver: externref): externref; + @external("env", "Reflect.has") + export function has(target: externref, propertyKey: string): bool; + @external("env", "Reflect.set") + export function set(target: externref, propertyKey: string, value: externref): externref; + @external("env", "Reflect.setWithReceiver") + @external.js("return Reflect.set(target, propertyKey, value, receiver);") + export function setWithReceiver(target: externref, propertyKey: string, value: externref , receiver: externref): externref; + @external("env", "Reflect.apply") + export function apply(target: externref, thisArgument: externref, argumentsList: externref): externref; +} + +export declare namespace String { + @external("env", "String.fromCodePoint") + export function fromCodePoint(codepoint: i32): externref; + @external("env", "String.fromCodePoints") + @external.js("return String.fromCodePoint(...codepoints);") + export function fromCodePoints(codepoints: i32[]): externref; +} + +export declare namespace Date { + @external("env", "Date.now") + export function now(): f64; +} + +export declare namespace console { + @external("env", "console.assert") + export function assert(condition: bool, message: string): void; + @external("env", "console.log") + export function log(text: string): void; + @external("env", "console.debug") + export function debug(text: string): void; + @external("env", "console.info") + export function info(text: string): void; + @external("env", "console.warn") + export function warn(text: string): void; + @external("env", "console.error") + export function error(text: string): void; + @external("env", "console.time") + export function time(label: string): void; + @external("env", "console.timeLog") + export function timeLog(label: string): void; + @external("env", "console.timeEnd") + export function timeEnd(label: string): void; +} + +export declare namespace document { + @external("env", "document.getElementById") + export function getElementById(id: string): externref; +} + +export declare namespace performance { + @external("env", "performance.now") + export function now(): f64; +} + +export namespace crypto { + export function getRandomValues(array: Uint8Array): void { + let values = getRandomValuesN(array.length); + array.set(values); + } + @external("env", "crypto.getRandomValuesN") + @external.js("let a = new Uint8Array(n); crypto.getRandomValues(a); return a;") + export declare function getRandomValuesN(n: u32): Uint8Array; +} +`,"bindings/node":`export declare namespace process { + @external("env", "process.argv") + export const argv: string[]; + @external("env", "process.exit") + export function exit(code: i32): void; +} +`,"bindings/wasi_snapshot_preview1":`// Phase: wasi_snapshot_preview1 +// See: https://github.com/WebAssembly/WASI/tree/main/phases/snapshot/witx + +// helper types to be more explicit +type char = u8; +type ptr = usize; // all pointers are usize'd +type struct = T; // structs are references already in AS + +/** Read command-line argument data. */ +// @ts-ignore: decorator +@unsafe +export declare function args_get( + /** Input: Pointer to a buffer to write the argument pointers. */ + argv: ptr>, + /** Input: Pointer to a buffer to write the argument string data. */ + argv_buf: ptr +): errno; + +/** Return command-line argument data sizes. */ +// @ts-ignore: decorator +@unsafe +export declare function args_sizes_get( + /** Output: Number of arguments. */ + argc: ptr, + /** Output: Size of the argument string data. */ + argv_buf_size: ptr +): errno; + +/** Return the resolution of a clock. */ +// @ts-ignore: decorator +@unsafe +export declare function clock_res_get( + /** Input: The clock for which to return the resolution. */ + clock: clockid, + /** Output: The resolution of the clock. */ + resolution: ptr +): errno; + +/** Return the time value of a clock. */ +// @ts-ignore: decorator +@unsafe +export declare function clock_time_get( + /** Input: Cock for which to return the time. */ + clock: clockid, + /** Input: Maximum lag (exclusive) that the returned time value may have, compared to its actual value. */ + precision: timestamp, + /** Output: Time value of the clock. */ + time: ptr +): errno; + +/** Read environment variable data. */ +// @ts-ignore: decorator +@unsafe +export declare function environ_get( + /** Input: Pointer to a buffer to write the environment variable pointers. */ + environ: ptr, + /** Input: Pointer to a buffer to write the environment variable string data. */ + environ_buf: usize +): errno; + +/** Return command-line argument data sizes. */ +// @ts-ignore: decorator +@unsafe +export declare function environ_sizes_get( + /** Output: The number of environment variables. */ + environ_count: ptr, + /** Output: The size of the environment variable string data. */ + environ_buf_size: ptr +): errno; + +/** Provide file advisory information on a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_advise( + /** Input: The file descriptor for the file for which to provide file advisory information. */ + fd: fd, + /** Input: The offset within the file to which the advisory applies. */ + offset: filesize, + /** Input: The length of the region to which the advisory applies. */ + len: filesize, + /** Input: The advice. */ + advice: advice +): errno; + +/** Provide file advisory information on a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_allocate( + /** Input: The file descriptor for the file in which to allocate space. */ + fd: fd, + /** Input: The offset at which to start the allocation. */ + offset: filesize, + /** Input: The length of the area that is allocated. */ + len: filesize +): errno; + +/** Close a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_close( + /** Input: The file descriptor to close. */ + fd: fd +): errno; + +/** Synchronize the data of a file to disk. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_datasync( + /** Input: The file descriptor of the file to synchronize to disk. */ + fd: fd +): errno; + +/** Get the attributes of a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_fdstat_get( + /** Input: The file descriptor to inspect. */ + fd: fd, + /** Input: The buffer where the file descriptor's attributes are stored. */ + buf: struct +): errno; + +/** Adjust the flags associated with a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_fdstat_set_flags( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The desired values of the file descriptor flags. */ + flags: fdflags +): errno; + +/** Adjust the rights associated with a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_fdstat_set_rights( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The desired rights of the file descriptor. */ + fs_rights_base: rights, + /** Input: The desired rights of the file descriptor. */ + fs_rights_inheriting: rights +): errno; + +/** Return the attributes of an open file. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_filestat_get( + /** Input: The file descriptor to inspect. */ + fd: fd, + /** Input: The buffer where the file's attributes are stored. */ + buf: struct +): errno; + +/** Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_filestat_set_size( + /** Input: A file descriptor for the file to adjust. */ + fd: fd, + /** Input: The desired file size. */ + size: filesize +): errno; + +/** Adjust the timestamps of an open file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_filestat_set_times( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The desired values of the data access timestamp. */ + st_atim: timestamp, + /** Input: The desired values of the data modification timestamp. */ + st_mtim: timestamp, + /** Input: A bitmask indicating which timestamps to adjust. */ + fstflags: fstflags +): errno; + +/** Read from a file descriptor, without using and updating the file descriptor's offset. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_pread( + /** Input: The file descriptor from which to read data. */ + fd: fd, + /** Input: List of scatter/gather vectors in which to store data. */ + iovs: ptr>, + /** Input: Length of the list of scatter/gather vectors in which to store data. */ + iovs_len: usize, + /** Input: The offset within the file at which to read. */ + offset: filesize, + /** Output: The number of bytes read. */ + nread: ptr +): errno; + +/** Return a description of the given preopened file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_prestat_get( + /** Input: The file descriptor about which to retrieve information. */ + fd: fd, + /** Input: The buffer where the description is stored. */ + buf: struct +): errno; + +/** Return a description of the given preopened file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_prestat_dir_name( + /** Input: The file descriptor about which to retrieve information. */ + fd: fd, + /** Input: Buffer into which to write the preopened directory name. */ + path: ptr, + /** Input: Length of the buffer into which to write the preopened directory name. */ + path_len: usize +): errno; + +/** Write to a file descriptor, without using and updating the file descriptor's offset. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_pwrite( + /** Input: The file descriptor to which to write data. */ + fd: fd, + /** Input: List of scatter/gather vectors from which to retrieve data. */ + iovs: ptr>, + /** Input: Length of the list of scatter/gather vectors from which to retrieve data. */ + iovs_len: usize, + /** Input: The offset within the file at which to write. */ + offset: filesize, + /** Output: The number of bytes written. */ + nwritten: ptr +): errno; + +/** Read from a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_read( + /** Input: The file descriptor from which to read data. */ + fd: fd, + /** Input: List of scatter/gather vectors to which to store data. */ + iovs: ptr>, + /** Input: Length of the list of scatter/gather vectors to which to store data. */ + iovs_len: usize, + /** Output: The number of bytes read. */ + nread: ptr +): errno; + +/** Read directory entries from a directory. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_readdir( + /** Input: Directory from which to read the directory entries. */ + fd: fd, + /** Input: Buffer where directory entries are stored. */ + buf: ptr>, + /** Input: Length of the buffer where directory entries are stored. */ + buf_len: usize, + /** Input: Location within the directory to start reading. */ + cookie: dircookie, + /** Output: Number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. */ + buf_used: ptr +): errno; + +/** Atomically replace a file descriptor by renumbering another file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_renumber( + /** Input: The file descriptor to renumber. */ + from: fd, + /** Input: The file descriptor to overwrite. */ + to: fd +): errno; + +/** Move the offset of a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_seek( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The number of bytes to move. */ + offset: filedelta, + /** Input: The base from which the offset is relative. */ + whence: whence, + /** Output: The new offset of the file descriptor, relative to the start of the file. */ + newoffset: ptr +): errno; + +/** Synchronize the data and metadata of a file to disk. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_sync( + /** Input: The file descriptor of the file containing the data and metadata to synchronize to disk. */ + fd: fd +): errno; + +/** Return the current offset of a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_tell( + /** Input: The file descriptor to inspect. */ + fd: fd, + /** Output: The current offset of the file descriptor, relative to the start of the file. */ + newoffset: ptr +): errno; + +/** Write to a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_write( + /** Input: The file descriptor to which to write data. */ + fd: fd, + /** Input: List of scatter/gather vectors from which to retrieve data. */ + iovs: ptr>, + /** Input: List of scatter/gather vectors from which to retrieve data. */ + iovs_len: usize, + /** Output: The number of bytes written. */ + nwritten: ptr +): errno; + +/* Create a directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_create_directory( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path at which to create the directory. */ + path: ptr, + /** Input: The path at which to create the directory. */ + path_len: usize +): errno; + +/** Return the attributes of a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_filestat_get( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + flags: lookupflags, + /** Input: The path of the file or directory to inspect. */ + path: ptr, + /** Input: The path of the file or directory to inspect. */ + path_len: usize, + /** Input: The buffer where the file's attributes are stored. */ + buf: struct +): errno; + +/** Adjust the timestamps of a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_filestat_set_times( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + flags: lookupflags, + /** Input: The path of the file or directory to operate on. */ + path: ptr, + /** Input: The path of the file or directory to operate on. */ + path_len: usize, + /** Input: The desired values of the data access timestamp. */ + st_atim: timestamp, + /** Input: The desired values of the data modification timestamp. */ + st_mtim: timestamp, + /** Input: A bitmask indicating which timestamps to adjust. */ + fstflags: fstflags +): errno; + +/** Create a hard link. */ +// @ts-ignore: decorator +@unsafe +export declare function path_link( + /** Input: The working directory at which the resolution of the old path starts. */ + old_fd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + old_flags: lookupflags, + /** Input: The source path from which to link. */ + old_path: ptr, + /** Input: The source path from which to link. */ + old_path_len: usize, + /** Input: The working directory at which the resolution of the new path starts. */ + new_fd: fd, + /** Input: The destination path at which to create the hard link. */ + new_path: ptr, + /** Input: The length of the destination path at which to create the hard link. */ + new_path_len: usize +): errno; + +/** Open a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_open( + /** Input: The working directory at which the resolution of the path starts. */ + dirfd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + dirflags: lookupflags, + /** Input: The path of the file or directory to open. */ + path: ptr, + /** Input: The length of the path of the file or directory to open. */ + path_len: usize, + /** Input: The method by which to open the file. */ + oflags: oflags, + /** Input: The initial base rights that apply to operations using the file descriptor itself. */ + fs_rights_base: rights, + /** Input: The initial inheriting rights that apply to file descriptors derived from it. */ + fs_rights_inheriting: rights, + /** Input: The initial flags of the file descriptor. */ + fs_flags: fdflags, + /** Output: The file descriptor of the file that has been opened. */ + fd: ptr +): errno; + +/** Read the contents of a symbolic link. */ +// @ts-ignore: decorator +@unsafe +export declare function path_readlink( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path of the symbolic link from which to read. */ + path: ptr, + /** Input: The length of the path of the symbolic link from which to read. */ + path_len: usize, + /** Input: The buffer to which to write the contents of the symbolic link. */ + buf: ptr, + /** Input: The length of the buffer to which to write the contents of the symbolic link. */ + buf_len: usize, + /** Output: The number of bytes placed in the buffer. */ + buf_used: ptr +): errno; + +/** Remove a directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_remove_directory( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path to a directory to remove. */ + path: ptr, + /** Input: The length of the path to a directory to remove. */ + path_len: usize +): errno; + +/** Rename a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_rename( + /** Input: The working directory at which the resolution of the old path starts. */ + old_fd: fd, + /** Input: The source path of the file or directory to rename. */ + old_path: ptr, + /** Input: The length of the source path of the file or directory to rename. */ + old_path_len: usize, + /** Input: The working directory at which the resolution of the new path starts. */ + new_fd: fd, + /** Input: The destination path to which to rename the file or directory. */ + new_path: ptr, + /** Input: The length of the destination path to which to rename the file or directory. */ + new_path_len: usize +): errno; + +/** Create a symbolic link. */ +// @ts-ignore: decorator +@unsafe +export declare function path_symlink( + /** Input: The contents of the symbolic link. */ + old_path: ptr, + /** Input: The length of the contents of the symbolic link. */ + old_path_len: usize, + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The destination path at which to create the symbolic link. */ + new_path: ptr, + /** Input: The length of the destination path at which to create the symbolic link. */ + new_path_len: usize +): errno; + +/** Unlink a file. */ +// @ts-ignore: decorator +@unsafe +export declare function path_unlink_file( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path to a file to unlink. */ + path: ptr, + /** Input: The length of the path to a file to unlink. */ + path_len: usize +): errno; + +/** Concurrently poll for the occurrence of a set of events. */ +// @ts-ignore: decorator +@unsafe +export declare function poll_oneoff( + /** Input: The events to which to subscribe. */ + in_: ptr>, + /** Input: The events that have occurred. */ + out: ptr>, + /** Input: Both the number of subscriptions and events. */ + nsubscriptions: usize, + /** Output: The number of events stored. */ + nevents: ptr +): errno; + +/** Terminate the process normally. An exit code of 0 indicates successful termination of the program. The meanings of other values is dependent on the environment. */ +// @ts-ignore: decorator +@unsafe +export declare function proc_exit( + /** Input: The exit code returned by the process. */ + rval: u32 +): void; + +/** Send a signal to the process of the calling thread. */ +// @ts-ignore: decorator +@unsafe +export declare function proc_raise( + /** Input: The signal condition to trigger. */ + sig: signal +): errno; + +/** Write high-quality random data into a buffer. */ +// @ts-ignore: decorator +@unsafe +export declare function random_get( + /** Input: The buffer to fill with random data. */ + buf: usize, + /** Input: The length of the buffer to fill with random data. */ + buf_len: usize +): errno; + +/** Temporarily yield execution of the calling thread. */ +// @ts-ignore: decorator +@unsafe +export declare function sched_yield(): errno; + +/** Receive a message from a socket. */ +// @ts-ignore: decorator +@unsafe +export declare function sock_recv( + /** Input: The socket on which to receive data. */ + sock: fd, + /** Input: List of scatter/gather vectors to which to store data. */ + ri_data: ptr>, + /** Input: The length of the list of scatter/gather vectors to which to store data. */ + ri_data_len: usize, + /** Input: Message flags. */ + ri_flags: riflags, + /** Output: Number of bytes stored in \`ri_data\`. */ + ro_datalen: ptr, + /** Output: Message flags. */ + ro_flags: ptr +): errno; + +/** Send a message on a socket. */ +// @ts-ignore: decorator +@unsafe +export declare function sock_send( + /** Input: The socket on which to send data. */ + sock: fd, + /** Input: List of scatter/gather vectors to which to retrieve data */ + si_data: ptr>, + /** Input: The length of the list of scatter/gather vectors to which to retrieve data */ + si_data_len: usize, + /** Input: Message flags. */ + si_flags: siflags, + /** Output: Number of bytes transmitted. */ + so_datalen: ptr +): errno; + +/** Shut down socket send and receive channels. */ +// @ts-ignore: decorator +@unsafe +export declare function sock_shutdown( + /** Input: The socket on which to shutdown channels. */ + sock: fd, + /** Input: Which channels on the socket to shut down. */ + how: sdflags +): errno; + +// === Types ====================================================================================== + +/** File or memory access pattern advisory information. */ +export namespace advice { + /** The application has no advice to give on its behavior with respect to the specified data. */ + // @ts-ignore: decorator + @inline + export const NORMAL: advice = 0; + /** The application expects to access the specified data sequentially from lower offsets to higher offsets. */ + // @ts-ignore: decorator + @inline + export const SEQUENTIAL : advice = 1; + /** The application expects to access the specified data in a random order. */ + // @ts-ignore: decorator + @inline + export const RANDOM: advice = 2; + /** The application expects to access the specified data in the near future. */ + // @ts-ignore: decorator + @inline + export const WILLNEED: advice = 3; + /** The application expects that it will not access the specified data in the near future. */ + // @ts-ignore: decorator + @inline + export const DONTNEED: advice = 4; + /** The application expects to access the specified data once and then not reuse it thereafter. */ + // @ts-ignore: decorator + @inline + export const NOREUSE: advice = 5; +} +export type advice = u8; + +/** Identifiers for clocks. */ +export namespace clockid { + /** The clock measuring real time. Time value zero corresponds with 1970-01-01T00:00:00Z. */ + // @ts-ignore: decorator + @inline + export const REALTIME: clockid = 0; + /** The store-wide monotonic clock. Absolute value has no meaning. */ + // @ts-ignore: decorator + @inline + export const MONOTONIC: clockid = 1; + /** The CPU-time clock associated with the current process. */ + // @ts-ignore: decorator + @inline + export const PROCESS_CPUTIME_ID: clockid = 2; + /** The CPU-time clock associated with the current thread. */ + // @ts-ignore: decorator + @inline + export const THREAD_CPUTIME_ID: clockid = 3; +} +export type clockid = u32; + +/** Identifier for a device containing a file system. Can be used in combination with \`inode\` to uniquely identify a file or directory in the filesystem. */ +export type device = u64; + +/** A reference to the offset of a directory entry. The value 0 signifies the start of the directory. */ +export type dircookie = u64; + +/** A directory entry. */ +@unmanaged export class dirent { + /** The offset of the next directory entry stored in this directory. */ + next: dircookie; + /** The serial number of the file referred to by this directory entry. */ + ino: inode; + /** The length of the name of the directory entry. */ + namlen: u32; + /** The type of the file referred to by this directory entry. */ + type: filetype; + private __padding0: u16; +} + +/** Error codes returned by functions. */ +export namespace errno { + /** No error occurred. System call completed successfully. */ + // @ts-ignore: decorator + @inline + export const SUCCESS: errno = 0; + /** Argument list too long. */ + // @ts-ignore: decorator + @inline + export const TOOBIG: errno = 1; + /** Permission denied. */ + // @ts-ignore: decorator + @inline + export const ACCES: errno = 2; + /** Address in use. */ + // @ts-ignore: decorator + @inline + export const ADDRINUSE: errno = 3; + /** Address not available. */ + // @ts-ignore: decorator + @inline + export const ADDRNOTAVAIL: errno = 4; + /** Address family not supported. */ + // @ts-ignore: decorator + @inline + export const AFNOSUPPORT: errno = 5; + /** Resource unavailable, or operation would block. */ + // @ts-ignore: decorator + @inline + export const AGAIN: errno = 6; + /** Connection already in progress. */ + // @ts-ignore: decorator + @inline + export const ALREADY: errno = 7; + /** Bad file descriptor. */ + // @ts-ignore: decorator + @inline + export const BADF: errno = 8; + /** Bad message. */ + // @ts-ignore: decorator + @inline + export const BADMSG: errno = 9; + /** Device or resource busy. */ + // @ts-ignore: decorator + @inline + export const BUSY: errno = 10; + /** Operation canceled. */ + // @ts-ignore: decorator + @inline + export const CANCELED: errno = 11; + /** No child processes. */ + // @ts-ignore: decorator + @inline + export const CHILD: errno = 12; + /** Connection aborted. */ + // @ts-ignore: decorator + @inline + export const CONNABORTED: errno = 13; + /** Connection refused. */ + // @ts-ignore: decorator + @inline + export const CONNREFUSED: errno = 14; + /** Connection reset. */ + // @ts-ignore: decorator + @inline + export const CONNRESET: errno = 15; + /** Resource deadlock would occur. */ + // @ts-ignore: decorator + @inline + export const DEADLK: errno = 16; + /** Destination address required. */ + // @ts-ignore: decorator + @inline + export const DESTADDRREQ: errno = 17; + /** Mathematics argument out of domain of function. */ + // @ts-ignore: decorator + @inline + export const DOM: errno = 18; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const DQUOT: errno = 19; + /** File exists. */ + // @ts-ignore: decorator + @inline + export const EXIST: errno = 20; + /** Bad address. */ + // @ts-ignore: decorator + @inline + export const FAULT: errno = 21; + /** File too large. */ + // @ts-ignore: decorator + @inline + export const FBIG: errno = 22; + /** Host is unreachable. */ + // @ts-ignore: decorator + @inline + export const HOSTUNREACH: errno = 23; + /** Identifier removed. */ + // @ts-ignore: decorator + @inline + export const IDRM: errno = 24; + /** Illegal byte sequence. */ + // @ts-ignore: decorator + @inline + export const ILSEQ: errno = 25; + /** Operation in progress. */ + // @ts-ignore: decorator + @inline + export const INPROGRESS: errno = 26; + /** Interrupted function. */ + // @ts-ignore: decorator + @inline + export const INTR: errno = 27; + /** Invalid argument. */ + // @ts-ignore: decorator + @inline + export const INVAL: errno = 28; + /** I/O error. */ + // @ts-ignore: decorator + @inline + export const IO: errno = 29; + /** Socket is connected. */ + // @ts-ignore: decorator + @inline + export const ISCONN: errno = 30; + /** Is a directory. */ + // @ts-ignore: decorator + @inline + export const ISDIR: errno = 31; + /** Too many levels of symbolic links. */ + // @ts-ignore: decorator + @inline + export const LOOP: errno = 32; + /** File descriptor value too large. */ + // @ts-ignore: decorator + @inline + export const MFILE: errno = 33; + /** Too many links. */ + // @ts-ignore: decorator + @inline + export const MLINK: errno = 34; + /** Message too large. */ + // @ts-ignore: decorator + @inline + export const MSGSIZE: errno = 35; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const MULTIHOP: errno = 36; + /** Filename too long. */ + // @ts-ignore: decorator + @inline + export const NAMETOOLONG: errno = 37; + /** Network is down. */ + // @ts-ignore: decorator + @inline + export const NETDOWN: errno = 38; + /** Connection aborted by network. */ + // @ts-ignore: decorator + @inline + export const NETRESET: errno = 39; + /** Network unreachable. */ + // @ts-ignore: decorator + @inline + export const NETUNREACH: errno = 40; + /** Too many files open in system. */ + // @ts-ignore: decorator + @inline + export const NFILE: errno = 41; + /** No buffer space available. */ + // @ts-ignore: decorator + @inline + export const NOBUFS: errno = 42; + /** No such device. */ + // @ts-ignore: decorator + @inline + export const NODEV: errno = 43; + /** No such file or directory. */ + // @ts-ignore: decorator + @inline + export const NOENT: errno = 44; + /** Executable file format error. */ + // @ts-ignore: decorator + @inline + export const NOEXEC: errno = 45; + /** No locks available. */ + // @ts-ignore: decorator + @inline + export const NOLCK: errno = 46; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const NOLINK: errno = 47; + /** Not enough space. */ + // @ts-ignore: decorator + @inline + export const NOMEM: errno = 48; + /** No message of the desired type. */ + // @ts-ignore: decorator + @inline + export const NOMSG: errno = 49; + /** Protocol not available. */ + // @ts-ignore: decorator + @inline + export const NOPROTOOPT: errno = 50; + /** No space left on device. */ + // @ts-ignore: decorator + @inline + export const NOSPC: errno = 51; + /** Function not supported. */ + // @ts-ignore: decorator + @inline + export const NOSYS: errno = 52; + /** The socket is not connected. */ + // @ts-ignore: decorator + @inline + export const NOTCONN: errno = 53; + /** Not a directory or a symbolic link to a directory. */ + // @ts-ignore: decorator + @inline + export const NOTDIR: errno = 54; + /** Directory not empty. */ + // @ts-ignore: decorator + @inline + export const NOTEMPTY: errno = 55; + /** State not recoverable. */ + // @ts-ignore: decorator + @inline + export const NOTRECOVERABLE: errno = 56; + /** Not a socket. */ + // @ts-ignore: decorator + @inline + export const NOTSOCK: errno = 57; + /** Not supported, or operation not supported on socket. */ + // @ts-ignore: decorator + @inline + export const NOTSUP: errno = 58; + /** Inappropriate I/O control operation. */ + // @ts-ignore: decorator + @inline + export const NOTTY: errno = 59; + /** No such device or address. */ + // @ts-ignore: decorator + @inline + export const NXIO: errno = 60; + /** Value too large to be stored in data type. */ + // @ts-ignore: decorator + @inline + export const OVERFLOW: errno = 61; + /** Previous owner died. */ + // @ts-ignore: decorator + @inline + export const OWNERDEAD: errno = 62; + /** Operation not permitted. */ + // @ts-ignore: decorator + @inline + export const PERM: errno = 63; + /** Broken pipe. */ + // @ts-ignore: decorator + @inline + export const PIPE: errno = 64; + /** Protocol error. */ + // @ts-ignore: decorator + @inline + export const PROTO: errno = 65; + /** Protocol not supported. */ + // @ts-ignore: decorator + @inline + export const PROTONOSUPPORT: errno = 66; + /** Protocol wrong type for socket. */ + // @ts-ignore: decorator + @inline + export const PROTOTYPE: errno = 67; + /** Result too large. */ + // @ts-ignore: decorator + @inline + export const RANGE: errno = 68; + /** Read-only file system. */ + // @ts-ignore: decorator + @inline + export const ROFS: errno = 69; + /** Invalid seek. */ + // @ts-ignore: decorator + @inline + export const SPIPE: errno = 70; + /** No such process. */ + // @ts-ignore: decorator + @inline + export const SRCH: errno = 71; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const STALE: errno = 72; + /** Connection timed out. */ + // @ts-ignore: decorator + @inline + export const TIMEDOUT: errno = 73; + /** Text file busy. */ + // @ts-ignore: decorator + @inline + export const TXTBSY: errno = 74; + /** Cross-device link. */ + // @ts-ignore: decorator + @inline + export const XDEV: errno = 75; + /** Extension: Capabilities insufficient. */ + // @ts-ignore: decorator + @inline + export const NOTCAPABLE: errno = 76; +} +export type errno = u16; + +/** Translates an error code to a string. */ +export function errnoToString(err: errno): string { + switch (err) { + case errno.SUCCESS: return "SUCCESS"; + case errno.TOOBIG: return "TOOBIG"; + case errno.ACCES: return "ACCES"; + case errno.ADDRINUSE: return "ADDRINUSE"; + case errno.ADDRNOTAVAIL: return "ADDRNOTAVAIL"; + case errno.AFNOSUPPORT: return "AFNOSUPPORT"; + case errno.AGAIN: return "AGAIN"; + case errno.ALREADY: return "ALREADY"; + case errno.BADF: return "BADF"; + case errno.BADMSG: return "BADMSG"; + case errno.BUSY: return "BUSY"; + case errno.CANCELED: return "CANCELED"; + case errno.CHILD: return "CHILD"; + case errno.CONNABORTED: return "CONNABORTED"; + case errno.CONNREFUSED: return "CONNREFUSED"; + case errno.CONNRESET: return "CONNRESET"; + case errno.DEADLK: return "DEADLK"; + case errno.DESTADDRREQ: return "DESTADDRREQ"; + case errno.DOM: return "DOM"; + case errno.DQUOT: return "DQUOT"; + case errno.EXIST: return "EXIST"; + case errno.FAULT: return "FAULT"; + case errno.FBIG: return "FBIG"; + case errno.HOSTUNREACH: return "HOSTUNREACH"; + case errno.IDRM: return "IDRM"; + case errno.ILSEQ: return "ILSEQ"; + case errno.INPROGRESS: return "INPROGRESS"; + case errno.INTR: return "INTR"; + case errno.INVAL: return "INVAL"; + case errno.IO: return "IO"; + case errno.ISCONN: return "ISCONN"; + case errno.ISDIR: return "ISDIR"; + case errno.LOOP: return "LOOP"; + case errno.MFILE: return "MFILE"; + case errno.MLINK: return "MLINK"; + case errno.MSGSIZE: return "MSGSIZE"; + case errno.MULTIHOP: return "MULTIHOP"; + case errno.NAMETOOLONG: return "NAMETOOLONG"; + case errno.NETDOWN: return "NETDOWN"; + case errno.NETRESET: return "NETRESET"; + case errno.NETUNREACH: return "NETUNREACH"; + case errno.NFILE: return "NFILE"; + case errno.NOBUFS: return "NOBUFS"; + case errno.NODEV: return "NODEV"; + case errno.NOENT: return "NOENT"; + case errno.NOEXEC: return "NOEXEC"; + case errno.NOLCK: return "NOLCK"; + case errno.NOLINK: return "NOLINK"; + case errno.NOMEM: return "NOMEM"; + case errno.NOMSG: return "NOMSG"; + case errno.NOPROTOOPT: return "NOPROTOOPT"; + case errno.NOSPC: return "NOSPC"; + case errno.NOSYS: return "NOSYS"; + case errno.NOTCONN: return "NOTCONN"; + case errno.NOTDIR: return "NOTDIR"; + case errno.NOTEMPTY: return "NOTEMPTY"; + case errno.NOTRECOVERABLE: return "NOTRECOVERABLE"; + case errno.NOTSOCK: return "NOTSOCK"; + case errno.NOTSUP: return "NOTSUP"; + case errno.NOTTY: return "NOTTY"; + case errno.NXIO: return "NXIO"; + case errno.OVERFLOW: return "OVERFLOW"; + case errno.OWNERDEAD: return "OWNERDEAD"; + case errno.PERM: return "PERM"; + case errno.PIPE: return "PIPE"; + case errno.PROTO: return "PROTO"; + case errno.PROTONOSUPPORT: return "PROTONOSUPPORT"; + case errno.PROTOTYPE: return "PROTOTYPE"; + case errno.RANGE: return "RANGE"; + case errno.ROFS: return "ROFS"; + case errno.SPIPE: return "SPIPE"; + case errno.SRCH: return "SRCH"; + case errno.STALE: return "STALE"; + case errno.TIMEDOUT: return "TIMEDOUT"; + case errno.TXTBSY: return "TXTBSY"; + case errno.XDEV: return "XDEV"; + case errno.NOTCAPABLE: return "NOTCAPABLE"; + } + return "UNKNOWN"; +} + +@unmanaged abstract class $event { // size=16/32 + /** User-provided value that got attached to \`subscription#userdata\`. */ + userdata: userdata; + /** If non-zero, an error that occurred while processing the subscription request. */ + error: errno; + /** The type of the event that occurred. */ + type: eventtype; + + private __padding0: u16; +} + +/** An event that occurred. */ +@unmanaged export abstract class event extends $event { + private __padding1: u64; + private __padding2: u64; +} + +/** An event that occurred when type is \`eventtype.FD_READ\` or \`eventtype.FD_WRITE\`. */ +@unmanaged export class event_fd_readwrite extends $event { + /* The number of bytes available for reading or writing. */ + nbytes: filesize; + /* The state of the file descriptor. */ + flags: eventrwflags; + + private __padding1: u32; +} + +/** The state of the file descriptor subscribed to with \`eventtype.FD_READ\` or \`eventtype.FD_WRITE\`. */ +export namespace eventrwflags { + /** The peer of this socket has closed or disconnected. */ + // @ts-ignore: decorator + @inline + export const HANGUP: eventrwflags = 1; +} +export type eventrwflags = u16; + +/** Type of a subscription to an event or its occurrence. */ +export namespace eventtype { + /** The time value of clock has reached the timestamp. */ + // @ts-ignore: decorator + @inline + export const CLOCK: eventtype = 0; + /** File descriptor has data available for reading. */ + // @ts-ignore: decorator + @inline + export const FD_READ: eventtype = 1; + /** File descriptor has capacity available for writing */ + // @ts-ignore: decorator + @inline + export const FD_WRITE: eventtype = 2; +} +export type eventtype = u8; + +/** Exit code generated by a process when exiting. */ +export type exitcode = u32; + +/** A file descriptor number. */ +export type fd = u32; + +/** File descriptor flags. */ +export namespace fdflags { + /** Append mode: Data written to the file is always appended to the file's end. */ + // @ts-ignore: decorator + @inline + export const APPEND: fdflags = 1; + /** Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized. */ + // @ts-ignore: decorator + @inline + export const DSYNC: fdflags = 2; + /** Non-blocking mode. */ + // @ts-ignore: decorator + @inline + export const NONBLOCK: fdflags = 4; + /** Synchronized read I/O operations. */ + // @ts-ignore: decorator + @inline + export const RSYNC: fdflags = 8; + /** Write according to synchronized I/O file integrity completion. */ + // @ts-ignore: decorator + @inline + export const SYNC: fdflags = 16; +} +export type fdflags = u16; + +/** File descriptor attributes. */ +@unmanaged export class fdstat { + /** File type. */ + filetype: filetype; + /** File descriptor flags. */ + flags: fdflags; + /** Rights that apply to this file descriptor. */ + rights_base: rights; + /** Maximum set of rights that may be installed on new file descriptors that are created through this file descriptor, e.g., through \`path_open\`. */ + rights_inheriting: rights; +} + +/** Relative offset within a file. */ +export type filedelta = i64; + +/** Non-negative file size or length of a region within a file. */ +export type filesize = u64; + +/** File attributes. */ +@unmanaged export class filestat { + /** Device ID of device containing the file. */ + dev: device; + /** File serial number. */ + ino: inode; + /** File type. */ + filetype: filetype; + /** Number of hard links to the file. */ + nlink: linkcount; + /** For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link. */ + size: filesize; + /** Last data access timestamp. */ + atim: timestamp; + /** Last data modification timestamp. */ + mtim: timestamp; + /** Last file status change timestamp. */ + ctim: timestamp; +} + +/** The type of a file descriptor or file. */ +export namespace filetype { + /** The type of the file descriptor or file is unknown or is different from any of the other types specified. */ + // @ts-ignore: decorator + @inline + export const UNKNOWN: filetype = 0; + /** The file descriptor or file refers to a block device inode. */ + // @ts-ignore: decorator + @inline + export const BLOCK_DEVICE: filetype = 1; + /** The file descriptor or file refers to a character device inode. */ + // @ts-ignore: decorator + @inline + export const CHARACTER_DEVICE: filetype = 2; + /** The file descriptor or file refers to a directory inode. */ + // @ts-ignore: decorator + @inline + export const DIRECTORY: filetype = 3; + /** The file descriptor or file refers to a regular file inode. */ + // @ts-ignore: decorator + @inline + export const REGULAR_FILE: filetype = 4; + /** The file descriptor or file refers to a datagram socket. */ + // @ts-ignore: decorator + @inline + export const SOCKET_DGRAM: filetype = 5; + /** The file descriptor or file refers to a byte-stream socket. */ + // @ts-ignore: decorator + @inline + export const SOCKET_STREAM: filetype = 6; + /** The file refers to a symbolic link inode. */ + // @ts-ignore: decorator + @inline + export const SYMBOLIC_LINK: filetype = 7; +} +export type filetype = u8; + +/** Which file time attributes to adjust. */ +export namespace fstflags { + /** Adjust the last data access timestamp to the value stored in \`filestat#st_atim\`. */ + // @ts-ignore: decorator + @inline + export const SET_ATIM: fstflags = 1; + /** Adjust the last data access timestamp to the time of clock \`clockid.REALTIME\`. */ + // @ts-ignore: decorator + @inline + export const SET_ATIM_NOW: fstflags = 2; + /** Adjust the last data modification timestamp to the value stored in \`filestat#st_mtim\`. */ + // @ts-ignore: decorator + @inline + export const SET_MTIM: fstflags = 4; + /** Adjust the last data modification timestamp to the time of clock \`clockid.REALTIME\`. */ + // @ts-ignore: decorator + @inline + export const SET_MTIM_NOW: fstflags = 8; +} +export type fstflags = u16; + +/** File serial number that is unique within its file system. */ +export type inode = u64; + +/** A region of memory for scatter/gather reads. */ +@unmanaged export class iovec { + /** The address of the buffer to be filled. */ + buf: usize; + /** The length of the buffer to be filled. */ + buf_len: usize; +} + +/** Number of hard links to an inode. */ +export type linkcount = u64; + +/** Flags determining the method of how paths are resolved. */ +export namespace lookupflags { + /** As long as the resolved path corresponds to a symbolic link, it is expanded. */ + // @ts-ignore: decorator + @inline + export const SYMLINK_FOLLOW: lookupflags = 1; +} +export type lookupflags = u32; + +/** Open flags. */ +export namespace oflags { + /** Create file if it does not exist. */ + // @ts-ignore: decorator + @inline + export const CREAT: oflags = 1; + /** Fail if not a directory. */ + // @ts-ignore: decorator + @inline + export const DIRECTORY: oflags = 2; + /** Fail if file already exists. */ + // @ts-ignore: decorator + @inline + export const EXCL: oflags = 4; + /** Truncate file to size 0. */ + // @ts-ignore: decorator + @inline + export const TRUNC: oflags = 8; +} +export type oflags = u16; + +/** Identifiers for preopened capabilities. */ +export namespace preopentype { + /** A pre-opened directory. */ + // @ts-ignore: decorator + @inline + export const DIR: preopentype = 0; +} +export type preopentype = u8; + +@unmanaged abstract class $prestat { // WASM32: size=1/8, WASM64: size=1/16 + /* The type of the pre-opened capability. */ + type: preopentype; +} + +/* Information about a pre-opened capability. */ +@unmanaged export abstract class prestat extends $prestat { + private __padding0: usize; +} + +/** The contents of a $prestat when type is \`preopentype.DIR\`. */ +@unmanaged export class prestat_dir extends $prestat { + /** The length of the directory name for use with \`fd_prestat_dir_name\`. */ + name_len: usize; +} + +/** Flags provided to \`sock_recv\`. */ +export namespace riflags { + /** Returns the message without removing it from the socket's receive queue. */ + // @ts-ignore: decorator + @inline + export const PEEK: riflags = 1; + /** On byte-stream sockets, block until the full amount of data can be returned. */ + // @ts-ignore: decorator + @inline + export const WAITALL: riflags = 2; +} +export type riflags = u16; + +/** File descriptor rights, determining which actions may be performed. */ +export namespace rights { + /** The right to invoke \`fd_datasync\`. */ + // @ts-ignore: decorator + @inline + export const FD_DATASYNC: rights = 1; + /** The right to invoke \`fd_read\` and \`sock_recv\`. */ + // @ts-ignore: decorator + @inline + export const FD_READ: rights = 2; + /** The right to invoke \`fd_seek\`. This flag implies \`rights.FD_TELL\`. */ + // @ts-ignore: decorator + @inline + export const FD_SEEK: rights = 4; + /** The right to invoke \`fd_fdstat_set_flags\`. */ + // @ts-ignore: decorator + @inline + export const FD_FDSTAT_SET_FLAGS: rights = 8; + /** The right to invoke \`fd_sync\`. */ + // @ts-ignore: decorator + @inline + export const FD_SYNC: rights = 16; + /** The right to invoke \`fd_seek\` in such a way that the file offset remains unaltered (i.e., \`whence.CUR\` with offset zero), or to invoke \`fd_tell\`). */ + // @ts-ignore: decorator + @inline + export const FD_TELL: rights = 32; + /** The right to invoke \`fd_write\` and \`sock_send\`. If \`rights.FD_SEEK\` is set, includes the right to invoke \`fd_pwrite\`. */ + // @ts-ignore: decorator + @inline + export const FD_WRITE: rights = 64; + /** The right to invoke \`fd_advise\`. */ + // @ts-ignore: decorator + @inline + export const FD_ADVISE: rights = 128; + /** The right to invoke \`fd_allocate\`. */ + // @ts-ignore: decorator + @inline + export const FD_ALLOCATE: rights = 256; + /** The right to invoke \`path_create_directory\`. */ + // @ts-ignore: decorator + @inline + export const PATH_CREATE_DIRECTORY: rights = 512; + /** If \`rights.PATH_OPEN\` is set, the right to invoke \`path_open\` with \`oflags.CREAT\`. */ + // @ts-ignore: decorator + @inline + export const PATH_CREATE_FILE: rights = 1024; + /** The right to invoke \`path_link\` with the file descriptor as the source directory. */ + // @ts-ignore: decorator + @inline + export const PATH_LINK_SOURCE: rights = 2048; + /** The right to invoke \`path_link\` with the file descriptor as the target directory. */ + // @ts-ignore: decorator + @inline + export const PATH_LINK_TARGET: rights = 4096; + /** The right to invoke \`path_open\`. */ + // @ts-ignore: decorator + @inline + export const PATH_OPEN: rights = 8192; + /** The right to invoke \`fd_readdir\`. */ + // @ts-ignore: decorator + @inline + export const FD_READDIR: rights = 16384; + /** The right to invoke \`path_readlink\`. */ + // @ts-ignore: decorator + @inline + export const PATH_READLINK: rights = 32768; + /** The right to invoke \`path_rename\` with the file descriptor as the source directory. */ + // @ts-ignore: decorator + @inline + export const PATH_RENAME_SOURCE: rights = 65536; + /** The right to invoke \`path_rename\` with the file descriptor as the target directory. */ + // @ts-ignore: decorator + @inline + export const PATH_RENAME_TARGET: rights = 131072; + /** The right to invoke \`path_filestat_get\`. */ + // @ts-ignore: decorator + @inline + export const PATH_FILESTAT_GET: rights = 262144; + /** The right to change a file's size (there is no \`path_filestat_set_size\`). If \`rights.PATH_OPEN\` is set, includes the right to invoke \`path_open\` with \`oflags.TRUNC\`. */ + // @ts-ignore: decorator + @inline + export const PATH_FILESTAT_SET_SIZE: rights = 524288; + /** The right to invoke \`path_filestat_set_times\`. */ + // @ts-ignore: decorator + @inline + export const PATH_FILESTAT_SET_TIMES: rights = 1048576; + /** The right to invoke \`fd_filestat_get\`. */ + // @ts-ignore: decorator + @inline + export const FD_FILESTAT_GET: rights = 2097152; + /** The right to invoke \`fd_filestat_set_size\`. */ + // @ts-ignore: decorator + @inline + export const FD_FILESTAT_SET_SIZE: rights = 4194304; + /** The right to invoke \`fd_filestat_set_times\`. */ + // @ts-ignore: decorator + @inline + export const FD_FILESTAT_SET_TIMES: rights = 8388608; + /** The right to invoke \`path_symlink\`. */ + // @ts-ignore: decorator + @inline + export const RIGHT_PATH_SYMLINK: rights = 16777216; + /** The right to invoke \`path_remove_directory\`. */ + // @ts-ignore: decorator + @inline + export const PATH_REMOVE_DIRECTORY: rights = 33554432; + /** The right to invoke \`path_unlink_file\`. */ + // @ts-ignore: decorator + @inline + export const PATH_UNLINK_FILE: rights = 67108864; + /** If \`rights.FD_READ\` is set, includes the right to invoke \`poll_oneoff\` to subscribe to \`eventtype.FD_READ\`. If \`rights.FD_WRITE\` is set, includes the right to invoke \`poll_oneoff\` to subscribe to \`eventtype.FD_WRITE\`. */ + // @ts-ignore: decorator + @inline + export const POLL_FD_READWRITE: rights = 134217728; + /** The right to invoke \`sock_shutdown\`. */ + // @ts-ignore: decorator + @inline + export const SOCK_SHUTDOWN: rights = 268435456; +} +export type rights = u64; + +/** Flags returned by \`sock_recv\`. */ +export namespace roflags { + /** Message data has been truncated. */ + // @ts-ignore: decorator + @inline + export const DATA_TRUNCATED: roflags = 1; +} +export type roflags = u16; + +/** Which channels on a socket to shut down. */ +export namespace sdflags { + /** Disables further receive operations. */ + // @ts-ignore: decorator + @inline + export const RD: sdflags = 1; + /** Disables further send operations. */ + // @ts-ignore: decorator + @inline + export const WR: sdflags = 2; +} +export type sdflags = u8; + +/** Flags provided to \`sock_send\`. */ +export namespace siflags { + // As there are currently no flags defined, it must be set to zero. +} +export type siflags = u16; + +/** Signal condition. */ +export namespace signal { + /** Hangup. */ + // @ts-ignore: decorator + @inline + export const HUP: signal = 1; + /** Terminate interrupt signal. */ + // @ts-ignore: decorator + @inline + export const INT: signal = 2; + /** Terminal quit signal. */ + // @ts-ignore: decorator + @inline + export const QUIT: signal = 3; + /** Illegal instruction. */ + // @ts-ignore: decorator + @inline + export const ILL: signal = 4; + /** Trace/breakpoint trap. */ + // @ts-ignore: decorator + @inline + export const TRAP: signal = 5; + /** Process abort signal. */ + // @ts-ignore: decorator + @inline + export const ABRT: signal = 6; + /** Access to an undefined portion of a memory object. */ + // @ts-ignore: decorator + @inline + export const BUS: signal = 7; + /** Erroneous arithmetic operation. */ + // @ts-ignore: decorator + @inline + export const FPE: signal = 8; + /** Kill. */ + // @ts-ignore: decorator + @inline + export const KILL: signal = 9; + /** User-defined signal 1. */ + // @ts-ignore: decorator + @inline + export const USR1: signal = 10; + /** Invalid memory reference. */ + // @ts-ignore: decorator + @inline + export const SEGV: signal = 11; + /** User-defined signal 2. */ + // @ts-ignore: decorator + @inline + export const USR2: signal = 12; + /** Write on a pipe with no one to read it. */ + // @ts-ignore: decorator + @inline + export const PIPE: signal = 13; + /** Alarm clock. */ + // @ts-ignore: decorator + @inline + export const ALRM: signal = 14; + /** Termination signal. */ + // @ts-ignore: decorator + @inline + export const TERM: signal = 15; + /** Child process terminated, stopped, or continued. */ + // @ts-ignore: decorator + @inline + export const CHLD: signal = 16; + /** Continue executing, if stopped. */ + // @ts-ignore: decorator + @inline + export const CONT: signal = 17; + /** Stop executing. */ + // @ts-ignore: decorator + @inline + export const STOP: signal = 18; + /** Terminal stop signal. */ + // @ts-ignore: decorator + @inline + export const TSTP: signal = 19; + /** Background process attempting read. */ + // @ts-ignore: decorator + @inline + export const TTIN: signal = 20; + /** Background process attempting write. */ + // @ts-ignore: decorator + @inline + export const TTOU: signal = 21; + /** High bandwidth data is available at a socket. */ + // @ts-ignore: decorator + @inline + export const URG: signal = 22; + /** CPU time limit exceeded. */ + // @ts-ignore: decorator + @inline + export const XCPU: signal = 23; + /** File size limit exceeded. */ + // @ts-ignore: decorator + @inline + export const XFSZ: signal = 24; + /** Virtual timer expired. */ + // @ts-ignore: decorator + @inline + export const VTALRM: signal = 25; + // @ts-ignore: decorator + @inline + export const PROF: signal = 26; + // @ts-ignore: decorator + @inline + export const WINCH: signal = 27; + // @ts-ignore: decorator + @inline + export const POLL: signal = 28; + // @ts-ignore: decorator + @inline + export const PWR: signal = 29; + /** Bad system call. */ + // @ts-ignore: decorator + @inline + export const SYS: signal = 30; +} +export type signal = u8; + +/** Flags determining how to interpret the timestamp provided in \`subscription_t::u.clock.timeout. */ +export namespace subclockflags { + /** If set, treat the timestamp provided in \`clocksubscription\` as an absolute timestamp. */ + // @ts-ignore: decorator + @inline + export const ABSTIME: subclockflags = 1; +} +export type subclockflags = u16; + +@unmanaged abstract class $subscription { // size=16/48 + /** User-provided value that is attached to the subscription. */ + userdata: userdata; + /** The type of the event to which to subscribe. */ + type: eventtype; + + private __padding0: u32; +} + +/** Subscription to an event. */ +@unmanaged export abstract class subscription extends $subscription { + private __padding1: u64; + private __padding2: u64; + private __padding3: u64; + private __padding4: u64; +} + +/* Subscription to an event of type \`eventtype.CLOCK\`.**/ +@unmanaged export class subscription_clock extends $subscription { + /** The clock against which to compare the timestamp. */ + clock_id: clockid; + /** The absolute or relative timestamp. */ + timeout: timestamp; + /** The amount of time that the implementation may wait additionally to coalesce with other events. */ + precision: timestamp; + /** Flags specifying whether the timeout is absolute or relative. */ + flags: subclockflags; + + private __padding1: u32; +} + +/* Subscription to an event of type \`eventtype.FD_READ\` or \`eventtype.FD_WRITE\`.**/ +@unmanaged export class subscription_fd_readwrite extends $subscription { + /** The file descriptor on which to wait for it to become ready for reading or writing. */ + file_descriptor: fd; + + private __padding1: u64; + private __padding2: u64; + private __padding3: u64; +} + +/** Timestamp in nanoseconds. */ +export type timestamp = u64; + +/** User-provided value that may be attached to objects that is retained when extracted from the implementation. */ +export type userdata = u64; + +/** The position relative to which to set the offset of the file descriptor. */ +export namespace whence { + /** Seek relative to start-of-file. */ + // @ts-ignore: decorator + @inline + export const SET: whence = 0; + /** Seek relative to current position. */ + // @ts-ignore: decorator + @inline + export const CUR: whence = 1; + /** Seek relative to end-of-file. */ + // @ts-ignore: decorator + @inline + export const END: whence = 2; +} + +export type whence = u8; +`,"bindings/wasi_unstable":`// Phase: wasi_unstable / wasi_snapshot_preview0 +// See: https://github.com/WebAssembly/WASI/tree/main/phases/old/snapshot_0/witx + +// helper types to be more explicit +type char = u8; +type ptr = usize; // all pointers are usize'd +type struct = T; // structs are references already in AS + +/** Read command-line argument data. */ +// @ts-ignore: decorator +@unsafe +export declare function args_get( + /** Input: Pointer to a buffer to write the argument pointers. */ + argv: ptr>, + /** Input: Pointer to a buffer to write the argument string data. */ + argv_buf: ptr +): errno; + +/** Return command-line argument data sizes. */ +// @ts-ignore: decorator +@unsafe +export declare function args_sizes_get( + /** Output: Number of arguments. */ + argc: ptr, + /** Output: Size of the argument string data. */ + argv_buf_size: ptr +): errno; + +/** Return the resolution of a clock. */ +// @ts-ignore: decorator +@unsafe +export declare function clock_res_get( + /** Input: The clock for which to return the resolution. */ + clock: clockid, + /** Output: The resolution of the clock. */ + resolution: ptr +): errno; + +/** Return the time value of a clock. */ +// @ts-ignore: decorator +@unsafe +export declare function clock_time_get( + /** Input: Cock for which to return the time. */ + clock: clockid, + /** Input: Maximum lag (exclusive) that the returned time value may have, compared to its actual value. */ + precision: timestamp, + /** Output: Time value of the clock. */ + time: ptr +): errno; + +/** Read environment variable data. */ +// @ts-ignore: decorator +@unsafe +export declare function environ_get( + /** Input: Pointer to a buffer to write the environment variable pointers. */ + environ: ptr, + /** Input: Pointer to a buffer to write the environment variable string data. */ + environ_buf: usize +): errno; + +/** Return command-line argument data sizes. */ +// @ts-ignore: decorator +@unsafe +export declare function environ_sizes_get( + /** Output: The number of environment variables. */ + environ_count: ptr, + /** Output: The size of the environment variable string data. */ + environ_buf_size: ptr +): errno; + +/** Provide file advisory information on a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_advise( + /** Input: The file descriptor for the file for which to provide file advisory information. */ + fd: fd, + /** Input: The offset within the file to which the advisory applies. */ + offset: filesize, + /** Input: The length of the region to which the advisory applies. */ + len: filesize, + /** Input: The advice. */ + advice: advice +): errno; + +/** Provide file advisory information on a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_allocate( + /** Input: The file descriptor for the file in which to allocate space. */ + fd: fd, + /** Input: The offset at which to start the allocation. */ + offset: filesize, + /** Input: The length of the area that is allocated. */ + len: filesize +): errno; + +/** Close a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_close( + /** Input: The file descriptor to close. */ + fd: fd +): errno; + +/** Synchronize the data of a file to disk. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_datasync( + /** Input: The file descriptor of the file to synchronize to disk. */ + fd: fd +): errno; + +/** Get the attributes of a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_fdstat_get( + /** Input: The file descriptor to inspect. */ + fd: fd, + /** Input: The buffer where the file descriptor's attributes are stored. */ + buf: struct +): errno; + +/** Adjust the flags associated with a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_fdstat_set_flags( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The desired values of the file descriptor flags. */ + flags: fdflags +): errno; + +/** Adjust the rights associated with a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_fdstat_set_rights( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The desired rights of the file descriptor. */ + fs_rights_base: rights, + /** Input: The desired rights of the file descriptor. */ + fs_rights_inheriting: rights +): errno; + +/** Return the attributes of an open file. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_filestat_get( + /** Input: The file descriptor to inspect. */ + fd: fd, + /** Input: The buffer where the file's attributes are stored. */ + buf: struct +): errno; + +/** Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_filestat_set_size( + /** Input: A file descriptor for the file to adjust. */ + fd: fd, + /** Input: The desired file size. */ + size: filesize +): errno; + +/** Adjust the timestamps of an open file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_filestat_set_times( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The desired values of the data access timestamp. */ + st_atim: timestamp, + /** Input: The desired values of the data modification timestamp. */ + st_mtim: timestamp, + /** Input: A bitmask indicating which timestamps to adjust. */ + fstflags: fstflags +): errno; + +/** Read from a file descriptor, without using and updating the file descriptor's offset. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_pread( + /** Input: The file descriptor from which to read data. */ + fd: fd, + /** Input: List of scatter/gather vectors in which to store data. */ + iovs: ptr>, + /** Input: Length of the list of scatter/gather vectors in which to store data. */ + iovs_len: usize, + /** Input: The offset within the file at which to read. */ + offset: filesize, + /** Output: The number of bytes read. */ + nread: ptr +): errno; + +/** Return a description of the given preopened file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_prestat_get( + /** Input: The file descriptor about which to retrieve information. */ + fd: fd, + /** Input: The buffer where the description is stored. */ + buf: struct +): errno; + +/** Return a description of the given preopened file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_prestat_dir_name( + /** Input: The file descriptor about which to retrieve information. */ + fd: fd, + /** Input: Buffer into which to write the preopened directory name. */ + path: ptr, + /** Input: Length of the buffer into which to write the preopened directory name. */ + path_len: usize +): errno; + +/** Write to a file descriptor, without using and updating the file descriptor's offset. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_pwrite( + /** Input: The file descriptor to which to write data. */ + fd: fd, + /** Input: List of scatter/gather vectors from which to retrieve data. */ + iovs: ptr>, + /** Input: Length of the list of scatter/gather vectors from which to retrieve data. */ + iovs_len: usize, + /** Input: The offset within the file at which to write. */ + offset: filesize, + /** Output: The number of bytes written. */ + nwritten: ptr +): errno; + +/** Read from a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_read( + /** Input: The file descriptor from which to read data. */ + fd: fd, + /** Input: List of scatter/gather vectors to which to store data. */ + iovs: ptr>, + /** Input: Length of the list of scatter/gather vectors to which to store data. */ + iovs_len: usize, + /** Output: The number of bytes read. */ + nread: ptr +): errno; + +/** Read directory entries from a directory. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_readdir( + /** Input: Directory from which to read the directory entries. */ + fd: fd, + /** Input: Buffer where directory entries are stored. */ + buf: ptr>, + /** Input: Length of the buffer where directory entries are stored. */ + buf_len: usize, + /** Input: Location within the directory to start reading. */ + cookie: dircookie, + /** Output: Number of bytes stored in the read buffer. If less than the size of the read buffer, the end of the directory has been reached. */ + buf_used: ptr +): errno; + +/** Atomically replace a file descriptor by renumbering another file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_renumber( + /** Input: The file descriptor to renumber. */ + from: fd, + /** Input: The file descriptor to overwrite. */ + to: fd +): errno; + +/** Move the offset of a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_seek( + /** Input: The file descriptor to operate on. */ + fd: fd, + /** Input: The number of bytes to move. */ + offset: filedelta, + /** Input: The base from which the offset is relative. */ + whence: whence, + /** Output: The new offset of the file descriptor, relative to the start of the file. */ + newoffset: ptr +): errno; + +/** Synchronize the data and metadata of a file to disk. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_sync( + /** Input: The file descriptor of the file containing the data and metadata to synchronize to disk. */ + fd: fd +): errno; + +/** Return the current offset of a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_tell( + /** Input: The file descriptor to inspect. */ + fd: fd, + /** Output: The current offset of the file descriptor, relative to the start of the file. */ + newoffset: ptr +): errno; + +/** Write to a file descriptor. */ +// @ts-ignore: decorator +@unsafe +export declare function fd_write( + /** Input: The file descriptor to which to write data. */ + fd: fd, + /** Input: List of scatter/gather vectors from which to retrieve data. */ + iovs: ptr>, + /** Input: List of scatter/gather vectors from which to retrieve data. */ + iovs_len: usize, + /** Output: The number of bytes written. */ + nwritten: ptr +): errno; + +/* Create a directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_create_directory( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path at which to create the directory. */ + path: ptr, + /** Input: The path at which to create the directory. */ + path_len: usize +): errno; + +/** Return the attributes of a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_filestat_get( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + flags: lookupflags, + /** Input: The path of the file or directory to inspect. */ + path: ptr, + /** Input: The path of the file or directory to inspect. */ + path_len: usize, + /** Input: The buffer where the file's attributes are stored. */ + buf: struct +): errno; + +/** Adjust the timestamps of a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_filestat_set_times( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + flags: lookupflags, + /** Input: The path of the file or directory to operate on. */ + path: ptr, + /** Input: The path of the file or directory to operate on. */ + path_len: usize, + /** Input: The desired values of the data access timestamp. */ + st_atim: timestamp, + /** Input: The desired values of the data modification timestamp. */ + st_mtim: timestamp, + /** Input: A bitmask indicating which timestamps to adjust. */ + fstflags: fstflags +): errno; + +/** Create a hard link. */ +// @ts-ignore: decorator +@unsafe +export declare function path_link( + /** Input: The working directory at which the resolution of the old path starts. */ + old_fd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + old_flags: lookupflags, + /** Input: The source path from which to link. */ + old_path: ptr, + /** Input: The source path from which to link. */ + old_path_len: usize, + /** Input: The working directory at which the resolution of the new path starts. */ + new_fd: fd, + /** Input: The destination path at which to create the hard link. */ + new_path: ptr, + /** Input: The length of the destination path at which to create the hard link. */ + new_path_len: usize +): errno; + +/** Open a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_open( + /** Input: The working directory at which the resolution of the path starts. */ + dirfd: fd, + /** Input: Flags determining the method of how the path is resolved. */ + dirflags: lookupflags, + /** Input: The path of the file or directory to open. */ + path: ptr, + /** Input: The length of the path of the file or directory to open. */ + path_len: usize, + /** Input: The method by which to open the file. */ + oflags: oflags, + /** Input: The initial base rights that apply to operations using the file descriptor itself. */ + fs_rights_base: rights, + /** Input: The initial inheriting rights that apply to file descriptors derived from it. */ + fs_rights_inheriting: rights, + /** Input: The initial flags of the file descriptor. */ + fs_flags: fdflags, + /** Output: The file descriptor of the file that has been opened. */ + fd: ptr +): errno; + +/** Read the contents of a symbolic link. */ +// @ts-ignore: decorator +@unsafe +export declare function path_readlink( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path of the symbolic link from which to read. */ + path: ptr, + /** Input: The length of the path of the symbolic link from which to read. */ + path_len: usize, + /** Input: The buffer to which to write the contents of the symbolic link. */ + buf: ptr, + /** Input: The length of the buffer to which to write the contents of the symbolic link. */ + buf_len: usize, + /** Output: The number of bytes placed in the buffer. */ + buf_used: ptr +): errno; + +/** Remove a directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_remove_directory( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path to a directory to remove. */ + path: ptr, + /** Input: The length of the path to a directory to remove. */ + path_len: usize +): errno; + +/** Rename a file or directory. */ +// @ts-ignore: decorator +@unsafe +export declare function path_rename( + /** Input: The working directory at which the resolution of the old path starts. */ + old_fd: fd, + /** Input: The source path of the file or directory to rename. */ + old_path: ptr, + /** Input: The length of the source path of the file or directory to rename. */ + old_path_len: usize, + /** Input: The working directory at which the resolution of the new path starts. */ + new_fd: fd, + /** Input: The destination path to which to rename the file or directory. */ + new_path: ptr, + /** Input: The length of the destination path to which to rename the file or directory. */ + new_path_len: usize +): errno; + +/** Create a symbolic link. */ +// @ts-ignore: decorator +@unsafe +export declare function path_symlink( + /** Input: The contents of the symbolic link. */ + old_path: ptr, + /** Input: The length of the contents of the symbolic link. */ + old_path_len: usize, + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The destination path at which to create the symbolic link. */ + new_path: ptr, + /** Input: The length of the destination path at which to create the symbolic link. */ + new_path_len: usize +): errno; + +/** Unlink a file. */ +// @ts-ignore: decorator +@unsafe +export declare function path_unlink_file( + /** Input: The working directory at which the resolution of the path starts. */ + fd: fd, + /** Input: The path to a file to unlink. */ + path: ptr, + /** Input: The length of the path to a file to unlink. */ + path_len: usize +): errno; + +/** Concurrently poll for the occurrence of a set of events. */ +// @ts-ignore: decorator +@unsafe +export declare function poll_oneoff( + /** Input: The events to which to subscribe. */ + in_: ptr>, + /** Input: The events that have occurred. */ + out: ptr>, + /** Input: Both the number of subscriptions and events. */ + nsubscriptions: usize, + /** Output: The number of events stored. */ + nevents: ptr +): errno; + +/** Terminate the process normally. An exit code of 0 indicates successful termination of the program. The meanings of other values is dependent on the environment. */ +// @ts-ignore: decorator +@unsafe +export declare function proc_exit( + /** Input: The exit code returned by the process. */ + rval: u32 +): void; + +/** Send a signal to the process of the calling thread. */ +// @ts-ignore: decorator +@unsafe +export declare function proc_raise( + /** Input: The signal condition to trigger. */ + sig: signal +): errno; + +/** Write high-quality random data into a buffer. */ +// @ts-ignore: decorator +@unsafe +export declare function random_get( + /** Input: The buffer to fill with random data. */ + buf: usize, + /** Input: The length of the buffer to fill with random data. */ + buf_len: usize +): errno; + +/** Temporarily yield execution of the calling thread. */ +// @ts-ignore: decorator +@unsafe +export declare function sched_yield(): errno; + +/** Receive a message from a socket. */ +// @ts-ignore: decorator +@unsafe +export declare function sock_recv( + /** Input: The socket on which to receive data. */ + sock: fd, + /** Input: List of scatter/gather vectors to which to store data. */ + ri_data: ptr>, + /** Input: The length of the list of scatter/gather vectors to which to store data. */ + ri_data_len: usize, + /** Input: Message flags. */ + ri_flags: riflags, + /** Output: Number of bytes stored in \`ri_data\`. */ + ro_datalen: ptr, + /** Output: Message flags. */ + ro_flags: ptr +): errno; + +/** Send a message on a socket. */ +// @ts-ignore: decorator +@unsafe +export declare function sock_send( + /** Input: The socket on which to send data. */ + sock: fd, + /** Input: List of scatter/gather vectors to which to retrieve data */ + si_data: ptr>, + /** Input: The length of the list of scatter/gather vectors to which to retrieve data */ + si_data_len: usize, + /** Input: Message flags. */ + si_flags: siflags, + /** Output: Number of bytes transmitted. */ + so_datalen: ptr +): errno; + +/** Shut down socket send and receive channels. */ +// @ts-ignore: decorator +@unsafe +export declare function sock_shutdown( + /** Input: The socket on which to shutdown channels. */ + sock: fd, + /** Input: Which channels on the socket to shut down. */ + how: sdflags +): errno; + +// === Types ====================================================================================== + +/** File or memory access pattern advisory information. */ +export namespace advice { + /** The application has no advice to give on its behavior with respect to the specified data. */ + // @ts-ignore: decorator + @inline + export const NORMAL: advice = 0; + /** The application expects to access the specified data sequentially from lower offsets to higher offsets. */ + // @ts-ignore: decorator + @inline + export const SEQUENTIAL : advice = 1; + /** The application expects to access the specified data in a random order. */ + // @ts-ignore: decorator + @inline + export const RANDOM: advice = 2; + /** The application expects to access the specified data in the near future. */ + // @ts-ignore: decorator + @inline + export const WILLNEED: advice = 3; + /** The application expects that it will not access the specified data in the near future. */ + // @ts-ignore: decorator + @inline + export const DONTNEED: advice = 4; + /** The application expects to access the specified data once and then not reuse it thereafter. */ + // @ts-ignore: decorator + @inline + export const NOREUSE: advice = 5; +} +export type advice = u8; + +/** Identifiers for clocks. */ +export namespace clockid { + /** The clock measuring real time. Time value zero corresponds with 1970-01-01T00:00:00Z. */ + // @ts-ignore: decorator + @inline + export const REALTIME: clockid = 0; + /** The store-wide monotonic clock. Absolute value has no meaning. */ + // @ts-ignore: decorator + @inline + export const MONOTONIC: clockid = 1; + /** The CPU-time clock associated with the current process. */ + // @ts-ignore: decorator + @inline + export const PROCESS_CPUTIME_ID: clockid = 2; + /** The CPU-time clock associated with the current thread. */ + // @ts-ignore: decorator + @inline + export const THREAD_CPUTIME_ID: clockid = 3; +} +export type clockid = u32; + +/** Identifier for a device containing a file system. Can be used in combination with \`inode\` to uniquely identify a file or directory in the filesystem. */ +export type device = u64; + +/** A reference to the offset of a directory entry. */ +export type dircookie = u64; + +/** A directory entry. */ +@unmanaged export class dirent { + /** The offset of the next directory entry stored in this directory. */ + next: dircookie; + /** The serial number of the file referred to by this directory entry. */ + ino: inode; + /** The length of the name of the directory entry. */ + namlen: u32; + /** The type of the file referred to by this directory entry. */ + type: filetype; + private __padding0: u16; +} + +/** Error codes returned by functions. */ +export namespace errno { + /** No error occurred. System call completed successfully. */ + // @ts-ignore: decorator + @inline + export const SUCCESS: errno = 0; + /** Argument list too long. */ + // @ts-ignore: decorator + @inline + export const TOOBIG: errno = 1; + /** Permission denied. */ + // @ts-ignore: decorator + @inline + export const ACCES: errno = 2; + /** Address in use. */ + // @ts-ignore: decorator + @inline + export const ADDRINUSE: errno = 3; + /** Address not available. */ + // @ts-ignore: decorator + @inline + export const ADDRNOTAVAIL: errno = 4; + /** Address family not supported. */ + // @ts-ignore: decorator + @inline + export const AFNOSUPPORT: errno = 5; + /** Resource unavailable, or operation would block. */ + // @ts-ignore: decorator + @inline + export const AGAIN: errno = 6; + /** Connection already in progress. */ + // @ts-ignore: decorator + @inline + export const ALREADY: errno = 7; + /** Bad file descriptor. */ + // @ts-ignore: decorator + @inline + export const BADF: errno = 8; + /** Bad message. */ + // @ts-ignore: decorator + @inline + export const BADMSG: errno = 9; + /** Device or resource busy. */ + // @ts-ignore: decorator + @inline + export const BUSY: errno = 10; + /** Operation canceled. */ + // @ts-ignore: decorator + @inline + export const CANCELED: errno = 11; + /** No child processes. */ + // @ts-ignore: decorator + @inline + export const CHILD: errno = 12; + /** Connection aborted. */ + // @ts-ignore: decorator + @inline + export const CONNABORTED: errno = 13; + /** Connection refused. */ + // @ts-ignore: decorator + @inline + export const CONNREFUSED: errno = 14; + /** Connection reset. */ + // @ts-ignore: decorator + @inline + export const CONNRESET: errno = 15; + /** Resource deadlock would occur. */ + // @ts-ignore: decorator + @inline + export const DEADLK: errno = 16; + /** Destination address required. */ + // @ts-ignore: decorator + @inline + export const DESTADDRREQ: errno = 17; + /** Mathematics argument out of domain of function. */ + // @ts-ignore: decorator + @inline + export const DOM: errno = 18; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const DQUOT: errno = 19; + /** File exists. */ + // @ts-ignore: decorator + @inline + export const EXIST: errno = 20; + /** Bad address. */ + // @ts-ignore: decorator + @inline + export const FAULT: errno = 21; + /** File too large. */ + // @ts-ignore: decorator + @inline + export const FBIG: errno = 22; + /** Host is unreachable. */ + // @ts-ignore: decorator + @inline + export const HOSTUNREACH: errno = 23; + /** Identifier removed. */ + // @ts-ignore: decorator + @inline + export const IDRM: errno = 24; + /** Illegal byte sequence. */ + // @ts-ignore: decorator + @inline + export const ILSEQ: errno = 25; + /** Operation in progress. */ + // @ts-ignore: decorator + @inline + export const INPROGRESS: errno = 26; + /** Interrupted function. */ + // @ts-ignore: decorator + @inline + export const INTR: errno = 27; + /** Invalid argument. */ + // @ts-ignore: decorator + @inline + export const INVAL: errno = 28; + /** I/O error. */ + // @ts-ignore: decorator + @inline + export const IO: errno = 29; + /** Socket is connected. */ + // @ts-ignore: decorator + @inline + export const ISCONN: errno = 30; + /** Is a directory. */ + // @ts-ignore: decorator + @inline + export const ISDIR: errno = 31; + /** Too many levels of symbolic links. */ + // @ts-ignore: decorator + @inline + export const LOOP: errno = 32; + /** File descriptor value too large. */ + // @ts-ignore: decorator + @inline + export const MFILE: errno = 33; + /** Too many links. */ + // @ts-ignore: decorator + @inline + export const MLINK: errno = 34; + /** Message too large. */ + // @ts-ignore: decorator + @inline + export const MSGSIZE: errno = 35; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const MULTIHOP: errno = 36; + /** Filename too long. */ + // @ts-ignore: decorator + @inline + export const NAMETOOLONG: errno = 37; + /** Network is down. */ + // @ts-ignore: decorator + @inline + export const NETDOWN: errno = 38; + /** Connection aborted by network. */ + // @ts-ignore: decorator + @inline + export const NETRESET: errno = 39; + /** Network unreachable. */ + // @ts-ignore: decorator + @inline + export const NETUNREACH: errno = 40; + /** Too many files open in system. */ + // @ts-ignore: decorator + @inline + export const NFILE: errno = 41; + /** No buffer space available. */ + // @ts-ignore: decorator + @inline + export const NOBUFS: errno = 42; + /** No such device. */ + // @ts-ignore: decorator + @inline + export const NODEV: errno = 43; + /** No such file or directory. */ + // @ts-ignore: decorator + @inline + export const NOENT: errno = 44; + /** Executable file format error. */ + // @ts-ignore: decorator + @inline + export const NOEXEC: errno = 45; + /** No locks available. */ + // @ts-ignore: decorator + @inline + export const NOLCK: errno = 46; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const NOLINK: errno = 47; + /** Not enough space. */ + // @ts-ignore: decorator + @inline + export const NOMEM: errno = 48; + /** No message of the desired type. */ + // @ts-ignore: decorator + @inline + export const NOMSG: errno = 49; + /** Protocol not available. */ + // @ts-ignore: decorator + @inline + export const NOPROTOOPT: errno = 50; + /** No space left on device. */ + // @ts-ignore: decorator + @inline + export const NOSPC: errno = 51; + /** Function not supported. */ + // @ts-ignore: decorator + @inline + export const NOSYS: errno = 52; + /** The socket is not connected. */ + // @ts-ignore: decorator + @inline + export const NOTCONN: errno = 53; + /** Not a directory or a symbolic link to a directory. */ + // @ts-ignore: decorator + @inline + export const NOTDIR: errno = 54; + /** Directory not empty. */ + // @ts-ignore: decorator + @inline + export const NOTEMPTY: errno = 55; + /** State not recoverable. */ + // @ts-ignore: decorator + @inline + export const NOTRECOVERABLE: errno = 56; + /** Not a socket. */ + // @ts-ignore: decorator + @inline + export const NOTSOCK: errno = 57; + /** Not supported, or operation not supported on socket. */ + // @ts-ignore: decorator + @inline + export const NOTSUP: errno = 58; + /** Inappropriate I/O control operation. */ + // @ts-ignore: decorator + @inline + export const NOTTY: errno = 59; + /** No such device or address. */ + // @ts-ignore: decorator + @inline + export const NXIO: errno = 60; + /** Value too large to be stored in data type. */ + // @ts-ignore: decorator + @inline + export const OVERFLOW: errno = 61; + /** Previous owner died. */ + // @ts-ignore: decorator + @inline + export const OWNERDEAD: errno = 62; + /** Operation not permitted. */ + // @ts-ignore: decorator + @inline + export const PERM: errno = 63; + /** Broken pipe. */ + // @ts-ignore: decorator + @inline + export const PIPE: errno = 64; + /** Protocol error. */ + // @ts-ignore: decorator + @inline + export const PROTO: errno = 65; + /** Protocol not supported. */ + // @ts-ignore: decorator + @inline + export const PROTONOSUPPORT: errno = 66; + /** Protocol wrong type for socket. */ + // @ts-ignore: decorator + @inline + export const PROTOTYPE: errno = 67; + /** Result too large. */ + // @ts-ignore: decorator + @inline + export const RANGE: errno = 68; + /** Read-only file system. */ + // @ts-ignore: decorator + @inline + export const ROFS: errno = 69; + /** Invalid seek. */ + // @ts-ignore: decorator + @inline + export const SPIPE: errno = 70; + /** No such process. */ + // @ts-ignore: decorator + @inline + export const SRCH: errno = 71; + /** Reserved. */ + // @ts-ignore: decorator + @inline + export const STALE: errno = 72; + /** Connection timed out. */ + // @ts-ignore: decorator + @inline + export const TIMEDOUT: errno = 73; + /** Text file busy. */ + // @ts-ignore: decorator + @inline + export const TXTBSY: errno = 74; + /** Cross-device link. */ + // @ts-ignore: decorator + @inline + export const XDEV: errno = 75; + /** Extension: Capabilities insufficient. */ + // @ts-ignore: decorator + @inline + export const NOTCAPABLE: errno = 76; +} +export type errno = u16; + +/** An event that occurred. */ +@unmanaged export abstract class event { + /** User-provided value that got attached to \`subscription#userdata\`. */ + userdata: userdata; + /** If non-zero, an error that occurred while processing the subscription request. */ + error: errno; + /* The type of the event that occurred. */ + type: eventtype; + private __padding0: u16; +} + +/** An event that occurred when type is \`eventtype.FD_READ\` or \`eventtype.FD_WRITE\`. */ +@unmanaged export class rwevent extends event { + /* The number of bytes available for reading or writing. */ + nbytes: filesize; + /* The state of the file descriptor. */ + flags: eventrwflags; + private __padding1: u32; +} + +/** The state of the file descriptor subscribed to with \`eventtype.FD_READ\` or \`eventtype.FD_WRITE\`. */ +export namespace eventrwflags { + /** The peer of this socket has closed or disconnected. */ + // @ts-ignore: decorator + @inline + export const HANGUP: eventrwflags = 1; +} +export type eventrwflags = u16; + +/** Type of a subscription to an event or its occurrence. */ +export namespace eventtype { + /** The time value of clock has reached the timestamp. */ + // @ts-ignore: decorator + @inline + export const CLOCK: eventtype = 0; + /** File descriptor has data available for reading. */ + // @ts-ignore: decorator + @inline + export const FD_READ: eventtype = 1; + /** File descriptor has capacity available for writing */ + // @ts-ignore: decorator + @inline + export const FD_WRITE: eventtype = 2; +} +export type eventtype = u8; + +/** Exit code generated by a process when exiting. */ +export type exitcode = u32; + +/** A file descriptor number. */ +export type fd = u32; + +/** File descriptor flags. */ +export namespace fdflags { + /** Append mode: Data written to the file is always appended to the file's end. */ + // @ts-ignore: decorator + @inline + export const APPEND: fdflags = 1; + /** Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized. */ + // @ts-ignore: decorator + @inline + export const DSYNC: fdflags = 2; + /** Non-blocking mode. */ + // @ts-ignore: decorator + @inline + export const NONBLOCK: fdflags = 4; + /** Synchronized read I/O operations. */ + // @ts-ignore: decorator + @inline + export const RSYNC: fdflags = 8; + /** Write according to synchronized I/O file integrity completion. */ + // @ts-ignore: decorator + @inline + export const SYNC: fdflags = 16; +} +export type fdflags = u16; + +/** File descriptor attributes. */ +@unmanaged export class fdstat { + /** File type. */ + filetype: filetype; + /** File descriptor flags. */ + flags: fdflags; + /** Rights that apply to this file descriptor. */ + rights_base: rights; + /** Maximum set of rights that may be installed on new file descriptors that are created through this file descriptor, e.g., through \`path_open\`. */ + rights_inheriting: rights; +} + +/** Relative offset within a file. */ +export type filedelta = i64; + +/** Non-negative file size or length of a region within a file. */ +export type filesize = u64; + +/** File attributes. */ +@unmanaged export class filestat { + /** Device ID of device containing the file. */ + dev: device; + /** File serial number. */ + ino: inode; + /** File type. */ + filetype: filetype; + /** Number of hard links to the file. */ + nlink: linkcount; + /** For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link. */ + size: filesize; + /** Last data access timestamp. */ + atim: timestamp; + /** Last data modification timestamp. */ + mtim: timestamp; + /** Last file status change timestamp. */ + ctim: timestamp; +} + +/** The type of a file descriptor or file. */ +export namespace filetype { + /** The type of the file descriptor or file is unknown or is different from any of the other types specified. */ + // @ts-ignore: decorator + @inline + export const UNKNOWN: filetype = 0; + /** The file descriptor or file refers to a block device inode. */ + // @ts-ignore: decorator + @inline + export const BLOCK_DEVICE: filetype = 1; + /** The file descriptor or file refers to a character device inode. */ + // @ts-ignore: decorator + @inline + export const CHARACTER_DEVICE: filetype = 2; + /** The file descriptor or file refers to a directory inode. */ + // @ts-ignore: decorator + @inline + export const DIRECTORY: filetype = 3; + /** The file descriptor or file refers to a regular file inode. */ + // @ts-ignore: decorator + @inline + export const REGULAR_FILE: filetype = 4; + /** The file descriptor or file refers to a datagram socket. */ + // @ts-ignore: decorator + @inline + export const SOCKET_DGRAM: filetype = 5; + /** The file descriptor or file refers to a byte-stream socket. */ + // @ts-ignore: decorator + @inline + export const SOCKET_STREAM: filetype = 6; + /** The file refers to a symbolic link inode. */ + // @ts-ignore: decorator + @inline + export const SYMBOLIC_LINK: filetype = 7; +} +export type filetype = u8; + +/** Which file time attributes to adjust. */ +export namespace fstflags { + /** Adjust the last data access timestamp to the value stored in \`filestat#st_atim\`. */ + // @ts-ignore: decorator + @inline + export const SET_ATIM: fstflags = 1; + /** Adjust the last data access timestamp to the time of clock \`clockid.REALTIME\`. */ + // @ts-ignore: decorator + @inline + export const SET_ATIM_NOW: fstflags = 2; + /** Adjust the last data modification timestamp to the value stored in \`filestat#st_mtim\`. */ + // @ts-ignore: decorator + @inline + export const SET_MTIM: fstflags = 4; + /** Adjust the last data modification timestamp to the time of clock \`clockid.REALTIME\`. */ + // @ts-ignore: decorator + @inline + export const SET_MTIM_NOW: fstflags = 8; +} +export type fstflags = u16; + +/** File serial number that is unique within its file system. */ +export type inode = u64; + +/** A region of memory for scatter/gather reads. */ +@unmanaged export class iovec { + /** The address of the buffer to be filled. */ + buf: usize; + /** The length of the buffer to be filled. */ + buf_len: usize; +} + +/** Number of hard links to an inode. */ +export type linkcount = u32; + +/** Flags determining the method of how paths are resolved. */ +export namespace lookupflags { + /** As long as the resolved path corresponds to a symbolic link, it is expanded. */ + // @ts-ignore: decorator + @inline + export const SYMLINK_FOLLOW: lookupflags = 1; +} +export type lookupflags = u32; + +/** Open flags. */ +export namespace oflags { + /** Create file if it does not exist. */ + // @ts-ignore: decorator + @inline + export const CREAT: oflags = 1; + /** Fail if not a directory. */ + // @ts-ignore: decorator + @inline + export const DIRECTORY: oflags = 2; + /** Fail if file already exists. */ + // @ts-ignore: decorator + @inline + export const EXCL: oflags = 4; + /** Truncate file to size 0. */ + // @ts-ignore: decorator + @inline + export const TRUNC: oflags = 8; +} +export type oflags = u16; + +// TODO: undocumented +export namespace preopentype { + // @ts-ignore: decorator + @inline + export const DIR: preopentype = 0; +} +export type preopentype = u8; + +// TODO: undocumented +export abstract class prestat { + type: preopentype; +} + +// TODO: undocumented +export class dirprestat extends prestat { + name_len: usize; +} + +/** Flags provided to \`sock_recv\`. */ +export namespace riflags { + /** Returns the message without removing it from the socket's receive queue. */ + // @ts-ignore: decorator + @inline + export const PEEK: riflags = 1; + /** On byte-stream sockets, block until the full amount of data can be returned. */ + // @ts-ignore: decorator + @inline + export const WAITALL: riflags = 2; +} +export type riflags = u16; + +/** File descriptor rights, determining which actions may be performed. */ +export namespace rights { + /** The right to invoke \`fd_datasync\`. */ + // @ts-ignore: decorator + @inline + export const FD_DATASYNC: rights = 1; + /** The right to invoke \`fd_read\` and \`sock_recv\`. */ + // @ts-ignore: decorator + @inline + export const FD_READ: rights = 2; + /** The right to invoke \`fd_seek\`. This flag implies \`rights.FD_TELL\`. */ + // @ts-ignore: decorator + @inline + export const FD_SEEK: rights = 4; + /** The right to invoke \`fd_fdstat_set_flags\`. */ + // @ts-ignore: decorator + @inline + export const FD_FDSTAT_SET_FLAGS: rights = 8; + /** The right to invoke \`fd_sync\`. */ + // @ts-ignore: decorator + @inline + export const FD_SYNC: rights = 16; + /** The right to invoke \`fd_seek\` in such a way that the file offset remains unaltered (i.e., \`whence.CUR\` with offset zero), or to invoke \`fd_tell\`). */ + // @ts-ignore: decorator + @inline + export const FD_TELL: rights = 32; + /** The right to invoke \`fd_write\` and \`sock_send\`. If \`rights.FD_SEEK\` is set, includes the right to invoke \`fd_pwrite\`. */ + // @ts-ignore: decorator + @inline + export const FD_WRITE: rights = 64; + /** The right to invoke \`fd_advise\`. */ + // @ts-ignore: decorator + @inline + export const FD_ADVISE: rights = 128; + /** The right to invoke \`fd_allocate\`. */ + // @ts-ignore: decorator + @inline + export const FD_ALLOCATE: rights = 256; + /** The right to invoke \`path_create_directory\`. */ + // @ts-ignore: decorator + @inline + export const PATH_CREATE_DIRECTORY: rights = 512; + /** If \`rights.PATH_OPEN\` is set, the right to invoke \`path_open\` with \`oflags.CREAT\`. */ + // @ts-ignore: decorator + @inline + export const PATH_CREATE_FILE: rights = 1024; + /** The right to invoke \`path_link\` with the file descriptor as the source directory. */ + // @ts-ignore: decorator + @inline + export const PATH_LINK_SOURCE: rights = 2048; + /** The right to invoke \`path_link\` with the file descriptor as the target directory. */ + // @ts-ignore: decorator + @inline + export const PATH_LINK_TARGET: rights = 4096; + /** The right to invoke \`path_open\`. */ + // @ts-ignore: decorator + @inline + export const PATH_OPEN: rights = 8192; + /** The right to invoke \`fd_readdir\`. */ + // @ts-ignore: decorator + @inline + export const FD_READDIR: rights = 16384; + /** The right to invoke \`path_readlink\`. */ + // @ts-ignore: decorator + @inline + export const PATH_READLINK: rights = 32768; + /** The right to invoke \`path_rename\` with the file descriptor as the source directory. */ + // @ts-ignore: decorator + @inline + export const PATH_RENAME_SOURCE: rights = 65536; + /** The right to invoke \`path_rename\` with the file descriptor as the target directory. */ + // @ts-ignore: decorator + @inline + export const PATH_RENAME_TARGET: rights = 131072; + /** The right to invoke \`path_filestat_get\`. */ + // @ts-ignore: decorator + @inline + export const PATH_FILESTAT_GET: rights = 262144; + /** The right to change a file's size (there is no \`path_filestat_set_size\`). If \`rights.PATH_OPEN\` is set, includes the right to invoke \`path_open\` with \`oflags.TRUNC\`. */ + // @ts-ignore: decorator + @inline + export const PATH_FILESTAT_SET_SIZE: rights = 524288; + /** The right to invoke \`path_filestat_set_times\`. */ + // @ts-ignore: decorator + @inline + export const PATH_FILESTAT_SET_TIMES: rights = 1048576; + /** The right to invoke \`fd_filestat_get\`. */ + // @ts-ignore: decorator + @inline + export const FD_FILESTAT_GET: rights = 2097152; + /** The right to invoke \`fd_filestat_set_size\`. */ + // @ts-ignore: decorator + @inline + export const FD_FILESTAT_SET_SIZE: rights = 4194304; + /** The right to invoke \`fd_filestat_set_times\`. */ + // @ts-ignore: decorator + @inline + export const FD_FILESTAT_SET_TIMES: rights = 8388608; + /** The right to invoke \`path_symlink\`. */ + // @ts-ignore: decorator + @inline + export const RIGHT_PATH_SYMLINK: rights = 16777216; + /** The right to invoke \`path_remove_directory\`. */ + // @ts-ignore: decorator + @inline + export const PATH_REMOVE_DIRECTORY: rights = 33554432; + /** The right to invoke \`path_unlink_file\`. */ + // @ts-ignore: decorator + @inline + export const PATH_UNLINK_FILE: rights = 67108864; + /** If \`rights.FD_READ\` is set, includes the right to invoke \`poll_oneoff\` to subscribe to \`eventtype.FD_READ\`. If \`rights.FD_WRITE\` is set, includes the right to invoke \`poll_oneoff\` to subscribe to \`eventtype.FD_WRITE\`. */ + // @ts-ignore: decorator + @inline + export const POLL_FD_READWRITE: rights = 134217728; + /** The right to invoke \`sock_shutdown\`. */ + // @ts-ignore: decorator + @inline + export const SOCK_SHUTDOWN: rights = 268435456; +} +export type rights = u64; + +/** Flags returned by \`sock_recv\`. */ +export namespace roflags { + /** Message data has been truncated. */ + // @ts-ignore: decorator + @inline + export const DATA_TRUNCATED: roflags = 1; +} +export type roflags = u16; + +/** Which channels on a socket to shut down. */ +export namespace sdflags { + /** Disables further receive operations. */ + // @ts-ignore: decorator + @inline + export const RD: sdflags = 1; + /** Disables further send operations. */ + // @ts-ignore: decorator + @inline + export const WR: sdflags = 2; +} +export type sdflags = u8; + +/** Flags provided to \`sock_send\`. */ +export namespace siflags { + // As there are currently no flags defined, it must be set to zero. +} +export type siflags = u16; + +/** Signal condition. */ +export namespace signal { + /** Hangup. */ + // @ts-ignore: decorator + @inline + export const HUP: signal = 1; + /** Terminate interrupt signal. */ + // @ts-ignore: decorator + @inline + export const INT: signal = 2; + /** Terminal quit signal. */ + // @ts-ignore: decorator + @inline + export const QUIT: signal = 3; + /** Illegal instruction. */ + // @ts-ignore: decorator + @inline + export const ILL: signal = 4; + /** Trace/breakpoint trap. */ + // @ts-ignore: decorator + @inline + export const TRAP: signal = 5; + /** Process abort signal. */ + // @ts-ignore: decorator + @inline + export const ABRT: signal = 6; + /** Access to an undefined portion of a memory object. */ + // @ts-ignore: decorator + @inline + export const BUS: signal = 7; + /** Erroneous arithmetic operation. */ + // @ts-ignore: decorator + @inline + export const FPE: signal = 8; + /** Kill. */ + // @ts-ignore: decorator + @inline + export const KILL: signal = 9; + /** User-defined signal 1. */ + // @ts-ignore: decorator + @inline + export const USR1: signal = 10; + /** Invalid memory reference. */ + // @ts-ignore: decorator + @inline + export const SEGV: signal = 11; + /** User-defined signal 2. */ + // @ts-ignore: decorator + @inline + export const USR2: signal = 12; + /** Write on a pipe with no one to read it. */ + // @ts-ignore: decorator + @inline + export const PIPE: signal = 13; + /** Alarm clock. */ + // @ts-ignore: decorator + @inline + export const ALRM: signal = 14; + /** Termination signal. */ + // @ts-ignore: decorator + @inline + export const TERM: signal = 15; + /** Child process terminated, stopped, or continued. */ + // @ts-ignore: decorator + @inline + export const CHLD: signal = 16; + /** Continue executing, if stopped. */ + // @ts-ignore: decorator + @inline + export const CONT: signal = 17; + /** Stop executing. */ + // @ts-ignore: decorator + @inline + export const STOP: signal = 18; + /** Terminal stop signal. */ + // @ts-ignore: decorator + @inline + export const TSTP: signal = 19; + /** Background process attempting read. */ + // @ts-ignore: decorator + @inline + export const TTIN: signal = 20; + /** Background process attempting write. */ + // @ts-ignore: decorator + @inline + export const TTOU: signal = 21; + /** High bandwidth data is available at a socket. */ + // @ts-ignore: decorator + @inline + export const URG: signal = 22; + /** CPU time limit exceeded. */ + // @ts-ignore: decorator + @inline + export const XCPU: signal = 23; + /** File size limit exceeded. */ + // @ts-ignore: decorator + @inline + export const XFSZ: signal = 24; + /** Virtual timer expired. */ + // @ts-ignore: decorator + @inline + export const VTALRM: signal = 25; + // @ts-ignore: decorator + @inline + export const PROF: signal = 26; + // @ts-ignore: decorator + @inline + export const WINCH: signal = 27; + // @ts-ignore: decorator + @inline + export const POLL: signal = 28; + // @ts-ignore: decorator + @inline + export const PWR: signal = 29; + /** Bad system call. */ + // @ts-ignore: decorator + @inline + export const SYS: signal = 30; +} +export type signal = u8; + +/** Flags determining how to interpret the timestamp provided in \`subscription_t::u.clock.timeout. */ +export namespace subclockflags { + /** If set, treat the timestamp provided in \`clocksubscription\` as an absolute timestamp. */ + // @ts-ignore: decorator + @inline + export const ABSTIME: subclockflags = 1; +} +export type subclockflags = u16; + +/** Subscription to an event. */ +@unmanaged export abstract class subscription { + /** User-provided value that is attached to the subscription. */ + userdata: userdata; + /** The type of the event to which to subscribe. */ + type: eventtype; + private __padding0: u32; +} + +/* Subscription to an event of type \`eventtype.CLOCK\`.**/ +@unmanaged export class clocksubscription extends subscription { + /** The user-defined unique identifier of the clock. */ + identifier: userdata; + /** The clock against which to compare the timestamp. */ + clock_id: clockid; + /** The absolute or relative timestamp. */ + timeout: timestamp; + /** The amount of time that the implementation may wait additionally to coalesce with other events. */ + precision: timestamp; + /** Flags specifying whether the timeout is absolute or relative. */ + flags: subclockflags; + private __padding1: u32; +} + +/* Subscription to an event of type \`eventtype.FD_READ\` or \`eventtype.FD_WRITE\`.**/ +@unmanaged export class fdsubscription extends subscription { + /** The file descriptor on which to wait for it to become ready for reading or writing. */ + fd: fd; +} + +/** Timestamp in nanoseconds. */ +export type timestamp = u64; + +/** User-provided value that may be attached to objects that is retained when extracted from the implementation. */ +export type userdata = u64; + +/** The position relative to which to set the offset of the file descriptor. */ +export namespace whence { + /** Seek relative to current position. */ + // @ts-ignore: decorator + @inline + export const CUR: whence = 0; + /** Seek relative to end-of-file. */ + // @ts-ignore: decorator + @inline + export const END: whence = 1; + /** Seek relative to start-of-file. */ + // @ts-ignore: decorator + @inline + export const SET: whence = 2; +} +export type whence = u8;`,"bindings/wasi":`export * from "./wasi_snapshot_preview1"; + +// A WASI-wide reusable temporary buffer to store and work with out values. Must +// be large enough to fit any operation it is used in, i.e. process/writeString. +// @ts-ignore: decorator +@lazy export const tempbuf = memory.data(4 * sizeof()); +`,builtins:`type auto = i32; + +// @ts-ignore: decorator +@builtin +export declare function isInteger(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isFloat(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isBoolean(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isSigned(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isReference(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isString(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isArray(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isArrayLike(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isFunction(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isNullable(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isDefined(expression: auto): bool; + +// @ts-ignore: decorator +@builtin +export declare function isConstant(expression: auto): bool; + +// @ts-ignore: decorator +@builtin +export declare function isManaged(value?: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isVoid(): bool; + +// @ts-ignore +@builtin +export declare function lengthof(func?: T): i32; + +// @ts-ignore: decorator +@builtin +export declare function clz(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function ctz(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function popcnt(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function rotl(value: T, shift: T): T; + +// @ts-ignore: decorator +@builtin +export declare function rotr(value: T, shift: T): T; + +// @ts-ignore: decorator +@builtin +export declare function abs(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function max(left: T, right: T): T; + +// @ts-ignore: decorator +@builtin +export declare function min(left: T, right: T): T; + +// @ts-ignore: decorator +@builtin +export declare function ceil(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function floor(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function copysign(left: T, right: T): T; + +// @ts-ignore: decorator +@builtin +export declare function nearest(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function reinterpret(value: number): T; + +// @ts-ignore: decorator +@builtin +export declare function sqrt(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function trunc(value: T): T; + +// @ts-ignore: decorator +@builtin +export declare function add(left: T, right: T): T; + +// @ts-ignore: decorator +@builtin +export declare function sub(left: T, right: T): T; + +// @ts-ignore: decorator +@builtin +export declare function mul(left: T, right: T): T; + +// @ts-ignore: decorator +@builtin +export declare function div(left: T, right: T): T; + +// @ts-ignore: decorator +@builtin +export declare function eq(left: T, right: T): i32; + +// @ts-ignore: decorator +@builtin +export declare function ne(left: T, right: T): i32; + +// @ts-ignore: decorator +@unsafe @builtin +export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): T; + +// @ts-ignore: decorator +@unsafe @builtin +export declare function store(ptr: usize, value: auto, immOffset?: usize, immAlign?: usize): void; + +// @ts-ignore: decorator +@builtin +export declare function sizeof(): usize; // | u32 / u64 + +// @ts-ignore: decorator +@builtin +export declare function alignof(): usize; // | u32 / u64 + +// @ts-ignore: decorator +@builtin +export declare function offsetof(fieldName?: string): usize; // | u32 / u64 + +// @ts-ignore: decorator +@builtin +export declare function idof(): u32; + +// @ts-ignore +@builtin +export declare function nameof(): string; + +// @ts-ignore: decorator +@builtin +export declare function select(ifTrue: T, ifFalse: T, condition: bool): T; + +// @ts-ignore: decorator +@unsafe @builtin +export declare function unreachable(): auto; + +// @ts-ignore: decorator +@builtin +export declare function changetype(value: auto): T; + +// @ts-ignore: decorator +@builtin +export declare function assert(isTrueish: T, message?: string): T; + +// @ts-ignore: decorator +@unsafe @builtin +export declare function unchecked(expr: T): T; + +// @ts-ignore: decorator +@unsafe @builtin +export declare function call_indirect(index: u32, ...args: auto[]): T; + +// @ts-ignore: decorator +@builtin +export declare function instantiate(...args: auto[]): T; + +export namespace atomic { + // @ts-ignore: decorator + @unsafe @builtin + export declare function load(ptr: usize, immOffset?: usize): T; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: T, immOffset?: usize): void; + + // @ts-ignore: decorator + @builtin + export declare function add(ptr: usize, value: T, immOffset?: usize): T; + + // @ts-ignore: decorator + @builtin + export declare function sub(ptr: usize, value: T, immOffset?: usize): T; + + // @ts-ignore: decorator + @builtin + export declare function and(ptr: usize, value: T, immOffset?: usize): T; + + // @ts-ignore: decorator + @builtin + export declare function or(ptr: usize, value: T, immOffset?: usize): T; + + // @ts-ignore: decorator + @builtin + export declare function xor(ptr: usize, value: T, immOffset?: usize): T; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg(ptr: usize, value: T, immOffset?: usize): T; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg(ptr: usize, expected: T, replacement: T, immOffset?: usize): T; + + // @ts-ignore: decorator + @builtin + export declare function wait(ptr: usize, expected: T, timeout: i64): AtomicWaitResult; + + // @ts-ignore: decorator + @builtin + export declare function notify(ptr: usize, count: i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function fence(): void; +} + +// @ts-ignore: decorator +@lazy +export const enum AtomicWaitResult { + OK = 0, + NOT_EQUAL = 1, + TIMED_OUT = 2 +} + +// @ts-ignore: decorator +@builtin +export declare function i8(value: auto): i8; + +export namespace i8 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: i8 = -128; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: i8 = 127; +} + +// @ts-ignore: decorator +@builtin +export declare function i16(value: auto): i16; + +export namespace i16 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: i16 = -32768; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: i16 = 32767; +} + +// @ts-ignore: decorator +@builtin +export declare function i32(value: auto): i32; + +export namespace i32 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: i32 = -2147483648; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: i32 = 2147483647; + + // @ts-ignore: decorator + @builtin + export declare function clz(value: i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function ctz(value: i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function popcnt(value: i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function add(left: i32, right:i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function sub(left: i32, right:i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function mul(left: i32, right:i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function div_s(left: i32, right:i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function div_u(left: i32, right:i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function rotl(value: i32, shift: i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function rotr(value: i32, shift: i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function eq(left: i32, right:i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function ne(left: i32, right:i32): i32; + + // @ts-ignore: decorator + @builtin + export declare function reinterpret_f32(value: f32): i32; + + // @ts-ignore: decorator + @builtin + export declare function load8_s(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function load8_u(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function load16_s(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function load16_u(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store8(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store16(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; + + export namespace atomic { + + // @ts-ignore: decorator + @builtin + export declare function load8_u(ptr: usize, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function load16_u(ptr: usize, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function load(ptr: usize, immOffset?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store8(ptr: usize, value: i32, immOffset?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store16(ptr: usize, value: i32, immOffset?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: i32, immOffset?: usize): void; + + // @ts-ignore: decorator + @builtin + export declare function wait(ptr: usize, expected: i32, timeout: i64): AtomicWaitResult; + + export namespace rmw8 { + + // @ts-ignore: decorator + @builtin + export declare function add_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function sub_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function and_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function or_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function xor_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg_u(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; + } + + export namespace rmw16 { + + // @ts-ignore: decorator + @builtin + export declare function add_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function sub_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function and_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function or_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function xor_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg_u(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg_u(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; + } + + export namespace rmw { + + // @ts-ignore: decorator + @builtin + export declare function add(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function sub(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function and(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function or(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @builtin + export declare function xor(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg(ptr: usize, value: i32, immOffset?: usize): i32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; + } + } +} + +// @ts-ignore: decorator +@builtin +export declare function i64(value: auto): i64; + +export namespace i64 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: i64 = -9223372036854775808; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: i64 = 9223372036854775807; + + // @ts-ignore: decorator + @builtin + export declare function clz(value: i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function ctz(value: i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function add(left: i64, right:i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function sub(left: i64, right:i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function mul(left: i64, right:i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function div_s(left: i64, right:i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function div_u(left: i64, right:i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function load8_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load8_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load16_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load16_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load32_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load32_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load(ptr: usize, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function popcnt(value: i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function rotl(value: i64, shift: i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function rotr(value: i64, shift: i64): i64; + + // @ts-ignore: decorator + @builtin + export declare function eq(left: i64, right:i64): i32; + + // @ts-ignore: decorator + @builtin + export declare function ne(left: i64, right:i64): i32; + + // @ts-ignore: decorator + @builtin + export declare function reinterpret_f64(value: f64): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store8(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store16(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store32(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + + export namespace atomic { + + // @ts-ignore: decorator + @builtin + export declare function load8_u(ptr: usize, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load16_u(ptr: usize, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load32_u(ptr: usize, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function load(ptr: usize, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store8(ptr: usize, value: i64, immOffset?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store16(ptr: usize, value: i64, immOffset?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store32(ptr: usize, value: i64, immOffset?: usize): void; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: i64, immOffset?: usize): void; + + // @ts-ignore: decorator + @builtin + export declare function wait(ptr: usize, expected: i64, timeout: i64): AtomicWaitResult; + + export namespace rmw8 { + + // @ts-ignore: decorator + @builtin + export declare function add_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function and_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function or_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + + export namespace rmw16 { + + // @ts-ignore: decorator + @builtin + export declare function add_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function and_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function or_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + + export namespace rmw32 { + + // @ts-ignore: decorator + @builtin + export declare function add_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function and_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function or_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + + export namespace rmw { + + // @ts-ignore: decorator + @builtin + export declare function add(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function sub(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function and(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function or(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @builtin + export declare function xor(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function xchg(ptr: usize, value: i64, immOffset?: usize): i64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function cmpxchg(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + } +} + +// @ts-ignore: decorator +@builtin +export declare function isize(value: auto): isize; + +export namespace isize { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: isize = sizeof() == sizeof() + ? -2147483648 + : -9223372036854775808; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: isize = sizeof() == sizeof() + ? 2147483647 + : 9223372036854775807; +} + +// @ts-ignore: decorator +@builtin +export declare function u8(value: auto): u8; + +export namespace u8 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: u8 = 0; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: u8 = 255; +} + +// @ts-ignore: decorator +@builtin +export declare function u16(value: auto): u16; + +export namespace u16 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: u16 = 0; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: u16 = 65535; +} + +// @ts-ignore: decorator +@builtin +export declare function u32(value: auto): u32; + +export namespace u32 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: u32 = 0; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: u32 = 4294967295; +} + +// @ts-ignore: decorator +@builtin +export declare function u64(value: auto): u64; + +export namespace u64 { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: u64 = 0; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: u64 = 18446744073709551615; +} + +// @ts-ignore: decorator +@builtin +export declare function usize(value: auto): usize; + +export namespace usize { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: usize = 0; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: usize = sizeof() == sizeof() + ? 4294967295 + : 18446744073709551615; +} + +// @ts-ignore: decorator +@builtin +export declare function bool(value: auto): bool; + +export namespace bool { + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE: bool = false; + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE: bool = true; +} + +// @ts-ignore: decorator +@builtin +export declare function f32(value: auto): f32; + +export namespace f32 { + + // @ts-ignore: decorator + @lazy + export const EPSILON = reinterpret(0x34000000); // 0x1p-23f + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE = reinterpret(0x00000001); // 0x0.000001p+0f + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE = reinterpret(0x7F7FFFFF); // 0x1.fffffep+127f + + // @ts-ignore: decorator + @lazy + export const MIN_NORMAL_VALUE = reinterpret(0x00800000); // 0x1p-126f + + // @ts-ignore: decorator + @lazy + export const MIN_SAFE_INTEGER: f32 = -16777215; + + // @ts-ignore: decorator + @lazy + export const MAX_SAFE_INTEGER: f32 = 16777215; + + // @ts-ignore: decorator + @lazy + export const POSITIVE_INFINITY: f32 = Infinity; + + // @ts-ignore: decorator + @lazy + export const NEGATIVE_INFINITY: f32 = -Infinity; + + // @ts-ignore: decorator + @lazy + export const NaN: f32 = 0.0 / 0.0; + + // @ts-ignore: decorator + @builtin + export declare function abs(value: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function ceil(value: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function copysign(x: f32, y: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function floor(value: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): f32; + + // @ts-ignore: decorator + @builtin + export declare function max(left: f32, right: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function min(left: f32, right: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function nearest(value: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function reinterpret_i32(value: i32): f32; + + // @ts-ignore: decorator + @builtin + export declare function sqrt(value: f32): f32; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: f32, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @builtin + export declare function trunc(value: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function add(left: f32, right: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function sub(left: f32, right: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function mul(left: f32, right: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function div(left: f32, right: f32): f32; + + // @ts-ignore: decorator + @builtin + export declare function eq(left: f32, right: f32): i32; + + // @ts-ignore: decorator + @builtin + export declare function ne(left: f32, right: f32): i32; +} + +// @ts-ignore: decorator +@builtin +export declare function f64(value: auto): f64; + +export namespace f64 { + + // @ts-ignore: decorator + @lazy + export const EPSILON = reinterpret(0x3CB0000000000000); // 0x1p-52 + + // @ts-ignore: decorator + @lazy + export const MIN_VALUE = reinterpret(0x0000000000000001); // 0x0.0000000000001p+0 + + // @ts-ignore: decorator + @lazy + export const MAX_VALUE = reinterpret(0x7FEFFFFFFFFFFFFF); // 0x1.fffffffffffffp+1023 + + // @ts-ignore: decorator + @lazy + export const MIN_NORMAL_VALUE = reinterpret(0x0010000000000000); // 0x1p-1022 + + // @ts-ignore: decorator + @lazy + export const MIN_SAFE_INTEGER: f64 = -9007199254740991; + + // @ts-ignore: decorator + @lazy + export const MAX_SAFE_INTEGER: f64 = 9007199254740991; + + // @ts-ignore: decorator + @lazy + export const POSITIVE_INFINITY: f64 = Infinity; + + // @ts-ignore: decorator + @lazy + export const NEGATIVE_INFINITY: f64 = -Infinity; + + // @ts-ignore: decorator + @lazy + export const NaN: f64 = 0.0 / 0.0; + + // @ts-ignore: decorator + @builtin + export declare function abs(value: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function ceil(value: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function copysign(x: f64, y: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function floor(value: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): f64; + + // @ts-ignore: decorator + @builtin + export declare function max(left: f64, right: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function min(left: f64, right: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function nearest(value: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function reinterpret_i64(value: i64): f64; + + // @ts-ignore: decorator + @builtin + export declare function sqrt(value: f64): f64; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: f64, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @builtin + export declare function trunc(value: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function add(left: f64, right: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function sub(left: f64, right: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function mul(left: f64, right: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function div(left: f64, right: f64): f64; + + // @ts-ignore: decorator + @builtin + export declare function eq(left: f64, right: f64): i32; + + // @ts-ignore: decorator + @builtin + export declare function ne(left: f64, right: f64): i32; +} + +// @ts-ignore: decorator +@builtin +export declare function v128( + a: i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8, + i: i8, j: i8, k: i8, l: i8, m: i8, n: i8, o: i8, p: i8 +): v128; + +export namespace v128 { + + // @ts-ignore: decorator + @builtin + export declare function splat(x: T): v128; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane(x: v128, idx: u8): T; + + // @ts-ignore: decorator + @builtin + export declare function replace_lane(x: v128, idx: u8, value: T): v128; + + // @ts-ignore: decorator + @builtin + export declare function shuffle(a: v128, b: v128, ...lanes: u8[]): v128; + + // @ts-ignore: decorator + @builtin + export declare function swizzle(a: v128, s: v128): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load_ext(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load_zero(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + + // @ts-ignore: decorator + @builtin + export declare function load8x8_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @builtin + export declare function load8x8_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @builtin + export declare function load16x4_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @builtin + export declare function load16x4_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @builtin + export declare function load32x2_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @builtin + export declare function load32x2_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load_splat(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load8_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load16_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load32_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load64_splat(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load32_zero(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load64_zero(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load8_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load16_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load32_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function load64_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store8_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store16_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store32_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store64_lane(ptr: usize, vec: v128, idx: u8, immOffset?: u32, immAlign?: u32): v128; + + // @ts-ignore: decorator + @unsafe @builtin + export declare function store(ptr: usize, value: v128, immOffset?: usize, immAlign?: usize): void; + + // @ts-ignore: decorator + @builtin + export declare function add(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function mul(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function div(a: v128, b: v128): v128; // f32, f64 only + + // @ts-ignore: decorator + @builtin + export declare function neg(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function add_sat(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub_sat(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function shl(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function and(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function or(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function xor(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function andnot(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function not(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function bitselect(v1: v128, v2: v128, c: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function any_true(a: v128): bool; + + // @ts-ignore: decorator + @builtin + export declare function all_true(a: v128): bool; + + // @ts-ignore: decorator + @builtin + export declare function bitmask(a: v128): i32; + + // @ts-ignore: decorator + @builtin + export declare function popcnt(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function pmin(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function pmax(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function dot(a: v128, b: v128): v128; // i16 only + + // @ts-ignore: decorator + @builtin + export declare function avgr(a: v128, b: v128): v128; // u8, u16 only + + // @ts-ignore: decorator + @builtin + export declare function abs(a: v128): v128; // f32, f64 only + + // @ts-ignore: decorator + @builtin + export declare function sqrt(a: v128): v128; // f32, f64 only + + // @ts-ignore: decorator + @builtin + export declare function ceil(a: v128): v128; // f32, f64 only + + // @ts-ignore: decorator + @builtin + export declare function floor(a: v128): v128; // f32, f64 only + + // @ts-ignore: decorator + @builtin + export declare function trunc(a: v128): v128; // f32, f64 only + + // @ts-ignore: decorator + @builtin + export declare function nearest(a: v128): v128; // f32, f64 only + + // @ts-ignore: decorator + @builtin + export declare function eq(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ne(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function convert(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function convert_low(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc_sat(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc_sat_zero(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function narrow(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_low(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_high(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extadd_pairwise(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function demote_zero(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function promote_low(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function q15mulr_sat(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_low(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_high(a: v128, b: v128): v128; +} + +// @ts-ignore: decorator +@builtin +export declare function i8x16( + a: i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8, + i: i8, j: i8, k: i8, l: i8, m: i8, n: i8, o: i8, p: i8 +): v128; + +export namespace i8x16 { + + // @ts-ignore: decorator + @builtin + export declare function splat(x: i8): v128; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane_s(x: v128, idx: u8): i8; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane_u(x: v128, idx: u8): u8; + + // @ts-ignore: decorator + @builtin + export declare function replace_lane(x: v128, idx: u8, value: i8): v128; + + // @ts-ignore: decorator + @builtin + export declare function add(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function avgr_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function abs(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function neg(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function add_sat_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function add_sat_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub_sat_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub_sat_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function shl(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_s(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_u(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function all_true(a: v128): bool; + + // @ts-ignore: decorator + @builtin + export declare function bitmask(a: v128): i32; + + // @ts-ignore: decorator + @builtin + export declare function popcnt(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function eq(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ne(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function narrow_i16x8_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function narrow_i16x8_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function shuffle( + a: v128, b: v128, + l0: u8, l1: u8, l2: u8, l3: u8, l4: u8, l5: u8, l6: u8, l7: u8, + l8: u8, l9: u8, l10: u8, l11: u8, l12: u8, l13: u8, l14: u8, l15: u8 + ): v128; + + // @ts-ignore: decorator + @builtin + export declare function swizzle(a: v128, s: v128): v128; +} + +// @ts-ignore: decorator +@builtin +export declare function i16x8(a: i16, b: i16, c: i16, d: i16, e: i16, f: i16, g: i16, h: i16): v128; + +export namespace i16x8 { + + // @ts-ignore: decorator + @builtin + export declare function splat(x: i16): v128; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane_s(x: v128, idx: u8): i16; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane_u(x: v128, idx: u8): u16; + + // @ts-ignore: decorator + @builtin + export declare function replace_lane(x: v128, idx: u8, value: i16): v128; + + // @ts-ignore: decorator + @builtin + export declare function add(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function mul(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function avgr_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function abs(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function neg(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function add_sat_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function add_sat_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub_sat_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub_sat_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function shl(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_s(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_u(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function all_true(a: v128): bool; + + // @ts-ignore: decorator + @builtin + export declare function bitmask(a: v128): i32; + + // @ts-ignore: decorator + @builtin + export declare function eq(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ne(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function narrow_i32x4_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function narrow_i32x4_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_low_i8x16_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_low_i8x16_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_high_i8x16_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_high_i8x16_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extadd_pairwise_i8x16_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extadd_pairwise_i8x16_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function q15mulr_sat_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_low_i8x16_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_low_i8x16_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_high_i8x16_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_high_i8x16_u(a: v128, b: v128): v128; +} + +// @ts-ignore: decorator +@builtin +export declare function i32x4(a: i32, b: i32, c: i32, d: i32): v128; + +export namespace i32x4 { + + // @ts-ignore: decorator + @builtin + export declare function splat(x: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane(x: v128, idx: u8): i32; + + // @ts-ignore: decorator + @builtin + export declare function replace_lane(x: v128, idx: u8, value: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function add(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function mul(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function dot_i16x8_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function abs(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function neg(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function shl(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_s(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_u(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function all_true(a: v128): bool; + + // @ts-ignore: decorator + @builtin + export declare function bitmask(a: v128): i32; + + // @ts-ignore: decorator + @builtin + export declare function eq(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ne(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc_sat_f32x4_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc_sat_f32x4_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc_sat_f64x2_s_zero(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc_sat_f64x2_u_zero(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_low_i16x8_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_low_i16x8_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_high_i16x8_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_high_i16x8_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extadd_pairwise_i16x8_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extadd_pairwise_i16x8_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_low_i16x8_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_low_i16x8_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_high_i16x8_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_high_i16x8_u(a: v128, b: v128): v128; +} + +// @ts-ignore: decorator +@builtin +export declare function i64x2(a: i64, b: i64): v128; + +export namespace i64x2 { + + // @ts-ignore: decorator + @builtin + export declare function splat(x: i64): v128; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane(x: v128, idx: u8): i64; + + // @ts-ignore: decorator + @builtin + export declare function replace_lane(x: v128, idx: u8, value: i64): v128; + + // @ts-ignore: decorator + @builtin + export declare function add(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function mul(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function abs(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function neg(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function shl(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_s(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function shr_u(a: v128, b: i32): v128; + + // @ts-ignore: decorator + @builtin + export declare function all_true(a: v128): bool; + + // @ts-ignore: decorator + @builtin + export declare function bitmask(a: v128): i32; + + // @ts-ignore: decorator + @builtin + export declare function eq(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ne(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_low_i32x4_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_low_i32x4_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_high_i32x4_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extend_high_i32x4_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_low_i32x4_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_low_i32x4_u(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_high_i32x4_s(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function extmul_high_i32x4_u(a: v128, b: v128): v128; +} + +// @ts-ignore: decorator +@builtin +export declare function f32x4(a: f32, b: f32, c: f32, d: f32): v128; + +export namespace f32x4 { + + // @ts-ignore: decorator + @builtin + export declare function splat(x: f32): v128; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane(x: v128, idx: u8): f32; + + // @ts-ignore: decorator + @builtin + export declare function replace_lane(x: v128, idx: u8, value: f32): v128; + + // @ts-ignore: decorator + @builtin + export declare function add(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function mul(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function div(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function neg(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function pmin(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function pmax(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function abs(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sqrt(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ceil(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function floor(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function nearest(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function eq(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ne(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function convert_i32x4_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function convert_i32x4_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function demote_f64x2_zero(a: v128): v128; +} + +// @ts-ignore: decorator +@builtin +export declare function f64x2(a: f64, b: f64): v128; + +export namespace f64x2 { + + // @ts-ignore: decorator + @builtin + export declare function splat(x: f64): v128; + + // @ts-ignore: decorator + @builtin + export declare function extract_lane(x: v128, idx: u8): f64; + + // @ts-ignore: decorator + @builtin + export declare function replace_lane(x: v128, idx: u8, value: f64): v128; + + // @ts-ignore: decorator + @builtin + export declare function add(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sub(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function mul(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function div(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function neg(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function min(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function max(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function pmin(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function pmax(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function abs(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function sqrt(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ceil(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function floor(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function trunc(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function nearest(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function eq(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ne(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function lt(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function le(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function gt(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function ge(a: v128, b: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function convert_low_i32x4_s(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function convert_low_i32x4_u(a: v128): v128; + + // @ts-ignore: decorator + @builtin + export declare function promote_low_f32x4(a: v128): v128; +} + +@final +export abstract class i31 { // FIXME: usage of 'new' requires a class :( + + // @ts-ignore: decorator + @builtin + static new(value: i32): i31ref { return changetype(unreachable()); } + + // @ts-ignore: decorator + @builtin + static get(i31expr: i31ref): i32 { return unreachable(); } +} + +/* eslint-disable @typescript-eslint/no-unused-vars */ + +// @ts-ignore: decorator +@external("env", "abort") +@external.js("throw Error(\`\${message} in \${fileName}:\${lineNumber}:\${columnNumber}\`);") +declare function abort( + message?: string | null, + fileName?: string | null, + lineNumber?: u32, + columnNumber?: u32 +): void; + +// @ts-ignore: decorator +@external("env", "trace") +@external.js("console.log(message, ...[a0, a1, a2, a3, a4].slice(0, n));") +declare function trace( + message: string, + n?: i32, + a0?: f64, + a1?: f64, + a2?: f64, + a3?: f64, + a4?: f64 +): void; + +// @ts-ignore: decorator +@external("env", "seed") +@external.js("return Date.now() * Math.random();") +declare function seed(): f64; + +/* eslint-enable @typescript-eslint/no-unused-vars */ +`,compat:`export type ReturnType = returnof; +export type NonNullable = nonnull; +`,console:`import { + process +} from "./process"; + +import { + console as binding +} from "./bindings/dom"; + +// @ts-ignore: decorator +@lazy var timers = new Map(); + +export namespace console { + + export function assert(condition: T, message: string = ""): void { + if (isDefined(ASC_WASI)) { + if (!condition) { + let stderr = process.stderr; + stderr.write("Assertion failed: "); + stderr.write(message); + stderr.write("\\n"); + } + } else { + binding.assert(!!condition, message); + } + } + + export function log(message: string = ""): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + stdout.write(message); + stdout.write("\\n"); + } else { + binding.log(message); + } + } + + export function debug(message: string = ""): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + stdout.write("Debug: "); + stdout.write(message); + stdout.write("\\n"); + } else { + binding.debug(message); + } + } + + export function info(message: string = ""): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + stdout.write("Info: "); + stdout.write(message); + stdout.write("\\n"); + } else { + binding.info(message); + } + } + + export function warn(message: string = ""): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + stdout.write("Warning: "); + stdout.write(message); + stdout.write("\\n"); + } else { + binding.warn(message); + } + } + + export function error(message: string = ""): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + stdout.write("Error: "); + stdout.write(message); + stdout.write("\\n"); + } else { + binding.error(message); + } + } + + export function time(label: string = "default"): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + if (timers.has(label)) { + stdout.write("Warning: Label '"); + stdout.write(label); + stdout.write("' already exists for console.time()\\n"); + return; + } + timers.set(label, process.hrtime()); + } else { + binding.time(label); + } + } + + export function timeLog(label: string = "default"): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + if (!timers.has(label)) { + stdout.write("Warning: No such label '"); + stdout.write(label); + stdout.write("' for console.timeLog()\\n"); + return; + } + timeLogImpl(label); + } else { + binding.timeLog(label); + } + } + + export function timeEnd(label: string = "default"): void { + if (isDefined(ASC_WASI)) { + let stdout = process.stdout; + if (!timers.has(label)) { + stdout.write("Warning: No such label '"); + stdout.write(label); + stdout.write("' for console.timeEnd()\\n"); + return; + } + timeLogImpl(label); + timers.delete(label); + } else { + binding.timeEnd(label); + } + } +} + +function timeLogImpl(label: string): void { + var start = changetype(timers.get(label)); + var end = process.hrtime(); + var nanos = end - start; + var millis = nanos / 1000000; + var millisStr = millis.toString(); + var stdout = process.stdout; + stdout.write(label); + stdout.write(": "); + stdout.write(millisStr); + stdout.write("ms\\n"); +} +`,crypto:`import { + errnoToString, + random_get +} from "bindings/wasi_snapshot_preview1"; + +import { + crypto as crypto_binding +} from "bindings/dom"; + +export namespace crypto { + export function getRandomValues(array: Uint8Array): void { + if (isDefined(ASC_WASI)) { + let err = random_get(changetype(array.buffer) + array.byteOffset, array.byteLength); + if (err) throw new Error(errnoToString(err)); + } else { + crypto_binding.getRandomValues(array); + } + } +} +`,dataview:`import { BLOCK_MAXSIZE } from "./rt/common"; +import { ArrayBuffer } from "./arraybuffer"; +import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH } from "./util/error"; + +// TODO: there is probably a smarter way to check byteOffset for accesses larger than 1 byte + +export class DataView { + + readonly buffer: ArrayBuffer; + @unsafe readonly dataStart: usize; + readonly byteLength: i32; + + get byteOffset(): i32 { + return (this.dataStart - changetype(this.buffer)); + } + + constructor( + buffer: ArrayBuffer, + byteOffset: i32 = 0, + byteLength: i32 = buffer.byteLength + ) { + if ( + i32(byteLength > BLOCK_MAXSIZE) | + i32(byteOffset + byteLength > buffer.byteLength) + ) throw new RangeError(E_INVALIDLENGTH); + this.buffer = buffer; // links + var dataStart = changetype(buffer) + byteOffset; + this.dataStart = dataStart; + this.byteLength = byteLength; + } + + getFloat32(byteOffset: i32, littleEndian: bool = false): f32 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 4 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + return littleEndian + ? load(this.dataStart + byteOffset) + : reinterpret(bswap(load(this.dataStart + byteOffset))); + } + + getFloat64(byteOffset: i32, littleEndian: bool = false): f64 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 8 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + return littleEndian + ? load(this.dataStart + byteOffset) + : reinterpret(bswap(load(this.dataStart + byteOffset))); + } + + getInt8(byteOffset: i32): i8 { + if (byteOffset >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + byteOffset); + } + + getInt16(byteOffset: i32, littleEndian: bool = false): i16 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 2 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + var result: i16 = load(this.dataStart + byteOffset); + return littleEndian ? result : bswap(result); + } + + getInt32(byteOffset: i32, littleEndian: bool = false): i32 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 4 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + var result: i32 = load(this.dataStart + byteOffset); + return littleEndian ? result : bswap(result); + } + + getUint8(byteOffset: i32): u8 { + if (byteOffset >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + byteOffset); + } + + getUint16(byteOffset: i32, littleEndian: bool = false): u16 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 2 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + var result: u16 = load(this.dataStart + byteOffset); + return littleEndian ? result : bswap(result); + } + + getUint32(byteOffset: i32, littleEndian: bool = false): u32 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 4 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + var result: u32 = load(this.dataStart + byteOffset); + return littleEndian ? result : bswap(result); + } + + setFloat32(byteOffset: i32, value: f32, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 4 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + if (littleEndian) store(this.dataStart + byteOffset, value); + else store(this.dataStart + byteOffset, bswap(reinterpret(value))); + } + + setFloat64(byteOffset: i32, value: f64, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 8 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + if (littleEndian) store(this.dataStart + byteOffset, value); + else store(this.dataStart + byteOffset, bswap(reinterpret(value))); + } + + setInt8(byteOffset: i32, value: i8): void { + if (byteOffset >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, value); + } + + setInt16(byteOffset: i32, value: i16, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 2 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, littleEndian ? value : bswap(value)); + } + + setInt32(byteOffset: i32, value: i32, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 4 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, littleEndian ? value : bswap(value)); + } + + setUint8(byteOffset: i32, value: u8): void { + if (byteOffset >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, value); + } + + setUint16(byteOffset: i32, value: u16, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 2 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, littleEndian ? value : bswap(value)); + } + + setUint32(byteOffset: i32, value: u32, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 4 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, littleEndian ? value : bswap(value)); + } + + // Non-standard additions that make sense in WebAssembly, but won't work in JS: + + getInt64(byteOffset: i32, littleEndian: bool = false): i64 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 8 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + var result: i64 = load(this.dataStart + byteOffset); + return littleEndian ? result : bswap(result); + } + + getUint64(byteOffset: i32, littleEndian: bool = false): u64 { + if ( + (byteOffset >>> 31) | i32(byteOffset + 8 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + var result = load(this.dataStart + byteOffset); + return littleEndian ? result : bswap(result); + } + + setInt64(byteOffset: i32, value: i64, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 8 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, littleEndian ? value : bswap(value)); + } + + setUint64(byteOffset: i32, value: u64, littleEndian: bool = false): void { + if ( + (byteOffset >>> 31) | i32(byteOffset + 8 > this.byteLength) + ) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + byteOffset, littleEndian ? value : bswap(value)); + } + + toString(): string { + return "[object DataView]"; + } +} +`,date:`import { E_INVALIDDATE } from "util/error"; +import { Date as Date_binding } from "./bindings/dom"; + +// @ts-ignore: decorator +@inline const + MILLIS_PER_DAY = 1000 * 60 * 60 * 24, + MILLIS_PER_HOUR = 1000 * 60 * 60, + MILLIS_PER_MINUTE = 1000 * 60, + MILLIS_PER_SECOND = 1000; + +// ymdFromEpochDays returns values via globals to avoid allocations +// @ts-ignore: decorator +@lazy let _month: i32, _day: i32; + +export class Date { + private year: i32 = 0; + private month: i32 = 0; + private day: i32 = 0; + + @inline static UTC( + year: i32, + month: i32 = 0, + day: i32 = 1, + hour: i32 = 0, + minute: i32 = 0, + second: i32 = 0, + millisecond: i32 = 0 + ): i64 { + if (year >= 0 && year <= 99) year += 1900; + var ms = epochMillis(year, month + 1, day, hour, minute, second, millisecond); + if (invalidDate(ms)) throw new RangeError(E_INVALIDDATE); + return ms; + } + + @inline static now(): i64 { + return Date_binding.now(); + } + + // It can parse only ISO 8601 inputs like YYYY-MM-DDTHH:MM:SS.000Z + @inline static parse(dateString: string): Date { + return this.fromString(dateString); + } + + static fromString(dateTimeString: string): Date { + if (!dateTimeString.length) throw new RangeError(E_INVALIDDATE); + var + hour: i32 = 0, + min: i32 = 0, + sec: i32 = 0, + ms: i32 = 0; + + var dateString = dateTimeString; + var posT = dateTimeString.indexOf("T"); + if (~posT) { + // includes a time component + let timeString: string; + dateString = dateTimeString.substring(0, posT); + timeString = dateTimeString.substring(posT + 1); + // parse the HH-MM-SS component + let timeParts = timeString.split(":"); + let len = timeParts.length; + if (len <= 1) throw new RangeError(E_INVALIDDATE); + + hour = I32.parseInt(timeParts[0]); + min = I32.parseInt(timeParts[1]); + if (len >= 3) { + let secAndMs = timeParts[2]; + let posDot = secAndMs.indexOf("."); + if (~posDot) { + // includes milliseconds + sec = I32.parseInt(secAndMs.substring(0, posDot)); + ms = I32.parseInt(secAndMs.substring(posDot + 1)); + } else { + sec = I32.parseInt(secAndMs); + } + } + } + // parse the YYYY-MM-DD component + var parts = dateString.split("-"); + var year = I32.parseInt(parts[0]); + var month = 1, day = 1; + var len = parts.length; + if (len >= 2) { + month = I32.parseInt(parts[1]); + if (len >= 3) { + day = I32.parseInt(parts[2]); + } + } + return new Date(epochMillis(year, month, day, hour, min, sec, ms)); + } + + constructor(private epochMillis: i64) { + // this differs from JavaScript which prefer return NaN or "Invalid Date" string + // instead throwing exception. + if (invalidDate(epochMillis)) throw new RangeError(E_INVALIDDATE); + + this.year = ymdFromEpochDays(i32(floorDiv(epochMillis, MILLIS_PER_DAY))); + this.month = _month; + this.day = _day; + } + + @inline getTime(): i64 { + return this.epochMillis; + } + + setTime(time: i64): i64 { + if (invalidDate(time)) throw new RangeError(E_INVALIDDATE); + + this.epochMillis = time; + this.year = ymdFromEpochDays(i32(floorDiv(time, MILLIS_PER_DAY))); + this.month = _month; + this.day = _day; + + return time; + } + + @inline getUTCFullYear(): i32 { + return this.year; + } + + @inline getUTCMonth(): i32 { + return this.month - 1; + } + + @inline getUTCDate(): i32 { + return this.day; + } + + @inline getUTCDay(): i32 { + return dayOfWeek(this.year, this.month, this.day); + } + + getUTCHours(): i32 { + return i32(euclidRem(this.epochMillis, MILLIS_PER_DAY)) / MILLIS_PER_HOUR; + } + + getUTCMinutes(): i32 { + return i32(euclidRem(this.epochMillis, MILLIS_PER_HOUR)) / MILLIS_PER_MINUTE; + } + + getUTCSeconds(): i32 { + return i32(euclidRem(this.epochMillis, MILLIS_PER_MINUTE)) / MILLIS_PER_SECOND; + } + + getUTCMilliseconds(): i32 { + return i32(euclidRem(this.epochMillis, MILLIS_PER_SECOND)); + } + + setUTCMilliseconds(millis: i32): void { + this.setTime(this.epochMillis + (millis - this.getUTCMilliseconds())); + } + + setUTCSeconds(seconds: i32): void { + this.setTime(this.epochMillis + (seconds - this.getUTCSeconds()) * MILLIS_PER_SECOND); + } + + setUTCMinutes(minutes: i32): void { + this.setTime(this.epochMillis + (minutes - this.getUTCMinutes()) * MILLIS_PER_MINUTE); + } + + setUTCHours(hours: i32): void { + this.setTime(this.epochMillis + (hours - this.getUTCHours()) * MILLIS_PER_HOUR); + } + + setUTCDate(day: i32): void { + if (this.day == day) return; + var ms = euclidRem(this.epochMillis, MILLIS_PER_DAY); + this.setTime(i64(daysSinceEpoch(this.year, this.month, day)) * MILLIS_PER_DAY + ms); + } + + setUTCMonth(month: i32, day: i32 = this.day): void { + if (this.month == month + 1) return; + var ms = euclidRem(this.epochMillis, MILLIS_PER_DAY); + this.setTime(i64(daysSinceEpoch(this.year, month + 1, day)) * MILLIS_PER_DAY + ms); + } + + setUTCFullYear(year: i32): void { + if (this.year == year) return; + var ms = euclidRem(this.epochMillis, MILLIS_PER_DAY); + this.setTime(i64(daysSinceEpoch(year, this.month, this.day)) * MILLIS_PER_DAY + ms); + } + + toISOString(): string { + // TODO: add more low-level helper which combine toString and padStart without extra allocation + var yearStr: string; + var year = this.year; + var isNeg = year < 0; + if (isNeg || year >= 10000) { + yearStr = (isNeg ? "-" : "+") + abs(year).toString().padStart(6, "0"); + } else { + yearStr = year.toString().padStart(4, "0"); + } + + return ( + yearStr + + "-" + + this.month.toString().padStart(2, "0") + + "-" + + this.day.toString().padStart(2, "0") + + "T" + + this.getUTCHours().toString().padStart(2, "0") + + ":" + + this.getUTCMinutes().toString().padStart(2, "0") + + ":" + + this.getUTCSeconds().toString().padStart(2, "0") + + "." + + this.getUTCMilliseconds().toString().padStart(3, "0") + + "Z" + ); + } + + toUTCString(): string { + const weeks: StaticArray = [ + "Sun, ", "Mon, ", "Tue, ", "Wed, ", "Thu, ", "Fri, ", "Sat, " + ]; + + const months: StaticArray = [ + " Jan ", " Feb ", " Mar ", " Apr ", " May ", " Jun ", + " Jul ", " Aug ", " Sep ", " Oct ", " Nov ", " Dec " + ]; + + var mo = this.month; + var da = this.day; + var yr = this.year; + var wd = dayOfWeek(yr, mo, da); + var year = abs(yr).toString().padStart(4, "0"); + if (yr < 0) year = "-" + year; + + return ( + unchecked(weeks[wd]) + + da.toString().padStart(2, "0") + + unchecked(months[mo - 1]) + + year + + " " + + this.getUTCHours().toString().padStart(2, "0") + + ":" + + this.getUTCMinutes().toString().padStart(2, "0") + + ":" + + this.getUTCSeconds().toString().padStart(2, "0") + + " GMT" + ); + } + + toDateString(): string { + // TODO: use u64 static data instead 4 chars + // also use stream itoa variants. + const weeks: StaticArray = [ + "Sun ", "Mon ", "Tue ", "Wed ", "Thu ", "Fri ", "Sat " + ]; + + const months: StaticArray = [ + "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", + "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec " + ]; + + var mo = this.month; + var da = this.day; + var yr = this.year; + var wd = dayOfWeek(yr, mo, da); + var year = abs(yr).toString().padStart(4, "0"); + if (yr < 0) year = "-" + year; + + return ( + unchecked(weeks[wd]) + + unchecked(months[mo - 1]) + + da.toString().padStart(2, "0") + + " " + year + ); + } + + // Note: it uses UTC time instead local time (without timezone offset) + toTimeString(): string { + // TODO: add timezone + return ( + this.getUTCHours().toString().padStart(2, "0") + + ":" + + this.getUTCMinutes().toString().padStart(2, "0") + + ":" + + this.getUTCSeconds().toString().padStart(2, "0") + ); + } + + // Note: it uses UTC datetime instead local datetime (without timezone offset) + toString(): string { + return this.toDateString() + " " + this.toTimeString(); + } +} + +function epochMillis( + year: i32, + month: i32, + day: i32, + hour: i32, + minute: i32, + second: i32, + milliseconds: i32 +): i64 { + return ( + i64(daysSinceEpoch(year, month, day)) * MILLIS_PER_DAY + + hour * MILLIS_PER_HOUR + + minute * MILLIS_PER_MINUTE + + second * MILLIS_PER_SECOND + + milliseconds + ); +} + +// @ts-ignore: decorator +@inline function floorDiv(a: T, b: T): T { + return (a >= 0 ? a : a - b + 1) / b as T; +} + +// @ts-ignore: decorator +@inline function euclidRem(a: T, b: T): T { + var m = a % b; + return m + (m < 0 ? b : 0) as T; +} + +function invalidDate(millis: i64): bool { + // @ts-ignore + return (millis < -8640000000000000) | (millis > 8640000000000000); +} + +// see: http://howardhinnant.github.io/date_algorithms.html#civil_from_days +function ymdFromEpochDays(z: i32): i32 { + z += 719468; + var era = floorDiv(z, 146097); + var doe = z - era * 146097; // [0, 146096] + var yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399] + var year = yoe + era * 400; + var doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] + var mo = (5 * doy + 2) / 153; // [0, 11] + _day = doy - (153 * mo + 2) / 5 + 1; // [1, 31] + mo += mo < 10 ? 3 : -9; // [1, 12] + _month = mo; + year += u32(mo <= 2); + return year; +} + +// http://howardhinnant.github.io/date_algorithms.html#days_from_civil +function daysSinceEpoch(y: i32, m: i32, d: i32): i32 { + y -= i32(m <= 2); + var era = floorDiv(y, 400); + var yoe = y - era * 400; // [0, 399] + var doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; // [0, 365] + var doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] + return era * 146097 + doe - 719468; +} + +// TomohikoSakamoto algorithm from https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week +function dayOfWeek(year: i32, month: i32, day: i32): i32 { + const tab = memory.data([0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]); + + year -= i32(month < 3); + year += floorDiv(year, 4) - floorDiv(year, 100) + floorDiv(year, 400); + month = load(tab + month - 1); + return euclidRem(year + month + day, 7); +} +`,diagnostics:`// @ts-ignore: decorator +@builtin +export declare function ERROR(message?: string): void; + +// @ts-ignore: decorator +@builtin +export declare function WARNING(message?: string): void; + +// @ts-ignore: decorator +@builtin +export declare function INFO(message?: string): void; +`,error:`export class Error { + + name: string = "Error"; + stack: string = ""; // TODO + + constructor( + public message: string = "" + ) {} + + toString(): string { + var message = this.message; + return message.length + ? this.name + ": " + message + : this.name; + } +} + +export class RangeError extends Error { + constructor(message: string = "") { + super(message); + this.name = "RangeError"; + } +} + +export class TypeError extends Error { + constructor(message: string = "") { + super(message); + this.name = "TypeError"; + } +} + +export class SyntaxError extends Error { + constructor(message: string = "") { + super(message); + this.name = "SyntaxError"; + } +} + +export class URIError extends Error { + constructor(message: string = "") { + super(message); + this.name = "URIError"; + } +} +`,function:`type auto = i32; + +@final export abstract class Function { + private _index: u32; + private _env: usize; + + // @ts-ignore: this on getter + get index(this: T): u32 { + return load(changetype(this), offsetof>("_index")); + } + + // @ts-ignore: this on getter + get name(this: T): string { + return ""; + } + + // @ts-ignore: this on getter + get length(this: T): i32 { + // @ts-ignore: T is function + return lengthof(); + } + + // @ts-ignore: T is function + @builtin call(thisArg: thisof | null, ...args: auto[]): returnof { + return unreachable(); + } + + toString(this: T): string { + return "function() { [native code] }"; + } + + // RT integration + + @unsafe private __visit(cookie: u32): void { + // Env is either \`null\` (nop) or compiler-generated + __visit(this._env, cookie); + } +} +`,iterator:`export abstract class Iterable { + // ? +} + +@final +export abstract class Iterator { + + // private constructor(iterable: Iterable) { + // } + + // TODO: these need to evaluate the classId at the respective reference in order to obtain the + // next value, i.e. arrays work differently than maps. we'd then have: + // + // \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Iterator layout (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 + // 3 2 1 + // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits + // \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 + // \u2502 index \u2502 + // \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u252C\u2500\u2524 + // \u2502 reference \u2502 0 \u2502D\u2502 + // \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2518 + // D: Done flag + + // get value(this: u64): T { + // ? + // } + + // next(this: u64): Iterator { + // ? + // } + + done(this: u64): bool { + return (this & 1); + } +} +`,map:`/// + +import { HASH } from "./util/hash"; +import { E_KEYNOTFOUND } from "./util/error"; + +// A deterministic hash map based on CloseTable from https://github.com/jorendorff/dht + +// @ts-ignore: decorator +@inline const INITIAL_CAPACITY = 4; + +// @ts-ignore: decorator +@inline const FILL_FACTOR_N = 8; + +// @ts-ignore: decorator +@inline const FILL_FACTOR_D = 3; + +// @ts-ignore: decorator +@inline const FREE_FACTOR_N = 3; + +// @ts-ignore: decorator +@inline const FREE_FACTOR_D = 4; + +/** Structure of a map entry. */ +@unmanaged class MapEntry { + key: K; + value: V; + taggedNext: usize; // LSB=1 indicates EMPTY +} + +/** Empty bit. */ +// @ts-ignore: decorator +@inline const EMPTY: usize = 1 << 0; + +/** Size of a bucket. */ +// @ts-ignore: decorator +@inline const BUCKET_SIZE = sizeof(); + +/** Computes the alignment of an entry. */ +// @ts-ignore: decorator +@inline +function ENTRY_ALIGN(): usize { + // can align to 4 instead of 8 if 32-bit and K/V is <= 32-bits + const maxkv = sizeof() > sizeof() ? sizeof() : sizeof(); + const align = (maxkv > sizeof() ? maxkv : sizeof()) - 1; + return align; +} + +/** Computes the aligned size of an entry. */ +// @ts-ignore: decorator +@inline +function ENTRY_SIZE(): usize { + const align = ENTRY_ALIGN(); + const size = (offsetof>() + align) & ~align; + return size; +} + +export class Map { + + // buckets referencing their respective first entry, usize[bucketsMask + 1] + private buckets: ArrayBuffer = new ArrayBuffer(INITIAL_CAPACITY * BUCKET_SIZE); + private bucketsMask: u32 = INITIAL_CAPACITY - 1; + + // entries in insertion order, MapEntry[entriesCapacity] + private entries: ArrayBuffer = new ArrayBuffer(INITIAL_CAPACITY * ENTRY_SIZE()); + private entriesCapacity: i32 = INITIAL_CAPACITY; + private entriesOffset: i32 = 0; + private entriesCount: i32 = 0; + + constructor() { + /* nop */ + } + + get size(): i32 { + return this.entriesCount; + } + + clear(): void { + this.buckets = new ArrayBuffer(INITIAL_CAPACITY * BUCKET_SIZE); + this.bucketsMask = INITIAL_CAPACITY - 1; + this.entries = new ArrayBuffer(INITIAL_CAPACITY * ENTRY_SIZE()); + this.entriesCapacity = INITIAL_CAPACITY; + this.entriesOffset = 0; + this.entriesCount = 0; + } + + private find(key: K, hashCode: u32): MapEntry | null { + var entry = load>( // unmanaged! + changetype(this.buckets) + (hashCode & this.bucketsMask) * BUCKET_SIZE + ); + while (entry) { + let taggedNext = entry.taggedNext; + if (!(taggedNext & EMPTY) && entry.key == key) return entry; + entry = changetype>(taggedNext & ~EMPTY); + } + return null; + } + + has(key: K): bool { + return this.find(key, HASH(key)) != null; + } + + @operator("[]") + get(key: K): V { + var entry = this.find(key, HASH(key)); + if (!entry) throw new Error(E_KEYNOTFOUND); // cannot represent \`undefined\` + return entry.value; + } + + @operator("[]=") + set(key: K, value: V): this { + var hashCode = HASH(key); + var entry = this.find(key, hashCode); // unmanaged! + if (entry) { + entry.value = value; + if (isManaged()) { + __link(changetype(this), changetype(value), true); + } + } else { + // check if rehashing is necessary + if (this.entriesOffset == this.entriesCapacity) { + this.rehash( + this.entriesCount < this.entriesCapacity * FREE_FACTOR_N / FREE_FACTOR_D + ? this.bucketsMask // just rehash if 1/4+ entries are empty + : (this.bucketsMask << 1) | 1 // grow capacity to next 2^N + ); + } + // append new entry + let entries = this.entries; + entry = changetype>(changetype(entries) + (this.entriesOffset++) * ENTRY_SIZE()); + // link with the map + entry.key = key; + if (isManaged()) { + __link(changetype(this), changetype(key), true); + } + entry.value = value; + if (isManaged()) { + __link(changetype(this), changetype(value), true); + } + ++this.entriesCount; + // link with previous entry in bucket + let bucketPtrBase = changetype(this.buckets) + (hashCode & this.bucketsMask) * BUCKET_SIZE; + entry.taggedNext = load(bucketPtrBase); + store(bucketPtrBase, changetype(entry)); + } + return this; + } + + delete(key: K): bool { + var entry = this.find(key, HASH(key)); + if (!entry) return false; + entry.taggedNext |= EMPTY; + --this.entriesCount; + // check if rehashing is appropriate + var halfBucketsMask = this.bucketsMask >> 1; + if ( + halfBucketsMask + 1 >= max(INITIAL_CAPACITY, this.entriesCount) && + this.entriesCount < this.entriesCapacity * FREE_FACTOR_N / FREE_FACTOR_D + ) this.rehash(halfBucketsMask); + return true; + } + + private rehash(newBucketsMask: u32): void { + var newBucketsCapacity = (newBucketsMask + 1); + var newBuckets = new ArrayBuffer(newBucketsCapacity * BUCKET_SIZE); + var newEntriesCapacity = newBucketsCapacity * FILL_FACTOR_N / FILL_FACTOR_D; + var newEntries = new ArrayBuffer(newEntriesCapacity * ENTRY_SIZE()); + + // copy old entries to new entries + var oldPtr = changetype(this.entries); + var oldEnd = oldPtr + this.entriesOffset * ENTRY_SIZE(); + var newPtr = changetype(newEntries); + while (oldPtr != oldEnd) { + let oldEntry = changetype>(oldPtr); + if (!(oldEntry.taggedNext & EMPTY)) { + let newEntry = changetype>(newPtr); + let oldEntryKey = oldEntry.key; + newEntry.key = oldEntryKey; + newEntry.value = oldEntry.value; + let newBucketIndex = HASH(oldEntryKey) & newBucketsMask; + let newBucketPtrBase = changetype(newBuckets) + newBucketIndex * BUCKET_SIZE; + newEntry.taggedNext = load(newBucketPtrBase); + store(newBucketPtrBase, newPtr); + newPtr += ENTRY_SIZE(); + } + oldPtr += ENTRY_SIZE(); + } + + this.buckets = newBuckets; + this.bucketsMask = newBucketsMask; + this.entries = newEntries; + this.entriesCapacity = newEntriesCapacity; + this.entriesOffset = this.entriesCount; + } + + keys(): K[] { + // FIXME: this is preliminary, needs iterators/closures + var start = changetype(this.entries); + var size = this.entriesOffset; + var keys = new Array(size); + var length = 0; + for (let i = 0; i < size; ++i) { + let entry = changetype>(start + i * ENTRY_SIZE()); + if (!(entry.taggedNext & EMPTY)) { + keys[length++] = entry.key; + } + } + keys.length = length; + return keys; + } + + values(): V[] { + // FIXME: this is preliminary, needs iterators/closures + var start = changetype(this.entries); + var size = this.entriesOffset; + var values = new Array(size); + var length = 0; + for (let i = 0; i < size; ++i) { + let entry = changetype>(start + i * ENTRY_SIZE()); + if (!(entry.taggedNext & EMPTY)) { + values[length++] = entry.value; + } + } + values.length = length; + return values; + } + + toString(): string { + return "[object Map]"; + } + + // RT integration + + @unsafe private __visit(cookie: u32): void { + __visit(changetype(this.buckets), cookie); + var entries = changetype(this.entries); + if (isManaged() || isManaged()) { + let cur = entries; + let end = cur + this.entriesOffset * ENTRY_SIZE(); + while (cur < end) { + let entry = changetype>(cur); + if (!(entry.taggedNext & EMPTY)) { + if (isManaged()) { + let val = changetype(entry.key); + if (isNullable()) { + if (val) __visit(val, cookie); + } else __visit(val, cookie); + } + if (isManaged()) { + let val = changetype(entry.value); + if (isNullable()) { + if (val) __visit(val, cookie); + } else __visit(val, cookie); + } + } + cur += ENTRY_SIZE(); + } + } + __visit(entries, cookie); + } +} +`,math:`import { Math as JSMath } from "./bindings/dom"; +export { JSMath }; + +import { + pow_lut, exp_lut, exp2_lut, log_lut, log2_lut, + powf_lut, expf_lut, exp2f_lut, logf_lut, log2f_lut +} from "./util/math"; + +import { + abs as builtin_abs, + ceil as builtin_ceil, + clz as builtin_clz, + copysign as builtin_copysign, + floor as builtin_floor, + max as builtin_max, + min as builtin_min, + sqrt as builtin_sqrt, + trunc as builtin_trunc +} from "./builtins"; + +// SUN COPYRIGHT NOTICE +// +// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. +// Developed at SunPro, a Sun Microsystems, Inc. business. +// Permission to use, copy, modify, and distribute this software +// is freely granted, provided that this notice is preserved. +// +// Applies to all functions marked with a comment referring here. + +/** @internal */ +// @ts-ignore: decorator +@lazy var rempio2_y0: f64, rempio2_y1: f64, res128_hi: u64; + +/** @internal */ +// @ts-ignore: decorator +@lazy @inline const PIO2_TABLE = memory.data([ + 0x00000000A2F9836E, 0x4E441529FC2757D1, 0xF534DDC0DB629599, 0x3C439041FE5163AB, + 0xDEBBC561B7246E3A, 0x424DD2E006492EEA, 0x09D1921CFE1DEB1C, 0xB129A73EE88235F5, + 0x2EBB4484E99C7026, 0xB45F7E413991D639, 0x835339F49C845F8B, 0xBDF9283B1FF897FF, + 0xDE05980FEF2F118B, 0x5A0A6D1F6D367ECF, 0x27CB09B74F463F66, 0x9E5FEA2D7527BAC7, + 0xEBE5F17B3D0739F7, 0x8A5292EA6BFB5FB1, 0x1F8D5D0856033046, 0xFC7B6BABF0CFBC20, + 0x9AF4361DA9E39161, 0x5EE61B086599855F, 0x14A068408DFFD880, 0x4D73273106061557 +]); + +/** @internal */ +function R(z: f64): f64 { // Rational approximation of (asin(x)-x)/x^3 + const // see: musl/src/math/asin.c and SUN COPYRIGHT NOTICE above + pS0 = reinterpret(0x3FC5555555555555), // 1.66666666666666657415e-01 + pS1 = reinterpret(0xBFD4D61203EB6F7D), // -3.25565818622400915405e-01 + pS2 = reinterpret(0x3FC9C1550E884455), // 2.01212532134862925881e-01 + pS3 = reinterpret(0xBFA48228B5688F3B), // -4.00555345006794114027e-02 + pS4 = reinterpret(0x3F49EFE07501B288), // 7.91534994289814532176e-04 + pS5 = reinterpret(0x3F023DE10DFDF709), // 3.47933107596021167570e-05 + qS1 = reinterpret(0xC0033A271C8A2D4B), // -2.40339491173441421878e+00 + qS2 = reinterpret(0x40002AE59C598AC8), // 2.02094576023350569471e+00 + qS3 = reinterpret(0xBFE6066C1B8D0159), // -6.88283971605453293030e-01 + qS4 = reinterpret(0x3FB3B8C5B12E9282); // 7.70381505559019352791e-02 + + var p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); + var q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); + return p / q; +} + +/** @internal */ +// @ts-ignore: decorator +@inline +function expo2(x: f64, sign: f64): f64 { // exp(x)/2 for x >= log(DBL_MAX) + const // see: musl/src/math/__expo2.c + k = 2043, + kln2 = reinterpret(0x40962066151ADD8B); // 0x1.62066151add8bp+10 + var scale = reinterpret(((0x3FF + k / 2) << 20) << 32); + // in directed rounding correct sign before rounding or overflow is important + return NativeMath.exp(x - kln2) * (sign * scale) * scale; +} + +/** @internal */ +/* Helper function to eventually get bits of \u03C0/2 * |x| + * + * y = \u03C0/4 * (frac << clz(frac) >> 11) + * return clz(frac) + * + * Right shift 11 bits to make upper half fit in \`double\` + */ +// @ts-ignore: decorator +@inline +function pio2_right(q0: u64, q1: u64): u64 { // see: jdh8/metallic/blob/master/src/math/double/rem_pio2.c + // Bits of \u03C0/4 + const p0: u64 = 0xC4C6628B80DC1CD1; + const p1: u64 = 0xC90FDAA22168C234; + + const Ox1p_64 = reinterpret(0x3BF0000000000000); // 0x1p-64 + const Ox1p_75 = reinterpret(0x3B40000000000000); // 0x1p-75 + + var shift = clz(q1); + + q1 = q1 << shift | q0 >> (64 - shift); + q0 <<= shift; + + var lo = umuldi(p1, q1); + var hi = res128_hi; + + var ahi = hi >> 11; + var alo = lo >> 11 | hi << 53; + var blo = (Ox1p_75 * p0 * q1 + Ox1p_75 * p1 * q0); + + rempio2_y0 = (ahi + u64(lo < blo)); + rempio2_y1 = Ox1p_64 * (alo + blo); + + return shift; +} + +/** @internal */ +// @ts-ignore: decorator +@inline +function umuldi(u: u64, v: u64): u64 { + var u1: u64 , v1: u64, w0: u64, w1: u64, t: u64; + + u1 = u & 0xFFFFFFFF; + v1 = v & 0xFFFFFFFF; + + u >>= 32; + v >>= 32; + + t = u1 * v1; + w0 = t & 0xFFFFFFFF; + t = u * v1 + (t >> 32); + w1 = t >> 32; + t = u1 * v + (t & 0xFFFFFFFF); + + res128_hi = u * v + w1 + (t >> 32); + return (t << 32) + w0; +} + +/** @internal */ +function pio2_large_quot(x: f64, u: i64): i32 { // see: jdh8/metallic/blob/master/src/math/double/rem_pio2.c + var magnitude = u & 0x7FFFFFFFFFFFFFFF; + var offset = (magnitude >> 52) - 1045; + var shift = offset & 63; + var tblPtr = PIO2_TABLE + ((offset >> 6) << 3); + var s0: u64, s1: u64, s2: u64; + + var b0 = load(tblPtr, 0 << 3); + var b1 = load(tblPtr, 1 << 3); + var b2 = load(tblPtr, 2 << 3); + + // Get 192 bits of 0x1p-31 / \u03C0 with \`offset\` bits skipped + if (shift) { + let rshift = 64 - shift; + let b3 = load(tblPtr, 3 << 3); + s0 = b1 >> rshift | b0 << shift; + s1 = b2 >> rshift | b1 << shift; + s2 = b3 >> rshift | b2 << shift; + } else { + s0 = b0; + s1 = b1; + s2 = b2; + } + + var significand = (u & 0x000FFFFFFFFFFFFF) | 0x0010000000000000; + + // First 128 bits of fractional part of x/(2\u03C0) + var blo = umuldi(s1, significand); + var bhi = res128_hi; + + var ahi = s0 * significand; + var clo = (s2 >> 32) * (significand >> 32); + var plo = blo + clo; + var phi = ahi + bhi + u64(plo < clo); + + // r: u128 = p << 2 + var rlo = plo << 2; + var rhi = phi << 2 | plo >> 62; + + // s: i128 = r >> 127 + var slo = rhi >> 63; + var shi = slo >> 1; + var q = (phi >> 62) - slo; + + var shifter = 0x3CB0000000000000 - (pio2_right(rlo ^ slo, rhi ^ shi) << 52); + var signbit = (u ^ rhi) & 0x8000000000000000; + var coeff = reinterpret(shifter | signbit); + + rempio2_y0 *= coeff; + rempio2_y1 *= coeff; + + return q; +} + +/** @internal */ +// @ts-ignore: decorator +@inline +function rempio2(x: f64, u: u64, sign: i32): i32 { + const + pio2_1 = reinterpret(0x3FF921FB54400000), // 1.57079632673412561417e+00 + pio2_1t = reinterpret(0x3DD0B4611A626331), // 6.07710050650619224932e-11 + pio2_2 = reinterpret(0x3DD0B4611A600000), // 6.07710050630396597660e-11 + pio2_2t = reinterpret(0x3BA3198A2E037073), // 2.02226624879595063154e-21 + pio2_3 = reinterpret(0x3BA3198A2E000000), // 2.02226624871116645580e-21 + pio2_3t = reinterpret(0x397B839A252049C1), // 8.47842766036889956997e-32 + invpio2 = reinterpret(0x3FE45F306DC9C883); // 0.63661977236758134308 + + var ix = (u >> 32) & 0x7FFFFFFF; + + if (ASC_SHRINK_LEVEL < 1) { + if (ix < 0x4002D97C) { // |x| < 3pi/4, special case with n=+-1 + let q = 1, z: f64, y0: f64, y1: f64; + if (!sign) { + z = x - pio2_1; + if (ix != 0x3FF921FB) { // 33+53 bit pi is good enough + y0 = z - pio2_1t; + y1 = (z - y0) - pio2_1t; + } else { // near pi/2, use 33+33+53 bit pi + z -= pio2_2; + y0 = z - pio2_2t; + y1 = (z - y0) - pio2_2t; + } + } else { // negative x + z = x + pio2_1; + if (ix != 0x3FF921FB) { // 33+53 bit pi is good enough + y0 = z + pio2_1t; + y1 = (z - y0) + pio2_1t; + } else { // near pi/2, use 33+33+53 bit pi + z += pio2_2; + y0 = z + pio2_2t; + y1 = (z - y0) + pio2_2t; + } + q = -1; + } + rempio2_y0 = y0; + rempio2_y1 = y1; + return q; + } + } + + if (ix < 0x413921FB) { // |x| ~< 2^20*pi/2 (1647099) + // Use precise Cody Waite scheme + let q = nearest(x * invpio2); + let r = x - q * pio2_1; + let w = q * pio2_1t; // 1st round good to 85 bit + let j = ix >> 20; + let y0 = r - w; + let hi = (reinterpret(y0) >> 32); + let i = j - ((hi >> 20) & 0x7FF); + + if (i > 16) { // 2nd iteration needed, good to 118 + let t = r; + w = q * pio2_2; + r = t - w; + w = q * pio2_2t - ((t - r) - w); + y0 = r - w; + hi = (reinterpret(y0) >> 32); + i = j - ((hi >> 20) & 0x7FF); + if (i > 49) { // 3rd iteration need, 151 bits acc + let t = r; + w = q * pio2_3; + r = t - w; + w = q * pio2_3t - ((t - r) - w); + y0 = r - w; + } + } + let y1 = (r - y0) - w; + rempio2_y0 = y0; + rempio2_y1 = y1; + return q; + } + var q = pio2_large_quot(x, u); + return select(-q, q, sign); +} + +/** @internal */ +// @ts-ignore: decorator +@inline +function sin_kern(x: f64, y: f64, iy: i32): f64 { // see: musl/tree/src/math/__sin.c + const + S1 = reinterpret(0xBFC5555555555549), // -1.66666666666666324348e-01 + S2 = reinterpret(0x3F8111111110F8A6), // 8.33333333332248946124e-03 + S3 = reinterpret(0xBF2A01A019C161D5), // -1.98412698298579493134e-04 + S4 = reinterpret(0x3EC71DE357B1FE7D), // 2.75573137070700676789e-06 + S5 = reinterpret(0xBE5AE5E68A2B9CEB), // -2.50507602534068634195e-08 + S6 = reinterpret(0x3DE5D93A5ACFD57C); // 1.58969099521155010221e-10 + + var z = x * x; + var w = z * z; + var r = S2 + z * (S3 + z * S4) + z * w * (S5 + z * S6); + var v = z * x; + if (!iy) { + return x + v * (S1 + z * r); + } else { + return x - ((z * (0.5 * y - v * r) - y) - v * S1); + } +} + +/** @internal */ +// @ts-ignore: decorator +@inline +function cos_kern(x: f64, y: f64): f64 { // see: musl/tree/src/math/__cos.c + const + C1 = reinterpret(0x3FA555555555554C), // 4.16666666666666019037e-02 + C2 = reinterpret(0xBF56C16C16C15177), // -1.38888888888741095749e-03 + C3 = reinterpret(0x3EFA01A019CB1590), // 2.48015872894767294178e-05 + C4 = reinterpret(0xBE927E4F809C52AD), // -2.75573143513906633035e-07 + C5 = reinterpret(0x3E21EE9EBDB4B1C4), // 2.08757232129817482790e-09 + C6 = reinterpret(0xBDA8FAE9BE8838D4); // -1.13596475577881948265e-11 + + var z = x * x; + var w = z * z; + var r = z * (C1 + z * (C2 + z * C3)) + w * w * (C4 + z * (C5 + z * C6)); + var hz = 0.5 * z; + w = 1.0 - hz; + return w + (((1.0 - w) - hz) + (z * r - x * y)); +} + +/** @internal */ +function tan_kern(x: f64, y: f64, iy: i32): f64 { // see: src/lib/msun/src/k_tan.c + const + T0 = reinterpret(0x3FD5555555555563), // 3.33333333333334091986e-01 + T1 = reinterpret(0x3FC111111110FE7A), // 1.33333333333201242699e-01 + T2 = reinterpret(0x3FABA1BA1BB341FE), // 5.39682539762260521377e-02 + T3 = reinterpret(0x3F9664F48406D637), // 2.18694882948595424599e-02 + T4 = reinterpret(0x3F8226E3E96E8493), // 8.86323982359930005737e-03 + T5 = reinterpret(0x3F6D6D22C9560328), // 3.59207910759131235356e-03 + T6 = reinterpret(0x3F57DBC8FEE08315), // 1.45620945432529025516e-03 + T7 = reinterpret(0x3F4344D8F2F26501), // 5.88041240820264096874e-04 + T8 = reinterpret(0x3F3026F71A8D1068), // 2.46463134818469906812e-04 + T9 = reinterpret(0x3F147E88A03792A6), // 7.81794442939557092300e-05 + T10 = reinterpret(0x3F12B80F32F0A7E9), // 7.14072491382608190305e-05 + T11 = reinterpret(0xBEF375CBDB605373), // -1.85586374855275456654e-05 + T12 = reinterpret(0x3EFB2A7074BF7AD4); // 2.59073051863633712884e-05 + + const + one = reinterpret(0x3FF0000000000000), // 1.00000000000000000000e+00 + pio4 = reinterpret(0x3FE921FB54442D18), // 7.85398163397448278999e-01 + pio4lo = reinterpret(0x3C81A62633145C07); // 3.06161699786838301793e-17 + + var z: f64, r: f64, v: f64, w: f64, s: f64; + var hx = (reinterpret(x) >> 32); // high word of x + var ix = hx & 0x7FFFFFFF; // high word of |x| + var big = ix >= 0x3FE59428; + if (big) { // |x| >= 0.6744 + if (hx < 0) { x = -x, y = -y; } + z = pio4 - x; + w = pio4lo - y; + x = z + w; + y = 0.0; + } + z = x * x; + w = z * z; + r = T1 + w * (T3 + w * (T5 + w * (T7 + w * (T9 + w * T11)))); + v = z * (T2 + w * (T4 + w * (T6 + w * (T8 + w * (T10 + w * T12))))); + s = z * x; + r = y + z * (s * (r + v) + y); + r += T0 * s; + w = x + r; + if (big) { + v = iy; + return (1 - ((hx >> 30) & 2)) * (v - 2.0 * (x - (w * w / (w + v) - r))); + } + if (iy == 1) return w; + var a: f64, t: f64; + z = w; + z = reinterpret(reinterpret(z) & 0xFFFFFFFF00000000); + v = r - (z - x); // z + v = r + x + t = a = -one / w; // a = -1.0 / w + t = reinterpret(reinterpret(t) & 0xFFFFFFFF00000000); + s = one + t * z; + return t + a * (s + t * v); +} + +/** @internal */ +function dtoi32(x: f64): i32 { + if (ASC_SHRINK_LEVEL > 0) { + const inv32 = 1.0 / 4294967296; + return (x - 4294967296 * floor(x * inv32)); + } else { + let result = 0; + let u = reinterpret(x); + let e = (u >> 52) & 0x7FF; + if (e <= 1023 + 30) { + result = x; + } else if (e <= 1023 + 30 + 53) { + let v = (u & ((1 << 52) - 1)) | (1 << 52); + v = v << e - 1023 - 52 + 32; + result = (v >> 32); + result = select(-result, result, u >> 63); + } + return result; + } +} + +// @ts-ignore: decorator +@lazy var random_seeded = false; + +// @ts-ignore: decorator +@lazy var random_state0_64: u64, random_state1_64: u64; + +// @ts-ignore: decorator +@lazy var random_state0_32: u32, random_state1_32: u32; + +function murmurHash3(h: u64): u64 { // Force all bits of a hash block to avalanche + h ^= h >> 33; // see: https://github.com/aappleby/smhasher + h *= 0xFF51AFD7ED558CCD; + h ^= h >> 33; + h *= 0xC4CEB9FE1A85EC53; + h ^= h >> 33; + return h; +} + +function splitMix32(h: u32): u32 { + h += 0x6D2B79F5; + h = (h ^ (h >> 15)) * (h | 1); + h ^= h + (h ^ (h >> 7)) * (h | 61); + return h ^ (h >> 14); +} + +export namespace NativeMath { + + // @ts-ignore: decorator + @lazy + export const E = reinterpret(0x4005BF0A8B145769); // 2.7182818284590452354 + + // @ts-ignore: decorator + @lazy + export const LN2 = reinterpret(0x3FE62E42FEFA39EF); // 0.69314718055994530942 + + // @ts-ignore: decorator + @lazy + export const LN10 = reinterpret(0x40026BB1BBB55516); // 2.30258509299404568402 + + // @ts-ignore: decorator + @lazy + export const LOG2E = reinterpret(0x3FF71547652B82FE); // 1.4426950408889634074 + + // @ts-ignore: decorator + @lazy + export const LOG10E = reinterpret(0x3FDBCB7B1526E50E); // 0.43429448190325182765 + + // @ts-ignore: decorator + @lazy + export const PI = reinterpret(0x400921FB54442D18); // 3.14159265358979323846 + + // @ts-ignore: decorator + @lazy + export const SQRT1_2 = reinterpret(0x3FE6A09E667F3BCD); // 0.70710678118654752440 + + // @ts-ignore: decorator + @lazy + export const SQRT2 = reinterpret(0x3FF6A09E667F3BCD); // 1.41421356237309504880 + + // @ts-ignore: decorator + @lazy + export var sincos_sin: f64 = 0; + + // @ts-ignore: decorator + @lazy + export var sincos_cos: f64 = 0; + + // @ts-ignore: decorator + @inline export function abs(x: f64): f64 { + return builtin_abs(x); + } + + export function acos(x: f64): f64 { // see: musl/src/math/acos.c and SUN COPYRIGHT NOTICE above + const + pio2_hi = reinterpret(0x3FF921FB54442D18), // 1.57079632679489655800e+00 + pio2_lo = reinterpret(0x3C91A62633145C07), // 6.12323399573676603587e-17 + Ox1p_120f = reinterpret(0x03800000); + + var hx = (reinterpret(x) >> 32); + var ix = hx & 0x7FFFFFFF; + if (ix >= 0x3FF00000) { + let lx = reinterpret(x); + if ((ix - 0x3FF00000 | lx) == 0) { + if (hx >> 31) return 2 * pio2_hi + Ox1p_120f; + return 0; + } + return 0 / (x - x); + } + if (ix < 0x3FE00000) { + if (ix <= 0x3C600000) return pio2_hi + Ox1p_120f; + return pio2_hi - (x - (pio2_lo - x * R(x * x))); + } + var s: f64, w: f64, z: f64; + if (hx >> 31) { + // z = (1.0 + x) * 0.5; + z = 0.5 + x * 0.5; + s = builtin_sqrt(z); + w = R(z) * s - pio2_lo; + return 2 * (pio2_hi - (s + w)); + } + // z = (1.0 - x) * 0.5; + z = 0.5 - x * 0.5; + s = builtin_sqrt(z); + var df = reinterpret(reinterpret(s) & 0xFFFFFFFF00000000); + var c = (z - df * df) / (s + df); + w = R(z) * s + c; + return 2 * (df + w); + } + + export function acosh(x: f64): f64 { // see: musl/src/math/acosh.c + const s = reinterpret(0x3FE62E42FEFA39EF); + var u = reinterpret(x); + // Prevent propagation for all input values less than 1.0. + // Note musl lib didn't fix this yet. + if (u < 0x3FF0000000000000) return (x - x) / 0.0; + var e = u >> 52 & 0x7FF; + if (e < 0x3FF + 1) return log1p(x - 1 + builtin_sqrt((x - 1) * (x - 1) + 2 * (x - 1))); + if (e < 0x3FF + 26) return log(2 * x - 1 / (x + builtin_sqrt(x * x - 1))); + return log(x) + s; + } + + export function asin(x: f64): f64 { // see: musl/src/math/asin.c and SUN COPYRIGHT NOTICE above + const + pio2_hi = reinterpret(0x3FF921FB54442D18), // 1.57079632679489655800e+00 + pio2_lo = reinterpret(0x3C91A62633145C07), // 6.12323399573676603587e-17 + Ox1p_120f = reinterpret(0x03800000); + + var hx = (reinterpret(x) >> 32); + var ix = hx & 0x7FFFFFFF; + if (ix >= 0x3FF00000) { + let lx = reinterpret(x); + if ((ix - 0x3FF00000 | lx) == 0) return x * pio2_hi + Ox1p_120f; + return 0 / (x - x); + } + if (ix < 0x3FE00000) { + if (ix < 0x3E500000 && ix >= 0x00100000) return x; + return x + x * R(x * x); + } + // var z = (1.0 - builtin_abs(x)) * 0.5; + var z = 0.5 - builtin_abs(x) * 0.5; + var s = builtin_sqrt(z); + var r = R(z); + if (ix >= 0x3FEF3333) x = pio2_hi - (2 * (s + s * r) - pio2_lo); + else { + let f = reinterpret(reinterpret(s) & 0xFFFFFFFF00000000); + let c = (z - f * f) / (s + f); + x = 0.5 * pio2_hi - (2 * s * r - (pio2_lo - 2 * c) - (0.5 * pio2_hi - 2 * f)); + } + if (hx >> 31) return -x; + return x; + } + + export function asinh(x: f64): f64 { // see: musl/src/math/asinh.c + const c = reinterpret(0x3FE62E42FEFA39EF); // 0.693147180559945309417232121458176568 + var u = reinterpret(x); + var e = u >> 52 & 0x7FF; + var y = reinterpret(u & 0x7FFFFFFFFFFFFFFF); + if (e >= 0x3FF + 26) y = log(y) + c; + else if (e >= 0x3FF + 1) y = log(2 * y + 1 / (builtin_sqrt(y * y + 1) + y)); + else if (e >= 0x3FF - 26) y = log1p(y + y * y / (builtin_sqrt(y * y + 1) + 1)); + return builtin_copysign(y, x); + } + + export function atan(x: f64): f64 { // see musl/src/math/atan.c and SUN COPYRIGHT NOTICE above + const + atanhi0 = reinterpret(0x3FDDAC670561BB4F), // 4.63647609000806093515e-01 + atanhi1 = reinterpret(0x3FE921FB54442D18), // 7.85398163397448278999e-01 + atanhi2 = reinterpret(0x3FEF730BD281F69B), // 9.82793723247329054082e-01 + atanhi3 = reinterpret(0x3FF921FB54442D18), // 1.57079632679489655800e+00 + atanlo0 = reinterpret(0x3C7A2B7F222F65E2), // 2.26987774529616870924e-17 + atanlo1 = reinterpret(0x3C81A62633145C07), // 3.06161699786838301793e-17 + atanlo2 = reinterpret(0x3C7007887AF0CBBD), // 1.39033110312309984516e-17 + atanlo3 = reinterpret(0x3C91A62633145C07), // 6.12323399573676603587e-17 + aT0 = reinterpret(0x3FD555555555550D), // 3.33333333333329318027e-01 + aT1 = reinterpret(0xBFC999999998EBC4), // -1.99999999998764832476e-01 + aT2 = reinterpret(0x3FC24924920083FF), // 1.42857142725034663711e-01 + aT3 = reinterpret(0xBFBC71C6FE231671), // -1.11111104054623557880e-01, + aT4 = reinterpret(0x3FB745CDC54C206E), // 9.09088713343650656196e-02 + aT5 = reinterpret(0xBFB3B0F2AF749A6D), // -7.69187620504482999495e-02 + aT6 = reinterpret(0x3FB10D66A0D03D51), // 6.66107313738753120669e-02 + aT7 = reinterpret(0xBFADDE2D52DEFD9A), // -5.83357013379057348645e-02 + aT8 = reinterpret(0x3FA97B4B24760DEB), // 4.97687799461593236017e-02 + aT9 = reinterpret(0xBFA2B4442C6A6C2F), // -3.65315727442169155270e-02 + aT10 = reinterpret(0x3F90AD3AE322DA11), // 1.62858201153657823623e-02 + Ox1p_120f = reinterpret(0x03800000); + + var ix = (reinterpret(x) >> 32); + var sx = x; + ix &= 0x7FFFFFFF; + var z: f64; + if (ix >= 0x44100000) { + if (isNaN(x)) return x; + z = atanhi3 + Ox1p_120f; + return builtin_copysign(z, sx); + } + var id: i32; + if (ix < 0x3FDC0000) { + if (ix < 0x3E400000) return x; + id = -1; + } else { + x = builtin_abs(x); + if (ix < 0x3FF30000) { + if (ix < 0x3FE60000) { + id = 0; + x = (2.0 * x - 1.0) / (2.0 + x); + } else { + id = 1; + x = (x - 1.0) / (x + 1.0); + } + } else { + if (ix < 0x40038000) { + id = 2; + x = (x - 1.5) / (1.0 + 1.5 * x); + } else { + id = 3; + x = -1.0 / x; + } + } + } + z = x * x; + var w = z * z; + var s1 = z * (aT0 + w * (aT2 + w * (aT4 + w * (aT6 + w * (aT8 + w * aT10))))); + var s2 = w * (aT1 + w * (aT3 + w * (aT5 + w * (aT7 + w * aT9)))); + var s3 = x * (s1 + s2); + if (id < 0) return x - s3; + switch (id) { + case 0: { z = atanhi0 - ((s3 - atanlo0) - x); break; } + case 1: { z = atanhi1 - ((s3 - atanlo1) - x); break; } + case 2: { z = atanhi2 - ((s3 - atanlo2) - x); break; } + case 3: { z = atanhi3 - ((s3 - atanlo3) - x); break; } + default: unreachable(); + } + return builtin_copysign(z, sx); + } + + export function atanh(x: f64): f64 { // see: musl/src/math/atanh.c + var u = reinterpret(x); + var e = u >> 52 & 0x7FF; + var y = builtin_abs(x); + if (e < 0x3FF - 1) { + if (e >= 0x3FF - 32) y = 0.5 * log1p(2 * y + 2 * y * y / (1 - y)); + } else { + y = 0.5 * log1p(2 * (y / (1 - y))); + } + return builtin_copysign(y, x); + } + + export function atan2(y: f64, x: f64): f64 { // see: musl/src/math/atan2.c and SUN COPYRIGHT NOTICE above + const pi_lo = reinterpret(0x3CA1A62633145C07); // 1.2246467991473531772E-16 + if (isNaN(x) || isNaN(y)) return x + y; + var u = reinterpret(x); + var ix = (u >> 32); + var lx = u; + u = reinterpret(y); + var iy = (u >> 32); + var ly = u; + if ((ix - 0x3FF00000 | lx) == 0) return atan(y); + var m = ((iy >> 31) & 1) | ((ix >> 30) & 2); + ix = ix & 0x7FFFFFFF; + iy = iy & 0x7FFFFFFF; + if ((iy | ly) == 0) { + switch (m) { + case 0: + case 1: return y; + case 2: return PI; + case 3: return -PI; + } + } + if ((ix | lx) == 0) return m & 1 ? -PI / 2 : PI / 2; + if (ix == 0x7FF00000) { + if (iy == 0x7FF00000) { + let t = m & 2 ? 3 * PI / 4 : PI / 4; + return m & 1 ? -t : t; + } else { + let t = m & 2 ? PI : 0; + return m & 1 ? -t : t; + } + } + var z: f64; + if (ix + (64 << 20) < iy || iy == 0x7FF00000) return m & 1 ? -PI / 2 : PI / 2; + if ((m & 2) && iy + (64 << 20) < ix) z = 0; + else z = atan(builtin_abs(y / x)); + switch (m) { + case 0: return z; + case 1: return -z; + case 2: return PI - (z - pi_lo); + case 3: return (z - pi_lo) - PI; + } + unreachable(); + return 0; + } + + export function cbrt(x: f64): f64 { // see: musl/src/math/cbrt.c and SUN COPYRIGHT NOTICE above + const + B1 = 715094163, + B2 = 696219795, + P0 = reinterpret(0x3FFE03E60F61E692), // 1.87595182427177009643 + P1 = reinterpret(0xBFFE28E092F02420), // -1.88497979543377169875 + P2 = reinterpret(0x3FF9F1604A49D6C2), // 1.621429720105354466140 + P3 = reinterpret(0xBFE844CBBEE751D9), // -0.758397934778766047437 + P4 = reinterpret(0x3FC2B000D4E4EDD7), // 0.145996192886612446982 + Ox1p54 = reinterpret(0x4350000000000000); // 0x1p54 + + var u = reinterpret(x); + var hx = (u >> 32) & 0x7FFFFFFF; + if (hx >= 0x7FF00000) return x + x; + if (hx < 0x00100000) { + u = reinterpret(x * Ox1p54); + hx = (u >> 32) & 0x7FFFFFFF; + if (hx == 0) return x; + hx = hx / 3 + B2; + } else { + hx = hx / 3 + B1; + } + u &= 1 << 63; + u |= hx << 32; + var t = reinterpret(u); + var r = (t * t) * (t / x); + t = t * ((P0 + r * (P1 + r * P2)) + ((r * r) * r) * (P3 + r * P4)); + t = reinterpret((reinterpret(t) + 0x80000000) & 0xFFFFFFFFC0000000); + var s = t * t; + r = x / s; + r = (r - t) / (2 * t + r); + t = t + t * r; + return t; + } + + // @ts-ignore: decorator + @inline + export function ceil(x: f64): f64 { + return builtin_ceil(x); + } + + export function clz32(x: f64): f64 { + if (!isFinite(x)) return 32; + /* + * Wasm (MVP) and JS have different approaches for double->int conversions. + * + * For emulate JS conversion behavior and avoid trapping from wasm we should modulate by MAX_INT + * our float-point arguments before actual convertion to integers. + */ + return builtin_clz(dtoi32(x)); + } + + export function cos(x: f64): f64 { // see: musl/src/math/cos.c + var u = reinterpret(x); + var ix = (u >> 32); + var sign = ix >> 31; + + ix &= 0x7FFFFFFF; + + // |x| ~< pi/4 + if (ix <= 0x3FE921FB) { + if (ix < 0x3E46A09E) { // |x| < 2**-27 * sqrt(2) + return 1.0; + } + return cos_kern(x, 0); + } + + // sin(Inf or NaN) is NaN + if (ix >= 0x7FF00000) return x - x; + + // argument reduction needed + var n = rempio2(x, u, sign); + var y0 = rempio2_y0; + var y1 = rempio2_y1; + + x = n & 1 ? sin_kern(y0, y1, 1) : cos_kern(y0, y1); + return (n + 1) & 2 ? -x : x; + } + + export function cosh(x: f64): f64 { // see: musl/src/math/cosh.c + var u = reinterpret(x); + u &= 0x7FFFFFFFFFFFFFFF; + x = reinterpret(u); + var w = (u >> 32); + var t: f64; + if (w < 0x3FE62E42) { + if (w < 0x3FF00000 - (26 << 20)) return 1; + t = expm1(x); + // return 1 + t * t / (2 * (1 + t)); + return 1 + t * t / (2 + 2 * t); + } + if (w < 0x40862E42) { + t = exp(x); + return 0.5 * (t + 1 / t); + } + t = expo2(x, 1); + return t; + } + + export function exp(x: f64): f64 { // see: musl/src/math/exp.c and SUN COPYRIGHT NOTICE above + if (ASC_SHRINK_LEVEL < 1) { + return exp_lut(x); + } else { + const + ln2hi = reinterpret(0x3FE62E42FEE00000), // 6.93147180369123816490e-01 + ln2lo = reinterpret(0x3DEA39EF35793C76), // 1.90821492927058770002e-10 + invln2 = reinterpret(0x3FF71547652B82FE), // 1.44269504088896338700e+00 + P1 = reinterpret(0x3FC555555555553E), // 1.66666666666666019037e-01 + P2 = reinterpret(0xBF66C16C16BEBD93), // -2.77777777770155933842e-03 + P3 = reinterpret(0x3F11566AAF25DE2C), // 6.61375632143793436117e-05 + P4 = reinterpret(0xBEBBBD41C5D26BF1), // -1.65339022054652515390e-06 + P5 = reinterpret(0x3E66376972BEA4D0), // 4.13813679705723846039e-08 + overflow = reinterpret(0x40862E42FEFA39EF), // 709.782712893383973096 + underflow = reinterpret(0xC0874910D52D3051), // -745.13321910194110842 + Ox1p1023 = reinterpret(0x7FE0000000000000); // 0x1p1023 + + let hx = (reinterpret(x) >> 32); + let sign_ = (hx >> 31); + hx &= 0x7FFFFFFF; + if (hx >= 0x4086232B) { + if (isNaN(x)) return x; + if (x > overflow) return x * Ox1p1023; + if (x < underflow) return 0; + } + let hi: f64, lo: f64 = 0; + let k = 0; + if (hx > 0x3FD62E42) { + if (hx >= 0x3FF0A2B2) { + k = (invln2 * x + builtin_copysign(0.5, x)); + } else { + k = 1 - (sign_ << 1); + } + hi = x - k * ln2hi; + lo = k * ln2lo; + x = hi - lo; + } else if (hx > 0x3E300000) { + hi = x; + } else return 1.0 + x; + let xs = x * x; + // var c = x - xp2 * (P1 + xp2 * (P2 + xp2 * (P3 + xp2 * (P4 + xp2 * P5)))); + let xq = xs * xs; + let c = x - (xs * P1 + xq * ((P2 + xs * P3) + xq * (P4 + xs * P5))); + let y = 1.0 + (x * c / (2 - c) - lo + hi); + return k == 0 ? y : scalbn(y, k); + } + } + + export function exp2(x: f64): f64 { + return exp2_lut(x); + } + + export function expm1(x: f64): f64 { // see: musl/src/math/expm1.c and SUN COPYRIGHT NOTICE above + const + o_threshold = reinterpret(0x40862E42FEFA39EF), // 7.09782712893383973096e+02 + ln2_hi = reinterpret(0x3FE62E42FEE00000), // 6.93147180369123816490e-01 + ln2_lo = reinterpret(0x3DEA39EF35793C76), // 1.90821492927058770002e-10 + invln2 = reinterpret(0x3FF71547652B82FE), // 1.44269504088896338700e+00 + Q1 = reinterpret(0xBFA11111111110F4), // -3.33333333333331316428e-02 + Q2 = reinterpret(0x3F5A01A019FE5585), // 1.58730158725481460165e-03 + Q3 = reinterpret(0xBF14CE199EAADBB7), // -7.93650757867487942473e-05 + Q4 = reinterpret(0x3ED0CFCA86E65239), // 4.00821782732936239552e-06 + Q5 = reinterpret(0xBE8AFDB76E09C32D), // -2.01099218183624371326e-07 + Ox1p1023 = reinterpret(0x7FE0000000000000); // 0x1p1023 + + var u = reinterpret(x); + var hx = (u >> 32 & 0x7FFFFFFF); + var k = 0, sign_ = (u >> 63); + if (hx >= 0x4043687A) { + if (isNaN(x)) return x; + if (sign_) return -1; + if (x > o_threshold) return x * Ox1p1023; + } + var c = 0.0, t: f64; + if (hx > 0x3FD62E42) { + k = select( + 1 - (sign_ << 1), + (invln2 * x + builtin_copysign(0.5, x)), + hx < 0x3FF0A2B2 + ); + t = k; + let hi = x - t * ln2_hi; + let lo = t * ln2_lo; + x = hi - lo; + c = (hi - x) - lo; + } else if (hx < 0x3C900000) return x; + var hfx = 0.5 * x; + var hxs = x * hfx; + // var r1 = 1.0 + hxs * (Q1 + hxs * (Q2 + hxs * (Q3 + hxs * (Q4 + hxs * Q5)))); + var hxq = hxs * hxs; + var r1 = (1.0 + hxs * Q1) + hxq * ((Q2 + hxs * Q3) + hxq * (Q4 + hxs * Q5)); + t = 3.0 - r1 * hfx; + var e = hxs * ((r1 - t) / (6.0 - x * t)); + if (k == 0) return x - (x * e - hxs); + e = x * (e - c) - c; + e -= hxs; + if (k == -1) return 0.5 * (x - e) - 0.5; + if (k == 1) { + if (x < -0.25) return -2.0 * (e - (x + 0.5)); + return 1.0 + 2.0 * (x - e); + } + u = (0x3FF + k) << 52; + var twopk = reinterpret(u); + var y: f64; + if (k < 0 || k > 56) { + y = x - e + 1.0; + if (k == 1024) y = y * 2.0 * Ox1p1023; + else y = y * twopk; + return y - 1.0; + } + u = (0x3FF - k) << 52; + y = reinterpret(u); + if (k < 20) y = (1 - y) - e; + else y = 1 - (e + y); + return (x + y) * twopk; + } + + // @ts-ignore: decorator + @inline + export function floor(x: f64): f64 { + return builtin_floor(x); + } + + // @ts-ignore: decorator + @inline + export function fround(x: f64): f64 { + return x; + } + + export function hypot(x: f64, y: f64): f64 { // see: musl/src/math/hypot.c + const + SPLIT = reinterpret(0x41A0000000000000) + 1, // 0x1p27 + 1 + Ox1p700 = reinterpret(0x6BB0000000000000), + Ox1p_700 = reinterpret(0x1430000000000000); + + var ux = reinterpret(x); + var uy = reinterpret(y); + ux &= 0x7FFFFFFFFFFFFFFF; + uy &= 0x7FFFFFFFFFFFFFFF; + if (ux < uy) { + let ut = ux; + ux = uy; + uy = ut; + } + var ex = (ux >> 52); + var ey = (uy >> 52); + y = reinterpret(uy); + if (ey == 0x7FF) return y; + x = reinterpret(ux); + if (ex == 0x7FF || uy == 0) return x; + if (ex - ey > 64) return x + y; + var z = 1.0; + if (ex > 0x3FF + 510) { + z = Ox1p700; + x *= Ox1p_700; + y *= Ox1p_700; + } else if (ey < 0x3FF - 450) { + z = Ox1p_700; + x *= Ox1p700; + y *= Ox1p700; + } + var c = x * SPLIT; + var h = x - c + c; + var l = x - h; + var hx = x * x; + var lx = h * h - hx + (2 * h + l) * l; + c = y * SPLIT; + h = y - c + c; + l = y - h; + var hy = y * y; + var ly = h * h - hy + (2 * h + l) * l; + return z * builtin_sqrt(ly + lx + hy + hx); + } + + export function imul(x: f64, y: f64): f64 { + /* + * Wasm (MVP) and JS have different approaches for double->int conversions. + * + * For emulate JS conversion behavior and avoid trapping from wasm we should modulate by MAX_INT + * our float-point arguments before actual convertion to integers. + */ + if (!isFinite(x + y)) return 0; + return dtoi32(x) * dtoi32(y); + } + + export function log(x: f64): f64 { // see: musl/src/math/log.c and SUN COPYRIGHT NOTICE above + if (ASC_SHRINK_LEVEL < 1) { + return log_lut(x); + } else { + const + ln2_hi = reinterpret(0x3FE62E42FEE00000), // 6.93147180369123816490e-01 + ln2_lo = reinterpret(0x3DEA39EF35793C76), // 1.90821492927058770002e-10 + Lg1 = reinterpret(0x3FE5555555555593), // 6.666666666666735130e-01 + Lg2 = reinterpret(0x3FD999999997FA04), // 3.999999999940941908e-01 + Lg3 = reinterpret(0x3FD2492494229359), // 2.857142874366239149e-01 + Lg4 = reinterpret(0x3FCC71C51D8E78AF), // 2.222219843214978396e-01 + Lg5 = reinterpret(0x3FC7466496CB03DE), // 1.818357216161805012e-01 + Lg6 = reinterpret(0x3FC39A09D078C69F), // 1.531383769920937332e-01 + Lg7 = reinterpret(0x3FC2F112DF3E5244), // 1.479819860511658591e-01 + Ox1p54 = reinterpret(0x4350000000000000); // 0x1p54 + + let u = reinterpret(x); + let hx = (u >> 32); + let k = 0; + if (hx < 0x00100000 || (hx >> 31)) { + if (u << 1 == 0) return -1 / (x * x); + if (hx >> 31) return (x - x) / 0.0; + k -= 54; + x *= Ox1p54; + u = reinterpret(x); + hx = (u >> 32); + } else if (hx >= 0x7FF00000) { + return x; + } else if (hx == 0x3FF00000 && u << 32 == 0) { + return 0; + } + hx += 0x3FF00000 - 0x3FE6A09E; + k += (hx >> 20) - 0x3FF; + hx = (hx & 0x000FFFFF) + 0x3FE6A09E; + u = hx << 32 | (u & 0xFFFFFFFF); + x = reinterpret(u); + let f = x - 1.0; + let hfsq = 0.5 * f * f; + let s = f / (2.0 + f); + let z = s * s; + let w = z * z; + let t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + let t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + let r = t2 + t1; + let dk = k; + return s * (hfsq + r) + dk * ln2_lo - hfsq + f + dk * ln2_hi; + } + } + + export function log10(x: f64): f64 { // see: musl/src/math/log10.c and SUN COPYRIGHT NOTICE above + const + ivln10hi = reinterpret(0x3FDBCB7B15200000), // 4.34294481878168880939e-01 + ivln10lo = reinterpret(0x3DBB9438CA9AADD5), // 2.50829467116452752298e-11 + log10_2hi = reinterpret(0x3FD34413509F6000), // 3.01029995663611771306e-01 + log10_2lo = reinterpret(0x3D59FEF311F12B36), // 3.69423907715893078616e-13 + Lg1 = reinterpret(0x3FE5555555555593), // 6.666666666666735130e-01 + Lg2 = reinterpret(0x3FD999999997FA04), // 3.999999999940941908e-01 + Lg3 = reinterpret(0x3FD2492494229359), // 2.857142874366239149e-01 + Lg4 = reinterpret(0x3FCC71C51D8E78AF), // 2.222219843214978396e-01 + Lg5 = reinterpret(0x3FC7466496CB03DE), // 1.818357216161805012e-01 + Lg6 = reinterpret(0x3FC39A09D078C69F), // 1.531383769920937332e-01 + Lg7 = reinterpret(0x3FC2F112DF3E5244), // 1.479819860511658591e-01 + Ox1p54 = reinterpret(0x4350000000000000); // 0x1p54 + + var u = reinterpret(x); + var hx = (u >> 32); + var k = 0; + if (hx < 0x00100000 || (hx >> 31)) { + if (u << 1 == 0) return -1 / (x * x); + if (hx >> 31) return (x - x) / 0.0; + k -= 54; + x *= Ox1p54; + u = reinterpret(x); + hx = (u >> 32); + } else if (hx >= 0x7FF00000) { + return x; + } else if (hx == 0x3FF00000 && u << 32 == 0) { + return 0; + } + hx += 0x3FF00000 - 0x3FE6A09E; + k += (hx >> 20) - 0x3FF; + hx = (hx & 0x000FFFFF) + 0x3FE6A09E; + u = hx << 32 | (u & 0xFFFFFFFF); + x = reinterpret(u); + var f = x - 1.0; + var hfsq = 0.5 * f * f; + var s = f / (2.0 + f); + var z = s * s; + var w = z * z; + var t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + var t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + var r = t2 + t1; + var hi = f - hfsq; + u = reinterpret(hi); + u &= 0xFFFFFFFF00000000; + hi = reinterpret(u); + var lo = f - hi - hfsq + s * (hfsq + r); + var val_hi = hi * ivln10hi; + var dk = k; + var y = dk * log10_2hi; + var val_lo = dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi; + w = y + val_hi; + val_lo += (y - w) + val_hi; + return val_lo + w; + } + + export function log1p(x: f64): f64 { // see: musl/src/math/log1p.c and SUN COPYRIGHT NOTICE above + const + ln2_hi = reinterpret(0x3FE62E42FEE00000), // 6.93147180369123816490e-01 + ln2_lo = reinterpret(0x3DEA39EF35793C76), // 1.90821492927058770002e-10 + Lg1 = reinterpret(0x3FE5555555555593), // 6.666666666666735130e-01 + Lg2 = reinterpret(0x3FD999999997FA04), // 3.999999999940941908e-01 + Lg3 = reinterpret(0x3FD2492494229359), // 2.857142874366239149e-01 + Lg4 = reinterpret(0x3FCC71C51D8E78AF), // 2.222219843214978396e-01 + Lg5 = reinterpret(0x3FC7466496CB03DE), // 1.818357216161805012e-01 + Lg6 = reinterpret(0x3FC39A09D078C69F), // 1.531383769920937332e-01 + Lg7 = reinterpret(0x3FC2F112DF3E5244); // 1.479819860511658591e-01 + + var u = reinterpret(x); + var hx = (u >> 32); + var k = 1; + var c = 0.0, f = 0.0; + if (hx < 0x3FDA827A || (hx >> 31)) { + if (hx >= 0xBFF00000) { + if (x == -1) return x / 0.0; + return (x - x) / 0.0; + } + if (hx << 1 < 0x3CA00000 << 1) return x; + if (hx <= 0xBFD2BEC4) { + k = 0; + c = 0; + f = x; + } + } else if (hx >= 0x7FF00000) return x; + if (k) { + u = reinterpret(1 + x); + let hu = (u >> 32); + hu += 0x3FF00000 - 0x3FE6A09E; + k = (hu >> 20) - 0x3FF; + if (k < 54) { + let uf = reinterpret(u); + c = k >= 2 ? 1 - (uf - x) : x - (uf - 1); + c /= uf; + } else c = 0; + hu = (hu & 0x000FFFFF) + 0x3FE6A09E; + u = hu << 32 | (u & 0xFFFFFFFF); + f = reinterpret(u) - 1; + } + var hfsq = 0.5 * f * f; + var s = f / (2.0 + f); + var z = s * s; + var w = z * z; + var t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + var t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + var r = t2 + t1; + var dk = k; + return s * (hfsq + r) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; + } + + export function log2(x: f64): f64 { // see: musl/src/math/log2.c and SUN COPYRIGHT NOTICE above + if (ASC_SHRINK_LEVEL < 1) { + return log2_lut(x); + } else { + const + ivln2hi = reinterpret(0x3FF7154765200000), // 1.44269504072144627571e+00 + ivln2lo = reinterpret(0x3DE705FC2EEFA200), // 1.67517131648865118353e-10 + Lg1 = reinterpret(0x3FE5555555555593), // 6.666666666666735130e-01 + Lg2 = reinterpret(0x3FD999999997FA04), // 3.999999999940941908e-01 + Lg3 = reinterpret(0x3FD2492494229359), // 2.857142874366239149e-01 + Lg4 = reinterpret(0x3FCC71C51D8E78AF), // 2.222219843214978396e-01 + Lg5 = reinterpret(0x3FC7466496CB03DE), // 1.818357216161805012e-01 + Lg6 = reinterpret(0x3FC39A09D078C69F), // 1.531383769920937332e-01 + Lg7 = reinterpret(0x3FC2F112DF3E5244), // 1.479819860511658591e-01 + Ox1p54 = reinterpret(0x4350000000000000); // 1p54 + + let u = reinterpret(x); + let hx = (u >> 32); + let k = 0; + if (hx < 0x00100000 || (hx >> 31)) { + if (u << 1 == 0) return -1 / (x * x); + if (hx >> 31) return (x - x) / 0.0; + k -= 54; + x *= Ox1p54; + u = reinterpret(x); + hx = (u >> 32); + } else if (hx >= 0x7FF00000) { + return x; + } else if (hx == 0x3FF00000 && u << 32 == 0) { + return 0; + } + hx += 0x3FF00000 - 0x3FE6A09E; + k += (hx >> 20) - 0x3FF; + hx = (hx & 0x000FFFFF) + 0x3FE6A09E; + u = hx << 32 | (u & 0xFFFFFFFF); + x = reinterpret(u); + let f = x - 1.0; + let hfsq = 0.5 * f * f; + let s = f / (2.0 + f); + let z = s * s; + let w = z * z; + let t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + let t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + let r = t2 + t1; + let hi = f - hfsq; + u = reinterpret(hi); + u &= 0xFFFFFFFF00000000; + hi = reinterpret(u); + let lo = f - hi - hfsq + s * (hfsq + r); + let val_hi = hi * ivln2hi; + let val_lo = (lo + hi) * ivln2lo + lo * ivln2hi; + let y = k; + w = y + val_hi; + val_lo += (y - w) + val_hi; + val_hi = w; + return val_lo + val_hi; + } + } + + // @ts-ignore: decorator + @inline + export function max(value1: f64, value2: f64): f64 { + return builtin_max(value1, value2); + } + + // @ts-ignore: decorator + @inline + export function min(value1: f64, value2: f64): f64 { + return builtin_min(value1, value2); + } + + export function pow(x: f64, y: f64): f64 { // see: musl/src/math/pow.c and SUN COPYRIGHT NOTICE above + // TODO: remove this fast pathes after introduced own mid-end IR with "stdlib call simplify" transforms + if (builtin_abs(y) <= 2) { + if (y == 2.0) return x * x; + if (y == 0.5) { + return select( + builtin_abs(builtin_sqrt(x)), + Infinity, + x != -Infinity + ); + } + if (y == -1.0) return 1 / x; + if (y == 1.0) return x; + if (y == 0.0) return 1.0; + } + if (ASC_SHRINK_LEVEL < 1) { + return pow_lut(x, y); + } else { + const + dp_h1 = reinterpret(0x3FE2B80340000000), // 5.84962487220764160156e-01 + dp_l1 = reinterpret(0x3E4CFDEB43CFD006), // 1.35003920212974897128e-08 + two53 = reinterpret(0x4340000000000000), // 9007199254740992.0 + huge = reinterpret(0x7E37E43C8800759C), // 1e+300 + tiny = reinterpret(0x01A56E1FC2F8F359), // 1e-300 + L1 = reinterpret(0x3FE3333333333303), // 5.99999999999994648725e-01 + L2 = reinterpret(0x3FDB6DB6DB6FABFF), // 4.28571428578550184252e-01 + L3 = reinterpret(0x3FD55555518F264D), // 3.33333329818377432918e-01 + L4 = reinterpret(0x3FD17460A91D4101), // 2.72728123808534006489e-01 + L5 = reinterpret(0x3FCD864A93C9DB65), // 2.30660745775561754067e-01 + L6 = reinterpret(0x3FCA7E284A454EEF), // 2.06975017800338417784e-01 + P1 = reinterpret(0x3FC555555555553E), // 1.66666666666666019037e-01 + P2 = reinterpret(0xBF66C16C16BEBD93), // -2.77777777770155933842e-03 + P3 = reinterpret(0x3F11566AAF25DE2C), // 6.61375632143793436117e-05 + P4 = reinterpret(0xBEBBBD41C5D26BF1), // -1.65339022054652515390e-06 + P5 = reinterpret(0x3E66376972BEA4D0), // 4.13813679705723846039e-08 + lg2 = reinterpret(0x3FE62E42FEFA39EF), // 6.93147180559945286227e-01 + lg2_h = reinterpret(0x3FE62E4300000000), // 6.93147182464599609375e-01 + lg2_l = reinterpret(0xBE205C610CA86C39), // -1.90465429995776804525e-09 + ovt = reinterpret(0x3C971547652B82FE), // 8.0085662595372944372e-017 + cp = reinterpret(0x3FEEC709DC3A03FD), // 9.61796693925975554329e-01 + cp_h = reinterpret(0x3FEEC709E0000000), // 9.61796700954437255859e-01 + cp_l = reinterpret(0xBE3E2FE0145B01F5), // -7.02846165095275826516e-09 + ivln2 = reinterpret(0x3FF71547652B82FE), // 1.44269504088896338700e+00 + ivln2_h = reinterpret(0x3FF7154760000000), // 1.44269502162933349609e+00 + ivln2_l = reinterpret(0x3E54AE0BF85DDF44), // 1.92596299112661746887e-08 + inv3 = reinterpret(0x3FD5555555555555); // 0.3333333333333333333333 + + let u_ = reinterpret(x); + let hx = (u_ >> 32); + let lx = u_; + u_ = reinterpret(y); + let hy = (u_ >> 32); + let ly = u_; + let ix = hx & 0x7FFFFFFF; + let iy = hy & 0x7FFFFFFF; + if ((iy | ly) == 0) return 1.0; // x**0 = 1, even if x is NaN + // if (hx == 0x3FF00000 && lx == 0) return 1.0; // C: 1**y = 1, even if y is NaN, JS: NaN + if ( // NaN if either arg is NaN + ix > 0x7FF00000 || (ix == 0x7FF00000 && lx != 0) || + iy > 0x7FF00000 || (iy == 0x7FF00000 && ly != 0) + ) return x + y; + let yisint = 0, k: i32; + if (hx < 0) { + if (iy >= 0x43400000) yisint = 2; + else if (iy >= 0x3FF00000) { + k = (iy >> 20) - 0x3FF; + let offset = select(52, 20, k > 20) - k; + let Ly = select(ly, iy, k > 20); + let jj = Ly >> offset; + if ((jj << offset) == Ly) yisint = 2 - (jj & 1); + } + } + if (ly == 0) { + if (iy == 0x7FF00000) { // y is +-inf + if (((ix - 0x3FF00000) | lx) == 0) return NaN; // C: (-1)**+-inf is 1, JS: NaN + else if (ix >= 0x3FF00000) return hy >= 0 ? y : 0.0; // (|x|>1)**+-inf = inf,0 + else return hy >= 0 ? 0.0 : -y; // (|x|<1)**+-inf = 0,inf + } + if (iy == 0x3FF00000) { + if (hy >= 0) return x; + return 1 / x; + } + if (hy == 0x40000000) return x * x; + if (hy == 0x3FE00000) { + if (hx >= 0) return builtin_sqrt(x); + } + } + let ax = builtin_abs(x), z: f64; + if (lx == 0) { + if (ix == 0 || ix == 0x7FF00000 || ix == 0x3FF00000) { + z = ax; + if (hy < 0) z = 1.0 / z; + if (hx < 0) { + if (((ix - 0x3FF00000) | yisint) == 0) { + let d = z - z; + z = d / d; + } else if (yisint == 1) z = -z; + } + return z; + } + } + let s = 1.0; + if (hx < 0) { + if (yisint == 0) { + let d = x - x; + return d / d; + } + if (yisint == 1) s = -1.0; + } + let t1: f64, t2: f64, p_h: f64, p_l: f64, r: f64, t: f64, u: f64, v: f64, w: f64; + let j: i32, n: i32; + if (iy > 0x41E00000) { + if (iy > 0x43F00000) { + if (ix <= 0x3FEFFFFF) return hy < 0 ? huge * huge : tiny * tiny; + if (ix >= 0x3FF00000) return hy > 0 ? huge * huge : tiny * tiny; + } + if (ix < 0x3FEFFFFF) return hy < 0 ? s * huge * huge : s * tiny * tiny; + if (ix > 0x3FF00000) return hy > 0 ? s * huge * huge : s * tiny * tiny; + t = ax - 1.0; + w = (t * t) * (0.5 - t * (inv3 - t * 0.25)); + u = ivln2_h * t; + v = t * ivln2_l - w * ivln2; + t1 = u + v; + t1 = reinterpret(reinterpret(t1) & 0xFFFFFFFF00000000); + t2 = v - (t1 - u); + } else { + let ss: f64, s2: f64, s_h: f64, s_l: f64, t_h: f64, t_l: f64; + n = 0; + if (ix < 0x00100000) { + ax *= two53; + n -= 53; + ix = (reinterpret(ax) >> 32); + } + n += (ix >> 20) - 0x3FF; + j = ix & 0x000FFFFF; + ix = j | 0x3FF00000; + if (j <= 0x3988E) k = 0; + else if (j < 0xBB67A) k = 1; + else { + k = 0; + n += 1; + ix -= 0x00100000; + } + ax = reinterpret(reinterpret(ax) & 0xFFFFFFFF | (ix << 32)); + let bp = select(1.5, 1.0, k); // k ? 1.5 : 1.0 + u = ax - bp; + v = 1.0 / (ax + bp); + ss = u * v; + s_h = ss; + s_h = reinterpret(reinterpret(s_h) & 0xFFFFFFFF00000000); + t_h = reinterpret((((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18)) << 32); + t_l = ax - (t_h - bp); + s_l = v * ((u - s_h * t_h) - s_h * t_l); + s2 = ss * ss; + r = s2 * s2 * (L1 + s2 * (L2 + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6))))); + r += s_l * (s_h + ss); + s2 = s_h * s_h; + t_h = 3.0 + s2 + r; + t_h = reinterpret(reinterpret(t_h) & 0xFFFFFFFF00000000); + t_l = r - ((t_h - 3.0) - s2); + u = s_h * t_h; + v = s_l * t_h + t_l * ss; + p_h = u + v; + p_h = reinterpret(reinterpret(p_h) & 0xFFFFFFFF00000000); + p_l = v - (p_h - u); + let z_h = cp_h * p_h; + let dp_l = select(dp_l1, 0.0, k); + let z_l = cp_l * p_h + p_l * cp + dp_l; + t = n; + let dp_h = select(dp_h1, 0.0, k); + t1 = ((z_h + z_l) + dp_h) + t; + t1 = reinterpret(reinterpret(t1) & 0xFFFFFFFF00000000); + t2 = z_l - (((t1 - t) - dp_h) - z_h); + } + let y1 = y; + y1 = reinterpret(reinterpret(y1) & 0xFFFFFFFF00000000); + p_l = (y - y1) * t1 + y * t2; + p_h = y1 * t1; + z = p_l + p_h; + u_ = reinterpret(z); + j = (u_ >> 32); + let i = u_; + if (j >= 0x40900000) { + if (((j - 0x40900000) | i) != 0) return s * huge * huge; + if (p_l + ovt > z - p_h) return s * huge * huge; + } else if ((j & 0x7FFFFFFF) >= 0x4090CC00) { + if (((j - 0xC090CC00) | i) != 0) return s * tiny * tiny; + if (p_l <= z - p_h) return s * tiny * tiny; + } + i = j & 0x7FFFFFFF; + k = (i >> 20) - 0x3FF; + n = 0; + if (i > 0x3FE00000) { + n = j + (0x00100000 >> (k + 1)); + k = ((n & 0x7FFFFFFF) >> 20) - 0x3FF; + t = 0.0; + t = reinterpret((n & ~(0x000FFFFF >> k)) << 32); + n = ((n & 0x000FFFFF) | 0x00100000) >> (20 - k); + if (j < 0) n = -n; + p_h -= t; + } + t = p_l + p_h; + t = reinterpret(reinterpret(t) & 0xFFFFFFFF00000000); + u = t * lg2_h; + v = (p_l - (t - p_h)) * lg2 + t * lg2_l; + z = u + v; + w = v - (z - u); + t = z * z; + t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + r = (z * t1) / (t1 - 2.0) - (w + z * w); + z = 1.0 - (r - z); + j = (reinterpret(z) >> 32); + j += n << 20; + if ((j >> 20) <= 0) z = scalbn(z, n); + else z = reinterpret(reinterpret(z) & 0xFFFFFFFF | (j << 32)); + return s * z; + } + } + + export function seedRandom(value: i64): void { + // Instead zero seed use golden ratio: + // phi = (1 + sqrt(5)) / 2 + // trunc(2^64 / phi) = 0x9e3779b97f4a7c15 + if (value == 0) value = 0x9e3779b97f4a7c15; + random_state0_64 = murmurHash3(value); + random_state1_64 = murmurHash3(~random_state0_64); + random_state0_32 = splitMix32(value); + random_state1_32 = splitMix32(random_state0_32); + random_seeded = true; + } + + export function random(): f64 { // see: v8/src/base/utils/random-number-generator.cc + if (!random_seeded) seedRandom(reinterpret(seed())); + var s1 = random_state0_64; + var s0 = random_state1_64; + random_state0_64 = s0; + s1 ^= s1 << 23; + s1 ^= s1 >> 17; + s1 ^= s0; + s1 ^= s0 >> 26; + random_state1_64 = s1; + var r = (s0 >> 12) | 0x3FF0000000000000; + return reinterpret(r) - 1; + } + + // @ts-ignore: decorator + @inline + export function round(x: f64): f64 { + let roundUp = builtin_ceil(x); + return select(roundUp, roundUp - 1.0, roundUp - 0.5 <= x); + } + + // @ts-ignore: decorator + @inline + export function sign(x: f64): f64 { + if (ASC_SHRINK_LEVEL > 0) { + return builtin_abs(x) > 0 ? builtin_copysign(1, x) : x; + } else { + return x > 0 ? 1 : x < 0 ? -1 : x; + } + } + + // @ts-ignore: decorator + @inline + export function signbit(x: f64): bool { + return (reinterpret(x) >>> 63); + } + + export function sin(x: f64): f64 { // see: musl/src/math/sin.c + var u = reinterpret(x); + var ix = (u >> 32); + var sign = ix >> 31; + + ix &= 0x7FFFFFFF; + + // |x| ~< pi/4 + if (ix <= 0x3FE921FB) { + if (ix < 0x3E500000) { // |x| < 2**-26 + return x; + } + return sin_kern(x, 0.0, 0); + } + + // sin(Inf or NaN) is NaN + if (ix >= 0x7FF00000) return x - x; + + // argument reduction needed + var n = rempio2(x, u, sign); + var y0 = rempio2_y0; + var y1 = rempio2_y1; + + x = n & 1 ? cos_kern(y0, y1) : sin_kern(y0, y1, 1); + return n & 2 ? -x : x; + } + + export function sinh(x: f64): f64 { // see: musl/src/math/sinh.c + var u = reinterpret(x) & 0x7FFFFFFFFFFFFFFF; + var a = reinterpret(u); + var w = (u >> 32); + var h = builtin_copysign(0.5, x); + if (w < 0x40862E42) { + let t = expm1(a); + if (w < 0x3FF00000) { + if (w < 0x3FF00000 - (26 << 20)) return x; + return h * (2 * t - t * t / (t + 1)); + } + return h * (t + t / (t + 1)); + } + return expo2(a, 2 * h); + } + + // @ts-ignore: decorator + @inline + export function sqrt(x: f64): f64 { + return builtin_sqrt(x); + } + + export function tan(x: f64): f64 { // see: musl/src/math/tan.c + var u = reinterpret(x); + var ix = (u >> 32); + var sign = ix >>> 31; + + ix &= 0x7FFFFFFF; + + // |x| ~< pi/4 + if (ix <= 0x3FE921FB) { + if (ix < 0x3E400000) { // |x| < 2**-27 + return x; + } + return tan_kern(x, 0.0, 1); + } + + // tan(Inf or NaN) is NaN + if (ix >= 0x7FF00000) return x - x; + + var n = rempio2(x, u, sign); + return tan_kern(rempio2_y0, rempio2_y1, 1 - ((n & 1) << 1)); + } + + export function tanh(x: f64): f64 { // see: musl/src/math/tanh.c + var u = reinterpret(x); + u &= 0x7FFFFFFFFFFFFFFF; + var y = reinterpret(u); + var w = (u >> 32); + var t: f64; + if (w > 0x3FE193EA) { + if (w > 0x40340000) { + t = 1 - 0 / y; + } else { + t = expm1(2 * y); + t = 1 - 2 / (t + 2); + } + } else if (w > 0x3FD058AE) { + t = expm1(2 * y); + t = t / (t + 2); + } else if (w >= 0x00100000) { + t = expm1(-2 * y); + t = -t / (t + 2); + } else t = y; + return builtin_copysign(t, x); + } + + // @ts-ignore: decorator + @inline + export function trunc(x: f64): f64 { + return builtin_trunc(x); + } + + export function scalbn(x: f64, n: i32): f64 { // see: https://git.musl-libc.org/cgit/musl/tree/src/math/scalbn.c + const + Ox1p53 = reinterpret(0x4340000000000000), + Ox1p1023 = reinterpret(0x7FE0000000000000), + Ox1p_1022 = reinterpret(0x0010000000000000); + + var y = x; + if (n > 1023) { + y *= Ox1p1023; + n -= 1023; + if (n > 1023) { + y *= Ox1p1023; + n = builtin_min(n - 1023, 1023); + } + } else if (n < -1022) { + // make sure final n < -53 to avoid double + // rounding in the subnormal range + y *= Ox1p_1022 * Ox1p53; + n += 1022 - 53; + if (n < -1022) { + y *= Ox1p_1022 * Ox1p53; + n = builtin_max(n + 1022 - 53, -1022); + } + } + return y * reinterpret((0x3FF + n) << 52); + } + + export function mod(x: f64, y: f64): f64 { // see: musl/src/math/fmod.c + if (builtin_abs(y) == 1.0) { + // x % 1, x % -1 ==> sign(x) * abs(x - 1.0 * trunc(x / 1.0)) + // TODO: move this rule to compiler's optimization pass. + // It could be apply for any x % C_pot, where "C_pot" is pow of two const. + return builtin_copysign(x - builtin_trunc(x), x); + } + var ux = reinterpret(x); + var uy = reinterpret(y); + var ex = (ux >> 52 & 0x7FF); + var ey = (uy >> 52 & 0x7FF); + var sx = ux >> 63; + var uy1 = uy << 1; + if (uy1 == 0 || ex == 0x7FF || isNaN(y)) { + let m = x * y; + return m / m; + } + var ux1 = ux << 1; + if (ux1 <= uy1) { + return x * f64(ux1 != uy1); + } + if (!ex) { + ex -= builtin_clz(ux << 12); + ux <<= 1 - ex; + } else { + ux &= -1 >> 12; + ux |= 1 << 52; + } + if (!ey) { + ey -= builtin_clz(uy << 12); + uy <<= 1 - ey; + } else { + uy &= -1 >> 12; + uy |= 1 << 52; + } + while (ex > ey) { + if (ux >= uy) { + if (ux == uy) return 0 * x; + ux -= uy; + } + ux <<= 1; + --ex; + } + if (ux >= uy) { + if (ux == uy) return 0 * x; + ux -= uy; + } + // for (; !(ux >> 52); ux <<= 1) --ex; + var shift = builtin_clz(ux << 11); + ex -= shift; + ux <<= shift; + if (ex > 0) { + ux -= 1 << 52; + ux |= ex << 52; + } else { + ux >>= -ex + 1; + } + return reinterpret(ux | (sx << 63)); + } + + export function rem(x: f64, y: f64): f64 { // see: musl/src/math/remquo.c + var ux = reinterpret(x); + var uy = reinterpret(y); + var ex = (ux >> 52 & 0x7FF); + var ey = (uy >> 52 & 0x7FF); + var sx = (ux >> 63); + if (uy << 1 == 0 || ex == 0x7FF || isNaN(y)) { + let m = x * y; + return m / m; + } + if (ux << 1 == 0) return x; + var uxi = ux; + if (!ex) { + ex -= builtin_clz(uxi << 12); + uxi <<= 1 - ex; + } else { + uxi &= -1 >> 12; + uxi |= 1 << 52; + } + if (!ey) { + ey -= builtin_clz(uy << 12); + uy <<= 1 - ey; + } else { + uy &= -1 >> 12; + uy |= 1 << 52; + } + var q: u32 = 0; + do { + if (ex < ey) { + if (ex + 1 == ey) break; // goto end + return x; + } + while (ex > ey) { + if (uxi >= uy) { + uxi -= uy; + ++q; + } + uxi <<= 1; + q <<= 1; + --ex; + } + if (uxi >= uy) { + uxi -= uy; + ++q; + } + if (uxi == 0) ex = -60; + else { + let shift = builtin_clz(uxi << 11); + ex -= shift; + uxi <<= shift; + } + break; + } while (false); + // end: + if (ex > 0) { + uxi -= 1 << 52; + uxi |= ex << 52; + } else { + uxi >>= -ex + 1; + } + x = reinterpret(uxi); + y = builtin_abs(y); + var x2 = x + x; + if (ex == ey || (ex + 1 == ey && (x2 > y || (x2 == y && (q & 1))))) { + x -= y; + // ++q; + } + return sx ? -x : x; + } + + export function sincos(x: f64): void { // see: musl/tree/src/math/sincos.c + var u = reinterpret(x); + var ix = (u >> 32); + var sign = ix >> 31; + ix &= 0x7FFFFFFF; + + if (ix <= 0x3FE921FB) { // |x| ~<= \u03C0/4 + if (ix < 0x3E46A09E) { // if |x| < 2**-27 * sqrt(2) + sincos_sin = x; + sincos_cos = 1; + return; + } + sincos_sin = sin_kern(x, 0, 0); + sincos_cos = cos_kern(x, 0); + return; + } + // sin(Inf or NaN) is NaN + if (ix >= 0x7F800000) { + let xx = x - x; + sincos_sin = xx; + sincos_cos = xx; + return; + } + // general argument reduction needed + var n = rempio2(x, u, sign); + var y0 = rempio2_y0; + var y1 = rempio2_y1; + var s = sin_kern(y0, y1, 1); + var c = cos_kern(y0, y1); + var sin = s, cos = c; + if (n & 1) { + sin = c; + cos = -s; + } + if (n & 2) { + sin = -sin; + cos = -cos; + } + sincos_sin = sin; + sincos_cos = cos; + } +} + +// @ts-ignore: decorator +@lazy var rempio2f_y: f64; + +// @ts-ignore: decorator +@lazy @inline const PIO2F_TABLE = memory.data([ + 0xA2F9836E4E441529, + 0xFC2757D1F534DDC0, + 0xDB6295993C439041, + 0xFE5163ABDEBBC561 +]); + +function Rf(z: f32): f32 { // Rational approximation of (asin(x)-x)/x^3 + const // see: musl/src/math/asinf.c and SUN COPYRIGHT NOTICE above + pS0 = reinterpret(0x3E2AAA75), // 1.6666586697e-01f + pS1 = reinterpret(0xBD2F13BA), // -4.2743422091e-02f + pS2 = reinterpret(0xBC0DD36B), // -8.6563630030e-03f + qS1 = reinterpret(0xBF34E5AE); // -7.0662963390e-01f + + var p = z * (pS0 + z * (pS1 + z * pS2)); + var q: f32 = 1 + z * qS1; + return p / q; +} + +// @ts-ignore: decorator +@inline +function expo2f(x: f32, sign: f32): f32 { // exp(x)/2 for x >= log(DBL_MAX) + const // see: musl/src/math/__expo2f.c + k = 235, + kln2 = reinterpret(0x4322E3BC); // 0x1.45c778p+7f + var scale = reinterpret((0x7F + (k >> 1)) << 23); + // in directed rounding correct sign before rounding or overflow is important + return NativeMathf.exp(x - kln2) * (sign * scale) * scale; +} + +// @ts-ignore: decorator +@inline +function pio2f_large_quot(x: f32, u: i32): i32 { // see: jdh8/metallic/blob/master/src/math/float/rem_pio2f.c + const coeff = reinterpret(0x3BF921FB54442D18); // \u03C0 * 0x1p-65 = 8.51530395021638647334e-20 + + var offset = (u >> 23) - 152; + var shift = (offset & 63); + var tblPtr = PIO2F_TABLE + (offset >> 6 << 3); + + var b0 = load(tblPtr, 0 << 3); + var b1 = load(tblPtr, 1 << 3); + var lo: u64; + + if (shift > 32) { + let b2 = load(tblPtr, 2 << 3); + lo = b2 >> (96 - shift); + lo |= b1 << (shift - 32); + } else { + lo = b1 >> (32 - shift); + } + + var hi = (b1 >> (64 - shift)) | (b0 << shift); + var mantissa: u64 = (u & 0x007FFFFF) | 0x00800000; + var product = mantissa * hi + (mantissa * lo >> 32); + var r: i64 = product << 2; + var q = ((product >> 62) + (r >>> 63)); + rempio2f_y = copysign(coeff, x) * r; + return q; +} + +// @ts-ignore: decorator +@inline +function rempio2f(x: f32, u: u32, sign: i32): i32 { // see: jdh8/metallic/blob/master/src/math/float/rem_pio2f.c + const + pi2hi = reinterpret(0x3FF921FB50000000), // 1.57079631090164184570 + pi2lo = reinterpret(0x3E5110B4611A6263), // 1.58932547735281966916e-8 + _2_pi = reinterpret(0x3FE45F306DC9C883); // 0.63661977236758134308 + + if (u < 0x4DC90FDB) { // \u03C0 * 0x1p28 + let q = nearest(x * _2_pi); + rempio2f_y = x - q * pi2hi - q * pi2lo; + return q; + } + + var q = pio2f_large_quot(x, u); + return select(-q, q, sign); +} + +// |sin(x)/x - s(x)| < 2**-37.5 (~[-4.89e-12, 4.824e-12]). +// @ts-ignore: decorator +@inline +function sin_kernf(x: f64): f32 { // see: musl/tree/src/math/__sindf.c + const + S1 = reinterpret(0xBFC5555554CBAC77), // -0x15555554cbac77.0p-55 + S2 = reinterpret(0x3F811110896EFBB2), // 0x111110896efbb2.0p-59 + S3 = reinterpret(0xBF2A00F9E2CAE774), // -0x1a00f9e2cae774.0p-65 + S4 = reinterpret(0x3EC6CD878C3B46A7); // 0x16cd878c3b46a7.0p-71 + + var z = x * x; + var w = z * z; + var r = S3 + z * S4; + var s = z * x; + return ((x + s * (S1 + z * S2)) + s * w * r); +} + +// |cos(x) - c(x)| < 2**-34.1 (~[-5.37e-11, 5.295e-11]). +// @ts-ignore: decorator +@inline +function cos_kernf(x: f64): f32 { // see: musl/tree/src/math/__cosdf.c + const + C0 = reinterpret(0xBFDFFFFFFD0C5E81), // -0x1ffffffd0c5e81.0p-54 + C1 = reinterpret(0x3FA55553E1053A42), // 0x155553e1053a42.0p-57 + C2 = reinterpret(0xBF56C087E80F1E27), // -0x16c087e80f1e27.0p-62 + C3 = reinterpret(0x3EF99342E0EE5069); // 0x199342e0ee5069.0p-68 + + var z = x * x; + var w = z * z; + var r = C2 + z * C3; + return (((1 + z * C0) + w * C1) + (w * z) * r); +} + +// |tan(x)/x - t(x)| < 2**-25.5 (~[-2e-08, 2e-08]). +// @ts-ignore: decorator +@inline +function tan_kernf(x: f64, odd: i32): f32 { // see: musl/tree/src/math/__tandf.c + const + T0 = reinterpret(0x3FD5554D3418C99F), // 0x15554d3418c99f.0p-54 + T1 = reinterpret(0x3FC112FD38999F72), // 0x1112fd38999f72.0p-55 + T2 = reinterpret(0x3FAB54C91D865AFE), // 0x1b54c91d865afe.0p-57 + T3 = reinterpret(0x3F991DF3908C33CE), // 0x191df3908c33ce.0p-58 + T4 = reinterpret(0x3F685DADFCECF44E), // 0x185dadfcecf44e.0p-61 + T5 = reinterpret(0x3F8362B9BF971BCD); // 0x1362b9bf971bcd.0p-59 + + var z = x * x; + var r = T4 + z * T5; + var t = T2 + z * T3; + var w = z * z; + var s = z * x; + var u = T0 + z * T1; + + r = (x + s * u) + (s * w) * (t + w * r); + return (odd ? -1 / r : r); +} + +// See: jdh8/metallic/src/math/float/log2f.c and jdh8/metallic/src/math/float/kernel/atanh.h +// @ts-ignore: decorator +@inline +function log2f(x: f64): f64 { + const + log2e = reinterpret(0x3FF71547652B82FE), // 1.44269504088896340736 + c0 = reinterpret(0x3FD555554FD9CAEF), // 0.33333332822728226129 + c1 = reinterpret(0x3FC999A7A8AF4132), // 0.20000167595436263505 + c2 = reinterpret(0x3FC2438D79437030), // 0.14268654271188685375 + c3 = reinterpret(0x3FBE2F663B001C97); // 0.11791075649681414150 + + var i = reinterpret(x); + var exponent = (i - 0x3FE6A09E667F3BCD) >> 52; + x = reinterpret(i - (exponent << 52)); + x = (x - 1) / (x + 1); + var xx = x * x; + var y = x + x * xx * (c0 + c1 * xx + (c2 + c3 * xx) * (xx * xx)); + return (2 * log2e) * y + exponent; +} + +// See: jdh8/metallic/src/math/float/exp2f.h and jdh8/metallic/blob/master/src/math/float/kernel/exp2f.h +// @ts-ignore: decorator +@inline +function exp2f(x: f64): f64 { + const + c0 = reinterpret(0x3FE62E4302FCC24A), // 6.931471880289532425e-1 + c1 = reinterpret(0x3FCEBFBE07D97B91), // 2.402265108421173406e-1 + c2 = reinterpret(0x3FAC6AF6CCFC1A65), // 5.550357105498874537e-2 + c3 = reinterpret(0x3F83B29E3CE9AEF6), // 9.618030771171497658e-3 + c4 = reinterpret(0x3F55F0896145A89F), // 1.339086685300950937e-3 + c5 = reinterpret(0x3F2446C81E384864); // 1.546973499989028719e-4 + + if (x < -1022) return 0; + if (x >= 1024) return Infinity; + + var n = nearest(x); + x -= n; + var xx = x * x; + var y = 1 + x * (c0 + c1 * x + (c2 + c3 * x) * xx + (c4 + c5 * x) * (xx * xx)); + return reinterpret(reinterpret(y) + (n << 52)); +} + +export namespace NativeMathf { + + // @ts-ignore: decorator + @lazy + export const E = NativeMath.E; + + // @ts-ignore: decorator + @lazy + export const LN2 = NativeMath.LN2; + + // @ts-ignore: decorator + @lazy + export const LN10 = NativeMath.LN10; + + // @ts-ignore: decorator + @lazy + export const LOG2E = NativeMath.LOG2E; + + // @ts-ignore: decorator + @lazy + export const LOG10E = NativeMath.LOG10E; + + // @ts-ignore: decorator + @lazy + export const PI = NativeMath.PI; + + // @ts-ignore: decorator + @lazy + export const SQRT1_2 = NativeMath.SQRT1_2; + + // @ts-ignore: decorator + @lazy + export const SQRT2 = NativeMath.SQRT2; + + // @ts-ignore: decorator + @lazy + export var sincos_sin: f32 = 0; + + // @ts-ignore: decorator + @lazy + export var sincos_cos: f32 = 0; + + // @ts-ignore: decorator + @inline + export function abs(x: f32): f32 { + return builtin_abs(x); + } + + export function acos(x: f32): f32 { // see: musl/src/math/acosf.c and SUN COPYRIGHT NOTICE above + const + pio2_hi = reinterpret(0x3FC90FDA), // 1.5707962513e+00f + pio2_lo = reinterpret(0x33A22168), // 7.5497894159e-08f + Ox1p_120f = reinterpret(0x03800000); // 0x1p-120f + + var hx = reinterpret(x); + var ix = hx & 0x7FFFFFFF; + if (ix >= 0x3F800000) { + if (ix == 0x3F800000) { + if (hx >> 31) return 2 * pio2_hi + Ox1p_120f; + return 0; + } + return 0 / (x - x); + } + if (ix < 0x3F000000) { + if (ix <= 0x32800000) return pio2_hi + Ox1p_120f; + return pio2_hi - (x - (pio2_lo - x * Rf(x * x))); + } + var z: f32, w: f32, s: f32; + if (hx >> 31) { + // z = (1 + x) * 0.5; + z = 0.5 + x * 0.5; + s = builtin_sqrt(z); + w = Rf(z) * s - pio2_lo; + return 2 * (pio2_hi - (s + w)); + } + // z = (1 - x) * 0.5; + z = 0.5 - x * 0.5; + s = builtin_sqrt(z); + hx = reinterpret(s); + var df = reinterpret(hx & 0xFFFFF000); + var c = (z - df * df) / (s + df); + w = Rf(z) * s + c; + return 2 * (df + w); + } + + export function acosh(x: f32): f32 { // see: musl/src/math/acoshf.c + const s = reinterpret(0x3F317218); // 0.693147180559945309417232121458176568f + var u = reinterpret(x); + var a = u & 0x7FFFFFFF; + if (a < 0x3F800000 + (1 << 23)) { // |x| < 2, invalid if x < 1 + let xm1 = x - 1; + return log1p(xm1 + builtin_sqrt(xm1 * (xm1 + 2))); + } + if (u < 0x3F800000 + (12 << 23)) { // 2 <= x < 0x1p12 + return log(2 * x - 1 / (x + builtin_sqrt(x * x - 1))); + } + // x >= 0x1p12 or x <= -2 or NaN + return log(x) + s; + } + + export function asin(x: f32): f32 { // see: musl/src/math/asinf.c and SUN COPYRIGHT NOTICE above + const + pio2 = reinterpret(0x3FC90FDB), // 1.570796326794896558e+00f + Ox1p_120f = reinterpret(0x03800000); // 0x1p-120f + + var sx = x; + var hx = reinterpret(x) & 0x7FFFFFFF; + if (hx >= 0x3F800000) { + if (hx == 0x3F800000) return x * pio2 + Ox1p_120f; + return 0 / (x - x); + } + if (hx < 0x3F000000) { + if (hx < 0x39800000 && hx >= 0x00800000) return x; + return x + x * Rf(x * x); + } + // var z: f32 = (1 - builtin_abs(x)) * 0.5; + var z: f32 = 0.5 - builtin_abs(x) * 0.5; + var s = builtin_sqrt(z); // sic + x = (pio2 - 2 * (s + s * Rf(z))); + return builtin_copysign(x, sx); + } + + export function asinh(x: f32): f32 { // see: musl/src/math/asinhf.c + const c = reinterpret(0x3F317218); // 0.693147180559945309417232121458176568f + var u = reinterpret(x) & 0x7FFFFFFF; + var y = reinterpret(u); + if (u >= 0x3F800000 + (12 << 23)) y = log(y) + c; + else if (u >= 0x3F800000 + (1 << 23)) y = log(2 * y + 1 / (builtin_sqrt(y * y + 1) + y)); + else if (u >= 0x3F800000 - (12 << 23)) y = log1p(y + y * y / (builtin_sqrt(y * y + 1) + 1)); + return builtin_copysign(y, x); + } + + export function atan(x: f32): f32 { // see: musl/src/math/atanf.c and SUN COPYRIGHT NOTICE above + const + atanhi0 = reinterpret(0x3EED6338), // 4.6364760399e-01f + atanhi1 = reinterpret(0x3F490FDA), // 7.8539812565e-01f + atanhi2 = reinterpret(0x3F7B985E), // 9.8279368877e-01f + atanhi3 = reinterpret(0x3FC90FDA), // 1.5707962513e+00f + atanlo0 = reinterpret(0x31AC3769), // 5.0121582440e-09f + atanlo1 = reinterpret(0x33222168), // 3.7748947079e-08f + atanlo2 = reinterpret(0x33140FB4), // 3.4473217170e-08f + atanlo3 = reinterpret(0x33A22168), // 7.5497894159e-08f + aT0 = reinterpret(0x3EAAAAA9), // 3.3333328366e-01f + aT1 = reinterpret(0xBE4CCA98), // -1.9999158382e-01f + aT2 = reinterpret(0x3E11F50D), // 1.4253635705e-01f + aT3 = reinterpret(0xBDDA1247), // -1.0648017377e-01f + aT4 = reinterpret(0x3D7CAC25), // 6.1687607318e-02f + Ox1p_120f = reinterpret(0x03800000); // 0x1p-120f + + var ix = reinterpret(x); + var sx = x; + ix &= 0x7FFFFFFF; + var z: f32; + if (ix >= 0x4C800000) { + if (isNaN(x)) return x; + z = atanhi3 + Ox1p_120f; + return builtin_copysign(z, sx); + } + var id: i32; + if (ix < 0x3EE00000) { + if (ix < 0x39800000) return x; + id = -1; + } else { + x = builtin_abs(x); + if (ix < 0x3F980000) { + if (ix < 0x3F300000) { + id = 0; + x = (2.0 * x - 1.0) / (2.0 + x); + } else { + id = 1; + x = (x - 1.0) / (x + 1.0); + } + } else { + if (ix < 0x401C0000) { + id = 2; + x = (x - 1.5) / (1.0 + 1.5 * x); + } else { + id = 3; + x = -1.0 / x; + } + } + } + z = x * x; + var w = z * z; + var s1 = z * (aT0 + w * (aT2 + w * aT4)); + var s2 = w * (aT1 + w * aT3); + var s3 = x * (s1 + s2); + if (id < 0) return x - s3; + switch (id) { + case 0: { z = atanhi0 - ((s3 - atanlo0) - x); break; } + case 1: { z = atanhi1 - ((s3 - atanlo1) - x); break; } + case 2: { z = atanhi2 - ((s3 - atanlo2) - x); break; } + case 3: { z = atanhi3 - ((s3 - atanlo3) - x); break; } + default: unreachable(); + } + return builtin_copysign(z, sx); + } + + export function atanh(x: f32): f32 { // see: musl/src/math/atanhf.c + var u = reinterpret(x); + var y = builtin_abs(x); + if (u < 0x3F800000 - (1 << 23)) { + if (u >= 0x3F800000 - (32 << 23)) y = 0.5 * log1p(2 * y * (1.0 + y / (1 - y))); + } else y = 0.5 * log1p(2 * (y / (1 - y))); + return builtin_copysign(y, x); + } + + export function atan2(y: f32, x: f32): f32 { // see: musl/src/math/atan2f.c and SUN COPYRIGHT NOTICE above + const + pi = reinterpret(0x40490FDB), // 3.1415927410e+00f + pi_lo = reinterpret(0xB3BBBD2E); // -8.7422776573e-08f + + if (isNaN(x) || isNaN(y)) return x + y; + var ix = reinterpret(x); + var iy = reinterpret(y); + if (ix == 0x3F800000) return atan(y); + var m = (((iy >> 31) & 1) | ((ix >> 30) & 2)); + ix &= 0x7FFFFFFF; + iy &= 0x7FFFFFFF; + if (iy == 0) { + switch (m) { + case 0: + case 1: return y; + case 2: return pi; + case 3: return -pi; + } + } + if (ix == 0) return m & 1 ? -pi / 2 : pi / 2; + if (ix == 0x7F800000) { + if (iy == 0x7F800000) { + let t: f32 = m & 2 ? 3 * pi / 4 : pi / 4; + return m & 1 ? -t : t; + } else { + let t: f32 = m & 2 ? pi : 0.0; + return m & 1 ? -t : t; + } + } + if (ix + (26 << 23) < iy || iy == 0x7F800000) return m & 1 ? -pi / 2 : pi / 2; + var z: f32; + if ((m & 2) && iy + (26 << 23) < ix) z = 0.0; + else z = atan(builtin_abs(y / x)); + switch (m) { + case 0: return z; + case 1: return -z; + case 2: return pi - (z - pi_lo); + case 3: return (z - pi_lo) - pi; + } + unreachable(); + return 0; + } + + export function cbrt(x: f32): f32 { // see: musl/src/math/cbrtf.c and SUN COPYRIGHT NOTICE above + const + B1 = 709958130, + B2 = 642849266, + Ox1p24f = reinterpret(0x4B800000); + + var u = reinterpret(x); + var hx = u & 0x7FFFFFFF; + if (hx >= 0x7F800000) return x + x; + if (hx < 0x00800000) { + if (hx == 0) return x; + u = reinterpret(x * Ox1p24f); + hx = u & 0x7FFFFFFF; + hx = hx / 3 + B2; + } else { + hx = hx / 3 + B1; + } + u &= 0x80000000; + u |= hx; + var t = reinterpret(u); + var r = t * t * t; + t = t * (x + x + r) / (x + r + r); + r = t * t * t; + t = t * (x + x + r) / (x + r + r); + return t; + } + + // @ts-ignore: decorator + @inline + export function ceil(x: f32): f32 { + return builtin_ceil(x); + } + + export function clz32(x: f32): f32 { + if (!isFinite(x)) return 32; + return builtin_clz(dtoi32(x)); + } + + export function cos(x: f32): f32 { // see: musl/src/math/cosf.c + const + c1pio2 = reinterpret(0x3FF921FB54442D18), // M_PI_2 * 1 + c2pio2 = reinterpret(0x400921FB54442D18), // M_PI_2 * 2 + c3pio2 = reinterpret(0x4012D97C7F3321D2), // M_PI_2 * 3 + c4pio2 = reinterpret(0x401921FB54442D18); // M_PI_2 * 4 + + var ix = reinterpret(x); + var sign = ix >> 31; + ix &= 0x7FFFFFFF; + + if (ix <= 0x3F490FDA) { // |x| ~<= \u03C0/4 + if (ix < 0x39800000) { // |x| < 2**-12 + // raise inexact if x != 0 + return 1; + } + return cos_kernf(x); + } + + if (ASC_SHRINK_LEVEL < 1) { + if (ix <= 0x407B53D1) { // |x| ~<= 5\u03C0/4 + if (ix > 0x4016CBE3) { // |x| ~> 3\u03C0/4 + return -cos_kernf(sign ? x + c2pio2 : x - c2pio2); + } else { + return sign ? sin_kernf(x + c1pio2) : sin_kernf(c1pio2 - x); + } + } + if (ix <= 0x40E231D5) { // |x| ~<= 9\u03C0/4 + if (ix > 0x40AFEDDF) { // |x| ~> 7\u03C0/4 + return cos_kernf(sign ? x + c4pio2 : x - c4pio2); + } else { + return sign ? sin_kernf(-x - c3pio2) : sin_kernf(x - c3pio2); + } + } + } + + // cos(Inf or NaN) is NaN + if (ix >= 0x7F800000) return x - x; + + // general argument reduction needed + var n = rempio2f(x, ix, sign); + var y = rempio2f_y; + + var t = n & 1 ? sin_kernf(y) : cos_kernf(y); + return (n + 1) & 2 ? -t : t; + } + + export function cosh(x: f32): f32 { // see: musl/src/math/coshf.c + var u = reinterpret(x); + u &= 0x7FFFFFFF; + x = reinterpret(u); + if (u < 0x3F317217) { + if (u < 0x3F800000 - (12 << 23)) return 1; + let t = expm1(x); + // return 1 + t * t / (2 * (1 + t)); + return 1 + t * t / (2 + 2 * t); + } + if (u < 0x42B17217) { + let t = exp(x); + // return 0.5 * (t + 1 / t); + return 0.5 * t + 0.5 / t; + } + return expo2f(x, 1); + } + + // @ts-ignore: decorator + @inline + export function floor(x: f32): f32 { + return builtin_floor(x); + } + + export function exp(x: f32): f32 { // see: musl/src/math/expf.c and SUN COPYRIGHT NOTICE above + if (ASC_SHRINK_LEVEL < 1) { + return expf_lut(x); + } else { + const + ln2hi = reinterpret(0x3F317200), // 6.9314575195e-1f + ln2lo = reinterpret(0x35BFBE8E), // 1.4286067653e-6f + invln2 = reinterpret(0x3FB8AA3B), // 1.4426950216e+0f + P1 = reinterpret(0x3E2AAA8F), // 1.6666625440e-1f + P2 = reinterpret(0xBB355215), // -2.7667332906e-3f + Ox1p127f = reinterpret(0x7F000000); // 0x1p+127f + + let hx = reinterpret(x); + let sign_ = (hx >> 31); + hx &= 0x7FFFFFFF; + if (hx >= 0x42AEAC50) { + if (hx > 0x7F800000) return x; // NaN + if (hx >= 0x42B17218) { + if (!sign_) return x * Ox1p127f; + else if (hx >= 0x42CFF1B5) return 0; + } + } + let hi: f32, lo: f32; + let k: i32; + if (hx > 0x3EB17218) { + if (hx > 0x3F851592) { + k = (invln2 * x + builtin_copysign(0.5, x)); + } else { + k = 1 - (sign_ << 1); + } + hi = x - k * ln2hi; + lo = k * ln2lo; + x = hi - lo; + } else if (hx > 0x39000000) { + k = 0; + hi = x; + lo = 0; + } else { + return 1 + x; + } + let xx = x * x; + let c = x - xx * (P1 + xx * P2); + let y: f32 = 1 + (x * c / (2 - c) - lo + hi); + return k == 0 ? y : scalbn(y, k); + } + } + + export function exp2(x: f32): f32 { + return exp2f_lut(x); + } + + export function expm1(x: f32): f32 { // see: musl/src/math/expm1f.c and SUN COPYRIGHT NOTICE above + const + ln2_hi = reinterpret(0x3F317180), // 6.9313812256e-01f + ln2_lo = reinterpret(0x3717F7D1), // 9.0580006145e-06f + invln2 = reinterpret(0x3FB8AA3B), // 1.4426950216e+00f + Q1 = reinterpret(0xBD088868), // -3.3333212137e-02f + Q2 = reinterpret(0x3ACF3010), // 1.5807170421e-03f + Ox1p127f = reinterpret(0x7F000000); // 0x1p+127f + + var u = reinterpret(x); + var hx = u & 0x7FFFFFFF; + var sign_ = (u >> 31); + if (hx >= 0x4195B844) { + if (hx > 0x7F800000) return x; + if (sign_) return -1; + if (hx > 0x42B17217) { // x > log(FLT_MAX) + x *= Ox1p127f; + return x; + } + } + var c: f32 = 0.0, t: f32, k: i32; + if (hx > 0x3EB17218) { + k = select( + 1 - (sign_ << 1), + (invln2 * x + builtin_copysign(0.5, x)), + hx < 0x3F851592 + ); + t = k; + let hi = x - t * ln2_hi; + let lo = t * ln2_lo; + x = hi - lo; + c = (hi - x) - lo; + } else if (hx < 0x33000000) { + return x; + } else k = 0; + var hfx: f32 = 0.5 * x; + var hxs: f32 = x * hfx; + var r1: f32 = 1.0 + hxs * (Q1 + hxs * Q2); + t = 3.0 - r1 * hfx; + var e = hxs * ((r1 - t) / (6.0 - x * t)); + if (k == 0) return x - (x * e - hxs); + e = x * (e - c) - c; + e -= hxs; + if (k == -1) return 0.5 * (x - e) - 0.5; + if (k == 1) { + if (x < -0.25) return -2.0 * (e - (x + 0.5)); + return 1.0 + 2.0 * (x - e); + } + u = (0x7F + k) << 23; + var twopk = reinterpret(u); + var y: f32; + if (k < 0 || k > 56) { + y = x - e + 1.0; + if (k == 128) y = y * 2.0 * Ox1p127f; + else y = y * twopk; + return y - 1.0; + } + u = (0x7F - k) << 23; + y = reinterpret(u); + if (k < 20) y = (1 - y) - e; + else y = 1 - (e + y); + return (x + y) * twopk; + } + + // @ts-ignore: decorator + @inline + export function fround(x: f32): f32 { + return x; + } + + export function hypot(x: f32, y: f32): f32 { // see: musl/src/math/hypotf.c + const + Ox1p90f = reinterpret(0x6C800000), + Ox1p_90f = reinterpret(0x12800000); + + var ux = reinterpret(x); + var uy = reinterpret(y); + ux &= 0x7FFFFFFF; + uy &= 0x7FFFFFFF; + if (ux < uy) { + let ut = ux; + ux = uy; + uy = ut; + } + x = reinterpret(ux); + y = reinterpret(uy); + if (uy == 0xFF << 23) return y; + if (ux >= 0xFF << 23 || uy == 0 || ux - uy >= 25 << 23) return x + y; + var z: f32 = 1; + if (ux >= (0x7F + 60) << 23) { + z = Ox1p90f; + x *= Ox1p_90f; + y *= Ox1p_90f; + } else if (uy < (0x7F - 60) << 23) { + z = Ox1p_90f; + x *= Ox1p90f; + y *= Ox1p90f; + } + return z * builtin_sqrt((x * x + y * y)); + } + + // @ts-ignore: decorator + @inline + export function imul(x: f32, y: f32): f32 { + /* + * Wasm (MVP) and JS have different approaches for double->int conversions. + * + * For emulate JS conversion behavior and avoid trapping from wasm we should modulate by MAX_INT + * our float-point arguments before actual convertion to integers. + */ + if (!isFinite(x + y)) return 0; + return (dtoi32(x) * dtoi32(y)); + } + + export function log(x: f32): f32 { // see: musl/src/math/logf.c and SUN COPYRIGHT NOTICE above + if (ASC_SHRINK_LEVEL < 1) { + return logf_lut(x); + } else { + const + ln2_hi = reinterpret(0x3F317180), // 6.9313812256e-01f + ln2_lo = reinterpret(0x3717F7D1), // 9.0580006145e-06f + Lg1 = reinterpret(0x3F2AAAAA), // 0xaaaaaa.0p-24f + Lg2 = reinterpret(0x3ECCCE13), // 0xccce13.0p-25f + Lg3 = reinterpret(0x3E91E9EE), // 0x91e9ee.0p-25f + Lg4 = reinterpret(0x3E789E26), // 0xf89e26.0p-26f + Ox1p25f = reinterpret(0x4C000000); + + let u = reinterpret(x); + let k = 0; + if (u < 0x00800000 || (u >> 31)) { + if (u << 1 == 0) return -1 / (x * x); + if (u >> 31) return (x - x) / 0; + k -= 25; + x *= Ox1p25f; + u = reinterpret(x); + } else if (u >= 0x7F800000) { + return x; + } else if (u == 0x3F800000) { + return 0; + } + u += 0x3F800000 - 0x3F3504F3; + k += (u >> 23) - 0x7F; + u = (u & 0x007FFFFF) + 0x3F3504F3; + x = reinterpret(u); + let f = x - 1.0; + let s = f / (2.0 + f); + let z = s * s; + let w = z * z; + let t1 = w * (Lg2 + w * Lg4); + let t2 = z * (Lg1 + w * Lg3); + let r = t2 + t1; + let hfsq = 0.5 * f * f; + let dk = k; + return s * (hfsq + r) + dk * ln2_lo - hfsq + f + dk * ln2_hi; + } + } + + export function log10(x: f32): f32 { // see: musl/src/math/log10f.c and SUN COPYRIGHT NOTICE above + const + ivln10hi = reinterpret(0x3EDE6000), // 4.3432617188e-01f + ivln10lo = reinterpret(0xB804EAD9), // -3.1689971365e-05f + log10_2hi = reinterpret(0x3E9A2080), // 3.0102920532e-01f + log10_2lo = reinterpret(0x355427DB), // 7.9034151668e-07f + Lg1 = reinterpret(0x3F2AAAAA), // 0xaaaaaa.0p-24f, 0.66666662693f + Lg2 = reinterpret(0x3ECCCE13), // 0xccce13.0p-25f, 0.40000972152f + Lg3 = reinterpret(0x3E91E9EE), // 0x91e9ee.0p-25f, 0.28498786688f + Lg4 = reinterpret(0x3E789E26), // 0xf89e26.0p-26f, 0.24279078841f + Ox1p25f = reinterpret(0x4C000000); // 0x1p25f + + var ix = reinterpret(x); + var k = 0; + if (ix < 0x00800000 || (ix >> 31)) { + if (ix << 1 == 0) return -1 / (x * x); + if (ix >> 31) return (x - x) / 0.0; + k -= 25; + x *= Ox1p25f; + ix = reinterpret(x); + } else if (ix >= 0x7F800000) { + return x; + } else if (ix == 0x3F800000) { + return 0; + } + ix += 0x3F800000 - 0x3F3504F3; + k += (ix >> 23) - 0x7F; + ix = (ix & 0x007FFFFF) + 0x3F3504F3; + x = reinterpret(ix); + var f = x - 1.0; + var s = f / (2.0 + f); + var z = s * s; + var w = z * z; + var t1 = w * (Lg2 + w * Lg4); + var t2 = z * (Lg1 + w * Lg3); + var r = t2 + t1; + var hfsq: f32 = 0.5 * f * f; + var hi = f - hfsq; + ix = reinterpret(hi); + ix &= 0xFFFFF000; + hi = reinterpret(ix); + var lo = f - hi - hfsq + s * (hfsq + r); + var dk = k; + return dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi + hi * ivln10hi + dk * log10_2hi; + } + + export function log1p(x: f32): f32 { // see: musl/src/math/log1pf.c and SUN COPYRIGHT NOTICE above + const + ln2_hi = reinterpret(0x3F317180), // 6.9313812256e-01 + ln2_lo = reinterpret(0x3717F7D1), // 9.0580006145e-06 + Lg1 = reinterpret(0x3F2AAAAA), // 0xaaaaaa.0p-24f, 0.66666662693f + Lg2 = reinterpret(0x3ECCCE13), // 0xccce13.0p-25f, 0.40000972152f + Lg3 = reinterpret(0x3E91E9EE), // 0x91e9ee.0p-25f, 0.28498786688f + Lg4 = reinterpret(0x3E789E26); // 0xf89e26.0p-26f, 0.24279078841f + + var ix = reinterpret(x); + var c: f32 = 0, f: f32 = 0; + var k: i32 = 1; + if (ix < 0x3ED413D0 || (ix >> 31)) { + if (ix >= 0xBF800000) { + if (x == -1) return x / 0.0; + return (x - x) / 0.0; + } + if (ix << 1 < 0x33800000 << 1) return x; + if (ix <= 0xBE95F619) { + k = 0; + c = 0; + f = x; + } + } else if (ix >= 0x7F800000) return x; + if (k) { + let uf: f32 = 1 + x; + let iu = reinterpret(uf); + iu += 0x3F800000 - 0x3F3504F3; + k = (iu >> 23) - 0x7F; + if (k < 25) { + c = k >= 2 ? 1 - (uf - x) : x - (uf - 1); + c /= uf; + } else c = 0; + iu = (iu & 0x007FFFFF) + 0x3F3504F3; + f = reinterpret(iu) - 1; + } + var s = f / (2.0 + f); + var z = s * s; + var w = z * z; + var t1 = w * (Lg2 + w * Lg4); + var t2 = z * (Lg1 + w * Lg3); + var r = t2 + t1; + var hfsq: f32 = 0.5 * f * f; + var dk = k; + return s * (hfsq + r) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; + } + + export function log2(x: f32): f32 { // see: musl/src/math/log2f.c and SUN COPYRIGHT NOTICE above + if (ASC_SHRINK_LEVEL < 1) { + return log2f_lut(x); + } else { + const + ivln2hi = reinterpret(0x3FB8B000), // 1.4428710938e+00f + ivln2lo = reinterpret(0xB9389AD4), // -1.7605285393e-04 + Lg1 = reinterpret(0x3F2AAAAA), // 0xaaaaaa.0p-24f, 0.66666662693f + Lg2 = reinterpret(0x3ECCCE13), // 0xccce13.0p-25f, 0.40000972152f + Lg3 = reinterpret(0x3E91E9EE), // 0x91e9ee.0p-25f, 0.28498786688f + Lg4 = reinterpret(0x3E789E26), // 0xf89e26.0p-26f, 0.24279078841f + Ox1p25f = reinterpret(0x4C000000); // 0x1p25f + + let ix = reinterpret(x); + let k: i32 = 0; + if (ix < 0x00800000 || (ix >> 31)) { + if (ix << 1 == 0) return -1 / (x * x); + if (ix >> 31) return (x - x) / 0.0; + k -= 25; + x *= Ox1p25f; + ix = reinterpret(x); + } else if (ix >= 0x7F800000) { + return x; + } else if (ix == 0x3F800000) { + return 0; + } + ix += 0x3F800000 - 0x3F3504F3; + k += (ix >> 23) - 0x7F; + ix = (ix & 0x007FFFFF) + 0x3F3504F3; + x = reinterpret(ix); + let f = x - 1.0; + let s = f / (2.0 + f); + let z = s * s; + let w = z * z; + let t1 = w * (Lg2 + w * Lg4); + let t2 = z * (Lg1 + w * Lg3); + let r = t2 + t1; + let hfsq: f32 = 0.5 * f * f; + let hi = f - hfsq; + let u = reinterpret(hi); + u &= 0xFFFFF000; + hi = reinterpret(u); + let lo: f32 = f - hi - hfsq + s * (hfsq + r); + let dk = k; + return (lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + dk; + } + } + + // @ts-ignore: decorator + @inline + export function max(value1: f32, value2: f32): f32 { + return builtin_max(value1, value2); + } + + // @ts-ignore: decorator + @inline + export function min(value1: f32, value2: f32): f32 { + return builtin_min(value1, value2); + } + + export function pow(x: f32, y: f32): f32 { + // TODO: remove this fast pathes after introduced own mid-end IR with "stdlib call simplify" transforms + if (builtin_abs(y) <= 2) { + if (y == 2.0) return x * x; + if (y == 0.5) { + return select( + builtin_abs(builtin_sqrt(x)), + Infinity, + x != -Infinity + ); + } + if (y == -1.0) return 1 / x; + if (y == 1.0) return x; + if (y == 0.0) return 1.0; + } + if (ASC_SHRINK_LEVEL < 1) { + // see: musl/src/math/powf.c + return powf_lut(x, y); + } else { + // based on: jdh8/metallic/src/math/float/powf.c + if (y == 0) return 1; + // @ts-ignore: cast + if (isNaN(x) | isNaN(y)) { + return NaN; + } + let sign: u32 = 0; + let uy = reinterpret(y); + let ux = reinterpret(x); + let sx = ux >> 31; + ux &= 0x7FFFFFFF; + if (sx && nearest(y) == y) { + x = -x; + sx = 0; + sign = u32(nearest(y * 0.5) != y * 0.5) << 31; + } + let m: u32; + if (ux == 0x3F800000) { // x == 1 + m = sx | u32((uy & 0x7FFFFFFF) == 0x7F800000) ? 0x7FC00000 : 0x3F800000; + } else if (ux == 0) { + m = uy >> 31 ? 0x7F800000 : 0; + } else if (ux == 0x7F800000) { + m = uy >> 31 ? 0 : 0x7F800000; + } else if (sx) { + m = 0x7FC00000; + } else { + m = reinterpret(exp2f(y * log2f(x))); + } + return reinterpret(m | sign); + } + } + + // @ts-ignore: decorator + @inline + export function seedRandom(value: i64): void { + NativeMath.seedRandom(value); + } + + // Using xoroshiro64starstar from http://xoshiro.di.unimi.it/xoroshiro64starstar.c + export function random(): f32 { + if (!random_seeded) seedRandom(reinterpret(seed())); + + var s0 = random_state0_32; + var s1 = random_state1_32; + var r = rotl(s0 * 0x9E3779BB, 5) * 5; + + s1 ^= s0; + random_state0_32 = rotl(s0, 26) ^ s1 ^ (s1 << 9); + random_state1_32 = rotl(s1, 13); + + return reinterpret((r >> 9) | (127 << 23)) - 1.0; + } + + // @ts-ignore: decorator + @inline + export function round(x: f32): f32 { + let roundUp = builtin_ceil(x); + return select(roundUp, roundUp - 1.0, roundUp - 0.5 <= x); + } + + // @ts-ignore: decorator + @inline + export function sign(x: f32): f32 { + if (ASC_SHRINK_LEVEL > 0) { + return builtin_abs(x) > 0 ? builtin_copysign(1, x) : x; + } else { + return x > 0 ? 1 : x < 0 ? -1 : x; + } + } + + // @ts-ignore: decorator + @inline + export function signbit(x: f32): bool { + return (reinterpret(x) >>> 31); + } + + export function sin(x: f32): f32 { // see: musl/src/math/sinf.c + const + s1pio2 = reinterpret(0x3FF921FB54442D18), // M_PI_2 * 1 + s2pio2 = reinterpret(0x400921FB54442D18), // M_PI_2 * 2 + s3pio2 = reinterpret(0x4012D97C7F3321D2), // M_PI_2 * 3 + s4pio2 = reinterpret(0x401921FB54442D18); // M_PI_2 * 4 + + var ix = reinterpret(x); + var sign = ix >> 31; + ix &= 0x7FFFFFFF; + + if (ix <= 0x3F490FDA) { // |x| ~<= \u03C0/4 + if (ix < 0x39800000) { // |x| < 2**-12 + return x; + } + return sin_kernf(x); + } + + if (ASC_SHRINK_LEVEL < 1) { + if (ix <= 0x407B53D1) { // |x| ~<= 5\u03C0/4 + if (ix <= 0x4016CBE3) { // |x| ~<= 3\u03C0/4 + return sign ? -cos_kernf(x + s1pio2) : cos_kernf(x - s1pio2); + } + return sin_kernf(-(sign ? x + s2pio2 : x - s2pio2)); + } + + if (ix <= 0x40E231D5) { // |x| ~<= 9\u03C0/4 + if (ix <= 0x40AFEDDF) { // |x| ~<= 7\u03C0/4 + return sign ? cos_kernf(x + s3pio2) : -cos_kernf(x - s3pio2); + } + return sin_kernf(sign ? x + s4pio2 : x - s4pio2); + } + } + + // sin(Inf or NaN) is NaN + if (ix >= 0x7F800000) return x - x; + + var n = rempio2f(x, ix, sign); + var y = rempio2f_y; + + var t = n & 1 ? cos_kernf(y) : sin_kernf(y); + return n & 2 ? -t : t; + } + + export function sinh(x: f32): f32 { // see: musl/src/math/sinhf.c + var u = reinterpret(x) & 0x7FFFFFFF; + var a = reinterpret(u); + var h = builtin_copysign(0.5, x); + if (u < 0x42B17217) { + let t = expm1(a); + if (u < 0x3F800000) { + if (u < 0x3F800000 - (12 << 23)) return x; + return h * (2 * t - t * t / (t + 1)); + } + return h * (t + t / (t + 1)); + } + return expo2f(a, 2 * h); + } + + // @ts-ignore: decorator + @inline + export function sqrt(x: f32): f32 { + return builtin_sqrt(x); + } + + export function tan(x: f32): f32 { // see: musl/src/math/tanf.c + const + t1pio2 = reinterpret(0x3FF921FB54442D18), // 1 * M_PI_2 + t2pio2 = reinterpret(0x400921FB54442D18), // 2 * M_PI_2 + t3pio2 = reinterpret(0x4012D97C7F3321D2), // 3 * M_PI_2 + t4pio2 = reinterpret(0x401921FB54442D18); // 4 * M_PI_2 + + var ix = reinterpret(x); + var sign = ix >> 31; + ix &= 0x7FFFFFFF; + + if (ix <= 0x3F490FDA) { // |x| ~<= \u03C0/4 + if (ix < 0x39800000) { // |x| < 2**-12 + return x; + } + return tan_kernf(x, 0); + } + + if (ASC_SHRINK_LEVEL < 1) { + if (ix <= 0x407B53D1) { // |x| ~<= 5\u03C0/4 + if (ix <= 0x4016CBE3) { // |x| ~<= 3\u03C0/4 + return tan_kernf((sign ? x + t1pio2 : x - t1pio2), 1); + } else { + return tan_kernf((sign ? x + t2pio2 : x - t2pio2), 0); + } + } + if (ix <= 0x40E231D5) { // |x| ~<= 9\u03C0/4 + if (ix <= 0x40AFEDDF) { // |x| ~<= 7\u03C0/4 + return tan_kernf((sign ? x + t3pio2 : x - t3pio2), 1); + } else { + return tan_kernf((sign ? x + t4pio2 : x - t4pio2), 0); + } + } + } + + // tan(Inf or NaN) is NaN + if (ix >= 0x7F800000) return x - x; + + // argument reduction + var n = rempio2f(x, ix, sign); + var y = rempio2f_y; + return tan_kernf(y, n & 1); + } + + export function tanh(x: f32): f32 { // see: musl/src/math/tanhf.c + var u = reinterpret(x); + u &= 0x7FFFFFFF; + var y = reinterpret(u); + var t: f32; + if (u > 0x3F0C9F54) { + if (u > 0x41200000) t = 1 + 0 / y; + else { + t = expm1(2 * y); + t = 1 - 2 / (t + 2); + } + } else if (u > 0x3E82C578) { + t = expm1(2 * y); + t = t / (t + 2); + } else if (u >= 0x00800000) { + t = expm1(-2 * y); + t = -t / (t + 2); + } else t = y; + return builtin_copysign(t, x); + } + + // @ts-ignore: decorator + @inline + export function trunc(x: f32): f32 { + return builtin_trunc(x); + } + + export function scalbn(x: f32, n: i32): f32 { // see: https://git.musl-libc.org/cgit/musl/tree/src/math/scalbnf.c + const + Ox1p24f = reinterpret(0x4B800000), + Ox1p127f = reinterpret(0x7F000000), + Ox1p_126f = reinterpret(0x00800000); + + var y = x; + if (n > 127) { + y *= Ox1p127f; + n -= 127; + if (n > 127) { + y *= Ox1p127f; + n = builtin_min(n - 127, 127); + } + } else if (n < -126) { + y *= Ox1p_126f * Ox1p24f; + n += 126 - 24; + if (n < -126) { + y *= Ox1p_126f * Ox1p24f; + n = builtin_max(n + 126 - 24, -126); + } + } + return y * reinterpret((0x7F + n) << 23); + } + + export function mod(x: f32, y: f32): f32 { // see: musl/src/math/fmodf.c + if (builtin_abs(y) == 1.0) { + // x % 1, x % -1 ==> sign(x) * abs(x - 1.0 * trunc(x / 1.0)) + // TODO: move this rule to compiler's optimization pass. + // It could be apply for any x % C_pot, where "C_pot" is pow of two const. + return builtin_copysign(x - builtin_trunc(x), x); + } + var ux = reinterpret(x); + var uy = reinterpret(y); + var ex = (ux >> 23 & 0xFF); + var ey = (uy >> 23 & 0xFF); + var sm = ux & 0x80000000; + var uy1 = uy << 1; + if (uy1 == 0 || ex == 0xFF || isNaN(y)) { + let m = x * y; + return m / m; + } + var ux1 = ux << 1; + if (ux1 <= uy1) { + return x * f32(ux1 != uy1); + } + if (!ex) { + ex -= builtin_clz(ux << 9); + ux <<= 1 - ex; + } else { + ux &= -1 >> 9; + ux |= 1 << 23; + } + if (!ey) { + ey -= builtin_clz(uy << 9); + uy <<= 1 - ey; + } else { + uy &= -1 >> 9; + uy |= 1 << 23; + } + while (ex > ey) { + if (ux >= uy) { + if (ux == uy) return 0 * x; + ux -= uy; + } + ux <<= 1; + --ex; + } + if (ux >= uy) { + if (ux == uy) return 0 * x; + ux -= uy; + } + // for (; !(ux >> 23); ux <<= 1) --ex; + var shift = builtin_clz(ux << 8); + ex -= shift; + ux <<= shift; + if (ex > 0) { + ux -= 1 << 23; + ux |= ex << 23; + } else { + ux >>= -ex + 1; + } + return reinterpret(ux | sm); + } + + export function rem(x: f32, y: f32): f32 { // see: musl/src/math/remquof.c + var ux = reinterpret(x); + var uy = reinterpret(y); + var ex = (ux >> 23 & 0xFF); + var ey = (uy >> 23 & 0xFF); + var sx = (ux >> 31); + var uxi = ux; + if (uy << 1 == 0 || ex == 0xFF || isNaN(y)) return (x * y) / (x * y); + if (ux << 1 == 0) return x; + if (!ex) { + ex -= builtin_clz(uxi << 9); + uxi <<= 1 - ex; + } else { + uxi &= -1 >> 9; + uxi |= 1 << 23; + } + if (!ey) { + ey -= builtin_clz(uy << 9); + uy <<= 1 - ey; + } else { + uy &= -1 >> 9; + uy |= 1 << 23; + } + var q = 0; + do { + if (ex < ey) { + if (ex + 1 == ey) break; // goto end + return x; + } + while (ex > ey) { + if (uxi >= uy) { + uxi -= uy; + ++q; + } + uxi <<= 1; + q <<= 1; + --ex; + } + if (uxi >= uy) { + uxi -= uy; + ++q; + } + if (uxi == 0) ex = -30; + else { + let shift = builtin_clz(uxi << 8); + ex -= shift; + uxi <<= shift; + } + break; + } while (false); + // end: + if (ex > 0) { + uxi -= 1 << 23; + uxi |= ex << 23; + } else { + uxi >>= -ex + 1; + } + x = reinterpret(uxi); + y = builtin_abs(y); + var x2 = x + x; + if (ex == ey || (ex + 1 == ey && (x2 > y || (x2 == y && (q & 1))))) { + x -= y; + // q++; + } + return sx ? -x : x; + } + + export function sincos(x: f32): void { // see: musl/tree/src/math/sincosf.c + const + s1pio2 = reinterpret(0x3FF921FB54442D18), // 1 * M_PI_2 + s2pio2 = reinterpret(0x400921FB54442D18), // 2 * M_PI_2 + s3pio2 = reinterpret(0x4012D97C7F3321D2), // 3 * M_PI_2 + s4pio2 = reinterpret(0x401921FB54442D18); // 4 * M_PI_2 + + var ix = reinterpret(x); + var sign = ix >> 31; + ix &= 0x7FFFFFFF; + + if (ix <= 0x3F490FDA) { // |x| ~<= \u03C0/4 + if (ix < 0x39800000) { // |x| < 2**-12 + sincos_sin = x; + sincos_cos = 1; + return; + } + sincos_sin = sin_kernf(x); + sincos_cos = cos_kernf(x); + return; + } + if (ASC_SHRINK_LEVEL < 1) { + if (ix <= 0x407B53D1) { // |x| ~<= 5\u03C0/4 + if (ix <= 0x4016CBE3) { // |x| ~<= 3\u03C0/4 + if (sign) { + sincos_sin = -cos_kernf(x + s1pio2); + sincos_cos = sin_kernf(x + s1pio2); + } else { + sincos_sin = cos_kernf(s1pio2 - x); + sincos_cos = sin_kernf(s1pio2 - x); + } + return; + } + // -sin(x + c) is not correct if x+c could be 0: -0 vs +0 + sincos_sin = -sin_kernf(sign ? x + s2pio2 : x - s2pio2); + sincos_cos = -cos_kernf(sign ? x + s2pio2 : x - s2pio2); + return; + } + if (ix <= 0x40E231D5) { // |x| ~<= 9\u03C0/4 + if (ix <= 0x40AFEDDF) { // |x| ~<= 7\u03C0/4 + if (sign) { + sincos_sin = cos_kernf(x + s3pio2); + sincos_cos = -sin_kernf(x + s3pio2); + } else { + sincos_sin = -cos_kernf(x - s3pio2); + sincos_cos = sin_kernf(x - s3pio2); + } + return; + } + sincos_sin = sin_kernf(sign ? x + s4pio2 : x - s4pio2); + sincos_cos = cos_kernf(sign ? x + s4pio2 : x - s4pio2); + return; + } + } + // sin(Inf or NaN) is NaN + if (ix >= 0x7F800000) { + let xx = x - x; + sincos_sin = xx; + sincos_cos = xx; + return; + } + // general argument reduction needed + var n = rempio2f(x, ix, sign); + var y = rempio2f_y; + var s = sin_kernf(y); + var c = cos_kernf(y); + var sin = s, cos = c; + if (n & 1) { + sin = c; + cos = -s; + } + if (n & 2) { + sin = -sin; + cos = -cos; + } + sincos_sin = sin; + sincos_cos = cos; + } +} + +export function ipow32(x: i32, e: i32): i32 { + var out = 1; + if (ASC_SHRINK_LEVEL < 1) { + if (x == 2) { + return select(1 << e, 0, e < 32); + } + if (e <= 0) { + if (x == -1) return select(-1, 1, e & 1); + return i32(e == 0) | i32(x == 1); + } + else if (e == 1) return x; + else if (e == 2) return x * x; + else if (e < 32) { + let log = 32 - clz(e); + // 32 = 2 ^ 5, so need only five cases. + // But some extra cases needs for properly overflowing + switch (log) { + case 5: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 4: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 3: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 2: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 1: { + if (e & 1) out *= x; + } + } + return out; + } + } + while (e) { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + return out; +} + +export function ipow64(x: i64, e: i64): i64 { + var out: i64 = 1; + if (ASC_SHRINK_LEVEL < 1) { + if (x == 2) { + return select(1 << e, 0, e < 64); + } + if (e <= 0) { + if (x == -1) return select(-1, 1, e & 1); + return i64(e == 0) | i64(x == 1); + } + else if (e == 1) return x; + else if (e == 2) return x * x; + else if (e < 64) { + let log = 64 - clz(e); + // 64 = 2 ^ 6, so need only six cases. + // But some extra cases needs for properly overflowing + switch (log) { + case 6: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 5: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 4: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 3: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 2: { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + case 1: { + if (e & 1) out *= x; + } + } + return out; + } + } + while (e) { + if (e & 1) out *= x; + e >>>= 1; + x *= x; + } + return out; +} + +/* +TODO: +In compile time if only exponent is constant we could replace ipow32/ipow64 by shortest addition chains +which usually faster than exponentiation by squaring + +for ipow32 and e < 32: + +let b: i32, c: i32, d: i32, h: i32, k: i32, g: i32; +switch (e) { + case 1: return x; + case 2: return x * x; + case 3: return x * x * x; + case 4: return (b = x * x) * b; + case 5: return (b = x * x) * b * x; + case 6: return (b = x * x) * b * b; + case 7: return (b = x * x) * b * b * x; + case 8: return (d = (b = x * x) * b) * d; + case 9: return (c = x * x * x) * c * c; + case 10: return (d = (b = x * x) * b) * d * b; + case 11: return (d = (b = x * x) * b) * d * b * x; + case 12: return (d = (b = x * x) * b) * d * d; + case 13: return (d = (b = x * x) * b) * d * d * x; + case 14: return (d = (b = x * x) * b) * d * d * b; + case 15: return (k = (b = x * x) * b * x) * k * k; + case 16: return (h = (d = (b = x * x) * b) * d) * h; + case 17: return (h = (d = (b = x * x) * b) * d) * h * x; + case 18: return (h = (d = (b = x * x) * b) * d * x) * h; + case 19: return (h = (d = (b = x * x) * b) * d * x) * h * x; + case 20: return (h = (k = (b = x * x) * b * x) * k) * h; + case 21: return (h = (k = (b = x * x) * b * x) * k) * h * x; + case 22: return (g = (h = (k = (b = x * x) * b * x) * k) * x) * g; + case 23: return (h = (d = (c = (b = x * x) * x) * b) * d) * h * c; + case 24: return (h = (d = (c = x * x * x) * c) * d) * h; + case 25: return (h = (d = (c = x * x * x) * c) * d) * h * x; + case 26: return (g = (h = (d = (c = x * x * x) * c) * d) * x) * g; + case 27: return (h = (d = (c = x * x * x) * c) * d) * h * c; + case 28: return (h = (d = (c = x * x * x) * c * x) * d) * h; + case 29: return (h = (d = (c = x * x * x) * c * x) * d) * h * x; + case 30: return (h = (d = (c = x * x * x) * c) * d * c) * h; + case 31: return (h = (d = (c = x * x * x) * c) * d * c) * h * x; +} + +for ipow64: TODO +switch (e) { + case 32: + ... + case 63: +} +*/ +`,memory:`import { memcmp, memmove, memset } from "./util/memory"; +import { E_NOTIMPLEMENTED } from "./util/error"; + +/** Memory manager interface. */ +export namespace memory { + + /** Gets the size of the memory in pages. */ + // @ts-ignore: decorator + @builtin + export declare function size(): i32; + + /** Grows the memory by the given size in pages and returns the previous size in pages. */ + // @ts-ignore: decorator + @unsafe @builtin + export declare function grow(pages: i32): i32; + + /** Fills a section in memory with the specified byte value. */ + // @ts-ignore: decorator + @unsafe @builtin + export function fill(dst: usize, c: u8, n: usize): void { + memset(dst, c, n); // fallback if "bulk-memory" isn't enabled + } + + /** Copies a section of memory to another. Has move semantics. */ + // @ts-ignore: decorator + @unsafe @builtin + export function copy(dst: usize, src: usize, n: usize): void { + memmove(dst, src, n); // fallback if "bulk-memory" isn't enabled + } + + /** Initializes a memory segment. */ + // @ts-ignore: decorator + @unsafe + export function init(segmentIndex: u32, srcOffset: usize, dstOffset: usize, n: usize): void { + throw new Error(E_NOTIMPLEMENTED); + } + + /** Drops a memory segment. */ + // @ts-ignore: decorator + @unsafe + export function drop(segmentIndex: u32): void { + throw new Error(E_NOTIMPLEMENTED); + } + + /** Repeats a section of memory at a specific address. */ + // @ts-ignore: decorator + @unsafe + export function repeat(dst: usize, src: usize, srcLength: usize, count: usize): void { + var index: usize = 0; + var total = srcLength * count; + while (index < total) { + memory.copy(dst + index, src, srcLength); + index += srcLength; + } + } + + /** Compares a section of memory to another. */ + // @ts-ignore: decorator + @inline + export function compare(vl: usize, vr: usize, n: usize): i32 { + return memcmp(vl, vr, n); + } + + /** Gets a pointer to a static chunk of memory of the given size. */ + // @ts-ignore: decorator + @builtin + export declare function data(size: T, align?: i32): usize; +} + +// @ts-ignore: decorator +@builtin +export declare const __data_end: usize; + +// @ts-ignore: decorator +@builtin +export declare var __stack_pointer: usize; + +// @ts-ignore: decorator +@builtin +export declare const __heap_base: usize; + +/** Heap memory interface. */ +export namespace heap { + + /** Allocates a chunk of memory of at least the specified size. */ + // @ts-ignore: decorator + @unsafe export function alloc(size: usize): usize { + return __alloc(size); + } + + /** Reallocates a chunk of memory to have at least the specified size. */ + // @ts-ignore: decorator + @unsafe export function realloc(ptr: usize, size: usize): usize { + return __realloc(ptr, size); + } + + /** Frees a chunk of memory. Does hardly anything (most recent block only) with the stub runtime. */ + // @ts-ignore: decorator + @unsafe export function free(ptr: usize): void { + __free(ptr); + } + + /** Dangerously resets the entire heap. Specific to the stub runtime. */ + // @ts-ignore: decorator + @unsafe export function reset(): void { + if (isDefined(__reset)) { + __reset(); + } else { + throw new Error(E_NOTIMPLEMENTED); + } + } +} +`,number:`import { itoa32, utoa32, itoa64, utoa64, dtoa } from "./util/number"; +import { strtol } from "./util/string"; + +// @ts-ignore: decorator +@builtin @inline +export const NaN: f64 = 0 / 0; + +// @ts-ignore: decorator +@builtin @inline +export const Infinity: f64 = 1 / 0; + +// @ts-ignore: decorator +@builtin +export declare function isNaN(value: T): bool; + +// @ts-ignore: decorator +@builtin +export declare function isFinite(value: T): bool; + +@final @unmanaged +export abstract class I8 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: i8 = i8.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: i8 = i8.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): i8 { + return strtol(value, radix); + } + + toString(this: i8, radix: i32 = 10): String { + return itoa32(this, radix); + } +} + +@final @unmanaged +export abstract class I16 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: i16 = i16.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: i16 = i16.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): i16 { + return strtol(value, radix); + } + + toString(this: i16, radix: i32 = 10): String { + return itoa32(this, radix); + } +} + +@final @unmanaged +export abstract class I32 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: i32 = i32.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: i32 = i32.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): i32 { + return strtol(value, radix); + } + + toString(this: i32, radix: i32 = 10): String { + return itoa32(this, radix); + } +} + +@final @unmanaged +export abstract class I64 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: i64 = i64.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: i64 = i64.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): i64 { + return strtol(value, radix); + } + + toString(this: i64, radix: i32 = 10): String { + return itoa64(this, radix); + } +} + +@final @unmanaged +export abstract class Isize { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: isize = isize.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: isize = isize.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): isize { + return strtol(value, radix); + } + + toString(this: isize, radix: i32 = 10): String { + if (sizeof() == 4) { + return itoa32(this, radix); + } else { + return itoa64(this, radix); + } + } +} + +@final @unmanaged +export abstract class U8 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: u8 = u8.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: u8 = u8.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): u8 { + return strtol(value, radix); + } + + toString(this: u8, radix: i32 = 10): String { + return utoa32(this, radix); + } +} + +@final @unmanaged +export abstract class U16 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: u16 = u16.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: u16 = u16.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): u16 { + return strtol(value, radix); + } + + toString(this: u16, radix: i32 = 10): String { + return utoa32(this, radix); + } +} + +@final @unmanaged +export abstract class U32 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: u32 = u32.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: u32 = u32.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): u32 { + return strtol(value, radix); + } + + toString(this: u32, radix: i32 = 10): String { + return utoa32(this, radix); + } +} + +@final @unmanaged +export abstract class U64 { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: u64 = u64.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: u64 = u64.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): u64 { + return strtol(value, radix); + } + + toString(this: u64, radix: i32 = 10): String { + return utoa64(this, radix); + } +} + +@final @unmanaged +export abstract class Usize { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: usize = usize.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: usize = usize.MAX_VALUE; + + static parseInt(value: string, radix: i32 = 0): usize { + return strtol(value, radix); + } + + toString(this: usize, radix: i32 = 10): String { + if (sizeof() == 4) { + return utoa32(this, radix); + } else { + return utoa64(this, radix); + } + } +} + +@final @unmanaged +export abstract class Bool { + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: bool = bool.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: bool = bool.MAX_VALUE; + + toString(this: bool, radix: i32 = 0): String { + return this ? "true" : "false"; + } +} + +export { Bool as Boolean }; + +@final @unmanaged +export abstract class F32 { + + // @ts-ignore: decorator + @lazy + static readonly EPSILON: f32 = f32.EPSILON; + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: f32 = f32.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: f32 = f32.MAX_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MIN_SAFE_INTEGER: f32 = f32.MIN_SAFE_INTEGER; + + // @ts-ignore: decorator + @lazy + static readonly MAX_SAFE_INTEGER: f32 = f32.MAX_SAFE_INTEGER; + + // @ts-ignore: decorator + @lazy + static readonly POSITIVE_INFINITY: f32 = f32.POSITIVE_INFINITY; + + // @ts-ignore: decorator + @lazy + static readonly NEGATIVE_INFINITY: f32 = f32.NEGATIVE_INFINITY; + + // @ts-ignore: decorator + @lazy + static readonly NaN: f32 = f32.NaN; + + static isNaN(value: f32): bool { + return isNaN(value); + } + + static isFinite(value: f32): bool { + return isFinite(value); + } + + static isSafeInteger(value: f32): bool { + return abs(value) <= f32.MAX_SAFE_INTEGER && trunc(value) == value; + } + + static isInteger(value: f32): bool { + return isFinite(value) && trunc(value) == value; + } + + static parseInt(value: string, radix: i32 = 0): f32 { + return strtol(value, radix); + } + + static parseFloat(value: string): f32 { + return parseFloat(value); + } + + toString(this: f32, radix: i32 = 0): String { + return dtoa(this); + } +} + +@final @unmanaged +export abstract class F64 { + + // @ts-ignore: decorator + @lazy + static readonly EPSILON: f64 = f64.EPSILON; + + // @ts-ignore: decorator + @lazy + static readonly MIN_VALUE: f64 = f64.MIN_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MAX_VALUE: f64 = f64.MAX_VALUE; + + // @ts-ignore: decorator + @lazy + static readonly MIN_SAFE_INTEGER: f64 = f64.MIN_SAFE_INTEGER; + + // @ts-ignore: decorator + @lazy + static readonly MAX_SAFE_INTEGER: f64 = f64.MAX_SAFE_INTEGER; + + // @ts-ignore: decorator + @lazy + static readonly POSITIVE_INFINITY: f64 = f64.POSITIVE_INFINITY; + + // @ts-ignore: decorator + @lazy + static readonly NEGATIVE_INFINITY: f64 = f64.NEGATIVE_INFINITY; + + // @ts-ignore: decorator + @lazy + static readonly NaN: f64 = f64.NaN; + + static isNaN(value: f64): bool { + return isNaN(value); + } + + static isFinite(value: f64): bool { + return isFinite(value); + } + + static isSafeInteger(value: f64): bool { + return abs(value) <= f64.MAX_SAFE_INTEGER && trunc(value) == value; + } + + static isInteger(value: f64): bool { + return isFinite(value) && trunc(value) == value; + } + + static parseInt(value: string, radix: i32 = 0): f64 { + return strtol(value, radix); + } + + static parseFloat(value: string): f64 { + return parseFloat(value); + } + + toString(this: f64, radix: i32 = 0): String { + return dtoa(this); + } +} + +export { F64 as Number }; +`,object:`export class Object { + static is(value1: T, value2: T): bool { + if (isFloat()) { + if (value1 == value2) { + // 0 == -0, but they are not identical + if (sizeof() == 8) { + // @ts-ignore: typecast + return reinterpret(value1) == reinterpret(value2); + } else { + // @ts-ignore: typecast + return reinterpret(value1) == reinterpret(value2); + } + } + // NaN != NaN, but they are identical. + // @ts-ignore: typecast + return bool(i32(isNaN(value1)) & i32(isNaN(value2))); + } + // For references, strings, integers and booleans + return value1 == value2; + } +} +`,performance:`import { + clock_time_get, + clockid, + errnoToString, + tempbuf +} from "bindings/wasi"; + +import { + performance as performance_binding +} from "bindings/dom"; + +export namespace performance { + export function now(): f64 { + if (isDefined(ASC_WASI)) { + let err = clock_time_get(clockid.MONOTONIC, 1000, tempbuf); // TODO: more precision? + if (err) throw new Error(errnoToString(err)); + return load(tempbuf) / 1000000; + } else { + return performance_binding.now(); + } + } +} +`,polyfills:`export function bswap(value: T): T { + if (isInteger()) { + if (sizeof() == 1) { + return value; + } + if (sizeof() == 2) { + return (value << 8 | (value >> 8)); + } + if (sizeof() == 4) { + return ( + rotl(value & 0xFF00FF00, 8) | + rotr(value & 0x00FF00FF, 8) + ); + } + if (sizeof() == 8) { + let a = (value >> 8) & 0x00FF00FF00FF00FF; + let b = (value & 0x00FF00FF00FF00FF) << 8; + let v = a | b; + + a = (v >>> 16) & 0x0000FFFF0000FFFF; + b = (v & 0x0000FFFF0000FFFF) << 16; + + return rotr(a | b, 32); + } + } + ERROR("Unsupported generic type"); +} + +export function bswap16(value: T): T { + if (isInteger()) { + if (sizeof() == 1) { + return value; + } + if (sizeof() == 2) { + return (value << 8 | (value >> 8)); + } + if (sizeof() == 4) { + return ( + (((value & 0xFF) << 8)) | + ((value >> 8) & 0xFF) | + (value & 0xFFFF0000) + ); + } + } + ERROR("Unsupported generic type"); +} +`,process:`import { + args_get, + args_sizes_get, + environ_get, + environ_sizes_get, + proc_exit, + fd_write, + fd_close, + fd_read, + clock_time_get, + clockid, + errnoToString, + fd, + tempbuf +} from "bindings/wasi"; + +import { + Date as Date_binding, + performance as performance_binding +} from "bindings/dom"; + +import { + process as process_binding +} from "bindings/node"; + +import { + E_INDEXOUTOFRANGE +} from "util/error"; + +export namespace process { + + // @ts-ignore: decorator + @lazy export const arch = sizeof() == 4 ? "wasm32" : "wasm64"; + + // @ts-ignore: decorator + @lazy export const platform = "wasm"; + + // @ts-ignore: decorator + @lazy export const argv = lazyArgv(); + + // @ts-ignore: decorator + @lazy export const env = lazyEnv(); + + // @ts-ignore: decorator + @lazy export var exitCode = 0; + + export function exit(code: i32 = exitCode): void { + if (isDefined(ASC_WASI)) { + proc_exit(code); + } else { + process_binding.exit(code); + } + } + + // @ts-ignore: decorator + @lazy export const stdin = changetype(0); + // @ts-ignore: decorator + @lazy export const stdout = changetype(1); + // @ts-ignore: decorator + @lazy export const stderr = changetype(2); + + export function time(): i64 { + if (isDefined(ASC_WASI)) { + let err = clock_time_get(clockid.REALTIME, 1000000, tempbuf); + if (err) throw new Error(errnoToString(err)); + return load(tempbuf) / 1000000; + } else { + return Date_binding.now(); + } + } + + export function hrtime(): u64 { + if (isDefined(ASC_WASI)) { + let err = clock_time_get(clockid.MONOTONIC, 0, tempbuf); + if (err) throw new Error(errnoToString(err)); + return load(tempbuf); + } else { + let now = performance_binding.now(); + let millis = now; + let fraction = now - millis; + return millis * 1000000 + (fraction * 1000000); + } + } +} + +function lazyArgv(): string[] { + if (isDefined(ASC_WASI)) { + let err = args_sizes_get(tempbuf, tempbuf + sizeof()); + if (err) throw new Error(errnoToString(err)); + let count = load(tempbuf); + let ptrsSize = count * sizeof(); + let dataSize = load(tempbuf, sizeof()); + let bufSize = ptrsSize + dataSize; + let buf = __alloc(bufSize); + err = args_get(buf, buf + ptrsSize); + if (err) throw new Error(errnoToString(err)); + let count32 = count; + let argv = new Array(count32); + for (let i = 0; i < count32; ++i) { + let ptr = load(buf + i * sizeof()); + let str = String.UTF8.decodeUnsafe(ptr, ptr + bufSize - buf, true); + argv[i] = str; + } + __free(buf); + return argv; + } else { + return process_binding.argv; + } +} + +function lazyEnv(): Map { + if (isDefined(ASC_WASI)) { + let err = environ_sizes_get(tempbuf, tempbuf + 4); + if (err) throw new Error(errnoToString(err)); + let count = load(tempbuf); + let ptrsSize = count * sizeof(); + let dataSize = load(tempbuf, sizeof()); + let bufSize = ptrsSize + dataSize; + let buf = __alloc(bufSize); + err = environ_get(buf, buf + ptrsSize); + if (err) throw new Error(errnoToString(err)); + let env = new Map(); + for (let i: usize = 0; i < count; ++i) { + let ptr = load(buf + i * sizeof()); + let str = String.UTF8.decodeUnsafe(ptr, ptr + bufSize - buf, true); + let pos = str.indexOf("="); + if (~pos) { + env.set(str.substring(0, pos), str.substring(pos + 1)); + // __dispose(changetype(str)); + } else { + env.set(str, ""); + } + } + __free(buf); + return env; + } else { + // TODO: What about Node? + return new Map(); + } +} + +@unmanaged +abstract class Stream { + close(): void { + var err = fd_close(changetype(this)); + if (err) throw new Error(errnoToString(err)); + } +} + +@unmanaged +abstract class WritableStream extends Stream { + write(data: T): void { + if (isString()) { + writeString(changetype(this), changetype(data)); + } else if (data instanceof ArrayBuffer) { + writeBuffer(changetype(this), data); + } else { + ERROR("String or ArrayBuffer expected"); + } + } +} + +@unmanaged +abstract class ReadableStream extends Stream { + read(buffer: ArrayBuffer, offset: isize = 0): i32 { + var end = buffer.byteLength; + if (offset < 0 || offset > end) { + throw new Error(E_INDEXOUTOFRANGE); + } + store(tempbuf, changetype(buffer) + offset); + store(tempbuf, end - offset, sizeof()); + var err = fd_read(changetype(this), tempbuf, 1, tempbuf + 2 * sizeof()); + if (err) throw new Error(errnoToString(err)); + return load(tempbuf, 2 * sizeof()); + } +} + +function writeBuffer(fd: fd, data: ArrayBuffer): void { + store(tempbuf, changetype(data)); + store(tempbuf, data.byteLength, sizeof()); + var err = fd_write(fd, tempbuf, 1, tempbuf + 2 * sizeof()); + if (err) throw new Error(errnoToString(err)); +} + +function writeString(fd: fd, data: string): void { + var len = data.length; + var + char2: u32 = 0, + char3: u32 = 0, + char4: u32 = 0; + switch (len) { + case 4: { // "null" + char4 = load(changetype(data), 6); + if (char4 >= 0x80) break; + } + case 3: { // "ms\\n" + char3 = load(changetype(data), 4); + if (char3 >= 0x80) break; + } + case 2: { // "\\r\\n" + char2 = load(changetype(data), 2); + if (char2 >= 0x80) break; + } + case 1: { // "\\n" + let char1 = load(changetype(data)); + if (char1 >= 0x80) break; + store(tempbuf, tempbuf + 2 * sizeof()); + store(tempbuf, len, sizeof()); + store(tempbuf, char1 | char2 << 8 | char3 << 16 | char4 << 24, 2 * sizeof()); + let err = fd_write(fd, tempbuf, 1, tempbuf + 3 * sizeof()); + if (err) throw new Error(errnoToString(err)); + } + case 0: return; + } + var utf8len = String.UTF8.byteLength(data); + var utf8buf = __alloc(utf8len); + assert(String.UTF8.encodeUnsafe(changetype(data), len, utf8buf) == utf8len); + store(tempbuf, utf8buf); + store(tempbuf, utf8len, sizeof()); + var err = fd_write(fd, tempbuf, 1, tempbuf + 2 * sizeof()); + __free(utf8buf); + if (err) throw new Error(errnoToString(err)); +} +`,reference:`@unmanaged +abstract class Ref { +} + +@final @unmanaged +export abstract class Funcref extends Ref { +} + +@final @unmanaged +export abstract class Externref extends Ref { +} + +@final @unmanaged +export abstract class Anyref extends Ref { +} + +@final @unmanaged +export abstract class Eqref extends Ref { +} + +@final @unmanaged +export abstract class I31ref extends Ref { +} + +@final @unmanaged +export abstract class Dataref extends Ref { +} +`,regexp:`export class RegExp { + + // @binding(CALL_NEW, [ STRING, STRING], OBJECT_HANDLE) + constructor(pattern: string, flags: string = "") { throw new Error("unreachable"); } + + // @binding(CALL_THIS, [ STRING ], PASS_THRU) + test(search: string): bool { throw new Error("unreachable"); } + + // @binding(CALL_THIS, [], STRING) + toString(): string { throw new Error("unreachable"); } + +} +`,rt:`import { Typeinfo, TypeinfoFlags } from "./shared/typeinfo"; +import { E_INDEXOUTOFRANGE } from "./util/error"; +import { OBJECT, TOTAL_OVERHEAD } from "./rt/common"; +import { ArrayBufferView } from "./arraybuffer"; + +// @ts-ignore: decorator +@builtin +export declare const __rtti_base: usize; + +// @ts-ignore: decorator +@builtin @unsafe +export declare function __visit_globals(cookie: u32): void; + +// @ts-ignore: decorator +@builtin @unsafe +export declare function __visit_members(ref: usize, cookie: u32): void; + +// @ts-ignore: decorator +@unsafe +export function __typeinfo(id: u32): TypeinfoFlags { + var ptr = __rtti_base; + if (id > load(ptr)) throw new Error(E_INDEXOUTOFRANGE); + return changetype(ptr + sizeof() + id * offsetof()).flags; +} + +// @ts-ignore: decorator +@unsafe +export function __instanceof(ptr: usize, classId: u32): bool { // keyword + var id = changetype(ptr - TOTAL_OVERHEAD).rtId; + var rttiBase = __rtti_base; + if (id <= load(rttiBase)) { + do if (id == classId) return true; + while (id = changetype(rttiBase + sizeof() + id * offsetof()).base); + } + return false; +} + +// @ts-ignore: decorator +@unsafe +export function __newBuffer(size: usize, id: u32, data: usize = 0): usize { + var buffer = __new(size, id); + if (data) memory.copy(buffer, data, size); + return buffer; +} + +// @ts-ignore: decorator +@unsafe +export function __newArray(length: i32, alignLog2: usize, id: u32, data: usize = 0): usize { + var bufferSize = length << alignLog2; + // make sure \`buffer\` is tracked by the shadow stack + var buffer = changetype(__newBuffer(bufferSize, idof(), data)); + // ...since allocating the array may trigger GC steps + var array = __new(offsetof(), id); + store(array, changetype(buffer), offsetof("buffer")); + __link(array, changetype(buffer), false); + store(array, changetype(buffer), offsetof("dataStart")); + store(array, bufferSize, offsetof("byteLength")); + store(array, length, offsetof("length_")); + return array; +} + +// @ts-ignore: decorator +@global @unsafe +function __tostack(ptr: usize): usize { // eslint-disable-line + return ptr; +} + +// These are provided by the respective implementation, included as another entry file by asc: + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __alloc(size: usize): usize; + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __realloc(ptr: usize, size: usize): usize; + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __free(ptr: usize): void; + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __new(size: usize, id: u32): usize; + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __renew(ptr: usize, size: usize): usize; + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __link(parentPtr: usize, childPtr: usize, expectMultiple: bool): void; + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __collect(): void; + +// // @ts-ignore: decorator +// @builtin @unsafe +// export declare function __visit(ptr: usize, cookie: u32): void; +`,"rt/common":`// Alignment guarantees + +// @ts-ignore: decorator +@inline export const AL_BITS: u32 = 4; // 16 bytes to fit up to v128 +// @ts-ignore: decorator +@inline export const AL_SIZE: usize = 1 << AL_BITS; +// @ts-ignore: decorator +@inline export const AL_MASK: usize = AL_SIZE - 1; + +// Extra debugging + +// @ts-ignore: decorator +@inline export const DEBUG = true; +// @ts-ignore: decorator +@inline export const TRACE = false; +// @ts-ignore: decorator +@inline export const RTRACE = isDefined(ASC_RTRACE); +// @ts-ignore: decorator +@inline export const PROFILE = isDefined(ASC_PROFILE); + +// Memory manager + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Memory manager block layout (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 +// \u2502 MM info \u2502 -4 +// \u255E>ptr\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 +// \u2502 ... \u2502 +@unmanaged export class BLOCK { + /** Memory manager info. */ + mmInfo: usize; +} + +/** Overhead of a memory manager block. */ +// @ts-ignore: decorator +@inline export const BLOCK_OVERHEAD: usize = offsetof(); + +/** Maximum size of a memory manager block's payload. */ +// @ts-ignore: decorator +@inline export const BLOCK_MAXSIZE: usize = (1 << 30) - BLOCK_OVERHEAD; + +// Garbage collector + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Garbage collector object layout (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 +// \u2502 Memory manager block \u2502 -20 +// \u255E\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 +// \u2502 GC info \u2502 -16 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 GC info \u2502 -12 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 RT id \u2502 -8 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 RT size \u2502 -4 +// \u255E>ptr\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 +// \u2502 ... \u2502 +@unmanaged export class OBJECT extends BLOCK { + /** Garbage collector info. */ + gcInfo: u32; + /** Garbage collector info. */ + gcInfo2: u32; + /** Runtime class id. */ + rtId: u32; + /** Runtime object size. */ + rtSize: u32; +} + +/** Overhead of a garbage collector object. Excludes memory manager block overhead. */ +// @ts-ignore: decorator +@inline export const OBJECT_OVERHEAD: usize = (offsetof() - BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK; + +/** Maximum size of a garbage collector object's payload. */ +// @ts-ignore: decorator +@inline export const OBJECT_MAXSIZE: usize = BLOCK_MAXSIZE - OBJECT_OVERHEAD; + +/** Total of memory manager and garbage collector overhead. */ +// @ts-ignore: decorator +@inline export const TOTAL_OVERHEAD: usize = BLOCK_OVERHEAD + OBJECT_OVERHEAD; +`,"rt/index-incremental":`import "rt/tlsf"; +import "rt/itcms"; +`,"rt/index-minimal":`import "rt/tlsf"; +import "rt/tcms"; +`,"rt/index-stub":`import "rt/stub"; +`,"rt/itcms":`import { BLOCK, BLOCK_OVERHEAD, OBJECT_OVERHEAD, OBJECT_MAXSIZE, TOTAL_OVERHEAD, DEBUG, TRACE, RTRACE, PROFILE } from "./common"; +import { onvisit, oncollect, oninterrupt, onyield } from "./rtrace"; +import { TypeinfoFlags } from "../shared/typeinfo"; +import { E_ALLOCATION_TOO_LARGE, E_ALREADY_PINNED, E_NOT_PINNED } from "../util/error"; + +// === ITCMS: An incremental Tri-Color Mark & Sweep garbage collector === +// Adapted from Bach Le's \u03BCgc, see: https://github.com/bullno1/ugc + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Colors \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// \u2502 Color \u2502 Meaning \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 WHITE* \u2502 Unprocessed \u2502 +// \u2502 BLACK* \u2502 Processed \u2502 +// \u2502 GRAY \u2502 Processed with unprocessed children \u2502 +// \u2502 TRANSPARENT \u2502 Manually pinned (always reachable) \u2502 +// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 +// * flipped between cycles + +// @ts-ignore: decorator +@lazy var white = 0; +// @ts-ignore: decorator +@inline const gray = 2; +// @ts-ignore: decorator +@inline const transparent = 3; +// @ts-ignore: decorator +@inline const COLOR_MASK = 3; + +/** Size in memory of all objects currently managed by the GC. */ +// @ts-ignore: decorator +@lazy var total: usize = 0; + +/** Currently transitioning from SWEEP to MARK state. */ +// @ts-ignore: decorator +@inline const STATE_IDLE = 0; +/** Currently marking reachable objects. */ +// @ts-ignore: decorator +@inline const STATE_MARK = 1; +/** Currently sweeping unreachable objects. */ +// @ts-ignore: decorator +@inline const STATE_SWEEP = 2; +/** Current collector state. */ +// @ts-ignore: decorator +@lazy var state = STATE_IDLE; + +// @ts-ignore: decorator +@lazy var fromSpace = initLazy(changetype(memory.data(offsetof()))); +// @ts-ignore: decorator +@lazy var toSpace = initLazy(changetype(memory.data(offsetof()))); +// @ts-ignore: decorator +@lazy var pinSpace = initLazy(changetype(memory.data(offsetof()))); +// @ts-ignore: decorator +@lazy var iter: Object; // null + +function initLazy(space: Object): Object { + space.nextWithColor = changetype(space); + space.prev = space; + return space; +} + +/** Visit cookie indicating scanning of an object. */ +// @ts-ignore: decorator +@inline const VISIT_SCAN = 0; + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Managed object layout (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 +// \u2502 Memory manager block \u2502 +// \u255E\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2561 +// \u2502 next \u2502 C \u2502 = nextWithColor +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2524 +// \u2502 prev \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 rtId \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 rtSize \u2502 +// \u255E>ptr\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 +// \u2502 ... \u2502 +// C: color + +/** Represents a managed object in memory, consisting of a header followed by the object's data. */ +@unmanaged class Object extends BLOCK { + /** Pointer to the next object with color flags stored in the alignment bits. */ + nextWithColor: usize; // *u32 + /** Pointer to the previous object. */ + prev: Object; // *u32 + /** Runtime id. */ + rtId: u32; + /** Runtime size. */ + rtSize: u32; + + /** Gets the pointer to the next object. */ + get next(): Object { + return changetype(this.nextWithColor & ~COLOR_MASK); + } + + /** Sets the pointer to the next object. */ + set next(obj: Object) { + this.nextWithColor = changetype(obj) | (this.nextWithColor & COLOR_MASK); + } + + /** Gets this object's color. */ + get color(): i32 { + return i32(this.nextWithColor & COLOR_MASK); + } + + /** Sets this object's color. */ + set color(color: i32) { + this.nextWithColor = (this.nextWithColor & ~COLOR_MASK) | color; + } + + /** Gets the size of this object in memory. */ + get size(): usize { + return BLOCK_OVERHEAD + (this.mmInfo & ~3); + } + + /** Tests if this object is pointerfree. */ + get isPointerfree(): bool { + var rtId = this.rtId; + return rtId <= idof() || (__typeinfo(rtId) & TypeinfoFlags.POINTERFREE) != 0; + } + + /** Unlinks this object from its list. */ + unlink(): void { + var next = this.next; + if (next == null) { + if (DEBUG) assert(this.prev == null && changetype(this) < __heap_base); + return; // static data not yet linked + } + var prev = this.prev; + if (DEBUG) assert(prev); + next.prev = prev; + prev.next = next; + } + + /** Links this object to the specified list, with the given color. */ + linkTo(list: Object, withColor: i32): void { + let prev = list.prev; + this.nextWithColor = changetype(list) | withColor; + this.prev = prev; + prev.next = this; + list.prev = this; + } + + /** Marks this object as gray, that is reachable with unscanned children. */ + makeGray(): void { + if (this == iter) iter = assert(this.prev); + this.unlink(); + this.linkTo(toSpace, this.isPointerfree ? i32(!white) : gray); + } +} + +/** Visits all objects considered to be program roots. */ +function visitRoots(cookie: u32): void { + __visit_globals(cookie); + var pn = pinSpace; + var iter = pn.next; + while (iter != pn) { + if (DEBUG) assert(iter.color == transparent); + __visit_members(changetype(iter) + TOTAL_OVERHEAD, cookie); + iter = iter.next; + } +} + +/** Visits all objects on the stack. */ +function visitStack(cookie: u32): void { + var ptr = __stack_pointer; + while (ptr < __heap_base) { + __visit(load(ptr), cookie); + ptr += sizeof(); + } +} + +/** Performs a single step according to the current state. */ +function step(): usize { + // Magic constants responsible for pause times. Obtained experimentally + // using the compiler compiling itself. 2048 budget pro run by default. + const MARKCOST = isDefined(ASC_GC_MARKCOST) ? ASC_GC_MARKCOST : 1; + const SWEEPCOST = isDefined(ASC_GC_SWEEPCOST) ? ASC_GC_SWEEPCOST : 10; + var obj: Object; + switch (state) { + case STATE_IDLE: { + state = STATE_MARK; + visitCount = 0; + visitRoots(VISIT_SCAN); + iter = toSpace; + return visitCount * MARKCOST; + } + case STATE_MARK: { + let black = i32(!white); + obj = iter.next; + while (obj != toSpace) { + iter = obj; + if (obj.color != black) { // skip already-blacks (pointerfree) + obj.color = black; + visitCount = 0; + __visit_members(changetype(obj) + TOTAL_OVERHEAD, VISIT_SCAN); + return visitCount * MARKCOST; + } + obj = obj.next; + } + visitCount = 0; + visitRoots(VISIT_SCAN); + obj = iter.next; + if (obj == toSpace) { + visitStack(VISIT_SCAN); + obj = iter.next; + while (obj != toSpace) { + if (obj.color != black) { + obj.color = black; + __visit_members(changetype(obj) + TOTAL_OVERHEAD, VISIT_SCAN); + } + obj = obj.next; + } + let from = fromSpace; + fromSpace = toSpace; + toSpace = from; + white = black; + iter = from.next; + state = STATE_SWEEP; + } + return visitCount * MARKCOST; + } + case STATE_SWEEP: { + obj = iter; + if (obj != toSpace) { + iter = obj.next; + if (DEBUG) assert(obj.color == i32(!white)); // old white + free(obj); + return SWEEPCOST; + } + toSpace.nextWithColor = changetype(toSpace); + toSpace.prev = toSpace; + state = STATE_IDLE; + break; + } + } + return 0; +} + +/** Frees an object. */ +function free(obj: Object): void { + if (changetype(obj) < __heap_base) { + obj.nextWithColor = 0; // may become linked again + obj.prev = changetype(0); + } else { + total -= obj.size; + if (isDefined(__finalize)) { + __finalize(changetype(obj) + TOTAL_OVERHEAD); + } + __free(changetype(obj) + BLOCK_OVERHEAD); + } +} + +// Garbage collector interface + +// @ts-ignore: decorator +@global @unsafe +export function __new(size: usize, id: i32): usize { + if (size >= OBJECT_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + if (total >= threshold) interrupt(); + var obj = changetype(__alloc(OBJECT_OVERHEAD + size) - BLOCK_OVERHEAD); + obj.rtId = id; + obj.rtSize = size; + obj.linkTo(fromSpace, white); // inits next/prev + total += obj.size; + var ptr = changetype(obj) + TOTAL_OVERHEAD; + // may be visited before being fully initialized, so must fill + memory.fill(ptr, 0, size); + return ptr; +} + +// @ts-ignore: decorator +@global @unsafe +export function __renew(oldPtr: usize, size: usize): usize { + var oldObj = changetype(oldPtr - TOTAL_OVERHEAD); + // Update object size if its block is large enough + if (size <= (oldObj.mmInfo & ~3) - OBJECT_OVERHEAD) { + oldObj.rtSize = size; + return oldPtr; + } + // If not the same object anymore, we have to move it move it due to the + // shadow stack potentially still referencing the old object + var newPtr = __new(size, oldObj.rtId); + memory.copy(newPtr, oldPtr, min(size, oldObj.rtSize)); + return newPtr; +} + +// @ts-ignore: decorator +@global @unsafe +export function __link(parentPtr: usize, childPtr: usize, expectMultiple: bool): void { + // Write barrier is unnecessary if non-incremental + if (!childPtr) return; + if (DEBUG) assert(parentPtr); + var child = changetype(childPtr - TOTAL_OVERHEAD); + if (child.color == white) { + let parent = changetype(parentPtr - TOTAL_OVERHEAD); + let parentColor = parent.color; + if (parentColor == i32(!white)) { + // Maintain the invariant that no black object may point to a white object. + if (expectMultiple) { + // Move the barrier "backward". Suitable for containers receiving multiple stores. + // Avoids a barrier for subsequent objects stored into the same container. + parent.makeGray(); + } else { + // Move the barrier "forward". Suitable for objects receiving isolated stores. + child.makeGray(); + } + } else if (parentColor == transparent && state == STATE_MARK) { + // Pinned objects are considered 'black' during the mark phase. + child.makeGray(); + } + } +} + +// @ts-ignore: decorator +@lazy var visitCount = 0; + +// @ts-ignore: decorator +@global @unsafe +export function __visit(ptr: usize, cookie: i32): void { + if (!ptr) return; + let obj = changetype(ptr - TOTAL_OVERHEAD); + if (RTRACE) if (!onvisit(obj)) return; + if (obj.color == white) { + obj.makeGray(); + ++visitCount; + } +} + +// @ts-ignore: decorator +@global @unsafe +export function __pin(ptr: usize): usize { + if (ptr) { + let obj = changetype(ptr - TOTAL_OVERHEAD); + if (obj.color == transparent) { + throw new Error(E_ALREADY_PINNED); + } + obj.unlink(); // from fromSpace + obj.linkTo(pinSpace, transparent); + } + return ptr; +} + +// @ts-ignore: decorator +@global @unsafe +export function __unpin(ptr: usize): void { + if (!ptr) return; + var obj = changetype(ptr - TOTAL_OVERHEAD); + if (obj.color != transparent) { + throw new Error(E_NOT_PINNED); + } + if (state == STATE_MARK) { + // We may be right at the point after marking roots for the second time and + // entering the sweep phase, in which case the object would be missed if it + // is not only pinned but also a root. Make sure it isn't missed. + obj.makeGray(); + } else { + obj.unlink(); + obj.linkTo(fromSpace, white); + } +} + +// @ts-ignore: decorator +@global @unsafe +export function __collect(): void { + if (TRACE) trace("GC (full) at", 1, total); + if (state > STATE_IDLE) { + // finish current cycle + while (state != STATE_IDLE) step(); + } + // perform a full cycle + step(); + while (state != STATE_IDLE) step(); + threshold = (total * IDLEFACTOR / 100) + GRANULARITY; + if (TRACE) trace("GC (full) done at cur/max", 2, total, memory.size() << 16); + if (RTRACE || PROFILE) oncollect(total); +} + +// Garbage collector automation + +/** How often to interrupt. The default of 1024 means "interrupt each 1024 bytes allocated". */ +// @ts-ignore: decorator +@inline const GRANULARITY: usize = isDefined(ASC_GC_GRANULARITY) ? ASC_GC_GRANULARITY : 1024; +/** How long to interrupt. The default of 200% means "run at double the speed of allocations". */ +// @ts-ignore: decorator +@inline const STEPFACTOR: usize = isDefined(ASC_GC_SWEEPFACTOR) ? ASC_GC_SWEEPFACTOR : 200; +/** How long to idle. The default of 200% means "wait for memory to double before kicking in again". */ +// @ts-ignore: decorator +@inline const IDLEFACTOR: usize = isDefined(ASC_GC_IDLEFACTOR) ? ASC_GC_IDLEFACTOR : 200; + +/** Threshold of memory used by objects to exceed before interrupting again. */ +// @ts-ignore: decorator +@lazy var threshold: usize = ((memory.size() << 16) - __heap_base) >> 1; + +/** Performs a reasonable amount of incremental GC steps. */ +function interrupt(): void { + if (PROFILE) oninterrupt(total); + if (TRACE) trace("GC (auto) at", 1, total); + var budget: isize = GRANULARITY * STEPFACTOR / 100; + do { + budget -= step(); + if (state == STATE_IDLE) { + if (TRACE) trace("\u2514 GC (auto) done at cur/max", 2, total, memory.size() << 16); + threshold = (total * IDLEFACTOR / 100) + GRANULARITY; + if (PROFILE) onyield(total); + return; + } + } while (budget > 0); + if (TRACE) trace("\u2514 GC (auto) ongoing at", 1, total); + threshold = total + GRANULARITY * usize(total - threshold < GRANULARITY); + if (PROFILE) onyield(total); +} +`,"rt/rtrace":`import { BLOCK } from "./common"; + +export declare function oninit(heapBase: usize): void; + +// Memory Allocator +export declare function onalloc(block: BLOCK): void; +export declare function onresize(block: BLOCK, oldSizeInclOverhead: usize): void; +export declare function onmove(oldBlock: BLOCK, newBlock: BLOCK): void; +export declare function onfree(block: BLOCK): void; + +// Garbage collector +export declare function onvisit(block: BLOCK): bool; +export declare function oncollect(total: usize): void; +export declare function oninterrupt(total: usize): void; +export declare function onyield(total: usize): void; +`,"rt/stub":`import { AL_MASK, OBJECT, OBJECT_OVERHEAD, BLOCK_MAXSIZE, BLOCK_OVERHEAD, BLOCK, OBJECT_MAXSIZE } from "./common"; +import { E_ALLOCATION_TOO_LARGE } from "../util/error"; + +// === A minimal runtime stub === + +// @ts-ignore: decorator +@lazy var startOffset: usize = ((__heap_base + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD; +// @ts-ignore: decorator +@lazy var offset: usize = startOffset; + +function maybeGrowMemory(newOffset: usize): void { + // assumes newOffset is aligned + var pagesBefore = memory.size(); + var maxOffset = ((pagesBefore << 16) + AL_MASK) & ~AL_MASK; + if (newOffset > maxOffset) { + let pagesNeeded = (((newOffset - maxOffset + 0xffff) & ~0xffff) >>> 16); + let pagesWanted = max(pagesBefore, pagesNeeded); // double memory + if (memory.grow(pagesWanted) < 0) { + if (memory.grow(pagesNeeded) < 0) unreachable(); // out of memory + } + } + offset = newOffset; +} + +// @ts-ignore: decorator +@inline function computeSize(size: usize): usize { + return ((size + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD; +} + +// @ts-ignore: decorator +@unsafe @global +export function __alloc(size: usize): usize { + if (size > BLOCK_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + var block = changetype(offset); + var ptr = offset + BLOCK_OVERHEAD; + var payloadSize = computeSize(size); + maybeGrowMemory(ptr + payloadSize); + block.mmInfo = payloadSize; + return ptr; +} + +// @ts-ignore: decorator +@unsafe @global +export function __realloc(ptr: usize, size: usize): usize { + assert(ptr != 0 && !(ptr & AL_MASK)); // must exist and be aligned + var block = changetype(ptr - BLOCK_OVERHEAD); + var actualSize = block.mmInfo; + var isLast = ptr + actualSize == offset; + var payloadSize = computeSize(size); + if (size > actualSize) { + if (isLast) { // last block: grow + if (size > BLOCK_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + maybeGrowMemory(ptr + payloadSize); + block.mmInfo = payloadSize; + } else { // copy to new block at least double the size + let newPtr = __alloc(max(payloadSize, actualSize << 1)); + memory.copy(newPtr, ptr, actualSize); + block = changetype((ptr = newPtr) - BLOCK_OVERHEAD); + } + } else if (isLast) { // last block: shrink + offset = ptr + payloadSize; + block.mmInfo = payloadSize; + } + return ptr; +} + +// @ts-ignore: decorator +@unsafe @global +export function __free(ptr: usize): void { + assert(ptr != 0 && !(ptr & AL_MASK)); // must exist and be aligned + var block = changetype(ptr - BLOCK_OVERHEAD); + if (ptr + block.mmInfo == offset) { // last block: discard + offset = changetype(block); + } +} + +// @ts-ignore: decorator +@unsafe @global +export function __reset(): void { // special + offset = startOffset; +} + +// @ts-ignore: decorator +@unsafe @global +export function __new(size: usize, id: u32): usize { + if (size > OBJECT_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + var ptr = __alloc(OBJECT_OVERHEAD + size); + var object = changetype(ptr - BLOCK_OVERHEAD); + object.gcInfo = 0; + object.gcInfo2 = 0; + object.rtId = id; + object.rtSize = size; + return ptr + OBJECT_OVERHEAD; +} + +// @ts-ignore: decorator +@unsafe @global +export function __renew(oldPtr: usize, size: usize): usize { + if (size > OBJECT_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + var newPtr = __realloc(oldPtr - OBJECT_OVERHEAD, OBJECT_OVERHEAD + size); + changetype(newPtr - BLOCK_OVERHEAD).rtSize = size; + return newPtr + OBJECT_OVERHEAD; +} + +// @ts-ignore: decorator +@global @unsafe +export function __link(parentPtr: usize, childPtr: usize, expectMultiple: bool): void { + // nop +} + +// @ts-ignore: decorator +@global @unsafe +export function __pin(ptr: usize): usize { + return ptr; +} + +// @ts-ignore: decorator +@global @unsafe +export function __unpin(ptr: usize): void { + // nop +} + +// @ts-ignore: decorator +@global @unsafe +function __visit(ptr: usize, cookie: u32): void { // eslint-disable-line @typescript-eslint/no-unused-vars + // nop +} + +// @ts-ignore: decorator +@global @unsafe +export function __collect(): void { + // nop +} +`,"rt/tcms":`import { BLOCK, BLOCK_OVERHEAD, OBJECT_OVERHEAD, OBJECT_MAXSIZE, TOTAL_OVERHEAD, DEBUG, TRACE, RTRACE } from "./common"; +import { onvisit, oncollect } from "./rtrace"; +import { E_ALLOCATION_TOO_LARGE, E_ALREADY_PINNED, E_NOT_PINNED } from "../util/error"; + +// === TCMS: A Two-Color Mark & Sweep garbage collector === + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Colors \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// \u2502 Color \u2502 Meaning \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 WHITE* \u2502 Unreachable \u2502 +// \u2502 BLACK* \u2502 Reachable \u2502 +// \u2502 TRANSPARENT \u2502 Manually pinned (always reachable) \u2502 +// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 +// * flipped between cycles + +// @ts-ignore: decorator +@lazy var white = 0; +// @ts-ignore: decorator +@inline const transparent = 3; +// @ts-ignore: decorator +@inline const COLOR_MASK = 3; + +/** Size in memory of all objects currently managed by the GC. */ +// @ts-ignore: decorator +@lazy var total: usize = 0; + +// @ts-ignore: decorator +@lazy var fromSpace = initLazy(changetype(memory.data(offsetof()))); +// @ts-ignore: decorator +@lazy var toSpace = initLazy(changetype(memory.data(offsetof()))); +// @ts-ignore: decorator +@lazy var pinSpace = initLazy(changetype(memory.data(offsetof()))); + +function initLazy(space: Object): Object { + space.nextWithColor = changetype(space); + space.prev = space; + return space; +} + +/** Visit cookie indicating scanning of an object. */ +// @ts-ignore: decorator +@inline const VISIT_SCAN = 0; + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Managed object layout (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 +// \u2502 Memory manager block \u2502 +// \u255E\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2561 +// \u2502 next \u2502 C \u2502 = nextWithColor +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2524 +// \u2502 prev \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 rtId \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 rtSize \u2502 +// \u255E>ptr\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 +// \u2502 ... \u2502 +// C: color + +/** Represents a managed object in memory, consisting of a header followed by the object's data. */ +@unmanaged class Object extends BLOCK { + /** Pointer to the next object with color flags stored in the alignment bits. */ + nextWithColor: usize; // *u32 + /** Pointer to the previous object. */ + prev: Object; // *u32 + /** Runtime id. */ + rtId: u32; + /** Runtime size. */ + rtSize: u32; + + /** Gets the pointer to the next object. */ + get next(): Object { + return changetype(this.nextWithColor & ~COLOR_MASK); + } + + /** Sets the pointer to the next object. */ + set next(obj: Object) { + this.nextWithColor = changetype(obj) | (this.nextWithColor & COLOR_MASK); + } + + /** Gets this object's color. */ + get color(): i32 { + return i32(this.nextWithColor & COLOR_MASK); + } + + /** Sets this object's color. */ + set color(color: i32) { + this.nextWithColor = (this.nextWithColor & ~COLOR_MASK) | color; + } + + /** Gets the size of this object in memory. */ + get size(): usize { + return BLOCK_OVERHEAD + (this.mmInfo & ~3); + } + + /** Unlinks this object from its list. */ + unlink(): void { + let next = this.next; + if (next == null) { + if (DEBUG) assert(this.prev == null && changetype(this) < __heap_base); + return; // static data not yet linked + } + let prev = this.prev; + if (DEBUG) assert(prev); + next.prev = prev; + prev.next = next; + } + + /** Links this object to the specified list, with the given color. */ + linkTo(list: Object, withColor: i32): void { + let prev = list.prev; + this.nextWithColor = changetype(list) | withColor; + this.prev = prev; + prev.next = this; + list.prev = this; + } +} + +// Garbage collector interface + +// @ts-ignore: decorator +@global @unsafe +export function __new(size: usize, id: i32): usize { + if (size > OBJECT_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + var obj = changetype(__alloc(OBJECT_OVERHEAD + size) - BLOCK_OVERHEAD); + obj.rtId = id; + obj.rtSize = size; + obj.linkTo(fromSpace, white); + total += obj.size; + return changetype(obj) + TOTAL_OVERHEAD; +} + +// @ts-ignore: decorator +@global @unsafe +export function __renew(oldPtr: usize, size: usize): usize { + var oldObj = changetype(oldPtr - TOTAL_OVERHEAD); + if (oldPtr < __heap_base) { // move to heap for simplicity + let newPtr = __new(size, oldObj.rtId); + memory.copy(newPtr, oldPtr, min(size, oldObj.rtSize)); + return newPtr; + } + if (size > OBJECT_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + total -= oldObj.size; + var newPtr = __realloc(oldPtr - OBJECT_OVERHEAD, OBJECT_OVERHEAD + size) + OBJECT_OVERHEAD; + var newObj = changetype(newPtr - TOTAL_OVERHEAD); + newObj.rtSize = size; + + // Replace with new object + newObj.next.prev = newObj; + newObj.prev.next = newObj; + + total += newObj.size; + return newPtr; +} + +// @ts-ignore: decorator +@global @unsafe +export function __link(parentPtr: usize, childPtr: usize, expectMultiple: bool): void { + // nop +} + +// @ts-ignore: decorator +@global @unsafe +export function __visit(ptr: usize, cookie: i32): void { + if (!ptr) return; + let obj = changetype(ptr - TOTAL_OVERHEAD); + if (RTRACE) if (!onvisit(obj)) return; + if (obj.color == white) { + obj.unlink(); // from fromSpace + obj.linkTo(toSpace, i32(!white)); + } +} + +// @ts-ignore: decorator +@global @unsafe +export function __pin(ptr: usize): usize { + if (ptr) { + let obj = changetype(ptr - TOTAL_OVERHEAD); + if (obj.color == transparent) { + throw new Error(E_ALREADY_PINNED); + } + obj.unlink(); // from fromSpace + obj.linkTo(pinSpace, transparent); + } + return ptr; +} + +// @ts-ignore: decorator +@global @unsafe +export function __unpin(ptr: usize): void { + if (!ptr) return; + var obj = changetype(ptr - TOTAL_OVERHEAD); + if (obj.color != transparent) { + throw new Error(E_NOT_PINNED); + } + obj.unlink(); // from pinSpace + obj.linkTo(fromSpace, white); +} + +// @ts-ignore: decorator +@global @unsafe +export function __collect(): void { + if (TRACE) trace("GC at", 1, total); + + // Mark roots (add to toSpace) + __visit_globals(VISIT_SCAN); + + // Mark direct members of pinned objects (add to toSpace) + var pn = pinSpace; + var iter = pn.next; + while (iter != pn) { + if (DEBUG) assert(iter.color == transparent); + __visit_members(changetype(iter) + TOTAL_OVERHEAD, VISIT_SCAN); + iter = iter.next; + } + + // Mark what's reachable from toSpace + var black = i32(!white); + var to = toSpace; + iter = to.next; + while (iter != to) { + if (DEBUG) assert(iter.color == black); + __visit_members(changetype(iter) + TOTAL_OVERHEAD, VISIT_SCAN); + iter = iter.next; + } + + // Sweep what's left in fromSpace + var from = fromSpace; + iter = from.next; + while (iter != from) { + if (DEBUG) assert(iter.color == white); + let newNext = iter.next; + if (changetype(iter) < __heap_base) { + iter.nextWithColor = 0; // may become linked again + iter.prev = changetype(0); + } else { + total -= iter.size; + if (isDefined(__finalize)) __finalize(changetype(iter) + TOTAL_OVERHEAD); + __free(changetype(iter) + BLOCK_OVERHEAD); + } + iter = newNext; + } + from.nextWithColor = changetype(from); + from.prev = from; + + // Flip spaces and colors + fromSpace = to; + toSpace = from; + white = black; + + if (TRACE) trace("GC done at", 1, total); + if (RTRACE) oncollect(total); +} +`,"rt/tlsf":`import { AL_BITS, AL_SIZE, AL_MASK, DEBUG, BLOCK, BLOCK_OVERHEAD, BLOCK_MAXSIZE } from "./common"; +import { oninit, onalloc, onresize, onmove, onfree } from "./rtrace"; +import { E_ALLOCATION_TOO_LARGE } from "../util/error"; + +// === The TLSF (Two-Level Segregate Fit) memory allocator === +// see: http://www.gii.upv.es/tlsf/ + +// - \`ffs(x)\` is equivalent to \`ctz(x)\` with x != 0 +// - \`fls(x)\` is equivalent to \`sizeof(x) * 8 - clz(x) - 1\` + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Block size interpretation (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u253C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u256B\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 +// \u2502 | FL \u2502 SB = SL + AL \u2502 \u25C4\u2500 usize +// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2568\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 +// FL: first level, SL: second level, AL: alignment, SB: small block + +// @ts-ignore: decorator +@inline const SL_BITS: u32 = 4; +// @ts-ignore: decorator +@inline const SL_SIZE: u32 = 1 << SL_BITS; + +// @ts-ignore: decorator +@inline const SB_BITS: u32 = SL_BITS + AL_BITS; +// @ts-ignore: decorator +@inline const SB_SIZE: u32 = 1 << SB_BITS; + +// @ts-ignore: decorator +@inline const FL_BITS: u32 = 31 - SB_BITS; + +// [00]: < 256B (SB) [12]: < 1M +// [01]: < 512B [13]: < 2M +// [02]: < 1K [14]: < 4M +// [03]: < 2K [15]: < 8M +// [04]: < 4K [16]: < 16M +// [05]: < 8K [17]: < 32M +// [06]: < 16K [18]: < 64M +// [07]: < 32K [19]: < 128M +// [08]: < 64K [20]: < 256M +// [09]: < 128K [21]: < 512M +// [10]: < 256K [22]: <= 1G - OVERHEAD +// [11]: < 512K +// VMs limit to 2GB total (currently), making one 1G block max (or three 512M etc.) due to block overhead + +// Tags stored in otherwise unused alignment bits + +// @ts-ignore: decorator +@inline const FREE: usize = 1 << 0; +// @ts-ignore: decorator +@inline const LEFTFREE: usize = 1 << 1; +// @ts-ignore: decorator +@inline const TAGS_MASK: usize = FREE | LEFTFREE; // <= AL_MASK + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Block layout (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u253C\u2500\u253C\u2500\u2524 \u2510 +// \u2502 size \u2502L\u2502F\u2502 \u25C4\u2500\u2510 info overhead +// \u255E>ptr\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2567\u2550\u2561 \u2502 \u2518 +// \u2502 if free: \u25C4 prev \u2502 \u25C4\u2500\u2524 usize +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 +// \u2502 if free: next \u25BA \u2502 \u25C4\u2500\u2524 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 +// \u2502 ... \u2502 \u2502 >= 0 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 +// \u2502 if free: back \u25B2 \u2502 \u25C4\u2500\u2518 +// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 >= MIN SIZE +// F: FREE, L: LEFTFREE +@unmanaged export class Block extends BLOCK { + + /** Previous free block, if any. Only valid if free, otherwise part of payload. */ + prev: Block | null; + /** Next free block, if any. Only valid if free, otherwise part of payload. */ + next: Block | null; + + // If the block is free, there is a 'back'reference at its end pointing at its start. +} + +// Block constants. A block must have a minimum size of three pointers so it can hold \`prev\`, +// \`next\` and \`back\` if free. + +// @ts-ignore: decorator +@inline const BLOCK_MINSIZE: usize = ((3 * sizeof() + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD; // prev + next + back +// @ts-ignore: decorator +// @inline const BLOCK_MAXSIZE: usize = 1 << (FL_BITS + SB_BITS - 1); // exclusive, lives in common.ts + +/** Gets the left block of a block. Only valid if the left block is free. */ +// @ts-ignore: decorator +@inline function GETFREELEFT(block: Block): Block { + return load(changetype(block) - sizeof()); +} + +/** Gets the right block of a block by advancing to the right by its size. */ +// @ts-ignore: decorator +@inline function GETRIGHT(block: Block): Block { + return changetype(changetype(block) + BLOCK_OVERHEAD + (block.mmInfo & ~TAGS_MASK)); +} + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Root layout (32-bit) \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 \u2510 +// \u2502 0 | flMap S\u2502 \u25C4\u2500\u2500\u2500\u2500\u2510 +// \u255E\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 \u2502 +// \u2502 slMap[0] S \u2502 \u25C4\u2500\u2510 \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2502 +// \u2502 slMap[1] \u2502 \u25C4\u2500\u2524 \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 u32 \u2502 +// \u2502 slMap[22] \u2502 \u25C4\u2500\u2518 \u2502 +// \u255E\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 usize +// \u2502 head[0] \u2502 \u25C4\u2500\u2500\u2500\u2500\u2524 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 +// \u2502 ... \u2502 \u25C4\u2500\u2500\u2500\u2500\u2524 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 +// \u2502 head[367] \u2502 \u25C4\u2500\u2500\u2500\u2500\u2524 +// \u255E\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 \u2502 +// \u2502 tail \u2502 \u25C4\u2500\u2500\u2500\u2500\u2518 +// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 SIZE \u2518 +// S: Small blocks map +@unmanaged class Root { + /** First level bitmap. */ + flMap: usize; +} + +// Root constants. Where stuff is stored inside of the root structure. + +// @ts-ignore: decorator +@inline const SL_START: usize = sizeof(); +// @ts-ignore: decorator +@inline const SL_END: usize = SL_START + (FL_BITS << alignof()); +// @ts-ignore: decorator +@inline const HL_START: usize = (SL_END + AL_MASK) & ~AL_MASK; +// @ts-ignore: decorator +@inline const HL_END: usize = HL_START + FL_BITS * SL_SIZE * sizeof(); +// @ts-ignore: decorator +@inline const ROOT_SIZE: usize = HL_END + sizeof(); + +// @ts-ignore: decorator +@lazy export var ROOT: Root; + +/** Gets the second level map of the specified first level. */ +// @ts-ignore: decorator +@inline function GETSL(root: Root, fl: usize): u32 { + return load( + changetype(root) + (fl << alignof()), + SL_START + ); +} + +/** Sets the second level map of the specified first level. */ +// @ts-ignore: decorator +@inline function SETSL(root: Root, fl: usize, slMap: u32): void { + store( + changetype(root) + (fl << alignof()), + slMap, + SL_START + ); +} + +/** Gets the head of the free list for the specified combination of first and second level. */ +// @ts-ignore: decorator +@inline function GETHEAD(root: Root, fl: usize, sl: u32): Block | null { + return load( + changetype(root) + (((fl << SL_BITS) + sl) << alignof()), + HL_START + ); +} + +/** Sets the head of the free list for the specified combination of first and second level. */ +// @ts-ignore: decorator +@inline function SETHEAD(root: Root, fl: usize, sl: u32, head: Block | null): void { + store( + changetype(root) + (((fl << SL_BITS) + sl) << alignof()), + head, + HL_START + ); +} + +/** Gets the tail block.. */ +// @ts-ignore: decorator +@inline function GETTAIL(root: Root): Block { + return load( + changetype(root), + HL_END + ); +} + +/** Sets the tail block. */ +// @ts-ignore: decorator +@inline function SETTAIL(root: Root, tail: Block): void { + store( + changetype(root), + tail, + HL_END + ); +} + +/** Inserts a previously used block back into the free list. */ +function insertBlock(root: Root, block: Block): void { + if (DEBUG) assert(block); // cannot be null + var blockInfo = block.mmInfo; + if (DEBUG) assert(blockInfo & FREE); // must be free + + var right = GETRIGHT(block); + var rightInfo = right.mmInfo; + + // merge with right block if also free + if (rightInfo & FREE) { + removeBlock(root, right); + block.mmInfo = blockInfo = blockInfo + BLOCK_OVERHEAD + (rightInfo & ~TAGS_MASK); // keep block tags + right = GETRIGHT(block); + rightInfo = right.mmInfo; + // 'back' is set below + } + + // merge with left block if also free + if (blockInfo & LEFTFREE) { + let left = GETFREELEFT(block); + let leftInfo = left.mmInfo; + if (DEBUG) assert(leftInfo & FREE); // must be free according to right tags + removeBlock(root, left); + block = left; + block.mmInfo = blockInfo = leftInfo + BLOCK_OVERHEAD + (blockInfo & ~TAGS_MASK); // keep left tags + // 'back' is set below + } + + right.mmInfo = rightInfo | LEFTFREE; + // reference to right is no longer used now, hence rightInfo is not synced + + // we now know the size of the block + var size = blockInfo & ~TAGS_MASK; + if (DEBUG) assert(size >= BLOCK_MINSIZE); // must be a valid size + if (DEBUG) assert(changetype(block) + BLOCK_OVERHEAD + size == changetype(right)); // must match + + // set 'back' to itself at the end of block + store(changetype(right) - sizeof(), block); + + // mapping_insert + var fl: usize, sl: u32; + if (size < SB_SIZE) { + fl = 0; + sl = (size >> AL_BITS); + } else { + const inv: usize = sizeof() * 8 - 1; + let boundedSize = min(size, BLOCK_MAXSIZE); + fl = inv - clz(boundedSize); + sl = ((boundedSize >> (fl - SL_BITS)) ^ (1 << SL_BITS)); + fl -= SB_BITS - 1; + } + if (DEBUG) assert(fl < FL_BITS && sl < SL_SIZE); // fl/sl out of range + + // perform insertion + var head = GETHEAD(root, fl, sl); + block.prev = null; + block.next = head; + if (head) head.prev = block; + SETHEAD(root, fl, sl, block); + + // update first and second level maps + root.flMap |= (1 << fl); + SETSL(root, fl, GETSL(root, fl) | (1 << sl)); +} + +/** Removes a free block from internal lists. */ +function removeBlock(root: Root, block: Block): void { + var blockInfo = block.mmInfo; + if (DEBUG) assert(blockInfo & FREE); // must be free + var size = blockInfo & ~TAGS_MASK; + if (DEBUG) assert(size >= BLOCK_MINSIZE); // must be valid + + // mapping_insert + var fl: usize, sl: u32; + if (size < SB_SIZE) { + fl = 0; + sl = (size >> AL_BITS); + } else { + const inv: usize = sizeof() * 8 - 1; + let boundedSize = min(size, BLOCK_MAXSIZE); + fl = inv - clz(boundedSize); + sl = ((boundedSize >> (fl - SL_BITS)) ^ (1 << SL_BITS)); + fl -= SB_BITS - 1; + } + if (DEBUG) assert(fl < FL_BITS && sl < SL_SIZE); // fl/sl out of range + + // link previous and next free block + var prev = block.prev; + var next = block.next; + if (prev) prev.next = next; + if (next) next.prev = prev; + + // update head if we are removing it + if (block == GETHEAD(root, fl, sl)) { + SETHEAD(root, fl, sl, next); + + // clear second level map if head is empty now + if (!next) { + let slMap = GETSL(root, fl); + SETSL(root, fl, slMap &= ~(1 << sl)); + + // clear first level map if second level is empty now + if (!slMap) root.flMap &= ~(1 << fl); + } + } + // note: does not alter left/back because it is likely that splitting + // is performed afterwards, invalidating those changes. so, the caller + // must perform those updates. +} + +/** Searches for a free block of at least the specified size. */ +function searchBlock(root: Root, size: usize): Block | null { + // size was already asserted by caller + + // mapping_search + var fl: usize, sl: u32; + if (size < SB_SIZE) { + fl = 0; + sl = (size >> AL_BITS); + } else { + const halfMaxSize = BLOCK_MAXSIZE >> 1; // don't round last fl + const inv: usize = sizeof() * 8 - 1; + const invRound = inv - SL_BITS; + let requestSize = size < halfMaxSize + ? size + (1 << (invRound - clz(size))) - 1 + : size; + fl = inv - clz(requestSize); + sl = ((requestSize >> (fl - SL_BITS)) ^ (1 << SL_BITS)); + fl -= SB_BITS - 1; + } + if (DEBUG) assert(fl < FL_BITS && sl < SL_SIZE); // fl/sl out of range + + // search second level + var slMap = GETSL(root, fl) & (~0 << sl); + var head: Block | null = null; + if (!slMap) { + // search next larger first level + let flMap = root.flMap & (~0 << (fl + 1)); + if (!flMap) { + head = null; + } else { + fl = ctz(flMap); + slMap = GETSL(root, fl); + if (DEBUG) assert(slMap); // can't be zero if fl points here + head = GETHEAD(root, fl, ctz(slMap)); + } + } else { + head = GETHEAD(root, fl, ctz(slMap)); + } + return head; +} + +/** Prepares the specified block before (re-)use, possibly splitting it. */ +function prepareBlock(root: Root, block: Block, size: usize): void { + // size was already asserted by caller + + var blockInfo = block.mmInfo; + if (DEBUG) assert(!((size + BLOCK_OVERHEAD) & AL_MASK)); // size must be aligned so the new block is + + // split if the block can hold another MINSIZE block incl. overhead + var remaining = (blockInfo & ~TAGS_MASK) - size; + if (remaining >= BLOCK_OVERHEAD + BLOCK_MINSIZE) { + block.mmInfo = size | (blockInfo & LEFTFREE); // also discards FREE + + let spare = changetype(changetype(block) + BLOCK_OVERHEAD + size); + spare.mmInfo = (remaining - BLOCK_OVERHEAD) | FREE; // not LEFTFREE + insertBlock(root, spare); // also sets 'back' + + // otherwise tag block as no longer FREE and right as no longer LEFTFREE + } else { + block.mmInfo = blockInfo & ~FREE; + GETRIGHT(block).mmInfo &= ~LEFTFREE; + } +} + +/** Adds more memory to the pool. */ +function addMemory(root: Root, start: usize, end: usize): bool { + if (DEBUG) assert(start <= end); // must be valid + start = ((start + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD; + end &= ~AL_MASK; + + var tail = GETTAIL(root); + var tailInfo: usize = 0; + if (tail) { // more memory + if (DEBUG) assert(start >= changetype(tail) + BLOCK_OVERHEAD); + + // merge with current tail if adjacent + const offsetToTail = AL_SIZE; + if (start - offsetToTail == changetype(tail)) { + start -= offsetToTail; + tailInfo = tail.mmInfo; + } else { + // We don't do this, but a user might \`memory.grow\` manually + // leading to non-adjacent pages managed by TLSF. + } + + } else if (DEBUG) { // first memory + assert(start >= changetype(root) + ROOT_SIZE); // starts after root + } + + // check if size is large enough for a free block and the tail block + var size = end - start; + if (size < BLOCK_OVERHEAD + BLOCK_MINSIZE + BLOCK_OVERHEAD) { + return false; + } + + // left size is total minus its own and the zero-length tail's header + var leftSize = size - 2 * BLOCK_OVERHEAD; + var left = changetype(start); + left.mmInfo = leftSize | FREE | (tailInfo & LEFTFREE); + left.prev = null; + left.next = null; + + // tail is a zero-length used block + tail = changetype(start + BLOCK_OVERHEAD + leftSize); + tail.mmInfo = 0 | LEFTFREE; + SETTAIL(root, tail); + + insertBlock(root, left); // also merges with free left before tail / sets 'back' + + return true; +} + +/** Grows memory to fit at least another block of the specified size. */ +function growMemory(root: Root, size: usize): void { + if (ASC_LOW_MEMORY_LIMIT) { + unreachable(); + return; + } + // Here, both rounding performed in searchBlock ... + const halfMaxSize = BLOCK_MAXSIZE >> 1; + if (size < halfMaxSize) { // don't round last fl + const invRound = (sizeof() * 8 - 1) - SL_BITS; + size += (1 << (invRound - clz(size))) - 1; + } + // and additional BLOCK_OVERHEAD must be taken into account. If we are going + // to merge with the tail block, that's one time, otherwise it's two times. + var pagesBefore = memory.size(); + size += BLOCK_OVERHEAD << usize((pagesBefore << 16) - BLOCK_OVERHEAD != changetype(GETTAIL(root))); + var pagesNeeded = (((size + 0xffff) & ~0xffff) >>> 16); + var pagesWanted = max(pagesBefore, pagesNeeded); // double memory + if (memory.grow(pagesWanted) < 0) { + if (memory.grow(pagesNeeded) < 0) unreachable(); + } + var pagesAfter = memory.size(); + addMemory(root, pagesBefore << 16, pagesAfter << 16); +} + +/** Computes the size (excl. header) of a block. */ +function computeSize(size: usize): usize { + // Size must be large enough and aligned minus preceeding overhead + return size <= BLOCK_MINSIZE + ? BLOCK_MINSIZE + : ((size + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD; +} + +/** Prepares and checks an allocation size. */ +function prepareSize(size: usize): usize { + if (size > BLOCK_MAXSIZE) throw new Error(E_ALLOCATION_TOO_LARGE); + return computeSize(size); +} + +/** Initializes the root structure. */ +function initialize(): void { + if (isDefined(ASC_RTRACE)) oninit(__heap_base); + var rootOffset = (__heap_base + AL_MASK) & ~AL_MASK; + var pagesBefore = memory.size(); + var pagesNeeded = ((((rootOffset + ROOT_SIZE) + 0xffff) & ~0xffff) >>> 16); + if (pagesNeeded > pagesBefore && memory.grow(pagesNeeded - pagesBefore) < 0) unreachable(); + var root = changetype(rootOffset); + root.flMap = 0; + SETTAIL(root, changetype(0)); + for (let fl: usize = 0; fl < FL_BITS; ++fl) { + SETSL(root, fl, 0); + for (let sl: u32 = 0; sl < SL_SIZE; ++sl) { + SETHEAD(root, fl, sl, null); + } + } + var memStart = rootOffset + ROOT_SIZE; + if (ASC_LOW_MEMORY_LIMIT) { + const memEnd = ASC_LOW_MEMORY_LIMIT & ~AL_MASK; + if (memStart <= memEnd) addMemory(root, memStart, memEnd); + else unreachable(); // low memory limit already exceeded + } else { + addMemory(root, memStart, memory.size() << 16); + } + ROOT = root; +} + +/** Allocates a block of the specified size. */ +export function allocateBlock(root: Root, size: usize): Block { + var payloadSize = prepareSize(size); + var block = searchBlock(root, payloadSize); + if (!block) { + growMemory(root, payloadSize); + block = changetype(searchBlock(root, payloadSize)); + if (DEBUG) assert(block); // must be found now + } + if (DEBUG) assert((block.mmInfo & ~TAGS_MASK) >= payloadSize); // must fit + removeBlock(root, block); + prepareBlock(root, block, payloadSize); + if (isDefined(ASC_RTRACE)) onalloc(block); + return block; +} + +/** Reallocates a block to the specified size. */ +export function reallocateBlock(root: Root, block: Block, size: usize): Block { + var payloadSize = prepareSize(size); + var blockInfo = block.mmInfo; + var blockSize = blockInfo & ~TAGS_MASK; + + // possibly split and update runtime size if it still fits + if (payloadSize <= blockSize) { + prepareBlock(root, block, payloadSize); + if (isDefined(ASC_RTRACE)) { + if (payloadSize != blockSize) onresize(block, BLOCK_OVERHEAD + blockSize); + } + return block; + } + + // merge with right free block if merger is large enough + var right = GETRIGHT(block); + var rightInfo = right.mmInfo; + if (rightInfo & FREE) { + let mergeSize = blockSize + BLOCK_OVERHEAD + (rightInfo & ~TAGS_MASK); + if (mergeSize >= payloadSize) { + removeBlock(root, right); + block.mmInfo = (blockInfo & TAGS_MASK) | mergeSize; + prepareBlock(root, block, payloadSize); + if (isDefined(ASC_RTRACE)) onresize(block, BLOCK_OVERHEAD + blockSize); + return block; + } + } + + // otherwise move the block + return moveBlock(root, block, size); +} + +/** Moves a block to a new one of the specified size. */ +function moveBlock(root: Root, block: Block, newSize: usize): Block { + var newBlock = allocateBlock(root, newSize); + memory.copy(changetype(newBlock) + BLOCK_OVERHEAD, changetype(block) + BLOCK_OVERHEAD, block.mmInfo & ~TAGS_MASK); + if (changetype(block) >= __heap_base) { + if (isDefined(ASC_RTRACE)) onmove(block, newBlock); + freeBlock(root, block); + } + return newBlock; +} + +/** Frees a block. */ +export function freeBlock(root: Root, block: Block): void { + if (isDefined(ASC_RTRACE)) onfree(block); + block.mmInfo = block.mmInfo | FREE; + insertBlock(root, block); +} + +/** Checks that a used block is valid to be freed or reallocated. */ +function checkUsedBlock(ptr: usize): Block { + var block = changetype(ptr - BLOCK_OVERHEAD); + assert( + ptr != 0 && !(ptr & AL_MASK) && // must exist and be aligned + !(block.mmInfo & FREE) // must be used + ); + return block; +} + +// @ts-ignore: decorator +@global @unsafe +export function __alloc(size: usize): usize { + if (!ROOT) initialize(); + return changetype(allocateBlock(ROOT, size)) + BLOCK_OVERHEAD; +} + +// @ts-ignore: decorator +@global @unsafe +export function __realloc(ptr: usize, size: usize): usize { + if (!ROOT) initialize(); + return (ptr < __heap_base + ? changetype(moveBlock(ROOT, checkUsedBlock(ptr), size)) + : changetype(reallocateBlock(ROOT, checkUsedBlock(ptr), size)) + ) + BLOCK_OVERHEAD; +} + +// @ts-ignore: decorator +@global @unsafe +export function __free(ptr: usize): void { + if (ptr < __heap_base) return; + if (!ROOT) initialize(); + freeBlock(ROOT, checkUsedBlock(ptr)); +} +`,set:`/// + +import { HASH } from "./util/hash"; + +// A deterministic hash set based on CloseTable from https://github.com/jorendorff/dht + +// @ts-ignore: decorator +@inline const INITIAL_CAPACITY = 4; + +// @ts-ignore: decorator +@inline const FILL_FACTOR_N = 8; + +// @ts-ignore: decorator +@inline const FILL_FACTOR_D = 3; + +// @ts-ignore: decorator +@inline const FREE_FACTOR_N = 3; + +// @ts-ignore: decorator +@inline const FREE_FACTOR_D = 4; + +/** Structure of a set entry. */ +@unmanaged class SetEntry { + key: K; + taggedNext: usize; // LSB=1 indicates EMPTY +} + +/** Empty bit. */ +// @ts-ignore: decorator +@inline const EMPTY: usize = 1 << 0; + +/** Size of a bucket. */ +// @ts-ignore: decorator +@inline const BUCKET_SIZE = sizeof(); + +/** Computes the alignment of an entry. */ +// @ts-ignore: decorator +@inline +function ENTRY_ALIGN(): usize { + // can align to 4 instead of 8 if 32-bit and K is <= 32-bits + const align = (sizeof() > sizeof() ? sizeof() : sizeof()) - 1; + return align; +} + +/** Computes the aligned size of an entry. */ +// @ts-ignore: decorator +@inline +function ENTRY_SIZE(): usize { + const align = ENTRY_ALIGN(); + const size = (offsetof>() + align) & ~align; + return size; +} + +export class Set { + + // buckets referencing their respective first entry, usize[bucketsMask + 1] + private buckets: ArrayBuffer = new ArrayBuffer(INITIAL_CAPACITY * BUCKET_SIZE); + private bucketsMask: u32 = INITIAL_CAPACITY - 1; + + // entries in insertion order, SetEntry[entriesCapacity] + private entries: ArrayBuffer = new ArrayBuffer(INITIAL_CAPACITY * ENTRY_SIZE()); + private entriesCapacity: i32 = INITIAL_CAPACITY; + private entriesOffset: i32 = 0; + private entriesCount: i32 = 0; + + constructor() { + /* nop */ + } + + get size(): i32 { + return this.entriesCount; + } + + clear(): void { + this.buckets = new ArrayBuffer(INITIAL_CAPACITY * BUCKET_SIZE); + this.bucketsMask = INITIAL_CAPACITY - 1; + this.entries = new ArrayBuffer(INITIAL_CAPACITY * ENTRY_SIZE()); + this.entriesCapacity = INITIAL_CAPACITY; + this.entriesOffset = 0; + this.entriesCount = 0; + } + + private find(key: T, hashCode: u32): SetEntry | null { + var entry = load>( // unmanaged! + changetype(this.buckets) + (hashCode & this.bucketsMask) * BUCKET_SIZE + ); + while (entry) { + let taggedNext = entry.taggedNext; + if (!(taggedNext & EMPTY) && entry.key == key) return entry; + entry = changetype>(taggedNext & ~EMPTY); + } + return null; + } + + @operator("[]") + has(key: T): bool { + return this.find(key, HASH(key)) != null; + } + + add(key: T): this { + var hashCode = HASH(key); + var entry = this.find(key, hashCode); // unmanaged! + if (!entry) { + // check if rehashing is necessary + if (this.entriesOffset == this.entriesCapacity) { + this.rehash( + this.entriesCount < this.entriesCapacity * FREE_FACTOR_N / FREE_FACTOR_D + ? this.bucketsMask // just rehash if 1/4+ entries are empty + : (this.bucketsMask << 1) | 1 // grow capacity to next 2^N + ); + } + // append new entry + entry = changetype>(changetype(this.entries) + (this.entriesOffset++) * ENTRY_SIZE()); + entry.key = key; + if (isManaged()) { + __link(changetype(this), changetype(key), true); + } + ++this.entriesCount; + // link with previous entry in bucket + let bucketPtrBase = changetype(this.buckets) + (hashCode & this.bucketsMask) * BUCKET_SIZE; + entry.taggedNext = load(bucketPtrBase); + store(bucketPtrBase, changetype(entry)); + } + return this; + } + + @operator("[]=") + private __set(key: T, value: bool): void { + if (value) this.add(key); + else this.delete(key); + } + + delete(key: T): bool { + var entry = this.find(key, HASH(key)); // unmanaged! + if (!entry) return false; + entry.taggedNext |= EMPTY; + --this.entriesCount; + // check if rehashing is appropriate + var halfBucketsMask = this.bucketsMask >> 1; + if ( + halfBucketsMask + 1 >= max(INITIAL_CAPACITY, this.entriesCount) && + this.entriesCount < this.entriesCapacity * FREE_FACTOR_N / FREE_FACTOR_D + ) this.rehash(halfBucketsMask); + return true; + } + + private rehash(newBucketsMask: u32): void { + var newBucketsCapacity = (newBucketsMask + 1); + var newBuckets = new ArrayBuffer(newBucketsCapacity * BUCKET_SIZE); + var newEntriesCapacity = newBucketsCapacity * FILL_FACTOR_N / FILL_FACTOR_D; + var newEntries = new ArrayBuffer(newEntriesCapacity * ENTRY_SIZE()); + + // copy old entries to new entries + var oldPtr = changetype(this.entries); + var oldEnd = oldPtr + this.entriesOffset * ENTRY_SIZE(); + var newPtr = changetype(newEntries); + while (oldPtr != oldEnd) { + let oldEntry = changetype>(oldPtr); // unmanaged! + if (!(oldEntry.taggedNext & EMPTY)) { + let newEntry = changetype>(newPtr); // unmanaged! + let oldEntryKey = oldEntry.key; + newEntry.key = oldEntryKey; + let newBucketIndex = HASH(oldEntryKey) & newBucketsMask; + let newBucketPtrBase = changetype(newBuckets) + newBucketIndex * BUCKET_SIZE; + newEntry.taggedNext = load(newBucketPtrBase); + store(newBucketPtrBase, newPtr); + newPtr += ENTRY_SIZE(); + } + oldPtr += ENTRY_SIZE(); + } + + this.buckets = newBuckets; + this.bucketsMask = newBucketsMask; + this.entries = newEntries; + this.entriesCapacity = newEntriesCapacity; + this.entriesOffset = this.entriesCount; + } + + values(): T[] { + // FIXME: this is preliminary, needs iterators/closures + var start = changetype(this.entries); + var size = this.entriesOffset; + var values = new Array(size); + var length = 0; + for (let i = 0; i < size; ++i) { + let entry = changetype>(start + i * ENTRY_SIZE()); + if (!(entry.taggedNext & EMPTY)) { + values[length++] = entry.key; + } + } + values.length = length; + return values; + } + + toString(): string { + return "[object Set]"; + } + + // RT integration + + @unsafe private __visit(cookie: u32): void { + __visit(changetype(this.buckets), cookie); + var entries = changetype(this.entries); + if (isManaged()) { + let cur = entries; + let end = cur + this.entriesOffset * ENTRY_SIZE(); + while (cur < end) { + let entry = changetype>(cur); + if (!(entry.taggedNext & EMPTY)) { + let val = changetype(entry.key); + if (isNullable()) { + if (val) __visit(val, cookie); + } else __visit(val, cookie); + } + cur += ENTRY_SIZE(); + } + } + __visit(entries, cookie); + } +} +`,"shared/feature":`// This file is shared with the compiler and must remain portable + +/** Indicates specific features to activate. */ +export const enum Feature { + /** No additional features. */ + NONE = 0, + /** Sign extension operations. */ + SIGN_EXTENSION = 1 << 0, // see: https://github.com/WebAssembly/sign-extension-ops + /** Mutable global imports and exports. */ + MUTABLE_GLOBALS = 1 << 1, // see: https://github.com/WebAssembly/mutable-global + /** Non-trapping float to integer operations. */ + NONTRAPPING_F2I = 1 << 2, // see: https://github.com/WebAssembly/nontrapping-float-to-int-conversions + /** Bulk memory operations. */ + BULK_MEMORY = 1 << 3, // see: https://github.com/WebAssembly/bulk-memory-operations + /** SIMD types and operations. */ + SIMD = 1 << 4, // see: https://github.com/WebAssembly/simd + /** Threading and atomic operations. */ + THREADS = 1 << 5, // see: https://github.com/WebAssembly/threads + /** Exception handling operations. */ + EXCEPTION_HANDLING = 1 << 6, // see: https://github.com/WebAssembly/exception-handling + /** Tail call operations. */ + TAIL_CALLS = 1 << 7, // see: https://github.com/WebAssembly/tail-call + /** Reference types. */ + REFERENCE_TYPES = 1 << 8, // see: https://github.com/WebAssembly/reference-types + /** Multi value types. */ + MULTI_VALUE = 1 << 9, // see: https://github.com/WebAssembly/multi-value + /** Garbage collection. */ + GC = 1 << 10, // see: https://github.com/WebAssembly/gc + /** Memory64. */ + MEMORY64 = 1 << 11, // see: https://github.com/WebAssembly/memory64 + /** Function references. */ + FUNCTION_REFERENCES = 1 << 12, // see: https://github.com/WebAssembly/function-references + /** Relaxed SIMD. */ + RELAXED_SIMD = 1 << 13, // see: https://github.com/WebAssembly/relaxed-simd + /** Extended const expressions. */ + EXTENDED_CONST = 1 << 14 // see: https://github.com/WebAssembly/extended-const +} + +/** Gets the name of the specified feature one would specify on the command line. */ +export function featureToString(feature: Feature): string { + switch (feature) { + case Feature.SIGN_EXTENSION: return "sign-extension"; + case Feature.MUTABLE_GLOBALS: return "mutable-globals"; + case Feature.NONTRAPPING_F2I: return "nontrapping-f2i"; + case Feature.BULK_MEMORY: return "bulk-memory"; + case Feature.SIMD: return "simd"; + case Feature.THREADS: return "threads"; + case Feature.EXCEPTION_HANDLING: return "exception-handling"; + case Feature.TAIL_CALLS: return "tail-calls"; + case Feature.REFERENCE_TYPES: return "reference-types"; + case Feature.MULTI_VALUE: return "multi-value"; + case Feature.GC: return "gc"; + case Feature.MEMORY64: return "memory64"; + } + assert(false); + return ""; +} +`,"shared/runtime":`// This file is shared with the compiler and must remain portable + +/** Runtime types. */ +export enum Runtime { + /** Simple bump allocator without GC. */ + Stub = 0, + /** Stop the world semi-automatic GC. */ + Minimal = 1, + /** incremental GC. */ + Incremental = 2, +} +`,"shared/target":`// This file is shared with the compiler and must remain portable + +/** Compilation target. */ +export enum Target { + /** Portable. */ + JS = 0, + /** WebAssembly with 32-bit pointers. */ + WASM32 = 1, + /** WebAssembly with 64-bit pointers. Experimental and not supported by any runtime yet. */ + WASM64 = 2, +} +`,"shared/typeinfo":`// This file is shared with the compiler and must remain portable + +// \u2552\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 Typeinfo interpretation \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2555 +// 3 2 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 bits +// \u251C\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2534\u2500\u2524 \u25C4\u2500 __rtti_base +// \u2502 count \u2502 +// \u255E\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2561 \u2510 +// \u2502 Typeinfo#flags [id=0] \u2502 id < count +// \u251C \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2524 +// \u2502 Typeinfo#base [id=0] \u2502 +// \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 +// \u2502 ... \u2502 + +/** Runtime type information data structure. */ +@unmanaged +export class Typeinfo { + /** Flags describing the shape of this class type. */ + flags: TypeinfoFlags = TypeinfoFlags.NONE; + /** Base class id or \`0\` if none. */ + base: u32 = 0; +} + +/** Runtime type information flags. */ +export const enum TypeinfoFlags { + /** No specific flags. */ + NONE = 0, + /** Type is an \`ArrayBufferView\`. */ + ARRAYBUFFERVIEW = 1 << 0, + /** Type is an \`Array\`. */ + ARRAY = 1 << 1, + /** Type is a \`StaticArray\`. */ + STATICARRAY = 1 << 2, + /** Type is a \`Set\`. */ + SET = 1 << 3, + /** Type is a \`Map\`. */ + MAP = 1 << 4, + /** Type has no outgoing pointers. */ + POINTERFREE = 1 << 5, + /** Value alignment of 1 byte. */ + VALUE_ALIGN_0 = 1 << 6, + /** Value alignment of 2 bytes. */ + VALUE_ALIGN_1 = 1 << 7, + /** Value alignment of 4 bytes. */ + VALUE_ALIGN_2 = 1 << 8, + /** Value alignment of 8 bytes. */ + VALUE_ALIGN_3 = 1 << 9, + /** Value alignment of 16 bytes. */ + VALUE_ALIGN_4 = 1 << 10, + /** Value is a signed type. */ + VALUE_SIGNED = 1 << 11, + /** Value is a float type. */ + VALUE_FLOAT = 1 << 12, + /** Value type is nullable. */ + VALUE_NULLABLE = 1 << 13, + /** Value type is managed. */ + VALUE_MANAGED = 1 << 14, + /** Key alignment of 1 byte. */ + KEY_ALIGN_0 = 1 << 15, + /** Key alignment of 2 bytes. */ + KEY_ALIGN_1 = 1 << 16, + /** Key alignment of 4 bytes. */ + KEY_ALIGN_2 = 1 << 17, + /** Key alignment of 8 bytes. */ + KEY_ALIGN_3 = 1 << 18, + /** Key alignment of 16 bytes. */ + KEY_ALIGN_4 = 1 << 19, + /** Key is a signed type. */ + KEY_SIGNED = 1 << 20, + /** Key is a float type. */ + KEY_FLOAT = 1 << 21, + /** Key type is nullable. */ + KEY_NULLABLE = 1 << 22, + /** Key type is managed. */ + KEY_MANAGED = 1 << 23 +} +`,staticarray:`/// + +import { OBJECT, BLOCK_MAXSIZE, TOTAL_OVERHEAD } from "./rt/common"; +import { Runtime } from "shared/runtime"; +import { COMPARATOR, SORT } from "./util/sort"; +import { REVERSE } from "./util/bytes"; +import { idof } from "./builtins"; +import { Array } from "./array"; +import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_HOLEYARRAY } from "./util/error"; +import { joinBooleanArray, joinIntegerArray, joinFloatArray, joinStringArray, joinReferenceArray } from "./util/string"; + +@final +export class StaticArray { + [key: number]: T; + + // Note that the interface of StaticArray instances must be a semantically + // compatible subset of Array in order for syntax highlighting to work + // properly, for instance when creating static arrays from array literals. + // The additionally provided static methods take care of dealing with static + // arrays exclusively, without having to convert to Array first. + + static fromArray(source: Array): StaticArray { + var length = source.length; + var outSize = length << alignof(); + var out = changetype>(__new(outSize, idof>())); + if (isManaged()) { + let sourcePtr = source.dataStart; + for (let i = 0; i < length; ++i) { + let off = i << alignof(); + let ref = load(sourcePtr + off); + store(changetype(out) + off, ref); + __link(changetype(out), ref, true); + } + } else { + memory.copy(changetype(out), source.dataStart, outSize); + } + return out; + } + + static concat(source: StaticArray, other: StaticArray): StaticArray { + var sourceLen = source.length; + var otherLen = other.length; + var outLen = sourceLen + otherLen; + if (outLen > BLOCK_MAXSIZE >>> alignof()) throw new Error(E_INVALIDLENGTH); + var out = changetype>(__new(outLen << alignof(), idof>())); + var outStart = changetype(out); + var sourceSize = sourceLen << alignof(); + if (isManaged()) { + for (let offset: usize = 0; offset < sourceSize; offset += sizeof()) { + let ref = load(changetype(source) + offset); + store(outStart + offset, ref); + __link(changetype(out), ref, true); + } + outStart += sourceSize; + let otherSize = otherLen << alignof(); + for (let offset: usize = 0; offset < otherSize; offset += sizeof()) { + let ref = load(changetype(other) + offset); + store(outStart + offset, ref); + __link(changetype(out), ref, true); + } + } else { + memory.copy(outStart, changetype(source), sourceSize); + memory.copy(outStart + sourceSize, changetype(other), otherLen << alignof()); + } + return out; + } + + static slice(source: StaticArray, start: i32 = 0, end: i32 = i32.MAX_VALUE): StaticArray { + var length = source.length; + start = start < 0 ? max(start + length, 0) : min(start, length); + end = end < 0 ? max(end + length, 0) : min(end , length); + length = max(end - start, 0); + var sliceSize = length << alignof(); + var slice = changetype>(__new(sliceSize, idof>())); + var sourcePtr = changetype(source) + (start << alignof()); + if (isManaged()) { + let off: usize = 0; + while (off < sliceSize) { + let ref = load(sourcePtr + off); + store(changetype(slice) + off, ref); + __link(changetype(slice), ref, true); + off += sizeof(); + } + } else { + memory.copy(changetype(slice), sourcePtr, sliceSize); + } + return slice; + } + + constructor(length: i32) { + if (length > BLOCK_MAXSIZE >>> alignof()) throw new RangeError(E_INVALIDLENGTH); + var outSize = length << alignof(); + var out = changetype>(__new(outSize, idof>())); + if (ASC_RUNTIME != Runtime.Incremental) { + memory.fill(changetype(out), 0, outSize); + } + return out; + } + + get length(): i32 { + return changetype(changetype(this) - TOTAL_OVERHEAD).rtSize >>> alignof(); + } + + at(index: i32): T { + var len = this.length; + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + var value = load(changetype(this) + (index << alignof())); + if (isReference()) { + if (!isNullable()) { + if (!changetype(value)) throw new Error(E_HOLEYARRAY); + } + } + return value; + } + + @operator("[]") private __get(index: i32): T { + if (index >= this.length) throw new RangeError(E_INDEXOUTOFRANGE); + var value = load(changetype(this) + (index << alignof())); + if (isReference()) { + if (!isNullable()) { + if (!changetype(value)) throw new Error(E_HOLEYARRAY); + } + } + return value; + } + + @unsafe @operator("{}") private __uget(index: i32): T { + return load(changetype(this) + (index << alignof())); + } + + @operator("[]=") private __set(index: i32, value: T): void { + if (index >= this.length) throw new RangeError(E_INDEXOUTOFRANGE); + this.__uset(index, value); + } + + @unsafe @operator("{}=") private __uset(index: i32, value: T): void { + store(changetype(this) + (index << alignof()), value); + if (isManaged()) { + __link(changetype(this), changetype(value), true); + } + } + + fill(value: T, start: i32 = 0, end: i32 = i32.MAX_VALUE): this { + var ptr = changetype(this); + var len = this.length; + start = start < 0 ? max(len + start, 0) : min(start, len); + end = end < 0 ? max(len + end, 0) : min(end, len); + if (isManaged()) { + for (; start < end; ++start) { + store(ptr + (start << alignof()), changetype(value)); + __link(changetype(this), changetype(value), true); + } + } else if (sizeof() == 1) { + if (start < end) { + memory.fill( + ptr + start, + u8(value), + (end - start) + ); + } + } else { + for (; start < end; ++start) { + store(ptr + (start << alignof()), value); + } + } + return this; + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): this { + var ptr = changetype(this); + var len = this.length; + + end = min(end, len); + + var to = target < 0 ? max(len + target, 0) : min(target, len); + var from = start < 0 ? max(len + start, 0) : min(start, len); + var last = end < 0 ? max(len + end, 0) : min(end, len); + var count = min(last - from, len - to); + + memory.copy( // is memmove + ptr + (to << alignof()), + ptr + (from << alignof()), + count << alignof() + ); + return this; + } + + includes(value: T, fromIndex: i32 = 0): bool { + if (isFloat()) { + let length = this.length; + if (length == 0 || fromIndex >= length) return false; + if (fromIndex < 0) fromIndex = max(length + fromIndex, 0); + while (fromIndex < length) { + let elem = load(changetype(this) + (fromIndex << alignof())); + // @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 { + var length = this.length; + if (length == 0 || fromIndex >= length) return -1; + if (fromIndex < 0) fromIndex = max(length + fromIndex, 0); + while (fromIndex < length) { + if (load(changetype(this) + (fromIndex << alignof())) == value) return fromIndex; + ++fromIndex; + } + return -1; + } + + lastIndexOf(value: T, fromIndex: i32 = this.length): i32 { + var length = this.length; + if (length == 0) return -1; + if (fromIndex < 0) fromIndex = length + fromIndex; + else if (fromIndex >= length) fromIndex = length - 1; + while (fromIndex >= 0) { + if (load(changetype(this) + (fromIndex << alignof())) == value) return fromIndex; + --fromIndex; + } + return -1; + } + + concat(other: Array): Array { + var thisLen = this.length; + var otherLen = other.length; + var outLen = thisLen + otherLen; + if (outLen > BLOCK_MAXSIZE >>> alignof()) throw new Error(E_INVALIDLENGTH); + var out = changetype>(__newArray(outLen, alignof(), idof>())); + var outStart = out.dataStart; + var thisSize = thisLen << alignof(); + if (isManaged()) { + let thisStart = changetype(this); + for (let offset: usize = 0; offset < thisSize; offset += sizeof()) { + let ref = load(thisStart + offset); + store(outStart + offset, ref); + __link(changetype(out), ref, true); + } + outStart += thisSize; + let otherStart = other.dataStart; + let otherSize = otherLen << alignof(); + for (let offset: usize = 0; offset < otherSize; offset += sizeof()) { + let ref = load(otherStart + offset); + store(outStart + offset, ref); + __link(changetype(out), ref, true); + } + } else { + memory.copy(outStart, changetype(this), thisSize); + memory.copy(outStart + thisSize, other.dataStart, otherLen << alignof()); + } + return out; + } + + slice(start: i32 = 0, end: i32 = i32.MAX_VALUE): Array { + var length = this.length; + start = start < 0 ? max(start + length, 0) : min(start, length); + end = end < 0 ? max(end + length, 0) : min(end , length); + length = max(end - start, 0); + var slice = changetype>(__newArray(length, alignof(), idof>())); + var sliceBase = slice.dataStart; + var thisBase = changetype(this) + (start << alignof()); + if (isManaged()) { + let off = 0; + let end = length << alignof(); + while (off < end) { + let ref = load(thisBase + off); + store(sliceBase + off, ref); + __link(changetype(slice), ref, true); + off += sizeof(); + } + } else { + memory.copy(sliceBase, thisBase, length << alignof()); + } + return slice; + } + + findIndex(fn: (value: T, index: i32, array: StaticArray) => bool): i32 { + for (let i = 0, len = this.length; i < len; ++i) { + if (fn(load(changetype(this) + (i << alignof())), i, this)) return i; + } + return -1; + } + + findLastIndex(fn: (value: T, index: i32, array: StaticArray) => bool): i32 { + for (let i = this.length - 1; i >= 0; --i) { + if (fn(load(changetype(this) + (i << alignof())), i, this)) return i; + } + return -1; + } + + forEach(fn: (value: T, index: i32, array: StaticArray) => void): void { + for (let i = 0, len = this.length; i < len; ++i) { + fn(load(changetype(this) + (i << alignof())), i, this); + } + } + + map(fn: (value: T, index: i32, array: StaticArray) => U): Array { + var len = this.length; + var out = changetype>(__newArray(len, alignof(), idof>())); + var outStart = out.dataStart; + for (let i = 0; i < len; ++i) { + let result = fn(load(changetype(this) + (i << alignof())), i, this); + store(outStart + (i << alignof()), result); + if (isManaged()) { + __link(changetype(out), changetype(result), true); + } + } + return out; + } + + filter(fn: (value: T, index: i32, array: StaticArray) => bool): Array { + var result = changetype>(__newArray(0, alignof(), idof>())); + for (let i = 0, len = this.length; i < len; ++i) { + let value = load(changetype(this) + (i << alignof())); + if (fn(value, i, this)) result.push(value); + } + return result; + } + + reduce( + fn: (previousValue: U, currentValue: T, currentIndex: i32, array: StaticArray) => U, + initialValue: U + ): U { + var acc = initialValue; + for (let i = 0, len = this.length; i < len; ++i) { + acc = fn(acc, load(changetype(this) + (i << alignof())), i, this); + } + return acc; + } + + reduceRight( + fn: (previousValue: U, currentValue: T, currentIndex: i32, array: StaticArray) => U, + initialValue: U + ): U { + var acc = initialValue; + for (let i = this.length - 1; i >= 0; --i) { + acc = fn(acc, load(changetype(this) + (i << alignof())), i, this); + } + return acc; + } + + every(fn: (value: T, index: i32, array: StaticArray) => bool): bool { + for (let i = 0, len = this.length; i < len; ++i) { + if (!fn(load(changetype(this) + (i << alignof())), i, this)) return false; + } + return true; + } + + some(fn: (value: T, index: i32, array: StaticArray) => bool): bool { + for (let i = 0, len = this.length; i < len; ++i) { + if (fn(load(changetype(this) + (i << alignof())), i, this)) return true; + } + return false; + } + + sort(comparator: (a: T, b: T) => i32 = COMPARATOR()): this { + SORT(changetype(this), this.length, comparator); + return this; + } + + join(separator: string = ","): string { + if (isBoolean()) return joinBooleanArray(changetype(this), this.length, separator); + if (isInteger()) return joinIntegerArray(changetype(this), this.length, separator); + if (isFloat()) return joinFloatArray(changetype(this), this.length, separator); + if (ASC_SHRINK_LEVEL < 1) { + if (isString()) return joinStringArray(changetype(this), this.length, separator); + } + if (isReference()) return joinReferenceArray(changetype(this), this.length, separator); + ERROR("unspported element type"); + return unreachable(); + } + + reverse(): this { + REVERSE(changetype(this), this.length); + return this; + } + + toString(): string { + return this.join(); + } + + // RT integration + + @unsafe private __visit(cookie: u32): void { + if (isManaged()) { + let cur = changetype(this); + let end = cur + changetype(changetype(this) - TOTAL_OVERHEAD).rtSize; + while (cur < end) { + let val = load(cur); + if (val) __visit(val, cookie); + cur += sizeof(); + } + } + } +} +`,string:`/// + +import { OBJECT, BLOCK_MAXSIZE, TOTAL_OVERHEAD } from "./rt/common"; +import { compareImpl, strtol, strtod, isSpace, isAscii, isFinalSigma, toLower8, toUpper8 } from "./util/string"; +import { SPECIALS_UPPER, casemap, bsearch } from "./util/casemap"; +import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_UNPAIRED_SURROGATE } from "./util/error"; +import { idof } from "./builtins"; +import { Array } from "./array"; + +@final export abstract class String { + + @lazy static readonly MAX_LENGTH: i32 = (BLOCK_MAXSIZE >>> alignof()); + + static fromCharCode(unit: i32, surr: i32 = -1): String { + var hasSur = surr > 0; + var out = changetype(__new(2 << i32(hasSur), idof())); + store(changetype(out), unit); + if (hasSur) store(changetype(out), surr, 2); + return out; + } + + static fromCharCodes(units: Array): String { + var length = units.length; + var out = changetype(__new(length << 1, idof())); + var ptr = units.dataStart; + for (let i = 0; i < length; ++i) { + store(changetype(out) + (i << 1), load(ptr + (i << 2))); + } + return out; + } + + static fromCodePoint(code: i32): String { + var hasSur = code > 0xFFFF; + var out = changetype(__new(2 << i32(hasSur), idof())); + if (!hasSur) { + store(changetype(out), code); + } else { + // Checks valid code point range + assert(code <= 0x10FFFF); + code -= 0x10000; + let hi = (code & 0x03FF) | 0xDC00; + let lo = code >>> 10 | 0xD800; + store(changetype(out), lo | hi << 16); + } + return out; + } + + @builtin static raw(parts: TemplateStringsArray, ...args: unknown[]): string { return unreachable(); } + + get length(): i32 { + return changetype(changetype(this) - TOTAL_OVERHEAD).rtSize >> 1; + } + + at(pos: i32): String { + var len = this.length; + pos += select(0, len, pos >= 0); + if (pos >= len) throw new RangeError(E_INDEXOUTOFRANGE); + var out = __new(2, idof()); + store(out, load(changetype(this) + (pos << 1))); + return changetype(out); // retains + } + + @operator("[]") charAt(pos: i32): String { + if (pos >= this.length) return changetype(""); + var out = changetype(__new(2, idof())); + store(changetype(out), load(changetype(this) + (pos << 1))); + return out; + } + + charCodeAt(pos: i32): i32 { + if (pos >= this.length) return -1; // (NaN) + return load(changetype(this) + (pos << 1)); + } + + codePointAt(pos: i32): i32 { + var len = this.length; + if (pos >= len) return -1; // (undefined) + var first = load(changetype(this) + (pos << 1)); + if ((first & 0xFC00) != 0xD800 || pos + 1 == len) return first; + var second = load(changetype(this) + (pos << 1), 2); + if ((second & 0xFC00) != 0xDC00) return first; + return (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; + } + + @operator("+") private static __concat(left: String, right: String): String { + return left.concat(right); + } + + concat(other: String): String { + var thisSize: isize = this.length << 1; + var otherSize: isize = other.length << 1; + var outSize: usize = thisSize + otherSize; + if (outSize == 0) return changetype(""); + var out = changetype(__new(outSize, idof())); + memory.copy(changetype(out), changetype(this), thisSize); + memory.copy(changetype(out) + thisSize, changetype(other), otherSize); + return out; + } + + endsWith(search: String, end: i32 = String.MAX_LENGTH): bool { + end = min(max(end, 0), this.length); + var searchLength = search.length; + var searchStart = end - searchLength; + if (searchStart < 0) return false; + // @ts-ignore: string <-> String + return !compareImpl(this, searchStart, search, 0, searchLength); + } + + @operator("==") private static __eq(left: String | null, right: String | null): bool { + if (changetype(left) == changetype(right)) return true; + if (changetype(left) == 0 || changetype(right) == 0) return false; + var leftLength = changetype(left).length; + if (leftLength != changetype(right).length) return false; + // @ts-ignore: string <-> String + return !compareImpl(left, 0, right, 0, leftLength); + } + + @operator.prefix("!") + private static __not(str: String | null): bool { + return changetype(str) == 0 || !changetype(str).length; + } + + @operator("!=") + private static __ne(left: String | null, right: String | null): bool { + return !this.__eq(left, right); + } + + @operator(">") private static __gt(left: String, right: String): bool { + if (changetype(left) == changetype(right)) return false; + var leftLength = left.length; + if (!leftLength) return false; + var rightLength = right.length; + if (!rightLength) return true; + // @ts-ignore: string <-> String + var res = compareImpl(left, 0, right, 0, min(leftLength, rightLength)); + return res ? res > 0 : leftLength > rightLength; + } + + @operator(">=") private static __gte(left: String, right: String): bool { + return !this.__lt(left, right); + } + + @operator("<") private static __lt(left: String, right: String): bool { + if (changetype(left) == changetype(right)) return false; + var rightLength = right.length; + if (!rightLength) return false; + var leftLength = left.length; + if (!leftLength) return true; + // @ts-ignore: string <-> String + var res = compareImpl(left, 0, right, 0, min(leftLength, rightLength)); + return res ? res < 0 : leftLength < rightLength; + } + + @operator("<=") private static __lte(left: String, right: String): bool { + return !this.__gt(left, right); + } + + includes(search: String, start: i32 = 0): bool { + return this.indexOf(search, start) != -1; + } + + indexOf(search: String, start: i32 = 0): i32 { + var searchLen = search.length; + if (!searchLen) return 0; + var len = this.length; + if (!len) return -1; + var searchStart = min(max(start, 0), len); + for (len -= searchLen; searchStart <= len; ++searchStart) { + // @ts-ignore: string <-> String + if (!compareImpl(this, searchStart, search, 0, searchLen)) return searchStart; + } + return -1; + } + + lastIndexOf(search: String, start: i32 = i32.MAX_VALUE): i32 { + var searchLen = search.length; + if (!searchLen) return this.length; + var len = this.length; + if (!len) return -1; + var searchStart = min(max(start, 0), len - searchLen); + for (; searchStart >= 0; --searchStart) { + // @ts-ignore: string <-> String + if (!compareImpl(this, searchStart, search, 0, searchLen)) return searchStart; + } + return -1; + } + + // TODO: implement full locale comparison with locales and Collator options + localeCompare(other: String): i32 { + if (changetype(other) == changetype(this)) return 0; + var len: isize = this.length; + var otherLen: isize = other.length; + if (otherLen != len) return select(1, -1, len > otherLen); + if (!otherLen) return 0; // "" == "" + // @ts-ignore: string <-> String + return compareImpl(this, 0, other, 0, otherLen); + } + + startsWith(search: String, start: i32 = 0): bool { + var len = this.length; + var searchStart = min(max(start, 0), len); + var searchLength = search.length; + if (searchLength + searchStart > len) return false; + // @ts-ignore: string <-> String + return !compareImpl(this, searchStart, search, 0, searchLength); + } + + substr(start: i32, length: i32 = i32.MAX_VALUE): String { // legacy + var intStart: isize = start; + var end: isize = length; + var len: isize = this.length; + if (intStart < 0) intStart = max(len + intStart, 0); + var size = min(max(end, 0), len - intStart) << 1; + if (size <= 0) return changetype(""); + var out = changetype(__new(size, idof())); + memory.copy(changetype(out), changetype(this) + (intStart << 1), size); + return out; + } + + substring(start: i32, end: i32 = i32.MAX_VALUE): String { + var len: isize = this.length; + var finalStart = min(max(start, 0), len); + var finalEnd = min(max(end, 0), len); + var fromPos = min(finalStart, finalEnd) << 1; + var toPos = max(finalStart, finalEnd) << 1; + var size = toPos - fromPos; + if (!size) return changetype(""); + if (!fromPos && toPos == len << 1) return this; + var out = changetype(__new(size, idof())); + memory.copy(changetype(out), changetype(this) + fromPos, size); + return out; + } + + trim(): String { + var len = this.length; + var size: usize = len << 1; + while (size && isSpace(load(changetype(this) + size - 2))) { + size -= 2; + } + var offset: usize = 0; + while (offset < size && isSpace(load(changetype(this) + offset))) { + offset += 2; size -= 2; + } + if (!size) return changetype(""); + if (!offset && size == len << 1) return this; + var out = changetype(__new(size, idof())); + memory.copy(changetype(out), changetype(this) + offset, size); + return out; + } + + @inline + trimLeft(): String { + return this.trimStart(); + } + + @inline + trimRight(): String { + return this.trimEnd(); + } + + trimStart(): String { + var size = this.length << 1; + var offset: usize = 0; + while (offset < size && isSpace(load(changetype(this) + offset))) { + offset += 2; + } + if (!offset) return this; + size -= offset; + if (!size) return changetype(""); + var out = changetype(__new(size, idof())); + memory.copy(changetype(out), changetype(this) + offset, size); + return out; + } + + trimEnd(): String { + var originalSize = this.length << 1; + var size = originalSize; + while (size && isSpace(load(changetype(this) + size - 2))) { + size -= 2; + } + if (!size) return changetype(""); + if (size == originalSize) return this; + var out = changetype(__new(size, idof())); + memory.copy(changetype(out), changetype(this), size); + return out; + } + + padStart(length: i32, pad: string = " "): String { + var thisSize = this.length << 1; + var targetSize = length << 1; + var padSize = pad.length << 1; + if (targetSize < thisSize || !padSize) return this; + var prependSize = targetSize - thisSize; + var out = changetype(__new(targetSize, idof())); + if (prependSize > padSize) { + let repeatCount = (prependSize - 2) / padSize; + let restBase = repeatCount * padSize; + let restSize = prependSize - restBase; + memory.repeat(changetype(out), changetype(pad), padSize, repeatCount); + memory.copy(changetype(out) + restBase, changetype(pad), restSize); + } else { + memory.copy(changetype(out), changetype(pad), prependSize); + } + memory.copy(changetype(out) + prependSize, changetype(this), thisSize); + return out; + } + + padEnd(length: i32, pad: string = " "): String { + var thisSize = this.length << 1; + var targetSize = length << 1; + var padSize = pad.length << 1; + if (targetSize < thisSize || !padSize) return this; + var appendSize = targetSize - thisSize; + var out = changetype(__new(targetSize, idof())); + memory.copy(changetype(out), changetype(this), thisSize); + if (appendSize > padSize) { + let repeatCount = (appendSize - 2) / padSize; + let restBase = repeatCount * padSize; + let restSize = appendSize - restBase; + memory.repeat(changetype(out) + thisSize, changetype(pad), padSize, repeatCount); + memory.copy(changetype(out) + thisSize + restBase, changetype(pad), restSize); + } else { + memory.copy(changetype(out) + thisSize, changetype(pad), appendSize); + } + return out; + } + + repeat(count: i32 = 0): String { + var length = this.length; + + // Most browsers can't handle strings 1 << 28 chars or longer + if (count < 0 || length * count > (1 << 28)) { + throw new RangeError(E_INVALIDLENGTH); + } + + if (count == 0 || !length) return changetype(""); + if (count == 1) return this; + var out = changetype(__new((length * count) << 1, idof())); + memory.repeat(changetype(out), changetype(this), length << 1, count); + return out; + } + + replace(search: String, replacement: String): String { + var len: usize = this.length; + var slen: usize = search.length; + if (len <= slen) { + return len < slen ? this : select(replacement, this, search == this); + } + var index: isize = this.indexOf(search); + if (~index) { + let rlen: usize = replacement.length; + len -= slen; + let olen = len + rlen; + if (olen) { + let out = changetype(__new(olen << 1, idof())); + memory.copy(changetype(out), changetype(this), index << 1); + memory.copy( + changetype(out) + (index << 1), + changetype(replacement), + rlen << 1 + ); + memory.copy( + changetype(out) + ((index + rlen) << 1), + changetype(this) + ((index + slen) << 1), + (len - index) << 1 + ); + return out; + } + } + return this; + } + + replaceAll(search: String, replacement: String): String { + var thisLen: usize = this.length; + var searchLen: usize = search.length; + if (thisLen <= searchLen) { + return thisLen < searchLen + ? this + : select(replacement, this, search == this); + } + var replaceLen: usize = replacement.length; + if (!searchLen) { + if (!replaceLen) return this; + // Special case: 'abc'.replaceAll('', '-') -> '-a-b-c-' + let out = changetype(__new((thisLen + (thisLen + 1) * replaceLen) << 1, idof())); + memory.copy(changetype(out), changetype(replacement), replaceLen << 1); + let offset = replaceLen; + for (let i: usize = 0; i < thisLen; ++i) { + store( + changetype(out) + (offset++ << 1), + load(changetype(this) + (i << 1)) + ); + memory.copy( + changetype(out) + (offset << 1), + changetype(replacement), + replaceLen << 1 + ); + offset += replaceLen; + } + return out; + } + var prev: isize = 0, next: isize = 0; + if (searchLen == replaceLen) { + // Fast path when search and replacement have same length + let outSize = thisLen << 1; + let out = changetype(__new(outSize, idof())); + memory.copy(changetype(out), changetype(this), outSize); + while (~(next = this.indexOf(search, prev))) { + memory.copy(changetype(out) + (next << 1), changetype(replacement), replaceLen << 1); + prev = next + searchLen; + } + return out; + } + var out: String | null = null, offset: usize = 0, outSize = thisLen; + while (~(next = this.indexOf(search, prev))) { + if (!out) out = changetype(__new(thisLen << 1, idof())); + let chunk = next - prev; + if (offset + chunk + replaceLen > outSize) { + outSize <<= 1; + out = changetype(__renew(changetype(out), outSize << 1)); + } + memory.copy( + changetype(out) + (offset << 1), + changetype(this) + (prev << 1), + chunk << 1 + ); + offset += chunk; + memory.copy( + changetype(out) + (offset << 1), + changetype(replacement), + replaceLen << 1 + ); + offset += replaceLen; + prev = next + searchLen; + } + if (out) { + let rest = thisLen - prev; + if (offset + rest > outSize) { + outSize <<= 1; + out = changetype(__renew(changetype(out), outSize << 1)); + } + if (rest) { + memory.copy( + changetype(out) + (offset << 1), + changetype(this) + (prev << 1), + rest << 1 + ); + } + rest += offset; + if (outSize > rest) { + out = changetype(__renew(changetype(out), rest << 1)); + } + return out; + } + return this; + } + + slice(start: i32, end: i32 = i32.MAX_VALUE): String { + var len = this.length; + start = start < 0 ? max(start + len, 0) : min(start, len); + end = end < 0 ? max(end + len, 0) : min(end, len); + len = end - start; + if (len <= 0) return changetype(""); + var out = changetype(__new(len << 1, idof())); + memory.copy(changetype(out), changetype(this) + (start << 1), len << 1); + return out; + } + + split(separator: String | null = null, limit: i32 = i32.MAX_VALUE): String[] { + if (!limit) return changetype(__newArray(0, alignof(), idof>())); + if (changetype(separator) == 0) return [ this ]; + var length: isize = this.length; + var sepLen = changetype(separator).length; + if (limit < 0) limit = i32.MAX_VALUE; + if (!sepLen) { + if (!length) return changetype(__newArray(0, alignof(), idof>())); + // split by chars + length = min(length, limit); + let result = changetype(__newArray(length, alignof(), idof>())); + // @ts-ignore: cast + let resultStart = result.dataStart as usize; + for (let i: isize = 0; i < length; ++i) { + let charStr = changetype(__new(2, idof())); + store(changetype(charStr), load(changetype(this) + (i << 1))); + store(resultStart + (i << alignof()), changetype(charStr)); // result[i] = charStr + __link(changetype(result), changetype(charStr), true); + } + return result; + } else if (!length) { + let result = changetype(__newArray(1, alignof(), idof>())); + // @ts-ignore: cast + store(result.dataStart as usize, changetype("")); // static "" + return result; + } + var result = changetype(__newArray(0, alignof(), idof>())); + var end = 0, start = 0, i = 0; + while (~(end = this.indexOf(changetype(separator), start))) { + let len = end - start; + if (len > 0) { + let out = changetype(__new(len << 1, idof())); + memory.copy(changetype(out), changetype(this) + (start << 1), len << 1); + result.push(out); + } else { + result.push(changetype("")); + } + if (++i == limit) return result; + start = end + sepLen; + } + if (!start) { // also means: loop above didn't do anything + result.push(this); + return result; + } + var len = length - start; + if (len > 0) { + let out = changetype(__new(len << 1, idof())); + memory.copy(changetype(out), changetype(this) + (start << 1), len << 1); + result.push(out); + } else { + result.push(changetype("")); // static "" + } + return result; + } + + toLowerCase(): String { + var len = this.length; + if (!len) return this; + var codes = changetype(__new(len * 2 * 2, idof())); + var j: usize = 0; + for (let i: usize = 0; i < len; ++i, ++j) { + let c = load(changetype(this) + (i << 1)); + if (isAscii(c)) { + store(changetype(codes) + (j << 1), toLower8(c)); + } else { + // check and read surrogate pair + if ((c - 0xD7FF < 0xDC00 - 0xD7FF) && i < len - 1) { + let c1 = load(changetype(this) + (i << 1), 2); + if (c1 - 0xDBFF < 0xE000 - 0xDBFF) { + let c0 = c; + c = (((c & 0x03FF) << 10) | (c1 & 0x03FF)) + 0x10000; + ++i; + if (c >= 0x20000) { + store(changetype(codes) + (j << 1), c0 | (c1 << 16)); + ++j; + continue; + } + } + } + // check special casing for lower table. It has one ently so instead lookup we just inline this. + if (c == 0x0130) { + // 0x0130 -> [0x0069, 0x0307] + store(changetype(codes) + (j << 1), (0x0307 << 16) | 0x0069); + ++j; + } else if (c == 0x03A3) { // '\u03A3' + // \u03A3 maps to \u03C3 but except at the end of a word where it maps to \u03C2 + let sigma = 0x03C3; // \u03C3 + if (len > 1 && isFinalSigma(changetype(this), i, len)) { + sigma = 0x03C2; // \u03C2 + } + store(changetype(codes) + (j << 1), sigma); + } else if (c - 0x24B6 <= 0x24CF - 0x24B6) { + // Range 0x24B6 <= c <= 0x24CF not covered by casemap and require special early handling + store(changetype(codes) + (j << 1), c + 26); + } else { + let code = casemap(c, 0) & 0x1FFFFF; + if (code < 0x10000) { + store(changetype(codes) + (j << 1), code); + } else { + // store as surrogare pair + code -= 0x10000; + let lo = (code >>> 10) | 0xD800; + let hi = (code & 0x03FF) | 0xDC00; + store(changetype(codes) + (j << 1), lo | (hi << 16)); + ++j; + } + } + } + } + return changetype(__renew(changetype(codes), j << 1)); + } + + toUpperCase(): String { + var len = this.length; + if (!len) return this; + var codes = changetype(__new(len * 3 * 2, idof())); + var specialsPtr = changetype(SPECIALS_UPPER); + var specialsLen = SPECIALS_UPPER.length; + var j: usize = 0; + for (let i: usize = 0; i < len; ++i, ++j) { + let c = load(changetype(this) + (i << 1)); + if (isAscii(c)) { + store(changetype(codes) + (j << 1), toUpper8(c)); + } else { + // check and read surrogate pair + if ((c - 0xD7FF < 0xDC00 - 0xD7FF) && i < len - 1) { + let c1 = load(changetype(this) + (i << 1), 2); + if (c1 - 0xDBFF < 0xE000 - 0xDBFF) { + let c0 = c; + c = (((c & 0x03FF) << 10) | (c1 & 0x03FF)) + 0x10000; + ++i; + if (c >= 0x20000) { + store(changetype(codes) + (j << 1), c0 | (c1 << 16)); + ++j; + continue; + } + } + } + // Range 0x24D0 <= c <= 0x24E9 not covered by casemap and require special early handling + if (c - 0x24D0 <= 0x24E9 - 0x24D0) { + // monkey patch + store(changetype(codes) + (j << 1), c - 26); + } else { + let index: usize = -1; + // Fast range check. See first and last rows in specialsUpper table + if (c - 0x00DF <= 0xFB17 - 0x00DF) { + index = bsearch(c, specialsPtr, specialsLen); + } + if (~index) { + // load next 3 code points from row with \`index\` offset for specialsUpper table + let ab = load(specialsPtr + (index << 1), 2); + let cc = load(specialsPtr + (index << 1), 6); + store(changetype(codes) + (j << 1), ab, 0); + store(changetype(codes) + (j << 1), cc, 4); + j += 1 + usize(cc != 0); + } else { + let code = casemap(c, 1) & 0x1FFFFF; + if (code < 0x10000) { + store(changetype(codes) + (j << 1), code); + } else { + // store as surrogare pair + code -= 0x10000; + let lo = (code >>> 10) | 0xD800; + let hi = (code & 0x03FF) | 0xDC00; + store(changetype(codes) + (j << 1), lo | (hi << 16)); + ++j; + } + } + } + } + } + return changetype(__renew(changetype(codes), j << 1)); + } + + toString(): String { + return this; + } +} + +// @ts-ignore: nolib +export type string = String; + +export function parseInt(str: string, radix: i32 = 0): f64 { + return strtol(str, radix); +} + +export function parseFloat(str: string): f64 { + return strtod(str); +} + +// Encoding helpers +export namespace String { + + export namespace UTF8 { + + export const enum ErrorMode { + WTF8, + REPLACE, + ERROR + } + + export function byteLength(str: string, nullTerminated: bool = false): i32 { + var strOff = changetype(str); + var strEnd = strOff + changetype(changetype(str) - TOTAL_OVERHEAD).rtSize; + var bufLen = i32(nullTerminated); + while (strOff < strEnd) { + let c1 = load(strOff); + if (c1 < 128) { + // @ts-ignore: cast + if (nullTerminated & !c1) break; + bufLen += 1; + } else if (c1 < 2048) { + bufLen += 2; + } else { + if ((c1 & 0xFC00) == 0xD800 && strOff + 2 < strEnd) { + if ((load(strOff, 2) & 0xFC00) == 0xDC00) { + bufLen += 4; strOff += 4; + continue; + } + } + bufLen += 3; + } + strOff += 2; + } + return bufLen; + } + + export function encode(str: string, nullTerminated: bool = false, errorMode: ErrorMode = ErrorMode.WTF8): ArrayBuffer { + var buf = changetype(__new(byteLength(str, nullTerminated), idof())); + encodeUnsafe(changetype(str), str.length, changetype(buf), nullTerminated, errorMode); + return buf; + } + + // @ts-ignore: decorator + @unsafe + export function encodeUnsafe(str: usize, len: i32, buf: usize, nullTerminated: bool = false, errorMode: ErrorMode = ErrorMode.WTF8): usize { + var strEnd = str + (len << 1); + var bufOff = buf; + while (str < strEnd) { + let c1 = load(str); + if (c1 < 128) { + store(bufOff, c1); + bufOff++; + // @ts-ignore: cast + if (nullTerminated & !c1) return bufOff - buf; + } else if (c1 < 2048) { + let b0 = c1 >> 6 | 192; + let b1 = c1 & 63 | 128; + store(bufOff, b1 << 8 | b0); + bufOff += 2; + } else { + // D800: 11011 0 0000000000 Lead + // DBFF: 11011 0 1111111111 + // DC00: 11011 1 0000000000 Trail + // DFFF: 11011 1 1111111111 + // F800: 11111 0 0000000000 Mask + // FC00: 11111 1 0000000000 + if ((c1 & 0xF800) == 0xD800) { + if (c1 < 0xDC00 && str + 2 < strEnd) { + let c2 = load(str, 2); + if ((c2 & 0xFC00) == 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) | (c2 & 0x03FF); + let b0 = c1 >> 18 | 240; + let b1 = c1 >> 12 & 63 | 128; + let b2 = c1 >> 6 & 63 | 128; + let b3 = c1 & 63 | 128; + store(bufOff, b3 << 24 | b2 << 16 | b1 << 8 | b0); + bufOff += 4; str += 4; + continue; + } + } + if (errorMode != ErrorMode.WTF8) { // unlikely + if (errorMode == ErrorMode.ERROR) throw new Error(E_UNPAIRED_SURROGATE); + c1 = 0xFFFD; + } + } + let b0 = c1 >> 12 | 224; + let b1 = c1 >> 6 & 63 | 128; + let b2 = c1 & 63 | 128; + store(bufOff, b1 << 8 | b0); + store(bufOff, b2, 2); + bufOff += 3; + } + str += 2; + } + if (nullTerminated) { + store(bufOff++, 0); + } + return bufOff - buf; + } + + export function decode(buf: ArrayBuffer, nullTerminated: bool = false): String { + return decodeUnsafe(changetype(buf), buf.byteLength, nullTerminated); + } + + // @ts-ignore: decorator + @unsafe + export function decodeUnsafe(buf: usize, len: usize, nullTerminated: bool = false): String { + var bufOff = buf; + var bufEnd = buf + len; + assert(bufEnd >= bufOff); // guard wraparound + var str = changetype(__new(len << 1, idof())); // max is one u16 char per u8 byte + var strOff = changetype(str); + while (bufOff < bufEnd) { + let u0 = load(bufOff); ++bufOff; + if (!(u0 & 128)) { + // @ts-ignore: cast + if (nullTerminated & !u0) break; + store(strOff, u0); + } else { + if (bufEnd == bufOff) break; + let u1 = load(bufOff) & 63; ++bufOff; + if ((u0 & 224) == 192) { + store(strOff, (u0 & 31) << 6 | u1); + } else { + if (bufEnd == bufOff) break; + let u2 = load(bufOff) & 63; ++bufOff; + if ((u0 & 240) == 224) { + u0 = (u0 & 15) << 12 | u1 << 6 | u2; + } else { + if (bufEnd == bufOff) break; + u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | load(bufOff) & 63; + ++bufOff; + } + if (u0 < 0x10000) { + store(strOff, u0); + } else { + u0 -= 0x10000; + let lo = u0 >> 10 | 0xD800; + let hi = (u0 & 0x03FF) | 0xDC00; + store(strOff, lo | (hi << 16)); + strOff += 2; + } + } + } + strOff += 2; + } + return changetype(__renew(changetype(str), strOff - changetype(str))); + } + } + + export namespace UTF16 { + + export function byteLength(str: string): i32 { + return changetype(changetype(str) - TOTAL_OVERHEAD).rtSize; + } + + export function encode(str: string): ArrayBuffer { + var buf = changetype(__new(byteLength(str), idof())); + encodeUnsafe(changetype(str), str.length, changetype(buf)); + return buf; + } + + // @ts-ignore: decorator + @unsafe + export function encodeUnsafe(str: usize, len: i32, buf: usize): usize { + var size = len << 1; + memory.copy(buf, changetype(str), size); + return size; + } + + export function decode(buf: ArrayBuffer): String { + return decodeUnsafe(changetype(buf), buf.byteLength); + } + + // @ts-ignore: decorator + @unsafe + export function decodeUnsafe(buf: usize, len: usize): String { + var str = changetype(__new(len &= ~1, idof())); + memory.copy(changetype(str), buf, len); + return str; + } + } +} + +export class TemplateStringsArray extends Array { + readonly raw: string[]; +} +`,symbol:`import { Map } from "./map"; + +// @ts-ignore: decorator +@lazy var stringToId: Map; + +// @ts-ignore: decorator +@lazy var idToString: Map; + +// @ts-ignore: decorator +@lazy var nextId: usize = 12; // Symbol.unscopables + 1 + +@unmanaged @final abstract class _Symbol { + + // TODO: all of the following default symbols are unused currently yet add to + // binary size if #toString becomes compiled. Ultimately we'll most likely want + // to remove the unsupported ones and only keep what's actually supported. + + // @ts-ignore: decorator + @lazy + static readonly hasInstance: symbol = changetype(1); + + // @ts-ignore: decorator + @lazy + static readonly isConcatSpreadable: symbol = changetype(2); + + // @ts-ignore: decorator + @lazy + static readonly isRegExp: symbol = changetype(3); + + // @ts-ignore: decorator + @lazy + static readonly iterator: symbol = changetype(3); + + // @ts-ignore: decorator + @lazy + static readonly match: symbol = changetype(4); + + // @ts-ignore: decorator + @lazy + static readonly replace: symbol = changetype(5); + + // @ts-ignore: decorator + @lazy + static readonly search: symbol = changetype(6); + + // @ts-ignore: decorator + @lazy + static readonly species: symbol = changetype(7); + + // @ts-ignore: decorator + @lazy + static readonly split: symbol = changetype(8); + + // @ts-ignore: decorator + @lazy + static readonly toPrimitive: symbol = changetype(9); + + // @ts-ignore: decorator + @lazy + static readonly toStringTag: symbol = changetype(10); + + // @ts-ignore: decorator + @lazy + static readonly unscopables: symbol = changetype(11); + + static for(key: string): symbol { + if (!stringToId) { stringToId = new Map(); idToString = new Map(); } + else if (stringToId.has(key)) return changetype(stringToId.get(key)); + var id = nextId++; + if (!id) unreachable(); // out of ids + stringToId.set(key, id); + idToString.set(id, key); + return changetype(id); + } + + static keyFor(sym: symbol): string | null { + return idToString != null && idToString.has(changetype(sym)) + ? idToString.get(changetype(sym)) + : null; + } + + toString(): string { + var id = changetype(this); + var str = ""; + switch (id) { + case 1: { str = "hasInstance"; break; } + case 2: { str = "isConcatSpreadable"; break; } + case 3: { str = "isRegExp"; break; } + case 4: { str = "match"; break; } + case 5: { str = "replace"; break; } + case 6: { str = "search"; break; } + case 7: { str = "species"; break; } + case 8: { str = "split"; break; } + case 9: { str = "toPrimitive"; break; } + case 10: { str = "toStringTag"; break; } + case 11: { str = "unscopables"; break; } + default: { + if (idToString != null && idToString.has(id)) str = idToString.get(id); + break; + } + } + return "Symbol(" + str + ")"; + } +} + +export function Symbol(description: string | null = null): symbol { + var id = nextId++; + if (!id) unreachable(); // out of ids + return changetype(id); +} + +export type Symbol = _Symbol; + +// @ts-ignore: nolib +export type symbol = _Symbol; +`,table:`import { E_NOTIMPLEMENTED } from "./util/error"; + +export namespace table { + + export function copy(dst: u32, src: u32, n: u32): void { + throw new Error(E_NOTIMPLEMENTED); + } + + export function init(elementIndex: u32, srcOffset: u32, dstOffset: u32, n: u32): void { + throw new Error(E_NOTIMPLEMENTED); + } + + export function drop(elementIndex: u32): void { + throw new Error(E_NOTIMPLEMENTED); + } +} +`,typedarray:`import { COMPARATOR, SORT } from "./util/sort"; +import { E_INDEXOUTOFRANGE, E_INVALIDLENGTH, E_NOTIMPLEMENTED } from "./util/error"; +import { joinIntegerArray, joinFloatArray } from "./util/string"; +import { REVERSE } from "./util/bytes"; +import { idof } from "./builtins"; +import { ArrayBufferView } from "./arraybuffer"; + +export class Int8Array extends ArrayBufferView { + [key: number]: i8; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength; + } + + @operator("[]") + private __get(index: i32): i8 { + if (index >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + index); + } + + @unsafe @operator("{}") + private __uget(index: i32): i8 { + return load(this.dataStart + index); + } + + @operator("[]=") + private __set(index: i32, value: native): void { + if (index >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + index, value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: native): void { + store(this.dataStart + index, value); + } + + at(index: i32): i8 { + var len = this.byteLength; + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + index); + } + + includes(searchElement: i8, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: i8, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: i8, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: i32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Int8Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: i8, b: i8) => i32 = COMPARATOR()): Int8Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int8Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int8Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Int8Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: i8, index: i32, array: Int8Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: i8, index: i32, array: Int8Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: i8, index: i32, self: Int8Array) => i8): Int8Array { + return MAP(this, fn); + } + + filter(fn: (value: i8, index: i32, self: Int8Array) => bool): Int8Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: i8, index: i32, self: Int8Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: i8, index: i32, self: Int8Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: i8, index: i32, self: Int8Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: i8, index: i32, self: Int8Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: i8, index: i32, self: Int8Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + toString(): string { + return this.join(); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Int8Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Uint8Array extends ArrayBufferView { + [key: number]: u8; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength; + } + + @operator("[]") + private __get(index: i32): u8 { + if (index >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + index); + } + + @unsafe @operator("{}") + private __uget(index: i32): u8 { + return load(this.dataStart + index); + } + + @operator("[]=") + private __set(index: i32, value: native): void { + if (index >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + index, value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: native): void { + store(this.dataStart + index, value); + } + + at(index: i32): u8 { + var len = this.byteLength; + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + index); + } + + includes(searchElement: u8, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: u8, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: u8, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: u32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Uint8Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: u8, b: u8) => i32 = COMPARATOR()): Uint8Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint8Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint8Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Uint8Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: u8, index: i32, array: Uint8Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: u8, index: i32, array: Uint8Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: u8, index: i32, self: Uint8Array) => u8): Uint8Array { + return MAP(this, fn); + } + + filter(fn: (value: u8, index: i32, self: Uint8Array) => bool): Uint8Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: u8, index: i32, self: Uint8Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: u8, index: i32, self: Uint8Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: u8, index: i32, self: Uint8Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: u8, index: i32, self: Uint8Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: u8, index: i32, self: Uint8Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Uint8Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Uint8ClampedArray extends ArrayBufferView { + [key: number]: u8; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength; + } + + @operator("[]") + private __get(index: i32): u8 { + if (index >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + index); + } + + @unsafe @operator("{}") + private __uget(index: i32): u8 { + return load(this.dataStart + index); + } + + @operator("[]=") + private __set(index: i32, value: native): void { + if (index >= this.byteLength) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + index, ~(value >> 31) & (((255 - value) >> 31) | value)); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: native): void { + store(this.dataStart + index, ~(value >> 31) & (((255 - value) >> 31) | value)); + } + + at(index: i32): u8 { + var len = this.byteLength; + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + index); + } + + includes(searchElement: u8, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: u8, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: u8, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: u32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Uint8ClampedArray { + return FILL(this, value, start, end); + } + + sort(comparator: (a: u8, b: u8) => i32 = COMPARATOR()): Uint8ClampedArray { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint8ClampedArray { + return SLICE(this, begin, end); + } + + subarray(start: i32 = 0, end: i32 = i32.MAX_VALUE): Uint8ClampedArray { + return SUBARRAY(this, start, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Uint8ClampedArray { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: u8, index: i32, array: Uint8ClampedArray) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: u8, index: i32, array: Uint8ClampedArray) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: u8, index: i32, self: Uint8ClampedArray) => u8): Uint8ClampedArray { + return MAP(this, fn); + } + + filter(fn: (value: u8, index: i32, self: Uint8ClampedArray) => bool): Uint8ClampedArray { + return FILTER(this, fn); + } + + findIndex(fn: (value: u8, index: i32, self: Uint8ClampedArray) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: u8, index: i32, self: Uint8ClampedArray) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: u8, index: i32, self: Uint8ClampedArray) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: u8, index: i32, self: Uint8ClampedArray) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: u8, index: i32, self: Uint8ClampedArray) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Uint8ClampedArray { + return WRAP(buffer, byteOffset, length); + } +} + +export class Int16Array extends ArrayBufferView { + [key: number]: i16; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): i16 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): i16 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: native): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: native): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): i16 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: i16, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: i16, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: i16, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: i32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Int16Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: i16, b: i16) => i32 = COMPARATOR()): Int16Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int16Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int16Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Int16Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: i16, index: i32, array: Int16Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: i16, index: i32, array: Int16Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: i16, index: i32, self: Int16Array) => i16): Int16Array { + return MAP(this, fn); + } + + filter(fn: (value: i16, index: i32, self: Int16Array) => bool): Int16Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: i16, index: i32, self: Int16Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: i16, index: i32, self: Int16Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: i16, index: i32, self: Int16Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: i16, index: i32, self: Int16Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: i16, index: i32, self: Int16Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Int16Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Uint16Array extends ArrayBufferView { + [key: number]: u16; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): u16 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): u16 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: native): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: native): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): u16 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: u16, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: u16, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: u16, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: u32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Uint16Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: u16, b: u16) => i32 = COMPARATOR()): Uint16Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint16Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint16Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Uint16Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: u16, index: i32, array: Uint16Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: u16, index: i32, array: Uint16Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: u16, index: i32, self: Uint16Array) => u16): Uint16Array { + return MAP(this, fn); + } + + filter(fn: (value: u16, index: i32, self: Uint16Array) => bool): Uint16Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: u16, index: i32, self: Uint16Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: u16, index: i32, self: Uint16Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: u16, index: i32, self: Uint16Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: u16, index: i32, self: Uint16Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: u16, index: i32, self: Uint16Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Uint16Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Int32Array extends ArrayBufferView { + [key: number]: i32; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): i32 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): i32 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: i32): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: i32): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): i32 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: i32, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: i32, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: i32, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: i32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Int32Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: i32, b: i32) => i32 = COMPARATOR()): Int32Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int32Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int32Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Int32Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: i32, index: i32, array: Int32Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: i32, index: i32, array: Int32Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: i32, index: i32, self: Int32Array) => i32): Int32Array { + return MAP(this, fn); + } + + filter(fn: (value: i32, index: i32, self: Int32Array) => bool): Int32Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: i32, index: i32, self: Int32Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: i32, index: i32, self: Int32Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: i32, index: i32, self: Int32Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: i32, index: i32, self: Int32Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: i32, index: i32, self: Int32Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Int32Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Uint32Array extends ArrayBufferView { + [key: number]: u32; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): u32 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): u32 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: u32): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: u32): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): u32 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: u32, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: u32, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: u32, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: u32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Uint32Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: u32, b: u32) => i32 = COMPARATOR()): Uint32Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint32Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint32Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Uint32Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: u32, index: i32, array: Uint32Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: u32, index: i32, array: Uint32Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: u32, index: i32, self: Uint32Array) => u32): Uint32Array { + return MAP(this, fn); + } + + filter(fn: (value: u32, index: i32, self: Uint32Array) => bool): Uint32Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: u32, index: i32, self: Uint32Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: u32, index: i32, self: Uint32Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: u32, index: i32, self: Uint32Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: u32, index: i32, self: Uint32Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: u32, index: i32, self: Uint32Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Uint32Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Int64Array extends ArrayBufferView { + [key: number]: i64; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): i64 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): i64 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: i64): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: i64): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): i64 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: i64, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: i64, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: i64, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: i64, start: i32 = 0, end: i32 = i32.MAX_VALUE): Int64Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: i64, b: i64) => i32 = COMPARATOR()): Int64Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int64Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Int64Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Int64Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: i64, index: i32, array: Int64Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: i64, index: i32, array: Int64Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: i64, index: i32, self: Int64Array) => i64): Int64Array { + return MAP(this, fn); + } + + filter(fn: (value: i64, index: i32, self: Int64Array) => bool): Int64Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: i64, index: i32, self: Int64Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: i64, index: i32, self: Int64Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: i64, index: i32, self: Int64Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: i64, index: i32, self: Int64Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: i64, index: i32, self: Int64Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Int64Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Uint64Array extends ArrayBufferView { + [key: number]: u64; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): u64 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): u64 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: u64): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: u64): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): u64 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: u64, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: u64, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: u64, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: u64, start: i32 = 0, end: i32 = i32.MAX_VALUE): Uint64Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: u64, b: u64) => i32 = COMPARATOR()): Uint64Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint64Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Uint64Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Uint64Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: u64, index: i32, array: Uint64Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: u64, index: i32, array: Uint64Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: u64, index: i32, self: Uint64Array) => u64): Uint64Array { + return MAP(this, fn); + } + + filter(fn: (value: u64, index: i32, self: Uint64Array) => bool): Uint64Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: u64, index: i32, self: Uint64Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: u64, index: i32, self: Uint64Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: u64, index: i32, self: Uint64Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: u64, index: i32, self: Uint64Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: u64, index: i32, self: Uint64Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinIntegerArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Uint64Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Float32Array extends ArrayBufferView { + [key: number]: f32; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): f32 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): f32 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: f32): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: f32): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): f32 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: f32, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: f32, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: f32, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: f32, start: i32 = 0, end: i32 = i32.MAX_VALUE): Float32Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: f32, b: f32) => i32 = COMPARATOR()): Float32Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Float32Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Float32Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Float32Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: f32, index: i32, array: Float32Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: f32, index: i32, array: Float32Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: f32, index: i32, self: Float32Array) => f32): Float32Array { + return MAP(this, fn); + } + + filter(fn: (value: f32, index: i32, self: Float32Array) => bool): Float32Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: f32, index: i32, self: Float32Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: f32, index: i32, self: Float32Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: f32, index: i32, self: Float32Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: f32, index: i32, self: Float32Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: f32, index: i32, self: Float32Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinFloatArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Float32Array { + return WRAP(buffer, byteOffset, length); + } +} + +export class Float64Array extends ArrayBufferView { + [key: number]: f64; + + // @ts-ignore: decorator + @lazy + static readonly BYTES_PER_ELEMENT: i32 = sizeof(); + + constructor(length: i32) { + super(length, alignof()); + } + + get length(): i32 { + return this.byteLength >>> alignof(); + } + + @operator("[]") + private __get(index: i32): f64 { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + @unsafe @operator("{}") + private __uget(index: i32): f64 { + return load(this.dataStart + (index << alignof())); + } + + @operator("[]=") + private __set(index: i32, value: f64): void { + if (index >= this.byteLength >>> alignof()) throw new RangeError(E_INDEXOUTOFRANGE); + store(this.dataStart + (index << alignof()), value); + } + + @unsafe @operator("{}=") + private __uset(index: i32, value: f64): void { + store(this.dataStart + (index << alignof()), value); + } + + at(index: i32): f64 { + var len = this.byteLength >>> alignof(); + index += select(0, len, index >= 0); + if (index >= len) throw new RangeError(E_INDEXOUTOFRANGE); + return load(this.dataStart + (index << alignof())); + } + + includes(searchElement: f64, fromIndex: i32 = 0): bool { + return INCLUDES(this, searchElement, fromIndex); + } + + indexOf(searchElement: f64, fromIndex: i32 = 0): i32 { + return INDEX_OF(this, searchElement, fromIndex); + } + + lastIndexOf(searchElement: f64, fromIndex: i32 = this.length): i32 { + return LAST_INDEX_OF(this, searchElement, fromIndex); + } + + fill(value: f64, start: i32 = 0, end: i32 = i32.MAX_VALUE): Float64Array { + return FILL(this, value, start, end); + } + + sort(comparator: (a: f64, b: f64) => i32 = COMPARATOR()): Float64Array { + SORT(this.dataStart, this.length, comparator); + return this; + } + + slice(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Float64Array { + return SLICE(this, begin, end); + } + + subarray(begin: i32 = 0, end: i32 = i32.MAX_VALUE): Float64Array { + return SUBARRAY(this, begin, end); + } + + copyWithin(target: i32, start: i32, end: i32 = i32.MAX_VALUE): Float64Array { + return COPY_WITHIN(this, target, start, end); + } + + reduce( + fn: (accumulator: T, value: f64, index: i32, array: Float64Array) => T, + initialValue: T, + ): T { + return REDUCE(this, fn, initialValue); + } + + reduceRight( + fn: (accumulator: T, value: f64, index: i32, array: Float64Array) => T, + initialValue: T, + ): T { + return REDUCE_RIGHT(this, fn, initialValue); + } + + map(fn: (value: f64, index: i32, self: Float64Array) => f64): Float64Array { + return MAP(this, fn); + } + + filter(fn: (value: f64, index: i32, self: Float64Array) => bool): Float64Array { + return FILTER(this, fn); + } + + findIndex(fn: (value: f64, index: i32, self: Float64Array) => bool): i32 { + return FIND_INDEX(this, fn); + } + + findLastIndex(fn: (value: f64, index: i32, self: Float64Array) => bool): i32 { + return FIND_LAST_INDEX(this, fn); + } + + some(fn: (value: f64, index: i32, self: Float64Array) => bool): bool { + return SOME(this, fn); + } + + every(fn: (value: f64, index: i32, self: Float64Array) => bool): bool { + return EVERY(this, fn); + } + + forEach(fn: (value: f64, index: i32, self: Float64Array) => void): void { + FOREACH(this, fn); + } + + reverse(): this { + REVERSE(this.dataStart, this.length); + return this; + } + + join(separator: string = ","): string { + return joinFloatArray(this.dataStart, this.length, separator); + } + + set(source: U, offset: i32 = 0): void { + SET>(this, source, offset); + } + + toString(): string { + return this.join(); + } + + static wrap(buffer: ArrayBuffer, byteOffset: i32 = 0, length: i32 = -1): Float64Array { + return WRAP(buffer, byteOffset, length); + } +} + +// @ts-ignore: decorator +@inline +function FILL( + array: TArray, + value: native, + start: i32, + end: i32 +): TArray { + var ptr = array.dataStart; + var len = array.length; + start = start < 0 ? max(len + start, 0) : min(start, len); + end = end < 0 ? max(len + end, 0) : min(end, len); + if (sizeof() == 1) { + if (start < end) memory.fill(ptr + start, value, (end - start)); + } else { + for (; start < end; ++start) { + store(ptr + (start << alignof()), value); + } + } + return array; +} + +// @ts-ignore: decorator +@inline +function SLICE( + array: TArray, + start: i32, + end: i32 +): TArray { + var len = array.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); + var slice = instantiate(len); + memory.copy( + slice.dataStart, + array.dataStart + (start << alignof()), + len << alignof() + ); + return slice; +} + +// @ts-ignore: decorator +@inline +function SUBARRAY( + array: TArray, + begin: i32, + end: i32 +): TArray { + var len = array.length; + begin = begin < 0 ? max(len + begin, 0) : min(begin, len); + end = end < 0 ? max(len + end, 0) : min(end, len); + end = max(end, begin); + + var out = changetype(__new(offsetof(), idof())); + var buf = changetype(array.buffer); + store(changetype(out), buf, offsetof("buffer")); + __link(changetype(out), buf, false); + store(changetype(out), array.dataStart + (begin << alignof()), offsetof("dataStart")); + store(changetype(out), (end - begin) << alignof(), offsetof("byteLength")); + return out; +} + +// @ts-ignore: decorator +@inline +function COPY_WITHIN( + array: TArray, + target: i32, + start: i32, + end: i32 +): TArray { + var len = array.length; + var ptr = array.dataStart; + + end = min(end, len); + var to = target < 0 ? max(len + target, 0) : min(target, len); + var from = start < 0 ? max(len + start, 0) : min(start, len); + var last = end < 0 ? max(len + end, 0) : min(end, len); + var count = min(last - from, len - to); + + memory.copy( + ptr + (to << alignof()), + ptr + (from << alignof()), + count << alignof() + ); + return array; +} + +// @ts-ignore: decorator +@inline +function REDUCE( + array: TArray, + fn: (accumulator: TRet, value: T, index: i32, array: TArray) => TRet, + initialValue: TRet +): TRet { + var ptr = array.dataStart; + for (let i = 0, k = array.length; i < k; i++) { + initialValue = fn(initialValue, load(ptr + (i << alignof())), i, array); + } + return initialValue; +} + +// @ts-ignore: decorator +@inline +function REDUCE_RIGHT( + array: TArray, + fn: (accumulator: TRet, value: T, index: i32, array: TArray) => TRet, + initialValue: TRet +): TRet { + var ptr = array.dataStart; + for (let i = array.length - 1; i >= 0; i--) { + initialValue = fn(initialValue, load(ptr + (i << alignof())), i, array); + } + return initialValue; +} + +// @ts-ignore: decorator +@inline +function MAP( + array: TArray, + fn: (value: T, index: i32, self: TArray) => T, +): TArray { + var len = array.length; + var ptr = array.dataStart; + + var byteLength = len << alignof(); + var out = changetype(__new(offsetof(), idof())); + var buf = changetype(__new(byteLength, idof())); + for (let i = 0; i < len; i++) { + store( + changetype(buf) + (i << alignof()), + fn(load(ptr + (i << alignof())), i, array) + ); + } + store(changetype(out), changetype(buf), offsetof("buffer")); + __link(changetype(out), changetype(buf), false); + store(changetype(out), changetype(buf), offsetof("dataStart")); + store(changetype(out), byteLength, offsetof("byteLength")); + return out; +} + +// @ts-ignore: decorator +@inline +function FILTER( + array: TArray, + fn: (value: T, index: i32, self: TArray) => bool, +): TArray { + var len = array.length; + var out = changetype(__new(offsetof(), idof())); + var buf = changetype(__new(len << alignof(), idof())); + var dataStart = array.dataStart; + var j: usize = 0; + for (let i = 0; i < len; i++) { + let value = load(dataStart + (i << alignof())); + if (fn(value, i, array)) { + store( + changetype(buf) + (j++ << alignof()), + value + ); + } + } + // shrink output buffer + var byteLength = j << alignof(); + var data = __renew(changetype(buf), byteLength); + store(changetype(out), data, offsetof("buffer")); + __link(changetype(out), data, false); + store(changetype(out), byteLength, offsetof("byteLength")); + store(changetype(out), data, offsetof("dataStart")); + return out; +} + +// @ts-ignore: decorator +@inline +function FIND_INDEX( + array: TArray, + fn: (value: T, index: i32, array: TArray) => bool, +): i32 { + var ptr = array.dataStart; + for (let i = 0, k = array.length; i < k; i++) { + if (fn(load(ptr + (i << alignof())), i, array)) return i; + } + return -1; +} + +// @ts-ignore: decorator +@inline +function FIND_LAST_INDEX( + array: TArray, + fn: (value: T, index: i32, array: TArray) => bool, +): i32 { + var ptr = array.dataStart; + for (let i = array.length - 1; i >= 0; --i) { + if (fn(load(ptr + (i << alignof())), i, array)) return i; + } + return -1; +} + +// @ts-ignore: decorator +@inline +function INCLUDES( + array: TArray, + searchElement: T, + fromIndex: i32, +): bool { + if (isFloat()) { + let index: isize = fromIndex; + let len: isize = array.length; + if (len == 0 || index >= len) return false; + if (index < 0) index = max(len + index, 0); + let dataStart = array.dataStart; + while (index < len) { + let elem = load(dataStart + (index << alignof())); + // @ts-ignore + if (elem == searchElement || isNaN(elem) & isNaN(searchElement)) return true; + ++index; + } + return false; + } else { + return INDEX_OF(array, searchElement, fromIndex) >= 0; + } +} + +// @ts-ignore: decorator +@inline +function INDEX_OF( + array: TArray, + searchElement: T, + fromIndex: i32, +): i32 { + var index: isize = fromIndex; + var len: isize = array.length; + if (len == 0 || index >= len) return -1; + if (index < 0) index = max(len + index, 0); + var dataStart = array.dataStart; + while (index < len) { + if (load(dataStart + (index << alignof())) == searchElement) return index; + ++index; + } + return -1; +} + +// @ts-ignore: decorator +@inline +function LAST_INDEX_OF( + array: TArray, + searchElement: T, + fromIndex: i32, +): i32 { + var index: isize = fromIndex; + var len: isize = array.length; + if (len == 0) return -1; + if (index < 0) index = len + index; // no need to clamp + else if (index >= len) index = len - 1; + var dataStart = array.dataStart; + while (index >= 0) { + if (load(dataStart + (index << alignof())) == searchElement) return index; + --index; + } + return -1; +} + +// @ts-ignore: decorator +@inline +function SOME( + array: TArray, + fn: (value: T, index: i32, array: TArray) => bool, +): bool { + var ptr = array.dataStart; + for (let i = 0, k = array.length; i < k; i++) { + if (fn(load(ptr + (i << alignof())), i, array)) return true; + } + return false; +} + +// @ts-ignore: decorator +@inline +function EVERY( + array: TArray, + fn: (value: T, index: i32, array: TArray) => bool, +): bool { + var ptr = array.dataStart; + for (let i = 0, k = array.length; i < k; i++) { + if (fn(load(ptr + (i << alignof())), i, array)) continue; + return false; + } + return true; +} + +// @ts-ignore: decorator +@inline +function FOREACH( + array: TArray, + fn: (value: T, index: i32, array: TArray) => void, +): void { + var ptr = array.dataStart; + for (let i = 0, k = array.length; i < k; i++) { + fn(load(ptr + (i << alignof())), i, array); + } +} + +// @ts-ignore: decorator +@inline +function WRAP( + buffer: ArrayBuffer, + byteOffset: i32 = 0, + len: i32 = -1 +): TArray { + var byteLength: i32; + var bufferByteLength = buffer.byteLength; + const mask: u32 = sizeof() - 1; + if (i32(byteOffset > bufferByteLength) | (byteOffset & mask)) { + throw new RangeError(E_INDEXOUTOFRANGE); + } + if (len < 0) { + if (len == -1) { + if (bufferByteLength & mask) { + throw new RangeError(E_INVALIDLENGTH); + } + byteLength = bufferByteLength - byteOffset; + } else { + throw new RangeError(E_INVALIDLENGTH); + } + } else { + byteLength = len << alignof(); + if (byteOffset + byteLength > bufferByteLength) { + throw new RangeError(E_INVALIDLENGTH); + } + } + var out = changetype(__new(offsetof(), idof())); + store(changetype(out), changetype(buffer), offsetof("buffer")); + __link(changetype(out), changetype(buffer), false); + store(changetype(out), byteLength, offsetof("byteLength")); + store(changetype(out), changetype(buffer) + byteOffset, offsetof("dataStart")); + return out; +} + +// @ts-ignore: decorator +@inline +function SET( + target: TArray, + source: UArray, + offset: i32 = 0 +): void { + // need to assert at compile time that U is not a reference or a function + if (isReference()) { + ERROR(E_NOTIMPLEMENTED); + } + + // Uncaught RangeError: offset is out of bounds + if (offset < 0) throw new RangeError(E_INDEXOUTOFRANGE); + if (source.length + offset > target.length) throw new RangeError(E_INDEXOUTOFRANGE); + + // if the types align and match, use memory.copy() instead of manual loop + if (isInteger() == isInteger() && alignof() == alignof() && + !(target instanceof Uint8ClampedArray && isSigned())) { + memory.copy( + target.dataStart + (offset << alignof()), + source.dataStart, + source.byteLength + ); + } else { + let targetDataStart = target.dataStart + (offset << alignof()); + let sourceDataStart = source.dataStart; + let count = source.length; + for (let i = 0; i < count; i++) { + // if TArray is Uint8ClampedArray, then values must be clamped + if (target instanceof Uint8ClampedArray) { + if (isFloat()) { + let value = load(sourceDataStart + (i << alignof())); + store( + targetDataStart + (i << alignof()), + isFinite(value) ? max(0, min(255, value)) : 0 + ); + } else { + let value = load(sourceDataStart + (i << alignof())); + if (!isSigned()) { + store( + targetDataStart + (i << alignof()), + // @ts-ignore: cast to T is valid for numeric types here + min(255, value) + ); + } else if (sizeof() <= 4) { + store( + targetDataStart + (i << alignof()), + // @ts-ignore: cast to T is valid for numeric types here + ~(value >> 31) & (((255 - value) >> 31) | value) + ); + } else { + store( + targetDataStart + (i << alignof()), + // @ts-ignore: cast to T is valid for numeric types here + ~(value >> 63) & (((255 - value) >> 63) | value) + ); + } + } + // if U is a float, then casting float to int must include a finite check + } else if (isFloat() && !isFloat()) { + let value = load(sourceDataStart + (i << alignof())); + // @ts-ignore: cast to T is valid for numeric types here + store(targetDataStart + (i << alignof()), isFinite(value) ? value : 0); + } else if (isFloat() && !isFloat()) { + // @ts-ignore: In this case the conversion is required + store(targetDataStart + (i << alignof()), load(sourceDataStart + (i << alignof()))); + } else { + store(targetDataStart + (i << alignof()), load(sourceDataStart + (i << alignof()))); + } + } + } +} +`,uri:`import { encode, decode, URI_UNSAFE, URL_UNSAFE } from "./util/uri"; + +export function encodeURI(str: string): string { + return changetype(encode(changetype(str), str.length, URI_UNSAFE)); +} + +export function decodeURI(str: string): string { + return changetype(decode(changetype(str), str.length, false)); +} + +export function encodeURIComponent(str: string): string { + return changetype(encode(changetype(str), str.length, URL_UNSAFE)); +} + +export function decodeURIComponent(str: string): string { + return changetype(decode(changetype(str), str.length, true)); +} +`,"util/bytes":`export function REVERSE(ptr: usize, len: usize): void { + if (len > 1) { + let + i: usize = 0, + tail: usize, + hlen: usize = len >> 1; + + if (ASC_SHRINK_LEVEL < 1) { + if (sizeof() == 1) { + // TODO: Decide later: Does we need this fast path cases? + // + // if (len == 4) { + // store(ptr, bswap(load(ptr))); + // return; + // } + // if (len == 8) { + // store(ptr, bswap(load(ptr))); + // return; + // } + tail = len - 8; + while (i + 7 < hlen) { + let front = ptr + i; + let back = ptr + tail - i; + let temp = bswap(load(front)); + store(front, bswap(load(back))); + store(back, temp); + i += 8; + } + } + + if (sizeof() == 2) { + tail = len - 2; + while (i + 1 < hlen) { + let front = ptr + (i << 1); + let back = ptr + (tail - i << 1); + let temp = rotr(load(back), 16); + store(back, rotr(load(front), 16)); + store(front, temp); + i += 2; + } + } + } + + tail = len - 1; + while (i < hlen) { + let front = ptr + (i << alignof()); + let back = ptr + (tail - i << alignof()); + let temp = load(front); + store(front, load(back)); + store(back, temp); + i++; + } + } +} +`,"util/casemap":`// Total tables size: ~5 kb (usually compressed to ~4 kb) +// See: https://git.musl-libc.org/cgit/musl/tree/src/ctype/casemap.h + +// @ts-ignore: decorator +@lazy @inline const TAB = memory.data([ + 7, 8, 9, 10, 11, 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 13, 6, 6, 14, 6, 6, 6, 6, 6, 6, 6, 6, 15, 16, 17, 18, + 6, 19, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 20, 21, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 22, 23, 6, 6, 6, 24, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 25, + 6, 6, 6, 6, 26, 6, 6, 6, 6, 6, 6, 6, 27, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 28, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 29, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 30, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, + 43, 43, 43, 43, 43, 43, 43, 43, 1, 0, 84, 86, 86, 86, 86, 86, + 86, 86, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 43, 43, 43, 43, 43, 43, + 43, 7, 43, 43, 91, 86, 86, 86, 86, 86, 86, 86, 74, 86, 86, 5, + 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, + 36, 80, 121, 49, 80, 49, 80, 49, 56, 80, 49, 80, 49, 80, 49, 80, + 49, 80, 49, 80, 49, 80, 49, 80, 78, 49, 2, 78, 13, 13, 78, 3, + 78, 0, 36, 110, 0, 78, 49, 38, 110, 81, 78, 36, 80, 78, 57, 20, + 129, 27, 29, 29, 83, 49, 80, 49, 80, 13, 49, 80, 49, 80, 49, 80, + 27, 83, 36, 80, 49, 2, 92, 123, 92, 123, 92, 123, 92, 123, 92, 123, + 20, 121, 92, 123, 92, 123, 92, 45, 43, 73, 3, 72, 3, 120, 92, 123, + 20, 0, 150, 10, 1, 43, 40, 6, 6, 0, 42, 6, 42, 42, 43, 7, + 187, 181, 43, 30, 0, 43, 7, 43, 43, 43, 1, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 1, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 205, 70, 205, 43, 0, 37, 43, 7, 1, 6, 1, 85, 86, 86, 86, + 86, 86, 85, 86, 86, 2, 36, 129, 129, 129, 129, 129, 21, 129, 129, 129, + 0, 0, 43, 0, 178, 209, 178, 209, 178, 209, 178, 209, 0, 0, 205, 204, + 1, 0, 215, 215, 215, 215, 215, 131, 129, 129, 129, 129, 129, 129, 129, 129, + 129, 129, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 28, 0, 0, 0, + 0, 0, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 2, 0, 0, + 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, + 49, 80, 78, 49, 80, 49, 80, 78, 49, 80, 49, 80, 49, 80, 49, 80, + 49, 80, 49, 80, 49, 80, 49, 2, 135, 166, 135, 166, 135, 166, 135, 166, + 135, 166, 135, 166, 135, 166, 135, 166, 42, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 0, 0, 0, 84, 86, 86, 86, 86, 86, 86, 86, + 86, 86, 86, 86, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 84, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, + 12, 0, 12, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 7, 42, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 86, 86, 108, 129, 21, 0, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 7, 108, 3, 65, 43, 43, 86, 86, 86, 86, 86, 86, + 86, 86, 86, 86, 86, 86, 86, 86, 44, 86, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 12, 108, 0, 0, 0, 0, 0, 6, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, + 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, + 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, + 6, 37, 6, 37, 6, 37, 6, 37, 86, 122, 158, 38, 6, 37, 6, 37, + 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, + 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 1, 43, 43, 79, 86, + 86, 44, 43, 127, 86, 86, 57, 43, 43, 85, 86, 86, 43, 43, 79, 86, + 86, 44, 43, 127, 86, 86, 129, 55, 117, 91, 123, 92, 43, 43, 79, 86, + 86, 2, 172, 4, 0, 0, 57, 43, 43, 85, 86, 86, 43, 43, 79, 86, + 86, 44, 43, 43, 86, 86, 50, 19, 129, 87, 0, 111, 129, 126, 201, 215, + 126, 45, 129, 129, 14, 126, 57, 127, 111, 87, 0, 129, 129, 126, 21, 0, + 126, 3, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 7, 43, + 36, 43, 151, 43, 43, 43, 43, 43, 43, 43, 43, 43, 42, 43, 43, 43, + 43, 43, 86, 86, 86, 86, 86, 128, 129, 129, 129, 129, 57, 187, 42, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 1, 129, 129, 129, 129, 129, 129, 129, 129, + 129, 129, 129, 129, 129, 129, 129, 201, 172, 172, 172, 172, 172, 172, 172, 172, + 172, 172, 172, 172, 172, 172, 172, 208, 13, 0, 78, 49, 2, 180, 193, 193, + 215, 215, 36, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, + 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, + 49, 80, 49, 80, 215, 215, 83, 193, 71, 212, 215, 215, 215, 5, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 7, 1, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 78, 49, 80, 49, 80, 49, 80, + 49, 80, 49, 80, 49, 80, 49, 80, 13, 0, 0, 0, 0, 0, 36, 80, + 49, 80, 49, 80, 49, 80, 49, 80, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 121, 92, 123, 92, 123, 79, 123, 92, 123, 92, 123, + 92, 123, 92, 123, 92, 123, 92, 123, 92, 123, 92, 123, 92, 123, 92, 45, + 43, 43, 121, 20, 92, 123, 92, 45, 121, 42, 92, 39, 92, 123, 92, 123, + 92, 123, 164, 0, 10, 180, 92, 123, 92, 123, 79, 3, 120, 56, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 79, 45, 43, 43, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 43, 43, 43, 43, 43, 43, 43, 43, 7, 0, 72, 86, 86, 86, 86, + 86, 86, 86, 86, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 85, 86, 86, 86, 86, 86, 86, + 86, 86, 86, 86, 86, 86, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 36, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 7, 0, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 7, 0, 0, + 0, 0, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, + 86, 86, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 86, 86, 86, 86, 86, 86, 86, 86, + 86, 86, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 86, 86, + 86, 86, 86, 86, 86, 86, 86, 86, 14, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 85, + 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 14, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +]); + +// @ts-ignore: decorator +@lazy @inline const RULES = memory.data([ + 0x0, 0x2001, -0x2000, 0x1dbf00, 0x2e700, 0x7900, + 0x2402, 0x101, -0x100, 0x0, 0x201, -0x200, + -0xc6ff, -0xe800, -0x78ff, -0x12c00, 0xc300, 0xd201, + 0xce01, 0xcd01, 0x4f01, 0xca01, 0xcb01, 0xcf01, + 0x6100, 0xd301, 0xd101, 0xa300, 0xd501, 0x8200, + 0xd601, 0xda01, 0xd901, 0xdb01, 0x3800, 0x3, + -0x4f00, -0x60ff, -0x37ff, 0x242802, 0x0, 0x101, + -0x100, -0xcd00, -0xda00, -0x81ff, 0x2a2b01, -0xa2ff, + 0x2a2801, 0x2a3f00, -0xc2ff, 0x4501, 0x4701, 0x2a1f00, + 0x2a1c00, 0x2a1e00, -0xd200, -0xce00, -0xca00, -0xcb00, + 0xa54f00, 0xa54b00, -0xcf00, 0xa52800, 0xa54400, -0xd100, + -0xd300, 0x29f700, 0xa54100, 0x29fd00, -0xd500, -0xd600, + 0x29e700, 0xa54300, 0xa52a00, -0x4500, -0xd900, -0x4700, + -0xdb00, 0xa51500, 0xa51200, 0x4c2402, 0x0, 0x2001, + -0x2000, 0x101, -0x100, 0x5400, 0x7401, 0x2601, + 0x2501, 0x4001, 0x3f01, -0x2600, -0x2500, -0x1f00, + -0x4000, -0x3f00, 0x801, -0x3e00, -0x3900, -0x2f00, + -0x3600, -0x800, -0x5600, -0x5000, 0x700, -0x7400, + -0x3bff, -0x6000, -0x6ff, 0x701a02, 0x101, -0x100, + 0x2001, -0x2000, 0x5001, 0xf01, -0xf00, 0x0, + 0x3001, -0x3000, 0x101, -0x100, 0x0, 0xbc000, + 0x1c6001, 0x0, 0x97d001, 0x801, -0x800, 0x8a0502, + 0x0, -0xbbfff, -0x186200, 0x89c200, -0x182500, -0x186e00, + -0x186d00, -0x186400, -0x186300, -0x185c00, 0x0, 0x8a3800, + 0x8a0400, 0xee600, 0x101, -0x100, 0x0, -0x3b00, + -0x1dbeff, 0x8f1d02, 0x800, -0x7ff, 0x0, 0x5600, + -0x55ff, 0x4a00, 0x6400, 0x8000, 0x7000, 0x7e00, + 0x900, -0x49ff, -0x8ff, -0x1c2500, -0x63ff, -0x6fff, + -0x7fff, -0x7dff, 0xac0502, 0x0, 0x1001, -0x1000, + 0x1c01, 0x101, -0x1d5cff, -0x20beff, -0x2045ff, -0x1c00, + 0xb10b02, 0x101, -0x100, 0x3001, -0x3000, 0x0, + -0x29f6ff, -0xee5ff, -0x29e6ff, -0x2a2b00, -0x2a2800, -0x2a1bff, + -0x29fcff, -0x2a1eff, -0x2a1dff, -0x2a3eff, 0x0, -0x1c6000, + 0x0, 0x101, -0x100, 0xbc0c02, 0x0, 0x101, + -0x100, -0xa543ff, 0x3a001, -0x8a03ff, -0xa527ff, 0x3000, + -0xa54eff, -0xa54aff, -0xa540ff, -0xa511ff, -0xa529ff, -0xa514ff, + -0x2fff, -0xa542ff, -0x8a37ff, 0x0, -0x97d000, -0x3a000, + 0x0, 0x2001, -0x2000, 0x0, 0x2801, -0x2800, + 0x0, 0x4001, -0x4000, 0x0, 0x2001, -0x2000, + 0x0, 0x2001, -0x2000, 0x0, 0x2201, -0x2200 +]); + +// @ts-ignore: decorator +@lazy @inline const RULE_BASES = memory.data([ + 0, 6, 39, 81, 111, 119, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 124, 0, 0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 131, 142, 146, 151, + 0, 170, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 180, 196, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 198, 201, 0, 0, 0, 219, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 222, + 0, 0, 0, 0, 225, 0, 0, 0, 0, 0, 0, 0, 228, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 231, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 234, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 237, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +]); + +// @ts-ignore: decorator +@lazy @inline const EXCEPTIONS = memory.data([ + 48, 12, 49, 13, 120, 14, 127, 15, + 128, 16, 129, 17, 134, 18, 137, 19, + 138, 19, 142, 20, 143, 21, 144, 22, + 147, 19, 148, 23, 149, 24, 150, 25, + 151, 26, 154, 27, 156, 25, 157, 28, + 158, 29, 159, 30, 166, 31, 169, 31, + 174, 31, 177, 32, 178, 32, 183, 33, + 191, 34, 197, 35, 200, 35, 203, 35, + 221, 36, 242, 35, 246, 37, 247, 38, + 32, 45, 58, 46, 61, 47, 62, 48, + 63, 49, 64, 49, 67, 50, 68, 51, + 69, 52, 80, 53, 81, 54, 82, 55, + 83, 56, 84, 57, 89, 58, 91, 59, + 92, 60, 97, 61, 99, 62, 101, 63, + 102, 64, 104, 65, 105, 66, 106, 64, + 107, 67, 108, 68, 111, 66, 113, 69, + 114, 70, 117, 71, 125, 72, 130, 73, + 135, 74, 137, 75, 138, 76, 139, 76, + 140, 77, 146, 78, 157, 79, 158, 80, + 69, 87, 123, 29, 124, 29, 125, 29, + 127, 88, 134, 89, 136, 90, 137, 90, + 138, 90, 140, 91, 142, 92, 143, 92, + 172, 93, 173, 94, 174, 94, 175, 94, + 194, 95, 204, 96, 205, 97, 206, 97, + 207, 98, 208, 99, 209, 100, 213, 101, + 214, 102, 215, 103, 240, 104, 241, 105, + 242, 106, 243, 107, 244, 108, 245, 109, + 249, 110, 253, 45, 254, 45, 255, 45, + 80, 105, 81, 105, 82, 105, 83, 105, + 84, 105, 85, 105, 86, 105, 87, 105, + 88, 105, 89, 105, 90, 105, 91, 105, + 92, 105, 93, 105, 94, 105, 95, 105, + 130, 0, 131, 0, 132, 0, 133, 0, + 134, 0, 135, 0, 136, 0, 137, 0, + 192, 117, 207, 118, 128, 137, 129, 138, + 130, 139, 133, 140, 134, 141, 112, 157, + 113, 157, 118, 158, 119, 158, 120, 159, + 121, 159, 122, 160, 123, 160, 124, 161, + 125, 161, 179, 162, 186, 163, 187, 163, + 188, 164, 190, 165, 195, 162, 204, 164, + 218, 166, 219, 166, 229, 106, 234, 167, + 235, 167, 236, 110, 243, 162, 248, 168, + 249, 168, 250, 169, 251, 169, 252, 164, + 38, 176, 42, 177, 43, 178, 78, 179, + 132, 8, 98, 186, 99, 187, 100, 188, + 101, 189, 102, 190, 109, 191, 110, 192, + 111, 193, 112, 194, 126, 195, 127, 195, + 125, 207, 141, 208, 148, 209, 171, 210, + 172, 211, 173, 212, 176, 213, 177, 214, + 178, 215, 196, 216, 197, 217, 198, 218 +]); + +/* Special Case Mappings + * See: https://unicode.org/Public/UNIDATA/SpecialCasing.txt + */ + +/* +@lazy @inline +const SPECIALS_LOWER: StaticArray = [ + 0x0130, 0x0069, 0x0307, 0x0000, +]; +*/ + +// @ts-ignore: decorator +@lazy @inlne +export const SPECIALS_UPPER: StaticArray = [ + // String#toUpperCase needs .length + 0x00DF, 0x0053, 0x0053, 0x0000, + 0x0149, 0x02BC, 0x004E, 0x0000, + 0x01F0, 0x004A, 0x030C, 0x0000, + 0x0390, 0x0399, 0x0308, 0x0301, + 0x03B0, 0x03A5, 0x0308, 0x0301, + 0x0587, 0x0535, 0x0552, 0x0000, + 0x1E96, 0x0048, 0x0331, 0x0000, + 0x1E97, 0x0054, 0x0308, 0x0000, + 0x1E98, 0x0057, 0x030A, 0x0000, + 0x1E99, 0x0059, 0x030A, 0x0000, + 0x1E9A, 0x0041, 0x02BE, 0x0000, + 0x1F50, 0x03A5, 0x0313, 0x0000, + 0x1F52, 0x03A5, 0x0313, 0x0300, + 0x1F54, 0x03A5, 0x0313, 0x0301, + 0x1F56, 0x03A5, 0x0313, 0x0342, + 0x1F80, 0x1F08, 0x0399, 0x0000, + 0x1F81, 0x1F09, 0x0399, 0x0000, + 0x1F82, 0x1F0A, 0x0399, 0x0000, + 0x1F83, 0x1F0B, 0x0399, 0x0000, + 0x1F84, 0x1F0C, 0x0399, 0x0000, + 0x1F85, 0x1F0D, 0x0399, 0x0000, + 0x1F86, 0x1F0E, 0x0399, 0x0000, + 0x1F87, 0x1F0F, 0x0399, 0x0000, + 0x1F88, 0x1F08, 0x0399, 0x0000, + 0x1F89, 0x1F09, 0x0399, 0x0000, + 0x1F8A, 0x1F0A, 0x0399, 0x0000, + 0x1F8B, 0x1F0B, 0x0399, 0x0000, + 0x1F8C, 0x1F0C, 0x0399, 0x0000, + 0x1F8D, 0x1F0D, 0x0399, 0x0000, + 0x1F8E, 0x1F0E, 0x0399, 0x0000, + 0x1F8F, 0x1F0F, 0x0399, 0x0000, + 0x1F90, 0x1F28, 0x0399, 0x0000, + 0x1F91, 0x1F29, 0x0399, 0x0000, + 0x1F92, 0x1F2A, 0x0399, 0x0000, + 0x1F93, 0x1F2B, 0x0399, 0x0000, + 0x1F94, 0x1F2C, 0x0399, 0x0000, + 0x1F95, 0x1F2D, 0x0399, 0x0000, + 0x1F96, 0x1F2E, 0x0399, 0x0000, + 0x1F97, 0x1F2F, 0x0399, 0x0000, + 0x1F98, 0x1F28, 0x0399, 0x0000, + 0x1F99, 0x1F29, 0x0399, 0x0000, + 0x1F9A, 0x1F2A, 0x0399, 0x0000, + 0x1F9B, 0x1F2B, 0x0399, 0x0000, + 0x1F9C, 0x1F2C, 0x0399, 0x0000, + 0x1F9D, 0x1F2D, 0x0399, 0x0000, + 0x1F9E, 0x1F2E, 0x0399, 0x0000, + 0x1F9F, 0x1F2F, 0x0399, 0x0000, + 0x1FA0, 0x1F68, 0x0399, 0x0000, + 0x1FA1, 0x1F69, 0x0399, 0x0000, + 0x1FA2, 0x1F6A, 0x0399, 0x0000, + 0x1FA3, 0x1F6B, 0x0399, 0x0000, + 0x1FA4, 0x1F6C, 0x0399, 0x0000, + 0x1FA5, 0x1F6D, 0x0399, 0x0000, + 0x1FA6, 0x1F6E, 0x0399, 0x0000, + 0x1FA7, 0x1F6F, 0x0399, 0x0000, + 0x1FA8, 0x1F68, 0x0399, 0x0000, + 0x1FA9, 0x1F69, 0x0399, 0x0000, + 0x1FAA, 0x1F6A, 0x0399, 0x0000, + 0x1FAB, 0x1F6B, 0x0399, 0x0000, + 0x1FAC, 0x1F6C, 0x0399, 0x0000, + 0x1FAD, 0x1F6D, 0x0399, 0x0000, + 0x1FAE, 0x1F6E, 0x0399, 0x0000, + 0x1FAF, 0x1F6F, 0x0399, 0x0000, + 0x1FB2, 0x1FBA, 0x0399, 0x0000, + 0x1FB3, 0x0391, 0x0399, 0x0000, + 0x1FB4, 0x0386, 0x0399, 0x0000, + 0x1FB6, 0x0391, 0x0342, 0x0000, + 0x1FB7, 0x0391, 0x0342, 0x0399, + 0x1FBC, 0x0391, 0x0399, 0x0000, + 0x1FC2, 0x1FCA, 0x0399, 0x0000, + 0x1FC3, 0x0397, 0x0399, 0x0000, + 0x1FC4, 0x0389, 0x0399, 0x0000, + 0x1FC6, 0x0397, 0x0342, 0x0000, + 0x1FC7, 0x0397, 0x0342, 0x0399, + 0x1FCC, 0x0397, 0x0399, 0x0000, + 0x1FD2, 0x0399, 0x0308, 0x0300, + 0x1FD3, 0x0399, 0x0308, 0x0301, + 0x1FD6, 0x0399, 0x0342, 0x0000, + 0x1FD7, 0x0399, 0x0308, 0x0342, + 0x1FE2, 0x03A5, 0x0308, 0x0300, + 0x1FE3, 0x03A5, 0x0308, 0x0301, + 0x1FE4, 0x03A1, 0x0313, 0x0000, + 0x1FE6, 0x03A5, 0x0342, 0x0000, + 0x1FE7, 0x03A5, 0x0308, 0x0342, + 0x1FF2, 0x1FFA, 0x0399, 0x0000, + 0x1FF3, 0x03A9, 0x0399, 0x0000, + 0x1FF4, 0x038F, 0x0399, 0x0000, + 0x1FF6, 0x03A9, 0x0342, 0x0000, + 0x1FF7, 0x03A9, 0x0342, 0x0399, + 0x1FFC, 0x03A9, 0x0399, 0x0000, + 0xFB00, 0x0046, 0x0046, 0x0000, + 0xFB01, 0x0046, 0x0049, 0x0000, + 0xFB02, 0x0046, 0x004C, 0x0000, + 0xFB03, 0x0046, 0x0046, 0x0049, + 0xFB04, 0x0046, 0x0046, 0x004C, + 0xFB05, 0x0053, 0x0054, 0x0000, + 0xFB06, 0x0053, 0x0054, 0x0000, + 0xFB13, 0x0544, 0x0546, 0x0000, + 0xFB14, 0x0544, 0x0535, 0x0000, + 0xFB15, 0x0544, 0x053B, 0x0000, + 0xFB16, 0x054E, 0x0546, 0x0000, + 0xFB17, 0x0544, 0x053D, 0x0000 +]; + +// @ts-ignore: decorator +@lazy @inline const MT = memory.data([ + 2048, 342, 57 +]); + +// Special binary search routine for Special Casing Tables +// @ts-ignore: decorator +@inline +export function bsearch(key: u32, ptr: usize, max: i32): i32 { + var min = 0; + while (min <= max) { + let mid = (min + max) >>> 3 << 2; + let cmp = load(ptr + (mid << alignof())) - key; + if (cmp == 0) return mid; // found + else if (cmp >>> 31) min = mid + 4; // < 0 + else max = mid - 4; // > 0 + } + return -1; // not found +} + +// See: https://git.musl-libc.org/cgit/musl/tree/src/ctype/towctrans.c +export function casemap(c: u32, dir: i32): i32 { + // if (c >= 0x20000) return c; + var c0 = c as i32; + var b = c >> 8; + c &= 255; + + var x = c / 3; + var y = c % 3; + + /* lookup entry in two-level base-6 table */ + // v = tab[(tab[b] as i32) * 86 + x] as u32; + var v = load(TAB + load(TAB + b) * 86 + x); + // v = (v * mt[y] >> 11) % 6; + v = (v * load(MT + (y << alignof())) >> 11) % 6; + /* use the bit vector out of the tables as an index into + * a block-specific set of rules and decode the rule into + * a type and a case-mapping delta. */ + // r = rules[(ruleBases[b] as u32) + v]; + var r = load(RULES + ((load(RULE_BASES + b) + v) << alignof())); + var rt: u32 = r & 255; + var rd: i32 = r >> 8; + /* rules 0/1 are simple lower/upper case with a delta. + * apply according to desired mapping direction. */ + if (rt < 2) return c0 + (rd & -(rt ^ dir)); + /* binary search. endpoints of the binary search for + * this block are stored in the rule delta field. */ + var xn: u32 = rd & 0xff; + var xb: u32 = rd >>> 8; + while (xn) { + let h = xn >> 1; + // let t = exceptions[(xb + h) * 2 + 0] as u32; + let t = load(EXCEPTIONS + (xb + h) * 2, 0); + if (t == c) { + // r = rules[exceptions[(xb + h) * 2 + 1]]; + r = load(RULES + (load(EXCEPTIONS + (xb + h) * 2, 1) << alignof())); + rt = r & 255; + rd = r >> 8; + if (rt < 2) return c0 + (rd & -(rt ^ dir)); + /* Hard-coded for the four exceptional titlecase */ + return c0 + 1 - (dir << 1); // (dir ? -1 : 1); + } else if (t > c) { + xn = h; + } else { + xb += h; + xn -= h; + } + } + return c0; +} +`,"util/error":`// Common error messages for use across the standard library. Keeping error messages compact +// and reusing them where possible ensures minimal static data in binaries. + +// @ts-ignore: decorator +@lazy @inline +export const E_INDEXOUTOFRANGE: string = "Index out of range"; + +// @ts-ignore: decorator +@lazy @inline +export const E_VALUEOUTOFRANGE: string = "Value out of range"; + +// @ts-ignore: decorator +@lazy @inline +export const E_INVALIDLENGTH: string = "Invalid length"; + +// @ts-ignore: decorator +@lazy @inline +export const E_ILLEGALGENTYPE: string = "Illegal generic type"; + +// @ts-ignore: decorator +@lazy @inline +export const E_EMPTYARRAY: string = "Array is empty"; + +// @ts-ignore: decorator +@lazy @inline +export const E_HOLEYARRAY: string = "Element type must be nullable if array is holey"; + +// @ts-ignore: decorator +@lazy @inline +export const E_NOTIMPLEMENTED: string = "Not implemented"; + +// @ts-ignore: decorator +@lazy @inline +export const E_KEYNOTFOUND: string = "Key does not exist"; + +// @ts-ignore: decorator +@lazy @inline +export const E_ALLOCATION_TOO_LARGE: string = "Allocation too large"; + +// @ts-ignore: decorator +@lazy @inline +export const E_ALREADY_PINNED: string = "Object already pinned"; + +// @ts-ignore: decorator +@lazy @inline +export const E_NOT_PINNED: string = "Object is not pinned"; + +// @ts-ignore: decorator +@lazy @inline +export const E_URI_MALFORMED: string = "URI malformed"; + +// @ts-ignore: decorator +@lazy @inline +export const E_INVALIDDATE: string = "Invalid Date"; + +// @ts-ignore: decorator +@lazy @inline +export const E_UNPAIRED_SURROGATE: string = "Unpaired surrogate"; +`,"util/hash":`export function HASH(key: T): u32 { + if (isString()) { + return hashStr(changetype(key)); + } else if (isReference()) { + if (sizeof() == 4) return hash32(changetype(key)); + if (sizeof() == 8) return hash64(changetype(key)); + } else if (isFloat()) { + if (sizeof() == 4) return hash32(reinterpret(f32(key))); + if (sizeof() == 8) return hash64(reinterpret(f64(key))); + } else { + if (sizeof() <= 4) return hash32(u32(key), sizeof()); + if (sizeof() == 8) return hash64(u64(key)); + } + return unreachable(); +} + +// XXHash 32-bit as a starting point, see: https://cyan4973.github.io/xxHash + +// primes +// @ts-ignore: decorator +@inline const XXH32_P1: u32 = 2654435761; +// @ts-ignore: decorator +@inline const XXH32_P2: u32 = 2246822519; +// @ts-ignore: decorator +@inline const XXH32_P3: u32 = 3266489917; +// @ts-ignore: decorator +@inline const XXH32_P4: u32 = 668265263; +// @ts-ignore: decorator +@inline const XXH32_P5: u32 = 374761393; +// @ts-ignore: decorator +@inline const XXH32_SEED: u32 = 0; + +// @ts-ignore: decorator +@inline +function hash32(key: u32, len: u32 = 4): u32 { + var h: u32 = XXH32_SEED + XXH32_P5 + len; + h += key * XXH32_P3; + h = rotl(h, 17) * XXH32_P4; + h ^= h >> 15; + h *= XXH32_P2; + h ^= h >> 13; + h *= XXH32_P3; + h ^= h >> 16; + return h; +} + +// @ts-ignore: decorator +@inline +function hash64(key: u64): u32 { + var h: u32 = XXH32_SEED + XXH32_P5 + 8; + h += key * XXH32_P3; + h = rotl(h, 17) * XXH32_P4; + h += (key >> 32) * XXH32_P3; + h = rotl(h, 17) * XXH32_P4; + h ^= h >> 15; + h *= XXH32_P2; + h ^= h >> 13; + h *= XXH32_P3; + h ^= h >> 16; + return h; +} + +// @ts-ignore: decorator +@inline +function mix(h: u32, key: u32): u32 { + return rotl(h + key * XXH32_P2, 13) * XXH32_P1; +} + +// @ts-ignore: decorator +@inline +function hashStr(key: string): u32 { + if (changetype(key) == 0) return XXH32_SEED; + + var h: u32 = key.length << 1; + var len: usize = h; + var pos = changetype(key); + + if (len >= 16) { + let s1 = XXH32_SEED + XXH32_P1 + XXH32_P2; + let s2 = XXH32_SEED + XXH32_P2; + let s3 = XXH32_SEED; + let s4 = XXH32_SEED - XXH32_P1; + + let end = len + pos - 16; + while (pos <= end) { + s1 = mix(s1, load(pos )); + s2 = mix(s2, load(pos, 4)); + s3 = mix(s3, load(pos, 8)); + s4 = mix(s4, load(pos, 12)); + pos += 16; + } + h += rotl(s1, 1) + rotl(s2, 7) + rotl(s3, 12) + rotl(s4, 18); + } else { + h += XXH32_SEED + XXH32_P5; + } + + var end = changetype(key) + len - 4; + while (pos <= end) { + h += load(pos) * XXH32_P3; + h = rotl(h, 17) * XXH32_P4; + pos += 4; + } + + end = changetype(key) + len; + while (pos < end) { + h += load(pos) * XXH32_P5; + h = rotl(h, 11) * XXH32_P1; + pos++; + } + + h ^= h >> 15; + h *= XXH32_P2; + h ^= h >> 13; + h *= XXH32_P3; + h ^= h >> 16; + return h; +} +`,"util/math":`// +// Lookup data for exp2f +// + +// @ts-ignore: decorator +@inline const EXP2F_TABLE_BITS = 5; + +// @ts-ignore: decorator +@lazy @inline const EXP2F_DATA_TAB = memory.data([ + // exp2f_data_tab[i] = uint(2^(i/N)) - (i << 52-BITS) + // used for computing 2^(k/N) for an int |k| < 150 N as + // double(tab[k%N] + (k << 52-BITS)) + 0x3FF0000000000000, 0x3FEFD9B0D3158574, 0x3FEFB5586CF9890F, 0x3FEF9301D0125B51, + 0x3FEF72B83C7D517B, 0x3FEF54873168B9AA, 0x3FEF387A6E756238, 0x3FEF1E9DF51FDEE1, + 0x3FEF06FE0A31B715, 0x3FEEF1A7373AA9CB, 0x3FEEDEA64C123422, 0x3FEECE086061892D, + 0x3FEEBFDAD5362A27, 0x3FEEB42B569D4F82, 0x3FEEAB07DD485429, 0x3FEEA47EB03A5585, + 0x3FEEA09E667F3BCD, 0x3FEE9F75E8EC5F74, 0x3FEEA11473EB0187, 0x3FEEA589994CCE13, + 0x3FEEACE5422AA0DB, 0x3FEEB737B0CDC5E5, 0x3FEEC49182A3F090, 0x3FEED503B23E255D, + 0x3FEEE89F995AD3AD, 0x3FEEFF76F2FB5E47, 0x3FEF199BDD85529C, 0x3FEF3720DCEF9069, + 0x3FEF5818DCFBA487, 0x3FEF7C97337B9B5F, 0x3FEFA4AFA2A490DA, 0x3FEFD0765B6E4540 +]); + +// ULP error: 0.502 (nearest rounding.) +// Relative error: 1.69 * 2^-34 in [-1/64, 1/64] (before rounding.) +// Wrong count: 168353 (all nearest rounding wrong results with fma.) +// @ts-ignore: decorator +@inline +export function exp2f_lut(x: f32): f32 { + const + N = 1 << EXP2F_TABLE_BITS, + N_MASK = N - 1, + shift = reinterpret(0x4338000000000000) / N, // 0x1.8p+52 + Ox127f = reinterpret(0x7F000000); + + const + C0 = reinterpret(0x3FAC6AF84B912394), // 0x1.c6af84b912394p-5 + C1 = reinterpret(0x3FCEBFCE50FAC4F3), // 0x1.ebfce50fac4f3p-3 + C2 = reinterpret(0x3FE62E42FF0C52D6); // 0x1.62e42ff0c52d6p-1 + + var xd = x; + var ix = reinterpret(x); + var ux = ix >> 20 & 0x7FF; + if (ux >= 0x430) { + // |x| >= 128 or x is nan. + if (ix == 0xFF800000) return 0; // x == -Inf -> 0 + if (ux >= 0x7F8) return x + x; // x == Inf/NaN -> Inf/NaN + if (x > 0) return x * Ox127f; // x > 0 -> HugeVal (Owerflow) + if (x <= -150) return 0; // x <= -150 -> 0 (Underflow) + } + + // x = k/N + r with r in [-1/(2N), 1/(2N)] and int k. + var kd = xd + shift; + var ki = reinterpret(kd); + var r = xd - (kd - shift); + var t: u64, y: f64, s: f64; + + // exp2(x) = 2^(k/N) * 2^r ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) + t = load(EXP2F_DATA_TAB + ((ki & N_MASK) << alignof())); + t += ki << (52 - EXP2F_TABLE_BITS); + s = reinterpret(t); + y = C2 * r + 1; + y += (C0 * r + C1) * (r * r); + y *= s; + + return y; +} + +// ULP error: 0.502 (nearest rounding.) +// Relative error: 1.69 * 2^-34 in [-ln2/64, ln2/64] (before rounding.) +// Wrong count: 170635 (all nearest rounding wrong results with fma.) +// @ts-ignore: decorator +@inline +export function expf_lut(x: f32): f32 { + const + N = 1 << EXP2F_TABLE_BITS, + N_MASK = N - 1, + shift = reinterpret(0x4338000000000000), // 0x1.8p+52 + InvLn2N = reinterpret(0x3FF71547652B82FE) * N, // 0x1.71547652b82fep+0 + Ox1p127f = reinterpret(0x7F000000); + + const + C0 = reinterpret(0x3FAC6AF84B912394) / N / N / N, // 0x1.c6af84b912394p-5 + C1 = reinterpret(0x3FCEBFCE50FAC4F3) / N / N, // 0x1.ebfce50fac4f3p-3 + C2 = reinterpret(0x3FE62E42FF0C52D6) / N; // 0x1.62e42ff0c52d6p-1 + + var xd = x; + var ix = reinterpret(x); + var ux = ix >> 20 & 0x7FF; + if (ux >= 0x42B) { + // |x| >= 88 or x is nan. + if (ix == 0xFF800000) return 0; // x == -Inf -> 0 + if (ux >= 0x7F8) return x + x; // x == Inf/NaN -> Inf/NaN + if (x > reinterpret(0x42B17217)) return x * Ox1p127f; // x > log(0x1p128) ~= 88.72 -> HugeVal (Owerflow) + if (x < reinterpret(0xC2CFF1B4)) return 0; // x < log(0x1p-150) ~= -103.97 -> 0 (Underflow) + } + + // x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k. + var z = InvLn2N * xd; + + // Round and convert z to int, the result is in [-150*N, 128*N] and + // ideally ties-to-even rule is used, otherwise the magnitude of r + // can be bigger which gives larger approximation error. + var kd = (z + shift); + var ki = reinterpret(kd); + var r = z - (kd - shift); + var s: f64, y: f64, t: u64; + + // exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) + t = load(EXP2F_DATA_TAB + ((ki & N_MASK) << alignof())); + t += ki << (52 - EXP2F_TABLE_BITS); + s = reinterpret(t); + z = C0 * r + C1; + y = C2 * r + 1; + y += z * (r * r); + y *= s; + + return y; +} + +// +// Lookup data for log2f +// + +// @ts-ignore: decorator +@inline const LOG2F_TABLE_BITS = 4; + +// @ts-ignore: decorator +@lazy @inline const LOG2F_DATA_TAB = memory.data([ + reinterpret(0x3FF661EC79F8F3BE), reinterpret(0xBFDEFEC65B963019), // 0x1.661ec79f8f3bep+0, -0x1.efec65b963019p-2, + reinterpret(0x3FF571ED4AAF883D), reinterpret(0xBFDB0B6832D4FCA4), // 0x1.571ed4aaf883dp+0, -0x1.b0b6832d4fca4p-2, + reinterpret(0x3FF49539F0F010B0), reinterpret(0xBFD7418B0A1FB77B), // 0x1.49539f0f010bp+0 , -0x1.7418b0a1fb77bp-2, + reinterpret(0x3FF3C995B0B80385), reinterpret(0xBFD39DE91A6DCF7B), // 0x1.3c995b0b80385p+0, -0x1.39de91a6dcf7bp-2, + reinterpret(0x3FF30D190C8864A5), reinterpret(0xBFD01D9BF3F2B631), // 0x1.30d190c8864a5p+0, -0x1.01d9bf3f2b631p-2, + reinterpret(0x3FF25E227B0B8EA0), reinterpret(0xBFC97C1D1B3B7AF0), // 0x1.25e227b0b8eap+0 , -0x1.97c1d1b3b7afp-3 , + reinterpret(0x3FF1BB4A4A1A343F), reinterpret(0xBFC2F9E393AF3C9F), // 0x1.1bb4a4a1a343fp+0, -0x1.2f9e393af3c9fp-3, + reinterpret(0x3FF12358F08AE5BA), reinterpret(0xBFB960CBBF788D5C), // 0x1.12358f08ae5bap+0, -0x1.960cbbf788d5cp-4, + reinterpret(0x3FF0953F419900A7), reinterpret(0xBFAA6F9DB6475FCE), // 0x1.0953f419900a7p+0, -0x1.a6f9db6475fcep-5, + reinterpret(0x3FF0000000000000), 0, // 0x1p+0, 0x0, + reinterpret(0x3FEE608CFD9A47AC), reinterpret(0x3FB338CA9F24F53D), // 0x1.e608cfd9a47acp-1, 0x1.338ca9f24f53dp-4, + reinterpret(0x3FECA4B31F026AA0), reinterpret(0x3FC476A9543891BA), // 0x1.ca4b31f026aap-1 , 0x1.476a9543891bap-3, + reinterpret(0x3FEB2036576AFCE6), reinterpret(0x3FCE840B4AC4E4D2), // 0x1.b2036576afce6p-1, 0x1.e840b4ac4e4d2p-3, + reinterpret(0x3FE9C2D163A1AA2D), reinterpret(0x3FD40645F0C6651C), // 0x1.9c2d163a1aa2dp-1, 0x1.40645f0c6651cp-2, + reinterpret(0x3FE886E6037841ED), reinterpret(0x3FD88E9C2C1B9FF8), // 0x1.886e6037841edp-1, 0x1.88e9c2c1b9ff8p-2, + reinterpret(0x3FE767DCF5534862), reinterpret(0x3FDCE0A44EB17BCC) // 0x1.767dcf5534862p-1, 0x1.ce0a44eb17bccp-2 +]); + +// ULP error: 0.752 (nearest rounding.) +// Relative error: 1.9 * 2^-26 (before rounding.) +// @ts-ignore: decorator +@inline +export function log2f_lut(x: f32): f32 { + const + N_MASK = (1 << LOG2F_TABLE_BITS) - 1, + Ox1p23f = reinterpret(0x4B000000); // 0x1p23f + + const + A0 = reinterpret(0xBFD712B6F70A7E4D), // -0x1.712b6f70a7e4dp-2 + A1 = reinterpret(0x3FDECABF496832E0), // 0x1.ecabf496832ep-2 + A2 = reinterpret(0xBFE715479FFAE3DE), // -0x1.715479ffae3dep-1 + A3 = reinterpret(0x3FF715475F35C8B8); // 0x1.715475f35c8b8p0 + + var ux = reinterpret(x); + // Fix sign of zero with downward rounding when x==1. + // if (WANT_ROUNDING && predict_false(ix == 0x3f800000)) return 0; + if (ux - 0x00800000 >= 0x7F800000 - 0x00800000) { + // x < 0x1p-126 or inf or nan. + if (ux * 2 == 0) return -Infinity; + if (ux == 0x7F800000) return x; // log2(inf) == inf. + if ((ux >> 31) || ux * 2 >= 0xFF000000) return (x - x) / (x - x); + // x is subnormal, normalize it. + ux = reinterpret(x * Ox1p23f); + ux -= 23 << 23; + } + // x = 2^k z; where z is in range [OFF,2*OFF] and exact. + // The range is split into N subintervals. + // The ith subinterval contains z and c is near its center. + var tmp = ux - 0x3F330000; + var i = (tmp >> (23 - LOG2F_TABLE_BITS)) & N_MASK; + var top = tmp & 0xFF800000; + var iz = ux - top; + var k = tmp >> 23; + + var invc = load(LOG2F_DATA_TAB + (i << (1 + alignof())), 0 << alignof()); + var logc = load(LOG2F_DATA_TAB + (i << (1 + alignof())), 1 << alignof()); + var z = reinterpret(iz); + + // log2(x) = log1p(z/c-1)/ln2 + log2(c) + k + var r = z * invc - 1; + var y0 = logc + k; + + // Pipelined polynomial evaluation to approximate log1p(r)/ln2. + var y = A1 * r + A2; + var p = A3 * r + y0; + var r2 = r * r; + y += A0 * r2; + y = y * r2 + p; + + return y; +} + +// +// Lookup data for logf. See: https://git.musl-libc.org/cgit/musl/tree/src/math/logf.c +// + +// @ts-ignore: decorator +@inline const LOGF_TABLE_BITS = 4; + +// @ts-ignore: decorator +@lazy @inline const LOGF_DATA_TAB = memory.data([ + reinterpret(0x3FF661EC79F8F3BE), reinterpret(0xBFD57BF7808CAADE), // 0x1.661ec79f8f3bep+0, -0x1.57bf7808caadep-2, + reinterpret(0x3FF571ED4AAF883D), reinterpret(0xBFD2BEF0A7C06DDB), // 0x1.571ed4aaf883dp+0, -0x1.2bef0a7c06ddbp-2, + reinterpret(0x3FF49539F0F010B0), reinterpret(0xBFD01EAE7F513A67), // 0x1.49539f0f010bp+0 , -0x1.01eae7f513a67p-2, + reinterpret(0x3FF3C995B0B80385), reinterpret(0xBFCB31D8A68224E9), // 0x1.3c995b0b80385p+0, -0x1.b31d8a68224e9p-3, + reinterpret(0x3FF30D190C8864A5), reinterpret(0xBFC6574F0AC07758), // 0x1.30d190c8864a5p+0, -0x1.6574f0ac07758p-3, + reinterpret(0x3FF25E227B0B8EA0), reinterpret(0xBFC1AA2BC79C8100), // 0x1.25e227b0b8eap+0 , -0x1.1aa2bc79c81p-3 , + reinterpret(0x3FF1BB4A4A1A343F), reinterpret(0xBFBA4E76CE8C0E5E), // 0x1.1bb4a4a1a343fp+0, -0x1.a4e76ce8c0e5ep-4, + reinterpret(0x3FF12358F08AE5BA), reinterpret(0xBFB1973C5A611CCC), // 0x1.12358f08ae5bap+0, -0x1.1973c5a611cccp-4, + reinterpret(0x3FF0953F419900A7), reinterpret(0xBFA252F438E10C1E), // 0x1.0953f419900a7p+0, -0x1.252f438e10c1ep-5, + reinterpret(0x3FF0000000000000), 0, // 0x1p+0, 0, + reinterpret(0x3FEE608CFD9A47AC), reinterpret(0x3FAAA5AA5DF25984), // 0x1.e608cfd9a47acp-1, 0x1.aa5aa5df25984p-5, + reinterpret(0x3FECA4B31F026AA0), reinterpret(0x3FBC5E53AA362EB4), // 0x1.ca4b31f026aap-1 , 0x1.c5e53aa362eb4p-4, + reinterpret(0x3FEB2036576AFCE6), reinterpret(0x3FC526E57720DB08), // 0x1.b2036576afce6p-1, 0x1.526e57720db08p-3, + reinterpret(0x3FE9C2D163A1AA2D), reinterpret(0x3FCBC2860D224770), // 0x1.9c2d163a1aa2dp-1, 0x1.bc2860d22477p-3 , + reinterpret(0x3FE886E6037841ED), reinterpret(0x3FD1058BC8A07EE1), // 0x1.886e6037841edp-1, 0x1.1058bc8a07ee1p-2, + reinterpret(0x3FE767DCF5534862), reinterpret(0x3FD4043057B6EE09) // 0x1.767dcf5534862p-1, 0x1.4043057b6ee09p-2 +]); + +// ULP error: 0.818 (nearest rounding.) +// Relative error: 1.957 * 2^-26 (before rounding.) +// @ts-ignore: decorator +@inline +export function logf_lut(x: f32): f32 { + const + N_MASK = (1 << LOGF_TABLE_BITS) - 1, + Ox1p23f = reinterpret(0x4B000000); // 0x1p23f + + const + Ln2 = reinterpret(0x3FE62E42FEFA39EF), // 0x1.62e42fefa39efp-1; + A0 = reinterpret(0xBFD00EA348B88334), // -0x1.00ea348b88334p-2 + A1 = reinterpret(0x3FD5575B0BE00B6A), // 0x1.5575b0be00b6ap-2 + A2 = reinterpret(0xBFDFFFFEF20A4123); // -0x1.ffffef20a4123p-2 + + var ux = reinterpret(x); + // Fix sign of zero with downward rounding when x==1. + // if (WANT_ROUNDING && ux == 0x3f800000) return 0; + if (ux - 0x00800000 >= 0x7F800000 - 0x00800000) { + // x < 0x1p-126 or inf or nan. + if ((ux << 1) == 0) return -Infinity; + if (ux == 0x7F800000) return x; // log(inf) == inf. + if ((ux >> 31) || (ux << 1) >= 0xFF000000) return (x - x) / (x - x); + // x is subnormal, normalize it. + ux = reinterpret(x * Ox1p23f); + ux -= 23 << 23; + } + // x = 2^k z; where z is in range [OFF,2*OFF] and exact. + // The range is split into N subintervals. + // The ith subinterval contains z and c is near its center. + var tmp = ux - 0x3F330000; + var i = (tmp >> (23 - LOGF_TABLE_BITS)) & N_MASK; + var k = tmp >> 23; + var iz = ux - (tmp & 0x1FF << 23); + + var invc = load(LOGF_DATA_TAB + (i << (1 + alignof())), 0 << alignof()); + var logc = load(LOGF_DATA_TAB + (i << (1 + alignof())), 1 << alignof()); + + var z = reinterpret(iz); + + // log(x) = log1p(z/c-1) + log(c) + k*Ln2 + var r = z * invc - 1; + var y0 = logc + k * Ln2; + + // Pipelined polynomial evaluation to approximate log1p(r). + var r2 = r * r; + var y = A1 * r + A2; + y += A0 * r2; + y = y * r2 + (y0 + r); + + return y; +} + +// +// Lookup data for powf. See: https://git.musl-libc.org/cgit/musl/tree/src/math/powf.c +// + +// @ts-ignore: decorator +@inline +function zeroinfnanf(ux: u32): bool { + return (ux << 1) - 1 >= (0x7f800000 << 1) - 1; +} + +// Returns 0 if not int, 1 if odd int, 2 if even int. The argument is +// the bit representation of a non-zero finite floating-point value. +// @ts-ignore: decorator +@inline +function checkintf(iy: u32): i32 { + var e = iy >> 23 & 0xFF; + if (e < 0x7F ) return 0; + if (e > 0x7F + 23) return 2; + e = 1 << (0x7F + 23 - e); + if (iy & (e - 1)) return 0; + if (iy & e ) return 1; + return 2; +} + +// Subnormal input is normalized so ix has negative biased exponent. +// Output is multiplied by N (POWF_SCALE) if TOINT_INTRINICS is set. +// @ts-ignore: decorator +@inline +function log2f_inline(ux: u32): f64 { + const N_MASK = (1 << LOG2F_TABLE_BITS) - 1; + + const + A0 = reinterpret(0x3FD27616C9496E0B), // 0x1.27616c9496e0bp-2 + A1 = reinterpret(0xBFD71969A075C67A), // -0x1.71969a075c67ap-2 + A2 = reinterpret(0x3FDEC70A6CA7BADD), // 0x1.ec70a6ca7baddp-2 + A3 = reinterpret(0xBFE7154748BEF6C8), // -0x1.7154748bef6c8p-1 + A4 = reinterpret(0x3FF71547652AB82B); // 0x1.71547652ab82bp+0 + + // x = 2^k z; where z is in range [OFF,2*OFF] and exact. + // The range is split into N subintervals. + // The ith subinterval contains z and c is near its center. + var tmp = ux - 0x3F330000; + var i = ((tmp >> (23 - LOG2F_TABLE_BITS)) & N_MASK); + var top = tmp & 0xFF800000; + var uz = ux - top; + var k = (top >> 23); + + var invc = load(LOG2F_DATA_TAB + (i << (1 + alignof())), 0 << alignof()); + var logc = load(LOG2F_DATA_TAB + (i << (1 + alignof())), 1 << alignof()); + var z = reinterpret(uz); + + // log2(x) = log1p(z/c-1)/ln2 + log2(c) + k + var r = z * invc - 1; + var y0 = logc + k; + + // Pipelined polynomial evaluation to approximate log1p(r)/ln2. + var y = A0 * r + A1; + var p = A2 * r + A3; + var q = A4 * r + y0; + + r *= r; + q += p * r; + y = y * (r * r) + q; + + return y; +} + +// The output of log2 and thus the input of exp2 is either scaled by N +// (in case of fast toint intrinsics) or not. The unscaled xd must be +// in [-1021,1023], sign_bias sets the sign of the result. +// @ts-ignore: decorator +@inline +function exp2f_inline(xd: f64, signBias: u32): f32 { + const + N = 1 << EXP2F_TABLE_BITS, + N_MASK = N - 1, + shift = reinterpret(0x4338000000000000) / N; // 0x1.8p+52 + + const + C0 = reinterpret(0x3FAC6AF84B912394), // 0x1.c6af84b912394p-5 + C1 = reinterpret(0x3FCEBFCE50FAC4F3), // 0x1.ebfce50fac4f3p-3 + C2 = reinterpret(0x3FE62E42FF0C52D6); // 0x1.62e42ff0c52d6p-1 + + // x = k/N + r with r in [-1/(2N), 1/(2N)] + var kd = (xd + shift); + var ki = reinterpret(kd); + var r = xd - (kd - shift); + var t: u64, z: f64, y: f64, s: f64; + + // exp2(x) = 2^(k/N) * 2^r ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) + t = load(EXP2F_DATA_TAB + ((ki & N_MASK) << alignof())); + t += (ki + signBias) << (52 - EXP2F_TABLE_BITS); + s = reinterpret(t); + z = C0 * r + C1; + y = C2 * r + 1; + y += z * (r * r); + y *= s; + return y; +} + +// @ts-ignore: decorator +@inline +function xflowf(sign: u32, y: f32): f32 { + return select(-y, y, sign) * y; +} + +// @ts-ignore: decorator +@inline +function oflowf(sign: u32): f32 { + return xflowf(sign, reinterpret(0x70000000)); // 0x1p97f +} + +// @ts-ignore: decorator +@inline +function uflowf(sign: u32): f32 { + return xflowf(sign, reinterpret(0x10000000)); // 0x1p-95f +} + +// @ts-ignore: decorator +@inline +export function powf_lut(x: f32, y: f32): f32 { + const + Ox1p23f = reinterpret(0x4B000000), // 0x1p23f + UPPER_LIMIT = reinterpret(0x405FFFFFFFD1D571), // 0x1.fffffffd1d571p+6 + LOWER_LIMIT = -150.0, + SIGN_BIAS = 1 << (EXP2F_TABLE_BITS + 11); + + var signBias: u32 = 0; + var ix = reinterpret(x); + var iy = reinterpret(y); + var ny = 0; + + if (i32(ix - 0x00800000 >= 0x7f800000 - 0x00800000) | (ny = i32(zeroinfnanf(iy)))) { + // Either (x < 0x1p-126 or inf or nan) or (y is 0 or inf or nan). + if (ny) { + if ((iy << 1) == 0) return 1.0; + if (ix == 0x3F800000) return NaN; // original: 1.0 + if ((ix << 1) > (0x7F800000 << 1) || (iy << 1) > (0x7F800000 << 1)) return x + y; + if ((ix << 1) == (0x3F800000 << 1)) return NaN; // original: 1.0 + if (((ix << 1) < (0x3F800000 << 1)) == !(iy >> 31)) return 0; // |x| < 1 && y==inf or |x| > 1 && y==-inf. + return y * y; + } + if (zeroinfnanf(ix)) { + let x2 = x * x; + if ((ix >> 31) && checkintf(iy) == 1) x2 = -x2; + return iy >> 31 ? 1 / x2 : x2; + } + // x and y are non-zero finite. + if (ix >> 31) { + // Finite x < 0. + let yint = checkintf(iy); + if (yint == 0) return (x - x) / (x - x); + if (yint == 1) signBias = SIGN_BIAS; + ix &= 0x7FFFFFFF; + } + if (ix < 0x00800000) { + // Normalize subnormal x so exponent becomes negative. + ix = reinterpret(x * Ox1p23f); + ix &= 0x7FFFFFFF; + ix -= 23 << 23; + } + } + var logx = log2f_inline(ix); + var ylogx = y * logx; // cannot overflow, y is single prec. + if ((reinterpret(ylogx) >> 47 & 0xFFFF) >= 0x80BF) { // reinterpret(126.0) >> 47 + // |y * log(x)| >= 126 + if (ylogx > UPPER_LIMIT) return oflowf(signBias); // overflow + if (ylogx <= LOWER_LIMIT) return uflowf(signBias); // underflow + } + return exp2f_inline(ylogx, signBias); +} + +// +// Lookup data for exp. See: https://git.musl-libc.org/cgit/musl/tree/src/math/exp.c +// + +// @ts-ignore: decorator +@inline const EXP_TABLE_BITS = 7; + +// @ts-ignore: decorator +@lazy @inline const EXP_DATA_TAB = memory.data([ + 0x0000000000000000, 0x3FF0000000000000, + 0x3C9B3B4F1A88BF6E, 0x3FEFF63DA9FB3335, + 0xBC7160139CD8DC5D, 0x3FEFEC9A3E778061, + 0xBC905E7A108766D1, 0x3FEFE315E86E7F85, + 0x3C8CD2523567F613, 0x3FEFD9B0D3158574, + 0xBC8BCE8023F98EFA, 0x3FEFD06B29DDF6DE, + 0x3C60F74E61E6C861, 0x3FEFC74518759BC8, + 0x3C90A3E45B33D399, 0x3FEFBE3ECAC6F383, + 0x3C979AA65D837B6D, 0x3FEFB5586CF9890F, + 0x3C8EB51A92FDEFFC, 0x3FEFAC922B7247F7, + 0x3C3EBE3D702F9CD1, 0x3FEFA3EC32D3D1A2, + 0xBC6A033489906E0B, 0x3FEF9B66AFFED31B, + 0xBC9556522A2FBD0E, 0x3FEF9301D0125B51, + 0xBC5080EF8C4EEA55, 0x3FEF8ABDC06C31CC, + 0xBC91C923B9D5F416, 0x3FEF829AAEA92DE0, + 0x3C80D3E3E95C55AF, 0x3FEF7A98C8A58E51, + 0xBC801B15EAA59348, 0x3FEF72B83C7D517B, + 0xBC8F1FF055DE323D, 0x3FEF6AF9388C8DEA, + 0x3C8B898C3F1353BF, 0x3FEF635BEB6FCB75, + 0xBC96D99C7611EB26, 0x3FEF5BE084045CD4, + 0x3C9AECF73E3A2F60, 0x3FEF54873168B9AA, + 0xBC8FE782CB86389D, 0x3FEF4D5022FCD91D, + 0x3C8A6F4144A6C38D, 0x3FEF463B88628CD6, + 0x3C807A05B0E4047D, 0x3FEF3F49917DDC96, + 0x3C968EFDE3A8A894, 0x3FEF387A6E756238, + 0x3C875E18F274487D, 0x3FEF31CE4FB2A63F, + 0x3C80472B981FE7F2, 0x3FEF2B4565E27CDD, + 0xBC96B87B3F71085E, 0x3FEF24DFE1F56381, + 0x3C82F7E16D09AB31, 0x3FEF1E9DF51FDEE1, + 0xBC3D219B1A6FBFFA, 0x3FEF187FD0DAD990, + 0x3C8B3782720C0AB4, 0x3FEF1285A6E4030B, + 0x3C6E149289CECB8F, 0x3FEF0CAFA93E2F56, + 0x3C834D754DB0ABB6, 0x3FEF06FE0A31B715, + 0x3C864201E2AC744C, 0x3FEF0170FC4CD831, + 0x3C8FDD395DD3F84A, 0x3FEEFC08B26416FF, + 0xBC86A3803B8E5B04, 0x3FEEF6C55F929FF1, + 0xBC924AEDCC4B5068, 0x3FEEF1A7373AA9CB, + 0xBC9907F81B512D8E, 0x3FEEECAE6D05D866, + 0xBC71D1E83E9436D2, 0x3FEEE7DB34E59FF7, + 0xBC991919B3CE1B15, 0x3FEEE32DC313A8E5, + 0x3C859F48A72A4C6D, 0x3FEEDEA64C123422, + 0xBC9312607A28698A, 0x3FEEDA4504AC801C, + 0xBC58A78F4817895B, 0x3FEED60A21F72E2A, + 0xBC7C2C9B67499A1B, 0x3FEED1F5D950A897, + 0x3C4363ED60C2AC11, 0x3FEECE086061892D, + 0x3C9666093B0664EF, 0x3FEECA41ED1D0057, + 0x3C6ECCE1DAA10379, 0x3FEEC6A2B5C13CD0, + 0x3C93FF8E3F0F1230, 0x3FEEC32AF0D7D3DE, + 0x3C7690CEBB7AAFB0, 0x3FEEBFDAD5362A27, + 0x3C931DBDEB54E077, 0x3FEEBCB299FDDD0D, + 0xBC8F94340071A38E, 0x3FEEB9B2769D2CA7, + 0xBC87DECCDC93A349, 0x3FEEB6DAA2CF6642, + 0xBC78DEC6BD0F385F, 0x3FEEB42B569D4F82, + 0xBC861246EC7B5CF6, 0x3FEEB1A4CA5D920F, + 0x3C93350518FDD78E, 0x3FEEAF4736B527DA, + 0x3C7B98B72F8A9B05, 0x3FEEAD12D497C7FD, + 0x3C9063E1E21C5409, 0x3FEEAB07DD485429, + 0x3C34C7855019C6EA, 0x3FEEA9268A5946B7, + 0x3C9432E62B64C035, 0x3FEEA76F15AD2148, + 0xBC8CE44A6199769F, 0x3FEEA5E1B976DC09, + 0xBC8C33C53BEF4DA8, 0x3FEEA47EB03A5585, + 0xBC845378892BE9AE, 0x3FEEA34634CCC320, + 0xBC93CEDD78565858, 0x3FEEA23882552225, + 0x3C5710AA807E1964, 0x3FEEA155D44CA973, + 0xBC93B3EFBF5E2228, 0x3FEEA09E667F3BCD, + 0xBC6A12AD8734B982, 0x3FEEA012750BDABF, + 0xBC6367EFB86DA9EE, 0x3FEE9FB23C651A2F, + 0xBC80DC3D54E08851, 0x3FEE9F7DF9519484, + 0xBC781F647E5A3ECF, 0x3FEE9F75E8EC5F74, + 0xBC86EE4AC08B7DB0, 0x3FEE9F9A48A58174, + 0xBC8619321E55E68A, 0x3FEE9FEB564267C9, + 0x3C909CCB5E09D4D3, 0x3FEEA0694FDE5D3F, + 0xBC7B32DCB94DA51D, 0x3FEEA11473EB0187, + 0x3C94ECFD5467C06B, 0x3FEEA1ED0130C132, + 0x3C65EBE1ABD66C55, 0x3FEEA2F336CF4E62, + 0xBC88A1C52FB3CF42, 0x3FEEA427543E1A12, + 0xBC9369B6F13B3734, 0x3FEEA589994CCE13, + 0xBC805E843A19FF1E, 0x3FEEA71A4623C7AD, + 0xBC94D450D872576E, 0x3FEEA8D99B4492ED, + 0x3C90AD675B0E8A00, 0x3FEEAAC7D98A6699, + 0x3C8DB72FC1F0EAB4, 0x3FEEACE5422AA0DB, + 0xBC65B6609CC5E7FF, 0x3FEEAF3216B5448C, + 0x3C7BF68359F35F44, 0x3FEEB1AE99157736, + 0xBC93091FA71E3D83, 0x3FEEB45B0B91FFC6, + 0xBC5DA9B88B6C1E29, 0x3FEEB737B0CDC5E5, + 0xBC6C23F97C90B959, 0x3FEEBA44CBC8520F, + 0xBC92434322F4F9AA, 0x3FEEBD829FDE4E50, + 0xBC85CA6CD7668E4B, 0x3FEEC0F170CA07BA, + 0x3C71AFFC2B91CE27, 0x3FEEC49182A3F090, + 0x3C6DD235E10A73BB, 0x3FEEC86319E32323, + 0xBC87C50422622263, 0x3FEECC667B5DE565, + 0x3C8B1C86E3E231D5, 0x3FEED09BEC4A2D33, + 0xBC91BBD1D3BCBB15, 0x3FEED503B23E255D, + 0x3C90CC319CEE31D2, 0x3FEED99E1330B358, + 0x3C8469846E735AB3, 0x3FEEDE6B5579FDBF, + 0xBC82DFCD978E9DB4, 0x3FEEE36BBFD3F37A, + 0x3C8C1A7792CB3387, 0x3FEEE89F995AD3AD, + 0xBC907B8F4AD1D9FA, 0x3FEEEE07298DB666, + 0xBC55C3D956DCAEBA, 0x3FEEF3A2B84F15FB, + 0xBC90A40E3DA6F640, 0x3FEEF9728DE5593A, + 0xBC68D6F438AD9334, 0x3FEEFF76F2FB5E47, + 0xBC91EEE26B588A35, 0x3FEF05B030A1064A, + 0x3C74FFD70A5FDDCD, 0x3FEF0C1E904BC1D2, + 0xBC91BDFBFA9298AC, 0x3FEF12C25BD71E09, + 0x3C736EAE30AF0CB3, 0x3FEF199BDD85529C, + 0x3C8EE3325C9FFD94, 0x3FEF20AB5FFFD07A, + 0x3C84E08FD10959AC, 0x3FEF27F12E57D14B, + 0x3C63CDAF384E1A67, 0x3FEF2F6D9406E7B5, + 0x3C676B2C6C921968, 0x3FEF3720DCEF9069, + 0xBC808A1883CCB5D2, 0x3FEF3F0B555DC3FA, + 0xBC8FAD5D3FFFFA6F, 0x3FEF472D4A07897C, + 0xBC900DAE3875A949, 0x3FEF4F87080D89F2, + 0x3C74A385A63D07A7, 0x3FEF5818DCFBA487, + 0xBC82919E2040220F, 0x3FEF60E316C98398, + 0x3C8E5A50D5C192AC, 0x3FEF69E603DB3285, + 0x3C843A59AC016B4B, 0x3FEF7321F301B460, + 0xBC82D52107B43E1F, 0x3FEF7C97337B9B5F, + 0xBC892AB93B470DC9, 0x3FEF864614F5A129, + 0x3C74B604603A88D3, 0x3FEF902EE78B3FF6, + 0x3C83C5EC519D7271, 0x3FEF9A51FBC74C83, + 0xBC8FF7128FD391F0, 0x3FEFA4AFA2A490DA, + 0xBC8DAE98E223747D, 0x3FEFAF482D8E67F1, + 0x3C8EC3BC41AA2008, 0x3FEFBA1BEE615A27, + 0x3C842B94C3A9EB32, 0x3FEFC52B376BBA97, + 0x3C8A64A931D185EE, 0x3FEFD0765B6E4540, + 0xBC8E37BAE43BE3ED, 0x3FEFDBFDAD9CBE14, + 0x3C77893B4D91CD9D, 0x3FEFE7C1819E90D8, + 0x3C5305C14160CC89, 0x3FEFF3C22B8F71F1 +]); + +// Handle cases that may overflow or underflow when computing the result that +// is scale*(1+TMP) without intermediate rounding. The bit representation of +// scale is in SBITS, however it has a computed exponent that may have +// overflown into the sign bit so that needs to be adjusted before using it as +// a double. (int32_t)KI is the k used in the argument reduction and exponent +// adjustment of scale, positive k here means the result may overflow and +// negative k means the result may underflow. +// @ts-ignore: decorator +@inline +function specialcase(tmp: f64, sbits: u64, ki: u64): f64 { + const + Ox1p_1022 = reinterpret(0x0010000000000000), // 0x1p-1022 + Ox1p1009 = reinterpret(0x7F00000000000000); // 0x1p1009 + + var scale: f64; + if (!(ki & 0x80000000)) { + // k > 0, the exponent of scale might have overflowed by <= 460. + sbits -= u64(1009) << 52; + scale = reinterpret(sbits); + return Ox1p1009 * (scale + scale * tmp); // 0x1p1009 + } + // k < 0, need special care in the subnormal range. + sbits += u64(1022) << 52; + // Note: sbits is signed scale. + scale = reinterpret(sbits); + var y = scale + scale * tmp; + if (abs(y) < 1.0) { + // Round y to the right precision before scaling it into the subnormal + // range to avoid double rounding that can cause 0.5+E/2 ulp error where + // E is the worst-case ulp error outside the subnormal range. So this + // is only useful if the goal is better than 1 ulp worst-case error. + let one = copysign(1.0, y); + let lo = scale - y + scale * tmp; + let hi = one + y; + lo = one - hi + y + lo; + y = (hi + lo) - one; + // Fix the sign of 0. + if (y == 0.0) y = reinterpret(sbits & 0x8000000000000000); + } + return y * Ox1p_1022; +} + +// @ts-ignore: decorator +@inline +export function exp_lut(x: f64): f64 { + const + N = 1 << EXP_TABLE_BITS, + N_MASK = N - 1; + + const + InvLn2N = reinterpret(0x3FF71547652B82FE) * N, // 0x1.71547652b82fep0 + NegLn2hiN = reinterpret(0xBF762E42FEFA0000), // -0x1.62e42fefa0000p-8 + NegLn2loN = reinterpret(0xBD0CF79ABC9E3B3A), // -0x1.cf79abc9e3b3ap-47 + shift = reinterpret(0x4338000000000000); // 0x1.8p52; + + const + C2 = reinterpret(0x3FDFFFFFFFFFFDBD), // __exp_data.poly[0] (0x1.ffffffffffdbdp-2) + C3 = reinterpret(0x3FC555555555543C), // __exp_data.poly[1] (0x1.555555555543cp-3) + C4 = reinterpret(0x3FA55555CF172B91), // __exp_data.poly[2] (0x1.55555cf172b91p-5) + C5 = reinterpret(0x3F81111167A4D017); // __exp_data.poly[3] (0x1.1111167a4d017p-7) + + var ux = reinterpret(x); + var abstop = (ux >> 52 & 0x7FF); + if (abstop - 0x3C9 >= 0x03F) { + if (abstop - 0x3C9 >= 0x80000000) return 1; + if (abstop >= 0x409) { + if (ux == 0xFFF0000000000000) return 0; + if (abstop >= 0x7FF) return 1.0 + x; + return select(0, Infinity, ux >> 63); + } + // Large x is special cased below. + abstop = 0; + } + + // exp(x) = 2^(k/N) * exp(r), with exp(r) in [2^(-1/2N),2^(1/2N)] + // x = ln2/N*k + r, with int k and r in [-ln2/2N, ln2/2N] + var z = InvLn2N * x; + // #if TOINT_INTRINSICS + // kd = roundtoint(z); + // ki = converttoint(z); + // #elif EXP_USE_TOINT_NARROW + // // z - kd is in [-0.5-2^-16, 0.5] in all rounding modes. + // var kd = z + shift; + // var ki = reinterpret(kd) >> 16; + // var kd = ki; + // #else + // z - kd is in [-1, 1] in non-nearest rounding modes. + var kd = z + shift; + var ki = reinterpret(kd); + kd -= shift; + // #endif + var r = x + kd * NegLn2hiN + kd * NegLn2loN; + // 2^(k/N) ~= scale * (1 + tail). + var idx = ((ki & N_MASK) << 1); + var top = ki << (52 - EXP_TABLE_BITS); + + var tail = reinterpret(load(EXP_DATA_TAB + (idx << alignof()))); // T[idx] + // This is only a valid scale when -1023*N < k < 1024*N + var sbits = load(EXP_DATA_TAB + (idx << alignof()), 1 << alignof()) + top; // T[idx + 1] + // exp(x) = 2^(k/N) * exp(r) ~= scale + scale * (tail + exp(r) - 1). + // Evaluation is optimized assuming superscalar pipelined execution. + var r2 = r * r; + // Without fma the worst case error is 0.25/N ulp larger. + // Worst case error is less than 0.5+1.11/N+(abs poly error * 2^53) ulp. + var tmp = tail + r + r2 * (C2 + r * C3) + r2 * r2 * (C4 + r * C5); + if (abstop == 0) return specialcase(tmp, sbits, ki); + var scale = reinterpret(sbits); + // Note: tmp == 0 or |tmp| > 2^-200 and scale > 2^-739, so there + // is no spurious underflow here even without fma. + return scale + scale * tmp; +} + +// +// Lookup data for exp2. See: https://git.musl-libc.org/cgit/musl/tree/src/math/exp2.c +// + +// Handle cases that may overflow or underflow when computing the result that +// is scale*(1+TMP) without intermediate rounding. The bit representation of +// scale is in SBITS, however it has a computed exponent that may have +// overflown into the sign bit so that needs to be adjusted before using it as +// a double. (int32_t)KI is the k used in the argument reduction and exponent +// adjustment of scale, positive k here means the result may overflow and +// negative k means the result may underflow. +// @ts-ignore: decorator +@inline +function specialcase2(tmp: f64, sbits: u64, ki: u64): f64 { + const Ox1p_1022 = reinterpret(0x10000000000000); // 0x1p-1022 + var scale: f64; + if ((ki & 0x80000000) == 0) { + // k > 0, the exponent of scale might have overflowed by 1 + sbits -= u64(1) << 52; + scale = reinterpret(sbits); + return 2 * (scale * tmp + scale); + } + // k < 0, need special care in the subnormal range + sbits += u64(1022) << 52; + scale = reinterpret(sbits); + var y = scale * tmp + scale; + if (y < 1.0) { + // Round y to the right precision before scaling it into the subnormal + // range to avoid double rounding that can cause 0.5+E/2 ulp error where + // E is the worst-case ulp error outside the subnormal range. So this + // is only useful if the goal is better than 1 ulp worst-case error. + let hi: f64, lo: f64; + lo = scale - y + scale * tmp; + hi = 1.0 + y; + lo = 1.0 - hi + y + lo; + y = (hi + lo) - 1.0; + } + return y * Ox1p_1022; +} + +// @ts-ignore: decorator +@inline +export function exp2_lut(x: f64): f64 { + const + N = 1 << EXP_TABLE_BITS, + N_MASK = N - 1, + shift = reinterpret(0x4338000000000000) / N; // 0x1.8p52 + + const + C1 = reinterpret(0x3FE62E42FEFA39EF), // 0x1.62e42fefa39efp-1 + C2 = reinterpret(0x3FCEBFBDFF82C424), // 0x1.ebfbdff82c424p-3 + C3 = reinterpret(0x3FAC6B08D70CF4B5), // 0x1.c6b08d70cf4b5p-5 + C4 = reinterpret(0x3F83B2ABD24650CC), // 0x1.3b2abd24650ccp-7 + C5 = reinterpret(0x3F55D7E09B4E3A84); // 0x1.5d7e09b4e3a84p-10 + + var ux = reinterpret(x); + var abstop = (ux >> 52 & 0x7ff); + if (abstop - 0x3C9 >= 0x03F) { + if (abstop - 0x3C9 >= 0x80000000) return 1.0; + if (abstop >= 0x409) { + if (ux == 0xFFF0000000000000) return 0; + if (abstop >= 0x7FF) return 1.0 + x; + if (!(ux >> 63)) return Infinity; + else if (ux >= 0xC090CC0000000000) return 0; + } + if ((ux << 1) > 0x811A000000000000) abstop = 0; // Large x is special cased below. + } + + // exp2(x) = 2^(k/N) * 2^r, with 2^r in [2^(-1/2N),2^(1/2N)]. + // x = k/N + r, with int k and r in [-1/2N, 1/2N] + var kd = x + shift; + var ki = reinterpret(kd); + kd -= shift; // k/N for int k + var r = x - kd; + // 2^(k/N) ~= scale * (1 + tail) + var idx = ((ki & N_MASK) << 1); + var top = ki << (52 - EXP_TABLE_BITS); + + var tail = reinterpret(load(EXP_DATA_TAB + (idx << alignof()), 0 << alignof())); // T[idx]) + // This is only a valid scale when -1023*N < k < 1024*N + var sbits = load(EXP_DATA_TAB + (idx << alignof()), 1 << alignof()) + top; // T[idx + 1] + // exp2(x) = 2^(k/N) * 2^r ~= scale + scale * (tail + 2^r - 1). + // Evaluation is optimized assuming superscalar pipelined execution + var r2 = r * r; + // Without fma the worst case error is 0.5/N ulp larger. + // Worst case error is less than 0.5+0.86/N+(abs poly error * 2^53) ulp. + var tmp = tail + r * C1 + r2 * (C2 + r * C3) + r2 * r2 * (C4 + r * C5); + if (abstop == 0) return specialcase2(tmp, sbits, ki); + var scale = reinterpret(sbits); + // Note: tmp == 0 or |tmp| > 2^-65 and scale > 2^-928, so there + // is no spurious underflow here even without fma. + return scale * tmp + scale; +} + +// +// Lookup data for log2. See: https://git.musl-libc.org/cgit/musl/tree/src/math/log2.c +// + +// @ts-ignore: decorator +@inline const LOG2_TABLE_BITS = 6; + +/* Algorithm: + + x = 2^k z + log2(x) = k + log2(c) + log2(z/c) + log2(z/c) = poly(z/c - 1) + +where z is in [1.6p-1; 1.6p0] which is split into N subintervals and z falls +into the ith one, then table entries are computed as + + tab[i].invc = 1/c + tab[i].logc = (double)log2(c) + tab2[i].chi = (double)c + tab2[i].clo = (double)(c - (double)c) + +where c is near the center of the subinterval and is chosen by trying +-2^29 +floating point invc candidates around 1/center and selecting one for which + + 1) the rounding error in 0x1.8p10 + logc is 0, + 2) the rounding error in z - chi - clo is < 0x1p-64 and + 3) the rounding error in (double)log2(c) is minimized (< 0x1p-68). + +Note: 1) ensures that k + logc can be computed without rounding error, 2) +ensures that z/c - 1 can be computed as (z - chi - clo)*invc with close to a +single rounding error when there is no fast fma for z*invc - 1, 3) ensures +that logc + poly(z/c - 1) has small error, however near x == 1 when +|log2(x)| < 0x1p-4, this is not enough so that is special cased. */ + +// @ts-ignore: decorator +@lazy @inline const LOG2_DATA_TAB1 = memory.data([ + // invc , logc + reinterpret(0x3FF724286BB1ACF8), reinterpret(0xBFE1095FEECDB000), + reinterpret(0x3FF6E1F766D2CCA1), reinterpret(0xBFE08494BD76D000), + reinterpret(0x3FF6A13D0E30D48A), reinterpret(0xBFE00143AEE8F800), + reinterpret(0x3FF661EC32D06C85), reinterpret(0xBFDEFEC5360B4000), + reinterpret(0x3FF623FA951198F8), reinterpret(0xBFDDFDD91AB7E000), + reinterpret(0x3FF5E75BA4CF026C), reinterpret(0xBFDCFFAE0CC79000), + reinterpret(0x3FF5AC055A214FB8), reinterpret(0xBFDC043811FDA000), + reinterpret(0x3FF571ED0F166E1E), reinterpret(0xBFDB0B67323AE000), + reinterpret(0x3FF53909590BF835), reinterpret(0xBFDA152F5A2DB000), + reinterpret(0x3FF5014FED61ADDD), reinterpret(0xBFD9217F5AF86000), + reinterpret(0x3FF4CAB88E487BD0), reinterpret(0xBFD8304DB0719000), + reinterpret(0x3FF49539B4334FEE), reinterpret(0xBFD74189F9A9E000), + reinterpret(0x3FF460CBDFAFD569), reinterpret(0xBFD6552BB5199000), + reinterpret(0x3FF42D664EE4B953), reinterpret(0xBFD56B23A29B1000), + reinterpret(0x3FF3FB01111DD8A6), reinterpret(0xBFD483650F5FA000), + reinterpret(0x3FF3C995B70C5836), reinterpret(0xBFD39DE937F6A000), + reinterpret(0x3FF3991C4AB6FD4A), reinterpret(0xBFD2BAA1538D6000), + reinterpret(0x3FF3698E0CE099B5), reinterpret(0xBFD1D98340CA4000), + reinterpret(0x3FF33AE48213E7B2), reinterpret(0xBFD0FA853A40E000), + reinterpret(0x3FF30D191985BDB1), reinterpret(0xBFD01D9C32E73000), + reinterpret(0x3FF2E025CAB271D7), reinterpret(0xBFCE857DA2FA6000), + reinterpret(0x3FF2B404CF13CD82), reinterpret(0xBFCCD3C8633D8000), + reinterpret(0x3FF288B02C7CCB50), reinterpret(0xBFCB26034C14A000), + reinterpret(0x3FF25E2263944DE5), reinterpret(0xBFC97C1C2F4FE000), + reinterpret(0x3FF234563D8615B1), reinterpret(0xBFC7D6023F800000), + reinterpret(0x3FF20B46E33EAF38), reinterpret(0xBFC633A71A05E000), + reinterpret(0x3FF1E2EEFDCDA3DD), reinterpret(0xBFC494F5E9570000), + reinterpret(0x3FF1BB4A580B3930), reinterpret(0xBFC2F9E424E0A000), + reinterpret(0x3FF19453847F2200), reinterpret(0xBFC162595AFDC000), + reinterpret(0x3FF16E06C0D5D73C), reinterpret(0xBFBF9C9A75BD8000), + reinterpret(0x3FF1485F47B7E4C2), reinterpret(0xBFBC7B575BF9C000), + reinterpret(0x3FF12358AD0085D1), reinterpret(0xBFB960C60FF48000), + reinterpret(0x3FF0FEF00F532227), reinterpret(0xBFB64CE247B60000), + reinterpret(0x3FF0DB2077D03A8F), reinterpret(0xBFB33F78B2014000), + reinterpret(0x3FF0B7E6D65980D9), reinterpret(0xBFB0387D1A42C000), + reinterpret(0x3FF0953EFE7B408D), reinterpret(0xBFAA6F9208B50000), + reinterpret(0x3FF07325CAC53B83), reinterpret(0xBFA47A954F770000), + reinterpret(0x3FF05197E40D1B5C), reinterpret(0xBF9D23A8C50C0000), + reinterpret(0x3FF03091C1208EA2), reinterpret(0xBF916A2629780000), + reinterpret(0x3FF0101025B37E21), reinterpret(0xBF7720F8D8E80000), + reinterpret(0x3FEFC07EF9CAA76B), reinterpret(0x3F86FE53B1500000), + reinterpret(0x3FEF4465D3F6F184), reinterpret(0x3FA11CCCE10F8000), + reinterpret(0x3FEECC079F84107F), reinterpret(0x3FAC4DFC8C8B8000), + reinterpret(0x3FEE573A99975AE8), reinterpret(0x3FB3AA321E574000), + reinterpret(0x3FEDE5D6F0BD3DE6), reinterpret(0x3FB918A0D08B8000), + reinterpret(0x3FED77B681FF38B3), reinterpret(0x3FBE72E9DA044000), + reinterpret(0x3FED0CB5724DE943), reinterpret(0x3FC1DCD2507F6000), + reinterpret(0x3FECA4B2DC0E7563), reinterpret(0x3FC476AB03DEA000), + reinterpret(0x3FEC3F8EE8D6CB51), reinterpret(0x3FC7074377E22000), + reinterpret(0x3FEBDD2B4F020C4C), reinterpret(0x3FC98EDE8BA94000), + reinterpret(0x3FEB7D6C006015CA), reinterpret(0x3FCC0DB86AD2E000), + reinterpret(0x3FEB20366E2E338F), reinterpret(0x3FCE840AAFCEE000), + reinterpret(0x3FEAC57026295039), reinterpret(0x3FD0790AB4678000), + reinterpret(0x3FEA6D01BC2731DD), reinterpret(0x3FD1AC056801C000), + reinterpret(0x3FEA16D3BC3FF18B), reinterpret(0x3FD2DB11D4FEE000), + reinterpret(0x3FE9C2D14967FEAD), reinterpret(0x3FD406464EC58000), + reinterpret(0x3FE970E4F47C9902), reinterpret(0x3FD52DBE093AF000), + reinterpret(0x3FE920FB3982BCF2), reinterpret(0x3FD651902050D000), + reinterpret(0x3FE8D30187F759F1), reinterpret(0x3FD771D2CDEAF000), + reinterpret(0x3FE886E5EBB9F66D), reinterpret(0x3FD88E9C857D9000), + reinterpret(0x3FE83C97B658B994), reinterpret(0x3FD9A80155E16000), + reinterpret(0x3FE7F405FFC61022), reinterpret(0x3FDABE186ED3D000), + reinterpret(0x3FE7AD22181415CA), reinterpret(0x3FDBD0F2AEA0E000), + reinterpret(0x3FE767DCF99EFF8C), reinterpret(0x3FDCE0A43DBF4000) +]); + +// @ts-ignore: decorator +@lazy @inline const LOG2_DATA_TAB2 = memory.data([ + // chi , clo + reinterpret(0x3FE6200012B90A8E), reinterpret(0x3C8904AB0644B605), + reinterpret(0x3FE66000045734A6), reinterpret(0x3C61FF9BEA62F7A9), + reinterpret(0x3FE69FFFC325F2C5), reinterpret(0x3C827ECFCB3C90BA), + reinterpret(0x3FE6E00038B95A04), reinterpret(0x3C88FF8856739326), + reinterpret(0x3FE71FFFE09994E3), reinterpret(0x3C8AFD40275F82B1), + reinterpret(0x3FE7600015590E10), reinterpret(0xBC72FD75B4238341), + reinterpret(0x3FE7A00012655BD5), reinterpret(0x3C7808E67C242B76), + reinterpret(0x3FE7E0003259E9A6), reinterpret(0xBC6208E426F622B7), + reinterpret(0x3FE81FFFEDB4B2D2), reinterpret(0xBC8402461EA5C92F), + reinterpret(0x3FE860002DFAFCC3), reinterpret(0x3C6DF7F4A2F29A1F), + reinterpret(0x3FE89FFFF78C6B50), reinterpret(0xBC8E0453094995FD), + reinterpret(0x3FE8E00039671566), reinterpret(0xBC8A04F3BEC77B45), + reinterpret(0x3FE91FFFE2BF1745), reinterpret(0xBC77FA34400E203C), + reinterpret(0x3FE95FFFCC5C9FD1), reinterpret(0xBC76FF8005A0695D), + reinterpret(0x3FE9A0003BBA4767), reinterpret(0x3C70F8C4C4EC7E03), + reinterpret(0x3FE9DFFFE7B92DA5), reinterpret(0x3C8E7FD9478C4602), + reinterpret(0x3FEA1FFFD72EFDAF), reinterpret(0xBC6A0C554DCDAE7E), + reinterpret(0x3FEA5FFFDE04FF95), reinterpret(0x3C867DA98CE9B26B), + reinterpret(0x3FEA9FFFCA5E8D2B), reinterpret(0xBC8284C9B54C13DE), + reinterpret(0x3FEADFFFDDAD03EA), reinterpret(0x3C5812C8EA602E3C), + reinterpret(0x3FEB1FFFF10D3D4D), reinterpret(0xBC8EFADDAD27789C), + reinterpret(0x3FEB5FFFCE21165A), reinterpret(0x3C53CB1719C61237), + reinterpret(0x3FEB9FFFD950E674), reinterpret(0x3C73F7D94194CE00), + reinterpret(0x3FEBE000139CA8AF), reinterpret(0x3C750AC4215D9BC0), + reinterpret(0x3FEC20005B46DF99), reinterpret(0x3C6BEEA653E9C1C9), + reinterpret(0x3FEC600040B9F7AE), reinterpret(0xBC7C079F274A70D6), + reinterpret(0x3FECA0006255FD8A), reinterpret(0xBC7A0B4076E84C1F), + reinterpret(0x3FECDFFFD94C095D), reinterpret(0x3C88F933F99AB5D7), + reinterpret(0x3FED1FFFF975D6CF), reinterpret(0xBC582C08665FE1BE), + reinterpret(0x3FED5FFFA2561C93), reinterpret(0xBC7B04289BD295F3), + reinterpret(0x3FED9FFF9D228B0C), reinterpret(0x3C870251340FA236), + reinterpret(0x3FEDE00065BC7E16), reinterpret(0xBC75011E16A4D80C), + reinterpret(0x3FEE200002F64791), reinterpret(0x3C89802F09EF62E0), + reinterpret(0x3FEE600057D7A6D8), reinterpret(0xBC7E0B75580CF7FA), + reinterpret(0x3FEEA00027EDC00C), reinterpret(0xBC8C848309459811), + reinterpret(0x3FEEE0006CF5CB7C), reinterpret(0xBC8F8027951576F4), + reinterpret(0x3FEF2000782B7DCC), reinterpret(0xBC8F81D97274538F), + reinterpret(0x3FEF6000260C450A), reinterpret(0xBC4071002727FFDC), + reinterpret(0x3FEF9FFFE88CD533), reinterpret(0xBC581BDCE1FDA8B0), + reinterpret(0x3FEFDFFFD50F8689), reinterpret(0x3C87F91ACB918E6E), + reinterpret(0x3FF0200004292367), reinterpret(0x3C9B7FF365324681), + reinterpret(0x3FF05FFFE3E3D668), reinterpret(0x3C86FA08DDAE957B), + reinterpret(0x3FF0A0000A85A757), reinterpret(0xBC57E2DE80D3FB91), + reinterpret(0x3FF0E0001A5F3FCC), reinterpret(0xBC91823305C5F014), + reinterpret(0x3FF11FFFF8AFBAF5), reinterpret(0xBC8BFABB6680BAC2), + reinterpret(0x3FF15FFFE54D91AD), reinterpret(0xBC9D7F121737E7EF), + reinterpret(0x3FF1A00011AC36E1), reinterpret(0x3C9C000A0516F5FF), + reinterpret(0x3FF1E00019C84248), reinterpret(0xBC9082FBE4DA5DA0), + reinterpret(0x3FF220000FFE5E6E), reinterpret(0xBC88FDD04C9CFB43), + reinterpret(0x3FF26000269FD891), reinterpret(0x3C8CFE2A7994D182), + reinterpret(0x3FF2A00029A6E6DA), reinterpret(0xBC700273715E8BC5), + reinterpret(0x3FF2DFFFE0293E39), reinterpret(0x3C9B7C39DAB2A6F9), + reinterpret(0x3FF31FFFF7DCF082), reinterpret(0x3C7DF1336EDC5254), + reinterpret(0x3FF35FFFF05A8B60), reinterpret(0xBC9E03564CCD31EB), + reinterpret(0x3FF3A0002E0EAECC), reinterpret(0x3C75F0E74BD3A477), + reinterpret(0x3FF3E000043BB236), reinterpret(0x3C9C7DCB149D8833), + reinterpret(0x3FF4200002D187FF), reinterpret(0x3C7E08AFCF2D3D28), + reinterpret(0x3FF460000D387CB1), reinterpret(0x3C820837856599A6), + reinterpret(0x3FF4A00004569F89), reinterpret(0xBC89FA5C904FBCD2), + reinterpret(0x3FF4E000043543F3), reinterpret(0xBC781125ED175329), + reinterpret(0x3FF51FFFCC027F0F), reinterpret(0x3C9883D8847754DC), + reinterpret(0x3FF55FFFFD87B36F), reinterpret(0xBC8709E731D02807), + reinterpret(0x3FF59FFFF21DF7BA), reinterpret(0x3C87F79F68727B02), + reinterpret(0x3FF5DFFFEBFC3481), reinterpret(0xBC9180902E30E93E) +]); + +// @ts-ignore: decorator +@inline +export function log2_lut(x: f64): f64 { + const N_MASK = (1 << LOG2_TABLE_BITS) - 1; + + const + LO: u64 = 0x3FEEA4AF00000000, // reinterpret(1.0 - 0x1.5b51p-5) + HI: u64 = 0x3FF0B55900000000; // reinterpret(1.0 + 0x1.6ab2p-5) + + const + InvLn2hi = reinterpret(0x3FF7154765200000), // 0x1.7154765200000p+0 + InvLn2lo = reinterpret(0x3DE705FC2EEFA200), // 0x1.705fc2eefa200p-33 + Ox1p52 = reinterpret(0x4330000000000000); // 0x1p52 + + const + B0 = reinterpret(0xBFE71547652B82FE), // -0x1.71547652b82fep-1 + B1 = reinterpret(0x3FDEC709DC3A03F7), // 0x1.ec709dc3a03f7p-2 + B2 = reinterpret(0xBFD71547652B7C3F), // -0x1.71547652b7c3fp-2 + B3 = reinterpret(0x3FD2776C50F05BE4), // 0x1.2776c50f05be4p-2 + B4 = reinterpret(0xBFCEC709DD768FE5), // -0x1.ec709dd768fe5p-3 + B5 = reinterpret(0x3FCA61761EC4E736), // 0x1.a61761ec4e736p-3 + B6 = reinterpret(0xBFC7153FBC64A79B), // -0x1.7153fbc64a79bp-3 + B7 = reinterpret(0x3FC484D154F01B4A), // 0x1.484d154f01b4ap-3 + B8 = reinterpret(0xBFC289E4A72C383C), // -0x1.289e4a72c383cp-3 + B9 = reinterpret(0x3FC0B32F285AEE66); // 0x1.0b32f285aee66p-3 + + const + A0 = reinterpret(0xBFE71547652B8339), // -0x1.71547652b8339p-1 + A1 = reinterpret(0x3FDEC709DC3A04BE), // 0x1.ec709dc3a04bep-2 + A2 = reinterpret(0xBFD7154764702FFB), // -0x1.7154764702ffbp-2 + A3 = reinterpret(0x3FD2776C50034C48), // 0x1.2776c50034c48p-2 + A4 = reinterpret(0xBFCEC7B328EA92BC), // -0x1.ec7b328ea92bcp-3 + A5 = reinterpret(0x3FCA6225E117F92E); // 0x1.a6225e117f92ep-3 + + var ix = reinterpret(x); + if (ix - LO < HI - LO) { + let r = x - 1.0; + // #if __FP_FAST_FMA + // hi = r * InvLn2hi; + // lo = r * InvLn2lo + __builtin_fma(r, InvLn2hi, -hi); + // #else + let rhi = reinterpret(reinterpret(r) & 0xFFFFFFFF00000000); + let rlo = r - rhi; + let hi = rhi * InvLn2hi; + let lo = rlo * InvLn2hi + r * InvLn2lo; + // #endif + let r2 = r * r; // rounding error: 0x1p-62 + let r4 = r2 * r2; + // Worst-case error is less than 0.54 ULP (0.55 ULP without fma) + let p = r2 * (B0 + r * B1); + let y = hi + p; + lo += hi - y + p; + lo += r4 * (B2 + r * B3 + r2 * (B4 + r * B5) + + r4 * (B6 + r * B7 + r2 * (B8 + r * B9))); + return y + lo; + } + var top = (ix >> 48); + if (top - 0x0010 >= 0x7ff0 - 0x0010) { + // x < 0x1p-1022 or inf or nan. + if ((ix << 1) == 0) return -1.0 / (x * x); + if (ix == 0x7FF0000000000000) return x; // log(inf) == inf + if ((top & 0x8000) || (top & 0x7FF0) == 0x7FF0) return (x - x) / (x - x); + // x is subnormal, normalize it. + ix = reinterpret(x * Ox1p52); + ix -= u64(52) << 52; + } + + // x = 2^k z; where z is in range [OFF,2*OFF) and exact. + // The range is split into N subintervals. + // The ith subinterval contains z and c is near its center. + var tmp = ix - 0x3FE6000000000000; + var i = ((tmp >> (52 - LOG2_TABLE_BITS)) & N_MASK); + var k = tmp >> 52; + var iz = ix - (tmp & 0xFFF0000000000000); + + var invc = load(LOG2_DATA_TAB1 + (i << (1 + alignof())), 0 << alignof()); // T[i].invc; + var logc = load(LOG2_DATA_TAB1 + (i << (1 + alignof())), 1 << alignof()); // T[i].logc; + var z = reinterpret(iz); + var kd = k; + + // log2(x) = log2(z/c) + log2(c) + k. + // r ~= z/c - 1, |r| < 1/(2*N). + // #if __FP_FAST_FMA + // // rounding error: 0x1p-55/N. + // r = __builtin_fma(z, invc, -1.0); + // t1 = r * InvLn2hi; + // t2 = r * InvLn2lo + __builtin_fma(r, InvLn2hi, -t1); + // #else + // rounding error: 0x1p-55/N + 0x1p-65. + var chi = load(LOG2_DATA_TAB2 + (i << (1 + alignof())), 0 << alignof()); // T[i].chi; + var clo = load(LOG2_DATA_TAB2 + (i << (1 + alignof())), 1 << alignof()); // T[i].clo; + + var r = (z - chi - clo) * invc; + var rhi = reinterpret(reinterpret(r) & 0xFFFFFFFF00000000); + var rlo = r - rhi; + var t1 = rhi * InvLn2hi; + var t2 = rlo * InvLn2hi + r * InvLn2lo; + // #endif + + // hi + lo = r/ln2 + log2(c) + k + var t3 = kd + logc; + var hi = t3 + t1; + var lo = t3 - hi + t1 + t2; + + // log2(r+1) = r/ln2 + r^2*poly(r) + // Evaluation is optimized assuming superscalar pipelined execution + var r2 = r * r; // rounding error: 0x1p-54/N^2 + // Worst-case error if |y| > 0x1p-4: 0.547 ULP (0.550 ULP without fma). + // ~ 0.5 + 2/N/ln2 + abs-poly-error*0x1p56 ULP (+ 0.003 ULP without fma). + var p = A0 + r * A1 + r2 * (A2 + r * A3) + (r2 * r2) * (A4 + r * A5); + return lo + r2 * p + hi; +} + +// +// Lookup data for log. See: https://git.musl-libc.org/cgit/musl/tree/src/math/log.c +// + +// @ts-ignore: decorator +@inline const LOG_TABLE_BITS = 7; + +/* Algorithm: + + x = 2^k z + log(x) = k ln2 + log(c) + log(z/c) + log(z/c) = poly(z/c - 1) + +where z is in [1.6p-1; 1.6p0] which is split into N subintervals and z falls +into the ith one, then table entries are computed as + + tab[i].invc = 1/c + tab[i].logc = (double)log(c) + tab2[i].chi = (double)c + tab2[i].clo = (double)(c - (double)c) + +where c is near the center of the subinterval and is chosen by trying +-2^29 +floating point invc candidates around 1/center and selecting one for which + + 1) the rounding error in 0x1.8p9 + logc is 0, + 2) the rounding error in z - chi - clo is < 0x1p-66 and + 3) the rounding error in (double)log(c) is minimized (< 0x1p-66). + +Note: 1) ensures that k*ln2hi + logc can be computed without rounding error, +2) ensures that z/c - 1 can be computed as (z - chi - clo)*invc with close to +a single rounding error when there is no fast fma for z*invc - 1, 3) ensures +that logc + poly(z/c - 1) has small error, however near x == 1 when +|log(x)| < 0x1p-4, this is not enough so that is special cased.*/ + +// @ts-ignore: decorator +@lazy @inline const LOG_DATA_TAB1 = memory.data([ + // invc , logc + reinterpret(0x3FF734F0C3E0DE9F), reinterpret(0xBFD7CC7F79E69000), + reinterpret(0x3FF713786A2CE91F), reinterpret(0xBFD76FEEC20D0000), + reinterpret(0x3FF6F26008FAB5A0), reinterpret(0xBFD713E31351E000), + reinterpret(0x3FF6D1A61F138C7D), reinterpret(0xBFD6B85B38287800), + reinterpret(0x3FF6B1490BC5B4D1), reinterpret(0xBFD65D5590807800), + reinterpret(0x3FF69147332F0CBA), reinterpret(0xBFD602D076180000), + reinterpret(0x3FF6719F18224223), reinterpret(0xBFD5A8CA86909000), + reinterpret(0x3FF6524F99A51ED9), reinterpret(0xBFD54F4356035000), + reinterpret(0x3FF63356AA8F24C4), reinterpret(0xBFD4F637C36B4000), + reinterpret(0x3FF614B36B9DDC14), reinterpret(0xBFD49DA7FDA85000), + reinterpret(0x3FF5F66452C65C4C), reinterpret(0xBFD445923989A800), + reinterpret(0x3FF5D867B5912C4F), reinterpret(0xBFD3EDF439B0B800), + reinterpret(0x3FF5BABCCB5B90DE), reinterpret(0xBFD396CE448F7000), + reinterpret(0x3FF59D61F2D91A78), reinterpret(0xBFD3401E17BDA000), + reinterpret(0x3FF5805612465687), reinterpret(0xBFD2E9E2EF468000), + reinterpret(0x3FF56397CEE76BD3), reinterpret(0xBFD2941B3830E000), + reinterpret(0x3FF54725E2A77F93), reinterpret(0xBFD23EC58CDA8800), + reinterpret(0x3FF52AFF42064583), reinterpret(0xBFD1E9E129279000), + reinterpret(0x3FF50F22DBB2BDDF), reinterpret(0xBFD1956D2B48F800), + reinterpret(0x3FF4F38F4734DED7), reinterpret(0xBFD141679AB9F800), + reinterpret(0x3FF4D843CFDE2840), reinterpret(0xBFD0EDD094EF9800), + reinterpret(0x3FF4BD3EC078A3C8), reinterpret(0xBFD09AA518DB1000), + reinterpret(0x3FF4A27FC3E0258A), reinterpret(0xBFD047E65263B800), + reinterpret(0x3FF4880524D48434), reinterpret(0xBFCFEB224586F000), + reinterpret(0x3FF46DCE1B192D0B), reinterpret(0xBFCF474A7517B000), + reinterpret(0x3FF453D9D3391854), reinterpret(0xBFCEA4443D103000), + reinterpret(0x3FF43A2744B4845A), reinterpret(0xBFCE020D44E9B000), + reinterpret(0x3FF420B54115F8FB), reinterpret(0xBFCD60A22977F000), + reinterpret(0x3FF40782DA3EF4B1), reinterpret(0xBFCCC00104959000), + reinterpret(0x3FF3EE8F5D57FE8F), reinterpret(0xBFCC202956891000), + reinterpret(0x3FF3D5D9A00B4CE9), reinterpret(0xBFCB81178D811000), + reinterpret(0x3FF3BD60C010C12B), reinterpret(0xBFCAE2C9CCD3D000), + reinterpret(0x3FF3A5242B75DAB8), reinterpret(0xBFCA45402E129000), + reinterpret(0x3FF38D22CD9FD002), reinterpret(0xBFC9A877681DF000), + reinterpret(0x3FF3755BC5847A1C), reinterpret(0xBFC90C6D69483000), + reinterpret(0x3FF35DCE49AD36E2), reinterpret(0xBFC87120A645C000), + reinterpret(0x3FF34679984DD440), reinterpret(0xBFC7D68FB4143000), + reinterpret(0x3FF32F5CCEFFCB24), reinterpret(0xBFC73CB83C627000), + reinterpret(0x3FF3187775A10D49), reinterpret(0xBFC6A39A9B376000), + reinterpret(0x3FF301C8373E3990), reinterpret(0xBFC60B3154B7A000), + reinterpret(0x3FF2EB4EBB95F841), reinterpret(0xBFC5737D76243000), + reinterpret(0x3FF2D50A0219A9D1), reinterpret(0xBFC4DC7B8FC23000), + reinterpret(0x3FF2BEF9A8B7FD2A), reinterpret(0xBFC4462C51D20000), + reinterpret(0x3FF2A91C7A0C1BAB), reinterpret(0xBFC3B08ABC830000), + reinterpret(0x3FF293726014B530), reinterpret(0xBFC31B996B490000), + reinterpret(0x3FF27DFA5757A1F5), reinterpret(0xBFC2875490A44000), + reinterpret(0x3FF268B39B1D3BBF), reinterpret(0xBFC1F3B9F879A000), + reinterpret(0x3FF2539D838FF5BD), reinterpret(0xBFC160C8252CA000), + reinterpret(0x3FF23EB7AAC9083B), reinterpret(0xBFC0CE7F57F72000), + reinterpret(0x3FF22A012BA940B6), reinterpret(0xBFC03CDC49FEA000), + reinterpret(0x3FF2157996CC4132), reinterpret(0xBFBF57BDBC4B8000), + reinterpret(0x3FF201201DD2FC9B), reinterpret(0xBFBE370896404000), + reinterpret(0x3FF1ECF4494D480B), reinterpret(0xBFBD17983EF94000), + reinterpret(0x3FF1D8F5528F6569), reinterpret(0xBFBBF9674ED8A000), + reinterpret(0x3FF1C52311577E7C), reinterpret(0xBFBADC79202F6000), + reinterpret(0x3FF1B17C74CB26E9), reinterpret(0xBFB9C0C3E7288000), + reinterpret(0x3FF19E010C2C1AB6), reinterpret(0xBFB8A646B372C000), + reinterpret(0x3FF18AB07BB670BD), reinterpret(0xBFB78D01B3AC0000), + reinterpret(0x3FF1778A25EFBCB6), reinterpret(0xBFB674F145380000), + reinterpret(0x3FF1648D354C31DA), reinterpret(0xBFB55E0E6D878000), + reinterpret(0x3FF151B990275FDD), reinterpret(0xBFB4485CDEA1E000), + reinterpret(0x3FF13F0EA432D24C), reinterpret(0xBFB333D94D6AA000), + reinterpret(0x3FF12C8B7210F9DA), reinterpret(0xBFB22079F8C56000), + reinterpret(0x3FF11A3028ECB531), reinterpret(0xBFB10E4698622000), + reinterpret(0x3FF107FBDA8434AF), reinterpret(0xBFAFFA6C6AD20000), + reinterpret(0x3FF0F5EE0F4E6BB3), reinterpret(0xBFADDA8D4A774000), + reinterpret(0x3FF0E4065D2A9FCE), reinterpret(0xBFABBCECE4850000), + reinterpret(0x3FF0D244632CA521), reinterpret(0xBFA9A1894012C000), + reinterpret(0x3FF0C0A77CE2981A), reinterpret(0xBFA788583302C000), + reinterpret(0x3FF0AF2F83C636D1), reinterpret(0xBFA5715E67D68000), + reinterpret(0x3FF09DDB98A01339), reinterpret(0xBFA35C8A49658000), + reinterpret(0x3FF08CABAF52E7DF), reinterpret(0xBFA149E364154000), + reinterpret(0x3FF07B9F2F4E28FB), reinterpret(0xBF9E72C082EB8000), + reinterpret(0x3FF06AB58C358F19), reinterpret(0xBF9A55F152528000), + reinterpret(0x3FF059EEA5ECF92C), reinterpret(0xBF963D62CF818000), + reinterpret(0x3FF04949CDD12C90), reinterpret(0xBF9228FB8CAA0000), + reinterpret(0x3FF038C6C6F0ADA9), reinterpret(0xBF8C317B20F90000), + reinterpret(0x3FF02865137932A9), reinterpret(0xBF8419355DAA0000), + reinterpret(0x3FF0182427EA7348), reinterpret(0xBF781203C2EC0000), + reinterpret(0x3FF008040614B195), reinterpret(0xBF60040979240000), + reinterpret(0x3FEFE01FF726FA1A), reinterpret(0x3F6FEFF384900000), + reinterpret(0x3FEFA11CC261EA74), reinterpret(0x3F87DC41353D0000), + reinterpret(0x3FEF6310B081992E), reinterpret(0x3F93CEA3C4C28000), + reinterpret(0x3FEF25F63CEEADCD), reinterpret(0x3F9B9FC114890000), + reinterpret(0x3FEEE9C8039113E7), reinterpret(0x3FA1B0D8CE110000), + reinterpret(0x3FEEAE8078CBB1AB), reinterpret(0x3FA58A5BD001C000), + reinterpret(0x3FEE741AA29D0C9B), reinterpret(0x3FA95C8340D88000), + reinterpret(0x3FEE3A91830A99B5), reinterpret(0x3FAD276AEF578000), + reinterpret(0x3FEE01E009609A56), reinterpret(0x3FB07598E598C000), + reinterpret(0x3FEDCA01E577BB98), reinterpret(0x3FB253F5E30D2000), + reinterpret(0x3FED92F20B7C9103), reinterpret(0x3FB42EDD8B380000), + reinterpret(0x3FED5CAC66FB5CCE), reinterpret(0x3FB606598757C000), + reinterpret(0x3FED272CAA5EDE9D), reinterpret(0x3FB7DA76356A0000), + reinterpret(0x3FECF26E3E6B2CCD), reinterpret(0x3FB9AB434E1C6000), + reinterpret(0x3FECBE6DA2A77902), reinterpret(0x3FBB78C7BB0D6000), + reinterpret(0x3FEC8B266D37086D), reinterpret(0x3FBD431332E72000), + reinterpret(0x3FEC5894BD5D5804), reinterpret(0x3FBF0A3171DE6000), + reinterpret(0x3FEC26B533BB9F8C), reinterpret(0x3FC067152B914000), + reinterpret(0x3FEBF583EEECE73F), reinterpret(0x3FC147858292B000), + reinterpret(0x3FEBC4FD75DB96C1), reinterpret(0x3FC2266ECDCA3000), + reinterpret(0x3FEB951E0C864A28), reinterpret(0x3FC303D7A6C55000), + reinterpret(0x3FEB65E2C5EF3E2C), reinterpret(0x3FC3DFC33C331000), + reinterpret(0x3FEB374867C9888B), reinterpret(0x3FC4BA366B7A8000), + reinterpret(0x3FEB094B211D304A), reinterpret(0x3FC5933928D1F000), + reinterpret(0x3FEADBE885F2EF7E), reinterpret(0x3FC66ACD2418F000), + reinterpret(0x3FEAAF1D31603DA2), reinterpret(0x3FC740F8EC669000), + reinterpret(0x3FEA82E63FD358A7), reinterpret(0x3FC815C0F51AF000), + reinterpret(0x3FEA5740EF09738B), reinterpret(0x3FC8E92954F68000), + reinterpret(0x3FEA2C2A90AB4B27), reinterpret(0x3FC9BB3602F84000), + reinterpret(0x3FEA01A01393F2D1), reinterpret(0x3FCA8BED1C2C0000), + reinterpret(0x3FE9D79F24DB3C1B), reinterpret(0x3FCB5B515C01D000), + reinterpret(0x3FE9AE2505C7B190), reinterpret(0x3FCC2967CCBCC000), + reinterpret(0x3FE9852EF297CE2F), reinterpret(0x3FCCF635D5486000), + reinterpret(0x3FE95CBAEEA44B75), reinterpret(0x3FCDC1BD3446C000), + reinterpret(0x3FE934C69DE74838), reinterpret(0x3FCE8C01B8CFE000), + reinterpret(0x3FE90D4F2F6752E6), reinterpret(0x3FCF5509C0179000), + reinterpret(0x3FE8E6528EFFD79D), reinterpret(0x3FD00E6C121FB800), + reinterpret(0x3FE8BFCE9FCC007C), reinterpret(0x3FD071B80E93D000), + reinterpret(0x3FE899C0DABEC30E), reinterpret(0x3FD0D46B9E867000), + reinterpret(0x3FE87427AA2317FB), reinterpret(0x3FD13687334BD000), + reinterpret(0x3FE84F00ACB39A08), reinterpret(0x3FD1980D67234800), + reinterpret(0x3FE82A49E8653E55), reinterpret(0x3FD1F8FFE0CC8000), + reinterpret(0x3FE8060195F40260), reinterpret(0x3FD2595FD7636800), + reinterpret(0x3FE7E22563E0A329), reinterpret(0x3FD2B9300914A800), + reinterpret(0x3FE7BEB377DCB5AD), reinterpret(0x3FD3187210436000), + reinterpret(0x3FE79BAA679725C2), reinterpret(0x3FD377266DEC1800), + reinterpret(0x3FE77907F2170657), reinterpret(0x3FD3D54FFBAF3000), + reinterpret(0x3FE756CADBD6130C), reinterpret(0x3FD432EEE32FE000) +]); + +// @ts-ignore: decorator +@lazy @inline const LOG_DATA_TAB2 = memory.data([ + // chi , clo + reinterpret(0x3FE61000014FB66B), reinterpret(0x3C7E026C91425B3C), + reinterpret(0x3FE63000034DB495), reinterpret(0x3C8DBFEA48005D41), + reinterpret(0x3FE650000D94D478), reinterpret(0x3C8E7FA786D6A5B7), + reinterpret(0x3FE67000074E6FAD), reinterpret(0x3C61FCEA6B54254C), + reinterpret(0x3FE68FFFFEDF0FAE), reinterpret(0xBC7C7E274C590EFD), + reinterpret(0x3FE6B0000763C5BC), reinterpret(0xBC8AC16848DCDA01), + reinterpret(0x3FE6D0001E5CC1F6), reinterpret(0x3C833F1C9D499311), + reinterpret(0x3FE6EFFFEB05F63E), reinterpret(0xBC7E80041AE22D53), + reinterpret(0x3FE710000E869780), reinterpret(0x3C7BFF6671097952), + reinterpret(0x3FE72FFFFC67E912), reinterpret(0x3C8C00E226BD8724), + reinterpret(0x3FE74FFFDF81116A), reinterpret(0xBC6E02916EF101D2), + reinterpret(0x3FE770000F679C90), reinterpret(0xBC67FC71CD549C74), + reinterpret(0x3FE78FFFFA7EC835), reinterpret(0x3C81BEC19EF50483), + reinterpret(0x3FE7AFFFFE20C2E6), reinterpret(0xBC707E1729CC6465), + reinterpret(0x3FE7CFFFED3FC900), reinterpret(0xBC808072087B8B1C), + reinterpret(0x3FE7EFFFE9261A76), reinterpret(0x3C8DC0286D9DF9AE), + reinterpret(0x3FE81000049CA3E8), reinterpret(0x3C897FD251E54C33), + reinterpret(0x3FE8300017932C8F), reinterpret(0xBC8AFEE9B630F381), + reinterpret(0x3FE850000633739C), reinterpret(0x3C89BFBF6B6535BC), + reinterpret(0x3FE87000204289C6), reinterpret(0xBC8BBF65F3117B75), + reinterpret(0x3FE88FFFEBF57904), reinterpret(0xBC89006EA23DCB57), + reinterpret(0x3FE8B00022BC04DF), reinterpret(0xBC7D00DF38E04B0A), + reinterpret(0x3FE8CFFFE50C1B8A), reinterpret(0xBC88007146FF9F05), + reinterpret(0x3FE8EFFFFC918E43), reinterpret(0x3C83817BD07A7038), + reinterpret(0x3FE910001EFA5FC7), reinterpret(0x3C893E9176DFB403), + reinterpret(0x3FE9300013467BB9), reinterpret(0x3C7F804E4B980276), + reinterpret(0x3FE94FFFE6EE076F), reinterpret(0xBC8F7EF0D9FF622E), + reinterpret(0x3FE96FFFDE3C12D1), reinterpret(0xBC7082AA962638BA), + reinterpret(0x3FE98FFFF4458A0D), reinterpret(0xBC87801B9164A8EF), + reinterpret(0x3FE9AFFFDD982E3E), reinterpret(0xBC8740E08A5A9337), + reinterpret(0x3FE9CFFFED49FB66), reinterpret(0x3C3FCE08C19BE000), + reinterpret(0x3FE9F00020F19C51), reinterpret(0xBC8A3FAA27885B0A), + reinterpret(0x3FEA10001145B006), reinterpret(0x3C74FF489958DA56), + reinterpret(0x3FEA300007BBF6FA), reinterpret(0x3C8CBEAB8A2B6D18), + reinterpret(0x3FEA500010971D79), reinterpret(0x3C88FECADD787930), + reinterpret(0x3FEA70001DF52E48), reinterpret(0xBC8F41763DD8ABDB), + reinterpret(0x3FEA90001C593352), reinterpret(0xBC8EBF0284C27612), + reinterpret(0x3FEAB0002A4F3E4B), reinterpret(0xBC69FD043CFF3F5F), + reinterpret(0x3FEACFFFD7AE1ED1), reinterpret(0xBC823EE7129070B4), + reinterpret(0x3FEAEFFFEE510478), reinterpret(0x3C6A063EE00EDEA3), + reinterpret(0x3FEB0FFFDB650D5B), reinterpret(0x3C5A06C8381F0AB9), + reinterpret(0x3FEB2FFFFEAACA57), reinterpret(0xBC79011E74233C1D), + reinterpret(0x3FEB4FFFD995BADC), reinterpret(0xBC79FF1068862A9F), + reinterpret(0x3FEB7000249E659C), reinterpret(0x3C8AFF45D0864F3E), + reinterpret(0x3FEB8FFFF9871640), reinterpret(0x3C7CFE7796C2C3F9), + reinterpret(0x3FEBAFFFD204CB4F), reinterpret(0xBC63FF27EEF22BC4), + reinterpret(0x3FEBCFFFD2415C45), reinterpret(0xBC6CFFB7EE3BEA21), + reinterpret(0x3FEBEFFFF86309DF), reinterpret(0xBC814103972E0B5C), + reinterpret(0x3FEC0FFFE1B57653), reinterpret(0x3C8BC16494B76A19), + reinterpret(0x3FEC2FFFF1FA57E3), reinterpret(0xBC64FEEF8D30C6ED), + reinterpret(0x3FEC4FFFDCBFE424), reinterpret(0xBC843F68BCEC4775), + reinterpret(0x3FEC6FFFED54B9F7), reinterpret(0x3C847EA3F053E0EC), + reinterpret(0x3FEC8FFFEB998FD5), reinterpret(0x3C7383068DF992F1), + reinterpret(0x3FECB0002125219A), reinterpret(0xBC68FD8E64180E04), + reinterpret(0x3FECCFFFDD94469C), reinterpret(0x3C8E7EBE1CC7EA72), + reinterpret(0x3FECEFFFEAFDC476), reinterpret(0x3C8EBE39AD9F88FE), + reinterpret(0x3FED1000169AF82B), reinterpret(0x3C757D91A8B95A71), + reinterpret(0x3FED30000D0FF71D), reinterpret(0x3C89C1906970C7DA), + reinterpret(0x3FED4FFFEA790FC4), reinterpret(0xBC580E37C558FE0C), + reinterpret(0x3FED70002EDC87E5), reinterpret(0xBC7F80D64DC10F44), + reinterpret(0x3FED900021DC82AA), reinterpret(0xBC747C8F94FD5C5C), + reinterpret(0x3FEDAFFFD86B0283), reinterpret(0x3C8C7F1DC521617E), + reinterpret(0x3FEDD000296C4739), reinterpret(0x3C88019EB2FFB153), + reinterpret(0x3FEDEFFFE54490F5), reinterpret(0x3C6E00D2C652CC89), + reinterpret(0x3FEE0FFFCDABF694), reinterpret(0xBC7F8340202D69D2), + reinterpret(0x3FEE2FFFDB52C8DD), reinterpret(0x3C7B00C1CA1B0864), + reinterpret(0x3FEE4FFFF24216EF), reinterpret(0x3C72FFA8B094AB51), + reinterpret(0x3FEE6FFFE88A5E11), reinterpret(0xBC57F673B1EFBE59), + reinterpret(0x3FEE9000119EFF0D), reinterpret(0xBC84808D5E0BC801), + reinterpret(0x3FEEAFFFDFA51744), reinterpret(0x3C780006D54320B5), + reinterpret(0x3FEED0001A127FA1), reinterpret(0xBC5002F860565C92), + reinterpret(0x3FEEF00007BABCC4), reinterpret(0xBC8540445D35E611), + reinterpret(0x3FEF0FFFF57A8D02), reinterpret(0xBC4FFB3139EF9105), + reinterpret(0x3FEF30001EE58AC7), reinterpret(0x3C8A81ACF2731155), + reinterpret(0x3FEF4FFFF5823494), reinterpret(0x3C8A3F41D4D7C743), + reinterpret(0x3FEF6FFFFCA94C6B), reinterpret(0xBC6202F41C987875), + reinterpret(0x3FEF8FFFE1F9C441), reinterpret(0x3C777DD1F477E74B), + reinterpret(0x3FEFAFFFD2E0E37E), reinterpret(0xBC6F01199A7CA331), + reinterpret(0x3FEFD0001C77E49E), reinterpret(0x3C7181EE4BCEACB1), + reinterpret(0x3FEFEFFFF7E0C331), reinterpret(0xBC6E05370170875A), + reinterpret(0x3FF00FFFF465606E), reinterpret(0xBC8A7EAD491C0ADA), + reinterpret(0x3FF02FFFF3867A58), reinterpret(0xBC977F69C3FCB2E0), + reinterpret(0x3FF04FFFFDFC0D17), reinterpret(0x3C97BFFE34CB945B), + reinterpret(0x3FF0700003CD4D82), reinterpret(0x3C820083C0E456CB), + reinterpret(0x3FF08FFFF9F2CBE8), reinterpret(0xBC6DFFDFBE37751A), + reinterpret(0x3FF0B000010CDA65), reinterpret(0xBC913F7FAEE626EB), + reinterpret(0x3FF0D00001A4D338), reinterpret(0x3C807DFA79489FF7), + reinterpret(0x3FF0EFFFFADAFDFD), reinterpret(0xBC77040570D66BC0), + reinterpret(0x3FF110000BBAFD96), reinterpret(0x3C8E80D4846D0B62), + reinterpret(0x3FF12FFFFAE5F45D), reinterpret(0x3C9DBFFA64FD36EF), + reinterpret(0x3FF150000DD59AD9), reinterpret(0x3C9A0077701250AE), + reinterpret(0x3FF170000F21559A), reinterpret(0x3C8DFDF9E2E3DEEE), + reinterpret(0x3FF18FFFFC275426), reinterpret(0x3C910030DC3B7273), + reinterpret(0x3FF1B000123D3C59), reinterpret(0x3C997F7980030188), + reinterpret(0x3FF1CFFFF8299EB7), reinterpret(0xBC65F932AB9F8C67), + reinterpret(0x3FF1EFFFF48AD400), reinterpret(0x3C937FBF9DA75BEB), + reinterpret(0x3FF210000C8B86A4), reinterpret(0x3C9F806B91FD5B22), + reinterpret(0x3FF2300003854303), reinterpret(0x3C93FFC2EB9FBF33), + reinterpret(0x3FF24FFFFFBCF684), reinterpret(0x3C7601E77E2E2E72), + reinterpret(0x3FF26FFFF52921D9), reinterpret(0x3C7FFCBB767F0C61), + reinterpret(0x3FF2900014933A3C), reinterpret(0xBC7202CA3C02412B), + reinterpret(0x3FF2B00014556313), reinterpret(0xBC92808233F21F02), + reinterpret(0x3FF2CFFFEBFE523B), reinterpret(0xBC88FF7E384FDCF2), + reinterpret(0x3FF2F0000BB8AD96), reinterpret(0xBC85FF51503041C5), + reinterpret(0x3FF30FFFFB7AE2AF), reinterpret(0xBC810071885E289D), + reinterpret(0x3FF32FFFFEAC5F7F), reinterpret(0xBC91FF5D3FB7B715), + reinterpret(0x3FF350000CA66756), reinterpret(0x3C957F82228B82BD), + reinterpret(0x3FF3700011FBF721), reinterpret(0x3C8000BAC40DD5CC), + reinterpret(0x3FF38FFFF9592FB9), reinterpret(0xBC943F9D2DB2A751), + reinterpret(0x3FF3B00004DDD242), reinterpret(0x3C857F6B707638E1), + reinterpret(0x3FF3CFFFF5B2C957), reinterpret(0x3C7A023A10BF1231), + reinterpret(0x3FF3EFFFEAB0B418), reinterpret(0x3C987F6D66B152B0), + reinterpret(0x3FF410001532AFF4), reinterpret(0x3C67F8375F198524), + reinterpret(0x3FF4300017478B29), reinterpret(0x3C8301E672DC5143), + reinterpret(0x3FF44FFFE795B463), reinterpret(0x3C89FF69B8B2895A), + reinterpret(0x3FF46FFFE80475E0), reinterpret(0xBC95C0B19BC2F254), + reinterpret(0x3FF48FFFEF6FC1E7), reinterpret(0x3C9B4009F23A2A72), + reinterpret(0x3FF4AFFFE5BEA704), reinterpret(0xBC94FFB7BF0D7D45), + reinterpret(0x3FF4D000171027DE), reinterpret(0xBC99C06471DC6A3D), + reinterpret(0x3FF4F0000FF03EE2), reinterpret(0x3C977F890B85531C), + reinterpret(0x3FF5100012DC4BD1), reinterpret(0x3C6004657166A436), + reinterpret(0x3FF530001605277A), reinterpret(0xBC96BFCECE233209), + reinterpret(0x3FF54FFFECDB704C), reinterpret(0xBC8902720505A1D7), + reinterpret(0x3FF56FFFEF5F54A9), reinterpret(0x3C9BBFE60EC96412), + reinterpret(0x3FF5900017E61012), reinterpret(0x3C887EC581AFEF90), + reinterpret(0x3FF5B00003C93E92), reinterpret(0xBC9F41080ABF0CC0), + reinterpret(0x3FF5D0001D4919BC), reinterpret(0xBC98812AFB254729), + reinterpret(0x3FF5EFFFE7B87A89), reinterpret(0xBC947EB780ED6904) +]); + +// @ts-ignore: decorator +@inline +export function log_lut(x: f64): f64 { + const N_MASK = (1 << LOG_TABLE_BITS) - 1; + + const + B0 = reinterpret(0xBFE0000000000000), // -0x1p-1 + B1 = reinterpret(0x3FD5555555555577), // 0x1.5555555555577p-2 + B2 = reinterpret(0xBFCFFFFFFFFFFDCB), // -0x1.ffffffffffdcbp-3 + B3 = reinterpret(0x3FC999999995DD0C), // 0x1.999999995dd0cp-3 + B4 = reinterpret(0xBFC55555556745A7), // -0x1.55555556745a7p-3 + B5 = reinterpret(0x3FC24924A344DE30), // 0x1.24924a344de3p-3 + B6 = reinterpret(0xBFBFFFFFA4423D65), // -0x1.fffffa4423d65p-4 + B7 = reinterpret(0x3FBC7184282AD6CA), // 0x1.c7184282ad6cap-4 + B8 = reinterpret(0xBFB999EB43B068FF), // -0x1.999eb43b068ffp-4 + B9 = reinterpret(0x3FB78182F7AFD085), // 0x1.78182f7afd085p-4 + B10 = reinterpret(0xBFB5521375D145CD); // -0x1.5521375d145cdp-4 + + const + A0 = reinterpret(0xBFE0000000000001), // -0x1.0000000000001p-1 + A1 = reinterpret(0x3FD555555551305B), // 0x1.555555551305bp-2 + A2 = reinterpret(0xBFCFFFFFFFEB4590), // -0x1.fffffffeb459p-3 + A3 = reinterpret(0x3FC999B324F10111), // 0x1.999b324f10111p-3 + A4 = reinterpret(0xBFC55575E506C89F); // -0x1.55575e506c89fp-3 + + const + LO: u64 = 0x3FEE000000000000, + HI: u64 = 0x3FF1090000000000; + + const + Ln2hi = reinterpret(0x3FE62E42FEFA3800), // 0x1.62e42fefa3800p-1 + Ln2lo = reinterpret(0x3D2EF35793C76730), // 0x1.ef35793c76730p-45 + Ox1p27 = reinterpret(0x41A0000000000000), // 0x1p27 + Ox1p52 = reinterpret(0x4330000000000000); // 0x1p52 + + var ix = reinterpret(x); + if (ix - LO < HI - LO) { + let r = x - 1.0; + let r2 = r * r; + let r3 = r2 * r; + let y = + r3 * (B1 + r * B2 + r2 * B3 + + r3 * (B4 + r * B5 + r2 * B6 + + r3 * (B7 + r * B8 + r2 * B9 + r3 * B10))); + // Worst-case error is around 0.507 ULP + let w = r * Ox1p27; + let rhi = r + w - w; + let rlo = r - rhi; + w = rhi * rhi * B0; // B[0] == -0.5 + let hi = r + w; + let lo = r - hi + w; + lo += B0 * rlo * (rhi + r); + return y + lo + hi; + } + var top = u32(ix >> 48); + if (top - 0x0010 >= 0x7FF0 - 0x0010) { + // x < 0x1p-1022 or inf or nan + if ((ix << 1) == 0) return -1.0 / (x * x); + if (ix == reinterpret(Infinity)) return x; // log(inf) == inf + if ((top & 0x8000) || (top & 0x7FF0) == 0x7FF0) return (x - x) / (x - x); + // x is subnormal, normalize it + ix = reinterpret(x * Ox1p52); + ix -= u64(52) << 52; + } + + // x = 2^k z; where z is in range [OFF,2*OFF) and exact. + // The range is split into N subintervals. + // The ith subinterval contains z and c is near its center. + var tmp = ix - 0x3FE6000000000000; + var i = ((tmp >> (52 - LOG_TABLE_BITS)) & N_MASK); + var k = tmp >> 52; + var iz = ix - (tmp & (u64(0xFFF) << 52)); + + var invc = load(LOG_DATA_TAB1 + (i << (1 + alignof())), 0 << alignof()); // T[i].invc; + var logc = load(LOG_DATA_TAB1 + (i << (1 + alignof())), 1 << alignof()); // T[i].logc; + var z = reinterpret(iz); + + // log(x) = log1p(z/c-1) + log(c) + k*Ln2. + // r ~= z/c - 1, |r| < 1/(2*N) + // #if __FP_FAST_FMA + // // rounding error: 0x1p-55/N + // r = __builtin_fma(z, invc, -1.0); + // #else + // rounding error: 0x1p-55/N + 0x1p-66 + const chi = load(LOG_DATA_TAB2 + (i << (1 + alignof())), 0 << alignof()); // T2[i].chi + const clo = load(LOG_DATA_TAB2 + (i << (1 + alignof())), 1 << alignof()); // T2[i].clo + var r = (z - chi - clo) * invc; + // #endif + var kd = k; + + // hi + lo = r + log(c) + k*Ln2 + var w = kd * Ln2hi + logc; + var hi = w + r; + var lo = w - hi + r + kd * Ln2lo; + + // log(x) = lo + (log1p(r) - r) + hi + var r2 = r * r; // rounding error: 0x1p-54/N^2 + // Worst case error if |y| > 0x1p-5: + // 0.5 + 4.13/N + abs-poly-error*2^57 ULP (+ 0.002 ULP without fma) + // Worst case error if |y| > 0x1p-4: + // 0.5 + 2.06/N + abs-poly-error*2^56 ULP (+ 0.001 ULP without fma). + return lo + r2 * A0 + r * r2 * (A1 + r * A2 + r2 * (A3 + r * A4)) + hi; +} + +// +// Lookup data for pow. See: https://git.musl-libc.org/cgit/musl/tree/src/math/pow.c +// + +// @ts-ignore: decorator +@inline const POW_LOG_TABLE_BITS = 7; + +/* Algorithm: + + x = 2^k z + log(x) = k ln2 + log(c) + log(z/c) + log(z/c) = poly(z/c - 1) + +where z is in [0x1.69555p-1; 0x1.69555p0] which is split into N subintervals +and z falls into the ith one, then table entries are computed as + + tab[i].invc = 1/c + tab[i].logc = round(0x1p43*log(c))/0x1p43 + tab[i].logctail = (double)(log(c) - logc) + +where c is chosen near the center of the subinterval such that 1/c has only a +few precision bits so z/c - 1 is exactly representible as double: + + 1/c = center < 1 ? round(N/center)/N : round(2*N/center)/N/2 + +Note: |z/c - 1| < 1/N for the chosen c, |log(c) - logc - logctail| < 0x1p-97, +the last few bits of logc are rounded away so k*ln2hi + logc has no rounding +error and the interval for z is selected such that near x == 1, where log(x) +is tiny, large cancellation error is avoided in logc + poly(z/c - 1). */ + +// @ts-ignore: decorator +@lazy @inline const POW_LOG_DATA_TAB = memory.data([ + // invc ,pad, logc , logctail + reinterpret(0x3FF6A00000000000), 0, reinterpret(0xBFD62C82F2B9C800), reinterpret(0x3CFAB42428375680), + reinterpret(0x3FF6800000000000), 0, reinterpret(0xBFD5D1BDBF580800), reinterpret(0xBD1CA508D8E0F720), + reinterpret(0x3FF6600000000000), 0, reinterpret(0xBFD5767717455800), reinterpret(0xBD2362A4D5B6506D), + reinterpret(0x3FF6400000000000), 0, reinterpret(0xBFD51AAD872DF800), reinterpret(0xBCE684E49EB067D5), + reinterpret(0x3FF6200000000000), 0, reinterpret(0xBFD4BE5F95777800), reinterpret(0xBD041B6993293EE0), + reinterpret(0x3FF6000000000000), 0, reinterpret(0xBFD4618BC21C6000), reinterpret(0x3D13D82F484C84CC), + reinterpret(0x3FF5E00000000000), 0, reinterpret(0xBFD404308686A800), reinterpret(0x3CDC42F3ED820B3A), + reinterpret(0x3FF5C00000000000), 0, reinterpret(0xBFD3A64C55694800), reinterpret(0x3D20B1C686519460), + reinterpret(0x3FF5A00000000000), 0, reinterpret(0xBFD347DD9A988000), reinterpret(0x3D25594DD4C58092), + reinterpret(0x3FF5800000000000), 0, reinterpret(0xBFD2E8E2BAE12000), reinterpret(0x3D267B1E99B72BD8), + reinterpret(0x3FF5600000000000), 0, reinterpret(0xBFD2895A13DE8800), reinterpret(0x3D15CA14B6CFB03F), + reinterpret(0x3FF5600000000000), 0, reinterpret(0xBFD2895A13DE8800), reinterpret(0x3D15CA14B6CFB03F), + reinterpret(0x3FF5400000000000), 0, reinterpret(0xBFD22941FBCF7800), reinterpret(0xBD165A242853DA76), + reinterpret(0x3FF5200000000000), 0, reinterpret(0xBFD1C898C1699800), reinterpret(0xBD1FAFBC68E75404), + reinterpret(0x3FF5000000000000), 0, reinterpret(0xBFD1675CABABA800), reinterpret(0x3D1F1FC63382A8F0), + reinterpret(0x3FF4E00000000000), 0, reinterpret(0xBFD1058BF9AE4800), reinterpret(0xBD26A8C4FD055A66), + reinterpret(0x3FF4C00000000000), 0, reinterpret(0xBFD0A324E2739000), reinterpret(0xBD0C6BEE7EF4030E), + reinterpret(0x3FF4A00000000000), 0, reinterpret(0xBFD0402594B4D000), reinterpret(0xBCF036B89EF42D7F), + reinterpret(0x3FF4A00000000000), 0, reinterpret(0xBFD0402594B4D000), reinterpret(0xBCF036B89EF42D7F), + reinterpret(0x3FF4800000000000), 0, reinterpret(0xBFCFB9186D5E4000), reinterpret(0x3D0D572AAB993C87), + reinterpret(0x3FF4600000000000), 0, reinterpret(0xBFCEF0ADCBDC6000), reinterpret(0x3D2B26B79C86AF24), + reinterpret(0x3FF4400000000000), 0, reinterpret(0xBFCE27076E2AF000), reinterpret(0xBD172F4F543FFF10), + reinterpret(0x3FF4200000000000), 0, reinterpret(0xBFCD5C216B4FC000), reinterpret(0x3D21BA91BBCA681B), + reinterpret(0x3FF4000000000000), 0, reinterpret(0xBFCC8FF7C79AA000), reinterpret(0x3D27794F689F8434), + reinterpret(0x3FF4000000000000), 0, reinterpret(0xBFCC8FF7C79AA000), reinterpret(0x3D27794F689F8434), + reinterpret(0x3FF3E00000000000), 0, reinterpret(0xBFCBC286742D9000), reinterpret(0x3D194EB0318BB78F), + reinterpret(0x3FF3C00000000000), 0, reinterpret(0xBFCAF3C94E80C000), reinterpret(0x3CBA4E633FCD9066), + reinterpret(0x3FF3A00000000000), 0, reinterpret(0xBFCA23BC1FE2B000), reinterpret(0xBD258C64DC46C1EA), + reinterpret(0x3FF3A00000000000), 0, reinterpret(0xBFCA23BC1FE2B000), reinterpret(0xBD258C64DC46C1EA), + reinterpret(0x3FF3800000000000), 0, reinterpret(0xBFC9525A9CF45000), reinterpret(0xBD2AD1D904C1D4E3), + reinterpret(0x3FF3600000000000), 0, reinterpret(0xBFC87FA06520D000), reinterpret(0x3D2BBDBF7FDBFA09), + reinterpret(0x3FF3400000000000), 0, reinterpret(0xBFC7AB890210E000), reinterpret(0x3D2BDB9072534A58), + reinterpret(0x3FF3400000000000), 0, reinterpret(0xBFC7AB890210E000), reinterpret(0x3D2BDB9072534A58), + reinterpret(0x3FF3200000000000), 0, reinterpret(0xBFC6D60FE719D000), reinterpret(0xBD10E46AA3B2E266), + reinterpret(0x3FF3000000000000), 0, reinterpret(0xBFC5FF3070A79000), reinterpret(0xBD1E9E439F105039), + reinterpret(0x3FF3000000000000), 0, reinterpret(0xBFC5FF3070A79000), reinterpret(0xBD1E9E439F105039), + reinterpret(0x3FF2E00000000000), 0, reinterpret(0xBFC526E5E3A1B000), reinterpret(0xBD20DE8B90075B8F), + reinterpret(0x3FF2C00000000000), 0, reinterpret(0xBFC44D2B6CCB8000), reinterpret(0x3D170CC16135783C), + reinterpret(0x3FF2C00000000000), 0, reinterpret(0xBFC44D2B6CCB8000), reinterpret(0x3D170CC16135783C), + reinterpret(0x3FF2A00000000000), 0, reinterpret(0xBFC371FC201E9000), reinterpret(0x3CF178864D27543A), + reinterpret(0x3FF2800000000000), 0, reinterpret(0xBFC29552F81FF000), reinterpret(0xBD248D301771C408), + reinterpret(0x3FF2600000000000), 0, reinterpret(0xBFC1B72AD52F6000), reinterpret(0xBD2E80A41811A396), + reinterpret(0x3FF2600000000000), 0, reinterpret(0xBFC1B72AD52F6000), reinterpret(0xBD2E80A41811A396), + reinterpret(0x3FF2400000000000), 0, reinterpret(0xBFC0D77E7CD09000), reinterpret(0x3D0A699688E85BF4), + reinterpret(0x3FF2400000000000), 0, reinterpret(0xBFC0D77E7CD09000), reinterpret(0x3D0A699688E85BF4), + reinterpret(0x3FF2200000000000), 0, reinterpret(0xBFBFEC9131DBE000), reinterpret(0xBD2575545CA333F2), + reinterpret(0x3FF2000000000000), 0, reinterpret(0xBFBE27076E2B0000), reinterpret(0x3D2A342C2AF0003C), + reinterpret(0x3FF2000000000000), 0, reinterpret(0xBFBE27076E2B0000), reinterpret(0x3D2A342C2AF0003C), + reinterpret(0x3FF1E00000000000), 0, reinterpret(0xBFBC5E548F5BC000), reinterpret(0xBD1D0C57585FBE06), + reinterpret(0x3FF1C00000000000), 0, reinterpret(0xBFBA926D3A4AE000), reinterpret(0x3D253935E85BAAC8), + reinterpret(0x3FF1C00000000000), 0, reinterpret(0xBFBA926D3A4AE000), reinterpret(0x3D253935E85BAAC8), + reinterpret(0x3FF1A00000000000), 0, reinterpret(0xBFB8C345D631A000), reinterpret(0x3D137C294D2F5668), + reinterpret(0x3FF1A00000000000), 0, reinterpret(0xBFB8C345D631A000), reinterpret(0x3D137C294D2F5668), + reinterpret(0x3FF1800000000000), 0, reinterpret(0xBFB6F0D28AE56000), reinterpret(0xBD269737C93373DA), + reinterpret(0x3FF1600000000000), 0, reinterpret(0xBFB51B073F062000), reinterpret(0x3D1F025B61C65E57), + reinterpret(0x3FF1600000000000), 0, reinterpret(0xBFB51B073F062000), reinterpret(0x3D1F025B61C65E57), + reinterpret(0x3FF1400000000000), 0, reinterpret(0xBFB341D7961BE000), reinterpret(0x3D2C5EDACCF913DF), + reinterpret(0x3FF1400000000000), 0, reinterpret(0xBFB341D7961BE000), reinterpret(0x3D2C5EDACCF913DF), + reinterpret(0x3FF1200000000000), 0, reinterpret(0xBFB16536EEA38000), reinterpret(0x3D147C5E768FA309), + reinterpret(0x3FF1000000000000), 0, reinterpret(0xBFAF0A30C0118000), reinterpret(0x3D2D599E83368E91), + reinterpret(0x3FF1000000000000), 0, reinterpret(0xBFAF0A30C0118000), reinterpret(0x3D2D599E83368E91), + reinterpret(0x3FF0E00000000000), 0, reinterpret(0xBFAB42DD71198000), reinterpret(0x3D1C827AE5D6704C), + reinterpret(0x3FF0E00000000000), 0, reinterpret(0xBFAB42DD71198000), reinterpret(0x3D1C827AE5D6704C), + reinterpret(0x3FF0C00000000000), 0, reinterpret(0xBFA77458F632C000), reinterpret(0xBD2CFC4634F2A1EE), + reinterpret(0x3FF0C00000000000), 0, reinterpret(0xBFA77458F632C000), reinterpret(0xBD2CFC4634F2A1EE), + reinterpret(0x3FF0A00000000000), 0, reinterpret(0xBFA39E87B9FEC000), reinterpret(0x3CF502B7F526FEAA), + reinterpret(0x3FF0A00000000000), 0, reinterpret(0xBFA39E87B9FEC000), reinterpret(0x3CF502B7F526FEAA), + reinterpret(0x3FF0800000000000), 0, reinterpret(0xBF9F829B0E780000), reinterpret(0xBD2980267C7E09E4), + reinterpret(0x3FF0800000000000), 0, reinterpret(0xBF9F829B0E780000), reinterpret(0xBD2980267C7E09E4), + reinterpret(0x3FF0600000000000), 0, reinterpret(0xBF97B91B07D58000), reinterpret(0xBD288D5493FAA639), + reinterpret(0x3FF0400000000000), 0, reinterpret(0xBF8FC0A8B0FC0000), reinterpret(0xBCDF1E7CF6D3A69C), + reinterpret(0x3FF0400000000000), 0, reinterpret(0xBF8FC0A8B0FC0000), reinterpret(0xBCDF1E7CF6D3A69C), + reinterpret(0x3FF0200000000000), 0, reinterpret(0xBF7FE02A6B100000), reinterpret(0xBD19E23F0DDA40E4), + reinterpret(0x3FF0200000000000), 0, reinterpret(0xBF7FE02A6B100000), reinterpret(0xBD19E23F0DDA40E4), + reinterpret(0x3FF0000000000000), 0, 0, 0, + reinterpret(0x3FF0000000000000), 0, 0, 0, + reinterpret(0x3FEFC00000000000), 0, reinterpret(0x3F80101575890000), reinterpret(0xBD10C76B999D2BE8), + reinterpret(0x3FEF800000000000), 0, reinterpret(0x3F90205658938000), reinterpret(0xBD23DC5B06E2F7D2), + reinterpret(0x3FEF400000000000), 0, reinterpret(0x3F98492528C90000), reinterpret(0xBD2AA0BA325A0C34), + reinterpret(0x3FEF000000000000), 0, reinterpret(0x3FA0415D89E74000), reinterpret(0x3D0111C05CF1D753), + reinterpret(0x3FEEC00000000000), 0, reinterpret(0x3FA466AED42E0000), reinterpret(0xBD2C167375BDFD28), + reinterpret(0x3FEE800000000000), 0, reinterpret(0x3FA894AA149FC000), reinterpret(0xBD197995D05A267D), + reinterpret(0x3FEE400000000000), 0, reinterpret(0x3FACCB73CDDDC000), reinterpret(0xBD1A68F247D82807), + reinterpret(0x3FEE200000000000), 0, reinterpret(0x3FAEEA31C006C000), reinterpret(0xBD0E113E4FC93B7B), + reinterpret(0x3FEDE00000000000), 0, reinterpret(0x3FB1973BD1466000), reinterpret(0xBD25325D560D9E9B), + reinterpret(0x3FEDA00000000000), 0, reinterpret(0x3FB3BDF5A7D1E000), reinterpret(0x3D2CC85EA5DB4ED7), + reinterpret(0x3FED600000000000), 0, reinterpret(0x3FB5E95A4D97A000), reinterpret(0xBD2C69063C5D1D1E), + reinterpret(0x3FED400000000000), 0, reinterpret(0x3FB700D30AEAC000), reinterpret(0x3CEC1E8DA99DED32), + reinterpret(0x3FED000000000000), 0, reinterpret(0x3FB9335E5D594000), reinterpret(0x3D23115C3ABD47DA), + reinterpret(0x3FECC00000000000), 0, reinterpret(0x3FBB6AC88DAD6000), reinterpret(0xBD1390802BF768E5), + reinterpret(0x3FECA00000000000), 0, reinterpret(0x3FBC885801BC4000), reinterpret(0x3D2646D1C65AACD3), + reinterpret(0x3FEC600000000000), 0, reinterpret(0x3FBEC739830A2000), reinterpret(0xBD2DC068AFE645E0), + reinterpret(0x3FEC400000000000), 0, reinterpret(0x3FBFE89139DBE000), reinterpret(0xBD2534D64FA10AFD), + reinterpret(0x3FEC000000000000), 0, reinterpret(0x3FC1178E8227E000), reinterpret(0x3D21EF78CE2D07F2), + reinterpret(0x3FEBE00000000000), 0, reinterpret(0x3FC1AA2B7E23F000), reinterpret(0x3D2CA78E44389934), + reinterpret(0x3FEBA00000000000), 0, reinterpret(0x3FC2D1610C868000), reinterpret(0x3D039D6CCB81B4A1), + reinterpret(0x3FEB800000000000), 0, reinterpret(0x3FC365FCB0159000), reinterpret(0x3CC62FA8234B7289), + reinterpret(0x3FEB400000000000), 0, reinterpret(0x3FC4913D8333B000), reinterpret(0x3D25837954FDB678), + reinterpret(0x3FEB200000000000), 0, reinterpret(0x3FC527E5E4A1B000), reinterpret(0x3D2633E8E5697DC7), + reinterpret(0x3FEAE00000000000), 0, reinterpret(0x3FC6574EBE8C1000), reinterpret(0x3D19CF8B2C3C2E78), + reinterpret(0x3FEAC00000000000), 0, reinterpret(0x3FC6F0128B757000), reinterpret(0xBD25118DE59C21E1), + reinterpret(0x3FEAA00000000000), 0, reinterpret(0x3FC7898D85445000), reinterpret(0xBD1C661070914305), + reinterpret(0x3FEA600000000000), 0, reinterpret(0x3FC8BEAFEB390000), reinterpret(0xBD073D54AAE92CD1), + reinterpret(0x3FEA400000000000), 0, reinterpret(0x3FC95A5ADCF70000), reinterpret(0x3D07F22858A0FF6F), + reinterpret(0x3FEA000000000000), 0, reinterpret(0x3FCA93ED3C8AE000), reinterpret(0xBD28724350562169), + reinterpret(0x3FE9E00000000000), 0, reinterpret(0x3FCB31D8575BD000), reinterpret(0xBD0C358D4EACE1AA), + reinterpret(0x3FE9C00000000000), 0, reinterpret(0x3FCBD087383BE000), reinterpret(0xBD2D4BC4595412B6), + reinterpret(0x3FE9A00000000000), 0, reinterpret(0x3FCC6FFBC6F01000), reinterpret(0xBCF1EC72C5962BD2), + reinterpret(0x3FE9600000000000), 0, reinterpret(0x3FCDB13DB0D49000), reinterpret(0xBD2AFF2AF715B035), + reinterpret(0x3FE9400000000000), 0, reinterpret(0x3FCE530EFFE71000), reinterpret(0x3CC212276041F430), + reinterpret(0x3FE9200000000000), 0, reinterpret(0x3FCEF5ADE4DD0000), reinterpret(0xBCCA211565BB8E11), + reinterpret(0x3FE9000000000000), 0, reinterpret(0x3FCF991C6CB3B000), reinterpret(0x3D1BCBECCA0CDF30), + reinterpret(0x3FE8C00000000000), 0, reinterpret(0x3FD07138604D5800), reinterpret(0x3CF89CDB16ED4E91), + reinterpret(0x3FE8A00000000000), 0, reinterpret(0x3FD0C42D67616000), reinterpret(0x3D27188B163CEAE9), + reinterpret(0x3FE8800000000000), 0, reinterpret(0x3FD1178E8227E800), reinterpret(0xBD2C210E63A5F01C), + reinterpret(0x3FE8600000000000), 0, reinterpret(0x3FD16B5CCBACF800), reinterpret(0x3D2B9ACDF7A51681), + reinterpret(0x3FE8400000000000), 0, reinterpret(0x3FD1BF99635A6800), reinterpret(0x3D2CA6ED5147BDB7), + reinterpret(0x3FE8200000000000), 0, reinterpret(0x3FD214456D0EB800), reinterpret(0x3D0A87DEBA46BAEA), + reinterpret(0x3FE7E00000000000), 0, reinterpret(0x3FD2BEF07CDC9000), reinterpret(0x3D2A9CFA4A5004F4), + reinterpret(0x3FE7C00000000000), 0, reinterpret(0x3FD314F1E1D36000), reinterpret(0xBD28E27AD3213CB8), + reinterpret(0x3FE7A00000000000), 0, reinterpret(0x3FD36B6776BE1000), reinterpret(0x3D116ECDB0F177C8), + reinterpret(0x3FE7800000000000), 0, reinterpret(0x3FD3C25277333000), reinterpret(0x3D183B54B606BD5C), + reinterpret(0x3FE7600000000000), 0, reinterpret(0x3FD419B423D5E800), reinterpret(0x3D08E436EC90E09D), + reinterpret(0x3FE7400000000000), 0, reinterpret(0x3FD4718DC271C800), reinterpret(0xBD2F27CE0967D675), + reinterpret(0x3FE7200000000000), 0, reinterpret(0x3FD4C9E09E173000), reinterpret(0xBD2E20891B0AD8A4), + reinterpret(0x3FE7000000000000), 0, reinterpret(0x3FD522AE0738A000), reinterpret(0x3D2EBE708164C759), + reinterpret(0x3FE6E00000000000), 0, reinterpret(0x3FD57BF753C8D000), reinterpret(0x3D1FADEDEE5D40EF), + reinterpret(0x3FE6C00000000000), 0, reinterpret(0x3FD5D5BDDF596000), reinterpret(0xBD0A0B2A08A465DC) +]); + +// Returns 0 if not int, 1 if odd int, 2 if even int. The argument is +// the bit representation of a non-zero finite floating-point value. +// @ts-ignore: decorator +@inline +function checkint(iy: u64): i32 { + var e = iy >> 52 & 0x7FF; + if (e < 0x3FF ) return 0; + if (e > 0x3FF + 52) return 2; + e = u64(1) << (0x3FF + 52 - e); + if (iy & (e - 1)) return 0; + if (iy & e ) return 1; + return 2; +} + +// @ts-ignore: decorator +@inline +function xflow(sign: u32, y: f64): f64 { + return select(-y, y, sign) * y; +} + +// @ts-ignore: decorator +@inline +function uflow(sign: u32): f64 { + return xflow(sign, reinterpret(0x1000000000000000)); // 0x1p-767 +} + +// @ts-ignore: decorator +@inline +function oflow(sign: u32): f64 { + return xflow(sign, reinterpret(0x7000000000000000)); // 0x1p769 +} + +// Returns 1 if input is the bit representation of 0, infinity or nan. +// @ts-ignore: decorator +@inline +function zeroinfnan(u: u64): bool { + return (u << 1) - 1 >= 0xFFE0000000000000 - 1; +} + +// @ts-ignore: decorator +@lazy var log_tail: f64 = 0; + +// Compute y+TAIL = log(x) where the rounded result is y and TAIL has about +// additional 15 bits precision. IX is the bit representation of x, but +// normalized in the subnormal range using the sign bit for the exponent. +// @ts-ignore: decorator +@inline +function log_inline(ix: u64): f64 { + const N = 1 << POW_LOG_TABLE_BITS; + const N_MASK = N - 1; + + const + Ln2hi = reinterpret(0x3FE62E42FEFA3800), + Ln2lo = reinterpret(0x3D2EF35793C76730); + + const + A0 = reinterpret(0xBFE0000000000000), + A1 = reinterpret(0xBFE5555555555560), + A2 = reinterpret(0x3FE0000000000006), + A3 = reinterpret(0x3FE999999959554E), + A4 = reinterpret(0xBFE555555529A47A), + A5 = reinterpret(0xBFF2495B9B4845E9), + A6 = reinterpret(0x3FF0002B8B263FC3); + + // x = 2^k z; where z is in range [OFF,2*OFF) and exact. + // The range is split into N subintervals. + // The ith subinterval contains z and c is near its center. + var tmp = ix - 0x3fE6955500000000; + var i = ((tmp >> (52 - POW_LOG_TABLE_BITS)) & N_MASK); + var k = tmp >> 52; + var iz = ix - (tmp & u64(0xFFF) << 52); + var z = reinterpret(iz); + var kd = k; + + // log(x) = k*Ln2 + log(c) + log1p(z/c-1). + var invc = load(POW_LOG_DATA_TAB + (i << (2 + alignof())), 0 << alignof()); // tab[i].invc + var logc = load(POW_LOG_DATA_TAB + (i << (2 + alignof())), 2 << alignof()); // tab[i].logc + var logctail = load(POW_LOG_DATA_TAB + (i << (2 + alignof())), 3 << alignof()); // tab[i].logctail + + // Note: 1/c is j/N or j/N/2 where j is an integer in [N,2N) and + // |z/c - 1| < 1/N, so r = z/c - 1 is exactly representible. + // Split z such that rhi, rlo and rhi*rhi are exact and |rlo| <= |r|. + var zhi = reinterpret((iz + u64(0x80000000)) & 0xFFFFFFFF00000000); + var zlo = z - zhi; + var rhi = zhi * invc - 1.0; + var rlo = zlo * invc; + var r = rhi + rlo; + + // k * Ln2 + log(c) + r. + var t1 = kd * Ln2hi + logc; + var t2 = t1 + r; + var lo1 = kd * Ln2lo + logctail; + var lo2 = t1 - t2 + r; + + // Evaluation is optimized assuming superscalar pipelined execution. + var ar = A0 * r; // A[0] = -0.5 + var ar2 = r * ar; + var ar3 = r * ar2; + // k * Ln2 + log(c) + r + A[0] * r * r. + var arhi = A0 * rhi; + var arhi2 = rhi * arhi; + var hi = t2 + arhi2; + var lo3 = rlo * (ar + arhi); + var lo4 = t2 - hi + arhi2; + + // p = log1p(r) - r - A[0] * r * r. + var p = ar3 * (A1 + r * A2 + ar2 * (A3 + r * A4 + ar2 * (A5 + r * A6))); + var lo = lo1 + lo2 + lo3 + lo4 + p; + var y = hi + lo; + log_tail = hi - y + lo; + + return y; +} + +// @ts-ignore: decorator +@inline const SIGN_BIAS = 0x800 << EXP_TABLE_BITS; + +// Computes sign*exp(x+xtail) where |xtail| < 2^-8/N and |xtail| <= |x|. +// The sign_bias argument is SIGN_BIAS or 0 and sets the sign to -1 or 1. +// @ts-ignore: decorator +@inline +function exp_inline(x: f64, xtail: f64, sign_bias: u32): f64 { + const N = 1 << EXP_TABLE_BITS; + const N_MASK = N - 1; + + const + InvLn2N = reinterpret(0x3FF71547652B82FE) * N, // 0x1.71547652b82fep0 + NegLn2hiN = reinterpret(0xBF762E42FEFA0000), // -0x1.62e42fefa0000p-8 + NegLn2loN = reinterpret(0xBD0CF79ABC9E3B3A), // -0x1.cf79abc9e3b3ap-47 + shift = reinterpret(0x4338000000000000); // 0x1.8p52 + + const + C2 = reinterpret(0x3FDFFFFFFFFFFDBD), // __exp_data.poly[0] (0x1.ffffffffffdbdp-2) + C3 = reinterpret(0x3FC555555555543C), // __exp_data.poly[1] (0x1.555555555543cp-3) + C4 = reinterpret(0x3FA55555CF172B91), // __exp_data.poly[2] (0x1.55555cf172b91p-5) + C5 = reinterpret(0x3F81111167A4D017); // __exp_data.poly[3] (0x1.1111167a4d017p-7) + + var abstop: u32; + var ki: u64, top: u64, sbits: u64; + var idx: usize; + // double_t for better performance on targets with FLT_EVAL_METHOD==2. + var kd: f64, z: f64, r: f64, r2: f64, scale: f64, tail: f64, tmp: f64; + + var ux = reinterpret(x); + abstop = (ux >> 52) & 0x7FF; + if (abstop - 0x3C9 >= 0x03F) { + if (abstop - 0x3C9 >= 0x80000000) { + // Avoid spurious underflow for tiny x. + // Note: 0 is common input. + return select(-1.0, 1.0, sign_bias); + } + if (abstop >= 0x409) { // top12(1024.0) + // Note: inf and nan are already handled. + return ux >> 63 ? uflow(sign_bias) : oflow(sign_bias); + } + // Large x is special cased below. + abstop = 0; + } + + // exp(x) = 2^(k/N) * exp(r), with exp(r) in [2^(-1/2N),2^(1/2N)]. + // x = ln2/N*k + r, with int k and r in [-ln2/2N, ln2/2N]. + z = InvLn2N * x; + + // #if TOINT_INTRINSICS + // kd = roundtoint(z); + // ki = converttoint(z); + // #elif EXP_USE_TOINT_NARROW + // // z - kd is in [-0.5-2^-16, 0.5] in all rounding modes. + // kd = eval_as_double(z + shift); + // ki = asuint64(kd) >> 16; + // kd = (double_t)(int32_t)ki; + // #else + // z - kd is in [-1, 1] in non-nearest rounding modes + kd = z + shift; + ki = reinterpret(kd); + kd -= shift; + // #endif + r = x + kd * NegLn2hiN + kd * NegLn2loN; + // The code assumes 2^-200 < |xtail| < 2^-8/N + r += xtail; + // 2^(k/N) ~= scale * (1 + tail) + idx = ((ki & N_MASK) << 1); + top = (ki + sign_bias) << (52 - EXP_TABLE_BITS); + + tail = reinterpret(load(EXP_DATA_TAB + (idx << alignof()))); + // This is only a valid scale when -1023*N < k < 1024*N + sbits = load(EXP_DATA_TAB + (idx << alignof()), 1 << alignof()) + top; + // exp(x) = 2^(k/N) * exp(r) ~= scale + scale * (tail + exp(r) - 1). + // Evaluation is optimized assuming superscalar pipelined execution. + r2 = r * r; + // Without fma the worst case error is 0.25/N ulp larger. + // Worst case error is less than 0.5+1.11/N+(abs poly error * 2^53) ulp + tmp = tail + r + r2 * (C2 + r * C3) + r2 * r2 * (C4 + r * C5); + if (abstop == 0) return specialcase(tmp, sbits, ki); + scale = reinterpret(sbits); + // Note: tmp == 0 or |tmp| > 2^-200 and scale > 2^-739, so there + // is no spurious underflow here even without fma. + return scale + scale * tmp; +} + +// @ts-ignore: decorator +@inline +export function pow_lut(x: f64, y: f64): f64 { + const Ox1p52 = reinterpret(0x4330000000000000); // 0x1p52 + + var sign_bias: u32 = 0; + var ix = reinterpret(x); + var iy = reinterpret(y); + var topx = ix >> 52; + var topy = iy >> 52; + + if (topx - 0x001 >= 0x7FF - 0x001 || (topy & 0x7FF) - 0x3BE >= 0x43e - 0x3BE) { + // Note: if |y| > 1075 * ln2 * 2^53 ~= 0x1.749p62 then pow(x,y) = inf/0 + // and if |y| < 2^-54 / 1075 ~= 0x1.e7b6p-65 then pow(x,y) = +-1. + // Special cases: (x < 0x1p-126 or inf or nan) or + // (|y| < 0x1p-65 or |y| >= 0x1p63 or nan). + if (zeroinfnan(iy)) { + if ((iy << 1) == 0) return 1.0; + if (ix == 0x3FF0000000000000) return NaN; // original: 1.0 + if ((ix << 1) > 0xFFE0000000000000 || (iy << 1) > 0xFFE0000000000000) return x + y; + if ((ix << 1) == 0x7FE0000000000000) return NaN; // original: 1.0 + if (((ix << 1) < 0x7FE0000000000000) == !(iy >> 63)) return 0; // |x|<1 && y==inf or |x|>1 && y==-inf. + return y * y; + } + if (zeroinfnan(ix)) { + let x2 = x * x; + if (i32(ix >> 63) && checkint(iy) == 1) x2 = -x2; + return iy >> 63 ? 1 / x2 : x2; + } + // Here x and y are non-zero finite + if (ix >> 63) { + // Finite x < 0 + let yint = checkint(iy); + if (yint == 0) return (x - x) / (x - x); + if (yint == 1) sign_bias = SIGN_BIAS; + ix &= 0x7FFFFFFFFFFFFFFF; + topx &= 0x7FF; + } + if ((topy & 0x7FF) - 0x3BE >= 0x43E - 0x3BE) { + // Note: sign_bias == 0 here because y is not odd. + if (ix == 0x3FF0000000000000) return 1; + if ((topy & 0x7FF) < 0x3BE) return 1; // |y| < 2^-65, x^y ~= 1 + y*log(x). + return (ix > 0x3FF0000000000000) == (topy < 0x800) ? Infinity : 0; + } + if (topx == 0) { + // Normalize subnormal x so exponent becomes negative. + ix = reinterpret(x * Ox1p52); + ix &= 0x7FFFFFFFFFFFFFFF; + ix -= u64(52) << 52; + } + } + + var hi = log_inline(ix); + var lo = log_tail; + var ehi: f64, elo: f64; + // #if __FP_FAST_FMA + // ehi = y * hi; + // elo = y * lo + __builtin_fma(y, hi, -ehi); + // #else + var yhi = reinterpret(iy & 0xFFFFFFFFF8000000); + var ylo = y - yhi; + var lhi = reinterpret(reinterpret(hi) & 0xFFFFFFFFF8000000); + var llo = hi - lhi + lo; + ehi = yhi * lhi; + elo = ylo * lhi + y * llo; // |elo| < |ehi| * 2^-25. + // #endif + return exp_inline(ehi, elo, sign_bias); +} +`,"util/memory":`export function memcpy(dest: usize, src: usize, n: usize): void { // see: musl/src/string/memcpy.c + var w: u32, x: u32; + + // copy 1 byte each until src is aligned to 4 bytes + while (n && (src & 3)) { + store(dest++, load(src++)); + n--; + } + + // if dst is aligned to 4 bytes as well, copy 4 bytes each + if ((dest & 3) == 0) { + while (n >= 16) { + store(dest , load(src )); + store(dest + 4, load(src + 4)); + store(dest + 8, load(src + 8)); + store(dest + 12, load(src + 12)); + src += 16; dest += 16; n -= 16; + } + if (n & 8) { + store(dest , load(src )); + store(dest + 4, load(src + 4)); + dest += 8; src += 8; + } + if (n & 4) { + store(dest, load(src)); + dest += 4; src += 4; + } + if (n & 2) { // drop to 2 bytes each + store(dest, load(src)); + dest += 2; src += 2; + } + if (n & 1) { // drop to 1 byte + store(dest++, load(src++)); + } + return; + } + + // if dst is not aligned to 4 bytes, use alternating shifts to copy 4 bytes each + // doing shifts if faster when copying enough bytes (here: 32 or more) + if (n >= 32) { + switch (dest & 3) { + // known to be != 0 + case 1: { + w = load(src); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + n -= 3; + while (n >= 17) { + x = load(src + 1); + store(dest, w >> 24 | x << 8); + w = load(src + 5); + store(dest + 4, x >> 24 | w << 8); + x = load(src + 9); + store(dest + 8, w >> 24 | x << 8); + w = load(src + 13); + store(dest + 12, x >> 24 | w << 8); + src += 16; dest += 16; n -= 16; + } + break; + } + case 2: { + w = load(src); + store(dest++, load(src++)); + store(dest++, load(src++)); + n -= 2; + while (n >= 18) { + x = load(src + 2); + store(dest, w >> 16 | x << 16); + w = load(src + 6); + store(dest + 4, x >> 16 | w << 16); + x = load(src + 10); + store(dest + 8, w >> 16 | x << 16); + w = load(src + 14); + store(dest + 12, x >> 16 | w << 16); + src += 16; dest += 16; n -= 16; + } + break; + } + case 3: { + w = load(src); + store(dest++, load(src++)); + n -= 1; + while (n >= 19) { + x = load(src + 3); + store(dest, w >> 8 | x << 24); + w = load(src + 7); + store(dest + 4, x >> 8 | w << 24); + x = load(src + 11); + store(dest + 8, w >> 8 | x << 24); + w = load(src + 15); + store(dest + 12, x >> 8 | w << 24); + src += 16; dest += 16; n -= 16; + } + break; + } + } + } + + // copy remaining bytes one by one + if (n & 16) { + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + } + if (n & 8) { + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + } + if (n & 4) { + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + store(dest++, load(src++)); + } + if (n & 2) { + store(dest++, load(src++)); + store(dest++, load(src++)); + } + if (n & 1) { + store(dest++, load(src++)); + } +} + +// @ts-ignore: decorator +@inline +export function memmove(dest: usize, src: usize, n: usize): void { // see: musl/src/string/memmove.c + if (dest == src) return; + if (ASC_SHRINK_LEVEL < 1) { + if (src - dest - n <= -(n << 1)) { + memcpy(dest, src, n); + return; + } + } + if (dest < src) { + if (ASC_SHRINK_LEVEL < 2) { + if ((src & 7) == (dest & 7)) { + while (dest & 7) { + if (!n) return; + --n; + store(dest++, load(src++)); + } + while (n >= 8) { + store(dest, load(src)); + n -= 8; + dest += 8; + src += 8; + } + } + } + while (n) { + store(dest++, load(src++)); + --n; + } + } else { + if (ASC_SHRINK_LEVEL < 2) { + if ((src & 7) == (dest & 7)) { + while ((dest + n) & 7) { + if (!n) return; + store(dest + --n, load(src + n)); + } + while (n >= 8) { + n -= 8; + store(dest + n, load(src + n)); + } + } + } + while (n) { + store(dest + --n, load(src + n)); + } + } +} + +// @ts-ignore: decorator +@inline +export function memset(dest: usize, c: u8, n: usize): void { // see: musl/src/string/memset + if (ASC_SHRINK_LEVEL > 1) { + while (n) { + store(dest++, c); + --n; + } + } else { + // fill head and tail with minimal branching + if (!n) return; + let dend = dest + n; + store(dest, c); + store(dend - 1, c); + if (n <= 2) return; + store(dest, c, 1); + store(dest, c, 2); + store(dend - 2, c); + store(dend - 3, c); + if (n <= 6) return; + store(dest, c, 3); + store(dend - 4, c); + if (n <= 8) return; + + // advance pointer to align it at 4-byte boundary + let k: usize = -dest & 3; + dest += k; + n -= k; + n &= -4; + + let c32: u32 = -1 / 255 * c; + + // fill head/tail up to 28 bytes each in preparation + dend = dest + n; + store(dest, c32); + store(dend - 4, c32); + if (n <= 8) return; + store(dest, c32, 4); + store(dest, c32, 8); + store(dend - 12, c32); + store(dend - 8, c32); + if (n <= 24) return; + store(dest, c32, 12); + store(dest, c32, 16); + store(dest, c32, 20); + store(dest, c32, 24); + store(dend - 28, c32); + store(dend - 24, c32); + store(dend - 20, c32); + store(dend - 16, c32); + + // align to a multiple of 8 + k = 24 + (dest & 4); + dest += k; + n -= k; + + // copy 32 bytes each + let c64: u64 = c32 | (c32 << 32); + while (n >= 32) { + store(dest, c64); + store(dest, c64, 8); + store(dest, c64, 16); + store(dest, c64, 24); + n -= 32; + dest += 32; + } + } +} + +// @ts-ignore: decorator +@inline +export function memcmp(vl: usize, vr: usize, n: usize): i32 { + if (vl == vr) return 0; + if (ASC_SHRINK_LEVEL < 2) { + if ((vl & 7) == (vr & 7)) { + while (vl & 7) { + if (!n) return 0; + let a = load(vl); + let b = load(vr); + if (a != b) return a - b; + n--; vl++; vr++; + } + while (n >= 8) { + if (load(vl) != load(vr)) break; + vl += 8; + vr += 8; + n -= 8; + } + } + } + while (n--) { + let a = load(vl); + let b = load(vr); + if (a != b) return a - b; + vl++; vr++; + } + return 0; +} +`,"util/number":`/// + +import { idof } from "../builtins"; +import { CharCode } from "./string"; + +// @ts-ignore: decorator +@inline +export const MAX_DOUBLE_LENGTH = 28; + +// @ts-ignore: decorator +@lazy @inline const POWERS10 = memory.data([ + 1, + 10, + 100, + 1000, + 10000, + 100000, + 1000000, + 10000000, + 100000000, + 1000000000 +]); + +/* + Lookup table for pairwise char codes in range [0-99] + + "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", + "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", + "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", + "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", + "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", + "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", + "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", + "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", + "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", + "90", "91", "92", "93", "94", "95", "96", "97", "98", "99" +*/ +// @ts-ignore: decorator +@lazy @inline const DIGITS = memory.data([ + 0x00300030, 0x00310030, 0x00320030, 0x00330030, 0x00340030, + 0x00350030, 0x00360030, 0x00370030, 0x00380030, 0x00390030, + 0x00300031, 0x00310031, 0x00320031, 0x00330031, 0x00340031, + 0x00350031, 0x00360031, 0x00370031, 0x00380031, 0x00390031, + 0x00300032, 0x00310032, 0x00320032, 0x00330032, 0x00340032, + 0x00350032, 0x00360032, 0x00370032, 0x00380032, 0x00390032, + 0x00300033, 0x00310033, 0x00320033, 0x00330033, 0x00340033, + 0x00350033, 0x00360033, 0x00370033, 0x00380033, 0x00390033, + 0x00300034, 0x00310034, 0x00320034, 0x00330034, 0x00340034, + 0x00350034, 0x00360034, 0x00370034, 0x00380034, 0x00390034, + 0x00300035, 0x00310035, 0x00320035, 0x00330035, 0x00340035, + 0x00350035, 0x00360035, 0x00370035, 0x00380035, 0x00390035, + 0x00300036, 0x00310036, 0x00320036, 0x00330036, 0x00340036, + 0x00350036, 0x00360036, 0x00370036, 0x00380036, 0x00390036, + 0x00300037, 0x00310037, 0x00320037, 0x00330037, 0x00340037, + 0x00350037, 0x00360037, 0x00370037, 0x00380037, 0x00390037, + 0x00300038, 0x00310038, 0x00320038, 0x00330038, 0x00340038, + 0x00350038, 0x00360038, 0x00370038, 0x00380038, 0x00390038, + 0x00300039, 0x00310039, 0x00320039, 0x00330039, 0x00340039, + 0x00350039, 0x00360039, 0x00370039, 0x00380039, 0x00390039 +]); + +// Lookup table for pairwise char codes in range [0x00-0xFF] +// @ts-ignore: decorator +@lazy @inline const HEX_DIGITS = +"000102030405060708090a0b0c0d0e0f\\ +101112131415161718191a1b1c1d1e1f\\ +202122232425262728292a2b2c2d2e2f\\ +303132333435363738393a3b3c3d3e3f\\ +404142434445464748494a4b4c4d4e4f\\ +505152535455565758595a5b5c5d5e5f\\ +606162636465666768696a6b6c6d6e6f\\ +707172737475767778797a7b7c7d7e7f\\ +808182838485868788898a8b8c8d8e8f\\ +909192939495969798999a9b9c9d9e9f\\ +a0a1a2a3a4a5a6a7a8a9aaabacadaeaf\\ +b0b1b2b3b4b5b6b7b8b9babbbcbdbebf\\ +c0c1c2c3c4c5c6c7c8c9cacbcccdcecf\\ +d0d1d2d3d4d5d6d7d8d9dadbdcdddedf\\ +e0e1e2e3e4e5e6e7e8e9eaebecedeeef\\ +f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"; + +// @ts-ignore: decorator +@lazy @inline const ANY_DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz"; + +// @ts-ignore: decorator +@lazy @inline const EXP_POWERS = memory.data([/* eslint-disable indent */ + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, + -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, + -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, + -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, + -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, + 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, + 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, + 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, + 907, 933, 960, 986, 1013, 1039, 1066 +/* eslint-enable indent */]); + +// 1e-348, 1e-340, ..., 1e340 +// @ts-ignore: decorator +@lazy @inline const FRC_POWERS = memory.data([ + 0xFA8FD5A0081C0288, 0xBAAEE17FA23EBF76, 0x8B16FB203055AC76, 0xCF42894A5DCE35EA, + 0x9A6BB0AA55653B2D, 0xE61ACF033D1A45DF, 0xAB70FE17C79AC6CA, 0xFF77B1FCBEBCDC4F, + 0xBE5691EF416BD60C, 0x8DD01FAD907FFC3C, 0xD3515C2831559A83, 0x9D71AC8FADA6C9B5, + 0xEA9C227723EE8BCB, 0xAECC49914078536D, 0x823C12795DB6CE57, 0xC21094364DFB5637, + 0x9096EA6F3848984F, 0xD77485CB25823AC7, 0xA086CFCD97BF97F4, 0xEF340A98172AACE5, + 0xB23867FB2A35B28E, 0x84C8D4DFD2C63F3B, 0xC5DD44271AD3CDBA, 0x936B9FCEBB25C996, + 0xDBAC6C247D62A584, 0xA3AB66580D5FDAF6, 0xF3E2F893DEC3F126, 0xB5B5ADA8AAFF80B8, + 0x87625F056C7C4A8B, 0xC9BCFF6034C13053, 0x964E858C91BA2655, 0xDFF9772470297EBD, + 0xA6DFBD9FB8E5B88F, 0xF8A95FCF88747D94, 0xB94470938FA89BCF, 0x8A08F0F8BF0F156B, + 0xCDB02555653131B6, 0x993FE2C6D07B7FAC, 0xE45C10C42A2B3B06, 0xAA242499697392D3, + 0xFD87B5F28300CA0E, 0xBCE5086492111AEB, 0x8CBCCC096F5088CC, 0xD1B71758E219652C, + 0x9C40000000000000, 0xE8D4A51000000000, 0xAD78EBC5AC620000, 0x813F3978F8940984, + 0xC097CE7BC90715B3, 0x8F7E32CE7BEA5C70, 0xD5D238A4ABE98068, 0x9F4F2726179A2245, + 0xED63A231D4C4FB27, 0xB0DE65388CC8ADA8, 0x83C7088E1AAB65DB, 0xC45D1DF942711D9A, + 0x924D692CA61BE758, 0xDA01EE641A708DEA, 0xA26DA3999AEF774A, 0xF209787BB47D6B85, + 0xB454E4A179DD1877, 0x865B86925B9BC5C2, 0xC83553C5C8965D3D, 0x952AB45CFA97A0B3, + 0xDE469FBD99A05FE3, 0xA59BC234DB398C25, 0xF6C69A72A3989F5C, 0xB7DCBF5354E9BECE, + 0x88FCF317F22241E2, 0xCC20CE9BD35C78A5, 0x98165AF37B2153DF, 0xE2A0B5DC971F303A, + 0xA8D9D1535CE3B396, 0xFB9B7CD9A4A7443C, 0xBB764C4CA7A44410, 0x8BAB8EEFB6409C1A, + 0xD01FEF10A657842C, 0x9B10A4E5E9913129, 0xE7109BFBA19C0C9D, 0xAC2820D9623BF429, + 0x80444B5E7AA7CF85, 0xBF21E44003ACDD2D, 0x8E679C2F5E44FF8F, 0xD433179D9C8CB841, + 0x9E19DB92B4E31BA9, 0xEB96BF6EBADF77D9, 0xAF87023B9BF0EE6B +]); + +// @ts-ignore: decorator +@inline +export function isPowerOf2(value: T): bool { + return popcnt(value) == 1; +} + +// Count number of decimals for u32 values +// In our case input value always non-zero so we can simplify some parts +export function decimalCount32(value: u32): u32 { + if (value < 100000) { + if (value < 100) { + return 1 + u32(value >= 10); + } else { + return 3 + u32(value >= 10000) + u32(value >= 1000); + } + } else { + if (value < 10000000) { + return 6 + u32(value >= 1000000); + } else { + return 8 + u32(value >= 1000000000) + u32(value >= 100000000); + } + } +} + +// Count number of decimals for u64 values +// In our case input value always greater than 2^32-1 so we can skip some parts +export function decimalCount64High(value: u64): u32 { + if (value < 1000000000000000) { + if (value < 1000000000000) { + return 10 + u32(value >= 100000000000) + u32(value >= 10000000000); + } else { + return 13 + u32(value >= 100000000000000) + u32(value >= 10000000000000); + } + } else { + if (value < 100000000000000000) { + return 16 + u32(value >= 10000000000000000); + } else { + return 18 + u32(value >= 10000000000000000000) + u32(value >= 1000000000000000000); + } + } +} + +function ulog_base(num: u64, base: i32): u32 { + if (isPowerOf2(base)) { + return (63 - clz(num)) / (31 - clz(base)) + 1; + } + var b64 = u64(base), b = b64, e: u32 = 1; + while (num >= b) { + num /= b; + b *= b; + e <<= 1; + } + while (num >= 1) { + num /= b64; + e++; + } + return e - 1; +} + +function utoa32_dec_lut(buffer: usize, num: u32, offset: usize): void { + while (num >= 10000) { + // in most VMs i32/u32 div and modulo by constant can be shared and simplificate + let t = num / 10000; + let r = num % 10000; + num = t; + + let d1 = r / 100; + let d2 = r % 100; + + let digits1 = load(DIGITS + (d1 << alignof())); + let digits2 = load(DIGITS + (d2 << alignof())); + + offset -= 4; + store(buffer + (offset << 1), digits1 | (digits2 << 32)); + } + + if (num >= 100) { + let t = num / 100; + let d1 = num % 100; + num = t; + offset -= 2; + let digits = load(DIGITS + (d1 << alignof())); + store(buffer + (offset << 1), digits); + } + + if (num >= 10) { + offset -= 2; + let digits = load(DIGITS + (num << alignof())); + store(buffer + (offset << 1), digits); + } else { + offset -= 1; + let digit = CharCode._0 + num; + store(buffer + (offset << 1), digit); + } +} + +function utoa64_dec_lut(buffer: usize, num: u64, offset: usize): void { + while (num >= 100000000) { + let t = num / 100000000; + let r = (num - t * 100000000); + num = t; + + let b = r / 10000; + let c = r % 10000; + + let b1 = b / 100; + let b2 = b % 100; + let c1 = c / 100; + let c2 = c % 100; + + let digits1 = load(DIGITS + (c1 << alignof())); + let digits2 = load(DIGITS + (c2 << alignof())); + + offset -= 4; + store(buffer + (offset << 1), digits1 | (digits2 << 32)); + + digits1 = load(DIGITS + (b1 << alignof())); + digits2 = load(DIGITS + (b2 << alignof())); + + offset -= 4; + store(buffer + (offset << 1), digits1 | (digits2 << 32)); + } + + utoa32_dec_lut(buffer, num, offset); +} + +function utoa_hex_lut(buffer: usize, num: u64, offset: usize): void { + const lut = changetype(HEX_DIGITS); + while (offset >= 2) { + offset -= 2; + store( + buffer + (offset << 1), + load(lut + ((num & 0xFF) << alignof())) + ); + num >>= 8; + } + if (offset & 1) { + store(buffer, load(lut + (num << 6))); + } +} + +function utoa_dec_simple(buffer: usize, num: T, offset: usize): void { + do { + let t = num / 10; + let r = (num % 10); + num = changetype(t); + offset--; + store(buffer + (offset << 1), CharCode._0 + r); + } while (num); +} + +function utoa_hex_simple(buffer: usize, num: T, offset: usize): void { + do { + let d = num & 0x0F | CharCode._0; + d += select(0x27, 0, d > CharCode._9); + offset--; + store(buffer + (offset << 1), d); + // @ts-ignore: type + num >>= 4; + } while (num); +} + +// @ts-ignore: decorator +@inline +export function utoa32_dec_core(buffer: usize, num: u32, offset: usize): void { + if (ASC_SHRINK_LEVEL >= 1) { + utoa_dec_simple(buffer, num, offset); + } else { + utoa32_dec_lut(buffer, num, offset); + } +} + +// @ts-ignore: decorator +@inline +function utoa32_hex_core(buffer: usize, num: u32, offset: usize): void { + if (ASC_SHRINK_LEVEL >= 1) { + utoa_hex_simple(buffer, num, offset); + } else { + utoa_hex_lut(buffer, num, offset); + } +} + +// @ts-ignore: decorator +@inline +function utoa64_dec_core(buffer: usize, num: u64, offset: usize): void { + if (ASC_SHRINK_LEVEL >= 1) { + utoa_dec_simple(buffer, num, offset); + } else { + utoa64_dec_lut(buffer, num, offset); + } +} + +// @ts-ignore: decorator +@inline +function utoa64_hex_core(buffer: usize, num: u64, offset: usize): void { + if (ASC_SHRINK_LEVEL >= 1) { + utoa_hex_simple(buffer, num, offset); + } else { + utoa_hex_lut(buffer, num, offset); + } +} + +function utoa64_any_core(buffer: usize, num: u64, offset: usize, radix: i32): void { + const lut = changetype(ANY_DIGITS); + var base = u64(radix); + if ((radix & (radix - 1)) == 0) { // for radix which pow of two + let shift = u64(ctz(radix) & 7); + let mask = base - 1; + do { + offset--; + store(buffer + (offset << 1), load(lut + (usize(num & mask) << 1))); + num >>= shift; + } while (num); + } else { + do { + offset--; + let q = num / base; + store(buffer + (offset << 1), load(lut + (usize(num - q * base) << 1))); + num = q; + } while (num); + } +} + +export function utoa32(value: u32, radix: i32): String { + if (radix < 2 || radix > 36) { + throw new RangeError("toString() radix argument must be between 2 and 36"); + } + if (!value) return "0"; + var out: String; + + if (radix == 10) { + let decimals = decimalCount32(value); + out = changetype(__new(decimals << 1, idof())); + utoa32_dec_core(changetype(out), value, decimals); + } else if (radix == 16) { + let decimals = (31 - clz(value) >> 2) + 1; + out = changetype(__new(decimals << 1, idof())); + utoa32_hex_core(changetype(out), value, decimals); + } else { + let decimals = ulog_base(value, radix); + out = changetype(__new(decimals << 1, idof())); + utoa64_any_core(changetype(out), value, decimals, radix); + } + return out; +} + +export function itoa32(value: i32, radix: i32): String { + if (radix < 2 || radix > 36) { + throw new RangeError("toString() radix argument must be between 2 and 36"); + } + if (!value) return "0"; + + var sign = value >>> 31; + if (sign) value = -value; + var out: String; + + if (radix == 10) { + let decimals = decimalCount32(value) + sign; + out = changetype(__new(decimals << 1, idof())); + utoa32_dec_core(changetype(out), value, decimals); + } else if (radix == 16) { + let decimals = (31 - clz(value) >> 2) + 1 + sign; + out = changetype(__new(decimals << 1, idof())); + utoa32_hex_core(changetype(out), value, decimals); + } else { + let val32 = u32(value); + let decimals = ulog_base(val32, radix) + sign; + out = changetype(__new(decimals << 1, idof())); + utoa64_any_core(changetype(out), val32, decimals, radix); + } + if (sign) store(changetype(out), CharCode.MINUS); + return out; +} + +export function utoa64(value: u64, radix: i32): String { + if (radix < 2 || radix > 36) { + throw new RangeError("toString() radix argument must be between 2 and 36"); + } + if (!value) return "0"; + var out: String; + + if (radix == 10) { + if (value <= u32.MAX_VALUE) { + let val32 = value; + let decimals = decimalCount32(val32); + out = changetype(__new(decimals << 1, idof())); + utoa32_dec_core(changetype(out), val32, decimals); + } else { + let decimals = decimalCount64High(value); + out = changetype(__new(decimals << 1, idof())); + utoa64_dec_core(changetype(out), value, decimals); + } + } else if (radix == 16) { + let decimals = (63 - u32(clz(value)) >> 2) + 1; + out = changetype(__new(decimals << 1, idof())); + utoa64_hex_core(changetype(out), value, decimals); + } else { + let decimals = ulog_base(value, radix); + out = changetype(__new(decimals << 1, idof())); + utoa64_any_core(changetype(out), value, decimals, radix); + } + return out; +} + +export function itoa64(value: i64, radix: i32): String { + if (radix < 2 || radix > 36) { + throw new RangeError("toString() radix argument must be between 2 and 36"); + } + if (!value) return "0"; + + var sign = u32(value >>> 63); + if (sign) value = -value; + var out: String; + + if (radix == 10) { + if (value <= u32.MAX_VALUE) { + let val32 = value; + let decimals = decimalCount32(val32) + sign; + out = changetype(__new(decimals << 1, idof())); + utoa32_dec_core(changetype(out), val32, decimals); + } else { + let decimals = decimalCount64High(value) + sign; + out = changetype(__new(decimals << 1, idof())); + utoa64_dec_core(changetype(out), value, decimals); + } + } else if (radix == 16) { + let decimals = (63 - u32(clz(value)) >> 2) + 1 + sign; + out = changetype(__new(decimals << 1, idof())); + utoa64_hex_core(changetype(out), value, decimals); + } else { + let decimals = ulog_base(value, radix) + sign; + out = changetype(__new(decimals << 1, idof())); + utoa64_any_core(changetype(out), value, decimals, radix); + } + if (sign) store(changetype(out), CharCode.MINUS); + return out; +} + +// @ts-ignore: decorator +@lazy var _K: i32 = 0; + +// // @ts-ignore: decorator +// @lazy +// var _frc: u64 = 0; + +// @ts-ignore: decorator +@lazy var _exp: i32 = 0; + +// @ts-ignore: decorator +@lazy var _frc_minus: u64 = 0; + +// @ts-ignore: decorator +@lazy var _frc_plus: u64 = 0; + +// @ts-ignore: decorator +@lazy var _frc_pow: u64 = 0; + +// @ts-ignore: decorator +@lazy var _exp_pow: i32 = 0; + +// @ts-ignore: decorator +@inline +function umul64f(u: u64, v: u64): u64 { + var u0 = u & 0xFFFFFFFF; + var v0 = v & 0xFFFFFFFF; + + var u1 = u >> 32; + var v1 = v >> 32; + + var l = u0 * v0; + var t = u1 * v0 + (l >> 32); + var w = u0 * v1 + (t & 0xFFFFFFFF); + + w += 0x7FFFFFFF; // rounding + + t >>= 32; + w >>= 32; + + return u1 * v1 + t + w; +} + +// @ts-ignore: decorator +@inline +function umul64e(e1: i32, e2: i32): i32 { + return e1 + e2 + 64; // where 64 is significand size +} + +// @ts-ignore: decorator +@inline +function normalizedBoundaries(f: u64, e: i32): void { + var frc = (f << 1) + 1; + var exp = e - 1; + var off = clz(frc); + frc <<= off; + exp -= off; + + var m = 1 + i32(f == 0x0010000000000000); + + _frc_plus = frc; + _frc_minus = ((f << m) - 1) << e - m - exp; + _exp = exp; +} + +// @ts-ignore: decorator +@inline +function grisuRound(buffer: usize, len: i32, delta: u64, rest: u64, ten_kappa: u64, wp_w: u64): void { + var lastp = buffer + ((len - 1) << 1); + var digit = load(lastp); + while ( + rest < wp_w && + delta - rest >= ten_kappa && ( + rest + ten_kappa < wp_w || + wp_w - rest > rest + ten_kappa - wp_w + ) + ) { + --digit; + rest += ten_kappa; + } + store(lastp, digit); +} + +// @ts-ignore: decorator +@inline +function getCachedPower(minExp: i32): void { + const c = reinterpret(0x3FD34413509F79FE); // 1 / lg(10) = 0.30102999566398114 + var dk = (-61 - minExp) * c + 347; // dk must be positive, so can do ceiling in positive + var k = dk; + k += i32(k != dk); // conversion with ceil + + var index = (k >> 3) + 1; + _K = 348 - (index << 3); // decimal exponent no need lookup table + _frc_pow = load(FRC_POWERS + (index << alignof())); + _exp_pow = load(EXP_POWERS + (index << alignof())); +} + +// @ts-ignore: decorator +@inline +function grisu2(value: f64, buffer: usize, sign: i32): i32 { + + // frexp routine + var uv = reinterpret(value); + var exp = i32((uv & 0x7FF0000000000000) >>> 52); + var sid = uv & 0x000FFFFFFFFFFFFF; + var frc = (u64(exp != 0) << 52) + sid; + exp = select(exp, 1, exp) - (0x3FF + 52); + + normalizedBoundaries(frc, exp); + getCachedPower(_exp); + + // normalize + var off = clz(frc); + frc <<= off; + exp -= off; + + var frc_pow = _frc_pow; + var exp_pow = _exp_pow; + + var w_frc = umul64f(frc, frc_pow); + var w_exp = umul64e(exp, exp_pow); + + var wp_frc = umul64f(_frc_plus, frc_pow) - 1; + var wp_exp = umul64e(_exp, exp_pow); + + var wm_frc = umul64f(_frc_minus, frc_pow) + 1; + var delta = wp_frc - wm_frc; + + return genDigits(buffer, w_frc, w_exp, wp_frc, wp_exp, delta, sign); +} + +function genDigits(buffer: usize, w_frc: u64, w_exp: i32, mp_frc: u64, mp_exp: i32, delta: u64, sign: i32): i32 { + var one_exp = -mp_exp; + var one_frc = (1) << one_exp; + var mask = one_frc - 1; + + var wp_w_frc = mp_frc - w_frc; + + var p1 = u32(mp_frc >> one_exp); + var p2 = mp_frc & mask; + + var kappa = decimalCount32(p1); + var len = sign; + + while (kappa > 0) { + let d: u32; + switch (kappa) { + case 10: { d = p1 / 1000000000; p1 %= 1000000000; break; } + case 9: { d = p1 / 100000000; p1 %= 100000000; break; } + case 8: { d = p1 / 10000000; p1 %= 10000000; break; } + case 7: { d = p1 / 1000000; p1 %= 1000000; break; } + case 6: { d = p1 / 100000; p1 %= 100000; break; } + case 5: { d = p1 / 10000; p1 %= 10000; break; } + case 4: { d = p1 / 1000; p1 %= 1000; break; } + case 3: { d = p1 / 100; p1 %= 100; break; } + case 2: { d = p1 / 10; p1 %= 10; break; } + case 1: { d = p1; p1 = 0; break; } + default: { d = 0; break; } + } + + if (d | len) store(buffer + (len++ << 1), CharCode._0 + d); + + --kappa; + let tmp = ((p1) << one_exp) + p2; + if (tmp <= delta) { + _K += kappa; + grisuRound(buffer, len, delta, tmp, load(POWERS10 + (kappa << alignof())) << one_exp, wp_w_frc); + return len; + } + } + + while (true) { + p2 *= 10; + delta *= 10; + + let d = p2 >> one_exp; + if (d | len) store(buffer + (len++ << 1), CharCode._0 + d); + + p2 &= mask; + --kappa; + if (p2 < delta) { + _K += kappa; + wp_w_frc *= load(POWERS10 + (-kappa << alignof())); + grisuRound(buffer, len, delta, p2, one_frc, wp_w_frc); + return len; + } + } +} + +// @ts-ignore: decorator +@inline +function genExponent(buffer: usize, k: i32): i32 { + var sign = k < 0; + if (sign) k = -k; + var decimals = decimalCount32(k) + 1; + utoa32_dec_core(buffer, k, decimals); + store(buffer, select(CharCode.MINUS, CharCode.PLUS, sign)); + return decimals; +} + +function prettify(buffer: usize, length: i32, k: i32): i32 { + if (!k) { + store(buffer + (length << 1), CharCode.DOT | (CharCode._0 << 16)); + return length + 2; + } + + var kk = length + k; + if (length <= kk && kk <= 21) { + // 1234e7 -> 12340000000 + for (let i = length; i < kk; ++i) { + store(buffer + (i << 1), CharCode._0); + } + store(buffer + (kk << 1), CharCode.DOT | (CharCode._0 << 16)); + return kk + 2; + } else if (kk > 0 && kk <= 21) { + // 1234e-2 -> 12.34 + let ptr = buffer + (kk << 1); + memory.copy( + ptr + 2, + ptr, + -k << 1 + ); + store(buffer + (kk << 1), CharCode.DOT); + return length + 1; + } else if (-6 < kk && kk <= 0) { + // 1234e-6 -> 0.001234 + let offset = 2 - kk; + memory.copy( + buffer + (offset << 1), + buffer, + length << 1 + ); + store(buffer, CharCode._0 | (CharCode.DOT << 16)); + for (let i = 2; i < offset; ++i) { + store(buffer + (i << 1), CharCode._0); + } + return length + offset; + } else if (length == 1) { + // 1e30 + store(buffer, CharCode.e, 2); + length = genExponent(buffer + 4, kk - 1); + return length + 2; + } else { + let len = length << 1; + memory.copy( + buffer + 4, + buffer + 2, + len - 2 + ); + store(buffer, CharCode.DOT, 2); + store(buffer + len, CharCode.e, 2); + length += genExponent(buffer + len + 4, kk - 1); + return length + 2; + } +} + +function dtoa_core(buffer: usize, value: f64): i32 { + var sign = i32(value < 0); + if (sign) { + value = -value; + store(buffer, CharCode.MINUS); + } + // assert(value > 0 && value <= 1.7976931348623157e308); + var len = grisu2(value, buffer, sign); + len = prettify(buffer + (sign << 1), len - sign, _K); + return len + sign; +} + +// @ts-ignore: decorator +@lazy @inline const dtoa_buf = memory.data(MAX_DOUBLE_LENGTH << 1); + +export function dtoa(value: f64): String { + if (value == 0) return "0.0"; + if (!isFinite(value)) { + if (isNaN(value)) return "NaN"; + return select("-Infinity", "Infinity", value < 0); + } + var size = dtoa_core(dtoa_buf, value) << 1; + var result = changetype(__new(size, idof())); + memory.copy(changetype(result), dtoa_buf, size); + return result; +} + +export function itoa_buffered(buffer: usize, value: T): u32 { + var sign: u32 = 0; + if (isSigned()) { + sign = u32(value < 0); + if (sign) { + value = changetype(-value); + store(buffer, CharCode.MINUS); + } + } + if (ASC_SHRINK_LEVEL <= 1) { + if (isSigned()) { + if (sizeof() <= 4) { + if (value < 10) { + store(buffer + (sign << 1), value | CharCode._0); + return 1 + sign; + } + } else { + if (value < 10) { + store(buffer + (sign << 1), value | CharCode._0); + return 1 + sign; + } + } + } else { + if (value < 10) { + store(buffer, value | CharCode._0); + return 1; + } + } + } + var decimals = sign; + if (sizeof() <= 4) { + decimals += decimalCount32(value); + utoa32_dec_core(buffer, value, decimals); + } else { + if (value <= u32.MAX_VALUE) { + let val32 = value; + decimals += decimalCount32(val32); + utoa32_dec_core(buffer, val32, decimals); + } else { + decimals += decimalCount64High(value); + utoa64_dec_core(buffer, value, decimals); + } + } + return decimals; +} + +export function dtoa_buffered(buffer: usize, value: f64): u32 { + if (value == 0) { + store(buffer, CharCode._0); + store(buffer, CharCode.DOT, 2); + store(buffer, CharCode._0, 4); + return 3; + } + if (!isFinite(value)) { + if (isNaN(value)) { + store(buffer, CharCode.N); + store(buffer, CharCode.a, 2); + store(buffer, CharCode.N, 4); + return 3; + } else { + let sign = value < 0; + if (sign) { + store(buffer, CharCode.MINUS); // - + buffer += 2; + } + store(buffer, 0x690066006E0049, 0); // ifnI + store(buffer, 0x7900740069006E, 8); // ytin + return 8 + u32(sign); + } + } + return dtoa_core(buffer, value); +} +`,"util/sort":`import { compareImpl } from "./string"; + +type Comparator = (a: T, b: T) => i32; + +// @ts-ignore: decorator +@lazy @inline const EMPTY = u32.MAX_VALUE; +// @ts-ignore: decorator +@inline const INSERTION_SORT_THRESHOLD = 48; +// @ts-ignore: decorator +@inline const MIN_RUN_LENGTH = 32; + +// @ts-ignore: decorator +@inline +function log2u(n: u32): u32 { + return 31 - clz(n); +} + +// @ts-ignore: decorator +@inline +export function COMPARATOR(): Comparator { + if (isInteger()) { + if (isSigned() && sizeof() <= 4) { + return (a, b) => i32(a) - i32(b); + } else { + return (a, b) => i32(a > b) - i32(a < b); + } + } else if (isFloat()) { + if (sizeof() == 4) { + return (a, b) => { + var ia = reinterpret(f32(a)); + var ib = reinterpret(f32(b)); + ia ^= ia >> 31 >>> 1; + ib ^= ib >> 31 >>> 1; + return i32(ia > ib) - i32(ia < ib); + }; + } else { + return (a, b) => { + var ia = reinterpret(f64(a)); + var ib = reinterpret(f64(b)); + ia ^= ia >> 63 >>> 1; + ib ^= ib >> 63 >>> 1; + return i32(ia > ib) - i32(ia < ib); + }; + } + } else if (isString()) { + return (a, b) => { + if (changetype(a) == changetype(b) || changetype(a) == 0 || changetype(b) == 0) return 0; + var alen = changetype(a).length; + var blen = changetype(b).length; + if (!(alen | blen)) return 0; + if (!alen) return -1; + if (!blen) return 1; + let res = compareImpl( + changetype(a), 0, + changetype(b), 0, + min(alen, blen) + ); + return res ? res : alen - blen; + }; + } else { + return (a, b) => i32(a > b) - i32(a < b); + } +} + +// Power Sort implementation (stable) from paper "Nearly-Optimal Mergesorts" +// https://arxiv.org/pdf/1805.04154.pdf +// This method usually outperform TimSort. +// TODO: refactor c >>> 31 to c < 0 when binaryen will support this opt +export function SORT( + ptr: usize, + len: i32, + comparator: Comparator +): void { + if (len <= INSERTION_SORT_THRESHOLD) { + if (len <= 1) return; + if (ASC_SHRINK_LEVEL < 1) { + switch (len) { + case 3: { + let a = load(ptr, 0); + let b = load(ptr, 1 << alignof()); + let c = comparator(a, b) > 0; + store(ptr, select(b, a, c), 0); + a = select(a, b, c); + b = load(ptr, 2 << alignof()); + c = comparator(a, b) > 0; + store(ptr, select(b, a, c), 1 << alignof()); + store(ptr, select(a, b, c), 2 << alignof()); + } + case 2: { + let a = load(ptr, 0); + let b = load(ptr, 1 << alignof()); + let c = comparator(a, b) > 0; + store(ptr, select(b, a, c), 0); + store(ptr, select(a, b, c), 1 << alignof()); + return; + } + } + } + insertionSort(ptr, 0, len - 1, 0, comparator); + return; + } + + var lgPlus2 = log2u(len) + 2; + var lgPlus2Size = lgPlus2 << alignof(); + var leftRunStartBuf = __alloc(lgPlus2Size << 1); + var leftRunEndBuf = leftRunStartBuf + lgPlus2Size; + + for (let i: u32 = 0; i < lgPlus2; ++i) { + store(leftRunStartBuf + (i << alignof()), EMPTY); + } + + var buffer = __alloc(len << alignof()); + + var hi = len - 1; + var endA = extendRunRight(ptr, 0, hi, comparator); + var lenA = endA + 1; + + if (lenA < MIN_RUN_LENGTH) { + endA = min(hi, MIN_RUN_LENGTH - 1); + insertionSort(ptr, 0, endA, lenA, comparator); + } + + var top: u32 = 0, startA = 0; + while (endA < hi) { + let startB = endA + 1; + let endB = extendRunRight(ptr, startB, hi, comparator); + let lenB = endB - startB + 1; + + if (lenB < MIN_RUN_LENGTH) { + endB = min(hi, startB + MIN_RUN_LENGTH - 1); + insertionSort(ptr, startB, endB, lenB, comparator); + } + + let k = nodePower(0, hi, startA, startB, endB); + + for (let i = top; i > k; --i) { + let start = load(leftRunStartBuf + (i << alignof())); + if (start != EMPTY) { + mergeRuns( + ptr, + start, + load(leftRunEndBuf + (i << alignof())) + 1, + endA, + buffer, + comparator + ); + startA = start; + store(leftRunStartBuf + (i << alignof()), EMPTY); + } + } + + store(leftRunStartBuf + (k << alignof()), startA); + store(leftRunEndBuf + (k << alignof()), endA); + startA = startB; + endA = endB; + top = k; + } + + for (let i = top; i != 0; --i) { + let start = load(leftRunStartBuf + (i << alignof())); + if (start != EMPTY) { + mergeRuns( + ptr, + start, + load(leftRunEndBuf + (i << alignof())) + 1, + hi, + buffer, + comparator + ); + } + } + // dealloc aux buffers + __free(buffer); + __free(leftRunStartBuf); +} + +function insertionSort( + ptr: usize, + left: i32, + right: i32, + presorted: i32, + comparator: Comparator +): void { + if (ASC_SHRINK_LEVEL >= 1) { + // slightly improved original insertion sort + for (let i = left + presorted; i <= right; ++i) { + let j = i - 1; + let a = load(ptr + (i << alignof())); + while (j >= left) { + let b = load(ptr + (j << alignof())); + if (comparator(a, b) < 0) { + store(ptr + (j << alignof()), b, 1 << alignof()); --j; + } else break; + } + store(ptr + (j << alignof()), a, 1 << alignof()); + } + } else { + // even-odd two-way insertion sort which allow increase minRunLen + let range = right - left + 1; + let i = left + select(range & 1, presorted - ((range - presorted) & 1), presorted == 0); + for (; i <= right; i += 2) { + let a = load(ptr + (i << alignof()), 0); + let b = load(ptr + (i << alignof()), 1 << alignof()); + let min = b, max = a; + if (comparator(a, b) <= 0) { + min = a, max = b; + } + let j = i - 1; + while (j >= left) { + a = load(ptr + (j << alignof())); + if (comparator(a, max) > 0) { + store(ptr + (j << alignof()), a, 2 << alignof()); --j; + } else break; + } + store(ptr + (j << alignof()), max, 2 << alignof()); + while (j >= left) { + a = load(ptr + (j << alignof())); + if (comparator(a, min) > 0) { + store(ptr + (j << alignof()), a, 1 << alignof()); --j; + } else break; + } + store(ptr + (j << alignof()), min, 1 << alignof()); + } + } +} + +function nodePower(left: u32, right: u32, startA: u32, startB: u32, endB: u32): u32 { + var n: u64 = right - left + 1; + var s = startB - (left << 1); + var l = startA + s; + var r = endB + s + 1; + var a = (l << 30) / n; + var b = (r << 30) / n; + return clz((a ^ b)); +} + +function extendRunRight( + ptr: usize, + i: i32, + right: i32, + comparator: Comparator +): i32 { + if (i == right) return i; + var j = i; + if (comparator( + load(ptr + ( j << alignof())), + load(ptr + (++j << alignof())) + ) > 0) { + while ( + j < right && + (comparator( + load(ptr + (j << alignof()), 1 << alignof()), + load(ptr + (j << alignof())) + ) >>> 31) // < 0 + ) ++j; + // reverse + let k = j; + while (i < k) { + let tmp = load(ptr + (i << alignof())); + store(ptr + (i << alignof()), load(ptr + (k << alignof()))); ++i; + store(ptr + (k << alignof()), tmp); --k; + } + } else { + while ( + j < right && + comparator( + load(ptr + (j << alignof()), 1 << alignof()), + load(ptr + (j << alignof())) + ) >= 0 + ) ++j; + } + return j; +} + +// Merges arr[l..m - 1] and arr[m..r] +function mergeRuns( + ptr: usize, + l: i32, + m: i32, + r: i32, + buffer: usize, + comparator: Comparator +): void { + --m; + var i: i32, j: i32, t = r + m; + for (i = m + 1; i > l; --i) { + store( + buffer + ((i - 1) << alignof()), + load(ptr + ((i - 1) << alignof())) + ); + } + for (j = m; j < r; ++j) { + store( + buffer + ((t - j) << alignof()), + load(ptr + (j << alignof()), 1 << alignof()) + ); + } + for (let k = l; k <= r; ++k) { + let a = load(buffer + (j << alignof())); + let b = load(buffer + (i << alignof())); + if (comparator(a, b) < 0) { + store(ptr + (k << alignof()), a); + --j; + } else { + store(ptr + (k << alignof()), b); + ++i; + } + } +} +`,"util/string":`import { itoa32, utoa32, itoa64, utoa64, dtoa, itoa_buffered, dtoa_buffered, MAX_DOUBLE_LENGTH } from "./number"; +import { ipow32 } from "../math"; + +// All tables are stored as two staged lookup tables (static tries) +// because the full range of Unicode symbols can't be efficiently +// represented as-is in memory (see Unicode spec ch 5, p.196): +// https://www.unicode.org/versions/Unicode12.0.0/ch05.pdf +// Tables have been generated using these forked musl tools: +// https://github.com/MaxGraey/musl-chartable-tools/tree/case-ignorable + +// Lookup table to check if a character is alphanumeric or not +// See: https://git.musl-libc.org/cgit/musl/tree/src/ctype/alpha.h +// size: 3904 bytes +// @ts-ignore +@inline @lazy const ALPHA_TABLE = memory.data([ + 18,17,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,17,34,35,36,17,37,38,39,40, + 41,42,43,44,17,45,46,47,16,16,48,16,16,16,16,16,16,16,49,50,51,16,52,53,16,16, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,54, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,55,17,17,17,17,56,17,57,58,59,60,61,62,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,63,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,64,65,17,66,67, + 68,69,70,71,72,73,74,17,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92, + 93,94,16,95,96,97,98,17,17,17,99,100,101,16,16,16,16,16,16,16,16,16,16,17,17, + 17,17,102,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,103,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,17,17,104,105,16,16,106,107,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,108,17,17,17,17,109,110,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 17,111,112,16,16,16,16,16,16,16,16,16,113,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,114,115,116,117,16,16,16,16,16,16,16,16,118, + 119,120,16,16,16,16,16,121,122,16,16,16,16,123,16,16,124,16,16,16,16,16,16,16, + 16,16,125,16,16,16, + 16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,254,255,255,7,254, + 255,255,7,0,0,0,0,0,4,32,4,255,255,127,255,255,255,127,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,195,255,3,0,31,80,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,223,188,64,215,255,255, + 251,255,255,255,255,255,255,255,255,255,191,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,3,252,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,254,255,255,255,127,2,255,255,255, + 255,255,1,0,0,0,0,255,191,182,0,255,255,255,135,7,0,0,0,255,7,255,255,255,255, + 255,255,255,254,255,195,255,255,255,255,255,255,255,255,255,255,255,255,239, + 31,254,225,255, + 159,0,0,255,255,255,255,255,255,0,224,255,255,255,255,255,255,255,255,255,255, + 255,255,3,0,255,255,255,255,255,7,48,4,255,255,255,252,255,31,0,0,255,255,255, + 1,255,7,0,0,0,0,0,0,255,255,223,255,255,0,240,255,248,3,255,255,255,255,255, + 255,255,255,255,239,255,223,225,255,207,255,254,255,239,159,249,255,255,253, + 197,227,159,89,128,176,207,255,3,16,238,135,249,255,255,253,109,195,135,25,2, + 94,192,255,63,0,238,191,251,255,255,253,237,227,191,27,1,0,207,255,0,30,238, + 159,249,255,255,253,237,227,159,25,192,176,207,255,2,0,236,199,61,214,24,199, + 255,195,199,29,129,0,192,255,0,0,239,223,253,255,255,253,255,227,223,29,96,7, + 207,255,0,0,239,223,253,255,255,253,239,227,223,29,96,64,207,255,6,0,255,223, + 253,255,255,255,255,231,223,93,240,128,207,255,0,252,238,255,127,252,255,255, + 251,47,127,128,95,255,192,255,12,0,254,255,255,255,255,127,255,7,63,32,255,3, + 0,0,0,0,214,247,255,255,175,255,255,59,95,32,255,243,0,0,0, + 0,1,0,0,0,255,3,0,0,255,254,255,255,255,31,254,255,3,255,255,254,255,255,255, + 31,0,0,0,0,0,0,0,0,255,255,255,255,255,255,127,249,255,3,255,255,255,255,255, + 255,255,255,255,63,255,255,255,255,191,32,255,255,255,255,255,247,255,255,255, + 255,255,255,255,255,255,61,127,61,255,255,255,255,255,61,255,255,255,255,61, + 127,61,255,127,255,255,255,255,255,255,255,61,255,255,255,255,255,255,255,255, + 7,0,0,0,0,255,255,0,0,255,255,255,255,255,255,255,255,255,255,63,63,254,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,159,255,255,254,255,255,7,255,255,255,255,255,255,255,255, + 255,199,255,1,255,223,15,0,255,255,15,0,255,255,15,0,255,223,13,0,255,255,255, + 255,255,255,207,255,255,1,128,16,255,3,0,0,0,0,255,3,255,255,255,255,255,255, + 255,255,255,255,255,1,255,255,255,255,255,7,255,255,255,255,255,255,255,255, + 63, + 0,255,255,255,127,255,15,255,1,192,255,255,255,255,63,31,0,255,255,255,255, + 255,15,255,255,255,3,255,3,0,0,0,0,255,255,255,15,255,255,255,255,255,255,255, + 127,254,255,31,0,255,3,255,3,128,0,0,128,1,0,0,0,0,0,0,0,255,255,255,255,255, + 255,239,255,239,15,255,3,0,0,0,0,255,255,255,255,255,243,255,255,255,255,255, + 255,191,255,3,0,255,255,255,255,255,255,127,0,255,227,255,255,255,255,255,63, + 255,1,255,255,255,255,255,231,0,0,0,0,0,222,111,4,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0, + 128,255,31,0,255,255,63,63,255,255,255,255,63,63,255,170,255,255,255,63,255, + 255,255,255,255,255,223,95,220,31,207,15,255,31,220,31,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,2,128,0,0,255,31,0,0,0,0,0,0,0,0,0,0,0,0,132,252,47,62,80,189,255,243, + 224,67,0,0,255,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,255,255,255,255,255,255,3,0, + 0,255,255,255,255,255,127,255,255,255,255,255,127,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,31,120,12,0,255,255,255,255,191,32,255, + 255,255,255,255,255,255,128,0,0,255,255,127,0,127,127,127,127,127,127,127,127, + 255,255,255,255,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,224,0,0,0,254,3,62,31,254,255,255,255,255,255,255,255,255,255,127,224,254, + 255,255,255,255,255,255,255,255,255,255,247,224,255,255,255,255,255,254,255, + 255,255,255,255,255,255,255,255,255,127,0,0,255,255,255,255,0,0,0,0,0,0,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255, + 31,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,0, + 0,0,0,0,0,0,255,255,255,255,255,63,255,31,255,255,255,15,0,0,255,255,255,255, + 255,127,240,143,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, + 0,128,255,252,255,255,255,255,255,255,255,255,255,255,255,255,249,255,255,255, + 255,255,255,252,7,0,0,0,0,224,255,191,255,255,255,255,0,0,0,255,255,255,255, + 255,255,15,0,255,255,255,255,255,255,255,255,47,0,255,3,0,0,252,232,255,255, + 255,255,255,7,255,255,255,255,7,0,255,255,255,31,255,255,255,255,255,255,247, + 255,0,128,255,3,255,255,255,127,255,255,255,255,255,255,127,0,255,63,255,3, + 255,255,127,252,255,255,255,255,255,255,255,127,5,0,0,56,255,255,60,0,126,126, + 126,0,127,127,255,255,255,255,255,247,255,3,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,7,255,3,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,15,0,255,255,127,248,255,255,255,255, + 255, + 15,255,255,255,255,255,255,255,255,255,255,255,255,255,63,255,255,255,255,255, + 255,255,255,255,255,255,255,255,3,0,0,0,0,127,0,248,224,255,253,127,95,219, + 255,255,255,255,255,255,255,255,255,255,255,255,255,3,0,0,0,248,255,255,255, + 255,255,255,255,255,255,255,255,255,63,0,0,255,255,255,255,255,255,255,255, + 252,255,255,255,255,255,255,0,0,0,0,0,255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,223, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,0,255,3, + 254,255,255,7,254,255,255,7,192,255,255,255,255,255,255,255,255,255,255,127, + 252,252,252,28,0,0,0,0,255,239,255,255,127,255,255,183,255,63,255,63,0,0,0,0, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,255,255,255,31,255,255,255,255,255,255,1,0,0,0,0, + 0,255,255,255,255,0,224,255,255,255,7,255,255,255,255,255,7,255,255,255,63, + 255,255,255,255,15,255,62,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,63,255,3,255,255,255,255,15,255,255,255, + 255,15,255,255,255,255,255,0,255,255,255,255,255,255,15,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,255,255,255,255,255,255,127,0,255,255,63,0,255,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,63,253,255,255,255,255,191,145,255,255,63,0,255,255, + 127,0,255,255,255,127,0,0,0,0,0,0,0,0,255,255,55,0,255,255,63,0,255,255,255,3, + 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,192,0,0,0,0,0,0,0,0,111,240,239, + 254,255,255,63,0,0,0,0,0,255,255,255,31,255,255,255,31,0,0,0,0,255,254,255, + 255,31,0,0,0,255,255,255,255,255,255,63,0,255,255,63,0,255,255,7,0,255,255,3, + 0,0,0,0,0,0,0,0,0,0,0,0, + 0,255,255,255,255,255,255,255,255,255,1,0,0,0,0,0,0,255,255,255,255,255,255,7, + 0,255,255,255,255,255,255,7,0,255,255,255,255,255,0,255,3,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255, + 255,27,3,0,0,0,0,0,0,0,0,0,255,255,255,31,128,0,255,255,63,0,0,0,0,0,0,0,0,0, + 0,0,0,0,255,255,31,0,0,0,255,255,127,0,255,255,255,255,255,255,255,255,63,0,0, + 0,192,255,0,0,252,255,255,255,255,255,255,1,0,0,255,255,255,1,255,3,255,255, + 255,255,255,255,199,255,240,0,255,255,255,255,71,0,255,255,255,255,255,255, + 255,255,30,192,255,23,0,0,0,0,255,255,251,255,255,255,159,64,0,0,0,0,0,0,0,0, + 127,189,255,191,255,1,255,255,255,255,255,255,255,1,255,3,239,159,249,255,255, + 253,237,227,159,25,129,224,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,255,255,255,255,255,255,255,255,187,7,255,131,3,0,0,0,255,255,255,255,255, + 255,255,255,179,0,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255, + 255,255,255,63,127,0,0,0,63,0,0,0,0,255,255,255,255,255,255,255,127,17,0,255, + 3,0,0,0,0,255,255,255,255,255,255,63,1,255,3,0,0,0,0,0,0,255,255,255,231,255, + 7,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255, + 255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,3,0,128, + 127,242,111,255,255,255,191,153,7,0,255,3,0,0,0,0,0,0,0,0,255,252,255,255,255, + 255,255,252,26,0,0,0,255,255,255,255,255,255,231,127,0,0,255,255,255,255,255, + 255,255,255,255,32,0,0,0,0,255,255,255,255,255,255,255,1,255,253,255,255,255, + 255,127,127,1,0,255,3,0,0,252,255,255,255,252,255,255,254,127,0,0,0,0,0,0,0,0, + 0,127,251,255,255,255,255,127,180,203,0,255,3,191,253,255,255,255,127,123,1, + 255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, + 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,3,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255, + 255,127,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,255,255,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,255,255,255,255,255,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0, + 0,255,255,255,255,255,255,255,1,255,255,255,127,255,3,0,0,0,0,0,0,0,0,0,0,0,0, + 255,255,255,63,0,0,255,255,255,255,255,255,0,0,15,0,255,3,248,255,255,224,255, + 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255, + 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,135, + 255,255,255,255,255,255,255,128,255,255,0,0,0,0,0,0,0,0,11,0,3,0,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,0,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,63,0,0,0,0,0, + 255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255, + 127,0,0,0,0,0,0,7,0,240,0,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,15,255,255,255,255,255, + 255,255,255,255,255,255,255,255,7,255,31,255,1,255,67,0,0,0,0,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,255,255,255,255,223,255,255,255,255,255,255,255,255, + 223,100,222,255,235,239,255,255,255,255,255,255,255,191,231,223,223,255,255, + 255,123,95,252,253,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,63,255,255,255,253,255,255,247,255,255,255, + 247,255,255,223,255,255,255,223,255,255,127,255,255,255,127,255,255,255,253, + 255,255,255,253,255,255,247,207,255,255,255,255,255,255,127,255,255,249,219,7, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,31, + 128,63,255,67,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,15,255, + 3,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,31,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,143,8, + 255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,239,255,255,255,150,254,247,10, + 132,234,150,170,150,247,247,94,255,251,255,15,238,251,255,15,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,255,255,255,3,255,255,255,3,255,255,255,3,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,3 +]); + +// size: 1568 bytes (compressed to ~1380 bytes after binaryen) +// @ts-ignore: decorator +@lazy @inline const CASED = memory.data([ + 18,19,20,21,22,23,16,16,16,16,16,16,16,16,16,16, + 24,16,16,25,16,16,16,16,16,16,16,16,26,27,17,28, + 29,30,16,16,31,16,16,16,16,16,16,16,32,33,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,34,35,16,16,16,36,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,37,16,16,16,38, + 16,16,16,16,39,16,16,16,16,16,16,16,40,16,16,16, + 16,16,16,16,16,16,16,16,41,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,42,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,43,44,45,46,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,47,16,16,16,16,16,16, + 16,48,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 0,0,0,0,0,0,0,0,254,255,255,7,254,255,255,7,0,0,0,0,0,4,32,4, + 255,255,127,255,255,255,127,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,247,240,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,239,255,255,255,255,1,3,0,0,0,31,0,0,0, + 0,0,0,0,0,0,0,0,32,0,0,0,0,0,207,188,64,215,255,255,251,255,255,255, + 255,255,255,255,255,255,191,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 3,252,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255, + 255,255,127,0,255,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255, + 191,32,255,255,255,255,255,231,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,255,255,255,255,255,255,255,255,255,255,63,63,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,255,1,255,255,255,255,255,231,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 0,0,0,0,0,0,0,0,255,255,63,63,255,255,255,255,63,63,255,170,255,255,255,63, + 255,255,255,255,255,255,223,95,220,31,207,15,255,31,220,31,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,2,128,0,0,255,31,0,0,0,0,0,0,0,0,0,0,0,0, + 132,252,47,62,80,189,31,242,224,67,0,0,255,255,255,255,24,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,192,255,255,255,255,255,255,3,0,0,255,255,255,255,255,127,255,255, + 255,255,255,127,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,120,12,0, + 255,255,255,255,191,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,63,0,0, + 255,255,255,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252,255,255,255, + 255,255,255,255,255,255,255,255,255,120,255,255,255,255,255,255,252,7,0,0,0,0,96,7, + 0,0,0,0,0,0,255,255,255,255,255,247,255,1,255,255,255,255,255,255,255,255,255,255, + 0,0,0,0,0,0,0,0,127,0,248,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,255,255,7, + 254,255,255,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,255,255, + 255,255,15,255,255,255,255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,7,0,255,255,255,255,255,255,7,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,0,0,0,0, + 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,223,255,255,255,255,255, + 255,255,255,223,100,222,255,235,239,255,255,255,255,255,255,255,191,231,223,223,255,255,255,123, + 95,252,253,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,63,255,255,255, + 253,255,255,247,255,255,255,247,255,255,223,255,255,255,223,255,255,127,255,255,255,127,255,255, + 255,253,255,255,255,253,255,255,247,15,0,0,0,0,0,0,255,255,255,255,255,255,255,255, + 15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,255,255,255,3,255,255,255,3,255,255,255,3,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0 +]); + +// size: 2976 bytes (compressed to ~2050 bytes after binaryen) +// @ts-ignore: decorator +@lazy @inline const CASE_IGNORABLES = memory.data([ + 18,16,19,20,21,22,23,24,25,26,27,28,29,30,31,32, + 33,16,16,34,16,16,16,35,36,37,38,39,40,41,16,42, + 43,16,16,16,16,16,16,16,16,16,16,16,44,45,46,16, + 47,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 48,16,16,16,49,16,50,51,52,53,54,55,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,56,16,16,57,58, + 16,59,60,61,16,16,16,16,16,16,62,16,16,63,64,65, + 66,67,68,69,70,71,72,73,74,75,76,16,77,78,79,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,80,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,81,82,16,16,16,83, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,84,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,85,86,16,16,16,16,16,16,16,87,16,16,16,16,16, + 88,89,90,16,16,16,16,16,91,92,16,16,16,16,16,16, + 16,16,16,93,16,16,16,16,16,16,16,16,16,16,16,16, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 0,0,0,0,128,64,0,4,0,0,0,64,1,0,0,0,0,0,0,0,0,161,144,1, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, + 255,255,255,255,255,255,48,4,176,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,248,3,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,130,0,0,0,0, + 0,0,254,255,255,255,255,191,182,0,0,0,0,0,16,0,63,0,255,23,0,0,0,0, + 1,248,255,255,0,0,1,0,0,0,0,0,0,0,0,0,0,0,192,191,255,61,0,0, + 0,128,2,0,0,0,255,255,255,7,0,0,0,0,0,0,0,0,0,0,192,255,1,0, + 0,0,0,0,0,248,63,36,0,0,192,255,255,63,0,0,0,0,0,14,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,248,255,255,255,255,255,7,0,0,0,0,0,0,20, + 254,33,254,0,12,0,2,0,2,0,0,0,0,0,0,16,30,32,0,0,12,0,0,64, + 6,0,0,0,0,0,0,16,134,57,2,0,0,0,35,0,6,0,0,0,0,0,0,16, + 190,33,0,0,12,0,0,252,2,0,0,0,0,0,0,144,30,32,96,0,12,0,0,0, + 4,0,0,0,0,0,0,0,1,32,0,0,0,0,0,0,17,0,0,0,0,0,0,192, + 193,61,96,0,12,0,0,0,2,0,0,0,0,0,0,144,64,48,0,0,12,0,0,0, + 3,0,0,0,0,0,0,24,30,32,0,0,12,0,0,0,2,0,0,0,0,0,0,0, + 0,4,92,0,0,0,0,0,0,0,0,0,0,0,242,7,192,127,0,0,0,0,0,0, + 0,0,0,0,0,0,242,31,64,63,0,0,0,0,0,0,0,0,0,3,0,0,160,2, + 0,0,0,0,0,0,254,127,223,224,255,254,255,255,255,31,64,0,0,0,0,0,0,0, + 0,0,0,0,0,224,253,102,0,0,0,195,1,0,30,0,100,32,0,32,0,0,0,0, + 0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,224,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,0,0,0,28,0, + 0,0,12,0,0,0,12,0,0,0,0,0,0,0,176,63,64,254,143,32,0,0,0,0, + 0,120,0,0,0,0,0,0,8,0,0,0,0,0,0,0,96,0,0,0,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,135,1,4,14,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,9,0,0,0,0, + 0,0,64,127,229,31,248,159,0,0,0,0,128,0,255,255,1,0,0,0,0,0,0,0, + 15,0,0,0,0,0,208,23,4,0,0,0,0,248,15,0,3,0,0,0,60,59,0,0, + 0,0,0,0,64,163,3,0,0,0,0,0,0,240,207,0,0,0,0,0,0,0,0,63, + 0,0,0,0,0,0,0,0,0,0,247,255,253,33,16,3,0,0,0,0,0,240,255,255, + 255,255,255,255,255,7,0,1,0,0,0,248,255,255,255,255,255,255,255,255,255,255,255,251, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160, + 3,224,0,224,0,224,0,96,0,248,0,3,144,124,0,0,0,0,0,0,223,255,2,128, + 0,0,255,31,0,0,0,0,0,0,255,255,255,255,1,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,0,0,0,128,3,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,128,0,0,0,0,0,0,0,0, + 0,0,0,0,255,255,255,255,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,60,62,8, + 0,0,0,0,0,0,0,0,0,0,0,126,0,0,0,0,0,0,0,0,0,0,0,112, + 0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,63,0,16,0,0,0,0,0,0, + 0,0,0,0,0,128,247,191,0,0,0,240,0,0,0,0,0,0,0,0,0,0,3,0, + 255,255,255,255,3,0,0,0,0,0,0,0,0,0,1,0,0,7,0,0,0,0,0,0, + 0,0,0,0,0,0,0,3,68,8,0,0,96,16,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,48,0,0,0,255,255,3,128,0,0,0,0,192,63,0,0, + 128,255,3,0,0,0,0,0,7,0,0,0,0,0,200,51,0,128,0,0,96,0,0,0, + 0,0,0,0,0,126,102,0,8,16,0,0,0,0,1,16,0,0,0,0,0,0,157,193, + 2,0,0,32,0,48,88,0,0,0,0,0,0,0,0,0,0,0,0,248,0,14,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,32,33,0,0,0,0,0,64,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,252,255,3,0,0,0,0,0,0,0, + 255,255,8,0,255,255,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,128,128,64,0,4,0,0,0,64,1,0,0,0,0,0,1,0, + 0,0,0,192,0,0,0,0,0,0,0,0,8,0,0,14,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,7, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,110,240,0,0,0,0,0,135, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,96,0,0,0, + 0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 192,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 2,0,0,0,0,0,0,255,127,0,0,0,0,0,0,128,3,0,0,0,0,0,120,38, + 0,32,0,0,0,0,0,0,7,0,0,0,128,239,31,0,0,0,0,0,0,0,8,0, + 3,0,0,0,0,0,192,127,0,158,0,0,0,0,0,0,0,0,0,0,0,128,211,64, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,248,7,0,0, + 3,0,0,0,0,0,0,24,1,0,0,0,192,31,31,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,92,0,0,64,0,0,0,0, + 0,0,0,0,0,0,248,133,13,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,60,176,1,0,0,48,0,0,0,0, + 0,0,0,0,0,0,248,167,1,0,0,0,0,0,0,0,0,0,0,0,0,40,191,0, + 0,0,0,0,0,0,0,0,0,0,0,224,188,15,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,255,6, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,88,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,240,12,1,0,0,0,254,7,0,0,0,0,248,121,128,0,126,14,0,0,0,0, + 0,252,127,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,127,191, + 0,0,0,0,0,0,0,0,0,0,252,255,255,252,109,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,126,180,191,0,0,0,0,0,0,0,0,0,163,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,255,1, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,31,0,0,0,0,0,0,0,127,0,15,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,128,0,0,0,0,0,0,0,128,255,255,0,0,0,0,0,0,0,0,27,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,96,15,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,3,248,255, + 231,15,0,0,0,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 28,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 255,255,255,255,255,255,127,248,255,255,255,255,255,31,32,0,16,0,0,248,254,255,0,0, + 0,0,0,0,0,0,0,0,127,255,255,249,219,7,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,63, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0, + 240,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,248 +]); + +// @ts-ignore: decorator +@lazy @inline const LOWER127 = memory.data([ + 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, + 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31, + 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47, + 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63, + 64, + 97,98,99,100,101,102,103,104,105,106,107,108,109, + 110,111,112,113,114,115,116,117,118,119,120,121,122, + 91,92,93,94,95,96, + 97,98,99,100,101,102,103,104,105,106,107,108,109, + 110,111,112,113,114,115,116,117,118,119,120,121,122, + 123,124,125,126,127 +]); + +// @ts-ignore: decorator +@lazy @inline const UPPER127 = memory.data([ + 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, + 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31, + 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47, + 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63, + 64, + 65,66,67,68,69,70,71,72,73,74,75,76,77, + 78,79,80,81,82,83,84,85,86,87,88,89,90, + 91,92,93,94,95,96, + 65,66,67,68,69,70,71,72,73,74,75,76,77, + 78,79,80,81,82,83,84,85,86,87,88,89,90, + 123,124,125,126,127 +]); + +// 23 * 8 = 184 bytes +// @ts-ignore: decorator +@lazy @inline const POWERS10 = memory.data([ + 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + 1e20, 1e21, 1e22 +]); + +// @ts-ignore: decorator +@inline +export const enum CharCode { + PERCENT = 0x25, + PLUS = 0x2B, + MINUS = 0x2D, + DOT = 0x2E, + _0 = 0x30, + _1 = 0x31, + _2 = 0x32, + _3 = 0x33, + _4 = 0x34, + _5 = 0x35, + _6 = 0x36, + _7 = 0x37, + _8 = 0x38, + _9 = 0x39, + A = 0x41, + B = 0x42, + E = 0x45, + I = 0x49, + N = 0x4E, + O = 0x4F, + X = 0x58, + Z = 0x5A, + a = 0x61, + b = 0x62, + e = 0x65, + n = 0x6E, + o = 0x6F, + u = 0x75, + x = 0x78, + z = 0x7A +} + +// @ts-ignore: decorator +@inline +export function isAscii(c: u32): bool { + return !(c >> 7); +} + +// @ts-ignore: decorator +@inline +export function isLower8(c: u32): bool { + return c - CharCode.a < 26; +} + +// @ts-ignore: decorator +@inline +export function isUpper8(c: u32): bool { + return c - CharCode.A < 26; +} + +export function isSpace(c: u32): bool { + if (c < 0x1680) { // < (1) + // , , , , , and + // (c == 0x20 || c == 0xA0) was optimized to (c | 0x80) == 0xA0 + return ((c | 0x80) == 0xA0) || (c - 0x09 <= 0x0D - 0x09); + } + if (c - 0x2000 <= 0x200A - 0x2000) return true; + switch (c) { + case 0x1680: // (1) + case 0x2028: // (2) + case 0x2029: // + case 0x202F: // + case 0x205F: // + case 0x3000: // + case 0xFEFF: return true; // + } + return false; +} + +export function isAlpha(c: u32): bool { + if (isAscii(c)) return (c | 32) - CharCode.a < 26; + if (c < 0x20000) { + // @ts-ignore: cast + return stagedBinaryLookup(ALPHA_TABLE, c); + } + return c < 0x2FFFE; +} + +// @ts-ignore: decorator +@inline +export function isCased(c: u32): bool { + // @ts-ignore: cast + return c < 0x1F18A && stagedBinaryLookup(CASED, c); +} + +// @ts-ignore: decorator +@inline +export function isCaseIgnorable(c: u32): bool { + // @ts-ignore: cast + return c < 0xE01F0 && stagedBinaryLookup(CASE_IGNORABLES, c); +} + +// @ts-ignore: decorator +@inline +export function isFinalSigma(buffer: usize, index: isize, len: isize): bool { + const lookaheadLimit = 30; // max lookahead limit + var found = false; + var pos = index; + var minPos = max(0, pos - lookaheadLimit); + while (pos > minPos) { + let c = codePointBefore(buffer, pos); + if (!isCaseIgnorable(c)) { + if (isCased(c)) { + found = true; + } else { + return false; + } + } + pos -= isize(c >= 0x10000) + 1; + } + if (!found) return false; + pos = index + 1; + var maxPos = min(pos + lookaheadLimit, len); + while (pos < maxPos) { + let c = load(buffer + (pos << 1)); + if (u32((c & 0xFC00) == 0xD800) & u32(pos + 1 != len)) { + let c1 = load(buffer + (pos << 1), 2); + if ((c1 & 0xFC00) == 0xDC00) { + c = (c - 0xD800 << 10) + (c1 - 0xDC00) + 0x10000; + } + } + if (!isCaseIgnorable(c)) { + return !isCased(c); + } + pos += isize(c >= 0x10000) + 1; + } + return true; +} + +// @ts-ignore: decorator +@inline +function codePointBefore(buffer: usize, index: isize): i32 { + if (index <= 0) return -1; + var c = load(buffer + (index - 1 << 1)); + if (u32((c & 0xFC00) == 0xDC00) & u32(index - 2 >= 0)) { + let c1 = load(buffer + (index - 2 << 1)); + if ((c1 & 0xFC00) == 0xD800) { + return ((c1 & 0x3FF) << 10) + (c & 0x3FF) + 0x10000; + } + } + return (c & 0xF800) == 0xD800 ? 0xFFFD : c; +} + +// Search routine for two-staged lookup tables +function stagedBinaryLookup(table: usize, c: u32): bool { + return ((load(table + (load(table + (c >>> 8)) << 5) + ((c & 255) >> 3)) >>> (c & 7)) & 1); +} + +export function compareImpl(str1: string, index1: usize, str2: string, index2: usize, len: usize): i32 { + var ptr1 = changetype(str1) + (index1 << 1); + var ptr2 = changetype(str2) + (index2 << 1); + if (ASC_SHRINK_LEVEL < 2) { + if (len >= 4 && !((ptr1 & 7) | (ptr2 & 7))) { + do { + if (load(ptr1) != load(ptr2)) break; + ptr1 += 8; + ptr2 += 8; + len -= 4; + } while (len >= 4); + } + } + while (len--) { + let a = load(ptr1); + let b = load(ptr2); + if (a != b) return a - b; + ptr1 += 2; + ptr2 += 2; + } + return 0; +} + +// @ts-ignore: decorator +@inline +export function toLower8(c: u32): u32 { + if (ASC_SHRINK_LEVEL > 0) { + return c | u32(isUpper8(c)) << 5; + } else { + return load(LOWER127 + c); + } +} + +// @ts-ignore: decorator +@inline +export function toUpper8(c: u32): u32 { + if (ASC_SHRINK_LEVEL > 0) { + return c & ~(u32(isLower8(c)) << 5); + } else { + return load(UPPER127 + c); + } +} + +/** Parses a string to an integer (usually), using the specified radix. */ +export function strtol(str: string, radix: i32 = 0): T { + var len = str.length; + if (!len) { + if (isFloat()) { + // @ts-ignore: cast + return NaN; + } else { + // @ts-ignore: cast + return 0; + } + } + + var ptr = changetype(str) /* + HEAD -> offset */; + var code = load(ptr); + + // trim white spaces + while (isSpace(code)) { + code = load(ptr += 2); + --len; + } + // determine sign + // @ts-ignore + var sign: T = 1; + if (code == CharCode.MINUS || code == CharCode.PLUS) { + if (!--len) { + if (isFloat()) { + // @ts-ignore: cast + return NaN; + } else { + // @ts-ignore: cast + return 0; + } + } + if (code == CharCode.MINUS) { + // @ts-ignore: type + sign = -1; + } + code = load(ptr += 2); + } + + // See https://tc39.es/ecma262/#sec-parseint-string-radix + if (radix) { + if (radix < 2 || radix > 36) { + if (isFloat()) { + // @ts-ignore: cast + return NaN; + } else { + // @ts-ignore: cast + return 0; + } + } + // handle case as parseInt("0xFF", 16) by spec + if (radix == 16) { + if ( + len > 2 && + code == CharCode._0 && + (load(ptr, 2) | 32) == CharCode.x + ) { + ptr += 4; len -= 2; + } + } + } else { + // determine radix by literal prefix + if (code == CharCode._0 && len > 2) { + switch (load(ptr, 2) | 32) { + case CharCode.b: { + ptr += 4; len -= 2; + radix = 2; + break; + } + case CharCode.o: { + ptr += 4; len -= 2; + radix = 8; + break; + } + case CharCode.x: { + ptr += 4; len -= 2; + radix = 16; + break; + } + } + } + if (!radix) radix = 10; + } + + // calculate value + // @ts-ignore: type + var num: T = 0; + var initial = len - 1; + while (len--) { + code = load(ptr); + if (code - CharCode._0 < 10) { + code -= CharCode._0; + } else if (code - CharCode.A <= (CharCode.Z - CharCode.A)) { + code -= CharCode.A - 10; + } else if (code - CharCode.a <= (CharCode.z - CharCode.a)) { + code -= CharCode.a - 10; + } + if (code >= radix) { + if (initial == len) { + if (isFloat()) { + // @ts-ignore: cast + return NaN; + } else { + // @ts-ignore: cast + return 0; + } + } + break; + } + // @ts-ignore: type + num = num * radix + code; + ptr += 2; + } + // @ts-ignore: type + return sign * num; +} + +export function strtod(str: string): f64 { + var len = str.length; + if (!len) return NaN; + + var ptr = changetype(str); + var code = load(ptr); + + var sign = 1.0; + // skip white spaces + while (len && isSpace(code)) { + code = load(ptr += 2); + --len; + } + if (!len) return NaN; + + // try parse '-' or '+' + if (code == CharCode.MINUS) { + if (!--len) return NaN; + code = load(ptr += 2); + sign = -1; + } else if (code == CharCode.PLUS) { + if (!--len) return NaN; + code = load(ptr += 2); + } + + // try parse Infinity + if (len >= 8 && code == CharCode.I) { + if ( + load(ptr, 0) == 0x690066006E0049 && // ifnI + load(ptr, 8) == 0x7900740069006E // ytin + ) { + return Infinity * sign; + } + return NaN; + } + // validate next symbol + if (code != CharCode.DOT && (code - CharCode._0) >= 10) { + return NaN; + } + var savedPtr = ptr; + // skip zeros + while (code == CharCode._0) { + code = load(ptr += 2); + --len; + } + if (len <= 0) return 0; + const capacity = 19; // int(64 * 0.3010) + var pointed = false; + var consumed = 0; + var position = 0; + var x: u64 = 0; + if (code == CharCode.DOT) { + let noDigits = !(savedPtr - ptr); + ptr += 2; --len; + if (!len && noDigits) return NaN; + for (pointed = true; (code = load(ptr)) == CharCode._0; --position, ptr += 2) --len; + if (len <= 0) return 0; + if (!position && noDigits && code - CharCode._0 >= 10) return NaN; + } + for (let digit = code - CharCode._0; digit < 10 || (code == CharCode.DOT && !pointed); digit = code - CharCode._0) { + if (digit < 10) { + x = consumed < capacity ? 10 * x + digit : x | u64(!!digit); + ++consumed; + } else { + position = consumed; + pointed = true; + } + if (!--len) break; + code = load(ptr += 2); + } + + if (!pointed) position = consumed; + return copysign(scientific(x, position - min(capacity, consumed) + parseExp(ptr, len)), sign); +} + +export function joinBooleanArray(dataStart: usize, length: i32, separator: string): string { + var lastIndex = length - 1; + if (lastIndex < 0) return ""; + if (!lastIndex) return select("true", "false", load(dataStart)); + + var sepLen = separator.length; + var valueLen = 5; // max possible length of element len("false") + var estLen = (valueLen + sepLen) * lastIndex + valueLen; + var result = changetype(__new(estLen << 1, idof())); + var offset = 0; + var value: bool; + for (let i = 0; i < lastIndex; ++i) { + value = load(dataStart + i); + valueLen = 4 + i32(!value); + memory.copy( + changetype(result) + (offset << 1), + changetype(select("true", "false", value)), + valueLen << 1 + ); + offset += valueLen; + if (sepLen) { + memory.copy( + changetype(result) + (offset << 1), + changetype(separator), + sepLen << 1 + ); + offset += sepLen; + } + } + value = load(dataStart + lastIndex); + valueLen = 4 + i32(!value); + memory.copy( + changetype(result) + (offset << 1), + changetype(select("true", "false", value)), + valueLen << 1 + ); + offset += valueLen; + + if (estLen > offset) return result.substring(0, offset); + return result; +} + +export function joinIntegerArray(dataStart: usize, length: i32, separator: string): string { + var lastIndex = length - 1; + if (lastIndex < 0) return ""; + if (!lastIndex) { + let value = load(dataStart); + if (isSigned()) { + if (sizeof() <= 4) { + // @ts-ignore: type + return changetype(itoa32(value, 10)); + } else { + // @ts-ignore: type + return changetype(itoa64(value, 10)); + } + } else { + if (sizeof() <= 4) { + // @ts-ignore: type + return changetype(utoa32(value, 10)); + } else { + // @ts-ignore: type + return changetype(utoa64(value, 10)); + } + } + } + + var sepLen = separator.length; + const valueLen = (sizeof() <= 4 ? 10 : 20) + i32(isSigned()); + var estLen = (valueLen + sepLen) * lastIndex + valueLen; + var result = changetype(__new(estLen << 1, idof())); + var offset = 0; + var value: T; + for (let i = 0; i < lastIndex; ++i) { + value = load(dataStart + (i << alignof())); + // @ts-ignore: type + offset += itoa_buffered(changetype(result) + (offset << 1), value); + if (sepLen) { + memory.copy( + changetype(result) + (offset << 1), + changetype(separator), + sepLen << 1 + ); + offset += sepLen; + } + } + value = load(dataStart + (lastIndex << alignof())); + // @ts-ignore: type + offset += itoa_buffered(changetype(result) + (offset << 1), value); + if (estLen > offset) return result.substring(0, offset); + return result; +} + +export function joinFloatArray(dataStart: usize, length: i32, separator: string): string { + var lastIndex = length - 1; + if (lastIndex < 0) return ""; + if (!lastIndex) { + return changetype(dtoa( + // @ts-ignore: type + load(dataStart)) + ); + } + + const valueLen = MAX_DOUBLE_LENGTH; + var sepLen = separator.length; + var estLen = (valueLen + sepLen) * lastIndex + valueLen; + var result = changetype(__new(estLen << 1, idof())); + var offset = 0; + var value: T; + for (let i = 0; i < lastIndex; ++i) { + value = load(dataStart + (i << alignof())); + // @ts-ignore: type + offset += dtoa_buffered(changetype(result) + (offset << 1), value); + if (sepLen) { + memory.copy( + changetype(result) + (offset << 1), + changetype(separator), + sepLen << 1 + ); + offset += sepLen; + } + } + value = load(dataStart + (lastIndex << alignof())); + // @ts-ignore: type + offset += dtoa_buffered(changetype(result) + (offset << 1), value); + if (estLen > offset) return result.substring(0, offset); + return result; +} + +export function joinStringArray(dataStart: usize, length: i32, separator: string): string { + var lastIndex = length - 1; + if (lastIndex < 0) return ""; + if (!lastIndex) { + // @ts-ignore: type + return load(dataStart) || ""; + } + var estLen = 0; + var value: string; + for (let i = 0; i < length; ++i) { + value = load(dataStart + (i << alignof())); + if (changetype(value) != 0) estLen += value.length; + } + var offset = 0; + var sepLen = separator.length; + var result = changetype(__new((estLen + sepLen * lastIndex) << 1, idof())); + for (let i = 0; i < lastIndex; ++i) { + value = load(dataStart + (i << alignof())); + if (changetype(value) != 0) { + let valueLen = value.length; + memory.copy( + changetype(result) + (offset << 1), + changetype(value), + valueLen << 1 + ); + offset += valueLen; + } + if (sepLen) { + memory.copy( + changetype(result) + (offset << 1), + changetype(separator), + sepLen << 1 + ); + offset += sepLen; + } + } + value = load(dataStart + (lastIndex << alignof())); + if (changetype(value) != 0) { + memory.copy( + changetype(result) + (offset << 1), + changetype(value), + value.length << 1 + ); + } + return result; +} + +export function joinReferenceArray(dataStart: usize, length: i32, separator: string): string { + var lastIndex = length - 1; + if (lastIndex < 0) return ""; + var value: T; + if (!lastIndex) { + value = load(dataStart); + // @ts-ignore: type + return value != null ? value.toString() : ""; + } + var result = ""; + var sepLen = separator.length; + for (let i = 0; i < lastIndex; ++i) { + value = load(dataStart + (i << alignof())); + // @ts-ignore: type + if (value != null) result += value.toString(); + if (sepLen) result += separator; + } + value = load(dataStart + (lastIndex << alignof())); + // @ts-ignore: type + if (value != null) result += value.toString(); + return result; +} + +// @ts-ignore: decorator +@inline +function scientific(significand: u64, exp: i32): f64 { + if (!significand || exp < -342) return 0; + if (exp > 308) return Infinity; + // Try use fast path + // Use fast path for string-to-double conversion if possible + // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion + // Simple integer + var significandf = significand; + if (!exp) return significandf; + if (exp > 22 && exp <= 22 + 15) { + significandf *= pow10(exp - 22); + exp = 22; + } + if (significand <= 9007199254740991 && abs(exp) <= 22) { + if (exp > 0) return significandf * pow10(exp); + return significandf / pow10(-exp); + } else if (exp < 0) { + return scaledown(significand, exp); + } else { + return scaleup(significand, exp); + } +} + +// Adopted from metallic lib: +// https://github.com/jdh8/metallic/blob/master/src/stdlib/parse/scientific.h +// @ts-ignore: decorator +@inline +function scaledown(significand: u64, exp: i32): f64 { + const denom: u64 = 6103515625; // 1e14 * 0x1p-14 + const scale = reinterpret(0x3F06849B86A12B9B); // 1e-14 * 0x1p32 + + var shift = clz(significand); + significand <<= shift; + shift = exp - shift; + + for (; exp <= -14; exp += 14) { + let q = significand / denom; + let r = significand % denom; + let s = clz(q); + significand = (q << s) + nearest(scale * (r << (s - 18))); + shift -= s; + } + var b = ipow32(5, -exp); + var q = significand / b; + var r = significand % b; + var s = clz(q); + significand = (q << s) + (reinterpret(reinterpret(r) + (s << 52)) / b); + shift -= s; + + return NativeMath.scalbn(significand, shift); +} + +// Adopted from metallic lib: +// https://github.com/jdh8/metallic/blob/master/src/stdlib/parse/scientific.h +// @ts-ignore: decorator +@inline +function scaleup(significand: u64, exp: i32): f64 { + const coeff: u32 = 1220703125; // 1e13 * 0x1p-13; + var shift = ctz(significand); + significand >>= shift; + shift += exp; + + __fixmulShift = shift; + for (; exp >= 13; exp -= 13) { + significand = fixmul(significand, coeff); + } + significand = fixmul(significand, ipow32(5, exp)); + shift = __fixmulShift; + return NativeMath.scalbn(significand, shift); +} + +// Adopted from metallic lib: +// https://github.com/jdh8/metallic/blob/master/src/stdlib/parse/scientific.h +// @ts-ignore: decorator +@inline +function parseExp(ptr: usize, len: i32): i32 { + var sign = 1, magnitude = 0; + var code = load(ptr); + // check code is 'e' or 'E' + if ((code | 32) != CharCode.e) return 0; + + if (!--len) return 0; + code = load(ptr += 2); + if (code == CharCode.MINUS) { + if (!--len) return 0; + code = load(ptr += 2); + sign = -1; + } else if (code == CharCode.PLUS) { + if (!--len) return 0; + code = load(ptr += 2); + } + // skip zeros + while (code == CharCode._0) { + if (!--len) return 0; + code = load(ptr += 2); + } + for (let digit: u32 = code - CharCode._0; len && digit < 10; digit = code - CharCode._0) { + if (magnitude >= 3200) return sign * 3200; + magnitude = 10 * magnitude + digit; + code = load(ptr += 2); + --len; + } + return sign * magnitude; +} + +// @ts-ignore: decorator +@lazy var __fixmulShift: u64 = 0; + +// Adopted from metallic lib: +// https://github.com/jdh8/metallic/blob/master/src/stdlib/parse/scientific.h +// @ts-ignore: decorator +@inline +function fixmul(a: u64, b: u32): u64 { + var low = (a & 0xFFFFFFFF) * b; + var high = (a >> 32) * b + (low >> 32); + var overflow = (high >> 32); + var space = clz(overflow); + var revspace: u64 = 32 - space; + __fixmulShift += revspace; + return (high << space | (low & 0xFFFFFFFF) >> revspace) + (low << space >> 31 & 1); +} + +// @ts-ignore: decorator +@inline +function pow10(n: i32): f64 { + // argument \`n\` should bounds in [0, 22] range + return load(POWERS10 + (n << alignof())); +} +`,"util/uri":`import { E_URI_MALFORMED } from "./error"; +import { CharCode } from "./string"; + +// Truncated lookup boolean table that helps us quickly determine +// if a char needs to be escaped for URIs (RFC 2396). +// @ts-ignore: decorator +@lazy export const URI_UNSAFE = memory.data([ +/* skip 32 + 1 always set to '1' head slots + */ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* + skip 128 + 1 always set to '1' tail slots */ +]); + +// Truncated lookup boolean table that helps us quickly determine +// if a char needs to be escaped for URLs (RFC 3986). +// @ts-ignore: decorator +@lazy export const URL_UNSAFE = memory.data([ +/* skip 32 + 1 always set to '1' head slots + */ 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* + skip 128 + 1 always set to '1' tail slots */ +]); + +// Truncated lookup boolean table for determine reserved chars: ;/?:@&=+$,# +// @ts-ignore: decorator +@lazy export const URI_RESERVED = memory.data([ + /* skip 32 + 3 always set to '0' head slots + */ 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, + 1, /* skip 191 always set to '0' tail slots */ +]); + +export function encode(src: usize, len: usize, table: usize): usize { + if (!len) return src; + + var i: usize = 0, offset: usize = 0, outSize = len << 1; + var dst = __new(outSize, idof()); + + while (i < len) { + let org = i; + let c: u32, c1: u32; + // fast scan a check chars until it valid ASCII + // and safe for copying withoud escaping. + do { + c = load(src + (i << 1)); + // is it valid ASII and safe? + if (c - 33 < 94) { // 127 - 33 + if (load(table + (c - 33))) break; + } else break; + } while (++i < len); + + // if we have some safe range of sequence just copy it without encoding + if (i > org) { + let size = i - org << 1; + if (offset + size > outSize) { + outSize = offset + size; + dst = __renew(dst, outSize); + } + // TODO: should we optimize for short cases like 2 byte size? + memory.copy( + dst + offset, + src + (org << 1), + size + ); + offset += size; + // return if we reach end on input string + if (i >= len) break; + } + + // decode UTF16 with checking for unpaired surrogates + if (c >= 0xD800) { + if (c >= 0xDC00 && c <= 0xDFFF) { + throw new URIError(E_URI_MALFORMED); + } + if (c <= 0xDBFF) { + if (i >= len) { + throw new URIError(E_URI_MALFORMED); + } + c1 = load(src + (++i << 1)); + if (c1 < 0xDC00 || c1 > 0xDFFF) { + throw new URIError(E_URI_MALFORMED); + } + c = (((c & 0x3FF) << 10) | (c1 & 0x3FF)) + 0x10000; + } + } + + let estSize = offset + (c < 0x80 ? 1 * 6 : 4 * 6); + if (estSize > outSize) { + // doubling estimated size but only for greater than one + // input lenght due to we already estemated it for worst case + outSize = len > 1 ? estSize << 1 : estSize; + dst = __renew(dst, outSize); + } + + if (c < 0x80) { + // encode ASCII unsafe code point + storeHex(dst, offset, c); + offset += 6; + } else { + // encode UTF-8 unsafe code point + if (c < 0x800) { + storeHex(dst, offset, (c >> 6) | 0xC0); + offset += 6; + } else { + if (c < 0x10000) { + storeHex(dst, offset, (c >> 12) | 0xE0); + offset += 6; + } else { + storeHex(dst, offset, (c >> 18) | 0xF0); + offset += 6; + storeHex(dst, offset, (c >> 12 & 0x3F) | 0x80); + offset += 6; + } + storeHex(dst, offset, (c >> 6 & 0x3F) | 0x80); + offset += 6; + } + storeHex(dst, offset, (c & 0x3F) | 0x80); + offset += 6; + } + ++i; + } + // shink output string buffer if necessary + if (outSize > offset) { + dst = __renew(dst, offset); + } + return dst; +} + +export function decode(src: usize, len: usize, component: bool): usize { + if (!len) return src; + + var i: usize = 0, offset: usize = 0, ch: u32 = 0; + var dst = __new(len << 1, idof()); + + while (i < len) { + let org = i; + while (i < len && (ch = load(src + (i << 1))) != CharCode.PERCENT) i++; + + if (i > org) { + let size = i - org << 1; + // TODO: should we optimize for short cases like 2 byte size? + memory.copy( + dst + offset, + src + (org << 1), + size + ); + offset += size; + if (i >= len) break; + } + + // decode hex + if ( + i + 2 >= len || + ch != CharCode.PERCENT || + (ch = loadHex(src, i + 1 << 1)) == -1 + ) throw new URIError(E_URI_MALFORMED); + + i += 3; + if (ch < 0x80) { + if (!component && isReserved(ch)) { + ch = CharCode.PERCENT; + i -= 2; + } + } else { + // decode UTF-8 sequence + let nb = utf8LenFromUpperByte(ch); + // minimal surrogate: 2 => 0x80, 3 => 0x800, 4 => 0x10000, _ => -1 + let lo: u32 = 1 << (17 * nb >> 2) - 1; + // mask: 2 => 31, 3 => 15, 4 => 7, _ => 0 + ch &= nb ? (0x80 >> nb) - 1 : 0; + + while (--nb != 0) { + let c1: u32; + // decode hex + if ( + i + 2 >= len || + load(src + (i << 1)) != CharCode.PERCENT || + (c1 = loadHex(src, i + 1 << 1)) == -1 + ) throw new URIError(E_URI_MALFORMED); + + i += 3; + if ((c1 & 0xC0) != 0x80) { + ch = 0; + break; + } + ch = (ch << 6) | (c1 & 0x3F); + } + + // check if UTF8 code point properly fit into invalid UTF16 encoding + if (ch < lo || lo == -1 || ch > 0x10FFFF || (ch >= 0xD800 && ch < 0xE000)) { + throw new URIError(E_URI_MALFORMED); + } + + // encode UTF16 + if (ch >= 0x10000) { + ch -= 0x10000; + let lo = ch >> 10 | 0xD800; + let hi = (ch & 0x03FF) | 0xDC00; + store(dst + offset, lo | (hi << 16)); + offset += 4; + continue; + } + } + store(dst + offset, ch); + offset += 2; + } + + assert(offset <= (len << 1)); + // shink output string buffer if necessary + if ((len << 1) > offset) { + dst = __renew(dst, offset); + } + return dst; +} + +function storeHex(dst: usize, offset: usize, ch: u32): void { + // @ts-ignore: decorator + const HEX_CHARS = memory.data([ + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46 + ]); + + store(dst + offset, CharCode.PERCENT, 0); // % + store( + dst + offset, + load(HEX_CHARS + (ch >> 4 & 0x0F)) | + load(HEX_CHARS + (ch & 0x0F)) << 16, + 2 + ); // XX +} + +function loadHex(src: usize, offset: usize): u32 { + let c0 = load(src + offset, 0); + let c1 = load(src + offset, 2); + return isHex(c0) && isHex(c1) + ? fromHex(c0) << 4 | fromHex(c1) + : -1; +} + +// @ts-ignore: decorator +@inline function fromHex(ch: u32): u32 { + return (ch | 32) % 39 - 9; +} + +// @ts-ignore: decorator +@inline function utf8LenFromUpperByte(c0: u32): u32 { + // same as + // if (c0 - 0xC0 <= 0xDF - 0xC0) return 2; + // if (c0 - 0xE0 <= 0xEF - 0xE0) return 3; + // if (c0 - 0xF0 <= 0xF7 - 0xF0) return 4; + // return 0; + return c0 - 0xC0 < 56 + ? clz(~(c0 << 24)) + : 0; +} + +// @ts-ignore: decorator +@inline function isReserved(ch: u32): bool { + return ch - 35 < 30 + ? load(URI_RESERVED + (ch - 35)) + : false; +} + +// @ts-ignore: decorator +@inline function isHex(ch: u32): bool { + return (ch - CharCode._0 < 10) || ((ch | 32) - CharCode.a < 6); +} +`,vector:`/** Vector abstraction. */ +@final @unmanaged +export abstract class V128 { +} +`,"wasi/index":`import { + proc_exit, + fd_write, + iovec, + random_get, + tempbuf +} from "bindings/wasi"; + +import { + MAX_DOUBLE_LENGTH, + decimalCount32, + dtoa_buffered +} from "util/number"; + +// @ts-ignore: decorator +@global @inline const ASC_WASI = true; // eslint-disable-line @typescript-eslint/no-unused-vars + +function abort( // eslint-disable-line @typescript-eslint/no-unused-vars + message: string | null = null, + fileName: string | null = null, + lineNumber: u32 = 0, + columnNumber: u32 = 0 +): void { + // 0: iov.buf + // 4: iov.buf_len + // 8: len + // 12: buf... + const iovPtr: usize = 0; + const lenPtr: usize = iovPtr + offsetof(); + const bufPtr: usize = lenPtr + sizeof(); + changetype(iovPtr).buf = bufPtr; + var ptr = bufPtr; + store(ptr, 0x203A74726F6261); ptr += 7; // 'abort: ' + if (message != null) { + ptr += String.UTF8.encodeUnsafe(changetype(message), message.length, ptr); + } + store(ptr, 0x206E6920); ptr += 4; // ' in ' + if (fileName != null) { + ptr += String.UTF8.encodeUnsafe(changetype(fileName), fileName.length, ptr); + } + store(ptr++, 0x28); // ( + var len = decimalCount32(lineNumber); ptr += len; + do { + let t = lineNumber / 10; + store(--ptr, 0x30 + lineNumber % 10); + lineNumber = t; + } while (lineNumber); ptr += len; + store(ptr++, 0x3A); // : + len = decimalCount32(columnNumber); ptr += len; + do { + let t = columnNumber / 10; + store(--ptr, 0x30 + columnNumber % 10); + columnNumber = t; + } while (columnNumber); ptr += len; + store(ptr, 0x0A29); ptr += 2; // )\\n + changetype(iovPtr).buf_len = ptr - bufPtr; + fd_write(2, iovPtr, 1, lenPtr); + proc_exit(255); +} + +function trace( // eslint-disable-line @typescript-eslint/no-unused-vars + message: string, + n: i32 = 0, + a0: f64 = 0, + a1: f64 = 0, + a2: f64 = 0, + a3: f64 = 0, + a4: f64 = 0 +): void { + // 0: iov.buf + // 4: iov.buf_len + // 8: len + // 12: buf... + var iovPtr = __alloc(offsetof() + sizeof() + 1 + (max(String.UTF8.byteLength(message), MAX_DOUBLE_LENGTH << 1))); + var lenPtr = iovPtr + offsetof(); + var bufPtr = lenPtr + sizeof(); + changetype(iovPtr).buf = bufPtr; + store(bufPtr, 0x203A6563617274); // 'trace: ' + changetype(iovPtr).buf_len = 7; + fd_write(2, iovPtr, 1, lenPtr); + changetype(iovPtr).buf_len = String.UTF8.encodeUnsafe(changetype(message), message.length, bufPtr); + fd_write(2, iovPtr, 1, lenPtr); + if (n) { + store(bufPtr++, 0x20); // space + changetype(iovPtr).buf_len = 1 + String.UTF8.encodeUnsafe(bufPtr, dtoa_buffered(bufPtr, a0), bufPtr); + fd_write(2, iovPtr, 1, lenPtr); + if (n > 1) { + changetype(iovPtr).buf_len = 1 + String.UTF8.encodeUnsafe(bufPtr, dtoa_buffered(bufPtr, a1), bufPtr); + fd_write(2, iovPtr, 1, lenPtr); + if (n > 2) { + changetype(iovPtr).buf_len = 1 + String.UTF8.encodeUnsafe(bufPtr, dtoa_buffered(bufPtr, a2), bufPtr); + fd_write(2, iovPtr, 1, lenPtr); + if (n > 3) { + changetype(iovPtr).buf_len = 1 + String.UTF8.encodeUnsafe(bufPtr, dtoa_buffered(bufPtr, a3), bufPtr); + fd_write(2, iovPtr, 1, lenPtr); + if (n > 4) { + changetype(iovPtr).buf_len = 1 + String.UTF8.encodeUnsafe(bufPtr, dtoa_buffered(bufPtr, a4), bufPtr); + fd_write(2, iovPtr, 1, lenPtr); + } + } + } + } + --bufPtr; + } + store(bufPtr, 0x0A); // \\n + changetype(iovPtr).buf_len = 1; + fd_write(2, iovPtr, 1, lenPtr); + __free(iovPtr); +} + +function seed(): f64 { // eslint-disable-line @typescript-eslint/no-unused-vars + var rand: u64; + do { + random_get(tempbuf, 8); + rand = load(tempbuf); + } while (!rand); + return reinterpret(rand); +} + +export * from "bindings/wasi"; +`},Ie={assembly:`/** + * Environment definitions for compiling AssemblyScript to WebAssembly using asc. + * @module std/assembly + *//***/ + +/// + +// Types + +/** An 8-bit signed integer. */ +declare type i8 = number; +/** A 16-bit signed integer. */ +declare type i16 = number; +/** A 32-bit signed integer. */ +declare type i32 = number; +/** A 64-bit signed integer. */ +declare type i64 = number; +/** A 32-bit signed integer when targeting 32-bit WebAssembly or a 64-bit signed integer when targeting 64-bit WebAssembly. */ +declare type isize = number; +/** An 8-bit unsigned integer. */ +declare type u8 = number; +/** A 16-bit unsigned integer. */ +declare type u16 = number; +/** A 32-bit unsigned integer. */ +declare type u32 = number; +/** A 64-bit unsigned integer. */ +declare type u64 = number; +/** A 32-bit unsigned integer when targeting 32-bit WebAssembly or a 64-bit unsigned integer when targeting 64-bit WebAssembly. */ +declare type usize = number; +/** A 1-bit unsigned integer. */ +declare type bool = boolean | number; +/** A 32-bit float. */ +declare type f32 = number; +/** A 64-bit float. */ +declare type f64 = number; +/** A 128-bit vector. */ +declare type v128 = object; +/** Function reference. */ +declare type funcref = object | null; +/** External reference. */ +declare type externref = object | null; +/** Any reference. */ +declare type anyref = object | null; +/** Equatable reference. */ +declare type eqref = object | null; +/** 31-bit integer reference. */ +declare type i31ref = object | null; +/** Data reference. */ +declare type dataref = object | null; + +// Compiler hints + +/** Compiler target. 0 = JS, 1 = WASM32, 2 = WASM64. */ +declare const ASC_TARGET: i32; +/** Runtime type. 0 = Stub, 1 = Minimal, 2 = Incremental. */ +declare const ASC_RUNTIME: i32; +/** Provided noAssert option. */ +declare const ASC_NO_ASSERT: bool; +/** Provided memoryBase option. */ +declare const ASC_MEMORY_BASE: i32; +/** Provided tableBase option. */ +declare const ASC_TABLE_BASE: i32; +/** Provided optimizeLevel option. */ +declare const ASC_OPTIMIZE_LEVEL: i32; +/** Provided shrinkLevel option. */ +declare const ASC_SHRINK_LEVEL: i32; +/** Provided lowMemoryLimit option. */ +declare const ASC_LOW_MEMORY_LIMIT: i32; +/** Provided noExportRuntime option. */ +declare const ASC_NO_EXPORT_RUNTIME: i32; +/** Whether the sign extension feature is enabled. */ +declare const ASC_FEATURE_SIGN_EXTENSION: bool; +/** Whether the mutable globals feature is enabled. */ +declare const ASC_FEATURE_MUTABLE_GLOBALS: bool; +/** Whether the non-trapping float-to-int feature is enabled. */ +declare const ASC_FEATURE_NONTRAPPING_F2I: bool; +/** Whether the bulk memory feature is enabled. */ +declare const ASC_FEATURE_BULK_MEMORY: bool; +/** Whether the SIMD feature is enabled. */ +declare const ASC_FEATURE_SIMD: bool; +/** Whether the threads feature is enabled. */ +declare const ASC_FEATURE_THREADS: bool; +/** Whether the exception handling feature is enabled. */ +declare const ASC_FEATURE_EXCEPTION_HANDLING: bool; +/** Whether the tail calls feature is enabled. */ +declare const ASC_FEATURE_TAIL_CALLS: bool; +/** Whether the reference types feature is enabled. */ +declare const ASC_FEATURE_REFERENCE_TYPES: bool; +/** Whether the multi value types feature is enabled. */ +declare const ASC_FEATURE_MULTI_VALUE: bool; +/** Whether the garbage collection feature is enabled. */ +declare const ASC_FEATURE_GC: bool; +/** Whether the memory64 feature is enabled. */ +declare const ASC_FEATURE_MEMORY64: bool; +/** Whether the function references feature is enabled. */ +declare const ASC_FEATURE_FUNCTION_REFERENCES: bool; +/** Whether the relaxed SIMD feature is enabled. */ +declare const ASC_FEATURE_RELAXED_SIMD: bool; +/** Whether the extended const expression feature is enabled. */ +declare const ASC_FEATURE_EXTENDED_CONST: bool; +/** Major version of the compiler. */ +declare const ASC_VERSION_MAJOR: i32; +/** Minor version of the compiler. */ +declare const ASC_VERSION_MINOR: i32; +/** Patch version of the compiler. */ +declare const ASC_VERSION_PATCH: i32; + +// Builtins + +/** Performs the sign-agnostic count leading zero bits operation on a 32-bit or 64-bit integer. All zero bits are considered leading if the value is zero. */ +declare function clz(value: T): T; +/** Performs the sign-agnostic count tailing zero bits operation on a 32-bit or 64-bit integer. All zero bits are considered trailing if the value is zero. */ +declare function ctz(value: T): T; +/** Performs the sign-agnostic count number of one bits operation on a 32-bit or 64-bit integer. */ +declare function popcnt(value: T): T; +/** Performs the sign-agnostic rotate left operation on a 32-bit or 64-bit integer. */ +declare function rotl(value: T, shift: T): T; +/** Performs the sign-agnostic rotate right operation on a 32-bit or 64-bit integer. */ +declare function rotr(value: T, shift: T): T; +/** Computes the absolute value of an integer or float. */ +declare function abs(value: T): T; +/** Determines the maximum of two integers or floats. If either operand is \`NaN\`, returns \`NaN\`. */ +declare function max(left: T, right: T): T; +/** Determines the minimum of two integers or floats. If either operand is \`NaN\`, returns \`NaN\`. */ +declare function min(left: T, right: T): T; +/** Performs the ceiling operation on a 32-bit or 64-bit float. */ +declare function ceil(value: T): T; +/** Composes a 32-bit or 64-bit float from the magnitude of \`x\` and the sign of \`y\`. */ +declare function copysign(x: T, y: T): T; +/** Performs the floor operation on a 32-bit or 64-bit float. */ +declare function floor(value: T): T; +/** Rounds to the nearest integer tied to even of a 32-bit or 64-bit float. */ +declare function nearest(value: T): T; +/** Reinterprets the bits of the specified value as type \`T\`. Valid reinterpretations are u32/i32 to/from f32 and u64/i64 to/from f64. */ +declare function reinterpret(value: number): T; +/** Selects one of two pre-evaluated values depending on the condition. */ +declare function select(ifTrue: T, ifFalse: T, condition: bool): T; +/** Calculates the square root of a 32-bit or 64-bit float. */ +declare function sqrt(value: T): T; +/** Rounds to the nearest integer towards zero of a 32-bit or 64-bit float. */ +declare function trunc(value: T): T; +/** Computes the sum of two integers or floats. */ +declare function add(left: T, right: T): T; +/** Computes the difference of two integers or floats. */ +declare function sub(left: T, right: T): T; +/** Computes the product of two integers or floats. */ +declare function mul(left: T, right: T): T; +/** Computes the quotient of two integers or floats. */ +declare function div(left: T, right: T): T; +/** Return 1 if two numbers are equal to each other, 0 otherwise. */ +declare function eq(left: T, right: T): i32; +/** Return 0 if two numbers are equal to each other, 1 otherwise. */ +declare function ne(left: T, right: T): i32; +/** Loads a value of the specified type from memory. Equivalent to dereferncing a pointer in other languages. */ +declare function load(ptr: usize, immOffset?: usize, immAlign?: usize): T; +/** Stores a value of the specified type to memory. Equivalent to dereferencing a pointer in other languages when assigning a value. */ +declare function store(ptr: usize, value: T, immOffset?: usize, immAlign?: usize): void; +/** Emits an unreachable operation that results in a runtime error when executed. Both a statement and an expression. */ +declare function unreachable(): never; + +/** NaN (not a number) as a 32-bit or 64-bit float depending on context. */ +declare const NaN: f32 | f64; +/** Positive infinity as a 32-bit or 64-bit float depending on context. */ +declare const Infinity: f32 | f64; +/** Data end offset. */ +declare const __data_end: usize; +/** Stack pointer offset. */ +declare var __stack_pointer: usize; +/** Heap base offset. */ +declare const __heap_base: usize; +/** Determines the byte size of the specified underlying core type. Compiles to a constant. */ +declare function sizeof(): usize; +/** Determines the alignment (log2) of the specified underlying core type. Compiles to a constant. */ +declare function alignof(): usize; +/** Determines the end offset of the given class type. Compiles to a constant. */ +declare function offsetof(): usize; +/** Determines the offset of the specified field within the given class type. Compiles to a constant. */ +declare function offsetof(fieldName: keyof T | string): usize; +/** Determines the offset of the specified field within the given class type. Returns the class type's end offset if field name has been omitted. Compiles to a constant. */ +declare function offsetof(fieldName?: string): usize; +/** Determines the name of a given type. */ +declare function nameof(value?: T): string; +/** Determines the unique runtime id of a class type. Compiles to a constant. */ +declare function idof(): u32; +/** Changes the type of any value of \`usize\` kind to another one of \`usize\` kind. Useful for casting class instances to their pointer values and vice-versa. Beware that this is unsafe.*/ +declare function changetype(value: any): T; +/** Explicitly requests no bounds checks on the provided expression. Useful for array accesses. */ +declare function unchecked(value: T): T; +/** Emits a \`call_indirect\` instruction, calling the specified function in the function table by index with the specified arguments. Does result in a runtime error if the arguments do not match the called function. */ +declare function call_indirect(index: u32, ...args: unknown[]): T; +/** Instantiates a new instance of \`T\` using the specified constructor arguments. */ +declare function instantiate(...args: any[]): T; +/** Tests if a 32-bit or 64-bit float is \`NaN\`. */ +declare function isNaN(value: T): bool; +/** Tests if a 32-bit or 64-bit float is finite, that is not \`NaN\` or +/-\`Infinity\`. */ +declare function isFinite(value: T): bool; +/** Tests if the specified type *or* expression is of an integer type and not a reference. Compiles to a constant. */ +declare function isInteger(value?: any): value is number; +/** Tests if the specified type *or* expression is of a float type. Compiles to a constant. */ +declare function isFloat(value?: any): value is number; +/** Tests if the specified type *or* expression is of a boolean type. */ +declare function isBoolean(value?: any): value is number; +/** Tests if the specified type *or* expression can represent negative numbers. Compiles to a constant. */ +declare function isSigned(value?: any): value is number; +/** Tests if the specified type *or* expression is of a reference type. Compiles to a constant. */ +declare function isReference(value?: any): value is object | string; +/** Tests if the specified type *or* expression can be used as a string. Compiles to a constant. */ +declare function isString(value?: any): value is string | String; +/** Tests if the specified type *or* expression can be used as an array. Compiles to a constant. */ +declare function isArray(value?: any): value is Array; +/** Tests if the specified type *or* expression can be used as an array like object. Compiles to a constant. */ +declare function isArrayLike(value?: any): value is ArrayLike; +/** Tests if the specified type *or* expression is of a function type. Compiles to a constant. */ +declare function isFunction(value?: any): value is (...args: any) => any; +/** Tests if the specified type *or* expression is of a nullable reference type. Compiles to a constant. */ +declare function isNullable(value?: any): bool; +/** Tests if the specified expression resolves to a defined element. Compiles to a constant. */ +declare function isDefined(expression: any): bool; +/** Tests if the specified expression evaluates to a constant value. Compiles to a constant. */ +declare function isConstant(expression: any): bool; +/** Tests if the specified type *or* expression is of a managed type. Compiles to a constant. */ +declare function isManaged(value?: any): bool; +/** Tests if the specified type is void. Compiles to a constant. */ +declare function isVoid(): bool; +/** Traps if the specified value is not true-ish, otherwise returns the (non-nullable) value. */ +declare function assert(isTrueish: T, message?: string): T & (object | string | number); // any better way to model \`: T != null\`? +/** Parses an integer string to a 64-bit float. */ +declare function parseInt(str: string, radix?: i32): f64; +/** Parses a string to a 64-bit float. */ +declare function parseFloat(str: string): f64; +/** Returns the 64-bit floating-point remainder of \`x/y\`. */ +declare function fmod(x: f64, y: f64): f64; +/** Returns the 32-bit floating-point remainder of \`x/y\`. */ +declare function fmodf(x: f32, y: f32): f32; +/** Returns the number of parameters in the given function signature type. */ +declare function lengthof any>(func?: T): i32; +/** Encodes a text string as a valid Uniform Resource Identifier (URI). */ +declare function encodeURI(str: string): string; +/** Encodes a text string as a valid component of a Uniform Resource Identifier (URI). */ +declare function encodeURIComponent(str: string): string; +/** Decodes a Uniform Resource Identifier (URI) previously created by encodeURI. */ +declare function decodeURI(str: string): string; +/** Decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent. */ +declare function decodeURIComponent(str: string): string; + +/** Atomic operations. */ +declare namespace atomic { + /** Atomically loads an integer value from memory and returns it. */ + export function load(ptr: usize, immOffset?: usize): T; + /** Atomically stores an integer value to memory. */ + export function store(ptr: usize, value: T, immOffset?: usize): void; + /** Atomically adds an integer value in memory. */ + export function add(ptr: usize, value: T, immOffset?: usize): T; + /** Atomically subtracts an integer value in memory. */ + export function sub(ptr: usize, value: T, immOffset?: usize): T; + /** Atomically performs a bitwise AND operation on an integer value in memory. */ + export function and(ptr: usize, value: T, immOffset?: usize): T; + /** Atomically performs a bitwise OR operation on an integer value in memory. */ + export function or(ptr: usize, value: T, immOffset?: usize): T; + /** Atomically performs a bitwise XOR operation on an integer value in memory. */ + export function xor(ptr: usize, value: T, immOffset?: usize): T; + /** Atomically exchanges an integer value in memory. */ + export function xchg(ptr: usize, value: T, immOffset?: usize): T; + /** Atomically compares and exchanges an integer value in memory if the condition is met. */ + export function cmpxchg(ptr: usize, expected: T, replacement: T, immOffset?: usize): T; + /** Performs a wait operation on an address in memory suspending this agent if the integer condition is met. */ + export function wait(ptr: usize, expected: T, timeout?: i64): AtomicWaitResult; + /** Performs a notify operation on an address in memory waking up suspended agents. */ + export function notify(ptr: usize, count?: i32): i32; + /** Performs a fence operation, preserving synchronization guarantees of higher level languages. */ + export function fence(): void; +} + +/** Describes the result of an atomic wait operation. */ +declare enum AtomicWaitResult { + /** Woken by another agent. */ + OK, + /** Loaded value did not match the expected value. */ + NOT_EQUAL, + /** Not woken before the timeout expired. */ + TIMED_OUT +} + +/** Converts any other numeric value to an 8-bit signed integer. */ +declare function i8(value: any): i8; +declare namespace i8 { + /** Smallest representable value. */ + export const MIN_VALUE: i8; + /** Largest representable value. */ + export const MAX_VALUE: i8; +} +/** Converts any other numeric value to a 16-bit signed integer. */ +declare function i16(value: any): i16; +declare namespace i16 { + /** Smallest representable value. */ + export const MIN_VALUE: i16; + /** Largest representable value. */ + export const MAX_VALUE: i16; +} +/** Converts any other numeric value to a 32-bit signed integer. */ +declare function i32(value: any): i32; +declare namespace i32 { + /** Smallest representable value. */ + export const MIN_VALUE: i32; + /** Largest representable value. */ + export const MAX_VALUE: i32; + /** Loads an 8-bit signed integer value from memory and returns it as a 32-bit integer. */ + export function load8_s(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + /** Loads an 8-bit unsigned integer value from memory and returns it as a 32-bit integer. */ + export function load8_u(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + /** Loads a 16-bit signed integer value from memory and returns it as a 32-bit integer. */ + export function load16_s(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + /** Loads a 16-bit unsigned integer value from memory and returns it as a 32-bit integer. */ + export function load16_u(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + /** Loads a 32-bit integer value from memory. */ + export function load(ptr: usize, immOffset?: usize, immAlign?: usize): i32; + /** Stores a 32-bit integer value to memory as an 8-bit integer. */ + export function store8(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; + /** Stores a 32-bit integer value to memory as a 16-bit integer. */ + export function store16(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; + /** Stores a 32-bit integer value to memory. */ + export function store(ptr: usize, value: i32, immOffset?: usize, immAlign?: usize): void; + /** Performs the sign-agnostic count leading zero bits operation on a 32-bit integer. All zero bits are considered leading if the value is zero. */ + export function clz(value: i32): i32; + /** Performs the sign-agnostic count tailing zero bits operation on a 32-bit integer. All zero bits are considered trailing if the value is zero. */ + export function ctz(value: i32): i32; + /** Performs the sign-agnostic count number of one bits operation on a 32-bit integer. */ + export function popcnt(value: i32): i32; + /** Performs the sign-agnostic rotate left operation on a 32-bit integer. */ + export function rotl(value: i32, shift: i32): i32; + /** Performs the sign-agnostic rotate right operation on a 32-bit integer. */ + export function rotr(value: i32, shift: i32): i32; + /** Reinterprets the bits of the specified 32-bit float as a 32-bit integer. */ + export function reinterpret_f32(value: f32): i32; + /** Computes the sum of two 32-bit integers. */ + export function add(left: i32, right: i32): i32; + /** Computes the difference of two 32-bit integers. */ + export function sub(left: i32, right: i32): i32; + /** Computes the product of two 32-bit integers. */ + export function mul(left: i32, right: i32): i32; + /** Computes the signed quotient of two 32-bit integers. */ + export function div_s(left: i32, right: i32): i32; + /** Computes the unsigned quotient of two 32-bit integers. */ + export function div_u(left: i32, right: i32): i32; + /** Return 1 two 32-bit inegers are equal to each other, 0 otherwise. */ + export function eq(left: i32, right: i32): i32; + /** Return 0 two 32-bit inegers are equal to each other, 1 otherwise. */ + export function ne(left: i32, right: i32): i32; + /** Atomic 32-bit integer operations. */ + export namespace atomic { + /** Atomically loads an 8-bit unsigned integer value from memory and returns it as a 32-bit integer. */ + export function load8_u(ptr: usize, immOffset?: usize): i32; + /** Atomically loads a 16-bit unsigned integer value from memory and returns it as a 32-bit integer. */ + export function load16_u(ptr: usize, immOffset?: usize): i32; + /** Atomically loads a 32-bit integer value from memory and returns it. */ + export function load(ptr: usize, immOffset?: usize): i32; + /** Atomically stores a 32-bit integer value to memory as an 8-bit integer. */ + export function store8(ptr: usize, value: i32, immOffset?: usize): void; + /** Atomically stores a 32-bit integer value to memory as a 16-bit integer. */ + export function store16(ptr: usize, value: i32, immOffset?: usize): void; + /** Atomically stores a 32-bit integer value to memory. */ + export function store(ptr: usize, value: i32, immOffset?: usize): void; + /** Performs a wait operation on a 32-bit integer value in memory suspending this agent if the condition is met. */ + export function wait(ptr: usize, expected: i32, timeout?: i64): AtomicWaitResult; + /** Atomic 32-bit integer read-modify-write operations on 8-bit values. */ + export namespace rmw8 { + /** Atomically adds an 8-bit unsigned integer value in memory. */ + export function add_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically subtracts an 8-bit unsigned integer value in memory. */ + export function sub_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise AND operation an 8-bit unsigned integer value in memory. */ + export function and_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise OR operation an 8-bit unsigned integer value in memory. */ + export function or_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise XOR operation an 8-bit unsigned integer value in memory. */ + export function xor_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically exchanges an 8-bit unsigned integer value in memory. */ + export function xchg_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically compares and exchanges an 8-bit unsigned integer value in memory if the condition is met. */ + export function cmpxchg_u(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; + } + /** Atomic 32-bit integer read-modify-write operations on 16-bit values. */ + export namespace rmw16 { + /** Atomically adds a 16-bit unsigned integer value in memory. */ + export function add_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically adds a 16-bit unsigned integer value in memory. */ + export function sub_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise AND operation a 16-bit unsigned integer value in memory. */ + export function and_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise OR operation a 16-bit unsigned integer value in memory. */ + export function or_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise XOR operation a 16-bit unsigned integer value in memory. */ + export function xor_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically exchanges a 16-bit unsigned integer value in memory. */ + export function xchg_u(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically compares and exchanges a 16-bit unsigned integer value in memory if the condition is met. */ + export function cmpxchg_u(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; + } + /** Atomic 32-bit integer read-modify-write operations. */ + export namespace rmw { + /** Atomically adds a 32-bit integer value in memory. */ + export function add(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically subtracts a 32-bit integer value in memory. */ + export function sub(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise AND operation a 32-bit integer value in memory. */ + export function and(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise OR operation a 32-bit integer value in memory. */ + export function or(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically performs a bitwise XOR operation a 32-bit integer value in memory. */ + export function xor(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically exchanges a 32-bit integer value in memory. */ + export function xchg(ptr: usize, value: i32, immOffset?: usize): i32; + /** Atomically compares and exchanges a 32-bit integer value in memory if the condition is met. */ + export function cmpxchg(ptr: usize, expected: i32, replacement: i32, immOffset?: usize): i32; + } + } +} +/** Converts any other numeric value to a 64-bit signed integer. */ +declare function i64(value: any): i64; +declare namespace i64 { + /** Smallest representable value. */ + export const MIN_VALUE: i64; + /** Largest representable value. */ + export const MAX_VALUE: i64; + /** Loads an 8-bit signed integer value from memory and returns it as a 64-bit integer. */ + export function load8_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + /** Loads an 8-bit unsigned integer value from memory and returns it as a 64-bit integer. */ + export function load8_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + /** Loads a 16-bit signed integer value from memory and returns it as a 64-bit integer. */ + export function load16_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + /** Loads a 16-bit unsigned integer value from memory and returns it as a 64-bit integer. */ + export function load16_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + /** Loads a 32-bit signed integer value from memory and returns it as a 64-bit integer. */ + export function load32_s(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + /** Loads a 32-bit unsigned integer value from memory and returns it as a 64-bit integer. */ + export function load32_u(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + /** Loads a 64-bit unsigned integer value from memory. */ + export function load(ptr: usize, immOffset?: usize, immAlign?: usize): i64; + /** Stores a 64-bit integer value to memory as an 8-bit integer. */ + export function store8(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + /** Stores a 64-bit integer value to memory as a 16-bit integer. */ + export function store16(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + /** Stores a 64-bit integer value to memory as a 32-bit integer. */ + export function store32(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + /** Stores a 64-bit integer value to memory. */ + export function store(ptr: usize, value: i64, immOffset?: usize, immAlign?: usize): void; + /** Performs the sign-agnostic count leading zero bits operation on a 64-bit integer. All zero bits are considered leading if the value is zero. */ + export function clz(value: i64): i64; + /** Performs the sign-agnostic count tailing zero bits operation on a 64-bit integer. All zero bits are considered trailing if the value is zero. */ + export function ctz(value: i64): i64; + /** Performs the sign-agnostic count number of one bits operation on a 64-bit integer. */ + export function popcnt(value: i64): i64; + /** Performs the sign-agnostic rotate left operation on a 64-bit integer. */ + export function rotl(value: i64, shift: i64): i64; + /** Performs the sign-agnostic rotate right operation on a 64-bit integer. */ + export function rotr(value: i64, shift: i64): i64; + /** Reinterprets the bits of the specified 64-bit float as a 64-bit integer. */ + export function reinterpret_f64(value: f64): i64; + /** Computes the sum of two 64-bit integers. */ + export function add(left: i64, right: i64): i64; + /** Computes the difference of two 64-bit integers. */ + export function sub(left: i64, right: i64): i64; + /** Computes the product of two 64-bit integers. */ + export function mul(left: i64, right: i64): i64; + /** Computes the signed quotient of two 64-bit integers. */ + export function div_s(left: i64, right: i64): i64; + /** Computes the unsigned quotient of two 64-bit integers. */ + export function div_u(left: i64, right: i64): i64; + /** Return 1 two 64-bit inegers are equal to each other, 0 otherwise. */ + export function eq(left: i64, right: i64): i32; + /** Return 0 two 64-bit inegers are equal to each other, 1 otherwise. */ + export function ne(left: i64, right: i64): i32; + /** Atomic 64-bit integer operations. */ + export namespace atomic { + /** Atomically loads an 8-bit unsigned integer value from memory and returns it as a 64-bit integer. */ + export function load8_u(ptr: usize, immOffset?: usize): i64; + /** Atomically loads a 16-bit unsigned integer value from memory and returns it as a 64-bit integer. */ + export function load16_u(ptr: usize, immOffset?: usize): i64; + /** Atomically loads a 32-bit unsigned integer value from memory and returns it as a 64-bit integer. */ + export function load32_u(ptr: usize, immOffset?: usize): i64; + /** Atomically loads a 64-bit integer value from memory and returns it. */ + export function load(ptr: usize, immOffset?: usize): i64; + /** Atomically stores a 64-bit integer value to memory as an 8-bit integer. */ + export function store8(ptr: usize, value: i64, immOffset?: usize): void; + /** Atomically stores a 64-bit integer value to memory as a 16-bit integer. */ + export function store16(ptr: usize, value: i64, immOffset?: usize): void; + /** Atomically stores a 64-bit integer value to memory as a 32-bit integer. */ + export function store32(ptr: usize, value: i64, immOffset?: usize): void; + /** Atomically stores a 64-bit integer value to memory. */ + export function store(ptr: usize, value: i64, immOffset?: usize): void; + /** Performs a wait operation on a 64-bit integer value in memory suspending this agent if the condition is met. */ + export function wait(ptr: usize, expected: i64, timeout?: i64): AtomicWaitResult; + /** Atomic 64-bit integer read-modify-write operations on 8-bit values. */ + export namespace rmw8 { + /** Atomically adds an 8-bit unsigned integer value in memory. */ + export function add_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically subtracts an 8-bit unsigned integer value in memory. */ + export function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise AND operation on an 8-bit unsigned integer value in memory. */ + export function and_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise OR operation on an 8-bit unsigned integer value in memory. */ + export function or_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise XOR operation on an 8-bit unsigned integer value in memory. */ + export function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically exchanges an 8-bit unsigned integer value in memory. */ + export function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically compares and exchanges an 8-bit unsigned integer value in memory if the condition is met. */ + export function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + /** Atomic 64-bit integer read-modify-write operations on 16-bit values. */ + export namespace rmw16 { + /** Atomically adds a 16-bit unsigned integer value in memory. */ + export function add_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically subtracts a 16-bit unsigned integer value in memory. */ + export function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise AND operation on a 16-bit unsigned integer value in memory. */ + export function and_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise OR operation on a 16-bit unsigned integer value in memory. */ + export function or_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise XOR operation on a 16-bit unsigned integer value in memory. */ + export function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically exchanges a 16-bit unsigned integer value in memory. */ + export function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically compares and exchanges a 16-bit unsigned integer value in memory if the condition is met. */ + export function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + /** Atomic 64-bit integer read-modify-write operations on 32-bit values. */ + export namespace rmw32 { + /** Atomically adds a 32-bit unsigned integer value in memory. */ + export function add_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically subtracts a 32-bit unsigned integer value in memory. */ + export function sub_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise AND operation on a 32-bit unsigned integer value in memory. */ + export function and_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise OR operation on a 32-bit unsigned integer value in memory. */ + export function or_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise XOR operation on a 32-bit unsigned integer value in memory. */ + export function xor_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically exchanges a 32-bit unsigned integer value in memory. */ + export function xchg_u(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically compares and exchanges a 32-bit unsigned integer value in memory if the condition is met. */ + export function cmpxchg_u(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + /** Atomic 64-bit integer read-modify-write operations. */ + export namespace rmw { + /** Atomically adds a 64-bit integer value in memory. */ + export function add(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically subtracts a 64-bit integer value in memory. */ + export function sub(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise AND operation on a 64-bit integer value in memory. */ + export function and(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise OR operation on a 64-bit integer value in memory. */ + export function or(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically performs a bitwise XOR operation on a 64-bit integer value in memory. */ + export function xor(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically exchanges a 64-bit integer value in memory. */ + export function xchg(ptr: usize, value: i64, immOffset?: usize): i64; + /** Atomically compares and exchanges a 64-bit integer value in memory if the condition is met. */ + export function cmpxchg(ptr: usize, expected: i64, replacement: i64, immOffset?: usize): i64; + } + } +} +/** Converts any other numeric value to a 32-bit (in WASM32) respectivel 64-bit (in WASM64) signed integer. */ +declare var isize: typeof i32 | typeof i64; +/** Converts any other numeric value to an 8-bit unsigned integer. */ +declare function u8(value: any): u8; +declare namespace u8 { + /** Smallest representable value. */ + export const MIN_VALUE: u8; + /** Largest representable value. */ + export const MAX_VALUE: u8; +} +/** Converts any other numeric value to a 16-bit unsigned integer. */ +declare function u16(value: any): u16; +declare namespace u16 { + /** Smallest representable value. */ + export const MIN_VALUE: u16; + /** Largest representable value. */ + export const MAX_VALUE: u16; +} +/** Converts any other numeric value to a 32-bit unsigned integer. */ +declare function u32(value: any): u32; +declare namespace u32 { + /** Smallest representable value. */ + export const MIN_VALUE: u32; + /** Largest representable value. */ + export const MAX_VALUE: u32; +} +/** Converts any other numeric value to a 64-bit unsigned integer. */ +declare function u64(value: any): u64; +declare namespace u64 { + /** Smallest representable value. */ + export const MIN_VALUE: u64; + /** Largest representable value. */ + export const MAX_VALUE: u64; +} +/** Converts any other numeric value to a 32-bit (in WASM32) respectivel 64-bit (in WASM64) unsigned integer. */ +declare var usize: typeof u32 | typeof u64; +/** Converts any other numeric value to a 1-bit unsigned integer. */ +declare function bool(value: any): bool; +declare namespace bool { + /** Smallest representable value. */ + export const MIN_VALUE: bool; + /** Largest representable value. */ + export const MAX_VALUE: bool; +} +/** Converts any other numeric value to a 32-bit float. */ +declare function f32(value: any): f32; +declare namespace f32 { + /** Smallest representable value. */ + export const MIN_VALUE: f32; + /** Largest representable value. */ + export const MAX_VALUE: f32; + /** Smallest normalized positive value. */ + export const MIN_NORMAL_VALUE: f32; + /** Smallest safely representable integer value. */ + export const MIN_SAFE_INTEGER: f32; + /** Largest safely representable integer value. */ + export const MAX_SAFE_INTEGER: f32; + /** Positive infinity value. */ + export const POSITIVE_INFINITY: f32; + /** Negative infinity value. */ + export const NEGATIVE_INFINITY: f32; + /** Not a number value. */ + export const NaN: f32; + /** Difference between 1 and the smallest representable value greater than 1. */ + export const EPSILON: f32; + /** Loads a 32-bit float from memory. */ + export function load(ptr: usize, immOffset?: usize, immAlign?: usize): f32; + /** Stores a 32-bit float to memory. */ + export function store(ptr: usize, value: f32, immOffset?: usize, immAlign?: usize): void; + /** Computes the sum of two 32-bit floats. */ + export function add(left: f32, right: f32): f32; + /** Computes the difference of two 32-bit floats. */ + export function sub(left: f32, right: f32): f32; + /** Computes the product of two 32-bit floats. */ + export function mul(left: f32, right: f32): f32; + /** Computes the quotient of two 32-bit floats. */ + export function div(left: f32, right: f32): f32; + /** Return 1 two 32-bit floats are equal to each other, 0 otherwise. */ + export function eq(left: f32, right: f32): i32; + /** Return 0 two 32-bit floats are equal to each other, 1 otherwise. */ + export function ne(left: f32, right: f32): i32; + /** Computes the absolute value of a 32-bit float. */ + export function abs(value: f32): f32; + /** Determines the maximum of two 32-bit floats. If either operand is \`NaN\`, returns \`NaN\`. */ + export function max(left: f32, right: f32): f32; + /** Determines the minimum of two 32-bit floats. If either operand is \`NaN\`, returns \`NaN\`. */ + export function min(left: f32, right: f32): f32; + /** Performs the ceiling operation on a 32-bit float. */ + export function ceil(value: f32): f32; + /** Composes a 32-bit float from the magnitude of \`x\` and the sign of \`y\`. */ + export function copysign(x: f32, y: f32): f32; + /** Performs the floor operation on a 32-bit float. */ + export function floor(value: f32): f32; + /** Rounds to the nearest integer tied to even of a 32-bit float. */ + export function nearest(value: f32): f32; + /** Reinterprets the bits of the specified 32-bit integer as a 32-bit float. */ + export function reinterpret_i32(value: i32): f32; + /** Calculates the square root of a 32-bit float. */ + export function sqrt(value: f32): f32; + /** Rounds to the nearest integer towards zero of a 32-bit float. */ + export function trunc(value: f32): f32; +} +/** Converts any other numeric value to a 64-bit float. */ +declare function f64(value: any): f64; +declare namespace f64 { + /** Smallest representable value. */ + export const MIN_VALUE: f64; + /** Largest representable value. */ + export const MAX_VALUE: f64; + /** Smallest normalized positive value. */ + export const MIN_NORMAL_VALUE: f64; + /** Smallest safely representable integer value. */ + export const MIN_SAFE_INTEGER: f64; + /** Largest safely representable integer value. */ + export const MAX_SAFE_INTEGER: f64; + /** Positive infinity value. */ + export const POSITIVE_INFINITY: f64; + /** Negative infinity value. */ + export const NEGATIVE_INFINITY: f64; + /** Not a number value. */ + export const NaN: f64; + /** Difference between 1 and the smallest representable value greater than 1. */ + export const EPSILON: f64; + /** Loads a 64-bit float from memory. */ + export function load(ptr: usize, immOffset?: usize, immAlign?: usize): f64; + /** Stores a 64-bit float to memory. */ + export function store(ptr: usize, value: f64, immOffset?: usize, immAlign?: usize): void; + /** Computes the sum of two 64-bit floats. */ + export function add(left: f64, right: f64): f64; + /** Computes the difference of two 64-bit floats. */ + export function sub(left: f64, right: f64): f64; + /** Computes the product of two 64-bit floats. */ + export function mul(left: f64, right: f64): f64; + /** Computes the quotient of two 64-bit floats. */ + export function div(left: f64, right: f64): f64; + /** Return 1 two 64-bit floats are equal to each other, 0 otherwise. */ + export function eq(left: f64, right: f64): i32; + /** Return 0 two 32-bit floats are equal to each other, 1 otherwise. */ + export function ne(left: f64, right: f64): i32; + /** Computes the absolute value of a 64-bit float. */ + export function abs(value: f64): f64; + /** Determines the maximum of two 64-bit floats. If either operand is \`NaN\`, returns \`NaN\`. */ + export function max(left: f64, right: f64): f64; + /** Determines the minimum of two 64-bit floats. If either operand is \`NaN\`, returns \`NaN\`. */ + export function min(left: f64, right: f64): f64; + /** Performs the ceiling operation on a 64-bit float. */ + export function ceil(value: f64): f64; + /** Composes a 64-bit float from the magnitude of \`x\` and the sign of \`y\`. */ + export function copysign(x: f64, y: f64): f64; + /** Performs the floor operation on a 64-bit float. */ + export function floor(value: f64): f64; + /** Rounds to the nearest integer tied to even of a 64-bit float. */ + export function nearest(value: f64): f64; + /** Reinterprets the bits of the specified 64-bit integer as a 64-bit float. */ + export function reinterpret_i64(value: i64): f64; + /** Calculates the square root of a 64-bit float. */ + export function sqrt(value: f64): f64; + /** Rounds to the nearest integer towards zero of a 64-bit float. */ + export function trunc(value: f64): f64; +} +/** Initializes a 128-bit vector from sixteen 8-bit integer values. Arguments must be compile-time constants. */ +declare function v128(a: i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8, i: i8, j: i8, k: i8, l: i8, m: i8, n: i8, o: i8, p: i8): v128; +declare namespace v128 { + /** Creates a vector with identical lanes. */ + export function splat(x: T): v128; + /** Extracts one lane as a scalar. */ + export function extract_lane(x: v128, idx: u8): T; + /** Replaces one lane. */ + export function replace_lane(x: v128, idx: u8, value: T): v128; + /** Selects lanes from either vector according to the specified lane indexes. */ + export function shuffle(a: v128, b: v128, ...lanes: u8[]): v128; + /** Selects 8-bit lanes from the first vector according to the indexes [0-15] specified by the 8-bit lanes of the second vector. */ + export function swizzle(a: v128, s: v128): v128; + /** Loads a vector from memory. */ + export function load(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Creates a vector by loading the lanes of the specified type and extending each to the next larger type. */ + export function load_ext(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Creates a vector by loading a value of the specified type into the lowest bits and initializing all other bits of the vector to zero. */ + export function load_zero(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Loads a single lane from memory into the specified lane of the given vector. Other lanes are bypassed as is. */ + export function load_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Stores the single lane at the specified index of the given vector to memory. */ + export function store_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Creates a vector with eight 16-bit integer lanes by loading and sign extending eight 8-bit integers. */ + export function load8x8_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + /** Creates a vector with eight 16-bit integer lanes by loading and zero extending eight 8-bit integers. */ + export function load8x8_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + /** Creates a vector with four 32-bit integer lanes by loading and sign extending four 16-bit integers. */ + export function load16x4_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + /** Creates a vector with four 32-bit integer lanes by loading and zero extending four 16-bit integers. */ + export function load16x4_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + /** Creates a vector with two 64-bit integer lanes by loading and sign extending two 32-bit integers. */ + export function load32x2_s(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + /** Creates a vector with two 64-bit integer lanes by loading and zero extending two 32-bit integers. */ + export function load32x2_u(ptr: usize, immOffset?: u32, immAlign?: u32): v128; + /** Creates a vector with identical lanes by loading the splatted value. */ + export function load_splat(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Loads an 8-bit integer and splats it sixteen times forming a new vector. */ + export function load8_splat(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Loads a 16-bit integer and splats it eight times forming a new vector. */ + export function load16_splat(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Loads a 32-bit integer and splats it four times forming a new vector. */ + export function load32_splat(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Loads a 64-bit integer and splats it two times forming a new vector. */ + export function load64_splat(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Creates a vector by loading a 32-bit value into the lowest bits and initializing all other bits of the vector to zero. */ + export function load32_zero(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Creates a vector by loading a 64-bit value into the lowest bits and initializing all other bits of the vector to zero. */ + export function load64_zero(ptr: usize, immOffset?: usize, immAlign?: usize): v128; + /** Loads a single 8-bit lane from memory into the specified lane of the given vector. Other lanes are bypassed as is. */ + export function load8_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Loads a single 16-bit lane from memory into the specified lane of the given vector. Other lanes are bypassed as is. */ + export function load16_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Loads a single 32-bit lane from memory into the specified lane of the given vector. Other lanes are bypassed as is. */ + export function load32_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Loads a single 64-bit lane from memory into the specified lane of the given vector. Other lanes are bypassed as is. */ + export function load64_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Stores the 8-bit lane at the specified lane of the given vector to memory. */ + export function store8_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Stores the 16-bit lane at the specified lane of the given vector to memory. */ + export function store16_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Stores the 32-bit lane at the specified lane of the given vector to memory. */ + export function store32_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Stores the 64-bit lane at the specified lane of the given vector to memory. */ + export function store64_lane(ptr: usize, vec: v128, idx: u8, immOffset?: usize, immAlign?: usize): v128; + /** Stores a vector to memory. */ + export function store(ptr: usize, value: v128, immOffset?: usize, immAlign?: usize): void; + /** Adds each lane. */ + export function add(a: v128, b: v128): v128; + /** Subtracts each lane. */ + export function sub(a: v128, b: v128): v128; + /** Multiplies each lane. */ + export function mul(a: v128, b: v128): v128; // except i64 + /** Divides each lane. */ + export function div(a: v128, b: v128): v128; + /** Negates each lane of a vector. */ + export function neg(a: v128): v128; + /** Adds each lane using saturation. */ + export function add_sat(a: v128, b: v128): v128; + /** Subtracts each lane using saturation. */ + export function sub_sat(a: v128, b: v128): v128; + /** Performs a bitwise left shift on each lane of a vector by a scalar. */ + export function shl(a: v128, b: i32): v128; + /** Performs a bitwise right shift on each lane of a vector by a scalar. */ + export function shr(a: v128, b: i32): v128; + /** Performs the bitwise AND operation on two vectors. */ + export function and(a: v128, b: v128): v128; + /** Performs the bitwise OR operation on two vectors. */ + export function or(a: v128, b: v128): v128; + /** Performs the bitwise XOR operation on two vectors. */ + export function xor(a: v128, b: v128): v128; + /** Performs the bitwise ANDNOT operation on two vectors. */ + export function andnot(a: v128, b: v128): v128; + /** Performs the bitwise NOT operation on a vector. */ + export function not(a: v128): v128; + /** Selects bits of either vector according to the specified mask. */ + export function bitselect(v1: v128, v2: v128, mask: v128): v128; + /** Reduces a vector to a scalar indicating whether any lane is considered \`true\`. */ + export function any_true(a: v128): bool; + /** Reduces a vector to a scalar indicating whether all lanes are considered \`true\`. */ + export function all_true(a: v128): bool; + /** Extracts the high bit of each lane and produces a scalar mask with all bits concatenated. */ + export function bitmask(a: v128): i32; + /** Counts the number of bits set to one within each lane. */ + export function popcnt(a: v128): v128; + /** Computes the minimum of each lane. */ + export function min(a: v128, b: v128): v128; + /** Computes the maximum of each lane. */ + export function max(a: v128, b: v128): v128; + /** Computes the pseudo-minimum of each lane. */ + export function pmin(a: v128, b: v128): v128; + /** Computes the pseudo-maximum of each lane. */ + export function pmax(a: v128, b: v128): v128; + /** Computes the dot product of two lanes each, yielding lanes one size wider than the input. */ + export function dot(a: v128, b: v128): v128; + /** Computes the average of each lane. */ + export function avgr(a: v128, b: v128): v128; + /** Computes the absolute value of each lane. */ + export function abs(a: v128): v128; + /** Computes the square root of each lane. */ + export function sqrt(a: v128): v128; + /** Performs the ceiling operation on each lane. */ + export function ceil(a: v128): v128; + /** Performs the floor operation on each lane. */ + export function floor(a: v128): v128; + /** Rounds to the nearest integer towards zero of each lane. */ + export function trunc(a: v128): v128; + /** Rounds to the nearest integer tied to even of each lane. */ + export function nearest(a: v128): v128; + /** Computes which lanes are equal. */ + export function eq(a: v128, b: v128): v128; + /** Computes which lanes are not equal. */ + export function ne(a: v128, b: v128): v128; + /** Computes which lanes of the first vector are less than those of the second. */ + export function lt(a: v128, b: v128): v128; + /** Computes which lanes of the first vector are less than or equal those of the second. */ + export function le(a: v128, b: v128): v128; + /** Computes which lanes of the first vector are greater than those of the second. */ + export function gt(a: v128, b: v128): v128; + /** Computes which lanes of the first vector are greater than or equal those of the second. */ + export function ge(a: v128, b: v128): v128; + /** Converts each lane of a vector from integer to single-precision floating point. */ + export function convert(a: v128): v128; + /** Converts the low lanes of a vector from integer to double-precision floating point. */ + export function convert_low(a: v128): v128; + /** Truncates each lane of a vector from single-precision floating point to integer with saturation. Takes the target type. */ + export function trunc_sat(a: v128): v128; + /** Truncates each lane of a vector from double-precision floating point to integer with saturation. Takes the target type. */ + export function trunc_sat_zero(a: v128): v128; + /** Narrows each lane to their respective narrower lanes. */ + export function narrow(a: v128, b: v128): v128; + /** Extends the low lanes of a vector to their respective wider lanes. */ + export function extend_low(a: v128): v128; + /** Extends the high lanes of a vector to their respective wider lanes. */ + export function extend_high(a: v128): v128; + /** Adds lanes pairwise producing twice wider extended results. */ + export function extadd_pairwise(a: v128): v128; + /** Demotes each float lane to lower precision. The higher lanes of the result are initialized to zero. */ + export function demote_zero(a: v128): v128; + /** Promotes the lower float lanes to higher precision. */ + export function promote_low(a: v128): v128; + /** Performs the line-wise saturating rounding multiplication in Q15 format. */ + export function q15mulr_sat(a: v128, b: v128): v128; + /** Performs the lane-wise integer extended multiplication of the lower lanes producing a twice wider result than the inputs. */ + export function extmul_low(a: v128, b: v128): v128; + /** Performs the lane-wise integer extended multiplication of the higher lanes producing a twice wider result than the inputs. */ + export function extmul_high(a: v128, b: v128): v128; +} +/** Initializes a 128-bit vector from sixteen 8-bit integer values. Arguments must be compile-time constants. */ +declare function i8x16(a: i8, b: i8, c: i8, d: i8, e: i8, f: i8, g: i8, h: i8, i: i8, j: i8, k: i8, l: i8, m: i8, n: i8, o: i8, p: i8): v128; +declare namespace i8x16 { + /** Creates a vector with sixteen identical 8-bit integer lanes. */ + export function splat(x: i8): v128; + /** Extracts one 8-bit integer lane as a signed scalar. */ + export function extract_lane_s(x: v128, idx: u8): i8; + /** Extracts one 8-bit integer lane as an unsigned scalar. */ + export function extract_lane_u(x: v128, idx: u8): u8; + /** Replaces one 8-bit integer lane. */ + export function replace_lane(x: v128, idx: u8, value: i8): v128; + /** Adds each 8-bit integer lane. */ + export function add(a: v128, b: v128): v128; + /** Subtracts each 8-bit integer lane. */ + export function sub(a: v128, b: v128): v128; + /** Computes the signed minimum of each 8-bit integer lane. */ + export function min_s(a: v128, b: v128): v128; + /** Computes the unsigned minimum of each 8-bit integer lane. */ + export function min_u(a: v128, b: v128): v128; + /** Computes the signed maximum of each 8-bit integer lane. */ + export function max_s(a: v128, b: v128): v128; + /** Computes the unsigned maximum of each 8-bit integer lane. */ + export function max_u(a: v128, b: v128): v128; + /** Computes the unsigned average of each 8-bit integer lane. */ + export function avgr_u(a: v128, b: v128): v128; + /** Computes the absolute value of each 8-bit integer lane. */ + export function abs(a: v128): v128; + /** Negates each 8-bit integer lane. */ + export function neg(a: v128): v128; + /** Adds each 8-bit integer lane using signed saturation. */ + export function add_sat_s(a: v128, b: v128): v128; + /** Adds each 8-bit integer lane using unsigned saturation. */ + export function add_sat_u(a: v128, b: v128): v128; + /** Subtracts each 8-bit integer lane using signed saturation. */ + export function sub_sat_s(a: v128, b: v128): v128; + /** Subtracts each 8-bit integer lane using unsigned saturation. */ + export function sub_sat_u(a: v128, b: v128): v128; + /** Performs a bitwise left shift on each 8-bit integer lane by a scalar. */ + export function shl(a: v128, b: i32): v128; + /** Performs a bitwise arithmetic right shift on each 8-bit integer lane by a scalar. */ + export function shr_s(a: v128, b: i32): v128; + /** Performs a bitwise logical right shift on each 8-bit integer lane by a scalar. */ + export function shr_u(a: v128, b: i32): v128; + /** Reduces a vector to a scalar indicating whether all 8-bit integer lanes are considered \`true\`. */ + export function all_true(a: v128): bool; + /** Extracts the high bit of each 8-bit integer lane and produces a scalar mask with all bits concatenated. */ + export function bitmask(a: v128): i32; + /** Counts the number of bits set to one within each 8-bit integer lane. */ + export function popcnt(a: v128): v128; + /** Computes which 8-bit integer lanes are equal. */ + export function eq(a: v128, b: v128): v128; + /** Computes which 8-bit integer lanes are not equal. */ + export function ne(a: v128, b: v128): v128; + /** Computes which 8-bit signed integer lanes of the first vector are less than those of the second. */ + export function lt_s(a: v128, b: v128): v128; + /** Computes which 8-bit unsigned integer lanes of the first vector are less than those of the second. */ + export function lt_u(a: v128, b: v128): v128; + /** Computes which 8-bit signed integer lanes of the first vector are less than or equal those of the second. */ + export function le_s(a: v128, b: v128): v128; + /** Computes which 8-bit unsigned integer lanes of the first vector are less than or equal those of the second. */ + export function le_u(a: v128, b: v128): v128; + /** Computes which 8-bit signed integer lanes of the first vector are greater than those of the second. */ + export function gt_s(a: v128, b: v128): v128; + /** Computes which 8-bit unsigned integer lanes of the first vector are greater than those of the second. */ + export function gt_u(a: v128, b: v128): v128; + /** Computes which 8-bit signed integer lanes of the first vector are greater than or equal those of the second. */ + export function ge_s(a: v128, b: v128): v128; + /** Computes which 8-bit unsigned integer lanes of the first vector are greater than or equal those of the second. */ + export function ge_u(a: v128, b: v128): v128; + /** Narrows each 16-bit signed integer lane to 8-bit signed integer lanes. */ + export function narrow_i16x8_s(a: v128, b: v128): v128; + /** Narrows each 16-bit signed integer lane to 8-bit unsigned integer lanes. */ + export function narrow_i16x8_u(a: v128, b: v128): v128; + /** Selects 8-bit lanes from either vector according to the specified [0-15] respectively [16-31] lane indexes. */ + export function shuffle(a: v128, b: v128, l0: u8, l1: u8, l2: u8, l3: u8, l4: u8, l5: u8, l6: u8, l7: u8, l8: u8, l9: u8, l10: u8, l11: u8, l12: u8, l13: u8, l14: u8, l15: u8): v128; + /** Selects 8-bit lanes from the first vector according to the indexes [0-15] specified by the 8-bit lanes of the second vector. */ + export function swizzle(a: v128, s: v128): v128; +} +/** Initializes a 128-bit vector from eight 16-bit integer values. Arguments must be compile-time constants. */ +declare function i16x8(a: i16, b: i16, c: i16, d: i16, e: i16, f: i16, g: i16, h: i16): v128; +declare namespace i16x8 { + /** Creates a vector with eight identical 16-bit integer lanes. */ + export function splat(x: i16): v128; + /** Extracts one 16-bit integer lane as a signed scalar. */ + export function extract_lane_s(x: v128, idx: u8): i16; + /** Extracts one 16-bit integer lane as an unsigned scalar. */ + export function extract_lane_u(x: v128, idx: u8): u16; + /** Replaces one 16-bit integer lane. */ + export function replace_lane(x: v128, idx: u8, value: i16): v128; + /** Adds each 16-bit integer lane. */ + export function add(a: v128, b: v128): v128; + /** Subtracts each 16-bit integer lane. */ + export function sub(a: v128, b: v128): v128; + /** Multiplies each 16-bit integer lane. */ + export function mul(a: v128, b: v128): v128; + /** Computes the signed minimum of each 16-bit integer lane. */ + export function min_s(a: v128, b: v128): v128; + /** Computes the unsigned minimum of each 16-bit integer lane. */ + export function min_u(a: v128, b: v128): v128; + /** Computes the signed maximum of each 16-bit integer lane. */ + export function max_s(a: v128, b: v128): v128; + /** Computes the unsigned maximum of each 16-bit integer lane. */ + export function max_u(a: v128, b: v128): v128; + /** Computes the unsigned average of each 16-bit integer lane. */ + export function avgr_u(a: v128, b: v128): v128; + /** Computes the absolute value of each 16-bit integer lane. */ + export function abs(a: v128): v128; + /** Negates each 16-bit integer lane. */ + export function neg(a: v128): v128; + /** Adds each 16-bit integer lane using signed saturation. */ + export function add_sat_s(a: v128, b: v128): v128; + /** Adds each 16-bit integer lane using unsigned saturation. */ + export function add_sat_u(a: v128, b: v128): v128; + /** Subtracts each 16-bit integer lane using signed saturation. */ + export function sub_sat_s(a: v128, b: v128): v128; + /** Subtracts each 16-bit integer lane using unsigned saturation. */ + export function sub_sat_u(a: v128, b: v128): v128; + /** Performs a bitwise left shift on each 16-bit integer lane by a scalar. */ + export function shl(a: v128, b: i32): v128; + /** Performs a bitwise arithmetic right shift each 16-bit integer lane by a scalar. */ + export function shr_s(a: v128, b: i32): v128; + /** Performs a bitwise logical right shift on each 16-bit integer lane by a scalar. */ + export function shr_u(a: v128, b: i32): v128; + /** Reduces a vector to a scalar indicating whether all 16-bit integer lanes are considered \`true\`. */ + export function all_true(a: v128): bool; + /** Extracts the high bit of each 16-bit integer lane and produces a scalar mask with all bits concatenated. */ + export function bitmask(a: v128): i32; + /** Computes which 16-bit integer lanes are equal. */ + export function eq(a: v128, b: v128): v128; + /** Computes which 16-bit integer lanes are not equal. */ + export function ne(a: v128, b: v128): v128; + /** Computes which 16-bit signed integer lanes of the first vector are less than those of the second. */ + export function lt_s(a: v128, b: v128): v128; + /** Computes which 16-bit unsigned integer lanes of the first vector are less than those of the second. */ + export function lt_u(a: v128, b: v128): v128; + /** Computes which 16-bit signed integer lanes of the first vector are less than or equal those of the second. */ + export function le_s(a: v128, b: v128): v128; + /** Computes which 16-bit unsigned integer lanes of the first vector are less than or equal those of the second. */ + export function le_u(a: v128, b: v128): v128; + /** Computes which 16-bit signed integer lanes of the first vector are greater than those of the second. */ + export function gt_s(a: v128, b: v128): v128; + /** Computes which 16-bit unsigned integer lanes of the first vector are greater than those of the second. */ + export function gt_u(a: v128, b: v128): v128; + /** Computes which 16-bit signed integer lanes of the first vector are greater than or equal those of the second. */ + export function ge_s(a: v128, b: v128): v128; + /** Computes which 16-bit unsigned integer lanes of the first vector are greater than or equal those of the second. */ + export function ge_u(a: v128, b: v128): v128; + /** Narrows each 32-bit signed integer lane to 16-bit signed integer lanes. */ + export function narrow_i32x4_s(a: v128, b: v128): v128; + /** Narrows each 32-bit signed integer lane to 16-bit unsigned integer lanes. */ + export function narrow_i32x4_u(a: v128, b: v128): v128; + /** Extends the low 8-bit signed integer lanes to 16-bit signed integer lanes. */ + export function extend_low_i8x16_s(a: v128): v128; + /** Extends the low 8-bit unsigned integer lanes to 16-bit unsigned integer lanes. */ + export function extend_low_i8x16_u(a: v128): v128; + /** Extends the high 8-bit signed integer lanes to 16-bit signed integer lanes. */ + export function extend_high_i8x16_s(a: v128): v128; + /** Extends the high 8-bit unsigned integer lanes to 16-bit unsigned integer lanes. */ + export function extend_high_i8x16_u(a: v128): v128; + /** Adds the sixteen 8-bit signed integer lanes pairwise producing eight 16-bit signed integer results. */ + export function extadd_pairwise_i8x16_s(a: v128): v128; + /** Adds the sixteen 8-bit unsigned integer lanes pairwise producing eight 16-bit unsigned integer results. */ + export function extadd_pairwise_i8x16_u(a: v128): v128; + /** Performs the line-wise 16-bit signed integer saturating rounding multiplication in Q15 format. */ + export function q15mulr_sat_s(a: v128, b: v128): v128; + /** Performs the lane-wise 8-bit signed integer extended multiplication of the eight lower lanes producing twice wider 16-bit integer results. */ + export function extmul_low_i8x16_s(a: v128, b: v128): v128; + /** Performs the lane-wise 8-bit unsigned integer extended multiplication of the eight lower lanes producing twice wider 16-bit integer results. */ + export function extmul_low_i8x16_u(a: v128, b: v128): v128; + /** Performs the lane-wise 8-bit signed integer extended multiplication of the eight higher lanes producing twice wider 16-bit integer results. */ + export function extmul_high_i8x16_s(a: v128, b: v128): v128; + /** Performs the lane-wise 8-bit unsigned integer extended multiplication of the eight higher lanes producing twice wider 16-bit integer results. */ + export function extmul_high_i8x16_u(a: v128, b: v128): v128; +} +/** Initializes a 128-bit vector from four 32-bit integer values. Arguments must be compile-time constants. */ +declare function i32x4(a: i32, b: i32, c: i32, d: i32): v128; +declare namespace i32x4 { + /** Creates a vector with four identical 32-bit integer lanes. */ + export function splat(x: i32): v128; + /** Extracts one 32-bit integer lane as a scalar. */ + export function extract_lane(x: v128, idx: u8): i32; + /** Replaces one 32-bit integer lane. */ + export function replace_lane(x: v128, idx: u8, value: i32): v128; + /** Adds each 32-bit integer lane. */ + export function add(a: v128, b: v128): v128; + /** Subtracts each 32-bit integer lane. */ + export function sub(a: v128, b: v128): v128; + /** Multiplies each 32-bit integer lane. */ + export function mul(a: v128, b: v128): v128; + /** Computes the signed minimum of each 32-bit integer lane. */ + export function min_s(a: v128, b: v128): v128; + /** Computes the unsigned minimum of each 32-bit integer lane. */ + export function min_u(a: v128, b: v128): v128; + /** Computes the signed maximum of each 32-bit integer lane. */ + export function max_s(a: v128, b: v128): v128; + /** Computes the unsigned maximum of each 32-bit integer lane. */ + export function max_u(a: v128, b: v128): v128; + /** Computes the dot product of two 16-bit integer lanes each, yielding 32-bit integer lanes. */ + export function dot_i16x8_s(a: v128, b: v128): v128; + /** Computes the absolute value of each 32-bit integer lane. */ + export function abs(a: v128): v128; + /** Negates each 32-bit integer lane. */ + export function neg(a: v128): v128; + /** Performs a bitwise left shift on each 32-bit integer lane by a scalar. */ + export function shl(a: v128, b: i32): v128; + /** Performs a bitwise arithmetic right shift on each 32-bit integer lane by a scalar. */ + export function shr_s(a: v128, b: i32): v128; + /** Performs a bitwise logical right shift on each 32-bit integer lane by a scalar. */ + export function shr_u(a: v128, b: i32): v128; + /** Reduces a vector to a scalar indicating whether all 32-bit integer lanes are considered \`true\`. */ + export function all_true(a: v128): bool; + /** Extracts the high bit of each 32-bit integer lane and produces a scalar mask with all bits concatenated. */ + export function bitmask(a: v128): i32; + /** Computes which 32-bit integer lanes are equal. */ + export function eq(a: v128, b: v128): v128; + /** Computes which 32-bit integer lanes are not equal. */ + export function ne(a: v128, b: v128): v128; + /** Computes which 32-bit signed integer lanes of the first vector are less than those of the second. */ + export function lt_s(a: v128, b: v128): v128; + /** Computes which 32-bit unsigned integer lanes of the first vector are less than those of the second. */ + export function lt_u(a: v128, b: v128): v128; + /** Computes which 32-bit signed integer lanes of the first vector are less than or equal those of the second. */ + export function le_s(a: v128, b: v128): v128; + /** Computes which 32-bit unsigned integer lanes of the first vector are less than or equal those of the second. */ + export function le_u(a: v128, b: v128): v128; + /** Computes which 32-bit signed integer lanes of the first vector are greater than those of the second. */ + export function gt_s(a: v128, b: v128): v128; + /** Computes which 32-bit unsigned integer lanes of the first vector are greater than those of the second. */ + export function gt_u(a: v128, b: v128): v128; + /** Computes which 32-bit signed integer lanes of the first vector are greater than or equal those of the second. */ + export function ge_s(a: v128, b: v128): v128; + /** Computes which 32-bit unsigned integer lanes of the first vector are greater than or equal those of the second. */ + export function ge_u(a: v128, b: v128): v128; + /** Truncates each 32-bit float lane to a signed integer with saturation. */ + export function trunc_sat_f32x4_s(a: v128): v128; + /** Truncates each 32-bit float lane to an unsigned integer with saturation. */ + export function trunc_sat_f32x4_u(a: v128): v128; + /** Truncates the two 64-bit float lanes to the two lower signed integer lanes with saturation. The two higher integer lanes of the result are initialized to zero. */ + export function trunc_sat_f64x2_s_zero(a: v128): v128; + /** Truncates the two 64-bit float lanes to the two lower unsigned integer lanes with saturation. The two higher integer lanes of the result are initialized to zero. */ + export function trunc_sat_f64x2_u_zero(a: v128): v128; + /** Extends the low 16-bit signed integer lanes to 32-bit signed integer lanes. */ + export function extend_low_i16x8_s(a: v128): v128; + /** Extends the low 16-bit unsigned integer lane to 32-bit unsigned integer lanes. */ + export function extend_low_i16x8_u(a: v128): v128; + /** Extends the high 16-bit signed integer lanes to 32-bit signed integer lanes. */ + export function extend_high_i16x8_s(a: v128): v128; + /** Extends the high 16-bit unsigned integer lanes to 32-bit unsigned integer lanes. */ + export function extend_high_i16x8_u(a: v128): v128; + /** Adds the eight 16-bit signed integer lanes pairwise producing four 32-bit signed integer results. */ + export function extadd_pairwise_i16x8_s(a: v128): v128; + /** Adds the eight 16-bit unsigned integer lanes pairwise producing four 32-bit unsigned integer results. */ + export function extadd_pairwise_i16x8_u(a: v128): v128; + /** Performs the lane-wise 16-bit signed integer extended multiplication of the four lower lanes producing twice wider 32-bit integer results. */ + export function extmul_low_i16x8_s(a: v128, b: v128): v128; + /** Performs the lane-wise 16-bit unsigned integer extended multiplication of the four lower lanes producing twice wider 32-bit integer results. */ + export function extmul_low_i16x8_u(a: v128, b: v128): v128; + /** Performs the lane-wise 16-bit signed integer extended multiplication of the four higher lanes producing twice wider 32-bit integer results. */ + export function extmul_high_i16x8_s(a: v128, b: v128): v128; + /** Performs the lane-wise 16-bit unsigned integer extended multiplication of the four higher lanes producing twice wider 32-bit integer results. */ + export function extmul_high_i16x8_u(a: v128, b: v128): v128; +} +/** Initializes a 128-bit vector from two 64-bit integer values. Arguments must be compile-time constants. */ +declare function i64x2(a: i64, b: i64): v128; +declare namespace i64x2 { + /** Creates a vector with two identical 64-bit integer lanes. */ + export function splat(x: i64): v128; + /** Extracts one 64-bit integer lane as a scalar. */ + export function extract_lane(x: v128, idx: u8): i64; + /** Replaces one 64-bit integer lane. */ + export function replace_lane(x: v128, idx: u8, value: i64): v128; + /** Adds each 64-bit integer lane. */ + export function add(a: v128, b: v128): v128; + /** Subtracts each 64-bit integer lane. */ + export function sub(a: v128, b: v128): v128; + /** Multiplies each 64-bit integer lane. */ + export function mul(a: v128, b: v128): v128; + /** Computes the absolute value of each 64-bit integer lane. */ + export function abs(a: v128): v128; + /** Negates each 64-bit integer lane. */ + export function neg(a: v128): v128; + /** Performs a bitwise left shift on each 64-bit integer lane by a scalar. */ + export function shl(a: v128, b: i32): v128; + /** Performs a bitwise arithmetic right shift on each 64-bit integer lane by a scalar. */ + export function shr_s(a: v128, b: i32): v128; + /** Performs a bitwise logical right shift on each 64-bit integer lane by a scalar. */ + export function shr_u(a: v128, b: i32): v128; + /** Reduces a vector to a scalar indicating whether all 64-bit integer lanes are considered \`true\`. */ + export function all_true(a: v128): bool; + /** Extracts the high bit of each 64-bit integer lane and produces a scalar mask with all bits concatenated. */ + export function bitmask(a: v128): i32; + /** Computes which 64-bit integer lanes are equal. */ + export function eq(a: v128, b: v128): v128; + /** Computes which 64-bit integer lanes are not equal. */ + export function ne(a: v128, b: v128): v128; + /** Computes which 64-bit signed integer lanes of the first vector are less than those of the second. */ + export function lt_s(a: v128, b: v128): v128; + /** Computes which 64-bit signed integer lanes of the first vector are less than or equal those of the second. */ + export function le_s(a: v128, b: v128): v128; + /** Computes which 64-bit signed integer lanes of the first vector are greater than those of the second. */ + export function gt_s(a: v128, b: v128): v128; + /** Computes which 64-bit signed integer lanes of the first vector are greater than or equal those of the second. */ + export function ge_s(a: v128, b: v128): v128; + /** Extends the low 32-bit signed integer lanes to 64-bit signed integer lanes. */ + export function extend_low_i32x4_s(a: v128): v128; + /** Extends the low 32-bit unsigned integer lane to 64-bit unsigned integer lanes. */ + export function extend_low_i32x4_u(a: v128): v128; + /** Extends the high 32-bit signed integer lanes to 64-bit signed integer lanes. */ + export function extend_high_i32x4_s(a: v128): v128; + /** Extends the high 32-bit unsigned integer lanes to 64-bit unsigned integer lanes. */ + export function extend_high_i32x4_u(a: v128): v128; + /** Performs the lane-wise 32-bit signed integer extended multiplication of the two lower lanes producing twice wider 64-bit integer results. */ + export function extmul_low_i32x4_s(a: v128, b: v128): v128; + /** Performs the lane-wise 32-bit unsigned integer extended multiplication of the two lower lanes producing twice wider 64-bit integer results. */ + export function extmul_low_i32x4_u(a: v128, b: v128): v128; + /** Performs the lane-wise 32-bit signed integer extended multiplication of the two higher lanes producing twice wider 64-bit integer results. */ + export function extmul_high_i32x4_s(a: v128, b: v128): v128; + /** Performs the lane-wise 32-bit unsigned integer extended multiplication of the two higher lanes producing twice wider 64-bit integer results. */ + export function extmul_high_i32x4_u(a: v128, b: v128): v128; +} +/** Initializes a 128-bit vector from four 32-bit float values. Arguments must be compile-time constants. */ +declare function f32x4(a: f32, b: f32, c: f32, d: f32): v128; +declare namespace f32x4 { + /** Creates a vector with four identical 32-bit float lanes. */ + export function splat(x: f32): v128; + /** Extracts one 32-bit float lane as a scalar. */ + export function extract_lane(x: v128, idx: u8): f32; + /** Replaces one 32-bit float lane. */ + export function replace_lane(x: v128, idx: u8, value: f32): v128; + /** Adds each 32-bit float lane. */ + export function add(a: v128, b: v128): v128; + /** Subtracts each 32-bit float lane. */ + export function sub(a: v128, b: v128): v128; + /** Multiplies each 32-bit float lane. */ + export function mul(a: v128, b: v128): v128; + /** Divides each 32-bit float lane. */ + export function div(a: v128, b: v128): v128; + /** Negates each 32-bit float lane. */ + export function neg(a: v128): v128; + /** Computes the minimum of each 32-bit float lane. */ + export function min(a: v128, b: v128): v128; + /** Computes the maximum of each 32-bit float lane. */ + export function max(a: v128, b: v128): v128; + /** Computes the pseudo-minimum of each 32-bit float lane. */ + export function pmin(a: v128, b: v128): v128; + /** Computes the pseudo-maximum of each 32-bit float lane. */ + export function pmax(a: v128, b: v128): v128; + /** Computes the absolute value of each 32-bit float lane. */ + export function abs(a: v128): v128; + /** Computes the square root of each 32-bit float lane. */ + export function sqrt(a: v128): v128; + /** Performs the ceiling operation on each 32-bit float lane. */ + export function ceil(a: v128): v128; + /** Performs the floor operation on each each 32-bit float lane. */ + export function floor(a: v128): v128; + /** Rounds to the nearest integer towards zero of each 32-bit float lane. */ + export function trunc(a: v128): v128; + /** Rounds to the nearest integer tied to even of each 32-bit float lane. */ + export function nearest(a: v128): v128; + /** Computes which 32-bit float lanes are equal. */ + export function eq(a: v128, b: v128): v128; + /** Computes which 32-bit float lanes are not equal. */ + export function ne(a: v128, b: v128): v128; + /** Computes which 32-bit float lanes of the first vector are less than those of the second. */ + export function lt(a: v128, b: v128): v128; + /** Computes which 32-bit float lanes of the first vector are less than or equal those of the second. */ + export function le(a: v128, b: v128): v128; + /** Computes which 32-bit float lanes of the first vector are greater than those of the second. */ + export function gt(a: v128, b: v128): v128; + /** Computes which 32-bit float lanes of the first vector are greater than or equal those of the second. */ + export function ge(a: v128, b: v128): v128; + /** Converts each 32-bit signed integer lane of a vector to single-precision floating point. */ + export function convert_i32x4_s(a: v128): v128; + /** Converts each 32-bit unsigned integer lane of a vector to single-precision floating point. */ + export function convert_i32x4_u(a: v128): v128; + /** Demotes each 64-bit float lane of a vector to single-precision. The higher lanes of the result are initialized to zero. */ + export function demote_f64x2_zero(a: v128): v128; +} +/** Initializes a 128-bit vector from two 64-bit float values. Arguments must be compile-time constants. */ +declare function f64x2(a: f64, b: f64): v128; +declare namespace f64x2 { + /** Creates a vector with two identical 64-bit float lanes. */ + export function splat(x: f64): v128; + /** Extracts one 64-bit float lane as a scalar. */ + export function extract_lane(x: v128, idx: u8): f64; + /** Replaces one 64-bit float lane. */ + export function replace_lane(x: v128, idx: u8, value: f64): v128; + /** Adds each 64-bit float lane. */ + export function add(a: v128, b: v128): v128; + /** Subtracts each 64-bit float lane. */ + export function sub(a: v128, b: v128): v128; + /** Multiplies each 64-bit float lane. */ + export function mul(a: v128, b: v128): v128; + /** Divides each 64-bit float lane. */ + export function div(a: v128, b: v128): v128; + /** Negates each 64-bit float lane. */ + export function neg(a: v128): v128; + /** Computes the minimum of each 64-bit float lane. */ + export function min(a: v128, b: v128): v128; + /** Computes the maximum of each 64-bit float lane. */ + export function max(a: v128, b: v128): v128; + /** Computes the pseudo-minimum of each 64-bit float lane. */ + export function pmin(a: v128, b: v128): v128; + /** Computes the pseudo-maximum of each 64-bit float lane. */ + export function pmax(a: v128, b: v128): v128; + /** Computes the absolute value of each 64-bit float lane. */ + export function abs(a: v128): v128; + /** Computes the square root of each 64-bit float lane. */ + export function sqrt(a: v128): v128; + /** Performs the ceiling operation on each 64-bit float lane. */ + export function ceil(a: v128): v128; + /** Performs the floor operation on each each 64-bit float lane. */ + export function floor(a: v128): v128; + /** Rounds to the nearest integer towards zero of each 64-bit float lane. */ + export function trunc(a: v128): v128; + /** Rounds to the nearest integer tied to even of each 64-bit float lane. */ + export function nearest(a: v128): v128; + /** Computes which 64-bit float lanes are equal. */ + export function eq(a: v128, b: v128): v128; + /** Computes which 64-bit float lanes are not equal. */ + export function ne(a: v128, b: v128): v128; + /** Computes which 64-bit float lanes of the first vector are less than those of the second. */ + export function lt(a: v128, b: v128): v128; + /** Computes which 64-bit float lanes of the first vector are less than or equal those of the second. */ + export function le(a: v128, b: v128): v128; + /** Computes which 64-bit float lanes of the first vector are greater than those of the second. */ + export function gt(a: v128, b: v128): v128; + /** Computes which 64-bit float lanes of the first vector are greater than or equal those of the second. */ + export function ge(a: v128, b: v128): v128; + /** Converts the low 32-bit signed integer lanes of a vector to double-precision floating point. */ + export function convert_low_i32x4_s(a: v128): v128; + /** Converts the low 32-bit unsigned integer lanes of a vector to double-precision floating point. */ + export function convert_low_i32x4_u(a: v128): v128; + /** Promotes the low 32-bit float lanes of a vector to double-precision. */ + export function promote_low_f32x4(a: v128): v128; +} + +declare abstract class i31 { + /** Creates a new i31ref from the specified integer value. */ + static new(value: i32): i31ref; + /** Gets the integer value of an i31ref. */ + static get(i31expr: i31ref): i32; +} + +/** Macro type evaluating to the underlying native WebAssembly type. */ +declare type native = T; +/** Special type evaluating the indexed access index type. */ +declare type indexof = keyof T; +/** Special type evaluating the indexed access value type. */ +declare type valueof = T[0]; +/** A special type evaluated to the return type of T if T is a callable function. */ +declare type ReturnType any> = T extends (...args: any) => infer R ? R : any; +/** A special type evaluated to the return type of T if T is a callable function. */ +declare type returnof any> = ReturnType; +/** A special type that excludes null and undefined from T. */ +declare type NonNullable = T extends null | undefined ? never : T; +/** A special type that excludes null and undefined from T. */ +declare type nonnull = NonNullable; + +/** Pseudo-class representing the backing class of integer types. */ +/** @internal */ +declare class _Integer { + /** Smallest representable value. */ + static readonly MIN_VALUE: number; + /** Largest representable value. */ + static readonly MAX_VALUE: number; + /** Converts a string to an integer of this type. */ + static parseInt(value: string, radix?: number): number; + /** Converts this integer to a string. */ + toString(radix?: number): string; +} + +/** Pseudo-class representing the backing class of floating-point types. */ +/** @internal */ +declare class _Float { + /** Difference between 1 and the smallest representable value greater than 1. */ + static readonly EPSILON: f32 | f64; + /** Smallest representable value. */ + static readonly MIN_VALUE: f32 | f64; + /** Largest representable value. */ + static readonly MAX_VALUE: f32 | f64; + /** Smallest safely representable integer value. */ + static readonly MIN_SAFE_INTEGER: f32 | f64; + /** Largest safely representable integer value. */ + static readonly MAX_SAFE_INTEGER: f32 | f64; + /** Value representing positive infinity. */ + static readonly POSITIVE_INFINITY: f32 | f64; + /** Value representing negative infinity. */ + static readonly NEGATIVE_INFINITY: f32 | f64; + /** Value representing 'not a number'. */ + static readonly NaN: f32 | f64; + /** Returns a boolean value that indicates whether a value is the reserved value NaN (not a number). */ + static isNaN(value: f32 | f64): bool; + /** Returns true if passed value is finite. */ + static isFinite(value: f32 | f64): bool; + /** Returns true if the value passed is a safe integer. */ + static isSafeInteger(value: f32 | f64): bool; + /** Returns true if the value passed is an integer, false otherwise. */ + static isInteger(value: f32 | f64): bool; + /** Converts a string to an integer. */ + static parseInt(value: string, radix?: i32): f32 | f64; + /** Converts a string to a floating-point number. */ + static parseFloat(value: string): f32 | f64; + /** Converts this floating-point number to a string. */ + toString(radix?: number): string; +} + +declare class Boolean { + toString(radix?: number): string; +} + +/** Backing class of signed 8-bit integers. */ +declare const I8: typeof _Integer; +/** Backing class of signed 16-bit integers. */ +declare const I16: typeof _Integer; +/** Backing class of signed 32-bit integers. */ +declare const I32: typeof _Integer; +/** Backing class of signed 64-bit integers. */ +declare const I64: typeof _Integer; +/** Backing class of signed size integers. */ +declare const Isize: typeof _Integer; +/** Backing class of unsigned 8-bit integers. */ +declare const U8: typeof _Integer; +/** Backing class of unsigned 16-bit integers. */ +declare const U16: typeof _Integer; +/** Backing class of unsigned 32-bit integers. */ +declare const U32: typeof _Integer; +/** Backing class of unsigned 64-bit integers. */ +declare const U64: typeof _Integer; +/** Backing class of unsigned size integers. */ +declare const Usize: typeof _Integer; +/** Backing class of 32-bit floating-point values. */ +declare const F32: typeof _Float; +/** Backing class of 64-bit floating-point values. */ +declare const F64: typeof _Float; +/** Alias of F64. */ +declare const Number: typeof F64; +declare type Number = typeof F64; + +// User-defined diagnostic macros + +/** Emits a user-defined diagnostic error when encountered. */ +declare function ERROR(message?: any): never; +/** Emits a user-defined diagnostic warning when encountered. */ +declare function WARNING(message?: any): void; +/** Emits a user-defined diagnostic info when encountered. */ +declare function INFO(message?: any): void; + +// Polyfills + +/** Performs the sign-agnostic reverse bytes **/ +declare function bswap(value: T): T; +/** Performs the sign-agnostic reverse bytes only for last 16-bit **/ +declare function bswap16(value: T): T; + +// Standard library + +/** Memory operations. */ +declare namespace memory { + /** Whether the memory managed interface is implemented. */ + export const implemented: bool; + /** Returns the current memory size in units of pages. One page is 64kb. */ + export function size(): i32; + /** Grows linear memory by a given unsigned delta of pages. One page is 64kb. Returns the previous memory size in units of pages or \`-1\` on failure. */ + export function grow(value: i32): i32; + /** Sets n bytes beginning at the specified destination in memory to the specified byte value. */ + export function fill(dst: usize, value: u8, count: usize): void; + /** Copies n bytes from the specified source to the specified destination in memory. These regions may overlap. */ + export function copy(dst: usize, src: usize, n: usize): void; + /** Repeats \`src\` of length \`srcLength\` \`count\` times at \`dst\`. */ + export function repeat(dst: usize, src: usize, srcLength: usize, count: usize): void; + /** Copies elements from a passive element segment to a table. */ + export function init(segmentIndex: u32, srcOffset: usize, dstOffset: usize, n: usize): void; + /** Prevents further use of a passive element segment. */ + export function drop(segmentIndex: u32): void; + /** Compares two chunks of memory. Returns \`0\` if equal, otherwise the difference of the first differing bytes. */ + export function compare(vl: usize, vr: usize, n: usize): i32; + /** Gets a pointer to a zeroed static chunk of memory of the given size. Alignment defaults to \`16\`. Arguments must be compile-time constants. */ + export function data(size: i32, align?: i32): usize; + /** Gets a pointer to a pre-initialized static chunk of memory. Alignment defaults to the size of \`T\`. Arguments must be compile-time constants. */ + export function data(values: T[], align?: i32): usize; +} + +/** Heap memory interface. */ +declare namespace heap { + /** Allocates a chunk of memory of at least the specified size. */ + export function alloc(size: usize): usize; + /** Reallocates a chunk of memory to have at least the specified size. */ + export function realloc(ptr: usize, size: usize): usize; + /** Frees a chunk of memory. Does hardly anything (most recent block only) with the stub/none runtime. */ + export function free(ptr: usize): void; +} + +/** Table operations. */ +declare namespace table { + /** Copies elements from a passive element segment to a table. */ + export function init(elementIndex: u32, srcOffset: u32, dstOffset: u32, n: u32): void; + /** Prevents further use of a passive element segment. */ + export function drop(elementIndex: u32): void; + /** Copies elements from one region of a table to another region. */ + export function copy(dest: u32, src: u32, n: u32): void; +} + +declare namespace Atomics { + export function load(array: TypedArray, index: i32): T; + export function store(array: TypedArray, index: i32, value: T): void; + export function add(array: TypedArray, index: i32, value: T): T; + export function sub(array: TypedArray, index: i32, value: T): T; + export function and(array: TypedArray, index: i32, value: T): T; + export function or(array: TypedArray, index: i32, value: T): T; + export function xor(array: TypedArray, index: i32, value: T): T; + export function exchange(array: TypedArray, index: i32, value: T): T; + export function compareExchange(array: TypedArray, index: i32, expectedValue: T, replacementValue: T): T; + export function wait(array: TypedArray, value: T, timeout?: i64): AtomicWaitResult; + export function notify(array: TypedArray, index: i32, count?: i32): i32; + /** The static Atomics.isLockFree() method is used to determine whether to use locks or atomic operations. It returns true, if the given size is one of the BYTES_PER_ELEMENT */ + export function isLockFree(size: usize): bool; +} + +/** Class representing a generic, fixed-length raw binary data buffer. */ +declare class ArrayBuffer { + /** The size, in bytes, of the array. */ + readonly byteLength: i32; + /** Returns true if value is one of the ArrayBuffer views, such as typed array or a DataView **/ + static isView(value: T): bool; + /** Constructs a new array buffer of the given length in bytes. */ + constructor(length: i32); + /** Returns a copy of this array buffer's bytes from begin, inclusive, up to end, exclusive. */ + slice(begin?: i32, end?: i32): ArrayBuffer; + /** Returns a string representation of ArrayBuffer. */ + toString(): string; +} + +/** The \`DataView\` view provides a low-level interface for reading and writing multiple number types in a binary \`ArrayBuffer\`, without having to care about the platform's endianness. */ +declare class DataView { + /** The \`buffer\` accessor property represents the \`ArrayBuffer\` or \`SharedArrayBuffer\` referenced by the \`DataView\` at construction time. */ + readonly buffer: ArrayBuffer; + /** Returns raw pointer to data storage including offset (unsafe). */ + readonly dataStart: usize; + /** The \`byteLength\` accessor property represents the length (in bytes) of this view from the start of its \`ArrayBuffer\` or \`SharedArrayBuffer\`. */ + readonly byteLength: i32; + /** The \`byteOffset\` accessor property represents the offset (in bytes) of this view from the start of its \`ArrayBuffer\` or \`SharedArrayBuffer\`. */ + readonly byteOffset: i32; + /** Constructs a new \`DataView\` with the given properties */ + constructor(buffer: ArrayBuffer, byteOffset?: i32, byteLength?: i32); + /** The \`getFloat32()\` method gets a signed 32-bit float (float) at the specified byte offset from the start of the \`DataView\`. */ + getFloat32(byteOffset: i32, littleEndian?: bool): f32; + /** The \`getFloat64()\` method gets a signed 64-bit float (double) at the specified byte offset from the start of the \`DataView\`. */ + getFloat64(byteOffset: i32, littleEndian?: bool): f64; + /** The \`getInt8()\` method gets a signed 8-bit integer (byte) at the specified byte offset from the start of the \`DataView\`. */ + getInt8(byteOffset: i32): i8; + /** The \`getInt16()\` method gets a signed 16-bit integer (short) at the specified byte offset from the start of the \`DataView\`. */ + getInt16(byteOffset: i32, littleEndian?: bool): i16; + /** The \`getInt32()\` method gets a signed 32-bit integer (long) at the specified byte offset from the start of the \`DataView\`. */ + getInt32(byteOffset: i32, littleEndian?: bool): i32; + /** The \`getInt64()\` method gets a signed 64-bit integer (long long) at the specified byte offset from the start of the \`DataView\`. */ + getInt64(byteOffset: i32, littleEndian?: bool): i64; + /** The \`getUint8()\` method gets an unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the \`DataView\`. */ + getUint8(byteOffset: i32): u8; + /** The \`getUint16()\` method gets an unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the \`DataView\`. */ + getUint16(byteOffset: i32, littleEndian?: bool): u16; + /** The \`getUint32()\` method gets an unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the \`DataView\`. */ + getUint32(byteOffset: i32, littleEndian?: bool): u32; + /** The \`getUint64()\` method gets an unsigned 64-bit integer (unsigned long long) at the specified byte offset from the start of the \`DataView\`. */ + getUint64(byteOffset: i32, littleEndian?: bool): u64; + /** The \`setFloat32()\` method stores a signed 32-bit float (float) value at the specified byte offset from the start of the \`DataView\`. */ + setFloat32(byteOffset: i32, value: f32, littleEndian?: bool): void; + /** The \`setFloat64()\` method stores a signed 64-bit float (double) value at the specified byte offset from the start of the \`DataView\`. */ + setFloat64(byteOffset: i32, value: f64, littleEndian?: bool): void; + /** The \`setInt8()\` method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the \`DataView\`. */ + setInt8(byteOffset: i32, value: i8): void; + /** The \`setInt16()\` method stores a signed 16-bit integer (short) value at the specified byte offset from the start of the \`DataView\`. */ + setInt16(byteOffset: i32, value: i16, littleEndian?: bool): void; + /** The \`setInt32()\` method stores a signed 32-bit integer (long) value at the specified byte offset from the start of the \`DataView\`. */ + setInt32(byteOffset: i32, value: i32, littleEndian?: bool): void; + /** The \`setInt64()\` method stores a signed 64-bit integer (long long) value at the specified byte offset from the start of the \`DataView\`. */ + setInt64(byteOffset: i32, value: i64, littleEndian?: bool): void; + /** The \`setUint8()\` method stores an unsigned 8-bit integer (byte) value at the specified byte offset from the start of the \`DataView\`. */ + setUint8(byteOffset: i32, value: u8): void; + /** The \`setUint16()\` method stores an unsigned 16-bit integer (unsigned short) value at the specified byte offset from the start of the \`DataView\`. */ + setUint16(byteOffset: i32, value: u16, littleEndian?: bool): void; + /** The \`setUint32()\` method stores an unsigned 32-bit integer (unsigned long) value at the specified byte offset from the start of the \`DataView\`. */ + setUint32(byteOffset: i32, value: u32, littleEndian?: bool): void; + /** The \`setUint64()\` method stores an unsigned 64-bit integer (unsigned long long) value at the specified byte offset from the start of the \`DataView\`. */ + setUint64(byteOffset: i32, value: u64, littleEndian?: bool): void; + /** Returns a string representation of DataView. */ + toString(): string; +} + +interface ArrayLike { + [key: number]: T; + length: i32; +} + +/** Interface for a typed view on an array buffer. */ +interface ArrayBufferView { + /** The {@link ArrayBuffer} referenced by this view. */ + readonly buffer: ArrayBuffer; + /** The offset in bytes from the start of the referenced {@link ArrayBuffer}. */ + readonly byteOffset: i32; + /** The length in bytes from the start of the referenced {@link ArrayBuffer}. */ + readonly byteLength: i32; + /** Returns raw pointer to data storage including offset (unsafe). */ + readonly dataStart: usize; +} + +/** @internal */ +declare abstract class TypedArray implements ArrayBufferView { + [key: number]: T; + /** Number of bytes per element. */ + static readonly BYTES_PER_ELEMENT: usize; + /** Constructs a new typed array. */ + constructor(length: i32); + /** The {@link ArrayBuffer} referenced by this view. */ + readonly buffer: ArrayBuffer; + /** The offset in bytes from the start of the referenced {@link ArrayBuffer}. */ + readonly byteOffset: i32; + /** The length in bytes from the start of the referenced {@link ArrayBuffer}. */ + readonly byteLength: i32; + /** Returns raw pointer to data storage including offset (unsafe). */ + readonly dataStart: usize; + /** The length (in elements). */ + readonly length: i32; + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): T; + /** The includes() method determines whether a typed array includes a certain element, returning true or false as appropriate. */ + includes(searchElement: T, fromIndex?: i32): bool; + /** The indexOf() method returns the first index at which a given element can be found in the typed array, or -1 if it is not present. */ + indexOf(searchElement: T, fromIndex?: i32): i32; + /** The lastIndexOf() method returns the last index at which a given element can be found in the typed array, or -1 if it is not present. The typed array is searched backwards, starting at fromIndex. */ + lastIndexOf(searchElement: T, fromIndex?: i32): i32; + /** Returns copied section of an TypedArray from begin inclusive to end exclusive */ + slice(begin?: i32, end?: i32): TypedArray; + /** Returns a new TypedArray of this type on the same ArrayBuffer from begin inclusive to end exclusive. */ + subarray(begin?: i32, end?: i32): TypedArray; + /** The copyWithin() method copies the sequence of array elements within the array to the position starting at target. The copy is taken from the index positions of the second and third arguments start and end. The end argument is optional and defaults to the length of the array. */ + copyWithin(target: i32, start: i32, end?: i32): this; + /** The reduce() method applies a function against an accumulator and each value of the typed array (from left-to-right) has to reduce it to a single value. This method has the same algorithm as Array.prototype.reduce(). */ + reduce(callbackfn: (accumulator: U, value: T, index: i32, self: this) => U, initialValue: U): U; + /** The reduceRight() method applies a function against an accumulator and each value of the typed array (from left-to-right) has to reduce it to a single value, starting from the end of the array. This method has the same algorithm as Array.prototype.reduceRight(). */ + reduceRight(callbackfn: (accumulator: U, value: T, index: i32, self: this) => U, initialValue: U): U; + /** The some() method tests whether some element in the typed array passes the test implemented by the provided function. This method has the same algorithm as Array.prototype.some().*/ + some(callbackfn: (value: T, index: i32, self: this) => bool): bool; + /** The map() method creates a new typed array with the results of calling a provided function on every element in this typed array. This method has the same algorithm as Array.prototype.map().*/ + map(callbackfn: (value: T, index: i32, self: this) => T): TypedArray; + /** The filter() method creates a new typed array with all elements that pass the test implemented by the provided function. This method has the same algorithm as Array.prototype.filter(). */ + filter(callbackfn: (value: T, index: i32, self: this) => bool): TypedArray; + /** The sort() method sorts the elements of a typed array numerically in place and returns the typed array. This method has the same algorithm as Array.prototype.sort(), except that sorts the values numerically instead of as strings. TypedArray is one of the typed array types here. */ + sort(callback?: (a: T, b: T) => i32): this; + /** The fill() method fills all the elements of a typed array from a start index to an end index with a static value. This method has the same algorithm as Array.prototype.fill(). */ + fill(value: T, start?: i32, end?: i32): this; + /** The findIndex() method returns an index in the typed array, if an element in the typed array satisfies the provided testing function. Otherwise -1 is returned. See also the find() [not implemented] method, which returns the value of a found element in the typed array instead of its index. */ + findIndex(callbackfn: (value: T, index: i32, self: this) => bool): i32; + /** The findLastIndex() method returns an index start searching from the end in the typed array, if an element in the typed array satisfies the provided testing function. Otherwise -1 is returned. See also the find() [not implemented] method, which returns the value of a found element in the typed array instead of its index. */ + findLastIndex(callbackfn: (value: T, index: i32, self: this) => bool): i32; + /** The every() method tests whether all elements in the typed array pass the test implemented by the provided function. This method has the same algorithm as Array.prototype.every(). */ + every(callbackfn: (value: T, index: i32, self: this) => bool): bool; + /** The forEach() method executes a provided function once per array element. This method has the same algorithm as Array.prototype.forEach().*/ + forEach(callbackfn: (value: T, index: i32, self: this) => void): void; + /** The reverse() method reverses a typed array in place. The first typed array element becomes the last and the last becomes the first. This method has the same algorithm as Array.prototype.reverse(). */ + reverse(): this; + /** The join() method joins all elements of an array into a string. This method has the same algorithm as Array.prototype.join(). */ + join(separator?: string): string; + /** The set() method stores multiple values in the typed array, reading input values from a specified array. */ + set(source: U, offset?: i32): void + /** The toString() method returns a string representing the specified array and its elements. This method has the same algorithm as Array.prototype.toString() */ + toString(): string; +} + +/** An array of twos-complement 8-bit signed integers. */ +declare class Int8Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Int8Array; +} +/** An array of 8-bit unsigned integers. */ +declare class Uint8Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint8Array; +} +/** A clamped array of 8-bit unsigned integers. */ +declare class Uint8ClampedArray extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint8ClampedArray; +} +/** An array of twos-complement 16-bit signed integers. */ +declare class Int16Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Int16Array; +} +/** An array of 16-bit unsigned integers. */ +declare class Uint16Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint16Array; +} +/** An array of twos-complement 32-bit signed integers. */ +declare class Int32Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Int32Array; +} +/** An array of 32-bit unsigned integers. */ +declare class Uint32Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint32Array; +} +/** An array of twos-complement 64-bit signed integers. */ +declare class Int64Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Int64Array; +} +/** An array of 64-bit unsigned integers. */ +declare class Uint64Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint64Array; +} +/** An array of 32-bit floating point numbers. */ +declare class Float32Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Float32Array; +} +/** An array of 64-bit floating point numbers. */ +declare class Float64Array extends TypedArray { + /** Wrap an ArrayBuffer */ + static wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Float64Array; +} + +/** Class representing a sequence of values of type \`T\`. */ +declare class Array { + + /** Tests if a value is an array. */ + static isArray(value: any): value is Array; + + [key: number]: T; + /** Current length of the array. */ + length: i32; + /** Returns raw pointer to data storage (unsafe). */ + readonly dataStart: usize; + /** Constructs a new array. */ + constructor(length?: i32); + at(index: i32): T; + fill(value: T, start?: i32, end?: i32): this; + findIndex(callbackfn: (value: T, index: i32, array: Array) => bool): i32; + findLastIndex(callbackfn: (value: T, index: i32, array: Array) => bool): i32; + includes(searchElement: T, fromIndex?: i32): bool; + indexOf(searchElement: T, fromIndex?: i32): i32; + lastIndexOf(searchElement: T, fromIndex?: i32): i32; + push(element: T): i32; + concat(items: T[]): T[]; + copyWithin(target: i32, start: i32, end?: i32): this; + pop(): T; + forEach(callbackfn: (value: T, index: i32, array: Array) => void): void; + map(callbackfn: (value: T, index: i32, array: Array) => U): Array; + filter(callbackfn: (value: T, index: i32, array: Array) => bool): Array; + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: Array) => U, initialValue: U): U; + every(callbackfn: (value: T, index: i32, array: Array) => bool): bool; + some(callbackfn: (value: T, index: i32, array: Array) => bool): bool; + shift(): T; + unshift(element: T): i32; + slice(from: i32, to?: i32): Array; + splice(start: i32, deleteCount?: i32): Array; + sort(comparator?: (a: T, b: T) => i32): this; + join(separator?: string): string; + reverse(): this; + /** Flattens an array of arrays. If any null entries exist in the array, they are ignored, unlike JavaScript's version of Array#flat(). */ + flat(): T extends unknown[] ? T : never; + toString(): string; +} + +/** Class representing a static (not resizable) sequence of values of type \`T\`. This class is @final. */ +declare class StaticArray { + [key: number]: T; + static fromArray(source: Array): StaticArray; + static concat(source: StaticArray, other: StaticArray): StaticArray; + static slice(source: StaticArray, start?: i32, end?: i32): StaticArray; + readonly length: i32; + constructor(length?: i32); + at(index: i32): T; + fill(value: T, start?: i32, end?: i32): this; + findIndex(callbackfn: (value: T, index: i32, array: StaticArray) => bool): i32; + findLastIndex(callbackfn: (value: T, index: i32, array: StaticArray) => bool): i32; + copyWithin(target: i32, start: i32, end?: i32): this; + includes(searchElement: T, fromIndex?: i32): bool; + indexOf(searchElement: T, fromIndex?: i32): i32; + lastIndexOf(searchElement: T, fromIndex?: i32): i32; + forEach(callbackfn: (value: T, index: i32, array: StaticArray) => void): void; + map(callbackfn: (value: T, index: i32, array: StaticArray) => U): Array; + filter(callbackfn: (value: T, index: i32, array: StaticArray) => bool): Array; + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: StaticArray) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: i32, array: StaticArray) => U, initialValue: U): U; + every(callbackfn: (value: T, index: i32, array: StaticArray) => bool): bool; + some(callbackfn: (value: T, index: i32, array: StaticArray) => bool): bool; + concat(items: Array): Array; + slice(from: i32, to?: i32): Array; + sort(comparator?: (a: T, b: T) => i32): this; + join(separator?: string): string; + reverse(): this; + toString(): string; +} + +/** Class representing a sequence of characters. */ +declare class String { + static fromCharCode(ls: i32, hs?: i32): string; + static fromCharCodes(arr: u16[]): string; + static fromCodePoint(code: i32): string; + static fromCodePoints(arr: i32[]): string; + static raw(parts: TemplateStringsArray, ...args: any[]): string; + readonly length: i32; + at(index: i32): string; + charAt(index: i32): string; + charCodeAt(index: i32): i32; + codePointAt(index: i32): i32; + concat(other: string): string; + endsWith(other: string): bool; + indexOf(other: string, fromIndex?: i32): i32; + lastIndexOf(other: string, fromIndex?: i32): i32; + localeCompare(other: string): i32; + includes(other: string): bool; + startsWith(other: string): bool; + substr(start: i32, length?: i32): string; + substring(start: i32, end?: i32): string; + trim(): string; + trimLeft(): string; + trimRight(): string; + trimStart(): string; + trimEnd(): string; + padStart(targetLength: i32, padString?: string): string; + padEnd(targetLength: i32, padString?: string): string; + repeat(count?: i32): string; + replace(search: string, replacement: string): string; + replaceAll(search: string, replacement: string): string; + slice(beginIndex: i32, endIndex?: i32): string; + split(separator?: string, limit?: i32): string[]; + toLowerCase(): string; + toUpperCase(): string; + toString(): string; +} + +declare namespace String { + /** Encoding helpers for UTF-8. */ + export namespace UTF8 { + /** UTF-8 encoding error modes. */ + export const enum ErrorMode { + /** Keeps unpaired surrogates as of WTF-8. This is the default. */ + WTF8, + /** Replaces unpaired surrogates with the replacement character (U+FFFD). */ + REPLACE, + /** Throws an error on unpaired surrogates. */ + ERROR + } + /** Calculates the byte length of the specified string when encoded as UTF-8, optionally null terminated. */ + export function byteLength(str: string, nullTerminated?: bool): i32; + /** Encodes the specified string to UTF-8 bytes, optionally null terminated. ErrorMode defaults to WTF-8. */ + export function encode(str: string, nullTerminated?: bool, errorMode?: ErrorMode): ArrayBuffer; + /** Encodes the specified raw string to UTF-8 bytes, opionally null terminated. ErrorMode defaults to WTF-8. Returns the number of bytes written. */ + export function encodeUnsafe(str: usize, len: i32, buf: usize, nullTerminated?: bool, errorMode?: ErrorMode): usize; + /** Decodes the specified buffer from UTF-8 bytes to a string, optionally null terminated. */ + export function decode(buf: ArrayBuffer, nullTerminated?: bool): string; + /** Decodes raw UTF-8 bytes to a string, optionally null terminated. */ + export function decodeUnsafe(buf: usize, len: usize, nullTerminated?: bool): string; + } + /** Encoding helpers for UTF-16. */ + export namespace UTF16 { + /** Calculates the byte length of the specified string when encoded as UTF-16. */ + export function byteLength(str: string): i32; + /** Encodes the specified string to UTF-16 bytes. */ + export function encode(str: string): ArrayBuffer; + /** Encodes the specified raw string to UTF-16 bytes. Returns the number of bytes written. */ + export function encodeUnsafe(str: usize, len: i32, buf: usize): usize; + /** Decodes the specified buffer from UTF-16 bytes to a string. */ + export function decode(buf: ArrayBuffer): string; + /** Decodes raw UTF-16 bytes to a string. */ + export function decodeUnsafe(buf: usize, len: usize): string; + } +} + +declare class TemplateStringsArray extends Array { + readonly raw: string[]; +} + +declare class Object { + /** The Object.is() method determines whether two values are the same value. */ + static is(value1: T, value2: T): bool; +} + +declare namespace performance { + /** Gets a high resolution timestamp measured in milliseconds. */ + export function now(): f64; +} + +declare class Date { + /** Returns the UTC timestamp in milliseconds of the specified date. */ + static UTC( + year: i32, + month: i32, + day: i32, + hour: i32, + minute: i32, + second: i32, + millisecond: i32 + ): i64; + /** Returns the current UTC timestamp in milliseconds. */ + static now(): i64; + /** Parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. */ + static parse(dateString: string): Date; + static fromString(dateString: string): Date; + /** Constructs a new date object from an UTC timestamp in milliseconds. */ + constructor(value: i64); + /** Returns the UTC timestamp of this date in milliseconds. */ + getTime(): i64; + /** Sets the UTC timestamp of this date in milliseconds. */ + setTime(value: i64): i64; + + getUTCFullYear(): i32; + getUTCMonth(): i32; + getUTCDate(): i32; + getUTCDay(): i32; + getUTCHours(): i32; + getUTCMinutes(): i32; + getUTCSeconds(): i32; + getUTCMilliseconds(): i32; + + setUTCFullYear(value: i32): void; + setUTCMonth(value: i32, day?: i32): void; + setUTCDate(value: i32): void; + setUTCHours(value: i32): void; + setUTCMinutes(value: i32): void; + setUTCSeconds(value: i32): void; + setUTCMilliseconds(value: i32): void; + + toString(): string; + toISOString(): string; + toUTCString(): string; + toDateString(): string; + toTimeString(): string; +} + +/** Class for representing a runtime error. Base class of all errors. */ +declare class Error { + + /** Error name. */ + name: string; + + /** Message provided on construction. */ + message: string; + + /** Stack trace. */ + stack?: string; + + /** Constructs a new error, optionally with a message. */ + constructor(message?: string); + + /** Method returns a string representing the specified Error class. */ + toString(): string; +} + +/** Class for indicating an error when a value is not in the set or range of allowed values. */ +declare class RangeError extends Error { } + +/** Class for indicating an error when a value is not of the expected type. */ +declare class TypeError extends Error { } + +/** Class for indicating an error when trying to interpret syntactically invalid code. */ +declare class SyntaxError extends Error { } + +/** Class for indicating an error when a global URI handling function was used in a wrong way. */ +declare class URIError extends Error { } + +interface Function { + /** Function table index. */ + readonly index: u32; + /** Function name. Always an empty string. */ + readonly name: string; + /** Number of expected parameters. */ + readonly length: u32; + /** Calls this function indirectly with the specified arguments. */ + call(thisArg: unknown, ...args: unknown[]): any; + /** Returns a string representation of this function. */ + toString(): string; +} +interface IArguments {} +interface RegExp {} + +declare class Map { + readonly size: i32; + has(key: K): bool; + set(key: K, value: V): this; + get(key: K): V; + delete(key: K): bool; + clear(): void; + keys(): K[]; // preliminary + values(): V[]; // preliminary + toString(): string; +} + +declare class Set { + readonly size: i32; + has(value: K): bool; + add(value: K): this; + delete(value: K): bool; + clear(): void; + values(): K[]; // preliminary + toString(): string; +} + +interface SymbolConstructor { + readonly hasInstance: symbol; + readonly isConcatSpreadable: symbol; + readonly isRegExp: symbol; + readonly iterator: symbol; + readonly match: symbol; + readonly replace: symbol; + readonly search: symbol; + readonly species: symbol; + readonly split: symbol; + readonly toPrimitive: symbol; + readonly toStringTag: symbol; + readonly unscopables: symbol; + (description?: string | null): symbol; + for(key: string): symbol; + keyFor(sym: symbol): string | null; +} + +declare const Symbol: SymbolConstructor; + +/** @internal */ +interface IMath { + /** The base of natural logarithms, e, approximately 2.718. */ + readonly E: T; + /** The natural logarithm of 2, approximately 0.693. */ + readonly LN2: T; + /** The natural logarithm of 10, approximately 2.302. */ + readonly LN10: T; + /** The base 2 logarithm of e, approximately 1.442. */ + readonly LOG2E: T; + /** The base 10 logarithm of e, approximately 0.434. */ + readonly LOG10E: T; + /** The ratio of the circumference of a circle to its diameter, approximately 3.14159. */ + readonly PI: T; + /** The square root of 1/2, approximately 0.707. */ + readonly SQRT1_2: T; + /** The square root of 2, approximately 1.414. */ + readonly SQRT2: T; + /** Returns the absolute value of \`x\`. */ + abs(x: T): T; + /** Returns the arccosine (in radians) of \`x\`. */ + acos(x: T): T; + /** Returns the hyperbolic arc-cosine of \`x\`. */ + acosh(x: T): T; + /** Returns the arcsine (in radians) of \`x\`. */ + asin(x: T): T; + /** Returns the hyperbolic arcsine of \`x\`. */ + asinh(x: T): T; + /** Returns the arctangent (in radians) of \`x\`. */ + atan(x: T): T; + /** Returns the arctangent of the quotient of its arguments. */ + atan2(y: T, x: T): T; + /** Returns the hyperbolic arctangent of \`x\`. */ + atanh(x: T): T; + /** Returns the cube root of \`x\`. */ + cbrt(x: T): T; + /** Returns the smallest integer greater than or equal to \`x\`. */ + ceil(x: T): T; + /** Returns the number of leading zero bits in the 32-bit binary representation of \`x\`. */ + clz32(x: T): T; + /** Returns the cosine (in radians) of \`x\`. */ + cos(x: T): T; + /** Returns the hyperbolic cosine of \`x\`. */ + cosh(x: T): T; + /** Returns e to the power of \`x\`. */ + exp(x: T): T; + /** Returns e to the power of \`x\`, minus 1. */ + expm1(x: T): T; + /** Returns the largest integer less than or equal to \`x\`. */ + floor(x: T): T; + /** Returns the nearest 32-bit single precision float representation of \`x\`. */ + fround(x: T): T; + /** Returns the square root of the sum of squares of its arguments. */ + hypot(value1: T, value2: T): T; // TODO: rest + /** Returns the result of the C-like 32-bit multiplication of \`a\` and \`b\`. */ + imul(a: T, b: T): T; + /** Returns the natural logarithm (base e) of \`x\`. */ + log(x: T): T; + /** Returns the base 10 logarithm of \`x\`. */ + log10(x: T): T; + /** Returns the natural logarithm (base e) of 1 + \`x\`. */ + log1p(x: T): T; + /** Returns the base 2 logarithm of \`x\`. */ + log2(x: T): T; + /** Returns the largest-valued number of its arguments. */ + max(value1: T, value2: T): T; // TODO: rest + /** Returns the lowest-valued number of its arguments. */ + min(value1: T, value2: T): T; // TODO: rest + /** Returns \`base\` to the power of \`exponent\`. */ + pow(base: T, exponent: T): T; + /** Returns a pseudo-random number in the range from 0.0 inclusive up to but not including 1.0. */ + random(): T; + /** Returns the value of \`x\` rounded to the nearest integer. */ + round(x: T): T; + /** Returns the sign of \`x\`, indicating whether the number is positive, negative or zero. */ + sign(x: T): T; + /** Returns whether the sign bit of \`x\` is set. */ + signbit(x: T): bool; + /** Returns the sine of \`x\`. */ + sin(x: T): T; + /** Returns the hyperbolic sine of \`x\`. */ + sinh(x: T): T; + /** Returns the square root of \`x\`. */ + sqrt(x: T): T; + /** Returns the tangent of \`x\`. */ + tan(x: T): T; + /** Returns the hyperbolic tangent of \`x\`. */ + tanh(x: T): T; + /** Returns the integer part of \`x\` by removing any fractional digits. */ + trunc(x: T): T; +} + +/** @internal */ +interface INativeMath extends IMath { + /** Contains sin value produced after Math/Mathf.sincos */ + sincos_sin: T; + /** Contains cos value produced after Math/Mathf.sincos */ + sincos_cos: T; + /** Seeds the random number generator. */ + seedRandom(value: i64): void; + /** Multiplies a floating point \`x\` by 2 raised to power exp \`n\`. */ + scalbn(x: T, n: i32): T; + /** Returns the floating-point remainder of \`x / y\` (rounded towards zero). */ + mod(x: T, y: T): T; + /** Returns the floating-point remainder of \`x / y\` (rounded to nearest). */ + rem(x: T, y: T): T; + /** Returns sin and cos simultaneously for same angle. Results stored to \`sincos_s32/64\` and \`sincos_c32/64\` globals */ + sincos(x: T): void; + /** Returns 2 raised to the given power x. Equivalent to 2 ** x. */ + exp2(x: T): T; +} + +/** Double precision math imported from JavaScript. */ +declare const JSMath: IMath; +/** Double precision math implemented natively. */ +declare const NativeMath: INativeMath; +/** Single precision math implemented natively. */ +declare const NativeMathf: INativeMath; +/** Alias of {@link NativeMath} or {@link JSMath} respectively. Defaults to \`NativeMath\`. */ +declare const Math: IMath; +/** Alias of {@link NativeMathf} or {@link JSMath} respectively. Defaults to \`NativeMathf\`. */ +declare const Mathf: IMath; + +/** Environmental abort function. */ +declare function abort(msg?: string | null, fileName?: string | null, lineNumber?: i32, columnNumber?: i32): never; +/** Environmental tracing function. */ +declare function trace(msg: string, n?: i32, a0?: f64, a1?: f64, a2?: f64, a3?: f64, a4?: f64): void; +/** Environmental seeding function. */ +declare function seed(): f64; + +/** Node-like process on top of WASI. */ +declare namespace process { + /** String representing the CPU architecture for which the binary was compiled. Either \`wasm32\` or \`wasm64\`. */ + export const arch: string; + /** String representing the operating system platform for which the binary was compiled. Always \`wasm\`. */ + export const platform: string; + /** Array of command line arguments passed to the binary upon instantiation. */ + export const argv: string[]; + /** Map of variables in the binary's user environment. */ + export const env: Map; + /** Terminates the process with either the given exit code, or \`process.exitCode\` if omitted. */ + export function exit(code?: i32): void; + /** \`exit()\`\u2019s default value. Defaults to \`0\`. */ + export var exitCode: i32; + /** Stream connected to \`stdin\` (fd \`0\`). */ + export const stdin: ReadableStream; + /** Stream connected to \`stdout\` (fd \`1\`). */ + export const stdout: WritableStream; + /** Stream connected to \`stderr\` (fd \`2\`). */ + export const stderr: WritableStream; + /** Obtains the system's current time of day, in milliseconds since Unix epoch. */ + export function time(): i64; + /** Obtains the system's monotonic high resolution time, in nanoseconds since an arbitrary time in the past. */ + export function hrtime(): u64; + + interface Stream { + /** Closes the stream. Throws if already closed or if the stream cannot be closed. */ + close(): void; + } + interface ReadableStream extends Stream { + /** Reads available data from the stream, into \`buffer\` at offset \`offset\`, returning the number of bytes read. */ + read(buffer: ArrayBuffer, offset?: isize): i32; + } + interface WritableStream extends Stream { + /** Writes string or buffer to the stream. */ + write(data: T): void; + } +} + +/** Browser-like console on top of WASI. */ +declare namespace console { + /** Logs \`message\` to console if \`assertion\` is false-ish. */ + export function assert(assertion: T, message?: string): void; + /** Outputs \`message\` to the console. */ + export function log(message?: string): void; + /** Outputs \`message\` to the console, prefixed with "Debug:". */ + export function debug(message?: string): void; + /** Outputs \`message\` to the console, prefixed with "Info:". */ + export function info(message?: string): void; + /** Outputs \`message\` to the console, prefixed with "Warning:". */ + export function warn(message?: string): void; + /** Outputs \`message\` to the console, prefixed with "Error:". */ + export function error(message?: string): void; + /** Starts a new timer using the specified \`label\`. */ + export function time(label?: string): void; + /** Logs the current value of a timer previously started with \`console.time\`. */ + export function timeLog(label?: string): void; + /** Logs the current value of a timer previously started with \`console.time\` and discards the timer. */ + export function timeEnd(label?: string): void; +} + +/** Browser-like crypto utilities on top of WASI. */ +declare namespace crypto { + /** Fills \`array\` with cryptographically strong random values. */ + export function getRandomValues(array: Uint8Array): void; +} + +// Decorators + +interface TypedPropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + writable?: boolean; + value?: T; + get?(): T; + set?(value: T): void; +} + +/** Annotates a method as a binary operator overload for the specified \`token\`. */ +declare function operator(token: + "[]" | "[]=" | "{}" | "{}=" | "==" | "!=" | ">" | "<" | "<=" | ">=" | + ">>" | ">>>" | "<<" | "&" | "|" | "^" | "+" | "-" | "*" | "**" | "/" | "%" +): ( + target: any, + propertyKey: string, + descriptor: TypedPropertyDescriptor +) => TypedPropertyDescriptor | void; + +declare namespace operator { + /** Annotates a method as a binary operator overload for the specified \`token\`. */ + export function binary(token: + "[]" | "[]=" | "{}" | "{}=" | "==" | "!=" | ">" | "<" | "<=" | ">=" | + ">>" | ">>>" | "<<" | "&" | "|" | "^" | "+" | "-" | "*" | "**" | "/" | "%" + ): ( + target: any, + propertyKey: string, + descriptor: TypedPropertyDescriptor + ) => TypedPropertyDescriptor | void; + /** Annotates a method as an unary prefix operator overload for the specified \`token\`. */ + export function prefix(token: "!" | "~" | "+" | "-" | "++" | "--"): ( + target: any, + propertyKey: string, + descriptor: TypedPropertyDescriptor + ) => TypedPropertyDescriptor | void; + /** Annotates a method as an unary postfix operator overload for the specified \`token\`. */ + export function postfix(token: "++" | "--"): ( + target: any, + propertyKey: string, + descriptor: TypedPropertyDescriptor + ) => TypedPropertyDescriptor | void; +} + +/** Annotates an element as a program global. */ +declare function global(...args: any[]): any; + +/** Annotates a class as being unmanaged with limited capabilities. */ +declare function unmanaged(constructor: Function): void; + +/** Annotates a class as being final / non-derivable. */ +declare function final(constructor: Function): void; + +/** Annotates a method, function or constant global as always inlined. */ +declare function inline(...args: any[]): any; + +/** Annotates a method, function or constant global as unsafe. */ +declare function unsafe(...args: any[]): any; + +/** Annotates an explicit external name of a function or global. */ +declare function external(name: string): any; +declare function external(moduleName: string, name: string): any; +declare namespace external { + function js(code: string): any; +} + +/** Annotates a global for lazy compilation. */ +declare function lazy(...args: any[]): any; +`,portable:`/** + * Environment definitions for compiling AssemblyScript to JavaScript using tsc. + * + * Note that semantic differences require additional explicit conversions for full compatibility. + * For example, when casting an i32 to an u8, doing \`(someI32 & 0xff)\` will yield the same + * result when compiling to WebAssembly or JS while \`someI32\` alone does nothing in JS. + * + * Note that i64's are not portable (JS numbers are IEEE754 doubles with a maximum safe integer + * value of 2^53-1) and instead require a compatibility layer to work in JS as well, as for example + * {@link glue/js/i64} respectively {@link glue/wasm/i64}. + * + * @module std/portable + *//***/ + +// Types + +declare type bool = boolean; +declare type i8 = number; +declare type i16 = number; +declare type i32 = number; +declare type isize = number; +declare type u8 = number; +declare type u16 = number; +declare type u32 = number; +declare type usize = number; +declare type f32 = number; +declare type f64 = number; + +/** Special type evaluating the indexed access index type. */ +declare type indexof = keyof T; +/** Special type evaluating the indexed access value type. */ +declare type valueof = T[0]; + +// Compiler hints + +/** Compiler target. 0 = JS, 1 = WASM32, 2 = WASM64. */ +declare const ASC_TARGET: i32; +/** Runtime type. 0 = Stub, 1 = Minimal, 2 = Incremental. */ +declare const ASC_RUNTIME: i32; +/** Provided noAssert option. */ +declare const ASC_NO_ASSERT: bool; +/** Provided memoryBase option. */ +declare const ASC_MEMORY_BASE: i32; +/** Provided optimizeLevel option. */ +declare const ASC_OPTIMIZE_LEVEL: i32; +/** Provided shrinkLevel option. */ +declare const ASC_SHRINK_LEVEL: i32; +/** Whether the mutable global feature is enabled. */ +declare const ASC_FEATURE_MUTABLE_GLOBAL: bool; +/** Whether the sign extension feature is enabled. */ +declare const ASC_FEATURE_SIGN_EXTENSION: bool; + +// Builtins + +/** Performs the sign-agnostic count leading zero bits operation on a 32-bit integer. All zero bits are considered leading if the value is zero. */ +declare function clz(value: T): T; +/** Performs the sign-agnostic count tailing zero bits operation on a 32-bit integer. All zero bits are considered trailing if the value is zero. */ +declare function ctz(value: T): T; +/** Performs the sign-agnostic count number of one bits operation on a 32-bit integer. */ +declare function popcnt(value: T): T; +/** Performs the sign-agnostic rotate left operation on a 32-bit integer. */ +declare function rotl(value: T, shift: T): T; +/** Performs the sign-agnostic rotate right operation on a 32-bit integer. */ +declare function rotr(value: T, shift: T): T; +/** Computes the absolute value of an integer or float. */ +declare function abs(value: T): T; +/** Determines the maximum of two integers or floats. If either operand is \`NaN\`, returns \`NaN\`. */ +declare function max(left: T, right: T): T; +/** Determines the minimum of two integers or floats. If either operand is \`NaN\`, returns \`NaN\`. */ +declare function min(left: T, right: T): T; +/** Composes a 32-bit or 64-bit float from the magnitude of \`x\` and the sign of \`y\`. */ +declare function copysign(x: T, y: T): T; +/** Performs the ceiling operation on a 32-bit or 64-bit float. */ +declare function ceil(value: T): T; +/** Performs the floor operation on a 32-bit or 64-bit float. */ +declare function floor(value: T): T; +/** Rounds to the nearest integer tied to even of a 32-bit or 64-bit float. */ +declare function nearest(value: T): T; +/** Selects one of two pre-evaluated values depending on the condition. */ +declare function select(ifTrue: T, ifFalse: T, condition: bool): T; +/** Calculates the square root of a 32-bit or 64-bit float. */ +declare function sqrt(value: T): T; +/** Rounds to the nearest integer towards zero of a 32-bit or 64-bit float. */ +declare function trunc(value: T): T; +/** Emits an unreachable operation that results in a runtime error when executed. */ +declare function unreachable(): any; // sic + +/** Changes the type of any value of \`usize\` kind to another one of \`usize\` kind. Useful for casting class instances to their pointer values and vice-versa. Beware that this is unsafe.*/ +declare function changetype(value: any): T; +/** Explicitly requests no bounds checks on the provided expression. Useful for array accesses. */ +declare function unchecked(value: T): T; +/** Tests if the specified value is a valid integer. Can't distinguish an integer from an integral float. */ +declare function isInteger(value: any): value is number; +/** Tests if the specified value is a valid float. Can't distinguish a float from an integer. */ +declare function isFloat(value: any): value is number; +/** Tests if the specified value is of a nullable reference type. */ +declare function isNullable(value: any): bool; +/** Tests if the specified value is of a reference type. */ +declare function isReference(value: any): value is object | string; +/** Tests if the specified value is of a function type */ +declare function isFunction(value: any): value is Function; +/** Tests if the specified value can be used as a string. */ +declare function isString(value: any): value is string | String; +/** Tests if the specified value can be used as an array. */ +declare function isArray(value: any): value is Array; +/** Tests if the specified type *or* expression can be used as an array like object. */ +declare function isArrayLike(value: any): value is ArrayLike; +/** Tests if the specified expression resolves to a defined element. */ +declare function isDefined(expression: any): bool; +/** Tests if the specified expression evaluates to a constant value. */ +declare function isConstant(expression: any): bool; +/** Traps if the specified value is not true-ish, otherwise returns the value. */ +declare function assert(isTrueish: T, message?: string): T & (object | string | number); // any better way to model \`: T != null\`? +/** Parses an integer string to a 64-bit float. */ +declare function parseInt(str: string, radix?: i32): f64; +/** Parses a floating point string to a 64-bit float. */ +declare function parseFloat(str: string): f64; +/** Returns the 64-bit floating-point remainder of \`x/y\`. */ +declare function fmod(x: f64, y: f64): f64; +/** Returns the 32-bit floating-point remainder of \`x/y\`. */ +declare function fmodf(x: f32, y: f32): f32; + +/** Converts any other numeric value to an 8-bit signed integer. */ +declare function i8(value: any): i8; +declare namespace i8 { + /** Smallest representable value. */ + export const MIN_VALUE: i8; + /** Largest representable value. */ + export const MAX_VALUE: i8; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): i8; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): i8; +} +/** Converts any other numeric value to a 16-bit signed integer. */ +declare function i16(value: any): i16; +declare namespace i16 { + /** Smallest representable value. */ + export const MIN_VALUE: i16; + /** Largest representable value. */ + export const MAX_VALUE: i16; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): i16; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): i16; +} +/** Converts any other numeric value to a 32-bit signed integer. */ +declare function i32(value: any): i32; +declare namespace i32 { + /** Smallest representable value. */ + export const MIN_VALUE: i32; + /** Largest representable value. */ + export const MAX_VALUE: i32; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): i32; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): i32; +} +/** Converts any other numeric value to a 32-bit (in WASM32) respectivel 64-bit (in WASM64) signed integer. */ +declare function isize(value: any): isize; +declare namespace isize { + /** Smallest representable value. */ + export const MIN_VALUE: isize; + /** Largest representable value. */ + export const MAX_VALUE: isize; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): isize; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): isize; +} +/** Converts any other numeric value to an 8-bit unsigned integer. */ +declare function u8(value: any): u8; +declare namespace u8 { + /** Smallest representable value. */ + export const MIN_VALUE: u8; + /** Largest representable value. */ + export const MAX_VALUE: u8; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): u8; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): u8; +} +/** Converts any other numeric value to a 16-bit unsigned integer. */ +declare function u16(value: any): u16; +declare namespace u16 { + /** Smallest representable value. */ + export const MIN_VALUE: u16; + /** Largest representable value. */ + export const MAX_VALUE: u16; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): u16; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): u16; +} +/** Converts any other numeric value to a 32-bit unsigned integer. */ +declare function u32(value: any): u32; +declare namespace u32 { + /** Smallest representable value. */ + export const MIN_VALUE: u32; + /** Largest representable value. */ + export const MAX_VALUE: u32; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): u32; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): u32; +} +/** Converts any other numeric value to a 32-bit (in WASM32) respectivel 64-bit (in WASM64) unsigned integer. */ +declare function usize(value: any): isize; +declare namespace usize { + /** Smallest representable value. */ + export const MIN_VALUE: usize; + /** Largest representable value. */ + export const MAX_VALUE: usize; + /** Converts a string to a floating-point number and cast to target integer after. */ + export function parseFloat(string: string): usize; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): usize; +} +/** Converts any other numeric value to a 1-bit unsigned integer. */ +declare function bool(value: any): bool; +declare namespace bool { + /** Smallest representable value. */ + export const MIN_VALUE: bool; + /** Largest representable value. */ + export const MAX_VALUE: bool; +} +/** Converts any other numeric value to a 32-bit float. */ +declare function f32(value: any): f32; +declare namespace f32 { + /** Smallest representable value. */ + export const MIN_VALUE: f32; + /** Largest representable value. */ + export const MAX_VALUE: f32; + /** Smallest normalized positive value. */ + export const MIN_NORMAL_VALUE: f32; + /** Smallest safely representable integer value. */ + export const MIN_SAFE_INTEGER: f32; + /** Largest safely representable integer value. */ + export const MAX_SAFE_INTEGER: f32; + /** Positive infinity value. */ + export const POSITIVE_INFINITY: f32; + /** Negative infinity value. */ + export const NEGATIVE_INFINITY: f32; + /** Not a number value. */ + /* eslint no-shadow-restricted-names: "off" */ + export const NaN: f32; + /** Difference between 1 and the smallest representable value greater than 1. */ + export const EPSILON: f32; + /** Returns a boolean value that indicates whether a value is the reserved value NaN (not a number). */ + export function isNaN(value: f32): bool; + /** Returns true if passed value is finite. */ + export function isFinite(value: f32): bool; + /** Returns true if the value passed is a safe integer. */ + export function isSafeInteger(value: f32): bool; + /** Returns true if the value passed is an integer, false otherwise. */ + export function isInteger(value: f32): bool; + /** Converts a string to a floating-point number. */ + export function parseFloat(string: string): f32; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): f32; +} +/** Converts any other numeric value to a 64-bit float. */ +declare function f64(value: any): f64; +declare namespace f64 { + /** Smallest representable value. */ + export const MIN_VALUE: f64; + /** Largest representable value. */ + export const MAX_VALUE: f64; + /** Smallest normalized positive value. */ + export const MIN_NORMAL_VALUE: f64; + /** Smallest safely representable integer value. */ + export const MIN_SAFE_INTEGER: f64; + /** Largest safely representable integer value. */ + export const MAX_SAFE_INTEGER: f64; + /** Positive infinity value. */ + export const POSITIVE_INFINITY: f64; + /** Negative infinity value. */ + export const NEGATIVE_INFINITY: f64; + /** Not a number value. */ + /* eslint no-shadow-restricted-names: "off" */ + export const NaN: f64; + /** Difference between 1 and the smallest representable value greater than 1. */ + export const EPSILON: f64; + /** Returns a boolean value that indicates whether a value is the reserved value NaN (not a number). */ + export function isNaN(value: f32): bool; + /** Returns true if passed value is finite. */ + export function isFinite(value: f32): bool; + /** Returns true if the value passed is a safe integer. */ + export function isSafeInteger(value: f64): bool; + /** Returns true if the value passed is an integer, false otherwise. */ + export function isInteger(value: f64): bool; + /** Converts a string to a floating-point number. */ + export function parseFloat(string: string): f64; + /** Converts A string to an integer. */ + export function parseInt(string: string, radix?: i32): f64; +} + +// Polyfills + +/** [Polyfill] Performs the sign-agnostic reverse bytes **/ +declare function bswap(value: T): T; +/** [Polyfill] Performs the sign-agnostic reverse bytes only for last 16-bit **/ +declare function bswap16(value: T): T; + +// Standard library + +declare const Mathf: typeof Math; +declare const JSMath: typeof Math; + +declare interface StringConstructor { + /** Equivalent to calling \`String.fromCharCode\` with multiple arguments. */ + fromCharCodes(arr: u16[]): string; + /** Equivalent to calling \`String.fromCodePoint\` with multiple arguments. */ + fromCodePoints(arr: i32[]): string; +} + +declare interface String { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): string; +} + +/** Annotates a class as being unmanaged with limited capabilities. */ +declare function unmanaged(constructor: Function): void; + +/** Environmental tracing function. */ +declare function trace(msg: string, n?: i32, a0?: f64, a1?: f64, a2?: f64, a3?: f64, a4?: f64): void; + +declare interface Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): T; + /** Returns an index start searching from the end in the array */ + findLastIndex(callbackfn: (value: T, index: i32, self: Array) => bool): i32; +} + +declare interface Int8ArrayConstructor { + /** Equivalent to calling \`new Int8Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Int8Array; +} + +declare interface Int8Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): i8; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: i8, index: i32, self: Int8Array) => bool): i32; +} + +declare interface Uint8ArrayConstructor { + /** Equivalent to calling \`new Uint8Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint8Array; +} + +declare interface Uint8Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): u8; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: u8, index: i32, self: Uint8Array) => bool): i32; +} + +declare interface Uint8ClampedArrayConstructor { + /** Equivalent to calling \`new Uint8ClampedArray\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint8ClampedArray; +} + +declare interface Uint8ClampedArray { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): u8; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: u8, index: i32, self: Uint8ClampedArray) => bool): i32; +} + +declare interface Int16ArrayConstructor { + /** Equivalent to calling \`new Int16Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Int16Array; +} + +declare interface Int16Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): i16; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: i16, index: i32, self: Int16Array) => bool): i32; +} + +declare interface Uint16ArrayConstructor { + /** Equivalent to calling \`new Uint16Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint16Array; +} + +declare interface Uint16Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): u16; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: u16, index: i32, self: Uint16Array) => bool): i32; +} + +declare interface Int32ArrayConstructor { + /** Equivalent to calling \`new Int32Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Int32Array; +} + +declare interface Int32Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): i32; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: i32, index: i32, self: Int32Array) => bool): i32; +} + +declare interface Uint32ArrayConstructor { + /** Equivalent to calling \`new Uint32Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Uint32Array; +} + +declare interface Uint32Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): u32; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: u32, index: i32, self: Uint32Array) => bool): i32; +} + +declare interface Float32ArrayConstructor { + /** Equivalent to calling \`new Float32Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Float32Array; +} + +declare interface Float32Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): f32; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: f32, index: i32, self: Float32Array) => bool): i32; +} + +declare interface Float64ArrayConstructor { + /** Equivalent to calling \`new Float64Array\` with multiple arguments. */ + wrap(buffer: ArrayBuffer, byteOffset?: i32, length?: i32): Float64Array; +} + +declare interface Float64Array { + /** Returns value using relative indexing. Index may be negative */ + at(index: i32): f64; + /** Returns an index start searching from the end in the typedarray */ + findLastIndex(callbackfn: (value: f64, index: i32, self: Float64Array) => bool): i32; +} + +// FIXME: remove +declare function offsetof(fieldName?: string): usize; +declare function idof(): u32; +`};var vn={};on(vn,{default:()=>Xn});Ln(vn,er);import*as er from"binaryen";import{default as Xn}from"binaryen";import*as Ut from"assemblyscript";var v=Ut,Kn=G.argv.indexOf("--wasm");if(~Kn){let t=String(G.argv[Kn+1]);G.argv.splice(Kn,2),v=await import(new URL(t,gn.pathToFileURL(G.cwd()+"/")))}var Wn=un.createRequire(import.meta.url),Jn=G.platform==="win32",F=Jn?`\r +`:` +`,qn=Jn?"\\":"/",_=".ts",Mt=`.d${_}`,yn=new RegExp("\\"+_+"$"),Pt=new RegExp("^(?!.*\\.d\\"+_+"$).*\\"+_+"$");function Oe(t){return t.replace(/-/g,"_").toUpperCase()}var Zn=we,Vt=nn,H=Se,W=De,Gt=Ie,ke=3,Re=0;function Qn(t,n=[]){return Object.keys(t||{}).forEach(e=>{let i=t[e],o=nn[e];o&&o.type==="b"?i&&n.push(`--${e}`):Array.isArray(i)?i.forEach(r=>{n.push(`--${e}`,String(r))}):n.push(`--${e}`,String(i))}),n}async function Ht(t,n={}){typeof t=="string"&&(t={[`input${_}`]:t});var e=["--outFile","binary","--textFile","text"];Qn(n,e);let i={},o=await Ue(e.concat(Object.keys(t)),{readFile:r=>Object.prototype.hasOwnProperty.call(t,r)?t[r]:null,writeFile:(r,l)=>{i[r]=l},listFiles:()=>[]});return Object.assign(o,i)}async function Ue(t,n){Array.isArray(t)||(t=Qn(t)),n||(n={});let e=n.stats||new ne,i=e.begin(),o=0,r=0,l=0,f=(Zn||"").split(".");f.length===3&&(r=parseInt(f[0])|0,o=parseInt(f[1])|0,l=parseInt(f[2])|0);let u=n.stdout||$n(),x=n.stderr||$n(),c=n.readFile||ae,m=n.writeFile||se,y=n.listFiles||le,g=ze(t,nn,!1),s=g.options;t=g.arguments;let B=new cn(u),I=new cn(x);s.noColors&&(B.enabled=!1,I.enabled=!1);let q=g.unknown;q.length&&q.forEach(a=>{x.write(`${I.yellow("WARNING ")}Unknown option '${a}'${F}`)});let Y=g.trailing;Y.length&&x.write(`${I.yellow("WARNING ")}Unsupported trailing arguments: ${Y.join(" ")}${F}`);var R=null,O=null,C=(a,p={})=>(a&&x.write(`${I.red("FAILURE ")}${a.stack.replace(/^ERROR: /i,"")}${F}`),O&&O.dispose(),e.total||(e.total=e.end(i)),Object.assign({error:a,stdout:u,stderr:x,stats:e},p));if(s.version)return u.write(`Version ${Zn}${F}`),C(null);let S=A.normalize(s.baseDir||"."),Z=an(s.config||"asconfig.json",S),Dn=A.basename(Z),en=A.dirname(Z),M=await Le(Dn,en,c),Me=M!=null&&Array.isArray(M.entries)&&M.entries.length;if(s.help||!t.length&&!Me){var Pe=s.help?u:x,$=s.help?B:I;return Pe.write([$.white("SYNTAX")," "+$.cyan("asc")+" [entryFile ...] [options]","",$.white("EXAMPLES")," "+$.cyan("asc")+" hello"+_," "+$.cyan("asc")+" hello"+_+" -o hello.wasm -t hello.wat"," "+$.cyan("asc")+" hello1"+_+" hello2"+_+" -o -O > hello.wasm"," "+$.cyan("asc")+" --config asconfig.json --target release","",$.white("OPTIONS")].concat(Be(nn,24,F)).join(F)+F),C(null)}if(!(X.promises&&X.promises.readFile)){if(c===ae)throw Error("'options.readFile' must be specified");if(m===se)throw Error("'options.writeFile' must be specified");if(y===le)throw Error("'options.listFiles' must be specified")}let In=new Set;In.add(Z);let Ve=s.target||"release";for(;M;){if(M.targets){let p=M.targets[Ve];p&&(s=Hn(nn,s,p,en))}let a=M.options;if(a&&(s=Hn(nn,s,a,en)),M.entries)for(let p of M.entries)t.push(an(p,en));if(M.extends){if(Z=an(M.extends,en,!0),Dn=A.basename(Z),en=A.dirname(Z),In.has(Z))break;In.add(Z),M=await Le(Dn,en,c)}else break}if(jn(nn,s),s.showConfig)return x.write(JSON.stringify({options:s,entries:t},null,2)),C(null);function te(a){return[...new Set(a)]}var D,bn;let z=v.newOptions();switch(s.runtime){case"stub":bn=0;break;case"minimal":bn=1;break;default:bn=2;break}if(v.setTarget(z,0),v.setRuntime(z,bn),v.setNoAssert(z,s.noAssert),v.setExportMemory(z,!s.noExportMemory),v.setImportMemory(z,s.importMemory),v.setInitialMemory(z,s.initialMemory>>>0),v.setMaximumMemory(z,s.maximumMemory>>>0),v.setSharedMemory(z,s.sharedMemory),v.setImportTable(z,s.importTable),v.setExportTable(z,s.exportTable),v.setExportStart(z,typeof s.exportStart=="string"?s.exportStart:null),v.setMemoryBase(z,s.memoryBase>>>0),v.setTableBase(z,s.tableBase>>>0),v.setSourceMap(z,s.sourceMap!=null),v.setNoUnsafe(z,s.noUnsafe),v.setPedantic(z,s.pedantic),v.setLowMemoryLimit(z,s.lowMemoryLimit>>>0),v.setExportRuntime(z,s.exportRuntime),v.setBundleVersion(z,r,o,l),!s.stackSize&&s.runtime=="incremental"&&(s.stackSize=v.DEFAULT_STACK_SIZE),v.setStackSize(z,s.stackSize),s.use){let a=s.use;for(let p=0,d=a.length;p(typeof a=="function"&&(Object.assign(a.prototype,{program:D,baseDir:S,stdout:u,stderr:x,log:console.error,readFile:c,writeFile:m,listFiles:y}),a=new a),a))}catch(a){return C(a)}async function On(a,...p){for(let d=0,h=sn.length;d{if(a.includes("/"))return;let p=e.begin();e.parseCount++,v.parse(D,W[a],H+a+_,!1),e.parseTime+=e.end(p)});let ln=[];if(s.lib){let a=s.lib;typeof a=="string"&&(a=a.split(",")),ln.push(...a.map(p=>p.trim())),ln=te(ln);for(let p=0,d=ln.length;p=k;--w)N[w-1]!=="node_modules"&&V.push(`${N.slice(0,w).join(qn)}${qn}node_modules`);V.push(...s.path);for(let w of V.map(k=>A.relative(S,k))){let k=J;if((d=await c(A.join(w,L,k+_),S))!=null){h=`${H}${L}/${k}${_}`,Fn.set(h.replace(yn,""),A.join(w,L));break}let dn=`${J}/index`;if((d=await c(A.join(w,L,dn+_),S))!=null){h=`${H}${L}/${dn}${_}`,Fn.set(h.replace(yn,""),A.join(w,L));break}}}}}}return d==null?null:{sourceText:d,sourcePath:h}}function He(a=[]){do{let p=v.nextFile(D);if(p==null)break;a.push(p)}while(!0);return a}async function re(){for(var a;(a=He()).length;){let d=[];for(let h of a){let E=v.getDependee(D,h);d.push(Ge(h,E))}d=await Promise.all(d);for(let h=0,E=a.length;h{En.includes(a=a.trim())||En.push(a)}));{let a=e.begin();try{e.optimizeCount++,v.optimize(R,tn,rn,ie,oe)}catch(p){U("optimize",p)}try{O.runPasses(En)}catch(p){U("runPasses",p)}if(je){let p;try{let d=e.begin();e.emitCount++,p=O.emitBinary(),e.emitTime+=e.end(d)}catch(d){U("emitBinary (converge)",d)}do{try{e.optimizeCount++,v.optimize(R,tn,rn,ie,oe)}catch(h){U("optimize (converge)",h)}try{O.runPasses(En)}catch(h){U("runPasses (converge)",h)}let d;try{let h=e.begin();e.emitCount++,d=O.emitBinary(),e.emitTime+=e.end(h)}catch(h){U("emitBinary (converge)",h)}if(d.length>=p.length){d.length>p.length&&x.write(`Last converge was suboptimial.${F}`);break}p=d}while(!0)}e.optimizeTime+=e.end(a)}let fn=[];if(!s.noEmit){let a=s.bindings||[],p=!1,d=s.outFile!=null,h=s.textFile!=null,E=d||h,b=d&&s.outFile.length>0||h&&s.textFile.length>0,T=b?(s.outFile||s.textFile).replace(/\.\w+$/,""):null,L=b?A.basename(T):"output";if(v.setBasenameHint(z,L),s.outFile!=null){let V=s.sourceMap!=null?s.sourceMap.length?s.sourceMap:`./${L}.wasm.map`:null,N=e.begin();e.emitCount++;let w;try{w=O.emitBinary(V)}catch(k){U("emitBinary",k)}if(e.emitTime+=e.end(N),s.outFile.length?fn.push(m(s.outFile,w.binary,S)):(p=!0,An(w.binary)),w.sourceMap!="")if(s.outFile.length){let k=JSON.parse(w.sourceMap);k.sourceRoot=`./${L}`;let dn=[];for(let Tn=0,Xe=k.sources.length;TnPt.test(d))}catch{return null}}function An(a){An.used||(An.used=!0,e.writeCount++),u.write(a)}function U(a,p){let d=B.red("\u258C ");console.error([F,d,"Whoops, the AssemblyScript compiler has crashed during ",a," :-(",F,d,F,(typeof p.stack=="string"?[d,"Here is the stack trace hinting at the problem, perhaps it's useful?",F,d,F,p.stack.replace(/^/mg,d),F]:[d,"There is no stack trace. Perhaps a Binaryen exception above / in console?",F,d,F,d,"> "+p.stack,F]).join(""),d,F,d,"If you see where the error is, feel free to send us a pull request. If not,",F,d,"please let us know: https://github.com/AssemblyScript/assemblyscript/issues",F,d,F,d,"Thank you!",F].join("")),G.exit(1)}}function Yn(t){return Object.prototype.toString.call(t)==="[object Object]"}async function Le(t,n,e){let i=await e(t,n),o=A.join(n,t);if(!i)return null;let r;try{r=JSON.parse(i)}catch{throw new Error(`Asconfig is not valid json: ${o}`)}if(r.options&&!Yn(r.options))throw new Error(`Asconfig.options is not an object: ${o}`);if(r.include&&!Array.isArray(r.include))throw new Error(`Asconfig.include is not an array: ${o}`);if(r.targets){if(!Yn(r.targets))throw new Error(`Asconfig.targets is not an object: ${o}`);let l=Object.keys(r.targets);for(let f=0;f"u"&&n&&(i=n.isTTY);var o=0;do{let r=v.nextDiagnostic(t);if(!r)break;if(n&&n.write(v.formatDiagnostic(r,i,!0)+F+F),e){let l=function(u){return u&&{start:v.getRangeStart(u),end:v.getRangeEnd(u),source:f(v.getRangeSource(u))}||null},f=function(u){return u&&{normalizedPath:v.getSourceNormalizedPath(u)}||null};e({message:v.getDiagnosticMessage(r),code:v.getDiagnosticCode(r),category:v.getDiagnosticCategory(r),range:l(v.getDiagnosticRange(r)),relatedRange:l(v.getDiagnosticRelatedRange(r))})}v.isError(r)&&++o}while(!0);return o}var ne=class{readCount=0;writeCount=0;parseTime=0;parseCount=0;initializeTime=0;initializeCount=0;compileTime=0;compileCount=0;emitTime=0;emitCount=0;validateTime=0;validateCount=0;optimizeTime=0;optimizeCount=0;transformTime=0;transformCount=0;begin(){return G.hrtime()}end(n){let e=G.hrtime(n);return e[0]*1e9+e[1]}toString(){let n=g=>g?`${(g/1e6).toFixed(3)} ms`:"n/a",e=Object.keys(this).filter(g=>g.endsWith("Time")).map(g=>g.substring(0,g.length-4)),i=e.map(g=>n(this[`${g}Time`])),o=e.map(g=>this[`${g}Count`].toString()),r=e.reduce((g,s)=>Math.max(s.length,g),0),l=i.reduce((g,s)=>Math.max(s.length,g),0),f=o.reduce((g,s)=>Math.max(s.length,g),0),u=r+l+f+6,x=[];x.push(`\u256D\u2500${"\u2500".repeat(u)}\u2500\u256E${F}`);let c="Stats";x.push(`\u2502 ${c}${" ".repeat(u-c.length)} \u2502${F}`),x.push(`\u255E\u2550${"\u2550".repeat(r)}\u2550\u2564\u2550${"\u2550".repeat(l)}\u2550\u2564\u2550${"\u2550".repeat(f)}\u2550\u2561${F}`);for(let g=0,s=e.length;gnew global.Buffer(t)):t=>new Uint8Array(t);function $n(t){var n=[];return n.write=function(e){if(t&&t(e),typeof e=="string"){let i=Ne(wn.length(e));wn.write(e,i,0),e=i}this.push(e)},n.reset=function(){n.length=0},n.toBuffer=function(){for(var e=0,i=0,o=this.length;i>>= 0; + if (cache = (0 <= value && value < 256)) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if (cache = (-128 <= value && value < 128)) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } +} + +/** + * Returns a Long representing the given 32 bit integer value. + * @function + * @param {number} value The 32 bit integer in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromInt = fromInt; + +/** + * @param {number} value + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) + return UZERO; + if (value >= TWO_PWR_64_DBL) + return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) + return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return MAX_VALUE; + } + if (value < 0) + return fromNumber(-value, unsigned).neg(); + return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); +} + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @function + * @param {number} value The number in question + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromNumber = fromNumber; + +/** + * @param {number} lowBits + * @param {number} highBits + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); +} + +/** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is + * assumed to use 32 bits. + * @function + * @param {number} lowBits The low 32 bits + * @param {number} highBits The high 32 bits + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} The corresponding Long value + */ +Long.fromBits = fromBits; + +/** + * @function + * @param {number} base + * @param {number} exponent + * @returns {number} + * @inner + */ +var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) + +/** + * @param {string} str + * @param {(boolean|number)=} unsigned + * @param {number=} radix + * @returns {!Long} + * @inner + */ +function fromString(str, unsigned, radix) { + if (str.length === 0) + throw Error('empty string'); + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + radix = unsigned; + unsigned = false; + } else { + unsigned = !!unsigned; + } + if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") + return unsigned ? UZERO : ZERO; + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + + var p; + if ((p = str.indexOf('-')) > 0) + throw Error('interior hyphen'); + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 8)); + + var result = ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), + value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; +} + +/** + * Returns a Long representation of the given string, written using the specified radix. + * @function + * @param {string} str The textual representation of the Long + * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed + * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 + * @returns {!Long} The corresponding Long value + */ +Long.fromString = fromString; + +/** + * @function + * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val + * @param {boolean=} unsigned + * @returns {!Long} + * @inner + */ +function fromValue(val, unsigned) { + if (typeof val === 'number') + return fromNumber(val, unsigned); + if (typeof val === 'string') + return fromString(val, unsigned); + // Throws for non-objects, converts non-instanceof Long: + return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); +} + +/** + * Converts the specified value to a Long using the appropriate from* function for its type. + * @function + * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {!Long} + */ +Long.fromValue = fromValue; + +// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be +// no runtime penalty for these. + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_16_DBL = 1 << 16; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_24_DBL = 1 << 24; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + +/** + * @type {number} + * @const + * @inner + */ +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + +/** + * @type {!Long} + * @const + * @inner + */ +var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + +/** + * @type {!Long} + * @inner + */ +var ZERO = fromInt(0); + +/** + * Signed zero. + * @type {!Long} + */ +Long.ZERO = ZERO; + +/** + * @type {!Long} + * @inner + */ +var UZERO = fromInt(0, true); + +/** + * Unsigned zero. + * @type {!Long} + */ +Long.UZERO = UZERO; + +/** + * @type {!Long} + * @inner + */ +var ONE = fromInt(1); + +/** + * Signed one. + * @type {!Long} + */ +Long.ONE = ONE; + +/** + * @type {!Long} + * @inner + */ +var UONE = fromInt(1, true); + +/** + * Unsigned one. + * @type {!Long} + */ +Long.UONE = UONE; + +/** + * @type {!Long} + * @inner + */ +var NEG_ONE = fromInt(-1); + +/** + * Signed negative one. + * @type {!Long} + */ +Long.NEG_ONE = NEG_ONE; + +/** + * @type {!Long} + * @inner + */ +var MAX_VALUE = fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0, false); + +/** + * Maximum signed value. + * @type {!Long} + */ +Long.MAX_VALUE = MAX_VALUE; + +/** + * @type {!Long} + * @inner + */ +var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF | 0, 0xFFFFFFFF | 0, true); + +/** + * Maximum unsigned value. + * @type {!Long} + */ +Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + +/** + * @type {!Long} + * @inner + */ +var MIN_VALUE = fromBits(0, 0x80000000 | 0, false); + +/** + * Minimum signed value. + * @type {!Long} + */ +Long.MIN_VALUE = MIN_VALUE; + +/** + * @alias Long.prototype + * @inner + */ +var LongPrototype = Long.prototype; + +/** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. + * @this {!Long} + * @returns {number} + */ +LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; +}; + +/** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). + * @this {!Long} + * @returns {number} + */ +LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); +}; + +/** + * Converts the Long to a string written in the specified radix. + * @this {!Long} + * @param {number=} radix Radix (2-36), defaults to 10 + * @returns {string} + * @override + * @throws {RangeError} If `radix` is out of range + */ +LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { // Unsigned Longs are never negative + if (this.eq(MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = fromNumber(radix), + div = this.div(radixLong), + rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else + return '-' + this.neg().toString(radix); + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), + rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower), + intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, + digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) + return digits + result; + else { + while (digits.length < 6) + digits = '0' + digits; + result = '' + digits + result; + } + } +}; + +/** + * Gets the high 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed high bits + */ +LongPrototype.getHighBits = function getHighBits() { + return this.high; +}; + +/** + * Gets the high 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned high bits + */ +LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; +}; + +/** + * Gets the low 32 bits as a signed integer. + * @this {!Long} + * @returns {number} Signed low bits + */ +LongPrototype.getLowBits = function getLowBits() { + return this.low; +}; + +/** + * Gets the low 32 bits as an unsigned integer. + * @this {!Long} + * @returns {number} Unsigned low bits + */ +LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; +}; + +/** + * Gets the number of bits needed to represent the absolute value of this Long. + * @this {!Long} + * @returns {number} + */ +LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) // Unsigned Longs are never negative + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) != 0) + break; + return this.high != 0 ? bit + 33 : bit + 1; +}; + +/** + * Tests if this Long's value equals zero. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; +}; + +/** + * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. + * @returns {boolean} + */ +LongPrototype.eqz = LongPrototype.isZero; + +/** + * Tests if this Long's value is negative. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; +}; + +/** + * Tests if this Long's value is positive or zero. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; +}; + +/** + * Tests if this Long's value is odd. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; +}; + +/** + * Tests if this Long's value is even. + * @this {!Long} + * @returns {boolean} + */ +LongPrototype.isEven = function isEven() { + return (this.low & 1) === 0; +}; + +/** + * Tests if this Long's value equals the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.equals = function equals(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1) + return false; + return this.high === other.high && this.low === other.low; +}; + +/** + * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.eq = LongPrototype.equals; + +/** + * Tests if this Long's value differs from the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.notEquals = function notEquals(other) { + return !this.eq(/* validates */ other); +}; + +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.neq = LongPrototype.notEquals; + +/** + * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.ne = LongPrototype.notEquals; + +/** + * Tests if this Long's value is less than the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lessThan = function lessThan(other) { + return this.comp(/* validates */ other) < 0; +}; + +/** + * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lt = LongPrototype.lessThan; + +/** + * Tests if this Long's value is less than or equal the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp(/* validates */ other) <= 0; +}; + +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.lte = LongPrototype.lessThanOrEqual; + +/** + * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.le = LongPrototype.lessThanOrEqual; + +/** + * Tests if this Long's value is greater than the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.greaterThan = function greaterThan(other) { + return this.comp(/* validates */ other) > 0; +}; + +/** + * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.gt = LongPrototype.greaterThan; + +/** + * Tests if this Long's value is greater than or equal the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp(/* validates */ other) >= 0; +}; + +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.gte = LongPrototype.greaterThanOrEqual; + +/** + * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. + * @function + * @param {!Long|number|string} other Other value + * @returns {boolean} + */ +LongPrototype.ge = LongPrototype.greaterThanOrEqual; + +/** + * Compares this Long's value with the specified's. + * @this {!Long} + * @param {!Long|number|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ +LongPrototype.compare = function compare(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), + otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + // At this point the sign bits are the same + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + // Both are positive if at least one is unsigned + return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1; +}; + +/** + * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. + * @function + * @param {!Long|number|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + */ +LongPrototype.comp = LongPrototype.compare; + +/** + * Negates this Long's value. + * @this {!Long} + * @returns {!Long} Negated Long + */ +LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) + return MIN_VALUE; + return this.not().add(ONE); +}; + +/** + * Negates this Long's value. This is an alias of {@link Long#negate}. + * @function + * @returns {!Long} Negated Long + */ +LongPrototype.neg = LongPrototype.negate; + +/** + * Returns the sum of this and the specified Long. + * @this {!Long} + * @param {!Long|number|string} addend Addend + * @returns {!Long} Sum + */ +LongPrototype.add = function add(addend) { + if (!isLong(addend)) + addend = fromValue(addend); + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xFFFF; + var a16 = this.low >>> 16; + var a00 = this.low & 0xFFFF; + + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xFFFF; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); +}; + +/** + * Returns the difference of this and the specified Long. + * @this {!Long} + * @param {!Long|number|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ +LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) + subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); +}; + +/** + * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. + * @function + * @param {!Long|number|string} subtrahend Subtrahend + * @returns {!Long} Difference + */ +LongPrototype.sub = LongPrototype.subtract; + +/** + * Returns the product of this and the specified Long. + * @this {!Long} + * @param {!Long|number|string} multiplier Multiplier + * @returns {!Long} Product + */ +LongPrototype.multiply = function multiply(multiplier) { + if (this.isZero()) + return this; + if (!isLong(multiplier)) + multiplier = fromValue(multiplier); + + // use wasm support if present + if (wasm) { + var low = wasm["mul"](this.low, + this.high, + multiplier.low, + multiplier.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + if (multiplier.isZero()) + return this.unsigned ? UZERO : ZERO; + if (this.eq(MIN_VALUE)) + return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) + return this.isOdd() ? MIN_VALUE : ZERO; + + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + + // If both longs are small, use float multiplication + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high >>> 16; + var a32 = this.high & 0xFFFF; + var a16 = this.low >>> 16; + var a00 = this.low & 0xFFFF; + + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xFFFF; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); +}; + +/** + * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. + * @function + * @param {!Long|number|string} multiplier Multiplier + * @returns {!Long} Product + */ +LongPrototype.mul = LongPrototype.multiply; + +/** + * Returns this Long divided by the specified. The result is signed if this Long is signed or + * unsigned if this Long is unsigned. + * @this {!Long} + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Quotient + */ +LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (divisor.isZero()) + throw Error('division by zero'); + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && divisor.high === -1) { + // be consistent with non-wasm code path + return this; + } + var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + if (this.isZero()) + return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(MIN_VALUE)) + return ONE; + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) + return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return UZERO; + if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true + return UONE; + res = UZERO; + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this; + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2), + delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48), + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + approxRes = fromNumber(approx), + approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) + approxRes = ONE; + + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; +}; + +/** + * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Quotient + */ +LongPrototype.div = LongPrototype.divide; + +/** + * Returns this Long modulo the specified. + * @this {!Long} + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + + // use wasm support if present + if (wasm) { + var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + + return this.sub(this.div(divisor).mul(divisor)); +}; + +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.mod = LongPrototype.modulo; + +/** + * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. + * @function + * @param {!Long|number|string} divisor Divisor + * @returns {!Long} Remainder + */ +LongPrototype.rem = LongPrototype.modulo; + +/** + * Returns the bitwise NOT of this Long. + * @this {!Long} + * @returns {!Long} + */ +LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); +}; + +/** + * Returns count leading zeros of this Long. + * @this {!Long} + * @returns {!number} + */ +LongPrototype.countLeadingZeros = function countLeadingZeros() { + return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; +}; + +/** + * Returns count leading zeros. This is an alias of {@link Long#countLeadingZeros}. + * @function + * @param {!Long} + * @returns {!number} + */ +LongPrototype.clz = LongPrototype.countLeadingZeros; + +/** + * Returns count trailing zeros of this Long. + * @this {!Long} + * @returns {!number} + */ +LongPrototype.countTrailingZeros = function countTrailingZeros() { + return this.low ? ctz32(this.low) : ctz32(this.high) + 32; +}; + +/** + * Returns count trailing zeros. This is an alias of {@link Long#countTrailingZeros}. + * @function + * @param {!Long} + * @returns {!number} + */ +LongPrototype.ctz = LongPrototype.countTrailingZeros; + +/** + * Returns the bitwise AND of this Long and the specified. + * @this {!Long} + * @param {!Long|number|string} other Other Long + * @returns {!Long} + */ +LongPrototype.and = function and(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low & other.low, this.high & other.high, this.unsigned); +}; + +/** + * Returns the bitwise OR of this Long and the specified. + * @this {!Long} + * @param {!Long|number|string} other Other Long + * @returns {!Long} + */ +LongPrototype.or = function or(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low | other.low, this.high | other.high, this.unsigned); +}; + +/** + * Returns the bitwise XOR of this Long and the given one. + * @this {!Long} + * @param {!Long|number|string} other Other Long + * @returns {!Long} + */ +LongPrototype.xor = function xor(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); + else + return fromBits(0, this.low << (numBits - 32), this.unsigned); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shl = LongPrototype.shiftLeft; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); + else + return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); +}; + +/** + * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shr = LongPrototype.shiftRight; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits < 32) return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >>> numBits, this.unsigned); + if (numBits === 32) return fromBits(this.high, 0, this.unsigned); + return fromBits(this.high >>> (numBits - 32), 0, this.unsigned); +}; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shru = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Shifted Long + */ +LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + +/** + * Returns this Long with bits rotated to the left by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = (32 - numBits); + return fromBits(((this.low << numBits) | (this.high >>> b)), ((this.high << numBits) | (this.low >>> b)), this.unsigned); + } + numBits -= 32; + b = (32 - numBits); + return fromBits(((this.high << numBits) | (this.low >>> b)), ((this.low << numBits) | (this.high >>> b)), this.unsigned); +} +/** + * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotl = LongPrototype.rotateLeft; + +/** + * Returns this Long with bits rotated to the right by the given amount. + * @this {!Long} + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) numBits = numBits.toInt(); + if ((numBits &= 63) === 0) return this; + if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = (32 - numBits); + return fromBits(((this.high << b) | (this.low >>> numBits)), ((this.low << b) | (this.high >>> numBits)), this.unsigned); + } + numBits -= 32; + b = (32 - numBits); + return fromBits(((this.low << b) | (this.high >>> numBits)), ((this.high << b) | (this.low >>> numBits)), this.unsigned); +} +/** + * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. + * @function + * @param {number|!Long} numBits Number of bits + * @returns {!Long} Rotated Long + */ +LongPrototype.rotr = LongPrototype.rotateRight; + +/** + * Converts this Long to signed. + * @this {!Long} + * @returns {!Long} Signed long + */ +LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) + return this; + return fromBits(this.low, this.high, false); +}; + +/** + * Converts this Long to unsigned. + * @this {!Long} + * @returns {!Long} Unsigned long + */ +LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) + return this; + return fromBits(this.low, this.high, true); +}; + +/** + * Converts this Long to its byte representation. + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @this {!Long} + * @returns {!Array.} Byte representation + */ +LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); +}; + +/** + * Converts this Long to its little endian byte representation. + * @this {!Long} + * @returns {!Array.} Little endian byte representation + */ +LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, + lo = this.low; + return [ + lo & 0xff, + lo >>> 8 & 0xff, + lo >>> 16 & 0xff, + lo >>> 24, + hi & 0xff, + hi >>> 8 & 0xff, + hi >>> 16 & 0xff, + hi >>> 24 + ]; +}; + +/** + * Converts this Long to its big endian byte representation. + * @this {!Long} + * @returns {!Array.} Big endian byte representation + */ +LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, + lo = this.low; + return [ + hi >>> 24, + hi >>> 16 & 0xff, + hi >>> 8 & 0xff, + hi & 0xff, + lo >>> 24, + lo >>> 16 & 0xff, + lo >>> 8 & 0xff, + lo & 0xff + ]; +}; + +/** + * Creates a Long from its byte representation. + * @param {!Array.} bytes Byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @param {boolean=} le Whether little or big endian, defaults to big endian + * @returns {Long} The corresponding Long value + */ +Long.fromBytes = function fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); +}; + +/** + * Creates a Long from its little endian byte representation. + * @param {!Array.} bytes Little endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ +Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long( + bytes[0] | + bytes[1] << 8 | + bytes[2] << 16 | + bytes[3] << 24, + bytes[4] | + bytes[5] << 8 | + bytes[6] << 16 | + bytes[7] << 24, + unsigned + ); +}; + +/** + * Creates a Long from its big endian byte representation. + * @param {!Array.} bytes Big endian byte representation + * @param {boolean=} unsigned Whether unsigned or not, defaults to signed + * @returns {Long} The corresponding Long value + */ +Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long( + bytes[4] << 24 | + bytes[5] << 16 | + bytes[6] << 8 | + bytes[7], + bytes[0] << 24 | + bytes[1] << 16 | + bytes[2] << 8 | + bytes[3], + unsigned + ); +}; + +export default Long; Index: binaries/data/mods/asc/mod.json =================================================================== --- /dev/null +++ binaries/data/mods/asc/mod.json @@ -0,0 +1,8 @@ +{ + "name": "asc", + "version": "0.0.26", + "label": "0 A.D. Empires Ascendant", + "url": "https://play0ad.com", + "description": "A free, open-source, historical RTS game.", + "dependencies": [] +} Index: binaries/data/mods/public/globalscripts/LoadWasm.mjs =================================================================== --- /dev/null +++ binaries/data/mods/public/globalscripts/LoadWasm.mjs @@ -0,0 +1,29 @@ +import asc from "assemblyscript/asc"; + +export async function LoadWasm(path) +{ + let moduleData; + try { + let res = await asc.main([ + path, + "--outFile", "__.wasm", + "--optimize" + ], { + readFile: (x) => { + if (x === "asconfig.json") + return null; + return Engine.ReadFile(x) + }, + writeFile: (filename, data) => moduleData = data, + listFiles: (x) => { warn("now" + x); error(x); return [] }, + }); + } catch (exc) + { + error(uneval(exc)); + } + try { + return (await WebAssembly.instantiate(moduleData)).instance.exports; + } catch (err) { + warn(uneval(err)); + } +} Index: binaries/data/mods/public/gui/pregame/MainMenuPage.js =================================================================== --- binaries/data/mods/public/gui/pregame/MainMenuPage.js +++ binaries/data/mods/public/gui/pregame/MainMenuPage.js @@ -12,6 +12,14 @@ new MusicHandler(); new ProjectInformationHandler(projectInformation); new CommunityButtonHandler(communityButtons); + + // Need to shim console for this to work + globalThis.console = { + log: error, + warn: error + }; + + Engine.LoadESModule("wasm/asmExample.mjs"); } getHotloadData() @@ -58,3 +66,27 @@ error("GUI page has space for " + buttons.length + " community buttons, but " + menuItems.length + " items are provided!"); } } + +async function toto() +{ + let to; + try { + const data = Uint8Array.from([ +0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x60, 0x02, 0x7F, 0x7F, 0x01, 0x7F, 0x03, 0x02, 0x01, 0x00, 0x05, 0x03, 0x01, 0x00, 0x00, 0x07, 0x10, 0x02, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x06, 0x6D, 0x65, 0x6D, 0x6F, 0x72, 0x79, 0x02, 0x00, 0x0A, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6A, 0x0B, 0x00, 0x24, 0x10, 0x73, 0x6F, 0x75, 0x72, 0x63, 0x65, 0x4D, 0x61, 0x70, 0x70, 0x69, 0x6E, 0x67, 0x55, 0x52, 0x4C, 0x12, 0x2E, 0x2F, 0x72, 0x65, 0x6C, 0x65, 0x61, 0x73, 0x65, 0x2E, 0x77, 0x61, 0x73, 0x6D, 0x2E, 0x6D, 0x61, 0x70]) + warn(uneval(data)); + to = await WebAssembly.instantiate(data); + } catch (ex) { + warn(uneval(ex)); + warn(ex.toString()); + } + warn("Done"); + try { + warn(uneval(to)); + warn(uneval(to.instance.exports.add(5, 9))); + } catch (ex) + { + warn(uneval(ex)); + warn(ex.toString()); + + } +} Index: binaries/data/mods/public/wasm/add.ts =================================================================== --- /dev/null +++ binaries/data/mods/public/wasm/add.ts @@ -0,0 +1,3 @@ +export function add(a: i32, b: i32): i32 { + return a + b; +} Index: binaries/data/mods/public/wasm/asmExample.mjs =================================================================== --- /dev/null +++ binaries/data/mods/public/wasm/asmExample.mjs @@ -0,0 +1,4 @@ +import { LoadWasm } from 'globalscripts/LoadWasm.mjs' + +let addModule = await LoadWasm("wasm/add.ts"); +warn("WASM Module says 4 + 5 is " + addModule.add(4, 5)); Index: source/gui/CGUI.cpp =================================================================== --- source/gui/CGUI.cpp +++ source/gui/CGUI.cpp @@ -298,6 +298,7 @@ void CGUI::TickObjects() { + m_ScriptInterface->RunJobs(); m_BaseObject->RecurseObject(&IGUIObject::IsHiddenOrGhost, &IGUIObject::Tick); SendEventToAll(EventNameTick); m_Tooltip.Update(FindObjectUnderMouse(), m_MousePos, *this); Index: source/gui/Scripting/JSInterface_GUIManager.cpp =================================================================== --- source/gui/Scripting/JSInterface_GUIManager.cpp +++ source/gui/Scripting/JSInterface_GUIManager.cpp @@ -1,4 +1,4 @@ -/* Copyright (C) 2021 Wildfire Games. +/* Copyright (C) 2022 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify @@ -73,6 +73,10 @@ return g_GUI->GetTemplate(templateName); } +void LoadESModule(const ScriptInterface& scriptInterface, VfsPath path) +{ + scriptInterface.LoadESModule(path); +} void RegisterScriptFunctions(const ScriptRequest& rq) { @@ -84,6 +88,8 @@ ScriptFunction::Register<&TemplateExists>(rq, "TemplateExists"); ScriptFunction::Register<&GetTemplate>(rq, "GetTemplate"); + ScriptFunction::Register<&LoadESModule>(rq, "LoadESModule"); + ScriptFunction::Register<&CGUI::FindObjectByName, &ScriptInterface::ObjectFromCBData>(rq, "GetGUIObjectByName"); ScriptFunction::Register<&CGUI::SetGlobalHotkey, &ScriptInterface::ObjectFromCBData>(rq, "SetGlobalHotkey"); ScriptFunction::Register<&CGUI::UnsetGlobalHotkey, &ScriptInterface::ObjectFromCBData>(rq, "UnsetGlobalHotkey"); Index: source/scriptinterface/Promises.h =================================================================== --- source/scriptinterface/Promises.h +++ source/scriptinterface/Promises.h @@ -66,6 +66,8 @@ private: }; +bool dispatchToEventLoop(void* closure, JS::Dispatchable* dispatchable); + /** * Run a job in the thread pool. This returns a promise right away, and once the future completes will resolve the promise. */ Index: source/scriptinterface/ScriptContext.h =================================================================== --- source/scriptinterface/ScriptContext.h +++ source/scriptinterface/ScriptContext.h @@ -78,6 +78,8 @@ void RegisterRealm(JS::Realm* realm); void UnRegisterRealm(JS::Realm* realm); + void AddDispatchable(void* ptr); + /** * GetGeneralJSContext returns the context without starting a GC request and without * entering any compartment. It should only be used in specific situations, such as @@ -95,6 +97,8 @@ void PrepareZonesForIncrementalGC() const; std::list m_Realms; + std::vector m_Dispatchables; + int m_ContextSize; int m_HeapGrowthBytesGCTrigger; int m_LastGCBytes; Index: source/scriptinterface/ScriptContext.cpp =================================================================== --- source/scriptinterface/ScriptContext.cpp +++ source/scriptinterface/ScriptContext.cpp @@ -127,10 +127,45 @@ m_jobqueue = std::make_unique(); JS::SetJobQueue(m_cx, m_jobqueue.get()); + + JS::InitDispatchToEventLoop(m_cx, Script::dispatchToEventLoop, this); +} + +#include + +std::mutex t; +namespace Script +{ +bool dispatchToEventLoop(void* closure, JS::Dispatchable* dispatchable) +{ + ((ScriptContext*)closure)->AddDispatchable((void*) dispatchable); + return true; +}; +} + +void ScriptContext::AddDispatchable(void* dip) +{ + std::lock_guard lock(t); + m_Dispatchables.push_back(dip); } ScriptContext::~ScriptContext() { + if (!m_Dispatchables.empty()) + { + std::vector tt; + { + std::lock_guard lock(t); + tt = m_Dispatchables; + } + for (void* t : tt) + ((JS::Dispatchable*)t)->run(m_cx, JS::Dispatchable::MaybeShuttingDown::NotShuttingDown); + { + std::lock_guard lock(t); + m_Dispatchables.clear(); + } + } + ENSURE(ScriptEngine::IsInitialised() && "The ScriptEngine must be active (initialized and not yet shut down) when destroying a ScriptContext!"); JS_DestroyContext(m_cx); @@ -157,6 +192,22 @@ { PROFILE2("MaybeIncrementalGC"); + if (!m_Dispatchables.empty()) + { + std::vector tt; + { + std::lock_guard lock(t); + tt = m_Dispatchables; + } + for (void* t : tt) + ((JS::Dispatchable*)t)->run(m_cx, JS::Dispatchable::MaybeShuttingDown::NotShuttingDown); + { + std::lock_guard lock(t); + m_Dispatchables.erase(m_Dispatchables.begin(), m_Dispatchables.begin() + tt.size()); + } + } + + if (JS::IsIncrementalGCEnabled(m_cx)) { // The idea is to get the heap size after a completed GC and trigger the next GC when the heap size has Index: source/scriptinterface/ScriptInterface.cpp =================================================================== --- source/scriptinterface/ScriptInterface.cpp +++ source/scriptinterface/ScriptInterface.cpp @@ -366,6 +366,22 @@ m_context->UnRegisterRealm(JS::GetObjectRealmOrNull(m_glob)); } +#include "jsfriendapi.h" + +/** + * This is required to get readable errors when parsing a module with top-level await. + */ +struct SEnvParser : public js::ScriptEnvironmentPreparer { + virtual ~SEnvParser() {}; + virtual void invoke(JS::HandleObject UNUSED(global), Closure& closure) + { + ScriptRequest rq(*si); + closure(rq.cx); + } + + ScriptInterface* si; +}; + ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugName, const std::shared_ptr& context) : m(std::make_unique(nativeScopeName, context, nullptr)) { @@ -379,6 +395,10 @@ ScriptRequest rq(this); m_CmptPrivate.pScriptInterface = this; JS::SetRealmPrivate(JS::GetObjectRealmOrNull(rq.glob), (void*)&m_CmptPrivate); + + SEnvParser* p = new SEnvParser(); + p->si = this; + js::SetScriptEnvironmentPreparer(rq.cx, p); } ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugName, const ScriptInterface& neighbor) Index: source/scriptinterface/ScriptModuleLoader.h =================================================================== --- source/scriptinterface/ScriptModuleLoader.h +++ source/scriptinterface/ScriptModuleLoader.h @@ -38,7 +38,7 @@ private: - static JSObject* ModuleResolutionHook(JSContext* cx, JS::HandleValue referencingModule, JS::HandleString path); + static JSObject* ModuleResolutionHook(JSContext* cx, JS::HandleValue referencingModule, JS::HandleObject path); static Status FileChangedHook(void* param, const VfsPath& path); Index: source/scriptinterface/ScriptModuleLoader.cpp =================================================================== --- source/scriptinterface/ScriptModuleLoader.cpp +++ source/scriptinterface/ScriptModuleLoader.cpp @@ -86,19 +86,22 @@ return VfsPath(ret); } -JSObject* ScriptModuleLoader::ModuleResolutionHook(JSContext* cx, JS::HandleValue referencingModule, JS::HandleString path) +JSObject* ScriptModuleLoader::ModuleResolutionHook(JSContext* cx, JS::HandleValue referencingModule, JS::HandleObject path) { ScriptRequest rq(cx); const ScriptModuleLoader& instance = rq.GetScriptInterface().GetScriptModuleLoader(); std::wstring pathString; - JS::RootedValue pathValue(cx, JS::StringValue(path)); + JS::RootedValue pathValue(cx, JS::StringValue(JS::GetModuleRequestSpecifier(rq.cx, path))); Script::FromJSVal(rq, pathValue, pathString); VfsPath filename = VfsPath(pathString); VfsPath refFilename = instance.GetScriptPath(cx, referencingModule); - VfsPath actualPath = (refFilename / filename).Normalize(); + VfsPath actualPath = (filename).Normalize(); + + if (actualPath.Extension().empty()) + actualPath = actualPath.ChangeExtension(".js"); std::map::iterator it = instance.m_ResolvedModules.find(actualPath); if (it != instance.m_ResolvedModules.end()) @@ -143,6 +146,11 @@ return INFO::OK; } +bool MetadataHook(JSContext*, JS::HandleValue, JS::HandleObject UNUSED(metaObject)) +{ + return true; +} + bool ScriptModuleLoader::Load(JSContext* cx, const VfsPath& modulePath) { ScriptRequest rq(cx); @@ -152,14 +160,21 @@ return false; JS::SetModuleResolveHook(JS_GetRuntime(cx), ModuleResolutionHook); + JS::SetModuleMetadataHook(JS_GetRuntime(cx), MetadataHook); JS::RootedObject topModule(cx, CompileModule(cx, modulePath)); - - if (!topModule || !JS::ModuleInstantiate(cx, topModule) || !JS::ModuleEvaluate(cx, topModule)) + JS::RootedValue rval(cx); + if (!topModule || !JS::ModuleInstantiate(cx, topModule) || !JS::ModuleEvaluate(cx, topModule, &rval)) { ScriptException::CatchPending(rq); return false; } + JS::RootedObject obj(rq.cx, rval.toObjectOrNull()); + if (obj) + JS::ThrowOnModuleEvaluationFailure(cx, obj); + + ScriptException::CatchPending(rq); + return true; }