JavascriptArray.cpp 457 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLibraryPch.h"
  6. #include "Types/PathTypeHandler.h"
  7. #include "Types/SpreadArgument.h"
  8. namespace Js
  9. {
  10. // Make sure EmptySegment points to read-only memory.
  11. // Can't do this the easy way because SparseArraySegment has a constructor...
  12. static const char EmptySegmentData[sizeof(SparseArraySegmentBase)] = {0};
  13. const SparseArraySegmentBase *JavascriptArray::EmptySegment = (SparseArraySegmentBase *)&EmptySegmentData;
  14. #if defined(_M_X64_OR_ARM64)
  15. const Var JavascriptArray::MissingItem = (Var)0x8000000280000002;
  16. #else
  17. const Var JavascriptArray::MissingItem = (Var)0x80000002;
  18. #endif
  19. const int32 JavascriptNativeIntArray::MissingItem = 0x80000002;
  20. static const uint64 FloatMissingItemPattern = 0x8000000280000002ull;
  21. const double JavascriptNativeFloatArray::MissingItem = *(double*)&FloatMissingItemPattern;
  22. // Allocate enough space for 4 inline property slots and 16 inline element slots
  23. const size_t JavascriptArray::StackAllocationSize = DetermineAllocationSize<JavascriptArray, 4>(16);
  24. const size_t JavascriptNativeIntArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeIntArray, 4>(16);
  25. const size_t JavascriptNativeFloatArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeFloatArray, 4>(16);
  26. SegmentBTree::SegmentBTree()
  27. : segmentCount(0),
  28. segments(NULL),
  29. keys(NULL),
  30. children(NULL)
  31. {
  32. }
  33. uint32 SegmentBTree::GetLazyCrossOverLimit()
  34. {
  35. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  36. if (Js::Configuration::Global.flags.DisableArrayBTree)
  37. {
  38. return Js::JavascriptArray::InvalidIndex;
  39. }
  40. else if (Js::Configuration::Global.flags.ForceArrayBTree)
  41. {
  42. return ARRAY_CROSSOVER_FOR_VALIDATE;
  43. }
  44. #endif
  45. #ifdef VALIDATE_ARRAY
  46. if (Js::Configuration::Global.flags.ArrayValidate)
  47. {
  48. return ARRAY_CROSSOVER_FOR_VALIDATE;
  49. }
  50. #endif
  51. return SegmentBTree::MinDegree * 3;
  52. }
  53. BOOL SegmentBTree::IsLeaf() const
  54. {
  55. return children == NULL;
  56. }
  57. BOOL SegmentBTree::IsFullNode() const
  58. {
  59. return segmentCount == MaxKeys;
  60. }
  61. void SegmentBTree::InternalFind(SegmentBTree* node, uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  62. {
  63. uint32 i = 0;
  64. for(; i < node->segmentCount; i++)
  65. {
  66. Assert(node->keys[i] == node->segments[i]->left);
  67. if (itemIndex < node->keys[i])
  68. {
  69. break;
  70. }
  71. }
  72. // i indicates the 1st segment in the node past any matching segment.
  73. // the i'th child is the children to the 'left' of the i'th segment.
  74. // If itemIndex matches segment i-1 (note that left is always a match even when length == 0)
  75. bool matches = i > 0 && (itemIndex == node->keys[i-1] || itemIndex < node->keys[i-1] + node->segments[i-1]->length);
  76. if (matches)
  77. {
  78. // Find prev segment
  79. if (node->IsLeaf())
  80. {
  81. if (i > 1)
  82. {
  83. // Previous is either sibling or set in a parent
  84. prev = node->segments[i-2];
  85. }
  86. }
  87. else
  88. {
  89. // prev is the right most leaf in children[i-1] tree
  90. SegmentBTree* child = &node->children[i - 1];
  91. while (!child->IsLeaf())
  92. {
  93. child = &child->children[child->segmentCount];
  94. }
  95. prev = child->segments[child->segmentCount - 1];
  96. }
  97. // Return the matching segment
  98. matchOrNext = node->segments[i-1];
  99. }
  100. else // itemIndex in between segment i-1 and i
  101. {
  102. if (i > 0)
  103. {
  104. // Store in previous in case a match or next is the first segment in a child.
  105. prev = node->segments[i-1];
  106. }
  107. if (node->IsLeaf())
  108. {
  109. matchOrNext = (i == 0 ? node->segments[0] : prev->next);
  110. }
  111. else
  112. {
  113. InternalFind(node->children + i, itemIndex, prev, matchOrNext);
  114. }
  115. }
  116. }
  117. void SegmentBTreeRoot::Find(uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  118. {
  119. prev = matchOrNext = NULL;
  120. InternalFind(this, itemIndex, prev, matchOrNext);
  121. Assert(prev == NULL || (prev->next == matchOrNext));// If prev exists it is immediately before matchOrNext in the list of arraysegments
  122. Assert(prev == NULL || (prev->left < itemIndex && prev->left + prev->length <= itemIndex)); // prev should never be a match (left is a match if length == 0)
  123. Assert(matchOrNext == NULL || (matchOrNext->left >= itemIndex || matchOrNext->left + matchOrNext->length > itemIndex));
  124. }
  125. void SegmentBTreeRoot::Add(Recycler* recycler, SparseArraySegmentBase* newSeg)
  126. {
  127. if (IsFullNode())
  128. {
  129. SegmentBTree * children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  130. children[0] = *this;
  131. // Even though the segments point to a GC pointer, the main array should keep a references
  132. // as well. So just make it a leaf allocation
  133. this->segmentCount = 0;
  134. this->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  135. this->keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  136. this->children = children;
  137. // This split is the only way the tree gets deeper
  138. SplitChild(recycler, this, 0, &children[0]);
  139. }
  140. InsertNonFullNode(recycler, this, newSeg);
  141. }
  142. void SegmentBTree::SwapSegment(uint32 originalKey, SparseArraySegmentBase* oldSeg, SparseArraySegmentBase* newSeg)
  143. {
  144. // Find old segment
  145. uint32 itemIndex = originalKey;
  146. uint32 i = 0;
  147. for(; i < segmentCount; i++)
  148. {
  149. Assert(keys[i] == segments[i]->left || (oldSeg == newSeg && newSeg == segments[i]));
  150. if (itemIndex < keys[i])
  151. {
  152. break;
  153. }
  154. }
  155. // i is 1 past any match
  156. if (i > 0)
  157. {
  158. if (oldSeg == segments[i-1])
  159. {
  160. segments[i-1] = newSeg;
  161. keys[i-1] = newSeg->left;
  162. return;
  163. }
  164. }
  165. Assert(!IsLeaf());
  166. children[i].SwapSegment(originalKey, oldSeg, newSeg);
  167. }
  168. void SegmentBTree::SplitChild(Recycler* recycler, SegmentBTree* parent, uint32 iChild, SegmentBTree* child)
  169. {
  170. // Split child in two, move it's median key up to parent, and put the result of the split
  171. // on either side of the key moved up into parent
  172. Assert(child != NULL);
  173. Assert(parent != NULL);
  174. Assert(!parent->IsFullNode());
  175. Assert(child->IsFullNode());
  176. SegmentBTree newNode;
  177. newNode.segmentCount = MinKeys;
  178. // Even though the segments point to a GC pointer, the main array should keep a references
  179. // as well. So just make it a leaf allocation
  180. newNode.segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  181. newNode.keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  182. // Move the keys above the median into the new node
  183. for(uint32 i = 0; i < MinKeys; i++)
  184. {
  185. newNode.segments[i] = child->segments[i+MinDegree];
  186. newNode.keys[i] = child->keys[i+MinDegree];
  187. // Do not leave false positive references around in the b-tree
  188. child->segments[i+MinDegree] = NULL;
  189. }
  190. // If children exist move those as well.
  191. if (!child->IsLeaf())
  192. {
  193. newNode.children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  194. for(uint32 j = 0; j < MinDegree; j++)
  195. {
  196. newNode.children[j] = child->children[j+MinDegree];
  197. // Do not leave false positive references around in the b-tree
  198. child->children[j+MinDegree].segments = NULL;
  199. child->children[j+MinDegree].children = NULL;
  200. }
  201. }
  202. child->segmentCount = MinKeys;
  203. // Make room for the new child in parent
  204. for(uint32 j = parent->segmentCount; j > iChild; j--)
  205. {
  206. parent->children[j+1] = parent->children[j];
  207. }
  208. // Copy the contents of the new node into the correct place in the parent's child array
  209. parent->children[iChild+1] = newNode;
  210. // Move the keys to make room for the median key
  211. for(uint32 k = parent->segmentCount; k > iChild; k--)
  212. {
  213. parent->segments[k] = parent->segments[k-1];
  214. parent->keys[k] = parent->keys[k-1];
  215. }
  216. // Move the median key into the proper place in the parent node
  217. parent->segments[iChild] = child->segments[MinKeys];
  218. parent->keys[iChild] = child->keys[MinKeys];
  219. // Do not leave false positive references around in the b-tree
  220. child->segments[MinKeys] = NULL;
  221. parent->segmentCount++;
  222. }
  223. void SegmentBTree::InsertNonFullNode(Recycler* recycler, SegmentBTree* node, SparseArraySegmentBase* newSeg)
  224. {
  225. Assert(!node->IsFullNode());
  226. AnalysisAssert(node->segmentCount < MaxKeys); // Same as !node->IsFullNode()
  227. Assert(newSeg != NULL);
  228. if (node->IsLeaf())
  229. {
  230. // Move the keys
  231. uint32 i = node->segmentCount - 1;
  232. while( (i != -1) && (newSeg->left < node->keys[i]))
  233. {
  234. node->segments[i+1] = node->segments[i];
  235. node->keys[i+1] = node->keys[i];
  236. i--;
  237. }
  238. if (!node->segments)
  239. {
  240. // Even though the segments point to a GC pointer, the main array should keep a references
  241. // as well. So just make it a leaf allocation
  242. node->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  243. node->keys = AllocatorNewArrayLeafZ(Recycler, recycler, uint32, MaxKeys);
  244. }
  245. node->segments[i + 1] = newSeg;
  246. node->keys[i + 1] = newSeg->left;
  247. node->segmentCount++;
  248. }
  249. else
  250. {
  251. // find the correct child node
  252. uint32 i = node->segmentCount-1;
  253. while((i != -1) && (newSeg->left < node->keys[i]))
  254. {
  255. i--;
  256. }
  257. i++;
  258. // Make room if full
  259. if(node->children[i].IsFullNode())
  260. {
  261. // This split doesn't make the tree any deeper as node already has children.
  262. SplitChild(recycler, node, i, node->children+i);
  263. Assert(node->keys[i] == node->segments[i]->left);
  264. if (newSeg->left > node->keys[i])
  265. {
  266. i++;
  267. }
  268. }
  269. InsertNonFullNode(recycler, node->children+i, newSeg);
  270. }
  271. }
  272. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure(BOOL operationSucceeded)
  273. {
  274. if (IsThrowTypeError(operationSucceeded))
  275. {
  276. ThrowTypeErrorOnFailure();
  277. }
  278. }
  279. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure()
  280. {
  281. JavascriptError::ThrowTypeError(m_scriptContext, VBSERR_ActionNotSupported, m_functionName);
  282. }
  283. inline BOOL ThrowTypeErrorOnFailureHelper::IsThrowTypeError(BOOL operationSucceeded)
  284. {
  285. return !operationSucceeded;
  286. }
  287. // Make sure EmptySegment points to read-only memory.
  288. // Can't do this the easy way because SparseArraySegment has a constructor...
  289. JavascriptArray::JavascriptArray(DynamicType * type)
  290. : ArrayObject(type, false, 0)
  291. {
  292. Assert(type->GetTypeId() == TypeIds_Array || type->GetTypeId() == TypeIds_NativeIntArray || type->GetTypeId() == TypeIds_NativeFloatArray || ((type->GetTypeId() == TypeIds_ES5Array || type->GetTypeId() == TypeIds_Object) && type->GetPrototype() == GetScriptContext()->GetLibrary()->GetArrayPrototype()));
  293. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  294. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  295. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  296. }
  297. JavascriptArray::JavascriptArray(uint32 length, DynamicType * type)
  298. : ArrayObject(type, false, length)
  299. {
  300. Assert(JavascriptArray::Is(type->GetTypeId()));
  301. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  302. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  303. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  304. }
  305. JavascriptArray::JavascriptArray(uint32 length, uint32 size, DynamicType * type)
  306. : ArrayObject(type, false, length)
  307. {
  308. Assert(type->GetTypeId() == TypeIds_Array);
  309. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  310. Recycler* recycler = GetRecycler();
  311. SetHeadAndLastUsedSegment(SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, size, nullptr));
  312. }
  313. JavascriptArray::JavascriptArray(DynamicType * type, uint32 size)
  314. : ArrayObject(type, false)
  315. {
  316. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  317. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, false>(this));
  318. head->size = size;
  319. Var fill = Js::JavascriptArray::MissingItem;
  320. for (uint i = 0; i < size; i++)
  321. {
  322. ((SparseArraySegment<Var>*)head)->elements[i] = fill;
  323. }
  324. }
  325. JavascriptNativeIntArray::JavascriptNativeIntArray(uint32 length, uint32 size, DynamicType * type)
  326. : JavascriptNativeArray(type)
  327. {
  328. Assert(type->GetTypeId() == TypeIds_NativeIntArray);
  329. this->length = length;
  330. Recycler* recycler = GetRecycler();
  331. SetHeadAndLastUsedSegment(SparseArraySegment<int32>::AllocateSegment(recycler, 0, 0, size, nullptr));
  332. }
  333. JavascriptNativeIntArray::JavascriptNativeIntArray(DynamicType * type, uint32 size)
  334. : JavascriptNativeArray(type)
  335. {
  336. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, false>(this));
  337. head->size = size;
  338. ((SparseArraySegment<int32>*)head)->FillSegmentBuffer(0, size);
  339. }
  340. JavascriptNativeFloatArray::JavascriptNativeFloatArray(uint32 length, uint32 size, DynamicType * type)
  341. : JavascriptNativeArray(type)
  342. {
  343. Assert(type->GetTypeId() == TypeIds_NativeFloatArray);
  344. this->length = length;
  345. Recycler* recycler = GetRecycler();
  346. SetHeadAndLastUsedSegment(SparseArraySegment<double>::AllocateSegment(recycler, 0, 0, size, nullptr));
  347. }
  348. JavascriptNativeFloatArray::JavascriptNativeFloatArray(DynamicType * type, uint32 size)
  349. : JavascriptNativeArray(type)
  350. {
  351. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, false>(this));
  352. head->size = size;
  353. ((SparseArraySegment<double>*)head)->FillSegmentBuffer(0, size);
  354. }
  355. bool JavascriptArray::Is(Var aValue)
  356. {
  357. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  358. return JavascriptArray::Is(typeId);
  359. }
  360. bool JavascriptArray::Is(TypeId typeId)
  361. {
  362. return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
  363. }
  364. bool JavascriptArray::IsVarArray(Var aValue)
  365. {
  366. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  367. return JavascriptArray::IsVarArray(typeId);
  368. }
  369. bool JavascriptArray::IsVarArray(TypeId typeId)
  370. {
  371. return typeId == TypeIds_Array;
  372. }
  373. JavascriptArray* JavascriptArray::FromVar(Var aValue)
  374. {
  375. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
  376. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  377. }
  378. // Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
  379. JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
  380. {
  381. AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  382. return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
  383. }
  384. // Check if a Var is a direct-accessible (fast path) JavascriptArray.
  385. bool JavascriptArray::IsDirectAccessArray(Var aValue)
  386. {
  387. return RecyclableObject::Is(aValue) &&
  388. (VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
  389. VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
  390. VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
  391. }
  392. DynamicObjectFlags JavascriptArray::GetFlags() const
  393. {
  394. return GetArrayFlags();
  395. }
  396. DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
  397. {
  398. return GetArrayFlags_Unchecked();
  399. }
  400. void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
  401. {
  402. SetArrayFlags(flags);
  403. }
  404. DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
  405. {
  406. return scriptContext->GetLibrary()->GetArrayType();
  407. }
  408. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
  409. {
  410. bool isObjectWithArray;
  411. TypeId arrayTypeId;
  412. return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  413. }
  414. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
  415. const Var var,
  416. bool *const isObjectWithArrayRef,
  417. TypeId *const arrayTypeIdRef)
  418. {
  419. // This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
  420. // (see Lowerer::GenerateArrayTest) to minimize bailouts.
  421. Assert(var);
  422. Assert(isObjectWithArrayRef);
  423. Assert(arrayTypeIdRef);
  424. *isObjectWithArrayRef = false;
  425. *arrayTypeIdRef = TypeIds_Undefined;
  426. if(!RecyclableObject::Is(var))
  427. {
  428. return nullptr;
  429. }
  430. JavascriptArray *array = nullptr;
  431. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  432. if(vtable == VirtualTableInfo<DynamicObject>::Address)
  433. {
  434. ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
  435. array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
  436. if(!array)
  437. {
  438. return nullptr;
  439. }
  440. *isObjectWithArrayRef = true;
  441. vtable = VirtualTableInfoBase::GetVirtualTable(array);
  442. }
  443. if(vtable == VirtualTableInfo<JavascriptArray>::Address)
  444. {
  445. *arrayTypeIdRef = TypeIds_Array;
  446. }
  447. else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
  448. {
  449. *arrayTypeIdRef = TypeIds_NativeIntArray;
  450. }
  451. else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
  452. {
  453. *arrayTypeIdRef = TypeIds_NativeFloatArray;
  454. }
  455. else
  456. {
  457. return nullptr;
  458. }
  459. if(!array)
  460. {
  461. array = FromVar(var);
  462. }
  463. return array;
  464. }
  465. const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
  466. {
  467. // This is a helper function used by jitted code
  468. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  469. return array ? array->head : nullptr;
  470. }
  471. uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
  472. {
  473. // This is a helper function used by jitted code
  474. return headSegment ? headSegment->length : 0;
  475. }
  476. bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  477. const SparseArraySegmentBase *const headSegmentBeforeOperation,
  478. const uint32 headSegmentLengthBeforeOperation,
  479. const Var varAfterOperation)
  480. {
  481. // This is a helper function used by jitted code
  482. Assert(varAfterOperation);
  483. if(!headSegmentBeforeOperation)
  484. {
  485. return false;
  486. }
  487. const SparseArraySegmentBase *const headSegmentAfterOperation =
  488. Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
  489. return
  490. headSegmentAfterOperation != headSegmentBeforeOperation ||
  491. headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
  492. }
  493. uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
  494. {
  495. // This is a helper function used by jitted code
  496. bool isObjectWithArray;
  497. TypeId arrayTypeId;
  498. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
  499. return array && !isObjectWithArray ? array->GetLength() : 0;
  500. }
  501. bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
  502. {
  503. // This is a helper function used by jitted code
  504. return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
  505. }
  506. DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
  507. {
  508. // This is a helper function used by jitted code
  509. JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
  510. return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
  511. }
  512. bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
  513. const DynamicObjectFlags flagsBeforeOperation,
  514. const Var varAfterOperation)
  515. {
  516. // This is a helper function used by jitted code
  517. Assert(varAfterOperation);
  518. return
  519. !!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
  520. !(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
  521. }
  522. bool JavascriptArray::HasNoMissingValues() const
  523. {
  524. return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
  525. }
  526. bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
  527. {
  528. return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
  529. }
  530. void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
  531. {
  532. SetFlags(
  533. hasNoMissingValues
  534. ? GetFlags() | DynamicObjectFlags::HasNoMissingValues
  535. : GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
  536. }
  537. template<class T>
  538. bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
  539. {
  540. Assert(index < head->length);
  541. return SparseArraySegment<T>::IsMissingItem(&static_cast<SparseArraySegment<T> *>(head)->elements[index]);
  542. }
  543. bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
  544. {
  545. return IsMissingHeadSegmentItemImpl<Var>(index);
  546. }
  547. #if ENABLE_COPYONACCESS_ARRAY
  548. void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
  549. {
  550. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  551. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  552. SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
  553. #if ENABLE_DEBUG_CONFIG_OPTIONS
  554. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  555. {
  556. Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
  557. Output::Flush();
  558. }
  559. #endif
  560. newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
  561. this->SetHeadAndLastUsedSegment(newSeg);
  562. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
  563. this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
  564. ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
  565. if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
  566. {
  567. arrayInfo->isNotCopyOnAccessArray = 1;
  568. }
  569. }
  570. uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
  571. {
  572. if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
  573. {
  574. return Js::JavascriptArray::InvalidIndex;
  575. }
  576. else if (index == Js::JavascriptArray::InvalidIndex)
  577. {
  578. return 0;
  579. }
  580. else
  581. {
  582. return index + 1;
  583. }
  584. }
  585. BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
  586. {
  587. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  588. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  589. if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
  590. {
  591. return FALSE;
  592. }
  593. else
  594. {
  595. *outVal = seg->elements[index];
  596. return TRUE;
  597. }
  598. }
  599. #endif
  600. bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
  601. {
  602. return IsMissingHeadSegmentItemImpl<int32>(index);
  603. }
  604. bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
  605. {
  606. return IsMissingHeadSegmentItemImpl<double>(index);
  607. }
  608. /* static */
  609. bool JavascriptArray::HasInlineHeadSegment(uint32 length)
  610. {
  611. return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
  612. }
  613. Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
  614. {
  615. // Called only to create array literals: size is known.
  616. return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  617. }
  618. Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
  619. {
  620. // Called only to create array literals: size is known.
  621. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  622. SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
  623. Assert(elementCount <= head->length);
  624. js_memcpy_s(head->elements, sizeof(Var) * head->length, elements, sizeof(Var) * elementCount);
  625. #ifdef VALIDATE_ARRAY
  626. arr->ValidateArray();
  627. #endif
  628. return arr;
  629. }
  630. Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
  631. {
  632. // Called only to create array literals: size is known.
  633. JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
  634. array->SetHasNoMissingValues(false);
  635. SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)array->head;
  636. head->FillSegmentBuffer(0, elementCount);
  637. return array;
  638. }
  639. #if ENABLE_PROFILE_INFO
  640. Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  641. {
  642. if (arrayInfo->IsNativeIntArray())
  643. {
  644. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
  645. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  646. return arr;
  647. }
  648. if (arrayInfo->IsNativeFloatArray())
  649. {
  650. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
  651. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  652. return arr;
  653. }
  654. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  655. return arr;
  656. }
  657. #endif
  658. Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
  659. {
  660. uint32 count = ints->count;
  661. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  662. SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
  663. Assert(count > 0 && count == head->length);
  664. for (uint i = 0; i < count; i++)
  665. {
  666. head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  667. }
  668. return arr;
  669. }
  670. #if ENABLE_PROFILE_INFO
  671. Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  672. {
  673. // Called only to create array literals: size is known.
  674. uint32 count = ints->count;
  675. if (arrayInfo->IsNativeIntArray())
  676. {
  677. JavascriptNativeIntArray *arr;
  678. FunctionBody *functionBody = weakFuncRef->Get();
  679. JavascriptLibrary *lib = scriptContext->GetLibrary();
  680. #if ENABLE_COPYONACCESS_ARRAY
  681. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
  682. {
  683. Assert(lib->cacheForCopyOnAccessArraySegments);
  684. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  685. }
  686. else
  687. #endif
  688. {
  689. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
  690. SparseArraySegment<int32> *head = static_cast<SparseArraySegment<int32>*>(arr->head);
  691. Assert(count > 0 && count == head->length);
  692. js_memcpy_s(head->elements, sizeof(int32)* head->length, ints->elements, sizeof(int32)* count);
  693. }
  694. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  695. return arr;
  696. }
  697. if (arrayInfo->IsNativeFloatArray())
  698. {
  699. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  700. SparseArraySegment<double> *head = (SparseArraySegment<double>*)arr->head;
  701. Assert(count > 0 && count == head->length);
  702. for (uint i = 0; i < count; i++)
  703. {
  704. head->elements[i] = (double)ints->elements[i];
  705. }
  706. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  707. return arr;
  708. }
  709. return OP_NewScIntArray(ints, scriptContext);
  710. }
  711. #endif
  712. Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
  713. {
  714. uint32 count = doubles->count;
  715. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  716. SparseArraySegment<Var> *head = (SparseArraySegment<Var>*)arr->head;
  717. Assert(count > 0 && count == head->length);
  718. for (uint i = 0; i < count; i++)
  719. {
  720. double dval = doubles->elements[i];
  721. int32 ival;
  722. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  723. {
  724. head->elements[i] = TaggedInt::ToVarUnchecked(ival);
  725. }
  726. else
  727. {
  728. head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
  729. }
  730. }
  731. return arr;
  732. }
  733. #if ENABLE_PROFILE_INFO
  734. Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  735. {
  736. // Called only to create array literals: size is known.
  737. if (arrayInfo->IsNativeFloatArray())
  738. {
  739. arrayInfo->SetIsNotNativeIntArray();
  740. uint32 count = doubles->count;
  741. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  742. SparseArraySegment<double> *head = (SparseArraySegment<double>*)arr->head;
  743. Assert(count > 0 && count == head->length);
  744. js_memcpy_s(head->elements, sizeof(double) * head->length, doubles->elements, sizeof(double) * count);
  745. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  746. return arr;
  747. }
  748. return OP_NewScFltArray(doubles, scriptContext);
  749. }
  750. Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  751. {
  752. ARGUMENTS(args, callInfo);
  753. Assert(JavascriptFunction::Is(function) &&
  754. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  755. Assert(callInfo.Count >= 2);
  756. ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
  757. JavascriptArray* pNew = nullptr;
  758. if (callInfo.Count == 2)
  759. {
  760. // Exactly one argument, which is the array length if it's a uint32.
  761. Var firstArgument = args[1];
  762. int elementCount;
  763. if (TaggedInt::Is(firstArgument))
  764. {
  765. elementCount = TaggedInt::ToInt32(firstArgument);
  766. if (elementCount < 0)
  767. {
  768. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  769. }
  770. if (arrayInfo && arrayInfo->IsNativeArray())
  771. {
  772. if (arrayInfo->IsNativeIntArray())
  773. {
  774. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  775. }
  776. else
  777. {
  778. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  779. }
  780. }
  781. else
  782. {
  783. pNew = function->GetLibrary()->CreateArray(elementCount);
  784. }
  785. }
  786. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  787. {
  788. // Non-tagged-int number: make sure the double value is really a uint32.
  789. double value = JavascriptNumber::GetValue(firstArgument);
  790. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  791. if (value != uvalue)
  792. {
  793. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  794. }
  795. if (arrayInfo && arrayInfo->IsNativeArray())
  796. {
  797. if (arrayInfo->IsNativeIntArray())
  798. {
  799. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  800. }
  801. else
  802. {
  803. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  804. }
  805. }
  806. else
  807. {
  808. pNew = function->GetLibrary()->CreateArray(uvalue);
  809. }
  810. }
  811. else
  812. {
  813. //
  814. // First element is not int/double
  815. // create an array of length 1.
  816. // Set first element as the passed Var
  817. //
  818. pNew = function->GetLibrary()->CreateArray(1);
  819. pNew->DirectSetItemAt<Var>(0, firstArgument);
  820. }
  821. }
  822. else
  823. {
  824. // Called with a list of initial element values.
  825. // Create an array of the appropriate length and walk the list.
  826. if (arrayInfo && arrayInfo->IsNativeArray())
  827. {
  828. if (arrayInfo->IsNativeIntArray())
  829. {
  830. pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  831. }
  832. else
  833. {
  834. pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  835. }
  836. }
  837. else
  838. {
  839. pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
  840. }
  841. pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
  842. }
  843. #ifdef VALIDATE_ARRAY
  844. pNew->ValidateArray();
  845. #endif
  846. return pNew;
  847. }
  848. #endif
  849. Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  850. {
  851. ARGUMENTS(args, callInfo);
  852. return NewInstance(function, args);
  853. }
  854. Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
  855. {
  856. // Call to new Array(), possibly under another name.
  857. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  858. // SkipDefaultNewObject function flag should have prevented the default object
  859. // being created, except when call true a host dispatch.
  860. const CallInfo &callInfo = args.Info;
  861. Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
  862. bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
  863. Assert( isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr
  864. || JavascriptOperators::GetTypeId(args[0]) == TypeIds_HostDispatch);
  865. ScriptContext* scriptContext = function->GetScriptContext();
  866. JavascriptArray* pNew = nullptr;
  867. if (callInfo.Count < 2)
  868. {
  869. if (pNew == nullptr)
  870. {
  871. // No arguments passed to Array(), so create with the default size (0).
  872. pNew = CreateArrayFromConstructor(function, 0, scriptContext);
  873. }
  874. else
  875. {
  876. pNew->SetLength((uint32)0);
  877. }
  878. return isCtorSuperCall ?
  879. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  880. pNew;
  881. }
  882. if (callInfo.Count == 2)
  883. {
  884. // Exactly one argument, which is the array length if it's a uint32.
  885. Var firstArgument = args[1];
  886. int elementCount;
  887. if (TaggedInt::Is(firstArgument))
  888. {
  889. elementCount = TaggedInt::ToInt32(firstArgument);
  890. if (elementCount < 0)
  891. {
  892. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  893. }
  894. if (pNew == nullptr)
  895. {
  896. pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
  897. }
  898. else
  899. {
  900. pNew->SetLength(elementCount);
  901. }
  902. }
  903. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  904. {
  905. // Non-tagged-int number: make sure the double value is really a uint32.
  906. double value = JavascriptNumber::GetValue(firstArgument);
  907. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  908. if (value != uvalue)
  909. {
  910. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  911. }
  912. if (pNew == nullptr)
  913. {
  914. pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
  915. }
  916. else
  917. {
  918. pNew->SetLength(uvalue);
  919. }
  920. }
  921. else
  922. {
  923. //
  924. // First element is not int/double
  925. // create an array of length 1.
  926. // Set first element as the passed Var
  927. //
  928. if (pNew == nullptr)
  929. {
  930. pNew = CreateArrayFromConstructor(function, 1, scriptContext);
  931. }
  932. JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  933. // If we were passed an uninitialized JavascriptArray as the this argument,
  934. // we need to set the length. We must do this _after_ setting the first
  935. // element as the array may have side effects such as a setter for property
  936. // named '0' which would make the previous length of the array observable.
  937. // If we weren't passed a JavascriptArray as the this argument, this is no-op.
  938. pNew->SetLength(1);
  939. }
  940. }
  941. else
  942. {
  943. // Called with a list of initial element values.
  944. // Create an array of the appropriate length and walk the list.
  945. if (pNew == nullptr)
  946. {
  947. pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
  948. }
  949. else
  950. {
  951. // If we were passed an uninitialized JavascriptArray as the this argument,
  952. // we need to set the length. We should do this _after_ setting the
  953. // elements as the array may have side effects such as a setter for property
  954. // named '0' which would make the previous length of the array observable.
  955. // Note: We don't support this case now as the DirectSetItemAt calls in FillFromArgs
  956. // will not call the setter. Need to refactor that method.
  957. pNew->SetLength(callInfo.Count - 1);
  958. }
  959. pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
  960. }
  961. #ifdef VALIDATE_ARRAY
  962. pNew->ValidateArray();
  963. #endif
  964. return isCtorSuperCall ?
  965. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
  966. pNew;
  967. }
  968. JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
  969. {
  970. JavascriptLibrary* library = constructor->GetLibrary();
  971. // Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
  972. // Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
  973. // This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
  974. // constructor.
  975. JavascriptArray* arr = library->CreateArray(length);
  976. return arr;
  977. }
  978. #if ENABLE_PROFILE_INFO
  979. Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  980. {
  981. Assert(JavascriptFunction::Is(function) &&
  982. JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  983. if (arrayInfo->IsNativeIntArray())
  984. {
  985. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
  986. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  987. return arr;
  988. }
  989. if (arrayInfo->IsNativeFloatArray())
  990. {
  991. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
  992. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  993. return arr;
  994. }
  995. return scriptContext->GetLibrary()->CreateArray();
  996. }
  997. #endif
  998. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  999. {
  1000. ARGUMENTS(args, callInfo);
  1001. return NewInstance(function, args);
  1002. }
  1003. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
  1004. {
  1005. Assert(!PHASE_OFF1(NativeArrayPhase));
  1006. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1007. const CallInfo &callInfo = args.Info;
  1008. if (callInfo.Count < 2)
  1009. {
  1010. // No arguments passed to Array(), so create with the default size (0).
  1011. return function->GetLibrary()->CreateNativeIntArray();
  1012. }
  1013. JavascriptArray* pNew = nullptr;
  1014. if (callInfo.Count == 2)
  1015. {
  1016. // Exactly one argument, which is the array length if it's a uint32.
  1017. Var firstArgument = args[1];
  1018. int elementCount;
  1019. if (TaggedInt::Is(firstArgument))
  1020. {
  1021. elementCount = TaggedInt::ToInt32(firstArgument);
  1022. if (elementCount < 0)
  1023. {
  1024. JavascriptError::ThrowRangeError(
  1025. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1026. }
  1027. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  1028. }
  1029. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1030. {
  1031. // Non-tagged-int number: make sure the double value is really a uint32.
  1032. double value = JavascriptNumber::GetValue(firstArgument);
  1033. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1034. if (value != uvalue)
  1035. {
  1036. JavascriptError::ThrowRangeError(
  1037. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1038. }
  1039. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  1040. }
  1041. else
  1042. {
  1043. //
  1044. // First element is not int/double
  1045. // create an array of length 1.
  1046. // Set first element as the passed Var
  1047. //
  1048. pNew = function->GetLibrary()->CreateArray(1);
  1049. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1050. }
  1051. }
  1052. else
  1053. {
  1054. // Called with a list of initial element values.
  1055. // Create an array of the appropriate length and walk the list.
  1056. JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  1057. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1058. }
  1059. #ifdef VALIDATE_ARRAY
  1060. pNew->ValidateArray();
  1061. #endif
  1062. return pNew;
  1063. }
  1064. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1065. {
  1066. ARGUMENTS(args, callInfo);
  1067. return NewInstance(function, args);
  1068. }
  1069. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
  1070. {
  1071. Assert(!PHASE_OFF1(NativeArrayPhase));
  1072. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1073. const CallInfo &callInfo = args.Info;
  1074. if (callInfo.Count < 2)
  1075. {
  1076. // No arguments passed to Array(), so create with the default size (0).
  1077. return function->GetLibrary()->CreateNativeFloatArray();
  1078. }
  1079. JavascriptArray* pNew = nullptr;
  1080. if (callInfo.Count == 2)
  1081. {
  1082. // Exactly one argument, which is the array length if it's a uint32.
  1083. Var firstArgument = args[1];
  1084. int elementCount;
  1085. if (TaggedInt::Is(firstArgument))
  1086. {
  1087. elementCount = TaggedInt::ToInt32(firstArgument);
  1088. if (elementCount < 0)
  1089. {
  1090. JavascriptError::ThrowRangeError(
  1091. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1092. }
  1093. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  1094. }
  1095. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1096. {
  1097. // Non-tagged-int number: make sure the double value is really a uint32.
  1098. double value = JavascriptNumber::GetValue(firstArgument);
  1099. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1100. if (value != uvalue)
  1101. {
  1102. JavascriptError::ThrowRangeError(
  1103. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1104. }
  1105. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  1106. }
  1107. else
  1108. {
  1109. //
  1110. // First element is not int/double
  1111. // create an array of length 1.
  1112. // Set first element as the passed Var
  1113. //
  1114. pNew = function->GetLibrary()->CreateArray(1);
  1115. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1116. }
  1117. }
  1118. else
  1119. {
  1120. // Called with a list of initial element values.
  1121. // Create an array of the appropriate length and walk the list.
  1122. JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  1123. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1124. }
  1125. #ifdef VALIDATE_ARRAY
  1126. pNew->ValidateArray();
  1127. #endif
  1128. return pNew;
  1129. }
  1130. #if ENABLE_PROFILE_INFO
  1131. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1132. #else
  1133. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1134. #endif
  1135. {
  1136. uint i;
  1137. for (i = start; i < length; i++)
  1138. {
  1139. Var item = args[i + 1];
  1140. bool isTaggedInt = TaggedInt::Is(item);
  1141. bool isTaggedIntMissingValue = false;
  1142. #ifdef _M_AMD64
  1143. if (isTaggedInt)
  1144. {
  1145. int32 iValue = TaggedInt::ToInt32(item);
  1146. isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
  1147. }
  1148. #endif
  1149. if (isTaggedInt && !isTaggedIntMissingValue)
  1150. {
  1151. // This is taggedInt case and we verified that item is not missing value in AMD64.
  1152. this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
  1153. }
  1154. else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
  1155. {
  1156. double dvalue = JavascriptNumber::GetValue(item);
  1157. int32 ivalue;
  1158. if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
  1159. {
  1160. this->DirectSetItemAt(i, ivalue);
  1161. }
  1162. else
  1163. {
  1164. #if ENABLE_PROFILE_INFO
  1165. if (arrayInfo)
  1166. {
  1167. arrayInfo->SetIsNotNativeIntArray();
  1168. }
  1169. #endif
  1170. if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1171. {
  1172. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1173. // array here, so go ahead.
  1174. JavascriptNativeFloatArray *fArr =
  1175. this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
  1176. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
  1177. }
  1178. JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
  1179. fArr->DirectSetItemAt(i, dvalue);
  1180. #if ENABLE_PROFILE_INFO
  1181. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
  1182. #else
  1183. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
  1184. #endif
  1185. }
  1186. }
  1187. else
  1188. {
  1189. #if ENABLE_PROFILE_INFO
  1190. if (arrayInfo)
  1191. {
  1192. arrayInfo->SetIsNotNativeArray();
  1193. }
  1194. #endif
  1195. #pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
  1196. if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1197. {
  1198. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1199. // array here, so go ahead.
  1200. JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
  1201. return arr->JavascriptArray::FillFromArgs(length, 0, args);
  1202. }
  1203. JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
  1204. #if ENABLE_PROFILE_INFO
  1205. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1206. #else
  1207. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1208. #endif
  1209. }
  1210. }
  1211. return this;
  1212. }
  1213. #if ENABLE_PROFILE_INFO
  1214. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1215. #else
  1216. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1217. #endif
  1218. {
  1219. uint i;
  1220. for (i = start; i < length; i++)
  1221. {
  1222. Var item = args[i + 1];
  1223. if (TaggedInt::Is(item))
  1224. {
  1225. this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
  1226. }
  1227. else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
  1228. {
  1229. this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
  1230. }
  1231. else
  1232. {
  1233. JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
  1234. #if ENABLE_PROFILE_INFO
  1235. if (arrayInfo)
  1236. {
  1237. arrayInfo->SetIsNotNativeArray();
  1238. }
  1239. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1240. #else
  1241. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1242. #endif
  1243. }
  1244. }
  1245. return this;
  1246. }
  1247. #if ENABLE_PROFILE_INFO
  1248. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1249. #else
  1250. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1251. #endif
  1252. {
  1253. uint32 i;
  1254. for (i = start; i < length; i++)
  1255. {
  1256. Var item = args[i + 1];
  1257. this->DirectSetItemAt(i, item);
  1258. }
  1259. return this;
  1260. }
  1261. DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1262. {
  1263. return scriptContext->GetLibrary()->GetNativeIntArrayType();
  1264. }
  1265. #if ENABLE_COPYONACCESS_ARRAY
  1266. DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1267. {
  1268. return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
  1269. }
  1270. #endif
  1271. JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
  1272. {
  1273. #if ENABLE_PROFILE_INFO
  1274. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1275. if (arrayInfo)
  1276. {
  1277. #if DBG
  1278. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1279. Js::JavascriptFunction* caller = NULL;
  1280. bool foundScriptCaller = false;
  1281. while(walker.GetCaller(&caller))
  1282. {
  1283. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1284. {
  1285. foundScriptCaller = true;
  1286. break;
  1287. }
  1288. }
  1289. if(foundScriptCaller)
  1290. {
  1291. Assert(caller);
  1292. Assert(caller->GetFunctionBody());
  1293. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1294. {
  1295. Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1296. Output::Flush();
  1297. }
  1298. }
  1299. else
  1300. {
  1301. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1302. {
  1303. Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
  1304. Output::Flush();
  1305. }
  1306. }
  1307. #else
  1308. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1309. {
  1310. Output::Print(_u("Conversion: Int array to Float array"));
  1311. Output::Flush();
  1312. }
  1313. #endif
  1314. arrayInfo->SetIsNotNativeIntArray();
  1315. }
  1316. #endif
  1317. // Grow the segments
  1318. ScriptContext *scriptContext = intArray->GetScriptContext();
  1319. Recycler *recycler = scriptContext->GetRecycler();
  1320. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1321. for (seg = intArray->head; seg; seg = nextSeg)
  1322. {
  1323. nextSeg = seg->next;
  1324. uint32 size = seg->size;
  1325. if (size == 0)
  1326. {
  1327. continue;
  1328. }
  1329. uint32 left = seg->left;
  1330. uint32 length = seg->length;
  1331. int i;
  1332. int32 ival;
  1333. // The old segment will have size/2 and length capped by the new size.
  1334. seg->size >>= 1;
  1335. if (seg == intArray->head || seg->length > (seg->size >>= 1))
  1336. {
  1337. // Some live elements are being pushed out of this segment, so allocate a new one.
  1338. SparseArraySegment<double> *newSeg =
  1339. SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
  1340. Assert(newSeg != nullptr);
  1341. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1342. newSeg->next = nextSeg;
  1343. intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
  1344. if (intArray->GetLastUsedSegment() == seg)
  1345. {
  1346. intArray->SetLastUsedSegment(newSeg);
  1347. }
  1348. prevSeg = newSeg;
  1349. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1350. if (segmentMap)
  1351. {
  1352. segmentMap->SwapSegment(left, seg, newSeg);
  1353. }
  1354. // Fill the new segment with the overflow.
  1355. for (i = 0; (uint)i < newSeg->length; i++)
  1356. {
  1357. ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
  1358. if (ival == JavascriptNativeIntArray::MissingItem)
  1359. {
  1360. continue;
  1361. }
  1362. newSeg->elements[i] = (double)ival;
  1363. }
  1364. }
  1365. else
  1366. {
  1367. // Now convert the contents that will remain in the old segment.
  1368. for (i = seg->length - 1; i >= 0; i--)
  1369. {
  1370. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1371. if (ival == JavascriptNativeIntArray::MissingItem)
  1372. {
  1373. ((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
  1374. }
  1375. else
  1376. {
  1377. ((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
  1378. }
  1379. }
  1380. prevSeg = seg;
  1381. }
  1382. }
  1383. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1384. {
  1385. intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1386. }
  1387. else
  1388. {
  1389. if (intArray->GetDynamicType()->GetIsLocked())
  1390. {
  1391. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1392. if (typeHandler->IsPathTypeHandler())
  1393. {
  1394. // We can't allow a type with the new type ID to be promoted to the old type.
  1395. // So go to a dictionary type handler, which will orphan the new type.
  1396. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1397. // If it does matter, try building a path from the new type's built-in root.
  1398. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1399. }
  1400. else
  1401. {
  1402. intArray->ChangeType();
  1403. }
  1404. }
  1405. intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1406. }
  1407. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1408. {
  1409. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1410. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
  1411. }
  1412. else
  1413. {
  1414. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1415. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
  1416. }
  1417. return (JavascriptNativeFloatArray*)intArray;
  1418. }
  1419. /*
  1420. * JavascriptArray::ChangeArrayTypeToNativeArray<double>
  1421. * - Converts the Var Array's type to NativeFloat.
  1422. * - Sets the VirtualTable to "JavascriptNativeFloatArray"
  1423. */
  1424. template<>
  1425. void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1426. {
  1427. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1428. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1429. {
  1430. varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1431. }
  1432. else
  1433. {
  1434. if (varArray->GetDynamicType()->GetIsLocked())
  1435. {
  1436. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1437. if (typeHandler->IsPathTypeHandler())
  1438. {
  1439. // We can't allow a type with the new type ID to be promoted to the old type.
  1440. // So go to a dictionary type handler, which will orphan the new type.
  1441. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1442. // If it does matter, try building a path from the new type's built-in root.
  1443. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1444. }
  1445. else
  1446. {
  1447. varArray->ChangeType();
  1448. }
  1449. }
  1450. varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1451. }
  1452. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1453. {
  1454. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1455. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
  1456. }
  1457. else
  1458. {
  1459. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1460. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
  1461. }
  1462. }
  1463. /*
  1464. * JavascriptArray::ChangeArrayTypeToNativeArray<int32>
  1465. * - Converts the Var Array's type to NativeInt.
  1466. * - Sets the VirtualTable to "JavascriptNativeIntArray"
  1467. */
  1468. template<>
  1469. void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1470. {
  1471. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1472. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1473. {
  1474. varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
  1475. }
  1476. else
  1477. {
  1478. if (varArray->GetDynamicType()->GetIsLocked())
  1479. {
  1480. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1481. if (typeHandler->IsPathTypeHandler())
  1482. {
  1483. // We can't allow a type with the new type ID to be promoted to the old type.
  1484. // So go to a dictionary type handler, which will orphan the new type.
  1485. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1486. // If it does matter, try building a path from the new type's built-in root.
  1487. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1488. }
  1489. else
  1490. {
  1491. varArray->ChangeType();
  1492. }
  1493. }
  1494. varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
  1495. }
  1496. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1497. {
  1498. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1499. VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
  1500. }
  1501. else
  1502. {
  1503. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1504. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
  1505. }
  1506. }
  1507. template<>
  1508. int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
  1509. {
  1510. return JavascriptConversion::ToInt32(ival, scriptContext);
  1511. }
  1512. template <>
  1513. double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
  1514. {
  1515. return JavascriptConversion::ToNumber(ival, scriptContext);
  1516. }
  1517. /*
  1518. * JavascriptArray::ConvertToNativeArrayInPlace
  1519. * In place conversion of all Var elements to Native Int/Double elements in an array.
  1520. * We do not update the DynamicProfileInfo of the array here.
  1521. */
  1522. template<typename NativeArrayType, typename T>
  1523. NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
  1524. {
  1525. AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
  1526. ScriptContext *scriptContext = varArray->GetScriptContext();
  1527. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1528. for (seg = varArray->head; seg; seg = nextSeg)
  1529. {
  1530. nextSeg = seg->next;
  1531. uint32 size = seg->size;
  1532. if (size == 0)
  1533. {
  1534. continue;
  1535. }
  1536. int i;
  1537. Var ival;
  1538. uint32 growFactor = sizeof(Var) / sizeof(T);
  1539. AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
  1540. // Now convert the contents that will remain in the old segment.
  1541. for (i = seg->length - 1; i >= 0; i--)
  1542. {
  1543. ival = ((SparseArraySegment<Var>*)seg)->elements[i];
  1544. if (ival == JavascriptArray::MissingItem)
  1545. {
  1546. ((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
  1547. }
  1548. else
  1549. {
  1550. ((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
  1551. }
  1552. }
  1553. prevSeg = seg;
  1554. }
  1555. // Update the type of the Array
  1556. ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
  1557. return (NativeArrayType*)varArray;
  1558. }
  1559. JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
  1560. {
  1561. #if ENABLE_COPYONACCESS_ARRAY
  1562. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
  1563. #endif
  1564. ScriptContext *scriptContext = intArray->GetScriptContext();
  1565. Recycler *recycler = scriptContext->GetRecycler();
  1566. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1567. for (seg = intArray->head; seg; seg = nextSeg)
  1568. {
  1569. nextSeg = seg->next;
  1570. uint32 size = seg->size;
  1571. if (size == 0)
  1572. {
  1573. continue;
  1574. }
  1575. uint32 left = seg->left;
  1576. uint32 length = seg->length;
  1577. int i;
  1578. int32 ival;
  1579. // Shrink?
  1580. uint32 growFactor = sizeof(Var) / sizeof(int32);
  1581. if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size /= growFactor))) ||
  1582. (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
  1583. {
  1584. // Some live elements are being pushed out of this segment, so allocate a new one.
  1585. // And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
  1586. SparseArraySegment<Var> *newSeg =
  1587. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1588. AnalysisAssert(newSeg);
  1589. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1590. newSeg->next = nextSeg;
  1591. intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1592. if (intArray->GetLastUsedSegment() == seg)
  1593. {
  1594. intArray->SetLastUsedSegment(newSeg);
  1595. }
  1596. prevSeg = newSeg;
  1597. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1598. if (segmentMap)
  1599. {
  1600. segmentMap->SwapSegment(left, seg, newSeg);
  1601. }
  1602. // Fill the new segment with the overflow.
  1603. for (i = 0; (uint)i < newSeg->length; i++)
  1604. {
  1605. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1606. if (ival == JavascriptNativeIntArray::MissingItem)
  1607. {
  1608. continue;
  1609. }
  1610. newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1611. }
  1612. }
  1613. else
  1614. {
  1615. // Now convert the contents that will remain in the old segment.
  1616. // Walk backward in case we're growing the element size.
  1617. for (i = seg->length - 1; i >= 0; i--)
  1618. {
  1619. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1620. if (ival == JavascriptNativeIntArray::MissingItem)
  1621. {
  1622. ((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
  1623. }
  1624. else
  1625. {
  1626. ((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1627. }
  1628. }
  1629. prevSeg = seg;
  1630. }
  1631. }
  1632. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1633. {
  1634. intArray->type = scriptContext->GetLibrary()->GetArrayType();
  1635. }
  1636. else
  1637. {
  1638. if (intArray->GetDynamicType()->GetIsLocked())
  1639. {
  1640. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1641. if (typeHandler->IsPathTypeHandler())
  1642. {
  1643. // We can't allow a type with the new type ID to be promoted to the old type.
  1644. // So go to a dictionary type handler, which will orphan the new type.
  1645. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1646. // If it does matter, try building a path from the new type's built-in root.
  1647. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1648. }
  1649. else
  1650. {
  1651. intArray->ChangeType();
  1652. }
  1653. }
  1654. intArray->GetType()->SetTypeId(TypeIds_Array);
  1655. }
  1656. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1657. {
  1658. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1659. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
  1660. }
  1661. else
  1662. {
  1663. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1664. VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
  1665. }
  1666. return intArray;
  1667. }
  1668. JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
  1669. {
  1670. #if ENABLE_PROFILE_INFO
  1671. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1672. if (arrayInfo)
  1673. {
  1674. #if DBG
  1675. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1676. Js::JavascriptFunction* caller = NULL;
  1677. bool foundScriptCaller = false;
  1678. while(walker.GetCaller(&caller))
  1679. {
  1680. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1681. {
  1682. foundScriptCaller = true;
  1683. break;
  1684. }
  1685. }
  1686. if(foundScriptCaller)
  1687. {
  1688. Assert(caller);
  1689. Assert(caller->GetFunctionBody());
  1690. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1691. {
  1692. Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1693. Output::Flush();
  1694. }
  1695. }
  1696. else
  1697. {
  1698. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1699. {
  1700. Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
  1701. Output::Flush();
  1702. }
  1703. }
  1704. #else
  1705. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1706. {
  1707. Output::Print(_u("Conversion: Int array to Var array"));
  1708. Output::Flush();
  1709. }
  1710. #endif
  1711. arrayInfo->SetIsNotNativeArray();
  1712. }
  1713. #endif
  1714. intArray->ClearArrayCallSiteIndex();
  1715. return ConvertToVarArray(intArray);
  1716. }
  1717. DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
  1718. {
  1719. return scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1720. }
  1721. /*
  1722. * JavascriptNativeFloatArray::ConvertToVarArray
  1723. * This function only converts all Float elements to Var elements in an array.
  1724. * DynamicProfileInfo of the array is not updated in this function.
  1725. */
  1726. JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
  1727. {
  1728. // We can't be growing the size of the element.
  1729. Assert(sizeof(double) >= sizeof(Var));
  1730. uint32 shrinkFactor = sizeof(double) / sizeof(Var);
  1731. ScriptContext *scriptContext = fArray->GetScriptContext();
  1732. Recycler *recycler = scriptContext->GetRecycler();
  1733. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1734. for (seg = fArray->head; seg; seg = nextSeg)
  1735. {
  1736. nextSeg = seg->next;
  1737. if (seg->size == 0)
  1738. {
  1739. continue;
  1740. }
  1741. uint32 left = seg->left;
  1742. uint32 length = seg->length;
  1743. SparseArraySegment<Var> *newSeg;
  1744. if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
  1745. {
  1746. // The old segment is not scanned by the recycler, so we need a new one to hold vars.
  1747. newSeg =
  1748. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1749. Assert((prevSeg == nullptr) == (seg == fArray->head));
  1750. newSeg->next = nextSeg;
  1751. fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1752. if (fArray->GetLastUsedSegment() == seg)
  1753. {
  1754. fArray->SetLastUsedSegment(newSeg);
  1755. }
  1756. prevSeg = newSeg;
  1757. SegmentBTree * segmentMap = fArray->GetSegmentMap();
  1758. if (segmentMap)
  1759. {
  1760. segmentMap->SwapSegment(left, seg, newSeg);
  1761. }
  1762. }
  1763. else
  1764. {
  1765. newSeg = (SparseArraySegment<Var>*)seg;
  1766. prevSeg = seg;
  1767. if (shrinkFactor != 1)
  1768. {
  1769. uint32 newSize = seg->size * shrinkFactor;
  1770. uint32 limit;
  1771. if (seg->next)
  1772. {
  1773. limit = seg->next->left;
  1774. }
  1775. else
  1776. {
  1777. limit = JavascriptArray::MaxArrayLength;
  1778. }
  1779. seg->size = min(newSize, limit - seg->left);
  1780. }
  1781. }
  1782. uint32 i;
  1783. for (i = 0; i < seg->length; i++)
  1784. {
  1785. if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
  1786. {
  1787. if (seg == newSeg)
  1788. {
  1789. newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
  1790. }
  1791. Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
  1792. }
  1793. else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
  1794. {
  1795. newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
  1796. }
  1797. else
  1798. {
  1799. int32 ival;
  1800. double dval = ((SparseArraySegment<double>*)seg)->elements[i];
  1801. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  1802. {
  1803. newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
  1804. }
  1805. else
  1806. {
  1807. newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
  1808. }
  1809. }
  1810. }
  1811. if (seg == newSeg && shrinkFactor != 1)
  1812. {
  1813. // Fill the remaining slots.
  1814. newSeg->FillSegmentBuffer(i, seg->size);
  1815. }
  1816. }
  1817. if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
  1818. {
  1819. fArray->type = scriptContext->GetLibrary()->GetArrayType();
  1820. }
  1821. else
  1822. {
  1823. if (fArray->GetDynamicType()->GetIsLocked())
  1824. {
  1825. DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
  1826. if (typeHandler->IsPathTypeHandler())
  1827. {
  1828. // We can't allow a type with the new type ID to be promoted to the old type.
  1829. // So go to a dictionary type handler, which will orphan the new type.
  1830. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1831. // If it does matter, try building a path from the new type's built-in root.
  1832. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
  1833. }
  1834. else
  1835. {
  1836. fArray->ChangeType();
  1837. }
  1838. }
  1839. fArray->GetType()->SetTypeId(TypeIds_Array);
  1840. }
  1841. if (CrossSite::IsCrossSiteObjectTyped(fArray))
  1842. {
  1843. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
  1844. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
  1845. }
  1846. else
  1847. {
  1848. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
  1849. VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
  1850. }
  1851. return fArray;
  1852. }
  1853. JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
  1854. {
  1855. #if ENABLE_PROFILE_INFO
  1856. ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
  1857. if (arrayInfo)
  1858. {
  1859. #if DBG
  1860. Js::JavascriptStackWalker walker(fArray->GetScriptContext());
  1861. Js::JavascriptFunction* caller = NULL;
  1862. bool foundScriptCaller = false;
  1863. while(walker.GetCaller(&caller))
  1864. {
  1865. if(caller != NULL && Js::ScriptFunction::Is(caller))
  1866. {
  1867. foundScriptCaller = true;
  1868. break;
  1869. }
  1870. }
  1871. if(foundScriptCaller)
  1872. {
  1873. Assert(caller);
  1874. Assert(caller->GetFunctionBody());
  1875. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1876. {
  1877. Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1878. Output::Flush();
  1879. }
  1880. }
  1881. else
  1882. {
  1883. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1884. {
  1885. Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
  1886. Output::Flush();
  1887. }
  1888. }
  1889. #else
  1890. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1891. {
  1892. Output::Print(_u("Conversion: Float array to Var array"));
  1893. Output::Flush();
  1894. }
  1895. #endif
  1896. if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
  1897. {
  1898. Assert(!arrayInfo->IsNativeIntArray());
  1899. }
  1900. arrayInfo->SetIsNotNativeArray();
  1901. }
  1902. #endif
  1903. fArray->ClearArrayCallSiteIndex();
  1904. return ConvertToVarArray(fArray);
  1905. }
  1906. // Convert Var to index in the Array.
  1907. // Note: Spec calls out a few rules for these parameters:
  1908. // 1. if (arg > length) { return length; }
  1909. // clamp to length, not length-1
  1910. // 2. if (arg < 0) { return max(0, length + arg); }
  1911. // treat negative arg as index from the end of the array (with -1 mapping to length-1)
  1912. // Effectively, this function will return a value between 0 and length, inclusive.
  1913. int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
  1914. {
  1915. int64 index;
  1916. if (TaggedInt::Is(arg))
  1917. {
  1918. int intValue = TaggedInt::ToInt32(arg);
  1919. if (intValue < 0)
  1920. {
  1921. index = max<int64>(0, length + intValue);
  1922. }
  1923. else
  1924. {
  1925. index = intValue;
  1926. }
  1927. if (index > length)
  1928. {
  1929. index = length;
  1930. }
  1931. }
  1932. else
  1933. {
  1934. double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
  1935. // Handle the Number.POSITIVE_INFINITY case
  1936. if (doubleValue > length)
  1937. {
  1938. return length;
  1939. }
  1940. index = NumberUtilities::TryToInt64(doubleValue);
  1941. if (index < 0)
  1942. {
  1943. index = max<int64>(0, index + length);
  1944. }
  1945. }
  1946. return index;
  1947. }
  1948. TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  1949. {
  1950. int32 iValue;
  1951. double dValue;
  1952. TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  1953. if (typeId == TypeIds_NativeIntArray)
  1954. {
  1955. arr->SetArrayLiteralItem(index, iValue);
  1956. }
  1957. else if (typeId == TypeIds_NativeFloatArray)
  1958. {
  1959. arr->SetArrayLiteralItem(index, dValue);
  1960. }
  1961. else
  1962. {
  1963. arr->SetArrayLiteralItem(index, value);
  1964. }
  1965. return typeId;
  1966. }
  1967. TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  1968. {
  1969. double dValue;
  1970. TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
  1971. if (typeId == TypeIds_NativeFloatArray)
  1972. {
  1973. arr->SetArrayLiteralItem(index, dValue);
  1974. }
  1975. else
  1976. {
  1977. arr->SetArrayLiteralItem(index, value);
  1978. }
  1979. return typeId;
  1980. }
  1981. template<typename T>
  1982. void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
  1983. {
  1984. SparseArraySegment<T> * segment = (SparseArraySegment<T>*)this->head;
  1985. Assert(segment->left == 0);
  1986. Assert(index < segment->length);
  1987. segment->elements[index] = value;
  1988. }
  1989. void JavascriptNativeIntArray::SetIsPrototype()
  1990. {
  1991. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  1992. ToVarArray(this);
  1993. __super::SetIsPrototype();
  1994. }
  1995. void JavascriptNativeFloatArray::SetIsPrototype()
  1996. {
  1997. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  1998. ToVarArray(this);
  1999. __super::SetIsPrototype();
  2000. }
  2001. #if ENABLE_PROFILE_INFO
  2002. ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
  2003. {
  2004. RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
  2005. if (weakRef)
  2006. {
  2007. FunctionBody *functionBody = weakRef->Get();
  2008. if (functionBody)
  2009. {
  2010. if (functionBody->HasDynamicProfileInfo())
  2011. {
  2012. Js::ProfileId profileId = this->GetArrayCallSiteIndex();
  2013. if (profileId < functionBody->GetProfiledArrayCallSiteCount())
  2014. {
  2015. return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  2016. }
  2017. }
  2018. }
  2019. else
  2020. {
  2021. this->ClearArrayCallSiteIndex();
  2022. }
  2023. }
  2024. return nullptr;
  2025. }
  2026. void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
  2027. {
  2028. Assert(weakRef);
  2029. FunctionBody *functionBody = weakRef->Get();
  2030. if (functionBody && functionBody->HasDynamicProfileInfo())
  2031. {
  2032. ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
  2033. Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
  2034. Assert(index < functionBody->GetProfiledArrayCallSiteCount());
  2035. SetArrayCallSite(index, weakRef);
  2036. }
  2037. }
  2038. void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
  2039. {
  2040. if (baseArray->weakRefToFuncBody)
  2041. {
  2042. if (baseArray->weakRefToFuncBody->Get())
  2043. {
  2044. SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
  2045. }
  2046. else
  2047. {
  2048. baseArray->ClearArrayCallSiteIndex();
  2049. }
  2050. }
  2051. }
  2052. #endif
  2053. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2054. {
  2055. if (JavascriptNativeIntArray::Is(this))
  2056. {
  2057. return this->FindMinOrMax<int32, false>(scriptContext, findMax);
  2058. }
  2059. else
  2060. {
  2061. return this->FindMinOrMax<double, true>(scriptContext, findMax);
  2062. }
  2063. }
  2064. template <typename T, bool checkNaNAndNegZero>
  2065. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2066. {
  2067. AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
  2068. uint len = this->GetLength();
  2069. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
  2070. uint headSegLen = headSegment->length;
  2071. Assert(headSegLen == len);
  2072. if (headSegment->next == nullptr)
  2073. {
  2074. T currentRes = headSegment->elements[0];
  2075. for (uint i = 0; i < headSegLen; i++)
  2076. {
  2077. T compare = headSegment->elements[i];
  2078. if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
  2079. {
  2080. return scriptContext->GetLibrary()->GetNaN();
  2081. }
  2082. if (findMax ? currentRes < compare : currentRes > compare ||
  2083. (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
  2084. {
  2085. currentRes = compare;
  2086. }
  2087. }
  2088. return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
  2089. }
  2090. else
  2091. {
  2092. AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
  2093. Throw::FatalInternalError();
  2094. }
  2095. }
  2096. SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
  2097. {
  2098. return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot->lastUsedSegment : segmentUnion.lastUsedSegment);
  2099. }
  2100. void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
  2101. {
  2102. Assert(!HasSegmentMap());
  2103. this->head = this->segmentUnion.lastUsedSegment = segment;
  2104. }
  2105. void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
  2106. {
  2107. if (HasSegmentMap())
  2108. {
  2109. this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
  2110. }
  2111. else
  2112. {
  2113. this->segmentUnion.lastUsedSegment = segment;
  2114. }
  2115. }
  2116. bool JavascriptArray::HasSegmentMap() const
  2117. {
  2118. return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
  2119. }
  2120. SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
  2121. {
  2122. return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
  2123. }
  2124. void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
  2125. {
  2126. Assert(!HasSegmentMap());
  2127. SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
  2128. SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
  2129. segmentUnion.segmentBTreeRoot = segmentMap;
  2130. segmentMap->lastUsedSegment = lastUsedSeg;
  2131. }
  2132. void JavascriptArray::ClearSegmentMap()
  2133. {
  2134. if (HasSegmentMap())
  2135. {
  2136. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  2137. SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
  2138. segmentUnion.segmentBTreeRoot = nullptr;
  2139. segmentUnion.lastUsedSegment = lastUsedSeg;
  2140. }
  2141. }
  2142. SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
  2143. {
  2144. Recycler* recycler = GetRecycler();
  2145. SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
  2146. ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
  2147. {
  2148. tmpSegmentMap->Add(recycler, current);
  2149. return false;
  2150. });
  2151. // There could be OOM during building segment map. Save to array only after its successful completion.
  2152. SetSegmentMap(tmpSegmentMap);
  2153. return tmpSegmentMap;
  2154. }
  2155. void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
  2156. {
  2157. SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
  2158. if (savedSegmentMap)
  2159. {
  2160. //
  2161. // We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
  2162. // array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
  2163. // if adding segment succeeds.
  2164. //
  2165. ClearSegmentMap();
  2166. savedSegmentMap->Add(recycler, seg);
  2167. SetSegmentMap(savedSegmentMap);
  2168. }
  2169. }
  2170. void JavascriptArray::InvalidateLastUsedSegment()
  2171. {
  2172. this->SetLastUsedSegment(this->head);
  2173. }
  2174. DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2175. {
  2176. DescriptorFlags flags;
  2177. if (GetSetterBuiltIns(propertyId, info, &flags))
  2178. {
  2179. return flags;
  2180. }
  2181. return __super::GetSetter(propertyId, setterValue, info, requestContext);
  2182. }
  2183. DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2184. {
  2185. DescriptorFlags flags;
  2186. PropertyRecord const* propertyRecord;
  2187. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2188. if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
  2189. {
  2190. return flags;
  2191. }
  2192. return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
  2193. }
  2194. bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
  2195. {
  2196. if (propertyId == PropertyIds::length)
  2197. {
  2198. PropertyValueInfo::SetNoCache(info, this);
  2199. *descriptorFlags = WritableData;
  2200. return true;
  2201. }
  2202. return false;
  2203. }
  2204. SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
  2205. {
  2206. SparseArraySegmentBase *seg = nullptr;
  2207. SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
  2208. if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
  2209. {
  2210. seg = lastUsedSeg;
  2211. if(index - lastUsedSeg->left < lastUsedSeg->size)
  2212. {
  2213. return seg;
  2214. }
  2215. }
  2216. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  2217. if(!useSegmentMap || !segmentMap)
  2218. {
  2219. return seg ? seg : this->head;
  2220. }
  2221. if(seg)
  2222. {
  2223. // If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
  2224. // segment map, as it is likely to hit
  2225. SparseArraySegmentBase *const nextSeg = seg->next;
  2226. if(nextSeg)
  2227. {
  2228. if(index < nextSeg->left)
  2229. {
  2230. return seg;
  2231. }
  2232. else if(index - nextSeg->left < nextSeg->size)
  2233. {
  2234. return nextSeg;
  2235. }
  2236. }
  2237. }
  2238. SparseArraySegmentBase *matchOrNextSeg;
  2239. segmentMap->Find(index, seg, matchOrNextSeg);
  2240. return seg ? seg : matchOrNextSeg;
  2241. }
  2242. uint32 JavascriptArray::GetNextIndex(uint32 index) const
  2243. {
  2244. if (JavascriptNativeIntArray::Is((Var)this))
  2245. {
  2246. return this->GetNextIndexHelper<int32>(index);
  2247. }
  2248. else if (JavascriptNativeFloatArray::Is((Var)this))
  2249. {
  2250. return this->GetNextIndexHelper<double>(index);
  2251. }
  2252. return this->GetNextIndexHelper<Var>(index);
  2253. }
  2254. template<typename T>
  2255. uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
  2256. {
  2257. AssertMsg(this->head, "array head should never be null");
  2258. uint candidateIndex;
  2259. if (index == JavascriptArray::InvalidIndex)
  2260. {
  2261. candidateIndex = head->left;
  2262. }
  2263. else
  2264. {
  2265. candidateIndex = index + 1;
  2266. }
  2267. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
  2268. while (current != nullptr)
  2269. {
  2270. if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
  2271. {
  2272. for (uint i = candidateIndex - current->left; i < current->length; i++)
  2273. {
  2274. if (!SparseArraySegment<T>::IsMissingItem(&current->elements[i]))
  2275. {
  2276. return i + current->left;
  2277. }
  2278. }
  2279. }
  2280. current = (SparseArraySegment<T>*)current->next;
  2281. if (current != NULL)
  2282. {
  2283. if (candidateIndex < current->left)
  2284. {
  2285. candidateIndex = current->left;
  2286. }
  2287. }
  2288. }
  2289. return JavascriptArray::InvalidIndex;
  2290. }
  2291. // If new length > length, we just reset the length
  2292. // If new length < length, we need to remove the rest of the elements and segment
  2293. void JavascriptArray::SetLength(uint32 newLength)
  2294. {
  2295. if (newLength == length)
  2296. return;
  2297. if (head == EmptySegment)
  2298. {
  2299. // Do nothing to the segment.
  2300. }
  2301. else if (newLength == 0)
  2302. {
  2303. this->ClearElements(head, 0);
  2304. head->length = 0;
  2305. head->next = nullptr;
  2306. SetHasNoMissingValues();
  2307. ClearSegmentMap();
  2308. this->InvalidateLastUsedSegment();
  2309. }
  2310. else if (newLength < length)
  2311. {
  2312. // _ _ 2 3 _ _ 6 7 _ _
  2313. // SetLength(0)
  2314. // 0 <= left -> set *prev = null
  2315. // SetLength(2)
  2316. // 2 <= left -> set *prev = null
  2317. // SetLength(3)
  2318. // 3 !<= left; 3 <= right -> truncate to length - 1
  2319. // SetLength(5)
  2320. // 5 <=
  2321. SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
  2322. SparseArraySegmentBase** prev = &head;
  2323. while(next != nullptr)
  2324. {
  2325. if (newLength <= next->left)
  2326. {
  2327. ClearSegmentMap(); // truncate segments, null out segmentMap
  2328. *prev = nullptr;
  2329. break;
  2330. }
  2331. else if (newLength <= (next->left + next->length))
  2332. {
  2333. if (next->next)
  2334. {
  2335. ClearSegmentMap(); // Will truncate segments, null out segmentMap
  2336. }
  2337. uint32 newSegmentLength = newLength - next->left;
  2338. this->ClearElements(next, newSegmentLength);
  2339. next->next = nullptr;
  2340. next->length = newSegmentLength;
  2341. break;
  2342. }
  2343. else
  2344. {
  2345. prev = &next->next;
  2346. next = next->next;
  2347. }
  2348. }
  2349. this->InvalidateLastUsedSegment();
  2350. }
  2351. this->length = newLength;
  2352. #ifdef VALIDATE_ARRAY
  2353. ValidateArray();
  2354. #endif
  2355. }
  2356. BOOL JavascriptArray::SetLength(Var newLength)
  2357. {
  2358. ScriptContext *scriptContext;
  2359. if(TaggedInt::Is(newLength))
  2360. {
  2361. int32 lenValue = TaggedInt::ToInt32(newLength);
  2362. if (lenValue < 0)
  2363. {
  2364. scriptContext = GetScriptContext();
  2365. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2366. {
  2367. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2368. }
  2369. }
  2370. else
  2371. {
  2372. this->SetLength(lenValue);
  2373. }
  2374. return TRUE;
  2375. }
  2376. scriptContext = GetScriptContext();
  2377. uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
  2378. double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
  2379. if (dblValue == uintValue)
  2380. {
  2381. this->SetLength(uintValue);
  2382. }
  2383. else
  2384. {
  2385. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2386. ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
  2387. if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
  2388. {
  2389. // We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
  2390. // Do nothing and let the jitted code bail out.
  2391. return TRUE;
  2392. }
  2393. if (threadContext->RecordImplicitException())
  2394. {
  2395. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2396. }
  2397. }
  2398. return TRUE;
  2399. }
  2400. void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2401. {
  2402. SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2403. }
  2404. void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2405. {
  2406. SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2407. }
  2408. void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2409. {
  2410. SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2411. }
  2412. Var JavascriptArray::DirectGetItem(uint32 index)
  2413. {
  2414. SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
  2415. uint32 offset = index - seg->left;
  2416. if (index >= seg->left && offset < seg->length)
  2417. {
  2418. if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
  2419. {
  2420. return seg->elements[offset];
  2421. }
  2422. }
  2423. Var element;
  2424. if (DirectGetItemAtFull(index, &element))
  2425. {
  2426. return element;
  2427. }
  2428. return GetType()->GetLibrary()->GetUndefined();
  2429. }
  2430. Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
  2431. {
  2432. #if ENABLE_COPYONACCESS_ARRAY
  2433. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2434. #endif
  2435. SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
  2436. uint32 offset = index - seg->left;
  2437. if (index >= seg->left && offset < seg->length)
  2438. {
  2439. if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
  2440. {
  2441. return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
  2442. }
  2443. }
  2444. Var element;
  2445. if (DirectGetItemAtFull(index, &element))
  2446. {
  2447. return element;
  2448. }
  2449. return GetType()->GetLibrary()->GetUndefined();
  2450. }
  2451. Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
  2452. {
  2453. SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
  2454. uint32 offset = index - seg->left;
  2455. if (index >= seg->left && offset < seg->length)
  2456. {
  2457. if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
  2458. {
  2459. return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
  2460. }
  2461. }
  2462. Var element;
  2463. if (DirectGetItemAtFull(index, &element))
  2464. {
  2465. return element;
  2466. }
  2467. return GetType()->GetLibrary()->GetUndefined();
  2468. }
  2469. Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
  2470. {
  2471. PropertyRecord const * propertyRecord;
  2472. scriptContext->GetOrAddPropertyRecord(propName->GetString(), propName->GetLength(), &propertyRecord);
  2473. return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
  2474. }
  2475. BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  2476. {
  2477. if (this->DirectGetItemAt(index, outVal))
  2478. {
  2479. return TRUE;
  2480. }
  2481. ScriptContext* requestContext = type->GetScriptContext();
  2482. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, (Var*)outVal, requestContext);
  2483. }
  2484. //
  2485. // Link prev and current. If prev is NULL, make current the head segment.
  2486. //
  2487. void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
  2488. {
  2489. if (prev)
  2490. {
  2491. prev->next = current;
  2492. }
  2493. else
  2494. {
  2495. Assert(current);
  2496. head = current;
  2497. }
  2498. }
  2499. template<typename T>
  2500. BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
  2501. {
  2502. if (itemIndex >= length)
  2503. {
  2504. return true;
  2505. }
  2506. SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
  2507. while(next != nullptr && next->left <= itemIndex)
  2508. {
  2509. uint32 limit = next->left + next->length;
  2510. if (itemIndex < limit)
  2511. {
  2512. next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
  2513. if(itemIndex - next->left == next->length - 1)
  2514. {
  2515. --next->length;
  2516. }
  2517. else if(next == head)
  2518. {
  2519. SetHasNoMissingValues(false);
  2520. }
  2521. break;
  2522. }
  2523. next = (SparseArraySegment<T>*)next->next;
  2524. }
  2525. #ifdef VALIDATE_ARRAY
  2526. ValidateArray();
  2527. #endif
  2528. return true;
  2529. }
  2530. template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2531. {
  2532. return idxDest.ToNumber(scriptContext);
  2533. }
  2534. template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2535. {
  2536. // Note this is only for setting Array length which is a uint32
  2537. return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
  2538. }
  2539. template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
  2540. {
  2541. return JavascriptNumber::ToVar(idxDest, scriptContext);
  2542. }
  2543. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
  2544. {
  2545. return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2546. }
  2547. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
  2548. {
  2549. ScriptContext* scriptContext = pDestObj->GetScriptContext();
  2550. if (idxDest.IsSmallIndex())
  2551. {
  2552. return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2553. }
  2554. PropertyRecord const * propertyRecord;
  2555. JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
  2556. return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
  2557. }
  2558. template<typename T>
  2559. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest, BOOL FirstPromotedItemIsSpreadable, BigIndex FirstPromotedItemLength)
  2560. {
  2561. // This never gets called.
  2562. Throw::InternalError();
  2563. }
  2564. //
  2565. // Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
  2566. //
  2567. template<typename T>
  2568. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest, BOOL firstPromotedItemIsSpreadable, BigIndex firstPromotedItemLength)
  2569. {
  2570. JavascriptArray* pDestArray = nullptr;
  2571. if (JavascriptArray::Is(pDestObj))
  2572. {
  2573. pDestArray = JavascriptArray::FromVar(pDestObj);
  2574. }
  2575. T idxDest = startIdxDest;
  2576. for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
  2577. {
  2578. Var aItem = args[idxArg];
  2579. BOOL spreadable = false;
  2580. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
  2581. {
  2582. // firstPromotedItemIsSpreadable is ONLY used to resume after a type promotion from uint32 to uint64
  2583. // we do this because calls to IsConcatSpreadable are observable (a big deal for proxies) and we don't
  2584. // want to do the work a second time as soon as we record the length we clear the flag.
  2585. spreadable = firstPromotedItemIsSpreadable || JavascriptOperators::IsConcatSpreadable(aItem);
  2586. if (!spreadable)
  2587. {
  2588. JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext);
  2589. ++idxDest;
  2590. continue;
  2591. }
  2592. }
  2593. if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)) // Fast path
  2594. {
  2595. if (JavascriptNativeIntArray::Is(aItem))
  2596. {
  2597. JavascriptNativeIntArray *pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2598. CopyNativeIntArrayElementsToVar(pDestArray, idxDest, pItemArray);
  2599. idxDest = idxDest + pItemArray->length;
  2600. }
  2601. else if (JavascriptNativeFloatArray::Is(aItem))
  2602. {
  2603. JavascriptNativeFloatArray *pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2604. CopyNativeFloatArrayElementsToVar(pDestArray, idxDest, pItemArray);
  2605. idxDest = idxDest + pItemArray->length;
  2606. }
  2607. else
  2608. {
  2609. JavascriptArray* pItemArray = JavascriptArray::FromVar(aItem);
  2610. CopyArrayElements(pDestArray, idxDest, pItemArray);
  2611. idxDest = idxDest + pItemArray->length;
  2612. }
  2613. }
  2614. else
  2615. {
  2616. // Flatten if other array or remote array (marked with TypeIds_Array)
  2617. if (DynamicObject::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array || spreadable)
  2618. {
  2619. //CONSIDER: enumerating remote array instead of walking all indices
  2620. BigIndex length;
  2621. if (firstPromotedItemIsSpreadable)
  2622. {
  2623. firstPromotedItemIsSpreadable = false;
  2624. length = firstPromotedItemLength;
  2625. }
  2626. else if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  2627. {
  2628. // we can cast to uin64 without fear of converting negative numbers to large positive ones
  2629. // from int64 because ToLength makes negative lengths 0
  2630. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
  2631. }
  2632. else
  2633. {
  2634. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
  2635. }
  2636. if (PromoteToBigIndex(length,idxDest))
  2637. {
  2638. // This is a special case for spreadable objects. We do not pre-calculate the length
  2639. // in EntryConcat like we do with Arrays because a getProperty on an object Length
  2640. // is observable. The result is we have to check for overflows separately for
  2641. // spreadable objects and promote to a bigger index type when we find them.
  2642. ConcatArgs<BigIndex>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, /*firstPromotedItemIsSpreadable*/true, length);
  2643. return;
  2644. }
  2645. RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
  2646. Var subItem;
  2647. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  2648. for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
  2649. {
  2650. if (JavascriptOperators::HasItem(itemObject, idxSubItem))
  2651. {
  2652. JavascriptOperators::GetItem(itemObject, idxSubItem, &subItem, scriptContext);
  2653. if (pDestArray)
  2654. {
  2655. pDestArray->DirectSetItemAt(idxDest, subItem);
  2656. }
  2657. else
  2658. {
  2659. SetArrayLikeObjects(pDestObj, idxDest, subItem);
  2660. }
  2661. }
  2662. ++idxDest;
  2663. }
  2664. for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
  2665. {
  2666. PropertyRecord const * propertyRecord;
  2667. JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
  2668. if (JavascriptOperators::HasProperty(itemObject,propertyRecord->GetPropertyId()))
  2669. {
  2670. subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext);
  2671. if (pDestArray)
  2672. {
  2673. pDestArray->DirectSetItemAt(idxDest, subItem);
  2674. }
  2675. else
  2676. {
  2677. SetArrayLikeObjects(pDestObj, idxDest, subItem);
  2678. }
  2679. }
  2680. ++idxDest;
  2681. }
  2682. }
  2683. else // concat 1 item
  2684. {
  2685. JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext);
  2686. ++idxDest;
  2687. }
  2688. }
  2689. }
  2690. if (!pDestArray)
  2691. {
  2692. pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr);
  2693. }
  2694. else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
  2695. {
  2696. pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
  2697. }
  2698. }
  2699. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
  2700. {
  2701. return false; // already a big index
  2702. }
  2703. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
  2704. {
  2705. ::Math::RecordOverflowPolicy destLengthOverflow;
  2706. if (lhs.IsSmallIndex())
  2707. {
  2708. UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
  2709. return destLengthOverflow.HasOverflowed();
  2710. }
  2711. return true;
  2712. }
  2713. void JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2714. {
  2715. uint idxDest = 0u;
  2716. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2717. {
  2718. Var aItem = args[idxArg];
  2719. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() && !JavascriptOperators::IsConcatSpreadable(aItem))
  2720. {
  2721. pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible);
  2722. idxDest = idxDest + 1;
  2723. if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2724. {
  2725. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
  2726. return;
  2727. }
  2728. continue;
  2729. }
  2730. if (JavascriptNativeIntArray::Is(aItem)) // Fast path
  2731. {
  2732. JavascriptNativeIntArray* pItemArray = JavascriptNativeIntArray::FromVar(aItem);
  2733. bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray);
  2734. idxDest = idxDest + pItemArray->length;
  2735. if (converted)
  2736. {
  2737. // Copying the last array forced a conversion, so switch over to the var version
  2738. // to finish.
  2739. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
  2740. return;
  2741. }
  2742. }
  2743. else
  2744. {
  2745. Assert(!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array);
  2746. if (TaggedInt::Is(aItem))
  2747. {
  2748. pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
  2749. }
  2750. else
  2751. {
  2752. #if DBG
  2753. int32 int32Value;
  2754. Assert(
  2755. JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
  2756. !SparseArraySegment<int32>::IsMissingItem(&int32Value));
  2757. #endif
  2758. pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
  2759. }
  2760. ++idxDest;
  2761. }
  2762. }
  2763. if (pDestArray->GetLength() != idxDest)
  2764. {
  2765. pDestArray->SetLength(idxDest);
  2766. }
  2767. }
  2768. void JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  2769. {
  2770. uint idxDest = 0u;
  2771. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2772. {
  2773. Var aItem = args[idxArg];
  2774. if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() && !JavascriptOperators::IsConcatSpreadable(aItem))
  2775. {
  2776. pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible);
  2777. idxDest = idxDest + 1;
  2778. if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  2779. {
  2780. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
  2781. return;
  2782. }
  2783. continue;
  2784. }
  2785. bool converted;
  2786. if (JavascriptArray::IsAnyArray(aItem))
  2787. {
  2788. if (JavascriptNativeIntArray::Is(aItem)) // Fast path
  2789. {
  2790. JavascriptNativeIntArray *pIntArray = JavascriptNativeIntArray::FromVar(aItem);
  2791. converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntArray);
  2792. idxDest = idxDest + pIntArray->length;
  2793. }
  2794. else
  2795. {
  2796. JavascriptNativeFloatArray* pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
  2797. converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pItemArray);
  2798. idxDest = idxDest + pItemArray->length;
  2799. }
  2800. if (converted)
  2801. {
  2802. // Copying the last array forced a conversion, so switch over to the var version
  2803. // to finish.
  2804. ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest);
  2805. return;
  2806. }
  2807. }
  2808. else
  2809. {
  2810. Assert(!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array);
  2811. if (TaggedInt::Is(aItem))
  2812. {
  2813. pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
  2814. }
  2815. else
  2816. {
  2817. Assert(JavascriptNumber::Is(aItem));
  2818. pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
  2819. }
  2820. ++idxDest;
  2821. }
  2822. }
  2823. if (pDestArray->GetLength() != idxDest)
  2824. {
  2825. pDestArray->SetLength(idxDest);
  2826. }
  2827. }
  2828. bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
  2829. {
  2830. return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
  2831. }
  2832. Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
  2833. {
  2834. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  2835. ARGUMENTS(args, callInfo);
  2836. ScriptContext* scriptContext = function->GetScriptContext();
  2837. Assert(!(callInfo.Flags & CallFlags_New));
  2838. if (args.Info.Count == 0)
  2839. {
  2840. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  2841. }
  2842. //
  2843. // Compute the destination ScriptArray size:
  2844. // - Each item, flattening only one level if a ScriptArray.
  2845. //
  2846. uint32 cDestLength = 0;
  2847. JavascriptArray * pDestArray = NULL;
  2848. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
  2849. TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
  2850. bool isInt = true;
  2851. bool isFloat = true;
  2852. ::Math::RecordOverflowPolicy destLengthOverflow;
  2853. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  2854. {
  2855. Var aItem = args[idxArg];
  2856. #if ENABLE_COPYONACCESS_ARRAY
  2857. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
  2858. #endif
  2859. if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
  2860. {
  2861. JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
  2862. if (isFloat)
  2863. {
  2864. if (!JavascriptNativeIntArray::Is(pItemArray))
  2865. {
  2866. isInt = false;
  2867. if (!JavascriptNativeFloatArray::Is(pItemArray))
  2868. {
  2869. isFloat = false;
  2870. }
  2871. }
  2872. }
  2873. cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
  2874. }
  2875. else // Get remote array or object length
  2876. {
  2877. // We already checked for types derived from JavascriptArray. These are types that should behave like array
  2878. // i.e. proxy to array and remote array.
  2879. if (JavascriptOperators::IsArray(aItem))
  2880. {
  2881. // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
  2882. // worth it.
  2883. isInt = false;
  2884. isFloat = false;
  2885. if (!JavascriptProxy::Is(aItem))
  2886. {
  2887. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  2888. {
  2889. int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
  2890. // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
  2891. cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
  2892. }
  2893. else
  2894. {
  2895. uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext);
  2896. cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
  2897. }
  2898. }
  2899. remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
  2900. }
  2901. else
  2902. {
  2903. if (isFloat)
  2904. {
  2905. if (BoxConcatItem(aItem, idxArg, scriptContext))
  2906. {
  2907. // A primitive will be boxed, so we have to create a var array for the result.
  2908. isInt = false;
  2909. isFloat = false;
  2910. }
  2911. else if (!TaggedInt::Is(aItem))
  2912. {
  2913. if (!JavascriptNumber::Is(aItem))
  2914. {
  2915. isInt = false;
  2916. isFloat = false;
  2917. }
  2918. else if (isInt)
  2919. {
  2920. int32 int32Value;
  2921. if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
  2922. SparseArraySegment<int32>::IsMissingItem(&int32Value))
  2923. {
  2924. isInt = false;
  2925. }
  2926. }
  2927. }
  2928. else if(isInt)
  2929. {
  2930. int32 int32Value = TaggedInt::ToInt32(aItem);
  2931. if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
  2932. {
  2933. isInt = false;
  2934. }
  2935. }
  2936. }
  2937. remoteTypeIds[idxArg] = TypeIds_Limit;
  2938. cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
  2939. }
  2940. }
  2941. }
  2942. if (destLengthOverflow.HasOverflowed())
  2943. {
  2944. cDestLength = MaxArrayLength;
  2945. isInt = false;
  2946. isFloat = false;
  2947. }
  2948. //
  2949. // Create the destination array
  2950. //
  2951. RecyclableObject* pDestObj = nullptr;
  2952. bool isArray = false;
  2953. pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext);
  2954. if (pDestObj)
  2955. {
  2956. isInt = JavascriptNativeIntArray::Is(pDestObj);
  2957. isFloat = !isInt && JavascriptNativeFloatArray::Is(pDestObj); // if we know it is an int short the condition to avoid a function call
  2958. isArray = isInt || isFloat || JavascriptArray::Is(pDestObj);
  2959. }
  2960. if (pDestObj == nullptr || isArray)
  2961. {
  2962. if (isInt)
  2963. {
  2964. JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
  2965. pIntArray->EnsureHead<int32>();
  2966. ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext);
  2967. pDestArray = pIntArray;
  2968. }
  2969. else if (isFloat)
  2970. {
  2971. JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
  2972. pFArray->EnsureHead<double>();
  2973. ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext);
  2974. pDestArray = pFArray;
  2975. }
  2976. else
  2977. {
  2978. pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
  2979. // if the constructor has changed then we no longer specialize for ints and floats
  2980. pDestArray->EnsureHead<Var>();
  2981. ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow);
  2982. }
  2983. //
  2984. // Return the new array instance.
  2985. //
  2986. #ifdef VALIDATE_ARRAY
  2987. pDestArray->ValidateArray();
  2988. #endif
  2989. return pDestArray;
  2990. }
  2991. Assert(pDestObj);
  2992. ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow);
  2993. return pDestObj;
  2994. }
  2995. void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
  2996. {
  2997. if (destLengthOverflow.HasOverflowed())
  2998. {
  2999. ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
  3000. }
  3001. else
  3002. {
  3003. // Use faster uint32 version if no overflow
  3004. ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
  3005. }
  3006. }
  3007. template<typename T>
  3008. /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
  3009. {
  3010. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3011. {
  3012. // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
  3013. RecyclableObject* pObj = nullptr;
  3014. if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
  3015. {
  3016. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3017. }
  3018. if (pDestArray)
  3019. {
  3020. pDestArray->DirectSetItemAt(idxDest, pObj);
  3021. }
  3022. else
  3023. {
  3024. SetArrayLikeObjects(pDestObj, idxDest, pObj);
  3025. }
  3026. }
  3027. else
  3028. {
  3029. if (pDestArray)
  3030. {
  3031. pDestArray->DirectSetItemAt(idxDest, aItem);
  3032. }
  3033. else
  3034. {
  3035. SetArrayLikeObjects(pDestObj, idxDest, aItem);
  3036. }
  3037. }
  3038. }
  3039. uint32 JavascriptArray::GetFromIndex(Var arg, uint32 length, ScriptContext *scriptContext)
  3040. {
  3041. uint32 fromIndex;
  3042. if (TaggedInt::Is(arg))
  3043. {
  3044. int intValue = TaggedInt::ToInt32(arg);
  3045. if (intValue >= 0)
  3046. {
  3047. fromIndex = intValue;
  3048. }
  3049. else
  3050. {
  3051. // (intValue + length) may exceed 2^31 or may be < 0, so promote to int64
  3052. fromIndex = (uint32)max(0i64, (int64)(length) + intValue);
  3053. }
  3054. }
  3055. else
  3056. {
  3057. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3058. if (value > length)
  3059. {
  3060. return (uint32)-1;
  3061. }
  3062. else if (value >= 0)
  3063. {
  3064. fromIndex = (uint32)value;
  3065. }
  3066. else
  3067. {
  3068. fromIndex = (uint32)max((double)0, value + length);
  3069. }
  3070. }
  3071. return fromIndex;
  3072. }
  3073. uint64 JavascriptArray::GetFromIndex(Var arg, uint64 length, ScriptContext *scriptContext)
  3074. {
  3075. uint64 fromIndex;
  3076. if (TaggedInt::Is(arg))
  3077. {
  3078. int64 intValue = TaggedInt::ToInt64(arg);
  3079. if (intValue >= 0)
  3080. {
  3081. fromIndex = intValue;
  3082. }
  3083. else
  3084. {
  3085. fromIndex = max((int64)0, (int64)(intValue + length));
  3086. }
  3087. }
  3088. else
  3089. {
  3090. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3091. if (value > length)
  3092. {
  3093. return (uint64)-1;
  3094. }
  3095. else if (value >= 0)
  3096. {
  3097. fromIndex = (uint64)value;
  3098. }
  3099. else
  3100. {
  3101. fromIndex = (uint64)max((double)0, value + length);
  3102. }
  3103. }
  3104. return fromIndex;
  3105. }
  3106. int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
  3107. {
  3108. int64 fromIndex;
  3109. if (TaggedInt::Is(arg))
  3110. {
  3111. int intValue = TaggedInt::ToInt32(arg);
  3112. if (intValue >= 0)
  3113. {
  3114. fromIndex = min<int64>(intValue, length - 1);
  3115. }
  3116. else if ((uint32)-intValue > length)
  3117. {
  3118. return length;
  3119. }
  3120. else
  3121. {
  3122. fromIndex = intValue + length;
  3123. }
  3124. }
  3125. else
  3126. {
  3127. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3128. if (value >= 0)
  3129. {
  3130. fromIndex = (int64)min(value, (double)(length - 1));
  3131. }
  3132. else if (value + length < 0)
  3133. {
  3134. return length;
  3135. }
  3136. else
  3137. {
  3138. fromIndex = (int64)(value + length);
  3139. }
  3140. }
  3141. return fromIndex;
  3142. }
  3143. // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
  3144. // Differences
  3145. // 1. Returns boolean true or false value instead of the search hit index
  3146. // 2. Follows SameValueZero algorithm instead of StrictEquals
  3147. // 3. Missing values are scanned if the search value is undefined
  3148. template <bool includesAlgorithm>
  3149. Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
  3150. {
  3151. RecyclableObject* obj = nullptr;
  3152. JavascriptArray* pArr = nullptr;
  3153. BigIndex length;
  3154. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3155. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3156. if (JavascriptArray::Is(args[0]))
  3157. {
  3158. #if ENABLE_COPYONACCESS_ARRAY
  3159. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  3160. #endif
  3161. pArr = JavascriptArray::FromVar(args[0]);
  3162. obj = pArr;
  3163. }
  3164. else
  3165. {
  3166. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  3167. {
  3168. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.indexOf"));
  3169. }
  3170. }
  3171. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  3172. // Even for arrays, this is now observable via proxies.
  3173. // If source object is not an array, we fall back to this behavior anyway.
  3174. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  3175. {
  3176. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  3177. {
  3178. length = (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  3179. }
  3180. else
  3181. {
  3182. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  3183. }
  3184. }
  3185. else
  3186. {
  3187. length = pArr->length;
  3188. }
  3189. if (pArr)
  3190. {
  3191. Var search;
  3192. uint32 fromIndex;
  3193. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3194. if (!GetParamForIndexOf(len, args, search, fromIndex, scriptContext))
  3195. {
  3196. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3197. }
  3198. int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext);
  3199. // If we found the search value in the head segment, or if we determined there is no need to search other segments,
  3200. // we stop right here.
  3201. if (index != -1 || fromIndex == -1)
  3202. {
  3203. if (includesAlgorithm)
  3204. {
  3205. //Array.prototype.includes
  3206. return (index == -1)? falseValue : trueValue;
  3207. }
  3208. else
  3209. {
  3210. //Array.prototype.indexOf
  3211. return JavascriptNumber::ToVar(index, scriptContext);
  3212. }
  3213. }
  3214. // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
  3215. switch (pArr->GetTypeId())
  3216. {
  3217. case Js::TypeIds_Array:
  3218. return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext);
  3219. case Js::TypeIds_NativeIntArray:
  3220. return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, len, scriptContext);
  3221. case Js::TypeIds_NativeFloatArray:
  3222. return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, len, scriptContext);
  3223. default:
  3224. AssertMsg(FALSE, "invalid array typeid");
  3225. return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext);
  3226. }
  3227. }
  3228. // source object is not a JavascriptArray but source could be a TypedArray
  3229. if (TypedArrayBase::Is(obj))
  3230. {
  3231. if (length.IsSmallIndex() || length.IsUint32Max())
  3232. {
  3233. Var search;
  3234. uint32 fromIndex;
  3235. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3236. if (!GetParamForIndexOf(len, args, search, fromIndex, scriptContext))
  3237. {
  3238. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3239. }
  3240. return TemplatedIndexOfHelper<includesAlgorithm>(TypedArrayBase::FromVar(obj), search, fromIndex, length.GetSmallIndex(), scriptContext);
  3241. }
  3242. }
  3243. if (length.IsSmallIndex())
  3244. {
  3245. Var search;
  3246. uint32 fromIndex;
  3247. if (!GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext))
  3248. {
  3249. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3250. }
  3251. return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext);
  3252. }
  3253. else
  3254. {
  3255. Var search;
  3256. uint64 fromIndex;
  3257. if (!GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex, scriptContext))
  3258. {
  3259. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3260. }
  3261. return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetBigIndex(), scriptContext);
  3262. }
  3263. }
  3264. // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
  3265. Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3266. {
  3267. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3268. ARGUMENTS(args, callInfo);
  3269. ScriptContext* scriptContext = function->GetScriptContext();
  3270. Assert(!(callInfo.Flags & CallFlags_New));
  3271. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayIndexOfCount);
  3272. Var returnValue = IndexOfHelper<false>(args, scriptContext);
  3273. //IndexOfHelper code is reused for array.prototype.includes as well. Let us assert here we didn't get a true or false instead of index
  3274. Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
  3275. return returnValue;
  3276. }
  3277. Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
  3278. {
  3279. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3280. ARGUMENTS(args, callInfo);
  3281. ScriptContext* scriptContext = function->GetScriptContext();
  3282. Assert(!(callInfo.Flags & CallFlags_New));
  3283. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayIncludesCount);
  3284. Var returnValue = IndexOfHelper<true>(args, scriptContext);
  3285. Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
  3286. return returnValue;
  3287. }
  3288. template<typename T>
  3289. BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
  3290. {
  3291. if (length == 0)
  3292. {
  3293. return false;
  3294. }
  3295. if (args.Info.Count > 2)
  3296. {
  3297. fromIndex = GetFromIndex(args[2], length, scriptContext);
  3298. if (fromIndex >= length)
  3299. {
  3300. return false;
  3301. }
  3302. search = args[1];
  3303. }
  3304. else
  3305. {
  3306. fromIndex = 0;
  3307. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3308. }
  3309. return true;
  3310. }
  3311. template <>
  3312. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext)
  3313. {
  3314. // Note: Sometime cross site array go down this path to get the marshalling
  3315. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3316. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3317. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3318. if (!JavascriptOperators::HasItem(obj, index))
  3319. {
  3320. return FALSE;
  3321. }
  3322. return JavascriptOperators::GetItem(obj, index, element, scriptContext);
  3323. }
  3324. template <>
  3325. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext)
  3326. {
  3327. // Note: Sometime cross site array go down this path to get the marshalling
  3328. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3329. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3330. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3331. PropertyRecord const * propertyRecord;
  3332. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  3333. if (!JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
  3334. {
  3335. return FALSE;
  3336. }
  3337. *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
  3338. return *element != scriptContext->GetLibrary()->GetUndefined();
  3339. }
  3340. template <>
  3341. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext)
  3342. {
  3343. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
  3344. || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
  3345. return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
  3346. }
  3347. template <>
  3348. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext)
  3349. {
  3350. // This should never get called.
  3351. Assert(false);
  3352. Throw::InternalError();
  3353. }
  3354. template <>
  3355. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext)
  3356. {
  3357. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
  3358. || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
  3359. return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
  3360. }
  3361. template <>
  3362. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext)
  3363. {
  3364. // This should never get called.
  3365. Assert(false);
  3366. Throw::InternalError();
  3367. }
  3368. template <>
  3369. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext)
  3370. {
  3371. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
  3372. || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
  3373. return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
  3374. }
  3375. template <>
  3376. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext)
  3377. {
  3378. // This should never get called.
  3379. Assert(false);
  3380. Throw::InternalError();
  3381. }
  3382. template <>
  3383. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext)
  3384. {
  3385. // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
  3386. // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
  3387. // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
  3388. // we don't know whether or not length == typedArrayBase->GetLength().
  3389. if (!typedArrayBase->HasItem(index))
  3390. {
  3391. return false;
  3392. }
  3393. *element = typedArrayBase->DirectGetItem(index);
  3394. return true;
  3395. }
  3396. template <>
  3397. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext)
  3398. {
  3399. // This should never get called.
  3400. Assert(false);
  3401. Throw::InternalError();
  3402. }
  3403. template <bool includesAlgorithm, typename T, typename P>
  3404. Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
  3405. {
  3406. Var element = nullptr;
  3407. bool isSearchTaggedInt = TaggedInt::Is(search);
  3408. bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
  3409. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3410. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3411. //Consider: enumerating instead of walking all indices
  3412. for (P i = fromIndex; i < toIndex; i++)
  3413. {
  3414. if (!TemplatedGetItem(pArr, i, &element, scriptContext))
  3415. {
  3416. if (doUndefinedSearch)
  3417. {
  3418. return trueValue;
  3419. }
  3420. continue;
  3421. }
  3422. if (isSearchTaggedInt && TaggedInt::Is(element))
  3423. {
  3424. if (element == search)
  3425. {
  3426. return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
  3427. }
  3428. continue;
  3429. }
  3430. if (includesAlgorithm)
  3431. {
  3432. //Array.prototype.includes
  3433. if (JavascriptConversion::SameValueZero(element, search))
  3434. {
  3435. return trueValue;
  3436. }
  3437. }
  3438. else
  3439. {
  3440. //Array.prototype.indexOf
  3441. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3442. {
  3443. return JavascriptNumber::ToVar(i, scriptContext);
  3444. }
  3445. }
  3446. }
  3447. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3448. }
  3449. int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3450. {
  3451. Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
  3452. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3453. {
  3454. return -1;
  3455. }
  3456. bool isSearchTaggedInt = TaggedInt::Is(search);
  3457. // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3458. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
  3459. // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
  3460. SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
  3461. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3462. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3463. {
  3464. Var element = head->GetElement(i);
  3465. if (isSearchTaggedInt && TaggedInt::Is(element))
  3466. {
  3467. if (search == element)
  3468. {
  3469. return i;
  3470. }
  3471. }
  3472. else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
  3473. {
  3474. //Array.prototype.includes
  3475. return i;
  3476. }
  3477. else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3478. {
  3479. //Array.prototype.indexOf
  3480. return i;
  3481. }
  3482. }
  3483. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3484. // the head segment.
  3485. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3486. return -1;
  3487. }
  3488. int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3489. {
  3490. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3491. // except when we can further optimize thanks to the knowledge that all elements in the array are int32's. This allows for two additional optimizations:
  3492. // 1. Only tagged ints or JavascriptNumbers that can be represented as int32 can be strict equal to some element in the array (all int32). Thus, if
  3493. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3494. // 2. If the search value is a number that can be represented as int32, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
  3495. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3496. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3497. {
  3498. return -1;
  3499. }
  3500. bool isSearchTaggedInt = TaggedInt::Is(search);
  3501. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3502. {
  3503. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3504. // the head segment has no gaps.
  3505. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3506. return -1;
  3507. }
  3508. int32 searchAsInt32;
  3509. if (isSearchTaggedInt)
  3510. {
  3511. searchAsInt32 = TaggedInt::ToInt32(search);
  3512. }
  3513. else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
  3514. {
  3515. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3516. // the head segment has no gaps.
  3517. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3518. return -1;
  3519. }
  3520. // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3521. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
  3522. // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
  3523. SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
  3524. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3525. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3526. {
  3527. int32 element = head->GetElement(i);
  3528. if (searchAsInt32 == element)
  3529. {
  3530. return i;
  3531. }
  3532. }
  3533. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3534. // the head segment.
  3535. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3536. return -1;
  3537. }
  3538. int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3539. {
  3540. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3541. // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
  3542. // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
  3543. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3544. // 2. If the search value is a number, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
  3545. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3546. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3547. {
  3548. return -1;
  3549. }
  3550. bool isSearchTaggedInt = TaggedInt::Is(search);
  3551. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3552. {
  3553. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3554. // the head segment has no gaps.
  3555. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3556. return -1;
  3557. }
  3558. double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
  3559. // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
  3560. // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
  3561. // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
  3562. SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
  3563. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3564. bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
  3565. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3566. {
  3567. double element = head->GetElement(i);
  3568. if (element == searchAsDouble)
  3569. {
  3570. return i;
  3571. }
  3572. //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
  3573. if (matchNaN && JavascriptNumber::IsNan(element))
  3574. {
  3575. return i;
  3576. }
  3577. }
  3578. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3579. return -1;
  3580. }
  3581. Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
  3582. {
  3583. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3584. ARGUMENTS(args, callInfo);
  3585. ScriptContext* scriptContext = function->GetScriptContext();
  3586. Assert(!(callInfo.Flags & CallFlags_New));
  3587. if (args.Info.Count == 0)
  3588. {
  3589. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
  3590. }
  3591. JavascriptString* separator;
  3592. if (args.Info.Count >= 2)
  3593. {
  3594. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  3595. //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
  3596. if (TypeIds_Undefined != typeId)
  3597. {
  3598. separator = JavascriptConversion::ToString(args[1], scriptContext);
  3599. }
  3600. else
  3601. {
  3602. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3603. }
  3604. }
  3605. else
  3606. {
  3607. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3608. }
  3609. return JoinHelper(args[0], separator, scriptContext);
  3610. }
  3611. JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
  3612. {
  3613. TypeId typeId = JavascriptOperators::GetTypeId(value);
  3614. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  3615. {
  3616. return scriptContext->GetLibrary()->GetEmptyString();
  3617. }
  3618. else
  3619. {
  3620. return JavascriptConversion::ToString(value, scriptContext);
  3621. }
  3622. }
  3623. JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
  3624. {
  3625. bool isArray = JavascriptArray::Is(thisArg) && (scriptContext == JavascriptArray::FromVar(thisArg)->GetScriptContext());
  3626. bool isProxy = JavascriptProxy::Is(thisArg) && (scriptContext == JavascriptProxy::FromVar(thisArg)->GetScriptContext());
  3627. Var target = NULL;
  3628. bool isTargetObjectPushed = false;
  3629. // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
  3630. // call the join helper for the target of this proxy, we will return above.
  3631. if (isProxy)
  3632. {
  3633. JavascriptProxy* proxy = JavascriptProxy::FromVar(thisArg);
  3634. Assert(proxy);
  3635. target = proxy->GetTarget();
  3636. if (target != nullptr)
  3637. {
  3638. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3639. if (scriptContext->CheckObject(target))
  3640. {
  3641. return scriptContext->GetLibrary()->GetEmptyString();
  3642. }
  3643. else
  3644. {
  3645. scriptContext->PushObject(target);
  3646. isTargetObjectPushed = true;
  3647. }
  3648. }
  3649. }
  3650. // If we end up joining same array, instead of going in infinite loop, return the empty string
  3651. else if (scriptContext->CheckObject(thisArg))
  3652. {
  3653. return scriptContext->GetLibrary()->GetEmptyString();
  3654. }
  3655. if (!isTargetObjectPushed)
  3656. {
  3657. scriptContext->PushObject(thisArg);
  3658. }
  3659. JavascriptString* res = nullptr;
  3660. TryFinally([&]()
  3661. {
  3662. if (isArray)
  3663. {
  3664. #if ENABLE_COPYONACCESS_ARRAY
  3665. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
  3666. #endif
  3667. JavascriptArray * arr = JavascriptArray::FromVar(thisArg);
  3668. switch (arr->GetTypeId())
  3669. {
  3670. case Js::TypeIds_Array:
  3671. res = JoinArrayHelper(arr, separator, scriptContext);
  3672. break;
  3673. case Js::TypeIds_NativeIntArray:
  3674. res = JoinArrayHelper(JavascriptNativeIntArray::FromVar(arr), separator, scriptContext);
  3675. break;
  3676. case Js::TypeIds_NativeFloatArray:
  3677. res = JoinArrayHelper(JavascriptNativeFloatArray::FromVar(arr), separator, scriptContext);
  3678. break;
  3679. }
  3680. }
  3681. else if (RecyclableObject::Is(thisArg))
  3682. {
  3683. res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext);
  3684. }
  3685. else
  3686. {
  3687. res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext);
  3688. }
  3689. },
  3690. [&](bool/*hasException*/)
  3691. {
  3692. Var top = scriptContext->PopObject();
  3693. if (JavascriptProxy::Is(thisArg))
  3694. {
  3695. AssertMsg(top == target, "Unmatched operation stack");
  3696. }
  3697. else
  3698. {
  3699. AssertMsg(top == thisArg, "Unmatched operation stack");
  3700. }
  3701. });
  3702. if (res == nullptr)
  3703. {
  3704. res = scriptContext->GetLibrary()->GetEmptyString();
  3705. }
  3706. return res;
  3707. }
  3708. static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
  3709. template <typename T>
  3710. JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
  3711. {
  3712. Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
  3713. const uint32 arrLength = arr->length;
  3714. switch(arrLength)
  3715. {
  3716. default:
  3717. {
  3718. CaseDefault:
  3719. bool hasSeparator = (separator->GetLength() != 0);
  3720. const charcount_t estimatedAppendCount =
  3721. min(
  3722. Join_MaxEstimatedAppendCount,
  3723. static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
  3724. CompoundString *const cs =
  3725. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  3726. Var item;
  3727. if (TemplatedGetItem(arr, 0u, &item, scriptContext))
  3728. {
  3729. cs->Append(JavascriptArray::JoinToString(item, scriptContext));
  3730. }
  3731. for (uint32 i = 1; i < arrLength; i++)
  3732. {
  3733. if (hasSeparator)
  3734. {
  3735. cs->Append(separator);
  3736. }
  3737. if (TemplatedGetItem(arr, i, &item, scriptContext))
  3738. {
  3739. cs->Append(JavascriptArray::JoinToString(item, scriptContext));
  3740. }
  3741. }
  3742. return cs;
  3743. }
  3744. case 2:
  3745. {
  3746. bool hasSeparator = (separator->GetLength() != 0);
  3747. if(hasSeparator)
  3748. {
  3749. goto CaseDefault;
  3750. }
  3751. JavascriptString *res = nullptr;
  3752. Var item;
  3753. if (TemplatedGetItem(arr, 0u, &item, scriptContext))
  3754. {
  3755. res = JavascriptArray::JoinToString(item, scriptContext);
  3756. }
  3757. if (TemplatedGetItem(arr, 1u, &item, scriptContext))
  3758. {
  3759. JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext);
  3760. return res ? ConcatString::New(res, itemString) : itemString;
  3761. }
  3762. if(res)
  3763. {
  3764. return res;
  3765. }
  3766. goto Case0;
  3767. }
  3768. case 1:
  3769. {
  3770. Var item;
  3771. if (TemplatedGetItem(arr, 0u, &item, scriptContext))
  3772. {
  3773. return JavascriptArray::JoinToString(item, scriptContext);
  3774. }
  3775. // fall through
  3776. }
  3777. case 0:
  3778. Case0:
  3779. return scriptContext->GetLibrary()->GetEmptyString();
  3780. }
  3781. }
  3782. JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
  3783. {
  3784. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  3785. // Even for arrays, this is now observable via proxies.
  3786. // If source object is not an array, we fall back to this behavior anyway.
  3787. Var lenValue = JavascriptOperators::OP_GetLength(object, scriptContext);
  3788. int64 cSrcLength = JavascriptConversion::ToLength(lenValue, scriptContext);
  3789. switch (cSrcLength)
  3790. {
  3791. default:
  3792. {
  3793. CaseDefault:
  3794. bool hasSeparator = (separator->GetLength() != 0);
  3795. const charcount_t estimatedAppendCount =
  3796. min(
  3797. Join_MaxEstimatedAppendCount,
  3798. static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
  3799. CompoundString *const cs =
  3800. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  3801. Var value;
  3802. if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
  3803. {
  3804. cs->Append(JavascriptArray::JoinToString(value, scriptContext));
  3805. }
  3806. for (uint32 i = 1; i < cSrcLength; i++)
  3807. {
  3808. if (hasSeparator)
  3809. {
  3810. cs->Append(separator);
  3811. }
  3812. Var value;
  3813. if (JavascriptOperators::GetItem(object, i, &value, scriptContext))
  3814. {
  3815. cs->Append(JavascriptArray::JoinToString(value, scriptContext));
  3816. }
  3817. }
  3818. return cs;
  3819. }
  3820. case 2:
  3821. {
  3822. bool hasSeparator = (separator->GetLength() != 0);
  3823. if(hasSeparator)
  3824. {
  3825. goto CaseDefault;
  3826. }
  3827. JavascriptString *res = nullptr;
  3828. Var value;
  3829. if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
  3830. {
  3831. res = JavascriptArray::JoinToString(value, scriptContext);
  3832. }
  3833. if (JavascriptOperators::GetItem(object, 1u, &value, scriptContext))
  3834. {
  3835. JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext);
  3836. return res ? ConcatString::New(res, valueString) : valueString;
  3837. }
  3838. if(res)
  3839. {
  3840. return res;
  3841. }
  3842. goto Case0;
  3843. }
  3844. case 1:
  3845. {
  3846. Var value;
  3847. if (JavascriptOperators::GetItem(object, 0u, &value, scriptContext))
  3848. {
  3849. return JavascriptArray::JoinToString(value, scriptContext);
  3850. }
  3851. // fall through
  3852. }
  3853. case 0:
  3854. Case0:
  3855. return scriptContext->GetLibrary()->GetEmptyString();
  3856. }
  3857. }
  3858. Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3859. {
  3860. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3861. ARGUMENTS(args, callInfo);
  3862. ScriptContext* scriptContext = function->GetScriptContext();
  3863. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayLastIndexOfCount);
  3864. Assert(!(callInfo.Flags & CallFlags_New));
  3865. int64 length;
  3866. JavascriptArray * pArr = nullptr;
  3867. RecyclableObject* obj = nullptr;
  3868. if (JavascriptArray::Is(args[0]))
  3869. {
  3870. #if ENABLE_COPYONACCESS_ARRAY
  3871. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  3872. #endif
  3873. pArr = JavascriptArray::FromVar(args[0]);
  3874. obj = pArr;
  3875. length = pArr->length;
  3876. }
  3877. else
  3878. {
  3879. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  3880. {
  3881. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.lastIndexOf"));
  3882. }
  3883. Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
  3884. length = JavascriptConversion::ToLength(lenValue, scriptContext);
  3885. }
  3886. Var search;
  3887. int64 fromIndex;
  3888. if (!GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext))
  3889. {
  3890. return TaggedInt::ToVarUnchecked(-1);
  3891. }
  3892. if (pArr)
  3893. {
  3894. switch (pArr->GetTypeId())
  3895. {
  3896. case Js::TypeIds_Array:
  3897. return LastIndexOfHelper(pArr, search, fromIndex, scriptContext);
  3898. case Js::TypeIds_NativeIntArray:
  3899. return LastIndexOfHelper(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, scriptContext);
  3900. case Js::TypeIds_NativeFloatArray:
  3901. return LastIndexOfHelper(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, scriptContext);
  3902. default:
  3903. AssertMsg(FALSE, "invalid array typeid");
  3904. return LastIndexOfHelper(pArr, search, fromIndex, scriptContext);
  3905. }
  3906. }
  3907. // source object is not a JavascriptArray but source could be a TypedArray
  3908. if (TypedArrayBase::Is(obj))
  3909. {
  3910. return LastIndexOfHelper(TypedArrayBase::FromVar(obj), search, fromIndex, scriptContext);
  3911. }
  3912. return LastIndexOfHelper(obj, search, fromIndex, scriptContext);
  3913. }
  3914. // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
  3915. BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
  3916. {
  3917. if (length == 0)
  3918. {
  3919. return false;
  3920. }
  3921. if (args.Info.Count > 2)
  3922. {
  3923. fromIndex = GetFromLastIndex(args[2], length, scriptContext);
  3924. if (fromIndex >= length)
  3925. {
  3926. return false;
  3927. }
  3928. search = args[1];
  3929. }
  3930. else
  3931. {
  3932. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3933. fromIndex = length - 1;
  3934. }
  3935. return true;
  3936. }
  3937. template <typename T>
  3938. Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
  3939. {
  3940. Var element = nullptr;
  3941. bool isSearchTaggedInt = TaggedInt::Is(search);
  3942. // First handle the indices > 2^32
  3943. while (fromIndex >= MaxArrayLength)
  3944. {
  3945. Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
  3946. if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
  3947. {
  3948. element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
  3949. if (isSearchTaggedInt && TaggedInt::Is(element))
  3950. {
  3951. if (element == search)
  3952. {
  3953. return index;
  3954. }
  3955. fromIndex--;
  3956. continue;
  3957. }
  3958. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3959. {
  3960. return index;
  3961. }
  3962. }
  3963. fromIndex--;
  3964. }
  3965. Assert(fromIndex < MaxArrayLength);
  3966. // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
  3967. uint32 end = static_cast<uint32>(fromIndex);
  3968. for (uint32 i = 0; i <= end; i++)
  3969. {
  3970. uint32 index = end - i;
  3971. if (!TemplatedGetItem(pArr, index, &element, scriptContext))
  3972. {
  3973. continue;
  3974. }
  3975. if (isSearchTaggedInt && TaggedInt::Is(element))
  3976. {
  3977. if (element == search)
  3978. {
  3979. return JavascriptNumber::ToVar(index, scriptContext);
  3980. }
  3981. continue;
  3982. }
  3983. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3984. {
  3985. return JavascriptNumber::ToVar(index, scriptContext);
  3986. }
  3987. }
  3988. return TaggedInt::ToVarUnchecked(-1);
  3989. }
  3990. /*
  3991. * PopWithNoDst
  3992. * - For pop calls that do not return a value, we only need to decrement the length of the array.
  3993. */
  3994. void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
  3995. {
  3996. Assert(JavascriptNativeArray::Is(nativeArray));
  3997. JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
  3998. // we will bailout on length 0
  3999. Assert(arr->GetLength() != 0);
  4000. uint32 index = arr->GetLength() - 1;
  4001. arr->SetLength(index);
  4002. }
  4003. /*
  4004. * JavascriptNativeIntArray::Pop
  4005. * - Returns int32 value from the array.
  4006. * - Returns missing item when the element is not available in the array object.
  4007. * - It doesn't walk up the prototype chain.
  4008. * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
  4009. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4010. */
  4011. int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
  4012. {
  4013. Assert(JavascriptNativeIntArray::Is(object));
  4014. JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
  4015. Assert(arr->GetLength() != 0);
  4016. uint32 index = arr->length - 1;
  4017. int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
  4018. //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
  4019. if(!SparseArraySegment<int32>::IsMissingItem(&element))
  4020. {
  4021. arr->SetLength(index);
  4022. }
  4023. return element;
  4024. }
  4025. /*
  4026. * JavascriptNativeFloatArray::Pop
  4027. * - Returns double value from the array.
  4028. * - Returns missing item when the element is not available in the array object.
  4029. * - It doesn't walk up the prototype chain.
  4030. * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
  4031. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4032. */
  4033. double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
  4034. {
  4035. Assert(JavascriptNativeFloatArray::Is(object));
  4036. JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
  4037. Assert(arr->GetLength() != 0);
  4038. uint32 index = arr->length - 1;
  4039. double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
  4040. // If it is a missing item then don't update the length - Pre-op Bail out will happen.
  4041. if(!SparseArraySegment<double>::IsMissingItem(&element))
  4042. {
  4043. arr->SetLength(index);
  4044. }
  4045. return element;
  4046. }
  4047. /*
  4048. * JavascriptArray::Pop
  4049. * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
  4050. * - This API may cause implicit calls. Handles Array and non-array objects
  4051. */
  4052. Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
  4053. {
  4054. if (JavascriptArray::Is(object))
  4055. {
  4056. return EntryPopJavascriptArray(scriptContext, object);
  4057. }
  4058. else
  4059. {
  4060. return EntryPopNonJavascriptArray(scriptContext, object);
  4061. }
  4062. }
  4063. Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, Var object)
  4064. {
  4065. JavascriptArray * arr = JavascriptArray::FromVar(object);
  4066. uint32 length = arr->length;
  4067. if (length == 0)
  4068. {
  4069. // If length is 0, return 'undefined'
  4070. return scriptContext->GetLibrary()->GetUndefined();
  4071. }
  4072. uint32 index = length - 1;
  4073. Var element;
  4074. if (!arr->DirectGetItemAtFull(index, &element))
  4075. {
  4076. element = scriptContext->GetLibrary()->GetUndefined();
  4077. }
  4078. else
  4079. {
  4080. element = CrossSite::MarshalVar(scriptContext, element);
  4081. }
  4082. arr->SetLength(index); // SetLength will clear element at index
  4083. #ifdef VALIDATE_ARRAY
  4084. arr->ValidateArray();
  4085. #endif
  4086. return element;
  4087. }
  4088. Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
  4089. {
  4090. RecyclableObject* dynamicObject = nullptr;
  4091. if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
  4092. {
  4093. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4094. }
  4095. BigIndex length;
  4096. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4097. {
  4098. length = (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  4099. }
  4100. else
  4101. {
  4102. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  4103. }
  4104. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
  4105. if (length == 0u)
  4106. {
  4107. // Set length = 0
  4108. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4109. return scriptContext->GetLibrary()->GetUndefined();
  4110. }
  4111. BigIndex index = length;
  4112. --index;
  4113. Var element;
  4114. if (index.IsSmallIndex())
  4115. {
  4116. if (!JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext))
  4117. {
  4118. element = scriptContext->GetLibrary()->GetUndefined();
  4119. }
  4120. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowIfNotExtensible));
  4121. // Set the new length
  4122. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4123. }
  4124. else
  4125. {
  4126. if (!JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext))
  4127. {
  4128. element = scriptContext->GetLibrary()->GetUndefined();
  4129. }
  4130. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowIfNotExtensible));
  4131. // Set the new length
  4132. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4133. }
  4134. return element;
  4135. }
  4136. Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
  4137. {
  4138. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4139. ARGUMENTS(args, callInfo);
  4140. ScriptContext* scriptContext = function->GetScriptContext();
  4141. Assert(!(callInfo.Flags & CallFlags_New));
  4142. if (args.Info.Count == 0)
  4143. {
  4144. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4145. }
  4146. if (JavascriptArray::Is(args[0]))
  4147. {
  4148. return EntryPopJavascriptArray(scriptContext, args.Values[0]);
  4149. }
  4150. else
  4151. {
  4152. return EntryPopNonJavascriptArray(scriptContext, args.Values[0]);
  4153. }
  4154. }
  4155. /*
  4156. * JavascriptNativeIntArray::Push
  4157. * Pushes Int element in a native Int Array.
  4158. * We call the generic Push, if the array is not native Int or we have a really big array.
  4159. */
  4160. Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
  4161. {
  4162. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4163. // JavascriptArray::Push will handle other cases.
  4164. if (JavascriptNativeIntArray::IsNonCrossSite(array))
  4165. {
  4166. JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::FromVar(array);
  4167. Assert(!nativeIntArray->IsCrossSiteObject());
  4168. uint32 n = nativeIntArray->length;
  4169. if(n < JavascriptArray::MaxArrayLength)
  4170. {
  4171. nativeIntArray->SetItem(n, value);
  4172. n++;
  4173. AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
  4174. return JavascriptNumber::ToVar(n, scriptContext);
  4175. }
  4176. }
  4177. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
  4178. }
  4179. /*
  4180. * JavascriptNativeFloatArray::Push
  4181. * Pushes Float element in a native Int Array.
  4182. * We call the generic Push, if the array is not native Float or we have a really big array.
  4183. */
  4184. Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
  4185. {
  4186. // Handle non crossSite native int arrays here length within MaxArrayLength.
  4187. // JavascriptArray::Push will handle other cases.
  4188. if(JavascriptNativeFloatArray::IsNonCrossSite(array))
  4189. {
  4190. JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::FromVar(array);
  4191. Assert(!nativeFloatArray->IsCrossSiteObject());
  4192. uint32 n = nativeFloatArray->length;
  4193. if(n < JavascriptArray::MaxArrayLength)
  4194. {
  4195. nativeFloatArray->SetItem(n, value);
  4196. n++;
  4197. AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
  4198. return JavascriptNumber::ToVar(n, scriptContext);
  4199. }
  4200. }
  4201. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
  4202. }
  4203. /*
  4204. * JavascriptArray::Push
  4205. * Pushes Var element in a Var Array.
  4206. */
  4207. Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
  4208. {
  4209. Var args[2];
  4210. args[0] = object;
  4211. args[1] = value;
  4212. if (JavascriptArray::Is(object))
  4213. {
  4214. return EntryPushJavascriptArray(scriptContext, args, 2);
  4215. }
  4216. else
  4217. {
  4218. return EntryPushNonJavascriptArray(scriptContext, args, 2);
  4219. }
  4220. }
  4221. /*
  4222. * EntryPushNonJavascriptArray
  4223. * - Handles Entry push calls, when Objects are not javascript arrays
  4224. */
  4225. Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4226. {
  4227. RecyclableObject* obj = nullptr;
  4228. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4229. {
  4230. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4231. }
  4232. Var length = JavascriptOperators::OP_GetLength(obj, scriptContext);
  4233. if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4234. scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
  4235. {
  4236. return length;
  4237. }
  4238. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4239. BigIndex n;
  4240. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4241. {
  4242. n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
  4243. }
  4244. else
  4245. {
  4246. n = JavascriptConversion::ToUInt32(length, scriptContext);
  4247. }
  4248. // First handle "small" indices.
  4249. uint index;
  4250. for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4251. {
  4252. if (h.IsThrowTypeError(JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible)))
  4253. {
  4254. if (scriptContext->GetThreadContext()->RecordImplicitException())
  4255. {
  4256. h.ThrowTypeErrorOnFailure();
  4257. }
  4258. else
  4259. {
  4260. return nullptr;
  4261. }
  4262. }
  4263. }
  4264. // Use BigIndex if we need to push indices >= MaxArrayLength
  4265. if (index < argCount)
  4266. {
  4267. BigIndex big = n;
  4268. for (; index < argCount; ++index, ++big)
  4269. {
  4270. if (h.IsThrowTypeError(big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible)))
  4271. {
  4272. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4273. {
  4274. h.ThrowTypeErrorOnFailure();
  4275. }
  4276. else
  4277. {
  4278. return nullptr;
  4279. }
  4280. }
  4281. }
  4282. // Set the new length; for objects it is all right for this to be >= MaxArrayLength
  4283. if (h.IsThrowTypeError(JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)))
  4284. {
  4285. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4286. {
  4287. h.ThrowTypeErrorOnFailure();
  4288. }
  4289. else
  4290. {
  4291. return nullptr;
  4292. }
  4293. }
  4294. return big.ToNumber(scriptContext);
  4295. }
  4296. else
  4297. {
  4298. // Set the new length
  4299. Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
  4300. if (h.IsThrowTypeError(JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible)))
  4301. {
  4302. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4303. {
  4304. h.ThrowTypeErrorOnFailure();
  4305. }
  4306. else
  4307. {
  4308. return nullptr;
  4309. }
  4310. }
  4311. return lengthAsNUmberVar;
  4312. }
  4313. }
  4314. /*
  4315. * JavascriptArray::EntryPushJavascriptArray
  4316. * Pushes Var element in a Var Array.
  4317. * Returns the length of the array.
  4318. */
  4319. Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4320. {
  4321. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4322. uint n = arr->length;
  4323. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4324. // Fast Path for one push for small indexes
  4325. if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
  4326. {
  4327. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4328. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
  4329. return JavascriptNumber::ToVar(n + 1, scriptContext);
  4330. }
  4331. // Fast Path for multiple push for small indexes
  4332. if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
  4333. {
  4334. uint index;
  4335. for (index = 1; index < argCount; ++index, ++n)
  4336. {
  4337. Assert(n != JavascriptArray::MaxArrayLength);
  4338. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4339. arr->JavascriptArray::DirectSetItemAt(n, args[index]);
  4340. }
  4341. return JavascriptNumber::ToVar(n, scriptContext);
  4342. }
  4343. return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
  4344. }
  4345. Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
  4346. {
  4347. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4348. uint n = arr->length;
  4349. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4350. // First handle "small" indices.
  4351. uint index;
  4352. for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4353. {
  4354. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4355. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
  4356. }
  4357. // Use BigIndex if we need to push indices >= MaxArrayLength
  4358. if (index < argCount)
  4359. {
  4360. // Not supporting native array with BigIndex.
  4361. arr = EnsureNonNativeArray(arr);
  4362. Assert(n == JavascriptArray::MaxArrayLength);
  4363. for (BigIndex big = n; index < argCount; ++index, ++big)
  4364. {
  4365. h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index]));
  4366. }
  4367. #ifdef VALIDATE_ARRAY
  4368. arr->ValidateArray();
  4369. #endif
  4370. // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
  4371. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  4372. }
  4373. #ifdef VALIDATE_ARRAY
  4374. arr->ValidateArray();
  4375. #endif
  4376. return JavascriptNumber::ToVar(n, scriptContext);
  4377. }
  4378. /*
  4379. * JavascriptArray::EntryPush
  4380. * Handles Push calls(Script Function)
  4381. */
  4382. Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
  4383. {
  4384. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4385. ARGUMENTS(args, callInfo);
  4386. ScriptContext* scriptContext = function->GetScriptContext();
  4387. Assert(!(callInfo.Flags & CallFlags_New));
  4388. if (args.Info.Count == 0)
  4389. {
  4390. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4391. }
  4392. if (JavascriptArray::Is(args[0]))
  4393. {
  4394. return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4395. }
  4396. else
  4397. {
  4398. return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4399. }
  4400. }
  4401. Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
  4402. {
  4403. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4404. ARGUMENTS(args, callInfo);
  4405. ScriptContext* scriptContext = function->GetScriptContext();
  4406. Assert(!(callInfo.Flags & CallFlags_New));
  4407. if (args.Info.Count == 0)
  4408. {
  4409. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4410. }
  4411. BigIndex length = 0u;
  4412. JavascriptArray* pArr = nullptr;
  4413. RecyclableObject* obj = nullptr;
  4414. if (JavascriptArray::Is(args[0]))
  4415. {
  4416. pArr = JavascriptArray::FromVar(args[0]);
  4417. #if ENABLE_COPYONACCESS_ARRAY
  4418. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  4419. #endif
  4420. obj = pArr;
  4421. }
  4422. else
  4423. {
  4424. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4425. {
  4426. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4427. }
  4428. }
  4429. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  4430. // Even for arrays, this is now observable via proxies.
  4431. // If source object is not an array, we fall back to this behavior anyway.
  4432. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  4433. {
  4434. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4435. {
  4436. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  4437. }
  4438. else
  4439. {
  4440. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  4441. }
  4442. }
  4443. else
  4444. {
  4445. length = pArr->length;
  4446. }
  4447. if (length.IsSmallIndex())
  4448. {
  4449. return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext);
  4450. }
  4451. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  4452. return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext);
  4453. }
  4454. // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
  4455. template <typename T>
  4456. Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
  4457. {
  4458. T middle = length / 2;
  4459. Var lowerValue = nullptr, upperValue = nullptr;
  4460. T lowerExists, upperExists;
  4461. const char16* methodName;
  4462. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  4463. if (isTypedArrayEntryPoint)
  4464. {
  4465. methodName = _u("[TypedArray].prototype.reverse");
  4466. }
  4467. else
  4468. {
  4469. methodName = _u("Array.prototype.reverse");
  4470. }
  4471. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  4472. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  4473. {
  4474. typedArrayBase = TypedArrayBase::FromVar(obj);
  4475. }
  4476. ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
  4477. if (pArr)
  4478. {
  4479. Recycler * recycler = scriptContext->GetRecycler();
  4480. if (length <= 1)
  4481. {
  4482. return pArr;
  4483. }
  4484. if (pArr->IsFillFromPrototypes())
  4485. {
  4486. // For odd-length arrays, the middle element is unchanged,
  4487. // so we cannot fill it from the prototypes.
  4488. if (length % 2 == 0)
  4489. {
  4490. pArr->FillFromPrototypes(0, (uint32)length);
  4491. }
  4492. else
  4493. {
  4494. middle = length / 2;
  4495. pArr->FillFromPrototypes(0, (uint32)middle);
  4496. pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length);
  4497. }
  4498. }
  4499. if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4500. {
  4501. // This function currently does not track missing values in the head segment if there are multiple segments
  4502. pArr->SetHasNoMissingValues(false);
  4503. }
  4504. SparseArraySegmentBase* seg = pArr->head;
  4505. SparseArraySegmentBase *prevSeg = nullptr;
  4506. SparseArraySegmentBase *nextSeg = nullptr;
  4507. SparseArraySegmentBase *pinPrevSeg = nullptr;
  4508. bool isIntArray = false;
  4509. bool isFloatArray = false;
  4510. if (JavascriptNativeIntArray::Is(pArr))
  4511. {
  4512. isIntArray = true;
  4513. }
  4514. else if (JavascriptNativeFloatArray::Is(pArr))
  4515. {
  4516. isFloatArray = true;
  4517. }
  4518. while (seg)
  4519. {
  4520. nextSeg = seg->next;
  4521. // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
  4522. // resulting in 2 segments sharing the same "left".
  4523. if (seg->length > 0)
  4524. {
  4525. if (isIntArray)
  4526. {
  4527. ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
  4528. }
  4529. else if (isFloatArray)
  4530. {
  4531. ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
  4532. }
  4533. else
  4534. {
  4535. ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
  4536. }
  4537. seg->left = ((uint32)length) - (seg->left + seg->length);
  4538. seg->next = prevSeg;
  4539. // Make sure size doesn't overlap with next segment.
  4540. // An easy fix is to just truncate the size...
  4541. seg->EnsureSizeInBound();
  4542. // If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
  4543. // segment. Hold onto it with pinPrevSeg until we reallocate below.
  4544. pinPrevSeg = prevSeg;
  4545. prevSeg = seg;
  4546. }
  4547. seg = nextSeg;
  4548. }
  4549. pArr->head = prevSeg;
  4550. // Just dump the segment map on reverse
  4551. pArr->ClearSegmentMap();
  4552. if (isIntArray)
  4553. {
  4554. if (pArr->head && pArr->head->next && SparseArraySegmentBase::IsLeafSegment(pArr->head, recycler))
  4555. {
  4556. pArr->ReallocNonLeafSegment((SparseArraySegment<int32>*)pArr->head, pArr->head->next);
  4557. }
  4558. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  4559. }
  4560. else if (isFloatArray)
  4561. {
  4562. if (pArr->head && pArr->head->next && SparseArraySegmentBase::IsLeafSegment(pArr->head, recycler))
  4563. {
  4564. pArr->ReallocNonLeafSegment((SparseArraySegment<double>*)pArr->head, pArr->head->next);
  4565. }
  4566. pArr->EnsureHeadStartsFromZero<double>(recycler);
  4567. }
  4568. else
  4569. {
  4570. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  4571. }
  4572. pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
  4573. #ifdef VALIDATE_ARRAY
  4574. pArr->ValidateArray();
  4575. #endif
  4576. }
  4577. else if (typedArrayBase)
  4578. {
  4579. Assert(length <= JavascriptArray::MaxArrayLength);
  4580. if (typedArrayBase->GetLength() == length)
  4581. {
  4582. // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
  4583. // and we won't have to check that the elements exist or not.
  4584. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  4585. {
  4586. uint32 upper = (uint32)length - lower - 1;
  4587. lowerValue = typedArrayBase->DirectGetItem(lower);
  4588. upperValue = typedArrayBase->DirectGetItem(upper);
  4589. // We still have to call HasItem even though we know the TypedArray has both lower and upper because
  4590. // there may be a proxy handler trapping HasProperty.
  4591. lowerExists = typedArrayBase->HasItem(lower);
  4592. upperExists = typedArrayBase->HasItem(upper);
  4593. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue, false));
  4594. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue, false));
  4595. }
  4596. }
  4597. else
  4598. {
  4599. for (uint32 lower = 0; lower < middle; lower++)
  4600. {
  4601. uint32 upper = (uint32)length - lower - 1;
  4602. lowerValue = typedArrayBase->DirectGetItem(lower);
  4603. upperValue = typedArrayBase->DirectGetItem(upper);
  4604. lowerExists = typedArrayBase->HasItem(lower);
  4605. upperExists = typedArrayBase->HasItem(upper);
  4606. if (lowerExists)
  4607. {
  4608. if (upperExists)
  4609. {
  4610. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue, false));
  4611. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue, false));
  4612. }
  4613. else
  4614. {
  4615. // This will always fail for a TypedArray if lower < length
  4616. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowIfNotExtensible));
  4617. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue, false));
  4618. }
  4619. }
  4620. else
  4621. {
  4622. if (upperExists)
  4623. {
  4624. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue, false));
  4625. // This will always fail for a TypedArray if upper < length
  4626. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowIfNotExtensible));
  4627. }
  4628. }
  4629. }
  4630. }
  4631. }
  4632. else
  4633. {
  4634. for (T lower = 0; lower < middle; lower++)
  4635. {
  4636. T upper = length - lower - 1;
  4637. lowerExists = JavascriptOperators::HasItem(obj, lower);
  4638. if (lowerExists)
  4639. {
  4640. BOOL getResult = JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext);
  4641. Assert(getResult);
  4642. }
  4643. upperExists = JavascriptOperators::HasItem(obj, upper);
  4644. if (upperExists)
  4645. {
  4646. BOOL getResult = JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext);
  4647. Assert(getResult);
  4648. }
  4649. if (lowerExists)
  4650. {
  4651. if (upperExists)
  4652. {
  4653. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4654. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4655. }
  4656. else
  4657. {
  4658. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowIfNotExtensible));
  4659. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4660. }
  4661. }
  4662. else
  4663. {
  4664. if (upperExists)
  4665. {
  4666. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4667. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowIfNotExtensible));
  4668. }
  4669. }
  4670. }
  4671. }
  4672. return obj;
  4673. }
  4674. template<typename T>
  4675. void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
  4676. {
  4677. Recycler * recycler = scriptContext->GetRecycler();
  4678. SparseArraySegment<T>* next = (SparseArraySegment<T>*)pArr->head->next;
  4679. while (next)
  4680. {
  4681. next->left--;
  4682. next = (SparseArraySegment<T>*)next->next;
  4683. }
  4684. // head and next might overlap as the next segment left is decremented
  4685. next = (SparseArraySegment<T>*)pArr->head->next;
  4686. if (next && (pArr->head->size > next->left))
  4687. {
  4688. AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
  4689. AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
  4690. SparseArraySegment<T> *head = (SparseArraySegment<T>*)pArr->head;
  4691. // Merge the two adjacent segments
  4692. if (next->length != 0)
  4693. {
  4694. uint32 offset = head->size - 1;
  4695. // There is room for one unshifted element in head segment.
  4696. // Hence it's enough if we grow the head segment by next->length - 1
  4697. if (next->next)
  4698. {
  4699. // If we have a next->next, we can't grow pass the left of that
  4700. // If the array had a segment map before, the next->next might just be right after next as well.
  4701. // So we just need to grow to the end of the next segment
  4702. // TODO: merge that segment too?
  4703. Assert(next->next->left >= head->size);
  4704. uint32 maxGrowSize = next->next->left - head->size;
  4705. if (maxGrowSize != 0)
  4706. {
  4707. head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
  4708. }
  4709. else
  4710. {
  4711. // The next segment is only of length one, so we already have space in the header to copy that
  4712. Assert(next->length == 1);
  4713. }
  4714. }
  4715. else
  4716. {
  4717. head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
  4718. }
  4719. memmove(head->elements + offset, next->elements, next->length * sizeof(T));
  4720. head->length = offset + next->length;
  4721. pArr->head = head;
  4722. }
  4723. head->next = next->next;
  4724. pArr->InvalidateLastUsedSegment();
  4725. }
  4726. #ifdef VALIDATE_ARRAY
  4727. pArr->ValidateArray();
  4728. #endif
  4729. }
  4730. Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
  4731. {
  4732. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4733. ARGUMENTS(args, callInfo);
  4734. ScriptContext* scriptContext = function->GetScriptContext();
  4735. Assert(!(callInfo.Flags & CallFlags_New));
  4736. Var res = scriptContext->GetLibrary()->GetUndefined();
  4737. if (args.Info.Count == 0)
  4738. {
  4739. return res;
  4740. }
  4741. if (JavascriptArray::Is(args[0]))
  4742. {
  4743. JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
  4744. #if ENABLE_COPYONACCESS_ARRAY
  4745. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  4746. #endif
  4747. if (pArr->length == 0)
  4748. {
  4749. return res;
  4750. }
  4751. if(pArr->IsFillFromPrototypes())
  4752. {
  4753. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  4754. }
  4755. if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4756. {
  4757. // This function currently does not track missing values in the head segment if there are multiple segments
  4758. pArr->SetHasNoMissingValues(false);
  4759. }
  4760. pArr->length--;
  4761. pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
  4762. Recycler * recycler = scriptContext->GetRecycler();
  4763. bool isIntArray = false;
  4764. bool isFloatArray = false;
  4765. if(JavascriptNativeIntArray::Is(pArr))
  4766. {
  4767. isIntArray = true;
  4768. }
  4769. else if(JavascriptNativeFloatArray::Is(pArr))
  4770. {
  4771. isFloatArray = true;
  4772. }
  4773. if (pArr->head->length != 0)
  4774. {
  4775. if(isIntArray)
  4776. {
  4777. int32 nativeResult = ((SparseArraySegment<int32>*)pArr->head)->GetElement(0);
  4778. if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
  4779. {
  4780. res = scriptContext->GetLibrary()->GetUndefined();
  4781. }
  4782. else
  4783. {
  4784. res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
  4785. }
  4786. ((SparseArraySegment<int32>*)pArr->head)->RemoveElement(recycler, 0);
  4787. }
  4788. else if (isFloatArray)
  4789. {
  4790. double nativeResult = ((SparseArraySegment<double>*)pArr->head)->GetElement(0);
  4791. if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
  4792. {
  4793. res = scriptContext->GetLibrary()->GetUndefined();
  4794. }
  4795. else
  4796. {
  4797. res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
  4798. }
  4799. ((SparseArraySegment<double>*)pArr->head)->RemoveElement(recycler, 0);
  4800. }
  4801. else
  4802. {
  4803. res = ((SparseArraySegment<Var>*)pArr->head)->GetElement(0);
  4804. if(SparseArraySegment<Var>::IsMissingItem(&res))
  4805. {
  4806. res = scriptContext->GetLibrary()->GetUndefined();
  4807. }
  4808. else
  4809. {
  4810. res = CrossSite::MarshalVar(scriptContext, res);
  4811. }
  4812. ((SparseArraySegment<Var>*)pArr->head)->RemoveElement(recycler, 0);
  4813. }
  4814. }
  4815. if(isIntArray)
  4816. {
  4817. ShiftHelper<int32>(pArr, scriptContext);
  4818. }
  4819. else if (isFloatArray)
  4820. {
  4821. ShiftHelper<double>(pArr, scriptContext);
  4822. }
  4823. else
  4824. {
  4825. ShiftHelper<Var>(pArr, scriptContext);
  4826. }
  4827. }
  4828. else
  4829. {
  4830. RecyclableObject* dynamicObject = nullptr;
  4831. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  4832. {
  4833. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
  4834. }
  4835. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
  4836. BigIndex length = 0u;
  4837. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4838. {
  4839. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  4840. }
  4841. else
  4842. {
  4843. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  4844. }
  4845. if (length == 0u)
  4846. {
  4847. // If length is 0, return 'undefined'
  4848. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4849. return scriptContext->GetLibrary()->GetUndefined();
  4850. }
  4851. if (!JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext))
  4852. {
  4853. res = scriptContext->GetLibrary()->GetUndefined();
  4854. }
  4855. --length;
  4856. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  4857. for (uint32 i = 0u; i < lengthToUin32Max; i++)
  4858. {
  4859. Var element;
  4860. if (JavascriptOperators::HasItem(dynamicObject, i + 1))
  4861. {
  4862. BOOL getResult = JavascriptOperators::GetItem(dynamicObject, i + 1, &element, scriptContext);
  4863. Assert(getResult);
  4864. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true));
  4865. }
  4866. else
  4867. {
  4868. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowIfNotExtensible));
  4869. }
  4870. }
  4871. for (uint64 i = MaxArrayLength; length > i; i++)
  4872. {
  4873. Var element;
  4874. if (JavascriptOperators::HasItem(dynamicObject, i + 1))
  4875. {
  4876. BOOL getResult = JavascriptOperators::GetItem(dynamicObject, i + 1, &element, scriptContext);
  4877. Assert(getResult);
  4878. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4879. }
  4880. else
  4881. {
  4882. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowIfNotExtensible));
  4883. }
  4884. }
  4885. if (length.IsSmallIndex())
  4886. {
  4887. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowIfNotExtensible));
  4888. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4889. }
  4890. else
  4891. {
  4892. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowIfNotExtensible));
  4893. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4894. }
  4895. }
  4896. return res;
  4897. }
  4898. Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
  4899. {
  4900. if (isIntArray)
  4901. {
  4902. Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
  4903. pnewArr->EnsureHead<int32>();
  4904. #if ENABLE_PROFILE_INFO
  4905. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::FromVar(baseArray));
  4906. #endif
  4907. return pnewArr;
  4908. }
  4909. else if (isFloatArray)
  4910. {
  4911. Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
  4912. pnewArr->EnsureHead<double>();
  4913. #if ENABLE_PROFILE_INFO
  4914. pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::FromVar(baseArray));
  4915. #endif
  4916. return pnewArr;
  4917. }
  4918. else
  4919. {
  4920. JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
  4921. pnewArr->EnsureHead<Var>();
  4922. return pnewArr;
  4923. }
  4924. }
  4925. template<typename T>
  4926. void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
  4927. {
  4928. SparseArraySegment<T>* headSeg = (SparseArraySegment<T>*)pArr->head;
  4929. SparseArraySegment<T>* pnewHeadSeg = (SparseArraySegment<T>*)pnewArr->head;
  4930. // Fill the newly created sliced array
  4931. js_memcpy_s(pnewHeadSeg->elements, sizeof(T) * newLen, headSeg->elements + start, sizeof(T) * newLen);
  4932. pnewHeadSeg->length = newLen;
  4933. Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
  4934. // Prototype lookup for missing elements
  4935. if (!pArr->HasNoMissingValues())
  4936. {
  4937. for (uint32 i = 0; i < newLen; i++)
  4938. {
  4939. if (SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]))
  4940. {
  4941. Var element;
  4942. pnewArr->SetHasNoMissingValues(false);
  4943. if (pArr->DirectGetItemAtFull(i + start, &element))
  4944. {
  4945. pnewArr->SetItem(i, element, PropertyOperation_None);
  4946. }
  4947. }
  4948. }
  4949. }
  4950. #ifdef DBG
  4951. else
  4952. {
  4953. for (uint32 i = 0; i < newLen; i++)
  4954. {
  4955. AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
  4956. }
  4957. }
  4958. #endif
  4959. }
  4960. // If the creating profile data has changed, convert it to the type of array indicated
  4961. // in the profile
  4962. void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
  4963. {
  4964. if (JavascriptNativeIntArray::Is(this))
  4965. {
  4966. #if ENABLE_PROFILE_INFO
  4967. JavascriptNativeIntArray* nativeIntArray = JavascriptNativeIntArray::FromVar(this);
  4968. ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
  4969. if(!info || info->IsNativeIntArray())
  4970. {
  4971. *isIntArray = true;
  4972. }
  4973. else if(info->IsNativeFloatArray())
  4974. {
  4975. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  4976. *isFloatArray = true;
  4977. }
  4978. else
  4979. {
  4980. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  4981. }
  4982. #else
  4983. *isIntArray = true;
  4984. #endif
  4985. }
  4986. else if (JavascriptNativeFloatArray::Is(this))
  4987. {
  4988. #if ENABLE_PROFILE_INFO
  4989. JavascriptNativeFloatArray* nativeFloatArray = JavascriptNativeFloatArray::FromVar(this);
  4990. ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
  4991. if(info && !info->IsNativeArray())
  4992. {
  4993. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  4994. }
  4995. else
  4996. {
  4997. *isFloatArray = true;
  4998. }
  4999. #else
  5000. *isFloatArray = true;
  5001. #endif
  5002. }
  5003. }
  5004. Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  5005. {
  5006. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5007. ARGUMENTS(args, callInfo);
  5008. ScriptContext* scriptContext = function->GetScriptContext();
  5009. Assert(!(callInfo.Flags & CallFlags_New));
  5010. Var res = scriptContext->GetLibrary()->GetUndefined();
  5011. if (args.Info.Count == 0)
  5012. {
  5013. return res;
  5014. }
  5015. BigIndex length;
  5016. JavascriptArray* pArr = nullptr;
  5017. RecyclableObject* obj = nullptr;
  5018. if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
  5019. {
  5020. pArr = JavascriptArray::FromVar(args[0]);
  5021. obj = pArr;
  5022. }
  5023. else
  5024. {
  5025. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  5026. {
  5027. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.slice"));
  5028. }
  5029. }
  5030. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  5031. // Even for arrays, this is now observable via proxies.
  5032. // If source object is not an array, we fall back to this behavior anyway.
  5033. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  5034. {
  5035. Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
  5036. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  5037. {
  5038. length = (uint64) JavascriptConversion::ToLength(lenValue, scriptContext);
  5039. }
  5040. else
  5041. {
  5042. length = JavascriptConversion::ToUInt32(lenValue, scriptContext);
  5043. }
  5044. }
  5045. else
  5046. {
  5047. length = pArr->length;
  5048. }
  5049. if (length.IsSmallIndex())
  5050. {
  5051. return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
  5052. }
  5053. Assert(pArr == nullptr || length.IsUint32Max());
  5054. return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
  5055. }
  5056. // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
  5057. template <typename T>
  5058. Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  5059. {
  5060. JavascriptLibrary* library = scriptContext->GetLibrary();
  5061. JavascriptArray* newArr = nullptr;
  5062. RecyclableObject* newObj = nullptr;
  5063. bool isIntArray = false;
  5064. bool isFloatArray = false;
  5065. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  5066. T startT = 0;
  5067. T newLenT = length;
  5068. T endT = length;
  5069. #if ENABLE_COPYONACCESS_ARRAY
  5070. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5071. #endif
  5072. if (args.Info.Count > 1)
  5073. {
  5074. startT = GetFromIndex(args[1], length, scriptContext);
  5075. if (startT > length)
  5076. {
  5077. startT = length;
  5078. }
  5079. if (args.Info.Count > 2)
  5080. {
  5081. if (JavascriptOperators::GetTypeId(args[2]) == TypeIds_Undefined)
  5082. {
  5083. endT = length;
  5084. }
  5085. else
  5086. {
  5087. endT = GetFromIndex(args[2], length, scriptContext);
  5088. if (endT > length)
  5089. {
  5090. endT = length;
  5091. }
  5092. }
  5093. }
  5094. newLenT = endT > startT ? endT - startT : 0;
  5095. }
  5096. if (TypedArrayBase::IsDetachedTypedArray(obj))
  5097. {
  5098. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
  5099. }
  5100. // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
  5101. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  5102. {
  5103. typedArrayBase = TypedArrayBase::FromVar(obj);
  5104. }
  5105. // If the entry point is %TypedArray%.prototype.slice or the source object is an Array exotic object we should try to load the constructor property
  5106. // and use it to construct the return object.
  5107. if (isTypedArrayEntryPoint)
  5108. {
  5109. Var constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext);
  5110. // If we have an array source object, we need to make sure to do the right thing if it's a native array.
  5111. // The helpers below which do the element copying require the source and destination arrays to have the same native type.
  5112. if (pArr && constructor == library->GetArrayConstructor())
  5113. {
  5114. if (newLenT > JavascriptArray::MaxArrayLength)
  5115. {
  5116. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5117. }
  5118. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  5119. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5120. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5121. newObj = newArr;
  5122. }
  5123. else if (JavascriptOperators::IsConstructor(constructor) && JavascriptLibrary::IsTypedArrayConstructor(constructor, scriptContext))
  5124. {
  5125. if (pArr)
  5126. {
  5127. // If the constructor function is any other function, it can return anything so we have to call it.
  5128. // Roll the source array into a non-native array if it was one.
  5129. pArr = EnsureNonNativeArray(pArr);
  5130. }
  5131. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
  5132. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  5133. newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  5134. }
  5135. else
  5136. {
  5137. // We only need to throw a TypeError when the constructor property is not an actual constructor if %TypedArray%.prototype.slice was called
  5138. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidTypedArray_Constructor, _u("[TypedArray].prototype.slice"));
  5139. }
  5140. }
  5141. else if (pArr != nullptr)
  5142. {
  5143. newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray);
  5144. }
  5145. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  5146. else
  5147. {
  5148. newObj = ArraySpeciesCreate(obj, newLenT, scriptContext);
  5149. }
  5150. // If we didn't create a new object above we will create a new array here.
  5151. // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
  5152. if (newObj == nullptr)
  5153. {
  5154. if (pArr)
  5155. {
  5156. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5157. }
  5158. if (newLenT > JavascriptArray::MaxArrayLength)
  5159. {
  5160. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5161. }
  5162. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5163. newObj = newArr;
  5164. }
  5165. else
  5166. {
  5167. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5168. if (JavascriptArray::Is(newObj))
  5169. {
  5170. newArr = JavascriptArray::FromVar(newObj);
  5171. }
  5172. }
  5173. uint32 start = (uint32) startT;
  5174. uint32 newLen = (uint32) newLenT;
  5175. // We at least have to have newObj as a valid object
  5176. Assert(newObj);
  5177. // Bail out early if the new object will have zero length.
  5178. if (newLen == 0)
  5179. {
  5180. return newObj;
  5181. }
  5182. if (pArr)
  5183. {
  5184. // If we constructed a new Array object, we have some nice helpers here
  5185. if (newArr)
  5186. {
  5187. if (JavascriptArray::IsDirectAccessArray(newArr))
  5188. {
  5189. if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
  5190. {
  5191. if (isIntArray)
  5192. {
  5193. SliceHelper<int32>(pArr, newArr, start, newLen);
  5194. }
  5195. else if (isFloatArray)
  5196. {
  5197. SliceHelper<double>(pArr, newArr, start, newLen);
  5198. }
  5199. else
  5200. {
  5201. SliceHelper<Var>(pArr, newArr, start, newLen);
  5202. }
  5203. }
  5204. else
  5205. {
  5206. if (isIntArray)
  5207. {
  5208. CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen);
  5209. }
  5210. else if (isFloatArray)
  5211. {
  5212. CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen);
  5213. }
  5214. else
  5215. {
  5216. CopyArrayElements(newArr, 0u, pArr, start, start + newLen);
  5217. }
  5218. }
  5219. }
  5220. else
  5221. {
  5222. AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
  5223. Var element;
  5224. for (uint32 i = 0; i < newLen; i++)
  5225. {
  5226. if (!pArr->DirectGetItemAtFull(i + start, &element))
  5227. {
  5228. continue;
  5229. }
  5230. newArr->DirectSetItemAt(i, element);
  5231. }
  5232. }
  5233. }
  5234. else
  5235. {
  5236. // The constructed object isn't an array, we'll need to use normal object manipulation
  5237. Var element;
  5238. for (uint32 i = 0; i < newLen; i++)
  5239. {
  5240. if (!pArr->DirectGetItemAtFull(i + start, &element))
  5241. {
  5242. continue;
  5243. }
  5244. JavascriptArray::SetArrayLikeObjects(newObj, i, element);
  5245. }
  5246. }
  5247. }
  5248. else if (typedArrayBase)
  5249. {
  5250. // Source is a TypedArray, we must have created the return object via a call to constructor, but newObj may not be a TypedArray (or an array either)
  5251. TypedArrayBase* newTypedArray = nullptr;
  5252. if (TypedArrayBase::Is(newObj))
  5253. {
  5254. newTypedArray = TypedArrayBase::FromVar(newObj);
  5255. }
  5256. Var element;
  5257. for (uint32 i = 0; i < newLen; i++)
  5258. {
  5259. // We only need to call HasItem in the case that we are called from Array.prototype.slice
  5260. if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
  5261. {
  5262. continue;
  5263. }
  5264. element = typedArrayBase->DirectGetItem(i + start);
  5265. // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
  5266. if (newTypedArray)
  5267. {
  5268. newTypedArray->DirectSetItem(i, element, false);
  5269. }
  5270. else if (newArr)
  5271. {
  5272. newArr->DirectSetItemAt(i, element);
  5273. }
  5274. else
  5275. {
  5276. JavascriptOperators::OP_SetElementI_UInt32(newObj, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  5277. }
  5278. }
  5279. }
  5280. else
  5281. {
  5282. Var element;
  5283. for (uint32 i = 0; i < newLen; i++)
  5284. {
  5285. if (!JavascriptOperators::HasItem(obj, i+start))
  5286. {
  5287. continue;
  5288. }
  5289. BOOL getResult = JavascriptOperators::GetItem(obj, i + start, &element, scriptContext);
  5290. Assert(getResult);
  5291. if (newArr != nullptr)
  5292. {
  5293. newArr->DirectSetItemAt(i, element);
  5294. }
  5295. else
  5296. {
  5297. JavascriptOperators::OP_SetElementI_UInt32(newObj, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  5298. }
  5299. }
  5300. }
  5301. if (!isTypedArrayEntryPoint)
  5302. {
  5303. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
  5304. }
  5305. #ifdef VALIDATE_ARRAY
  5306. if (JavascriptArray::Is(newObj))
  5307. {
  5308. JavascriptArray::FromVar(newObj)->ValidateArray();
  5309. }
  5310. #endif
  5311. return newObj;
  5312. }
  5313. struct CompareVarsInfo
  5314. {
  5315. ScriptContext* scriptContext;
  5316. RecyclableObject* compFn;
  5317. };
  5318. int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
  5319. {
  5320. CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
  5321. ScriptContext* requestContext=cvInfo->scriptContext;
  5322. RecyclableObject* compFn=cvInfo->compFn;
  5323. AssertMsg(*(Var*)aRef, "No null expected in sort");
  5324. AssertMsg(*(Var*)bRef, "No null expected in sort");
  5325. if (compFn != nullptr)
  5326. {
  5327. ScriptContext* scriptContext = compFn->GetScriptContext();
  5328. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  5329. CallFlags flags = CallFlags_Value;
  5330. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5331. Var retVal;
  5332. if (requestContext != scriptContext)
  5333. {
  5334. Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
  5335. Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
  5336. retVal = compFn->GetEntryPoint()(compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
  5337. }
  5338. else
  5339. {
  5340. retVal = compFn->GetEntryPoint()(compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
  5341. }
  5342. if (TaggedInt::Is(retVal))
  5343. {
  5344. return TaggedInt::ToInt32(retVal);
  5345. }
  5346. double dblResult;
  5347. if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
  5348. {
  5349. dblResult = JavascriptNumber::GetValue(retVal);
  5350. }
  5351. else
  5352. {
  5353. dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
  5354. }
  5355. if (dblResult < 0)
  5356. {
  5357. return -1;
  5358. }
  5359. return (dblResult > 0) ? 1 : 0;
  5360. }
  5361. else
  5362. {
  5363. JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
  5364. JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
  5365. return JavascriptString::strcmp(pStr1, pStr2);
  5366. }
  5367. }
  5368. static void hybridSort(__inout_ecount(length) Var *elements, uint32 length, CompareVarsInfo* compareInfo)
  5369. {
  5370. // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
  5371. // for arrays of more than 512 elements.
  5372. if (length > 512)
  5373. {
  5374. qsort_s(elements, length, sizeof(Var), compareVars, compareInfo);
  5375. return;
  5376. }
  5377. for (int i = 1; i < (int)length; i++)
  5378. {
  5379. if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
  5380. // binary search for the left-most element greater than value:
  5381. int first = 0;
  5382. int last = i - 1;
  5383. while (first <= last)
  5384. {
  5385. int middle = (first + last) / 2;
  5386. if (compareVars(compareInfo, elements + i, elements + middle) < 0)
  5387. {
  5388. last = middle - 1;
  5389. }
  5390. else
  5391. {
  5392. first = middle + 1;
  5393. }
  5394. }
  5395. // insert value right before first:
  5396. Var value = elements[i];
  5397. memmove(elements + first + 1, elements + first, (i - first) * sizeof(Var));
  5398. elements[first] = value;
  5399. }
  5400. }
  5401. }
  5402. void JavascriptArray::Sort(RecyclableObject* compFn)
  5403. {
  5404. if (length <= 1)
  5405. {
  5406. return;
  5407. }
  5408. this->EnsureHead<Var>();
  5409. ScriptContext* scriptContext = this->GetScriptContext();
  5410. Recycler* recycler = scriptContext->GetRecycler();
  5411. CompareVarsInfo cvInfo;
  5412. cvInfo.scriptContext = scriptContext;
  5413. cvInfo.compFn = compFn;
  5414. Assert(head != nullptr);
  5415. // Just dump the segment map on sort
  5416. ClearSegmentMap();
  5417. uint32 countUndefined = 0;
  5418. SparseArraySegment<Var>* startSeg = (SparseArraySegment<Var>*)head;
  5419. // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
  5420. uint32 saveLength = length;
  5421. // that if compare function tries to modify the array it won't AV.
  5422. head = const_cast<SparseArraySegmentBase*>(EmptySegment);
  5423. SetFlags(DynamicObjectFlags::None);
  5424. this->InvalidateLastUsedSegment();
  5425. length = 0;
  5426. TryFinally([&]()
  5427. {
  5428. //The array is a continuous array if there is only one segment
  5429. if (startSeg->next == nullptr) // Single segment fast path
  5430. {
  5431. if (compFn != nullptr)
  5432. {
  5433. countUndefined = startSeg->RemoveUndefined(scriptContext);
  5434. #ifdef VALIDATE_ARRAY
  5435. ValidateSegment(startSeg);
  5436. #endif
  5437. hybridSort(startSeg->elements, startSeg->length, &cvInfo);
  5438. }
  5439. else
  5440. {
  5441. countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext);
  5442. }
  5443. head = startSeg;
  5444. }
  5445. else
  5446. {
  5447. SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
  5448. SparseArraySegment<Var>* next = startSeg;
  5449. uint32 nextIndex = 0;
  5450. // copy all the elements to single segment
  5451. while (next)
  5452. {
  5453. countUndefined += next->RemoveUndefined(scriptContext);
  5454. if (next->length != 0)
  5455. {
  5456. allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
  5457. }
  5458. next = (SparseArraySegment<Var>*)next->next;
  5459. nextIndex = allElements->length;
  5460. #ifdef VALIDATE_ARRAY
  5461. ValidateSegment(allElements);
  5462. #endif
  5463. }
  5464. if (compFn != nullptr)
  5465. {
  5466. hybridSort(allElements->elements, allElements->length, &cvInfo);
  5467. }
  5468. else
  5469. {
  5470. sort(allElements->elements, &allElements->length, scriptContext);
  5471. }
  5472. head = allElements;
  5473. head->next = nullptr;
  5474. }
  5475. },
  5476. [&](bool hasException)
  5477. {
  5478. length = saveLength;
  5479. ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
  5480. if (hasException)
  5481. {
  5482. head = startSeg;
  5483. this->InvalidateLastUsedSegment();
  5484. }
  5485. });
  5486. #if DEBUG
  5487. {
  5488. uint32 countNull = 0;
  5489. uint32 index = head->length - 1;
  5490. while (countNull < head->length)
  5491. {
  5492. if (((SparseArraySegment<Var>*)head)->elements[index] != NULL)
  5493. {
  5494. break;
  5495. }
  5496. index--;
  5497. countNull++;
  5498. }
  5499. AssertMsg(countNull == 0, "No null expected at the end");
  5500. }
  5501. #endif
  5502. if (countUndefined != 0)
  5503. {
  5504. // fill undefined at the end
  5505. uint32 newLength = head->length + countUndefined;
  5506. if (newLength > head->size)
  5507. {
  5508. head = ((SparseArraySegment<Var>*)head)->GrowByMin(recycler, newLength - head->size);
  5509. }
  5510. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5511. for (uint32 i = head->length; i < newLength; i++)
  5512. {
  5513. ((SparseArraySegment<Var>*)head)->elements[i] = undefined;
  5514. }
  5515. head->length = newLength;
  5516. }
  5517. SetHasNoMissingValues();
  5518. this->InvalidateLastUsedSegment();
  5519. #ifdef VALIDATE_ARRAY
  5520. ValidateArray();
  5521. #endif
  5522. return;
  5523. }
  5524. uint32 JavascriptArray::sort(__inout_ecount(*len) Var *orig, uint32 *len, ScriptContext *scriptContext)
  5525. {
  5526. uint32 count = 0, countUndefined = 0;
  5527. Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
  5528. RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  5529. //
  5530. // Create the Elements array
  5531. //
  5532. for (uint32 i = 0; i < *len; ++i)
  5533. {
  5534. if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
  5535. {
  5536. if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
  5537. {
  5538. elements[count].Value = orig[i];
  5539. elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
  5540. count++;
  5541. }
  5542. else
  5543. {
  5544. countUndefined++;
  5545. }
  5546. orig[i] = SparseArraySegment<Var>::GetMissingItem();
  5547. }
  5548. }
  5549. if (count == 0)
  5550. {
  5551. *len = 0; // set the length to zero
  5552. return countUndefined;
  5553. }
  5554. SortElements(elements, 0, count - 1);
  5555. for (uint32 i = 0; i < count; ++i)
  5556. {
  5557. orig[i] = elements[i].Value;
  5558. }
  5559. *len = count; // set the correct length
  5560. return countUndefined;
  5561. }
  5562. int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
  5563. {
  5564. const Element* element1 = static_cast<const Element*>(elem1);
  5565. const Element* element2 = static_cast<const Element*>(elem2);
  5566. Assert(element1 != NULL);
  5567. Assert(element2 != NULL);
  5568. return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  5569. }
  5570. void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
  5571. {
  5572. qsort_s(elements, right - left + 1, sizeof(Element), CompareElements, this);
  5573. }
  5574. Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
  5575. {
  5576. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5577. ARGUMENTS(args, callInfo);
  5578. ScriptContext* scriptContext = function->GetScriptContext();
  5579. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
  5580. Assert(!(callInfo.Flags & CallFlags_New));
  5581. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5582. RecyclableObject* compFn = NULL;
  5583. if (args.Info.Count > 1)
  5584. {
  5585. if (JavascriptConversion::IsCallable(args[1]))
  5586. {
  5587. compFn = RecyclableObject::FromVar(args[1]);
  5588. }
  5589. else
  5590. {
  5591. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  5592. // Use default comparer:
  5593. // - In ES5 mode if the argument is undefined.
  5594. bool useDefaultComparer = typeId == TypeIds_Undefined;
  5595. if (!useDefaultComparer)
  5596. {
  5597. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedInternalObject, _u("Array.prototype.sort"));
  5598. }
  5599. }
  5600. }
  5601. if (JavascriptArray::Is(args[0]))
  5602. {
  5603. #if ENABLE_COPYONACCESS_ARRAY
  5604. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  5605. #endif
  5606. JavascriptArray *arr = JavascriptArray::FromVar(args[0]);
  5607. if (arr->length <= 1)
  5608. {
  5609. return args[0];
  5610. }
  5611. if(arr->IsFillFromPrototypes())
  5612. {
  5613. arr->FillFromPrototypes(0, arr->length); // We need find all missing value from [[proto]] object
  5614. }
  5615. // Maintain nativity of the array only for the following cases (To favor inplace conversions - keeps the conversion cost less):
  5616. // - int cases for X86 and
  5617. // - FloatArray for AMD64
  5618. // We convert the entire array back and forth once here O(n), rather than doing the costly conversion down the call stack which is O(nlogn)
  5619. #if defined(_M_X64_OR_ARM64)
  5620. if(compFn && JavascriptNativeFloatArray::Is(arr))
  5621. {
  5622. arr = JavascriptNativeFloatArray::ConvertToVarArray((JavascriptNativeFloatArray*)arr);
  5623. arr->Sort(compFn);
  5624. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeFloatArray, double>(arr);
  5625. }
  5626. else
  5627. {
  5628. EnsureNonNativeArray(arr);
  5629. arr->Sort(compFn);
  5630. }
  5631. #else
  5632. if(compFn && JavascriptNativeIntArray::Is(arr))
  5633. {
  5634. //EnsureNonNativeArray(arr);
  5635. arr = JavascriptNativeIntArray::ConvertToVarArray((JavascriptNativeIntArray*)arr);
  5636. arr->Sort(compFn);
  5637. arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeIntArray, int32>(arr);
  5638. }
  5639. else
  5640. {
  5641. EnsureNonNativeArray(arr);
  5642. arr->Sort(compFn);
  5643. }
  5644. #endif
  5645. }
  5646. else
  5647. {
  5648. RecyclableObject* pObj = nullptr;
  5649. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  5650. {
  5651. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
  5652. }
  5653. uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
  5654. JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
  5655. sortArray->EnsureHead<Var>();
  5656. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
  5657. BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
  5658. {
  5659. JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
  5660. for (uint32 i = 0; i < len; i++)
  5661. {
  5662. Var item;
  5663. if (JavascriptOperators::GetItem(pObj, i, &item, scriptContext))
  5664. {
  5665. indexList->Add(i);
  5666. sortArray->DirectSetItemAt(i, item);
  5667. }
  5668. }
  5669. if (indexList->Count() > 0)
  5670. {
  5671. if (sortArray->length > 1)
  5672. {
  5673. sortArray->FillFromPrototypes(0, sortArray->length); // We need find all missing value from [[proto]] object
  5674. }
  5675. sortArray->Sort(compFn);
  5676. uint32 removeIndex = sortArray->head->length;
  5677. for (uint32 i = 0; i < removeIndex; i++)
  5678. {
  5679. AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&((SparseArraySegment<Var>*)sortArray->head)->elements[i]), "No gaps expected in sorted array");
  5680. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, ((SparseArraySegment<Var>*)sortArray->head)->elements[i], scriptContext));
  5681. }
  5682. for (int i = 0; i < indexList->Count(); i++)
  5683. {
  5684. uint32 value = indexList->Item(i);
  5685. if (value >= removeIndex)
  5686. {
  5687. h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value)));
  5688. }
  5689. }
  5690. }
  5691. }
  5692. END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
  5693. }
  5694. return args[0];
  5695. }
  5696. Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
  5697. {
  5698. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5699. ARGUMENTS(args, callInfo);
  5700. ScriptContext* scriptContext = function->GetScriptContext();
  5701. Recycler *recycler = scriptContext->GetRecycler();
  5702. Assert(!(callInfo.Flags & CallFlags_New));
  5703. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  5704. bool isArr = false;
  5705. JavascriptArray* pArr = 0;
  5706. RecyclableObject* pObj = 0;
  5707. RecyclableObject* newObj = nullptr;
  5708. uint32 start = 0;
  5709. uint32 deleteLen = 0;
  5710. uint32 len = 0;
  5711. if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
  5712. {
  5713. isArr = true;
  5714. pArr = JavascriptArray::FromVar(args[0]);
  5715. pObj = pArr;
  5716. len = pArr->length;
  5717. #if ENABLE_COPYONACCESS_ARRAY
  5718. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  5719. #endif
  5720. }
  5721. else
  5722. {
  5723. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  5724. {
  5725. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.splice"));
  5726. }
  5727. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  5728. {
  5729. int64 len64 = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
  5730. len = len64 > UINT_MAX ? UINT_MAX : (uint)len64;
  5731. }
  5732. else
  5733. {
  5734. len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext);
  5735. }
  5736. }
  5737. switch (args.Info.Count)
  5738. {
  5739. case 1:
  5740. start = len;
  5741. deleteLen = 0;
  5742. break;
  5743. case 2:
  5744. start = min(GetFromIndex(args[1], len, scriptContext), len);
  5745. deleteLen = len - start;
  5746. break;
  5747. default:
  5748. start = GetFromIndex(args[1], len, scriptContext);
  5749. if (start > len)
  5750. {
  5751. start = len;
  5752. }
  5753. // When start >= len, we know we won't be deleting any items and don't really need to evaluate the second argument.
  5754. // However, ECMA 262 15.4.4.12 requires that it be evaluated, anyway. If the argument is an object with a valueOf
  5755. // with a side effect, this evaluation is observable. Hence, we must evaluate.
  5756. if (TaggedInt::Is(args[2]))
  5757. {
  5758. int intDeleteLen = TaggedInt::ToInt32(args[2]);
  5759. if (intDeleteLen < 0)
  5760. {
  5761. deleteLen = 0;
  5762. }
  5763. else
  5764. {
  5765. deleteLen = intDeleteLen;
  5766. }
  5767. }
  5768. else
  5769. {
  5770. double dblDeleteLen = JavascriptConversion::ToInteger(args[2], scriptContext);
  5771. if (dblDeleteLen > len)
  5772. {
  5773. deleteLen = (uint32)-1;
  5774. }
  5775. else if (dblDeleteLen <= 0)
  5776. {
  5777. deleteLen = 0;
  5778. }
  5779. else
  5780. {
  5781. deleteLen = (uint32)dblDeleteLen;
  5782. }
  5783. }
  5784. deleteLen = min(len - start, deleteLen);
  5785. break;
  5786. }
  5787. Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
  5788. uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
  5789. ::Math::RecordOverflowPolicy newLenOverflow;
  5790. uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
  5791. if (isArr)
  5792. {
  5793. // If we have missing values then convert to not native array for now
  5794. // In future, we could support this scenario.
  5795. if (deleteLen == insertLen)
  5796. {
  5797. pArr->FillFromPrototypes(start, start + deleteLen);
  5798. }
  5799. else if (len)
  5800. {
  5801. pArr->FillFromPrototypes(start, len);
  5802. }
  5803. //
  5804. // If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
  5805. // max array length, which would result in tons of index overflow and difficult to fix.
  5806. //
  5807. if (newLenOverflow.HasOverflowed())
  5808. {
  5809. pArr = EnsureNonNativeArray(pArr);
  5810. BigIndex dstIndex = MaxArrayLength;
  5811. uint32 maxInsertLen = MaxArrayLength - start;
  5812. if (insertLen > maxInsertLen)
  5813. {
  5814. // Copy overflowing insertArgs to properties
  5815. for (uint32 i = maxInsertLen; i < insertLen; i++)
  5816. {
  5817. pArr->DirectSetItemAt(dstIndex, insertArgs[i]);
  5818. ++dstIndex;
  5819. }
  5820. insertLen = maxInsertLen; // update
  5821. // Truncate elements on the right to properties
  5822. if (start + deleteLen < len)
  5823. {
  5824. pArr->TruncateToProperties(dstIndex, start + deleteLen);
  5825. }
  5826. }
  5827. else
  5828. {
  5829. // Truncate would-overflow elements to properties
  5830. pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
  5831. }
  5832. len = pArr->length; // update
  5833. newLen = len - deleteLen + insertLen;
  5834. Assert(newLen == MaxArrayLength);
  5835. }
  5836. if (insertArgs)
  5837. {
  5838. pArr = EnsureNonNativeArray(pArr);
  5839. }
  5840. bool isIntArray = false;
  5841. bool isFloatArray = false;
  5842. JavascriptArray *newArr = nullptr;
  5843. // Just dump the segment map on splice (before any possible allocation and throw)
  5844. pArr->ClearSegmentMap();
  5845. // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
  5846. // and use it to construct the return object.
  5847. newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext);
  5848. if (newObj != nullptr)
  5849. {
  5850. pArr = EnsureNonNativeArray(pArr);
  5851. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5852. if (JavascriptArray::Is(newObj))
  5853. {
  5854. newArr = JavascriptArray::FromVar(newObj);
  5855. }
  5856. }
  5857. else
  5858. // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
  5859. {
  5860. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5861. newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
  5862. }
  5863. // If return object is a JavascriptArray, we can use all the array splice helpers
  5864. if (newArr)
  5865. {
  5866. // Array has a single segment (need not start at 0) and splice start lies in the range
  5867. // of that segment we optimize splice - Fast path.
  5868. if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
  5869. {
  5870. if (isIntArray)
  5871. {
  5872. ArraySegmentSpliceHelper<int32>(newArr, (SparseArraySegment<int32>*)pArr->head, (SparseArraySegment<int32>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  5873. }
  5874. else if (isFloatArray)
  5875. {
  5876. ArraySegmentSpliceHelper<double>(newArr, (SparseArraySegment<double>*)pArr->head, (SparseArraySegment<double>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  5877. }
  5878. else
  5879. {
  5880. ArraySegmentSpliceHelper<Var>(newArr, (SparseArraySegment<Var>*)pArr->head, (SparseArraySegment<Var>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
  5881. }
  5882. // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
  5883. // missing values. If the original array had missing values in the head segment, some of them may have been
  5884. // copied into the array that will be returned; otherwise, the array that is returned will also not have any
  5885. // missing values.
  5886. newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
  5887. }
  5888. else
  5889. {
  5890. if (isIntArray)
  5891. {
  5892. ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  5893. }
  5894. else if (isFloatArray)
  5895. {
  5896. ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  5897. }
  5898. else
  5899. {
  5900. ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  5901. }
  5902. // This function currently does not track missing values in the head segment if there are multiple segments
  5903. pArr->SetHasNoMissingValues(false);
  5904. newArr->SetHasNoMissingValues(false);
  5905. }
  5906. if (isIntArray)
  5907. {
  5908. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  5909. newArr->EnsureHeadStartsFromZero<int32>(recycler);
  5910. }
  5911. else if (isFloatArray)
  5912. {
  5913. pArr->EnsureHeadStartsFromZero<double>(recycler);
  5914. newArr->EnsureHeadStartsFromZero<double>(recycler);
  5915. }
  5916. else
  5917. {
  5918. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  5919. newArr->EnsureHeadStartsFromZero<Var>(recycler);
  5920. }
  5921. pArr->InvalidateLastUsedSegment();
  5922. // it is possible for valueOf accessors for the start or deleteLen
  5923. // arguments to modify the size of the array. Since the resulting size of the array
  5924. // is based on the cached value of length, this might lead to us having to trim
  5925. // excess array segments at the end of the splice operation, which SetLength() will do.
  5926. // However, this is also slower than performing the simple length assignment, so we only
  5927. // do it if we can detect the array length changing.
  5928. if(pArr->length != len)
  5929. {
  5930. pArr->SetLength(newLen);
  5931. }
  5932. else
  5933. {
  5934. pArr->length = newLen;
  5935. }
  5936. newArr->InvalidateLastUsedSegment();
  5937. #ifdef VALIDATE_ARRAY
  5938. newArr->ValidateArray();
  5939. pArr->ValidateArray();
  5940. #endif
  5941. if (newLenOverflow.HasOverflowed())
  5942. {
  5943. // ES5 15.4.4.12 16: If new len overflowed, SetLength throws
  5944. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  5945. }
  5946. return newArr;
  5947. }
  5948. }
  5949. if (newLenOverflow.HasOverflowed())
  5950. {
  5951. return ObjectSpliceHelper<BigIndex>(pObj, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj);
  5952. }
  5953. else // Use uint32 version if no overflow
  5954. {
  5955. return ObjectSpliceHelper<uint32>(pObj, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj);
  5956. }
  5957. }
  5958. inline BOOL JavascriptArray::IsSingleSegmentArray() const
  5959. {
  5960. return nullptr == head->next;
  5961. }
  5962. template<typename T>
  5963. void JavascriptArray::ArraySegmentSpliceHelper(JavascriptArray *pnewArr, SparseArraySegment<T> *seg, SparseArraySegment<T> **prev,
  5964. uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
  5965. {
  5966. // book keeping variables
  5967. uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
  5968. //(Missing elements at the beginning)
  5969. uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
  5970. // head if deleteLen overflows the length of head
  5971. uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
  5972. // Save the deleted elements
  5973. if (headDeleteLen != 0)
  5974. {
  5975. pnewArr->InvalidateLastUsedSegment();
  5976. pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, (SparseArraySegment<T>*)pnewArr->head, 0, seg, start, headDeleteLen);
  5977. }
  5978. if (newHeadLen != 0)
  5979. {
  5980. if (seg->size < newHeadLen)
  5981. {
  5982. if (seg->next)
  5983. {
  5984. // If we have "next", require that we haven't adjusted next segments left yet.
  5985. seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
  5986. }
  5987. else
  5988. {
  5989. seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
  5990. }
  5991. #ifdef VALIDATE_ARRAY
  5992. ValidateSegment(seg);
  5993. #endif
  5994. }
  5995. // Move the elements if necessary
  5996. if (headDeleteLen != insertLen)
  5997. {
  5998. uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
  5999. memmove(seg->elements + relativeStart + insertLen,
  6000. seg->elements + relativeStart + headDeleteLen,
  6001. sizeof(T) * noElementsToMove);
  6002. if (newHeadLen < seg->length) // truncate if necessary
  6003. {
  6004. seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
  6005. }
  6006. seg->length = newHeadLen;
  6007. }
  6008. // Copy the new elements
  6009. if (insertLen > 0)
  6010. {
  6011. Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
  6012. !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
  6013. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6014. js_memcpy_s(seg->elements + relativeStart, sizeof(Var) * insertLen, insertArgs, sizeof(Var) * insertLen);
  6015. }
  6016. *prev = seg;
  6017. }
  6018. else
  6019. {
  6020. *prev = (SparseArraySegment<T>*)seg->next;
  6021. }
  6022. }
  6023. template<typename T>
  6024. void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6025. {
  6026. // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
  6027. Recycler *recycler = scriptContext->GetRecycler();
  6028. SparseArraySegmentBase** prevSeg = &pArr->head; // holds the next pointer of previous
  6029. SparseArraySegmentBase** prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
  6030. SparseArraySegmentBase* savePrev = nullptr;
  6031. Assert(pArr->head); // We should never have a null head.
  6032. pArr->EnsureHead<T>();
  6033. SparseArraySegment<T>* startSeg = (SparseArraySegment<T>*)pArr->head;
  6034. const uint32 limit = start + deleteLen;
  6035. uint32 rightLimit;
  6036. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6037. {
  6038. rightLimit = JavascriptArray::MaxArrayLength;
  6039. }
  6040. // Find out the segment to start delete
  6041. while (startSeg && (rightLimit <= start))
  6042. {
  6043. savePrev = startSeg;
  6044. prevPrevSeg = prevSeg;
  6045. prevSeg = &startSeg->next;
  6046. startSeg = (SparseArraySegment<T>*)startSeg->next;
  6047. if (startSeg)
  6048. {
  6049. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6050. {
  6051. rightLimit = JavascriptArray::MaxArrayLength;
  6052. }
  6053. }
  6054. }
  6055. // handle inlined segment
  6056. SparseArraySegmentBase* inlineHeadSegment = nullptr;
  6057. bool hasInlineSegment = false;
  6058. // The following if else set is used to determine whether a shallow or hard copy is needed
  6059. if (JavascriptNativeArray::Is(pArr))
  6060. {
  6061. if (JavascriptNativeFloatArray::Is(pArr))
  6062. {
  6063. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
  6064. }
  6065. else if (JavascriptNativeIntArray::Is(pArr))
  6066. {
  6067. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
  6068. }
  6069. Assert(inlineHeadSegment);
  6070. hasInlineSegment = (startSeg == (SparseArraySegment<T>*)inlineHeadSegment);
  6071. }
  6072. else
  6073. {
  6074. // This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
  6075. // does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
  6076. // This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
  6077. // so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
  6078. // false positives. It is better than always doing a hard copy.
  6079. hasInlineSegment = HasInlineHeadSegment(pArr->head->length);
  6080. }
  6081. if (startSeg)
  6082. {
  6083. // Delete Phase
  6084. if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
  6085. {
  6086. // All splice happens in one segment.
  6087. SparseArraySegmentBase *nextSeg = startSeg->next;
  6088. // Splice the segment first, which might OOM throw but the array would be intact.
  6089. JavascriptArray::ArraySegmentSpliceHelper(pnewArr, (SparseArraySegment<T>*)startSeg, (SparseArraySegment<T>**)prevSeg, start, deleteLen, insertArgs, insertLen, recycler);
  6090. while (nextSeg)
  6091. {
  6092. // adjust next segments left
  6093. nextSeg->left = nextSeg->left - deleteLen + insertLen;
  6094. if (nextSeg->next == nullptr)
  6095. {
  6096. nextSeg->EnsureSizeInBound();
  6097. }
  6098. nextSeg = nextSeg->next;
  6099. }
  6100. if (*prevSeg)
  6101. {
  6102. (*prevSeg)->EnsureSizeInBound();
  6103. }
  6104. return;
  6105. }
  6106. else
  6107. {
  6108. SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
  6109. SparseArraySegmentBase** prevNewHeadSeg = &(pnewArr->head);
  6110. // delete till deleteLen and reuse segments for new array if it is possible.
  6111. // 3 steps -
  6112. //1. delete 1st segment (which may be partial delete)
  6113. // 2. delete next n complete segments
  6114. // 3. delete last segment (which again may be partial delete)
  6115. // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
  6116. if (startSeg->left < start)
  6117. {
  6118. if (start < startSeg->left + startSeg->length)
  6119. {
  6120. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6121. if (startSeg->next)
  6122. {
  6123. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6124. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6125. }
  6126. else
  6127. {
  6128. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6129. }
  6130. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6131. newHeadSeg->next = nullptr;
  6132. *prevNewHeadSeg = newHeadSeg;
  6133. prevNewHeadSeg = &newHeadSeg->next;
  6134. startSeg->Truncate(start);
  6135. }
  6136. savePrev = startSeg;
  6137. prevPrevSeg = prevSeg;
  6138. prevSeg = &startSeg->next;
  6139. startSeg = (SparseArraySegment<T>*)startSeg->next;
  6140. }
  6141. // Step (2) first we should do a hard copy if we have an inline head Segment
  6142. else if (hasInlineSegment && nullptr != startSeg)
  6143. {
  6144. // start should be in between left and left + length
  6145. if (startSeg->left <= start && start < startSeg->left + startSeg->length)
  6146. {
  6147. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6148. if (startSeg->next)
  6149. {
  6150. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6151. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6152. }
  6153. else
  6154. {
  6155. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6156. }
  6157. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6158. *prevNewHeadSeg = newHeadSeg;
  6159. prevNewHeadSeg = &newHeadSeg->next;
  6160. // Remove the entire segment from the original array
  6161. *prevSeg = startSeg->next;
  6162. startSeg = (SparseArraySegment<T>*)startSeg->next;
  6163. }
  6164. // if we have an inline head segment with 0 elements, remove it
  6165. else if (startSeg->left == 0 && startSeg->length == 0)
  6166. {
  6167. Assert(startSeg->size != 0);
  6168. *prevSeg = startSeg->next;
  6169. startSeg = (SparseArraySegment<T>*)startSeg->next;
  6170. }
  6171. }
  6172. // Step (2) proper
  6173. SparseArraySegmentBase *temp = nullptr;
  6174. while (startSeg && (startSeg->left + startSeg->length) <= limit)
  6175. {
  6176. temp = startSeg->next;
  6177. // move that entire segment to new array
  6178. startSeg->left = startSeg->left - start;
  6179. startSeg->next = nullptr;
  6180. *prevNewHeadSeg = startSeg;
  6181. prevNewHeadSeg = &startSeg->next;
  6182. // Remove the entire segment from the original array
  6183. *prevSeg = temp;
  6184. startSeg = (SparseArraySegment<T>*)temp;
  6185. }
  6186. // Step(2) above could delete the original head segment entirely, causing current head not
  6187. // starting from 0. Then if any of the following throw, we have a corrupted array. Need
  6188. // protection here.
  6189. bool dummyHeadNodeInserted = false;
  6190. if (!savePrev && (!startSeg || startSeg->left != 0))
  6191. {
  6192. Assert(pArr->head == startSeg);
  6193. pArr->EnsureHeadStartsFromZero<T>(recycler);
  6194. Assert(pArr->head && pArr->head->next == startSeg);
  6195. savePrev = pArr->head;
  6196. prevPrevSeg = prevSeg;
  6197. prevSeg = &pArr->head->next;
  6198. dummyHeadNodeInserted = true;
  6199. }
  6200. // Step (3)
  6201. if (startSeg && (startSeg->left < limit))
  6202. {
  6203. // copy the first part of the last segment to be deleted to new array
  6204. uint32 headDeleteLen = start + deleteLen - startSeg->left ;
  6205. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
  6206. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
  6207. newHeadSeg->next = nullptr;
  6208. *prevNewHeadSeg = newHeadSeg;
  6209. prevNewHeadSeg = &newHeadSeg->next;
  6210. // move the last segment
  6211. memmove(startSeg->elements, startSeg->elements + headDeleteLen, sizeof(T) * (startSeg->length - headDeleteLen));
  6212. startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
  6213. startSeg->length = startSeg->length - headDeleteLen;
  6214. startSeg->Truncate(startSeg->left + startSeg->length);
  6215. startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
  6216. }
  6217. if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
  6218. {
  6219. Assert(start + insertLen == 0);
  6220. // Remove the dummy head node to preserve array consistency.
  6221. pArr->head = startSeg;
  6222. savePrev = nullptr;
  6223. prevSeg = &pArr->head;
  6224. }
  6225. while (startSeg)
  6226. {
  6227. startSeg->left = startSeg->left - deleteLen + insertLen ;
  6228. if (startSeg->next == nullptr)
  6229. {
  6230. startSeg->EnsureSizeInBound();
  6231. }
  6232. startSeg = (SparseArraySegment<T>*)startSeg->next;
  6233. }
  6234. }
  6235. }
  6236. // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
  6237. pnewArr->head->EnsureSizeInBound();
  6238. if (savePrev)
  6239. {
  6240. savePrev->EnsureSizeInBound();
  6241. }
  6242. // insert elements
  6243. if (insertLen > 0)
  6244. {
  6245. Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
  6246. // InsertPhase
  6247. SparseArraySegment<T> *segInsert = nullptr;
  6248. // see if we are just about the right of the previous segment
  6249. Assert(!savePrev || savePrev->left <= start);
  6250. if (savePrev && (start - savePrev->left < savePrev->size))
  6251. {
  6252. segInsert = (SparseArraySegment<T>*)savePrev;
  6253. uint32 spaceLeft = segInsert->size - (start - segInsert->left);
  6254. if(spaceLeft < insertLen)
  6255. {
  6256. if (!segInsert->next)
  6257. {
  6258. segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
  6259. }
  6260. else
  6261. {
  6262. segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
  6263. }
  6264. }
  6265. *prevPrevSeg = segInsert;
  6266. segInsert->length = start + insertLen - segInsert->left;
  6267. }
  6268. else
  6269. {
  6270. segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
  6271. segInsert->next = *prevSeg;
  6272. *prevSeg = segInsert;
  6273. savePrev = segInsert;
  6274. }
  6275. uint32 relativeStart = start - segInsert->left;
  6276. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6277. js_memcpy_s(segInsert->elements + relativeStart, sizeof(T) * insertLen, insertArgs, sizeof(T) * insertLen);
  6278. }
  6279. }
  6280. template<typename indexT>
  6281. RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, uint32 len, uint32 start,
  6282. uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
  6283. {
  6284. JavascriptArray *pnewArr = nullptr;
  6285. if (pNewObj == nullptr)
  6286. {
  6287. pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext);
  6288. if (pNewObj == nullptr || !JavascriptArray::Is(pNewObj))
  6289. {
  6290. pnewArr = scriptContext->GetLibrary()->CreateArray(deleteLen);
  6291. pnewArr->EnsureHead<Var>();
  6292. pNewObj = pnewArr;
  6293. }
  6294. }
  6295. if (JavascriptArray::Is(pNewObj))
  6296. {
  6297. pnewArr = JavascriptArray::FromVar(pNewObj);
  6298. }
  6299. // copy elements to delete to new array
  6300. if (deleteLen > 0)
  6301. {
  6302. for (uint32 i = 0; i < deleteLen; i++)
  6303. {
  6304. Var element;
  6305. if (JavascriptOperators::HasItem(pObj, start+i))
  6306. {
  6307. BOOL getResult = JavascriptOperators::GetItem(pObj, start + i, &element, scriptContext);
  6308. Assert(getResult);
  6309. if (pnewArr)
  6310. {
  6311. pnewArr->DirectSetItemAt(i, element);
  6312. }
  6313. else
  6314. {
  6315. JavascriptArray::SetArrayLikeObjects(pNewObj, i, element);
  6316. }
  6317. }
  6318. }
  6319. }
  6320. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
  6321. // If the return object is not an array, we'll need to set the 'length' property
  6322. if (pnewArr == nullptr)
  6323. {
  6324. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, JavascriptNumber::ToVar(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  6325. }
  6326. // Now we need reserve room if it is necessary
  6327. if (insertLen > deleteLen) // Might overflow max array length
  6328. {
  6329. // Unshift [start + deleteLen, len) to start + insertLen
  6330. Unshift<indexT>(pObj, start + insertLen, start + deleteLen, len, scriptContext);
  6331. }
  6332. else if (insertLen < deleteLen) // Won't overflow max array length
  6333. {
  6334. uint32 j = 0;
  6335. for (uint32 i = start + deleteLen; i < len; i++)
  6336. {
  6337. Var element;
  6338. if (JavascriptOperators::HasItem(pObj, i))
  6339. {
  6340. BOOL getResult = JavascriptOperators::GetItem(pObj, i, &element, scriptContext);
  6341. Assert(getResult);
  6342. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  6343. }
  6344. else
  6345. {
  6346. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowIfNotExtensible));
  6347. }
  6348. j++;
  6349. }
  6350. // Clean up the rest
  6351. for (uint32 i = len; i > len - deleteLen + insertLen; i--)
  6352. {
  6353. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowIfNotExtensible));
  6354. }
  6355. }
  6356. if (insertLen > 0)
  6357. {
  6358. indexT dstIndex = start; // insert index might overflow max array length
  6359. for (uint i = 0; i < insertLen; i++)
  6360. {
  6361. h.ThrowTypeErrorOnFailure(IndexTrace<indexT>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible));
  6362. ++dstIndex;
  6363. }
  6364. }
  6365. // Set up new length
  6366. indexT newLen = indexT(len - deleteLen) + insertLen;
  6367. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<indexT>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  6368. #ifdef VALIDATE_ARRAY
  6369. if (pnewArr)
  6370. {
  6371. pnewArr->ValidateArray();
  6372. }
  6373. #endif
  6374. return pNewObj;
  6375. }
  6376. Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  6377. {
  6378. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6379. ARGUMENTS(args, callInfo);
  6380. ScriptContext* scriptContext = function->GetScriptContext();
  6381. Assert(!(callInfo.Flags & CallFlags_New));
  6382. if (args.Info.Count == 0)
  6383. {
  6384. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
  6385. }
  6386. if (JavascriptArray::IsDirectAccessArray(args[0]))
  6387. {
  6388. JavascriptArray* arr = JavascriptArray::FromVar(args[0]);
  6389. return ToLocaleString(arr, scriptContext);
  6390. }
  6391. else
  6392. {
  6393. RecyclableObject* obj = nullptr;
  6394. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6395. {
  6396. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
  6397. }
  6398. return ToLocaleString(obj, scriptContext);
  6399. }
  6400. }
  6401. //
  6402. // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
  6403. //
  6404. template<typename T, typename P>
  6405. void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, uint32 start, P end, ScriptContext* scriptContext)
  6406. {
  6407. typedef IndexTrace<T> index_trace;
  6408. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6409. if (start < end)
  6410. {
  6411. T newEnd = (end - start - 1);// newEnd - 1
  6412. T dst = toIndex + newEnd;
  6413. uint32 i = 0;
  6414. if (end > UINT32_MAX)
  6415. {
  6416. uint64 i64 = end;
  6417. for (; i64 > UINT32_MAX; i64--)
  6418. {
  6419. Var element;
  6420. if (JavascriptOperators::HasItem(obj, i64 - 1))
  6421. {
  6422. BOOL getResult = JavascriptOperators::GetItem(obj, i64 - 1, &element, scriptContext);
  6423. Assert(getResult);
  6424. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible));
  6425. }
  6426. else
  6427. {
  6428. h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowIfNotExtensible));
  6429. }
  6430. --dst;
  6431. }
  6432. i = UINT32_MAX;
  6433. }
  6434. else
  6435. {
  6436. i = (uint32) end;
  6437. }
  6438. for (; i > start; i--)
  6439. {
  6440. Var element;
  6441. if (JavascriptOperators::HasItem(obj, i-1))
  6442. {
  6443. BOOL getResult = JavascriptOperators::GetItem(obj, i - 1, &element, scriptContext);
  6444. Assert(getResult);
  6445. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible));
  6446. }
  6447. else
  6448. {
  6449. h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowIfNotExtensible));
  6450. }
  6451. --dst;
  6452. }
  6453. }
  6454. }
  6455. template<typename T>
  6456. void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
  6457. {
  6458. SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
  6459. Recycler* recycler = scriptContext->GetRecycler();
  6460. if (nextToHeadSeg == nullptr)
  6461. {
  6462. pArr->EnsureHead<T>();
  6463. pArr->head = ((SparseArraySegment<T>*)pArr->head)->GrowByMin(recycler, unshiftElements);
  6464. }
  6465. else
  6466. {
  6467. pArr->head = ((SparseArraySegment<T>*)pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
  6468. }
  6469. }
  6470. template<typename T>
  6471. void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
  6472. {
  6473. SparseArraySegment<T>* head = (SparseArraySegment<T>*)pArr->head;
  6474. // Make enough room in the head segment to insert new elements at the front
  6475. memmove(head->elements + unshiftElements, head->elements, sizeof(T) * pArr->head->length);
  6476. uint32 oldHeadLength = head->length;
  6477. head->length += unshiftElements;
  6478. /* Set head segment as the last used segment */
  6479. pArr->InvalidateLastUsedSegment();
  6480. bool hasNoMissingValues = pArr->HasNoMissingValues();
  6481. /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
  6482. if(unshiftElements > oldHeadLength)
  6483. {
  6484. pArr->SetHasNoMissingValues(false);
  6485. }
  6486. #if ENABLE_PROFILE_INFO
  6487. pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
  6488. #else
  6489. pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
  6490. #endif
  6491. // Setting back to the old value
  6492. pArr->SetHasNoMissingValues(hasNoMissingValues);
  6493. }
  6494. Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
  6495. {
  6496. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6497. ARGUMENTS(args, callInfo);
  6498. ScriptContext* scriptContext = function->GetScriptContext();
  6499. Assert(!(callInfo.Flags & CallFlags_New));
  6500. Var res = scriptContext->GetLibrary()->GetUndefined();
  6501. if (args.Info.Count == 0)
  6502. {
  6503. return res;
  6504. }
  6505. if (JavascriptArray::Is(args[0]))
  6506. {
  6507. #if ENABLE_COPYONACCESS_ARRAY
  6508. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  6509. #endif
  6510. JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
  6511. uint32 unshiftElements = args.Info.Count - 1;
  6512. if (unshiftElements > 0)
  6513. {
  6514. if (pArr->IsFillFromPrototypes())
  6515. {
  6516. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  6517. }
  6518. // Pre-process: truncate overflowing elements to properties
  6519. bool newLenOverflowed = false;
  6520. uint32 maxLen = MaxArrayLength - unshiftElements;
  6521. if (pArr->length > maxLen)
  6522. {
  6523. newLenOverflowed = true;
  6524. // Ensure the array is non-native when overflow happens
  6525. EnsureNonNativeArray(pArr);
  6526. pArr->TruncateToProperties(MaxArrayLength, maxLen);
  6527. Assert(pArr->length + unshiftElements == MaxArrayLength);
  6528. }
  6529. pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
  6530. Assert(pArr->length <= MaxArrayLength - unshiftElements);
  6531. SparseArraySegmentBase* renumberSeg = pArr->head->next;
  6532. bool isIntArray = false;
  6533. bool isFloatArray = false;
  6534. if (JavascriptNativeIntArray::Is(pArr))
  6535. {
  6536. isIntArray = true;
  6537. }
  6538. else if (JavascriptNativeFloatArray::Is(pArr))
  6539. {
  6540. isFloatArray = true;
  6541. }
  6542. // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
  6543. // If there is OOM in array allocation, then array consistency is maintained.
  6544. if (pArr->head->size < pArr->head->length + unshiftElements)
  6545. {
  6546. if (isIntArray)
  6547. {
  6548. GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
  6549. }
  6550. else if (isFloatArray)
  6551. {
  6552. GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
  6553. }
  6554. else
  6555. {
  6556. GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
  6557. }
  6558. }
  6559. while (renumberSeg)
  6560. {
  6561. renumberSeg->left += unshiftElements;
  6562. if (renumberSeg->next == nullptr)
  6563. {
  6564. // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
  6565. renumberSeg->EnsureSizeInBound();
  6566. }
  6567. renumberSeg = renumberSeg->next;
  6568. }
  6569. if (isIntArray)
  6570. {
  6571. UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
  6572. }
  6573. else if (isFloatArray)
  6574. {
  6575. UnshiftHelper<double>(pArr, unshiftElements, args.Values);
  6576. }
  6577. else
  6578. {
  6579. UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
  6580. }
  6581. pArr->InvalidateLastUsedSegment();
  6582. pArr->length += unshiftElements;
  6583. #ifdef VALIDATE_ARRAY
  6584. pArr->ValidateArray();
  6585. #endif
  6586. if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
  6587. {
  6588. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  6589. }
  6590. }
  6591. res = JavascriptNumber::ToVar(pArr->length, scriptContext);
  6592. }
  6593. else
  6594. {
  6595. RecyclableObject* dynamicObject = nullptr;
  6596. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  6597. {
  6598. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
  6599. }
  6600. BigIndex length;
  6601. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  6602. {
  6603. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  6604. }
  6605. else
  6606. {
  6607. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  6608. }
  6609. uint32 unshiftElements = args.Info.Count - 1;
  6610. if (unshiftElements > 0)
  6611. {
  6612. uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
  6613. // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
  6614. // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
  6615. BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
  6616. if (end < length)
  6617. {
  6618. // Unshift [end, length) to MaxArrayLength
  6619. // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
  6620. if (length.IsSmallIndex())
  6621. {
  6622. Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext);
  6623. }
  6624. else
  6625. {
  6626. Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetBigIndex(), scriptContext);
  6627. }
  6628. }
  6629. // Unshift [0, end) to unshiftElements
  6630. // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
  6631. Unshift<uint32>(dynamicObject, unshiftElements, 0, end.GetSmallIndex(), scriptContext);
  6632. for (uint32 i = 0; i < unshiftElements; i++)
  6633. {
  6634. JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true);
  6635. }
  6636. }
  6637. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6638. //ES6 - update 'length' even if unshiftElements == 0;
  6639. BigIndex newLen = length + unshiftElements;
  6640. res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
  6641. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  6642. }
  6643. return res;
  6644. }
  6645. Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  6646. {
  6647. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6648. ARGUMENTS(args, callInfo);
  6649. ScriptContext* scriptContext = function->GetScriptContext();
  6650. Assert(!(callInfo.Flags & CallFlags_New));
  6651. if (args.Info.Count == 0)
  6652. {
  6653. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  6654. }
  6655. // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
  6656. RecyclableObject* obj = nullptr;
  6657. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6658. {
  6659. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
  6660. }
  6661. // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
  6662. Var join = JavascriptOperators::GetProperty(obj, PropertyIds::join, scriptContext);
  6663. if (JavascriptConversion::IsCallable(join))
  6664. {
  6665. RecyclableObject* func = RecyclableObject::FromVar(join);
  6666. // We need to record implicit call here, because marked the Array.toString as no side effect,
  6667. // but if we call user code here which may have side effect
  6668. ThreadContext * threadContext = scriptContext->GetThreadContext();
  6669. Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
  6670. {
  6671. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  6672. Assert(!ThreadContext::IsOnStack(obj));
  6673. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  6674. CallFlags flags = CallFlags_Value;
  6675. return func->GetEntryPoint()(func, CallInfo(flags, 1), obj);
  6676. });
  6677. if(!result)
  6678. {
  6679. // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
  6680. Assert(threadContext->IsDisableImplicitCall());
  6681. result = scriptContext->GetLibrary()->GetNull();
  6682. }
  6683. return result;
  6684. }
  6685. else
  6686. {
  6687. // call built-in Object.prototype.toString
  6688. return JavascriptObject::EntryToString(function, 1, obj);
  6689. }
  6690. }
  6691. #if DEBUG
  6692. BOOL JavascriptArray::GetIndex(const char16* propName, ulong *pIndex)
  6693. {
  6694. ulong lu, luDig;
  6695. long cch = (long)wcslen(propName);
  6696. char16* pch = const_cast<char16 *>(propName);
  6697. lu = *pch - '0';
  6698. if (lu > 9)
  6699. return FALSE;
  6700. if (0 == lu)
  6701. {
  6702. *pIndex = 0;
  6703. return 1 == cch;
  6704. }
  6705. while ((luDig = *++pch - '0') < 10)
  6706. {
  6707. // If we overflow 32 bits, ignore the item
  6708. if (lu > 0x19999999)
  6709. return FALSE;
  6710. lu *= 10;
  6711. if(lu > (ULONG_MAX - luDig))
  6712. return FALSE;
  6713. lu += luDig;
  6714. }
  6715. if (pch - propName != cch)
  6716. return FALSE;
  6717. if (lu == JavascriptArray::InvalidIndex)
  6718. {
  6719. // 0xFFFFFFFF is not treated as an array index so that the length can be
  6720. // capped at 32 bits.
  6721. return FALSE;
  6722. }
  6723. *pIndex = lu;
  6724. return TRUE;
  6725. }
  6726. #endif
  6727. JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
  6728. {
  6729. #ifdef ENABLE_GLOBALIZATION
  6730. LCID lcid = GetUserDefaultLCID();
  6731. int count = 0;
  6732. char16 szSeparator[6];
  6733. // According to the document for GetLocaleInfo this is a sufficient buffer size.
  6734. count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
  6735. if( !count)
  6736. {
  6737. AssertMsg(FALSE, "GetLocaleInfo failed");
  6738. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  6739. }
  6740. else
  6741. {
  6742. // Append ' ' if necessary
  6743. if( count < 2 || szSeparator[count-2] != ' ')
  6744. {
  6745. szSeparator[count-1] = ' ';
  6746. szSeparator[count] = '\0';
  6747. }
  6748. return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
  6749. }
  6750. #else
  6751. // xplat-todo: Support locale-specific seperator
  6752. return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  6753. #endif
  6754. }
  6755. template <typename T>
  6756. JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
  6757. {
  6758. uint32 length = ItemTrace<T>::GetLength(arr, scriptContext);
  6759. if (length == 0 || scriptContext->CheckObject(arr))
  6760. {
  6761. return scriptContext->GetLibrary()->GetEmptyString();
  6762. }
  6763. JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
  6764. bool pushedObject = false;
  6765. TryFinally([&]()
  6766. {
  6767. scriptContext->PushObject(arr);
  6768. pushedObject = true;
  6769. Var element;
  6770. if (ItemTrace<T>::GetItem(arr, 0, &element, scriptContext))
  6771. {
  6772. res = JavascriptArray::ToLocaleStringHelper(element, scriptContext);
  6773. }
  6774. if (length > 1)
  6775. {
  6776. JavascriptString* separator = GetLocaleSeparator(scriptContext);
  6777. for (uint32 i = 1; i < length; i++)
  6778. {
  6779. res = JavascriptString::Concat(res, separator);
  6780. if (ItemTrace<T>::GetItem(arr, i, &element, scriptContext))
  6781. {
  6782. res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext));
  6783. }
  6784. }
  6785. }
  6786. },
  6787. [&](bool/*hasException*/)
  6788. {
  6789. if (pushedObject)
  6790. {
  6791. Var top = scriptContext->PopObject();
  6792. AssertMsg(top == arr, "Unmatched operation stack");
  6793. }
  6794. });
  6795. if (res == nullptr)
  6796. {
  6797. res = scriptContext->GetLibrary()->GetEmptyString();
  6798. }
  6799. return res;
  6800. }
  6801. Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
  6802. {
  6803. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6804. ARGUMENTS(args, callInfo);
  6805. ScriptContext* scriptContext = function->GetScriptContext();
  6806. Assert(!(callInfo.Flags & CallFlags_New));
  6807. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayisArrayCount);
  6808. if (args.Info.Count < 2)
  6809. {
  6810. return scriptContext->GetLibrary()->GetFalse();
  6811. }
  6812. #if ENABLE_COPYONACCESS_ARRAY
  6813. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  6814. #endif
  6815. if (JavascriptOperators::IsArray(args[1]))
  6816. {
  6817. return scriptContext->GetLibrary()->GetTrue();
  6818. }
  6819. return scriptContext->GetLibrary()->GetFalse();
  6820. }
  6821. ///----------------------------------------------------------------------------
  6822. /// Find() calls the given predicate callback on each element of the array, in
  6823. /// order, and returns the first element that makes the predicate return true,
  6824. /// as described in (ES6.0: S22.1.3.8).
  6825. ///----------------------------------------------------------------------------
  6826. Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
  6827. {
  6828. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6829. ARGUMENTS(args, callInfo);
  6830. ScriptContext* scriptContext = function->GetScriptContext();
  6831. Assert(!(callInfo.Flags & CallFlags_New));
  6832. if (args.Info.Count == 0)
  6833. {
  6834. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  6835. }
  6836. int64 length;
  6837. JavascriptArray * pArr = nullptr;
  6838. RecyclableObject* obj = nullptr;
  6839. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  6840. {
  6841. pArr = JavascriptArray::FromVar(args[0]);
  6842. obj = pArr;
  6843. length = pArr->length;
  6844. }
  6845. else
  6846. {
  6847. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6848. {
  6849. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  6850. }
  6851. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  6852. // Even for arrays, this is now observable via proxies.
  6853. // If source object is not an array, we fall back to this behavior anyway.
  6854. Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
  6855. length = JavascriptConversion::ToLength(lenValue, scriptContext);
  6856. }
  6857. return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
  6858. }
  6859. template <bool findIndex>
  6860. Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  6861. {
  6862. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  6863. {
  6864. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  6865. if (typedArrayBase != nullptr)
  6866. {
  6867. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
  6868. }
  6869. else
  6870. {
  6871. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
  6872. }
  6873. }
  6874. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  6875. Var thisArg;
  6876. if (args.Info.Count > 2)
  6877. {
  6878. thisArg = args[2];
  6879. }
  6880. else
  6881. {
  6882. thisArg = scriptContext->GetLibrary()->GetUndefined();
  6883. }
  6884. // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
  6885. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  6886. {
  6887. typedArrayBase = TypedArrayBase::FromVar(obj);
  6888. }
  6889. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  6890. CallFlags flags = CallFlags_Value;
  6891. Var element = nullptr;
  6892. Var testResult = nullptr;
  6893. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  6894. if (pArr)
  6895. {
  6896. for (uint32 k = 0; k < length; k++)
  6897. {
  6898. element = undefined;
  6899. pArr->DirectGetItemAtFull(k, &element);
  6900. Var index = JavascriptNumber::ToVar(k, scriptContext);
  6901. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  6902. element,
  6903. index,
  6904. pArr);
  6905. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  6906. {
  6907. return findIndex ? index : element;
  6908. }
  6909. }
  6910. }
  6911. else if (typedArrayBase)
  6912. {
  6913. for (uint32 k = 0; k < length; k++)
  6914. {
  6915. element = typedArrayBase->DirectGetItem(k);
  6916. Var index = JavascriptNumber::ToVar(k, scriptContext);
  6917. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  6918. element,
  6919. index,
  6920. typedArrayBase);
  6921. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  6922. {
  6923. return findIndex ? index : element;
  6924. }
  6925. }
  6926. }
  6927. else
  6928. {
  6929. for (uint32 k = 0; k < length; k++)
  6930. {
  6931. element = undefined;
  6932. JavascriptOperators::GetItem(obj, k, &element, scriptContext);
  6933. Var index = JavascriptNumber::ToVar(k, scriptContext);
  6934. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  6935. element,
  6936. index,
  6937. obj);
  6938. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  6939. {
  6940. return findIndex ? index : element;
  6941. }
  6942. }
  6943. }
  6944. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  6945. }
  6946. ///----------------------------------------------------------------------------
  6947. /// FindIndex() calls the given predicate callback on each element of the
  6948. /// array, in order, and returns the index of the first element that makes the
  6949. /// predicate return true, as described in (ES6.0: S22.1.3.9).
  6950. ///----------------------------------------------------------------------------
  6951. Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
  6952. {
  6953. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6954. ARGUMENTS(args, callInfo);
  6955. ScriptContext* scriptContext = function->GetScriptContext();
  6956. Assert(!(callInfo.Flags & CallFlags_New));
  6957. if (args.Info.Count == 0)
  6958. {
  6959. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  6960. }
  6961. int64 length;
  6962. JavascriptArray * pArr = nullptr;
  6963. RecyclableObject* obj = nullptr;
  6964. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  6965. {
  6966. pArr = JavascriptArray::FromVar(args[0]);
  6967. obj = pArr;
  6968. length = pArr->length;
  6969. }
  6970. else
  6971. {
  6972. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6973. {
  6974. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  6975. }
  6976. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  6977. // Even for arrays, this is now observable via proxies.
  6978. // If source object is not an array, we fall back to this behavior anyway.
  6979. Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
  6980. length = JavascriptConversion::ToLength(lenValue, scriptContext);
  6981. }
  6982. return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
  6983. }
  6984. ///----------------------------------------------------------------------------
  6985. /// Entries() returns a new ArrayIterator object configured to return key-
  6986. /// value pairs matching the elements of the this array/array-like object,
  6987. /// as described in (ES6.0: S22.1.3.4).
  6988. ///----------------------------------------------------------------------------
  6989. Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  6990. {
  6991. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6992. ARGUMENTS(args, callInfo);
  6993. ScriptContext* scriptContext = function->GetScriptContext();
  6994. Assert(!(callInfo.Flags & CallFlags_New));
  6995. if (args.Info.Count == 0)
  6996. {
  6997. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  6998. }
  6999. RecyclableObject* thisObj = nullptr;
  7000. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7001. {
  7002. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7003. }
  7004. #if ENABLE_COPYONACCESS_ARRAY
  7005. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7006. #endif
  7007. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue);
  7008. }
  7009. ///----------------------------------------------------------------------------
  7010. /// Keys() returns a new ArrayIterator object configured to return the keys
  7011. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
  7012. ///----------------------------------------------------------------------------
  7013. Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  7014. {
  7015. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7016. ARGUMENTS(args, callInfo);
  7017. ScriptContext* scriptContext = function->GetScriptContext();
  7018. Assert(!(callInfo.Flags & CallFlags_New));
  7019. if (args.Info.Count == 0)
  7020. {
  7021. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7022. }
  7023. RecyclableObject* thisObj = nullptr;
  7024. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7025. {
  7026. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7027. }
  7028. #if ENABLE_COPYONACCESS_ARRAY
  7029. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7030. #endif
  7031. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key);
  7032. }
  7033. ///----------------------------------------------------------------------------
  7034. /// Values() returns a new ArrayIterator object configured to return the values
  7035. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
  7036. ///----------------------------------------------------------------------------
  7037. Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  7038. {
  7039. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7040. ARGUMENTS(args, callInfo);
  7041. ScriptContext* scriptContext = function->GetScriptContext();
  7042. Assert(!(callInfo.Flags & CallFlags_New));
  7043. if (args.Info.Count == 0)
  7044. {
  7045. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7046. }
  7047. RecyclableObject* thisObj = nullptr;
  7048. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7049. {
  7050. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7051. }
  7052. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value);
  7053. }
  7054. Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
  7055. {
  7056. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7057. ARGUMENTS(args, callInfo);
  7058. ScriptContext* scriptContext = function->GetScriptContext();
  7059. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
  7060. Assert(!(callInfo.Flags & CallFlags_New));
  7061. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayEveryCount);
  7062. if (args.Info.Count == 0)
  7063. {
  7064. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7065. }
  7066. BigIndex length;
  7067. JavascriptArray* pArr = nullptr;
  7068. RecyclableObject* obj = nullptr;
  7069. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  7070. {
  7071. pArr = JavascriptArray::FromVar(args[0]);
  7072. obj = pArr;
  7073. }
  7074. else
  7075. {
  7076. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7077. {
  7078. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7079. }
  7080. }
  7081. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  7082. // Even for arrays, this is now observable via proxies.
  7083. // If source object is not an array, we fall back to this behavior anyway.
  7084. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  7085. {
  7086. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  7087. {
  7088. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  7089. }
  7090. else
  7091. {
  7092. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  7093. }
  7094. }
  7095. else
  7096. {
  7097. length = pArr->length;
  7098. }
  7099. if (length.IsSmallIndex())
  7100. {
  7101. return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
  7102. }
  7103. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  7104. return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
  7105. }
  7106. // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
  7107. template <typename T>
  7108. Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7109. {
  7110. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7111. {
  7112. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7113. if (typedArrayBase != nullptr)
  7114. {
  7115. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
  7116. }
  7117. else
  7118. {
  7119. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
  7120. }
  7121. }
  7122. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7123. Var thisArg = nullptr;
  7124. if (args.Info.Count > 2)
  7125. {
  7126. thisArg = args[2];
  7127. }
  7128. else
  7129. {
  7130. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7131. }
  7132. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7133. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7134. {
  7135. typedArrayBase = TypedArrayBase::FromVar(obj);
  7136. }
  7137. Var element = nullptr;
  7138. Var testResult = nullptr;
  7139. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7140. CallFlags flags = CallFlags_Value;
  7141. if (pArr)
  7142. {
  7143. for (uint32 k = 0; k < length; k++)
  7144. {
  7145. if (!pArr->DirectGetItemAtFull(k, &element))
  7146. {
  7147. continue;
  7148. }
  7149. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7150. element,
  7151. JavascriptNumber::ToVar(k, scriptContext),
  7152. pArr);
  7153. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7154. {
  7155. return scriptContext->GetLibrary()->GetFalse();
  7156. }
  7157. }
  7158. }
  7159. else if (typedArrayBase)
  7160. {
  7161. Assert(length <= UINT_MAX);
  7162. for (uint32 k = 0; k < length; k++)
  7163. {
  7164. if (!typedArrayBase->HasItem(k))
  7165. {
  7166. continue;
  7167. }
  7168. element = typedArrayBase->DirectGetItem(k);
  7169. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7170. element,
  7171. JavascriptNumber::ToVar(k, scriptContext),
  7172. typedArrayBase);
  7173. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7174. {
  7175. return scriptContext->GetLibrary()->GetFalse();
  7176. }
  7177. }
  7178. }
  7179. else
  7180. {
  7181. for (T k = 0; k < length; k++)
  7182. {
  7183. // According to es6 spec, we need to call Has first before calling Get
  7184. if (!JavascriptOperators::HasItem(obj, k))
  7185. {
  7186. continue;
  7187. }
  7188. BOOL getResult = JavascriptOperators::GetItem(obj, k, &element, scriptContext);
  7189. Assert(getResult);
  7190. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7191. element,
  7192. JavascriptNumber::ToVar(k, scriptContext),
  7193. obj);
  7194. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7195. {
  7196. return scriptContext->GetLibrary()->GetFalse();
  7197. }
  7198. }
  7199. }
  7200. return scriptContext->GetLibrary()->GetTrue();
  7201. }
  7202. Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
  7203. {
  7204. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7205. ARGUMENTS(args, callInfo);
  7206. ScriptContext* scriptContext = function->GetScriptContext();
  7207. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
  7208. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArraySomeCount);
  7209. Assert(!(callInfo.Flags & CallFlags_New));
  7210. if (args.Info.Count == 0)
  7211. {
  7212. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7213. }
  7214. BigIndex length;
  7215. JavascriptArray* pArr = nullptr;
  7216. RecyclableObject* obj = nullptr;
  7217. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  7218. {
  7219. pArr = JavascriptArray::FromVar(args[0]);
  7220. obj = pArr;
  7221. }
  7222. else
  7223. {
  7224. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7225. {
  7226. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7227. }
  7228. }
  7229. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  7230. // Even for arrays, this is now observable via proxies.
  7231. // If source object is not an array, we fall back to this behavior anyway.
  7232. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  7233. {
  7234. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  7235. {
  7236. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  7237. }
  7238. else
  7239. {
  7240. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  7241. }
  7242. }
  7243. else
  7244. {
  7245. length = pArr->length;
  7246. }
  7247. if (length.IsSmallIndex())
  7248. {
  7249. return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
  7250. }
  7251. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  7252. return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
  7253. }
  7254. // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
  7255. template <typename T>
  7256. Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7257. {
  7258. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7259. {
  7260. // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
  7261. if (typedArrayBase != nullptr)
  7262. {
  7263. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
  7264. }
  7265. else
  7266. {
  7267. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
  7268. }
  7269. }
  7270. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7271. Var thisArg = nullptr;
  7272. if (args.Info.Count > 2)
  7273. {
  7274. thisArg = args[2];
  7275. }
  7276. else
  7277. {
  7278. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7279. }
  7280. // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
  7281. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7282. {
  7283. typedArrayBase = TypedArrayBase::FromVar(obj);
  7284. }
  7285. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7286. CallFlags flags = CallFlags_Value;
  7287. Var element = nullptr;
  7288. Var testResult = nullptr;
  7289. if (pArr)
  7290. {
  7291. for (uint32 k = 0; k < length; k++)
  7292. {
  7293. if (!pArr->DirectGetItemAtFull(k, &element))
  7294. {
  7295. continue;
  7296. }
  7297. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7298. element,
  7299. JavascriptNumber::ToVar(k, scriptContext),
  7300. pArr);
  7301. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7302. {
  7303. return scriptContext->GetLibrary()->GetTrue();
  7304. }
  7305. }
  7306. }
  7307. else if (typedArrayBase)
  7308. {
  7309. Assert(length <= UINT_MAX);
  7310. for (uint32 k = 0; k < length; k++)
  7311. {
  7312. // If k < typedArrayBase->length, we know that HasItem will return true.
  7313. // But we still have to call it in case there's a proxy trap or in the case that we are calling
  7314. // Array.prototype.some with a TypedArray that has a different length instance property.
  7315. if (!typedArrayBase->HasItem(k))
  7316. {
  7317. continue;
  7318. }
  7319. element = typedArrayBase->DirectGetItem(k);
  7320. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7321. element,
  7322. JavascriptNumber::ToVar(k, scriptContext),
  7323. typedArrayBase);
  7324. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7325. {
  7326. return scriptContext->GetLibrary()->GetTrue();
  7327. }
  7328. }
  7329. }
  7330. else
  7331. {
  7332. for (T k = 0; k < length; k++)
  7333. {
  7334. if (!JavascriptOperators::HasItem(obj, k))
  7335. {
  7336. continue;
  7337. }
  7338. BOOL getResult = JavascriptOperators::GetItem(obj, k, &element, scriptContext);
  7339. Assert(getResult);
  7340. testResult = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7341. element,
  7342. JavascriptNumber::ToVar(k, scriptContext),
  7343. obj);
  7344. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7345. {
  7346. return scriptContext->GetLibrary()->GetTrue();
  7347. }
  7348. }
  7349. }
  7350. return scriptContext->GetLibrary()->GetFalse();
  7351. }
  7352. Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
  7353. {
  7354. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7355. ARGUMENTS(args, callInfo);
  7356. ScriptContext* scriptContext = function->GetScriptContext();
  7357. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
  7358. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayForEachCount)
  7359. Assert(!(callInfo.Flags & CallFlags_New));
  7360. if (args.Info.Count == 0)
  7361. {
  7362. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7363. }
  7364. BigIndex length;
  7365. JavascriptArray* pArr = nullptr;
  7366. RecyclableObject* dynamicObject = nullptr;
  7367. RecyclableObject* callBackFn = nullptr;
  7368. Var thisArg = nullptr;
  7369. #if ENABLE_COPYONACCESS_ARRAY
  7370. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  7371. #endif
  7372. if (JavascriptArray::Is(args[0]) && scriptContext == JavascriptArray::FromVar(args[0])->GetScriptContext())
  7373. {
  7374. pArr = JavascriptArray::FromVar(args[0]);
  7375. dynamicObject = pArr;
  7376. }
  7377. else
  7378. {
  7379. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  7380. {
  7381. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7382. }
  7383. if (JavascriptArray::Is(dynamicObject) && scriptContext == JavascriptArray::FromVar(dynamicObject)->GetScriptContext())
  7384. {
  7385. pArr = JavascriptArray::FromVar(dynamicObject);
  7386. }
  7387. }
  7388. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  7389. // Even for arrays, this is now observable via proxies.
  7390. // If source object is not an array, we fall back to this behavior anyway.
  7391. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  7392. {
  7393. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  7394. {
  7395. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  7396. }
  7397. else
  7398. {
  7399. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  7400. }
  7401. }
  7402. else
  7403. {
  7404. length = pArr->length;
  7405. }
  7406. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7407. {
  7408. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
  7409. }
  7410. callBackFn = RecyclableObject::FromVar(args[1]);
  7411. if (args.Info.Count > 2)
  7412. {
  7413. thisArg = args[2];
  7414. }
  7415. else
  7416. {
  7417. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7418. }
  7419. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7420. CallFlags flags = CallFlags_Value;
  7421. auto fn32 = [dynamicObject, callBackFn, flags, thisArg, scriptContext](uint32 k, Var element)
  7422. {
  7423. callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7424. element,
  7425. JavascriptNumber::ToVar(k, scriptContext),
  7426. dynamicObject);
  7427. };
  7428. auto fn64 = [dynamicObject, callBackFn, flags, thisArg, scriptContext](uint64 k, Var element)
  7429. {
  7430. callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  7431. element,
  7432. JavascriptNumber::ToVar(k, scriptContext),
  7433. dynamicObject);
  7434. };
  7435. if (pArr)
  7436. {
  7437. Assert(pArr == dynamicObject);
  7438. pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32);
  7439. }
  7440. else
  7441. {
  7442. if (length.IsSmallIndex())
  7443. {
  7444. TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32);
  7445. }
  7446. else
  7447. {
  7448. TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64);
  7449. }
  7450. }
  7451. return scriptContext->GetLibrary()->GetUndefined();
  7452. }
  7453. Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
  7454. {
  7455. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7456. ARGUMENTS(args, callInfo);
  7457. ScriptContext* scriptContext = function->GetScriptContext();
  7458. Assert(!(callInfo.Flags & CallFlags_New));
  7459. RecyclableObject* obj = nullptr;
  7460. JavascriptArray* pArr = nullptr;
  7461. int64 length;
  7462. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  7463. {
  7464. #if ENABLE_COPYONACCESS_ARRAY
  7465. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  7466. #endif
  7467. pArr = JavascriptArray::FromVar(args[0]);
  7468. obj = pArr;
  7469. length = pArr->length;
  7470. }
  7471. else
  7472. {
  7473. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7474. {
  7475. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.copyWithin"));
  7476. }
  7477. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  7478. // Even for arrays, this is now observable via proxies.
  7479. // If source object is not an array, we fall back to this behavior anyway.
  7480. Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
  7481. length = JavascriptConversion::ToLength(lenValue, scriptContext);
  7482. }
  7483. return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
  7484. }
  7485. // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
  7486. Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7487. {
  7488. Assert(args.Info.Count > 0);
  7489. JavascriptLibrary* library = scriptContext->GetLibrary();
  7490. int64 fromVal = 0;
  7491. int64 toVal = 0;
  7492. int64 finalVal = length;
  7493. // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
  7494. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7495. {
  7496. typedArrayBase = TypedArrayBase::FromVar(obj);
  7497. }
  7498. if (args.Info.Count > 1)
  7499. {
  7500. toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext);
  7501. if (args.Info.Count > 2)
  7502. {
  7503. fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext);
  7504. if (args.Info.Count > 3 && args[3] != library->GetUndefined())
  7505. {
  7506. finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext);
  7507. }
  7508. }
  7509. }
  7510. // If count would be negative or zero, we won't do anything so go ahead and return early.
  7511. if (finalVal <= fromVal || length <= toVal)
  7512. {
  7513. return obj;
  7514. }
  7515. // Make sure we won't underflow during the count calculation
  7516. Assert(finalVal > fromVal && length > toVal);
  7517. int64 count = min(finalVal - fromVal, length - toVal);
  7518. // We shouldn't have made it here if the count was going to be zero
  7519. Assert(count > 0);
  7520. int direction;
  7521. if (fromVal < toVal && toVal < (fromVal + count))
  7522. {
  7523. direction = -1;
  7524. fromVal += count - 1;
  7525. toVal += count - 1;
  7526. }
  7527. else
  7528. {
  7529. direction = 1;
  7530. }
  7531. // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
  7532. // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
  7533. if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
  7534. || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
  7535. {
  7536. while (count > 0)
  7537. {
  7538. Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
  7539. if (JavascriptOperators::OP_HasItem(obj, index, scriptContext))
  7540. {
  7541. Var val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext);
  7542. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  7543. }
  7544. else
  7545. {
  7546. JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
  7547. }
  7548. fromVal += direction;
  7549. toVal += direction;
  7550. count--;
  7551. }
  7552. }
  7553. else
  7554. {
  7555. Assert(fromVal < MaxArrayLength);
  7556. Assert(toVal < MaxArrayLength);
  7557. Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
  7558. uint32 fromIndex = static_cast<uint32>(fromVal);
  7559. uint32 toIndex = static_cast<uint32>(toVal);
  7560. while (count > 0)
  7561. {
  7562. if (obj->HasItem(fromIndex))
  7563. {
  7564. if (typedArrayBase)
  7565. {
  7566. Var val = typedArrayBase->DirectGetItem(fromIndex);
  7567. typedArrayBase->DirectSetItem(toIndex, val, false);
  7568. }
  7569. else if (pArr)
  7570. {
  7571. Var val = pArr->DirectGetItem(fromIndex);
  7572. pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
  7573. }
  7574. else
  7575. {
  7576. Var val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext);
  7577. JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  7578. }
  7579. }
  7580. else
  7581. {
  7582. obj->DeleteItem(toIndex, PropertyOperation_ThrowIfNotExtensible);
  7583. }
  7584. fromIndex += direction;
  7585. toIndex += direction;
  7586. count--;
  7587. }
  7588. }
  7589. return obj;
  7590. }
  7591. Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
  7592. {
  7593. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7594. ARGUMENTS(args, callInfo);
  7595. ScriptContext* scriptContext = function->GetScriptContext();
  7596. Assert(!(callInfo.Flags & CallFlags_New));
  7597. RecyclableObject* obj = nullptr;
  7598. JavascriptArray* pArr = nullptr;
  7599. int64 length;
  7600. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  7601. {
  7602. pArr = JavascriptArray::FromVar(args[0]);
  7603. obj = pArr;
  7604. length = pArr->length;
  7605. }
  7606. else
  7607. {
  7608. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7609. {
  7610. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.fill"));
  7611. }
  7612. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  7613. // Even for arrays, this is now observable via proxies.
  7614. // If source object is not an array, we fall back to this behavior anyway.
  7615. Var lenValue = JavascriptOperators::OP_GetLength(obj, scriptContext);
  7616. length = JavascriptConversion::ToLength(lenValue, scriptContext);
  7617. }
  7618. return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
  7619. }
  7620. // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
  7621. Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7622. {
  7623. Assert(args.Info.Count > 0);
  7624. JavascriptLibrary* library = scriptContext->GetLibrary();
  7625. // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
  7626. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  7627. {
  7628. typedArrayBase = TypedArrayBase::FromVar(obj);
  7629. }
  7630. Var fillValue;
  7631. if (args.Info.Count > 1)
  7632. {
  7633. fillValue = args[1];
  7634. }
  7635. else
  7636. {
  7637. fillValue = library->GetUndefined();
  7638. }
  7639. int64 k = 0;
  7640. int64 finalVal = length;
  7641. if (args.Info.Count > 2)
  7642. {
  7643. k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext);
  7644. if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
  7645. {
  7646. finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext);
  7647. }
  7648. }
  7649. if (k < MaxArrayLength)
  7650. {
  7651. int64 end = min<int64>(finalVal, MaxArrayLength);
  7652. uint32 u32k = static_cast<uint32>(k);
  7653. while (u32k < end)
  7654. {
  7655. if (typedArrayBase)
  7656. {
  7657. typedArrayBase->DirectSetItem(u32k, fillValue, false);
  7658. }
  7659. else if (pArr)
  7660. {
  7661. pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
  7662. }
  7663. else
  7664. {
  7665. JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
  7666. }
  7667. u32k++;
  7668. }
  7669. BigIndex dstIndex = MaxArrayLength;
  7670. for (int64 i = end; i < finalVal; ++i)
  7671. {
  7672. if (pArr)
  7673. {
  7674. pArr->DirectSetItemAt(dstIndex, fillValue);
  7675. ++dstIndex;
  7676. }
  7677. else
  7678. {
  7679. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
  7680. }
  7681. }
  7682. }
  7683. else
  7684. {
  7685. BigIndex dstIndex = static_cast<uint64>(k);
  7686. for (int64 i = k; i < finalVal; i++)
  7687. {
  7688. if (pArr)
  7689. {
  7690. pArr->DirectSetItemAt(dstIndex, fillValue);
  7691. ++dstIndex;
  7692. }
  7693. else
  7694. {
  7695. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible);
  7696. }
  7697. }
  7698. }
  7699. return obj;
  7700. }
  7701. // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
  7702. Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
  7703. {
  7704. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7705. ARGUMENTS(args, callInfo);
  7706. ScriptContext* scriptContext = function->GetScriptContext();
  7707. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
  7708. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayMapCount);
  7709. Assert(!(callInfo.Flags & CallFlags_New));
  7710. if (args.Info.Count == 0)
  7711. {
  7712. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  7713. }
  7714. BigIndex length;
  7715. JavascriptArray* pArr = nullptr;
  7716. RecyclableObject* obj = nullptr;
  7717. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  7718. {
  7719. pArr = JavascriptArray::FromVar(args[0]);
  7720. obj = pArr;
  7721. }
  7722. else
  7723. {
  7724. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7725. {
  7726. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  7727. }
  7728. }
  7729. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  7730. // Even for arrays, this is now observable via proxies.
  7731. // If source object is not an array, we fall back to this behavior anyway.
  7732. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  7733. {
  7734. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  7735. }
  7736. else
  7737. {
  7738. length = pArr->length;
  7739. }
  7740. if (length.IsSmallIndex())
  7741. {
  7742. return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
  7743. }
  7744. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  7745. return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
  7746. }
  7747. template<typename T>
  7748. Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7749. {
  7750. RecyclableObject* newObj = nullptr;
  7751. JavascriptArray* newArr = nullptr;
  7752. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  7753. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7754. {
  7755. if (isTypedArrayEntryPoint)
  7756. {
  7757. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
  7758. }
  7759. else
  7760. {
  7761. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
  7762. }
  7763. }
  7764. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  7765. Var thisArg;
  7766. if (args.Info.Count > 2)
  7767. {
  7768. thisArg = args[2];
  7769. }
  7770. else
  7771. {
  7772. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7773. }
  7774. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7775. if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
  7776. {
  7777. typedArrayBase = TypedArrayBase::FromVar(obj);
  7778. }
  7779. // If the entry point is %TypedArray%.prototype.map or the source object is an Array exotic object we should try to load the constructor property
  7780. // and use it to construct the return object.
  7781. if (isTypedArrayEntryPoint)
  7782. {
  7783. Var constructor = JavascriptOperators::SpeciesConstructor(
  7784. typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext);
  7785. if (JavascriptOperators::IsConstructor(constructor))
  7786. {
  7787. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  7788. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  7789. newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  7790. }
  7791. else if (isTypedArrayEntryPoint)
  7792. {
  7793. // We only need to throw a TypeError when the constructor property is not an actual constructor if %TypedArray%.prototype.map was called
  7794. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("[TypedArray].prototype.map"));
  7795. }
  7796. }
  7797. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  7798. else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
  7799. {
  7800. newObj = ArraySpeciesCreate(obj, length, scriptContext);
  7801. }
  7802. if (newObj == nullptr)
  7803. {
  7804. if (length > UINT_MAX)
  7805. {
  7806. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  7807. }
  7808. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  7809. newArr->EnsureHead<Var>();
  7810. newObj = newArr;
  7811. }
  7812. else
  7813. {
  7814. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  7815. if (JavascriptArray::Is(newObj))
  7816. {
  7817. newArr = JavascriptArray::FromVar(newObj);
  7818. }
  7819. }
  7820. Var element = nullptr;
  7821. Var mappedValue = nullptr;
  7822. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7823. CallFlags callBackFnflags = CallFlags_Value;
  7824. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  7825. // We at least have to have newObj as a valid object
  7826. Assert(newObj);
  7827. if (pArr != nullptr)
  7828. {
  7829. // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
  7830. for (uint32 k = 0; k < length; k++)
  7831. {
  7832. if (!pArr->DirectGetItemAtFull(k, &element))
  7833. {
  7834. continue;
  7835. }
  7836. mappedValue = callBackFn->GetEntryPoint()(callBackFn, callBackFnInfo, thisArg,
  7837. element,
  7838. JavascriptNumber::ToVar(k, scriptContext),
  7839. pArr);
  7840. // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
  7841. if (newArr)
  7842. {
  7843. newArr->DirectSetItemAt(k, mappedValue);
  7844. }
  7845. else
  7846. {
  7847. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue);
  7848. }
  7849. }
  7850. }
  7851. else if (typedArrayBase != nullptr)
  7852. {
  7853. // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
  7854. TypedArrayBase* newTypedArray = nullptr;
  7855. if (TypedArrayBase::Is(newObj))
  7856. {
  7857. newTypedArray = TypedArrayBase::FromVar(newObj);
  7858. }
  7859. for (uint32 k = 0; k < length; k++)
  7860. {
  7861. // We can't rely on the length value being equal to typedArrayBase->GetLength() because user code may lie and
  7862. // attach any length property to a TypedArray instance and pass it as this parameter when .calling
  7863. // Array.prototype.map.
  7864. if (!typedArrayBase->HasItem(k))
  7865. {
  7866. // We know that if HasItem returns false, all the future calls to HasItem will return false as well since
  7867. // we visit the items in order. We could return early here except that we have to continue calling HasItem
  7868. // on all the subsequent items according to the spec.
  7869. continue;
  7870. }
  7871. element = typedArrayBase->DirectGetItem(k);
  7872. mappedValue = callBackFn->GetEntryPoint()(callBackFn, callBackFnInfo, thisArg,
  7873. element,
  7874. JavascriptNumber::ToVar(k, scriptContext),
  7875. obj);
  7876. // If newObj is a TypedArray, set the mappedValue directly, otherwise see if it's an array and finally fall back to
  7877. // the normal Set path.
  7878. if (newTypedArray)
  7879. {
  7880. newTypedArray->DirectSetItem(k, mappedValue, false);
  7881. }
  7882. else if (newArr)
  7883. {
  7884. newArr->DirectSetItemAt(k, mappedValue);
  7885. }
  7886. else
  7887. {
  7888. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue);
  7889. }
  7890. }
  7891. }
  7892. else
  7893. {
  7894. for (uint32 k = 0; k < length; k++)
  7895. {
  7896. if (!JavascriptOperators::HasItem(obj, k))
  7897. {
  7898. continue;
  7899. }
  7900. BOOL getResult = JavascriptOperators::GetItem(obj, k, &element, scriptContext);
  7901. Assert(getResult);
  7902. mappedValue = callBackFn->GetEntryPoint()(callBackFn, callBackFnInfo, thisArg,
  7903. element,
  7904. JavascriptNumber::ToVar(k, scriptContext),
  7905. obj);
  7906. if (newArr)
  7907. {
  7908. newArr->DirectSetItemAt(k, mappedValue);
  7909. }
  7910. else
  7911. {
  7912. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, mappedValue);
  7913. }
  7914. }
  7915. }
  7916. #ifdef VALIDATE_ARRAY
  7917. if (JavascriptArray::Is(newObj))
  7918. {
  7919. newArr->ValidateArray();
  7920. }
  7921. #endif
  7922. return newObj;
  7923. }
  7924. Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
  7925. {
  7926. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7927. ARGUMENTS(args, callInfo);
  7928. ScriptContext* scriptContext = function->GetScriptContext();
  7929. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
  7930. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayFilterCount);
  7931. Assert(!(callInfo.Flags & CallFlags_New));
  7932. if (args.Info.Count == 0)
  7933. {
  7934. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  7935. }
  7936. RecyclableObject* newObj = nullptr;
  7937. JavascriptArray* newArr = nullptr;
  7938. BigIndex length;
  7939. JavascriptArray* pArr = nullptr;
  7940. RecyclableObject* dynamicObject = nullptr;
  7941. RecyclableObject* callBackFn = nullptr;
  7942. Var thisArg = nullptr;
  7943. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  7944. {
  7945. pArr = JavascriptArray::FromVar(args[0]);
  7946. dynamicObject = pArr;
  7947. }
  7948. else
  7949. {
  7950. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  7951. {
  7952. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  7953. }
  7954. }
  7955. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  7956. // Even for arrays, this is now observable via proxies.
  7957. // If source object is not an array, we fall back to this behavior anyway.
  7958. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  7959. {
  7960. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  7961. {
  7962. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  7963. }
  7964. else
  7965. {
  7966. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(dynamicObject, scriptContext), scriptContext);
  7967. }
  7968. }
  7969. else
  7970. {
  7971. length = pArr->length;
  7972. }
  7973. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7974. {
  7975. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
  7976. }
  7977. callBackFn = RecyclableObject::FromVar(args[1]);
  7978. if (args.Info.Count > 2)
  7979. {
  7980. thisArg = args[2];
  7981. }
  7982. else
  7983. {
  7984. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7985. }
  7986. // If the source object is an Array exotic object we should try to load the constructor property and use it to construct the return object.
  7987. newObj = ArraySpeciesCreate(dynamicObject, 0, scriptContext);
  7988. if (newObj == nullptr)
  7989. {
  7990. newArr = scriptContext->GetLibrary()->CreateArray(0);
  7991. newArr->EnsureHead<Var>();
  7992. newObj = newArr;
  7993. }
  7994. else
  7995. {
  7996. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  7997. if (JavascriptArray::Is(newObj))
  7998. {
  7999. newArr = JavascriptArray::FromVar(newObj);
  8000. }
  8001. }
  8002. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8003. CallFlags flags = CallFlags_Value;
  8004. Var element = nullptr;
  8005. Var selected = nullptr;
  8006. BigIndex i = 0u;
  8007. if (pArr)
  8008. {
  8009. uint32 arrayLength = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  8010. // If source was an array object, the return object might be any random object
  8011. for (uint32 k = 0; k < arrayLength; k++)
  8012. {
  8013. if (!pArr->DirectGetItemAtFull(k, &element))
  8014. {
  8015. continue;
  8016. }
  8017. selected = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  8018. element,
  8019. JavascriptNumber::ToVar(k, scriptContext),
  8020. pArr);
  8021. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8022. {
  8023. // Try to fast path if the return object is an array
  8024. if (newArr)
  8025. {
  8026. newArr->DirectSetItemAt(i, element);
  8027. }
  8028. else
  8029. {
  8030. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), i, element);
  8031. }
  8032. ++i;
  8033. }
  8034. }
  8035. }
  8036. else
  8037. {
  8038. for (BigIndex k = 0u; k < length; ++k)
  8039. {
  8040. if (!JavascriptOperators::HasItem(dynamicObject, k.IsSmallIndex() ? k.GetSmallIndex() : k.GetBigIndex()))
  8041. {
  8042. continue;
  8043. }
  8044. BOOL getResult = JavascriptOperators::GetItem(dynamicObject, k.IsSmallIndex() ? k.GetSmallIndex() : k.GetBigIndex(), &element, scriptContext);
  8045. Assert(getResult);
  8046. selected = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 4), thisArg,
  8047. element,
  8048. JavascriptNumber::ToVar(k.IsSmallIndex() ? k.GetSmallIndex() : k.GetBigIndex(), scriptContext),
  8049. dynamicObject);
  8050. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8051. {
  8052. if (newArr)
  8053. {
  8054. newArr->DirectSetItemAt(i, element);
  8055. }
  8056. else
  8057. {
  8058. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), i, element);
  8059. }
  8060. ++i;
  8061. }
  8062. }
  8063. }
  8064. #ifdef VALIDATE_ARRAY
  8065. if (newArr)
  8066. {
  8067. newArr->ValidateArray();
  8068. }
  8069. #endif
  8070. return newObj;
  8071. }
  8072. Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
  8073. {
  8074. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8075. ARGUMENTS(args, callInfo);
  8076. ScriptContext* scriptContext = function->GetScriptContext();
  8077. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
  8078. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayReduceCount);
  8079. Assert(!(callInfo.Flags & CallFlags_New));
  8080. if (args.Info.Count == 0)
  8081. {
  8082. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8083. }
  8084. BigIndex length;
  8085. JavascriptArray * pArr = nullptr;
  8086. RecyclableObject* obj = nullptr;
  8087. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  8088. {
  8089. pArr = JavascriptArray::FromVar(args[0]);
  8090. obj = pArr;
  8091. length = pArr->length;
  8092. }
  8093. else
  8094. {
  8095. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  8096. {
  8097. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8098. }
  8099. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  8100. {
  8101. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  8102. }
  8103. else
  8104. {
  8105. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  8106. }
  8107. }
  8108. if (length.IsSmallIndex())
  8109. {
  8110. return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
  8111. }
  8112. return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
  8113. }
  8114. // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
  8115. template <typename T>
  8116. Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8117. {
  8118. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8119. {
  8120. if (typedArrayBase != nullptr)
  8121. {
  8122. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
  8123. }
  8124. else
  8125. {
  8126. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
  8127. }
  8128. }
  8129. // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
  8130. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8131. {
  8132. typedArrayBase = TypedArrayBase::FromVar(obj);
  8133. }
  8134. T k = 0;
  8135. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8136. Var accumulator = nullptr;
  8137. Var element = nullptr;
  8138. if (args.Info.Count > 2)
  8139. {
  8140. accumulator = args[2];
  8141. }
  8142. else
  8143. {
  8144. if (length == 0)
  8145. {
  8146. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8147. }
  8148. bool bPresent = false;
  8149. if (pArr)
  8150. {
  8151. for (; k < length && bPresent == false; k++)
  8152. {
  8153. if (!pArr->DirectGetItemAtFull((uint32)k, &element))
  8154. {
  8155. continue;
  8156. }
  8157. bPresent = true;
  8158. accumulator = element;
  8159. }
  8160. }
  8161. else if (typedArrayBase)
  8162. {
  8163. Assert(length <= UINT_MAX);
  8164. for (; k < length && bPresent == false; k++)
  8165. {
  8166. if (!typedArrayBase->HasItem((uint32)k))
  8167. {
  8168. continue;
  8169. }
  8170. element = typedArrayBase->DirectGetItem((uint32)k);
  8171. bPresent = true;
  8172. accumulator = element;
  8173. }
  8174. }
  8175. else
  8176. {
  8177. for (; k < length && bPresent == false; k++)
  8178. {
  8179. if (!JavascriptOperators::HasItem(obj, k))
  8180. {
  8181. continue;
  8182. }
  8183. BOOL getResult = JavascriptOperators::GetItem(obj, k, &accumulator, scriptContext);
  8184. Assert(getResult);
  8185. bPresent = true;
  8186. }
  8187. }
  8188. if (bPresent == false)
  8189. {
  8190. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8191. }
  8192. }
  8193. Assert(accumulator);
  8194. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8195. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8196. CallFlags flags = CallFlags_Value;
  8197. if (pArr)
  8198. {
  8199. for (; k < length; k++)
  8200. {
  8201. if (!pArr->DirectGetItemAtFull((uint32)k, &element))
  8202. {
  8203. continue;
  8204. }
  8205. accumulator = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 5), undefinedValue,
  8206. accumulator,
  8207. element,
  8208. JavascriptNumber::ToVar(k, scriptContext),
  8209. pArr);
  8210. }
  8211. }
  8212. else if (typedArrayBase)
  8213. {
  8214. Assert(length <= UINT_MAX);
  8215. for (; k < length; k++)
  8216. {
  8217. if (!typedArrayBase->HasItem((uint32)k))
  8218. {
  8219. continue;
  8220. }
  8221. element = typedArrayBase->DirectGetItem((uint32)k);
  8222. accumulator = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 5), undefinedValue,
  8223. accumulator,
  8224. element,
  8225. JavascriptNumber::ToVar(k, scriptContext),
  8226. typedArrayBase);
  8227. }
  8228. }
  8229. else
  8230. {
  8231. for (; k < length; k++)
  8232. {
  8233. if (!JavascriptOperators::HasItem(obj, k))
  8234. {
  8235. continue;
  8236. }
  8237. BOOL getResult = JavascriptOperators::GetItem(obj, k, &element, scriptContext);
  8238. Assert(getResult);
  8239. accumulator = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 5), undefinedValue,
  8240. accumulator,
  8241. element,
  8242. JavascriptNumber::ToVar(k, scriptContext),
  8243. obj);
  8244. }
  8245. }
  8246. return accumulator;
  8247. }
  8248. Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
  8249. {
  8250. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8251. ARGUMENTS(args, callInfo);
  8252. ScriptContext* scriptContext = function->GetScriptContext();
  8253. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
  8254. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(ArrayReduceRightCount);
  8255. Assert(!(callInfo.Flags & CallFlags_New));
  8256. if (args.Info.Count == 0)
  8257. {
  8258. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8259. }
  8260. BigIndex length;
  8261. JavascriptArray * pArr = nullptr;
  8262. RecyclableObject* obj = nullptr;
  8263. if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
  8264. {
  8265. pArr = JavascriptArray::FromVar(args[0]);
  8266. obj = pArr;
  8267. }
  8268. else
  8269. {
  8270. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  8271. {
  8272. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8273. }
  8274. }
  8275. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  8276. // Even for arrays, this is now observable via proxies.
  8277. // If source object is not an array, we fall back to this behavior anyway.
  8278. if (scriptContext->GetConfig()->IsES6TypedArrayExtensionsEnabled() || pArr == nullptr)
  8279. {
  8280. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  8281. {
  8282. length = (uint64) JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  8283. }
  8284. else
  8285. {
  8286. length = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  8287. }
  8288. }
  8289. else
  8290. {
  8291. length = pArr->length;
  8292. }
  8293. if (length.IsSmallIndex())
  8294. {
  8295. return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext);
  8296. }
  8297. return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext);
  8298. }
  8299. // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
  8300. template <typename T>
  8301. Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8302. {
  8303. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8304. {
  8305. if (typedArrayBase != nullptr)
  8306. {
  8307. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
  8308. }
  8309. else
  8310. {
  8311. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
  8312. }
  8313. }
  8314. // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
  8315. if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
  8316. {
  8317. typedArrayBase = TypedArrayBase::FromVar(obj);
  8318. }
  8319. RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
  8320. Var accumulator = nullptr;
  8321. Var element = nullptr;
  8322. T k = 0;
  8323. T index = 0;
  8324. if (args.Info.Count > 2)
  8325. {
  8326. accumulator = args[2];
  8327. }
  8328. else
  8329. {
  8330. if (length == 0)
  8331. {
  8332. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8333. }
  8334. bool bPresent = false;
  8335. if (pArr)
  8336. {
  8337. for (; k < length && bPresent == false; k++)
  8338. {
  8339. index = length - k - 1;
  8340. if (!pArr->DirectGetItemAtFull((uint32)index, &element))
  8341. {
  8342. continue;
  8343. }
  8344. bPresent = true;
  8345. accumulator = element;
  8346. }
  8347. }
  8348. else if (typedArrayBase)
  8349. {
  8350. Assert(length <= UINT_MAX);
  8351. for (; k < length && bPresent == false; k++)
  8352. {
  8353. index = length - k - 1;
  8354. if (!typedArrayBase->HasItem((uint32)index))
  8355. {
  8356. continue;
  8357. }
  8358. element = typedArrayBase->DirectGetItem((uint32)index);
  8359. bPresent = true;
  8360. accumulator = element;
  8361. }
  8362. }
  8363. else
  8364. {
  8365. for (; k < length && bPresent == false; k++)
  8366. {
  8367. index = length - k - 1;
  8368. if (!JavascriptOperators::HasItem(obj, index))
  8369. {
  8370. continue;
  8371. }
  8372. BOOL getResult = JavascriptOperators::GetItem(obj, index, &accumulator, scriptContext);
  8373. Assert(getResult);
  8374. bPresent = true;
  8375. }
  8376. }
  8377. if (bPresent == false)
  8378. {
  8379. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8380. }
  8381. }
  8382. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8383. CallFlags flags = CallFlags_Value;
  8384. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8385. if (pArr)
  8386. {
  8387. for (; k < length; k++)
  8388. {
  8389. index = length - k - 1;
  8390. if (!pArr->DirectGetItemAtFull((uint32)index, &element))
  8391. {
  8392. continue;
  8393. }
  8394. accumulator = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 5), undefinedValue,
  8395. accumulator,
  8396. element,
  8397. JavascriptNumber::ToVar(index, scriptContext),
  8398. pArr);
  8399. }
  8400. }
  8401. else if (typedArrayBase)
  8402. {
  8403. Assert(length <= UINT_MAX);
  8404. for (; k < length; k++)
  8405. {
  8406. index = length - k - 1;
  8407. if (!typedArrayBase->HasItem((uint32) index))
  8408. {
  8409. continue;
  8410. }
  8411. element = typedArrayBase->DirectGetItem((uint32)index);
  8412. accumulator = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 5), undefinedValue,
  8413. accumulator,
  8414. element,
  8415. JavascriptNumber::ToVar(index, scriptContext),
  8416. typedArrayBase);
  8417. }
  8418. }
  8419. else
  8420. {
  8421. for (; k < length; k++)
  8422. {
  8423. index = length - k - 1;
  8424. if (!JavascriptOperators::HasItem(obj, index))
  8425. {
  8426. continue;
  8427. }
  8428. BOOL getResult = JavascriptOperators::GetItem(obj, index, &element, scriptContext);
  8429. Assert(getResult);
  8430. accumulator = callBackFn->GetEntryPoint()(callBackFn, CallInfo(flags, 5), undefinedValue,
  8431. accumulator,
  8432. element,
  8433. JavascriptNumber::ToVar(index, scriptContext),
  8434. obj);
  8435. }
  8436. }
  8437. return accumulator;
  8438. }
  8439. Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
  8440. {
  8441. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8442. ARGUMENTS(args, callInfo);
  8443. ScriptContext* scriptContext = function->GetScriptContext();
  8444. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
  8445. Assert(!(callInfo.Flags & CallFlags_New));
  8446. JavascriptLibrary* library = scriptContext->GetLibrary();
  8447. RecyclableObject* constructor = nullptr;
  8448. if (JavascriptOperators::IsConstructor(args[0]))
  8449. {
  8450. constructor = RecyclableObject::FromVar(args[0]);
  8451. }
  8452. RecyclableObject* items = nullptr;
  8453. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
  8454. {
  8455. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
  8456. }
  8457. JavascriptArray* itemsArr = nullptr;
  8458. if (JavascriptArray::Is(items))
  8459. {
  8460. #if ENABLE_COPYONACCESS_ARRAY
  8461. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(items);
  8462. #endif
  8463. itemsArr = JavascriptArray::FromVar(items);
  8464. }
  8465. bool mapping = false;
  8466. JavascriptFunction* mapFn = nullptr;
  8467. Var mapFnThisArg = nullptr;
  8468. if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
  8469. {
  8470. if (!JavascriptFunction::Is(args[2]))
  8471. {
  8472. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
  8473. }
  8474. mapFn = JavascriptFunction::FromVar(args[2]);
  8475. if (args.Info.Count >= 4)
  8476. {
  8477. mapFnThisArg = args[3];
  8478. }
  8479. else
  8480. {
  8481. mapFnThisArg = library->GetUndefined();
  8482. }
  8483. mapping = true;
  8484. }
  8485. RecyclableObject* newObj = nullptr;
  8486. JavascriptArray* newArr = nullptr;
  8487. RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */);
  8488. if (iterator != nullptr)
  8489. {
  8490. if (constructor)
  8491. {
  8492. Js::Var constructorArgs[] = { constructor };
  8493. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8494. newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  8495. if (JavascriptArray::Is(newObj))
  8496. {
  8497. newArr = JavascriptArray::FromVar(newObj);
  8498. }
  8499. }
  8500. else
  8501. {
  8502. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8503. newArr->EnsureHead<Var>();
  8504. newObj = newArr;
  8505. }
  8506. Var nextValue;
  8507. uint32 k = 0;
  8508. while (JavascriptOperators::IteratorStepAndValue(iterator, scriptContext, &nextValue))
  8509. {
  8510. if (mapping)
  8511. {
  8512. Assert(mapFn != nullptr);
  8513. Assert(mapFnThisArg != nullptr);
  8514. Js::Var mapFnArgs[] = { mapFnThisArg, nextValue, JavascriptNumber::ToVar(k, scriptContext) };
  8515. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8516. nextValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
  8517. }
  8518. if (newArr)
  8519. {
  8520. newArr->DirectSetItemAt(k, nextValue);
  8521. }
  8522. else
  8523. {
  8524. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, nextValue);
  8525. }
  8526. k++;
  8527. }
  8528. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
  8529. }
  8530. else
  8531. {
  8532. Var lenValue = JavascriptOperators::OP_GetLength(items, scriptContext);
  8533. int64 len = JavascriptConversion::ToLength(lenValue, scriptContext);
  8534. if (constructor)
  8535. {
  8536. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8537. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8538. newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  8539. if (JavascriptArray::Is(newObj))
  8540. {
  8541. newArr = JavascriptArray::FromVar(newObj);
  8542. }
  8543. }
  8544. else
  8545. {
  8546. // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
  8547. if (len > MaxArrayLength)
  8548. {
  8549. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
  8550. }
  8551. // Static cast len should be valid (len < 2^32) or we would throw above
  8552. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
  8553. newArr->EnsureHead<Var>();
  8554. newObj = newArr;
  8555. }
  8556. uint32 k = 0;
  8557. for ( ; k < len; k++)
  8558. {
  8559. Var kValue;
  8560. if (itemsArr)
  8561. {
  8562. kValue = itemsArr->DirectGetItem(k);
  8563. }
  8564. else
  8565. {
  8566. kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext);
  8567. }
  8568. if (mapping)
  8569. {
  8570. Assert(mapFn != nullptr);
  8571. Assert(mapFnThisArg != nullptr);
  8572. Js::Var mapFnArgs[] = { mapFnThisArg, kValue, JavascriptNumber::ToVar(k, scriptContext) };
  8573. Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
  8574. kValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
  8575. }
  8576. if (newArr)
  8577. {
  8578. newArr->DirectSetItemAt(k, kValue);
  8579. }
  8580. else
  8581. {
  8582. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue);
  8583. }
  8584. }
  8585. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
  8586. }
  8587. return newObj;
  8588. }
  8589. Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
  8590. {
  8591. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8592. ARGUMENTS(args, callInfo);
  8593. ScriptContext* scriptContext = function->GetScriptContext();
  8594. Assert(!(callInfo.Flags & CallFlags_New));
  8595. if (args.Info.Count == 0)
  8596. {
  8597. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
  8598. }
  8599. return JavascriptArray::OfHelper(false, args, scriptContext);
  8600. }
  8601. Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  8602. {
  8603. ARGUMENTS(args, callInfo);
  8604. Assert(args.Info.Count > 0);
  8605. return args[0];
  8606. }
  8607. // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
  8608. Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
  8609. {
  8610. Assert(args.Info.Count > 0);
  8611. // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
  8612. uint32 len = args.Info.Count - 1;
  8613. Var newObj = nullptr;
  8614. JavascriptArray* newArr = nullptr;
  8615. TypedArrayBase* newTypedArray = nullptr;
  8616. if (JavascriptOperators::IsConstructor(args[0]))
  8617. {
  8618. RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
  8619. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  8620. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8621. newObj = JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext);
  8622. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8623. if (JavascriptArray::Is(newObj))
  8624. {
  8625. newArr = JavascriptArray::FromVar(newObj);
  8626. }
  8627. else if (TypedArrayBase::Is(newObj))
  8628. {
  8629. newTypedArray = TypedArrayBase::FromVar(newObj);
  8630. }
  8631. }
  8632. else
  8633. {
  8634. // We only throw when the constructor property is not a constructor function in the TypedArray version
  8635. if (isTypedArrayEntryPoint)
  8636. {
  8637. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
  8638. }
  8639. newArr = scriptContext->GetLibrary()->CreateArray(len);
  8640. newArr->EnsureHead<Var>();
  8641. newObj = newArr;
  8642. }
  8643. // At least we have a new object of some kind
  8644. Assert(newObj);
  8645. if (newArr)
  8646. {
  8647. for (uint32 k = 0; k < len; k++)
  8648. {
  8649. Var kValue = args[k + 1];
  8650. newArr->DirectSetItemAt(k, kValue);
  8651. }
  8652. }
  8653. else if (newTypedArray)
  8654. {
  8655. for (uint32 k = 0; k < len; k++)
  8656. {
  8657. Var kValue = args[k + 1];
  8658. newTypedArray->DirectSetItem(k, kValue, false);
  8659. }
  8660. }
  8661. else
  8662. {
  8663. for (uint32 k = 0; k < len; k++)
  8664. {
  8665. Var kValue = args[k + 1];
  8666. JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue);
  8667. }
  8668. }
  8669. if (!isTypedArrayEntryPoint)
  8670. {
  8671. // Set length if we are in the Array version of the function
  8672. JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible);
  8673. }
  8674. return newObj;
  8675. }
  8676. JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
  8677. {
  8678. TypeId typeId = JavascriptOperators::GetTypeId(value);
  8679. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  8680. {
  8681. return scriptContext->GetLibrary()->GetEmptyString();
  8682. }
  8683. else
  8684. {
  8685. return JavascriptConversion::ToLocaleString(value, scriptContext);
  8686. }
  8687. }
  8688. inline BOOL JavascriptArray::IsFullArray() const
  8689. {
  8690. if (head && head->length == length)
  8691. {
  8692. AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
  8693. return true;
  8694. }
  8695. return (0 == length);
  8696. }
  8697. /*
  8698. * IsFillFromPrototypes
  8699. * - Check the array has no missing values and only head segment.
  8700. * - Also ensure if the lengths match.
  8701. */
  8702. bool JavascriptArray::IsFillFromPrototypes()
  8703. {
  8704. return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
  8705. }
  8706. // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
  8707. // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
  8708. void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
  8709. {
  8710. if (startIndex >= limitIndex)
  8711. {
  8712. return;
  8713. }
  8714. RecyclableObject* prototype = this->GetPrototype();
  8715. // Fill all missing values by walking through prototype
  8716. while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  8717. {
  8718. ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
  8719. this->SetItem(index, value, PropertyOperation_None);
  8720. });
  8721. prototype = prototype->GetPrototype();
  8722. }
  8723. #ifdef VALIDATE_ARRAY
  8724. ValidateArray();
  8725. #endif
  8726. }
  8727. //
  8728. // JavascriptArray requires head->left == 0 for fast path Get.
  8729. //
  8730. template<typename T>
  8731. void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
  8732. {
  8733. if (head == nullptr || head->left != 0)
  8734. {
  8735. // This is used to fix up altered arrays.
  8736. // any SegmentMap would be invalid at this point.
  8737. ClearSegmentMap();
  8738. //
  8739. // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
  8740. // some protection here. Save the head and switch this array to EmptySegment. Will be restored
  8741. // correctly if allocating new segment succeeds.
  8742. //
  8743. SparseArraySegment<T>* savedHead = (SparseArraySegment<T>*)this->head;
  8744. SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  8745. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
  8746. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
  8747. newSeg->next = savedHead;
  8748. this->head = newSeg;
  8749. SetHasNoMissingValues();
  8750. this->SetLastUsedSegment(savedLastUsedSegment);
  8751. }
  8752. }
  8753. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  8754. void JavascriptArray::CheckForceES5Array()
  8755. {
  8756. if (Configuration::Global.flags.ForceES5Array)
  8757. {
  8758. // There's a bad interaction with the jitted code for native array creation here.
  8759. // ForceES5Array doesn't interact well with native arrays
  8760. if (PHASE_OFF1(NativeArrayPhase))
  8761. {
  8762. GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
  8763. }
  8764. }
  8765. }
  8766. #endif
  8767. template <typename Fn>
  8768. void JavascriptArray::ForEachOwnArrayIndexOfObject(RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, Fn fn)
  8769. {
  8770. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  8771. JavascriptArray* arr = nullptr;
  8772. if (DynamicObject::IsAnyArray(obj))
  8773. {
  8774. arr = JavascriptArray::FromAnyArray(obj);
  8775. }
  8776. else if (DynamicType::Is(obj->GetTypeId()))
  8777. {
  8778. DynamicObject* dynobj = DynamicObject::FromVar(obj);
  8779. arr = dynobj->GetObjectArray();
  8780. }
  8781. if (arr != nullptr)
  8782. {
  8783. if (JavascriptArray::Is(arr))
  8784. {
  8785. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  8786. while(e.MoveNext<Var>())
  8787. {
  8788. fn(e.GetIndex(), e.GetItem<Var>());
  8789. }
  8790. }
  8791. else
  8792. {
  8793. ScriptContext* scriptContext = obj->GetScriptContext();
  8794. Assert(ES5Array::Is(arr));
  8795. ES5Array* es5Array = ES5Array::FromVar(arr);
  8796. ES5ArrayIndexEnumerator<true> e(es5Array);
  8797. while (e.MoveNext())
  8798. {
  8799. uint32 index = e.GetIndex();
  8800. if (index < startIndex) continue;
  8801. else if (index >= limitIndex) break;
  8802. Var value;
  8803. BOOL success = JavascriptOperators::GetOwnItem(es5Array, index, &value, scriptContext);
  8804. Assert(success);
  8805. fn(index, value);
  8806. }
  8807. }
  8808. }
  8809. }
  8810. template <typename T, typename Fn>
  8811. void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, T destIndex, Fn fn)
  8812. {
  8813. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  8814. Var oldValue;
  8815. JavascriptArray* arr = nullptr;
  8816. if (DynamicObject::IsAnyArray(obj))
  8817. {
  8818. arr = JavascriptArray::FromAnyArray(obj);
  8819. }
  8820. else if (DynamicType::Is(obj->GetTypeId()))
  8821. {
  8822. DynamicObject* dynobj = DynamicObject::FromVar(obj);
  8823. ArrayObject* objectArray = dynobj->GetObjectArray();
  8824. arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::FromAnyArray(objectArray) : nullptr;
  8825. }
  8826. if (arr != nullptr)
  8827. {
  8828. if (JavascriptArray::Is(arr))
  8829. {
  8830. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  8831. while(e.MoveNext<Var>())
  8832. {
  8833. uint32 index = e.GetIndex();
  8834. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  8835. {
  8836. T n = destIndex + (index - startIndex);
  8837. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  8838. {
  8839. fn(index, e.GetItem<Var>());
  8840. }
  8841. }
  8842. }
  8843. }
  8844. else
  8845. {
  8846. ScriptContext* scriptContext = obj->GetScriptContext();
  8847. Assert(ES5Array::Is(arr));
  8848. ES5Array* es5Array = ES5Array::FromVar(arr);
  8849. ES5ArrayIndexEnumerator<true> e(es5Array);
  8850. while (e.MoveNext())
  8851. {
  8852. uint32 index = e.GetIndex();
  8853. if (index < startIndex) continue;
  8854. else if (index >= limitIndex) break;
  8855. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  8856. {
  8857. T n = destIndex + (index - startIndex);
  8858. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  8859. {
  8860. Var value;
  8861. BOOL success = JavascriptOperators::GetOwnItem(es5Array, index, &value, scriptContext);
  8862. Assert(success);
  8863. fn(index, value);
  8864. }
  8865. }
  8866. }
  8867. }
  8868. }
  8869. }
  8870. //
  8871. // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
  8872. //
  8873. JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
  8874. : start(start), end(min(end, arr->length))
  8875. {
  8876. Init(arr);
  8877. }
  8878. //
  8879. // Initialize this enumerator and prepare for the first MoveNext.
  8880. //
  8881. void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
  8882. {
  8883. // Find start segment
  8884. seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
  8885. while (seg && (seg->left + seg->length <= start))
  8886. {
  8887. seg = seg->next;
  8888. }
  8889. // Set start index and endIndex
  8890. if (seg)
  8891. {
  8892. if (seg->left >= end)
  8893. {
  8894. seg = nullptr;
  8895. }
  8896. else
  8897. {
  8898. // set index to be at target index - 1, so MoveNext will move to target
  8899. index = max(seg->left, start) - seg->left - 1;
  8900. endIndex = min(end - seg->left, seg->length);
  8901. }
  8902. }
  8903. }
  8904. //
  8905. // Move to the next element if available.
  8906. //
  8907. template<typename T>
  8908. inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
  8909. {
  8910. while (seg)
  8911. {
  8912. // Look for next non-null item in current segment
  8913. while (++index < endIndex)
  8914. {
  8915. if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
  8916. {
  8917. return true;
  8918. }
  8919. }
  8920. // Move to next segment
  8921. seg = seg->next;
  8922. if (seg)
  8923. {
  8924. if (seg->left >= end)
  8925. {
  8926. seg = nullptr;
  8927. break;
  8928. }
  8929. else
  8930. {
  8931. index = static_cast<uint32>(-1);
  8932. endIndex = min(end - seg->left, seg->length);
  8933. }
  8934. }
  8935. }
  8936. return false;
  8937. }
  8938. //
  8939. // Get current array element index.
  8940. //
  8941. uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
  8942. {
  8943. Assert(seg && index < seg->length && index < endIndex);
  8944. return seg->left + index;
  8945. }
  8946. //
  8947. // Get current array element value.
  8948. //
  8949. template<typename T>
  8950. T JavascriptArray::ArrayElementEnumerator::GetItem() const
  8951. {
  8952. Assert(seg && index < seg->length && index < endIndex &&
  8953. !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
  8954. return ((SparseArraySegment<T>*)seg)->elements[index];
  8955. }
  8956. //
  8957. // Construct a BigIndex initialized to a given uint32 (small index).
  8958. //
  8959. JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
  8960. : index(initIndex), bigIndex(InvalidIndex)
  8961. {
  8962. //ok if initIndex == InvalidIndex
  8963. }
  8964. //
  8965. // Construct a BigIndex initialized to a given uint64 (large or small index).
  8966. //
  8967. JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
  8968. : index(InvalidIndex), bigIndex(initIndex)
  8969. {
  8970. if (bigIndex < InvalidIndex) // if it's actually small index
  8971. {
  8972. index = static_cast<uint32>(bigIndex);
  8973. bigIndex = InvalidIndex;
  8974. }
  8975. }
  8976. bool JavascriptArray::BigIndex::IsUint32Max() const
  8977. {
  8978. return index == InvalidIndex && bigIndex == InvalidIndex;
  8979. }
  8980. bool JavascriptArray::BigIndex::IsSmallIndex() const
  8981. {
  8982. return index < InvalidIndex;
  8983. }
  8984. uint32 JavascriptArray::BigIndex::GetSmallIndex() const
  8985. {
  8986. Assert(IsSmallIndex());
  8987. return index;
  8988. }
  8989. uint64 JavascriptArray::BigIndex::GetBigIndex() const
  8990. {
  8991. Assert(!IsSmallIndex());
  8992. return bigIndex;
  8993. }
  8994. //
  8995. // Convert this index value to a JS number
  8996. //
  8997. Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
  8998. {
  8999. if (IsSmallIndex())
  9000. {
  9001. return small_index::ToNumber(index, scriptContext);
  9002. }
  9003. else
  9004. {
  9005. return JavascriptNumber::ToVar(bigIndex, scriptContext);
  9006. }
  9007. }
  9008. //
  9009. // Increment this index by 1.
  9010. //
  9011. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
  9012. {
  9013. if (IsSmallIndex())
  9014. {
  9015. ++index;
  9016. // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
  9017. }
  9018. else
  9019. {
  9020. bigIndex = bigIndex + 1;
  9021. }
  9022. return *this;
  9023. }
  9024. //
  9025. // Decrement this index by 1.
  9026. //
  9027. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
  9028. {
  9029. if (IsSmallIndex())
  9030. {
  9031. --index;
  9032. }
  9033. else
  9034. {
  9035. Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
  9036. --bigIndex;
  9037. if (bigIndex < InvalidIndex)
  9038. {
  9039. index = InvalidIndex - 1;
  9040. bigIndex = InvalidIndex;
  9041. }
  9042. }
  9043. return *this;
  9044. }
  9045. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
  9046. {
  9047. if (delta.IsSmallIndex())
  9048. {
  9049. return operator+(delta.GetSmallIndex());
  9050. }
  9051. if (IsSmallIndex())
  9052. {
  9053. return index + delta.GetBigIndex();
  9054. }
  9055. return bigIndex + delta.GetBigIndex();
  9056. }
  9057. //
  9058. // Get a new BigIndex representing this + delta.
  9059. //
  9060. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
  9061. {
  9062. if (IsSmallIndex())
  9063. {
  9064. uint32 newIndex;
  9065. if (UInt32Math::Add(index, delta, &newIndex))
  9066. {
  9067. return static_cast<uint64>(index) + static_cast<uint64>(delta);
  9068. }
  9069. else
  9070. {
  9071. return newIndex; // ok if newIndex == InvalidIndex
  9072. }
  9073. }
  9074. else
  9075. {
  9076. return bigIndex + static_cast<uint64>(delta);
  9077. }
  9078. }
  9079. bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
  9080. {
  9081. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9082. {
  9083. return this->GetSmallIndex() == rhs.GetSmallIndex();
  9084. }
  9085. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9086. {
  9087. // if lhs is big promote rhs
  9088. return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
  9089. }
  9090. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9091. {
  9092. // if rhs is big promote lhs
  9093. return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
  9094. }
  9095. return this->GetBigIndex() == rhs.GetBigIndex();
  9096. }
  9097. bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
  9098. {
  9099. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9100. {
  9101. return this->GetSmallIndex() > rhs.GetSmallIndex();
  9102. }
  9103. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9104. {
  9105. // if lhs is big promote rhs
  9106. return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
  9107. }
  9108. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9109. {
  9110. // if rhs is big promote lhs
  9111. return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
  9112. }
  9113. return this->GetBigIndex() > rhs.GetBigIndex();
  9114. }
  9115. bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
  9116. {
  9117. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9118. {
  9119. return this->GetSmallIndex() < rhs.GetSmallIndex();
  9120. }
  9121. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9122. {
  9123. // if lhs is big promote rhs
  9124. return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
  9125. }
  9126. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9127. {
  9128. // if rhs is big promote lhs
  9129. return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
  9130. }
  9131. return this->GetBigIndex() < rhs.GetBigIndex();
  9132. }
  9133. bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
  9134. {
  9135. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9136. {
  9137. return this->GetSmallIndex() <= rhs.GetSmallIndex();
  9138. }
  9139. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9140. {
  9141. // if lhs is big promote rhs
  9142. return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
  9143. }
  9144. else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
  9145. {
  9146. // if rhs is big promote lhs
  9147. return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
  9148. }
  9149. return this->GetBigIndex() <= rhs.GetBigIndex();
  9150. }
  9151. bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
  9152. {
  9153. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9154. {
  9155. return this->GetSmallIndex() >= rhs.GetSmallIndex();
  9156. }
  9157. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9158. {
  9159. // if lhs is big promote rhs
  9160. return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
  9161. }
  9162. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9163. {
  9164. // if rhs is big promote lhs
  9165. return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
  9166. }
  9167. return this->GetBigIndex() >= rhs.GetBigIndex();
  9168. }
  9169. BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
  9170. {
  9171. if (IsSmallIndex())
  9172. {
  9173. return small_index::GetItem(arr, index, outVal);
  9174. }
  9175. else
  9176. {
  9177. ScriptContext* scriptContext = arr->GetScriptContext();
  9178. PropertyRecord const * propertyRecord;
  9179. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9180. return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
  9181. }
  9182. }
  9183. BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
  9184. {
  9185. if (IsSmallIndex())
  9186. {
  9187. return small_index::SetItem(arr, index, newValue);
  9188. }
  9189. else
  9190. {
  9191. ScriptContext* scriptContext = arr->GetScriptContext();
  9192. PropertyRecord const * propertyRecord;
  9193. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9194. return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
  9195. }
  9196. }
  9197. void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
  9198. {
  9199. if (IsSmallIndex())
  9200. {
  9201. small_index::SetItemIfNotExist(arr, index, newValue);
  9202. }
  9203. else
  9204. {
  9205. ScriptContext* scriptContext = arr->GetScriptContext();
  9206. PropertyRecord const * propertyRecord;
  9207. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9208. Var oldValue;
  9209. PropertyId propertyId = propertyRecord->GetPropertyId();
  9210. if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
  9211. {
  9212. arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  9213. }
  9214. }
  9215. }
  9216. BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
  9217. {
  9218. if (IsSmallIndex())
  9219. {
  9220. return small_index::DeleteItem(arr, index);
  9221. }
  9222. else
  9223. {
  9224. ScriptContext* scriptContext = arr->GetScriptContext();
  9225. PropertyRecord const * propertyRecord;
  9226. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9227. return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
  9228. }
  9229. }
  9230. BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
  9231. {
  9232. if (IsSmallIndex())
  9233. {
  9234. return small_index::SetItem(obj, index, newValue, flags);
  9235. }
  9236. else
  9237. {
  9238. ScriptContext* scriptContext = obj->GetScriptContext();
  9239. PropertyRecord const * propertyRecord;
  9240. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9241. return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
  9242. }
  9243. }
  9244. BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
  9245. {
  9246. if (IsSmallIndex())
  9247. {
  9248. return small_index::DeleteItem(obj, index, flags);
  9249. }
  9250. else
  9251. {
  9252. PropertyRecord const * propertyRecord;
  9253. JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
  9254. return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
  9255. }
  9256. }
  9257. //
  9258. // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
  9259. //
  9260. void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
  9261. {
  9262. Assert(!dstIndex.IsSmallIndex());
  9263. typedef IndexTrace<BigIndex> index_trace;
  9264. BigIndex dst = dstIndex;
  9265. uint32 i = start;
  9266. ArrayElementEnumerator e(this, start);
  9267. while(e.MoveNext<Var>())
  9268. {
  9269. // delete all items not enumerated
  9270. while (i < e.GetIndex())
  9271. {
  9272. index_trace::DeleteItem(this, dst);
  9273. ++i;
  9274. ++dst;
  9275. }
  9276. // Copy over the item
  9277. index_trace::SetItem(this, dst, e.GetItem<Var>());
  9278. ++i;
  9279. ++dst;
  9280. }
  9281. // Delete the rest till length
  9282. while (i < this->length)
  9283. {
  9284. index_trace::DeleteItem(this, dst);
  9285. ++i;
  9286. ++dst;
  9287. }
  9288. // Elements moved, truncate the array at start
  9289. SetLength(start);
  9290. }
  9291. //
  9292. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
  9293. //
  9294. template<typename T>
  9295. void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9296. {
  9297. Assert(start < end && end <= srcArray->length);
  9298. uint32 count = 0;
  9299. // iterate on the array itself
  9300. ArrayElementEnumerator e(srcArray, start, end);
  9301. while(e.MoveNext<Var>())
  9302. {
  9303. T n = dstIndex + (e.GetIndex() - start);
  9304. dstArray->DirectSetItemAt(n, e.GetItem<Var>());
  9305. count++;
  9306. }
  9307. // iterate on the array's prototypes only if not all elements found
  9308. if (start + count != end)
  9309. {
  9310. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9311. }
  9312. }
  9313. //
  9314. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index. If the index grows larger than
  9315. // "array index", it will automatically turn to SetProperty using the index as property name.
  9316. //
  9317. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9318. {
  9319. end = min(end, srcArray->length);
  9320. if (start < end)
  9321. {
  9322. uint32 len = end - start;
  9323. if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
  9324. {
  9325. // Won't overflow, use faster small_index version
  9326. InternalCopyArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
  9327. }
  9328. else
  9329. {
  9330. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9331. }
  9332. }
  9333. }
  9334. //
  9335. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9336. //
  9337. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9338. {
  9339. end = min(end, srcArray->length);
  9340. if (start < end)
  9341. {
  9342. Assert(end - start <= MaxArrayLength - dstIndex);
  9343. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9344. }
  9345. }
  9346. template <typename T>
  9347. void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9348. {
  9349. #if ENABLE_COPYONACCESS_ARRAY
  9350. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
  9351. #endif
  9352. #if ENABLE_COPYONACCESS_ARRAY
  9353. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
  9354. #endif
  9355. if (JavascriptNativeIntArray::Is(srcArray))
  9356. {
  9357. CopyNativeIntArrayElementsToVar(dstArray, dstIndex, JavascriptNativeIntArray::FromVar(srcArray), start, end);
  9358. }
  9359. else if (JavascriptNativeFloatArray::Is(srcArray))
  9360. {
  9361. CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, JavascriptNativeFloatArray::FromVar(srcArray), start, end);
  9362. }
  9363. else
  9364. {
  9365. CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9366. }
  9367. }
  9368. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9369. {
  9370. end = min(end, srcArray->length);
  9371. if (start < end)
  9372. {
  9373. uint32 len = end - start;
  9374. if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
  9375. {
  9376. // Won't overflow, use faster small_index version
  9377. InternalCopyNativeIntArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
  9378. }
  9379. else
  9380. {
  9381. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9382. }
  9383. }
  9384. }
  9385. //
  9386. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9387. //
  9388. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9389. {
  9390. end = min(end, srcArray->length);
  9391. if (start < end)
  9392. {
  9393. Assert(end - start <= MaxArrayLength - dstIndex);
  9394. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9395. }
  9396. }
  9397. bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9398. {
  9399. end = min(end, srcArray->length);
  9400. if (start >= end)
  9401. {
  9402. return false;
  9403. }
  9404. Assert(end - start <= MaxArrayLength - dstIndex);
  9405. Assert(start < end && end <= srcArray->length);
  9406. uint32 count = 0;
  9407. // iterate on the array itself
  9408. ArrayElementEnumerator e(srcArray, start, end);
  9409. while(e.MoveNext<int32>())
  9410. {
  9411. uint n = dstIndex + (e.GetIndex() - start);
  9412. dstArray->DirectSetItemAt(n, e.GetItem<int32>());
  9413. count++;
  9414. }
  9415. // iterate on the array's prototypes only if not all elements found
  9416. if (start + count != end)
  9417. {
  9418. JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
  9419. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9420. return true;
  9421. }
  9422. return false;
  9423. }
  9424. bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9425. {
  9426. end = min(end, srcArray->length);
  9427. if (start >= end)
  9428. {
  9429. return false;
  9430. }
  9431. Assert(end - start <= MaxArrayLength - dstIndex);
  9432. Assert(start < end && end <= srcArray->length);
  9433. uint32 count = 0;
  9434. // iterate on the array itself
  9435. ArrayElementEnumerator e(srcArray, start, end);
  9436. while(e.MoveNext<int32>())
  9437. {
  9438. uint n = dstIndex + (e.GetIndex() - start);
  9439. dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
  9440. count++;
  9441. }
  9442. // iterate on the array's prototypes only if not all elements found
  9443. if (start + count != end)
  9444. {
  9445. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9446. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9447. return true;
  9448. }
  9449. return false;
  9450. }
  9451. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9452. {
  9453. end = min(end, srcArray->length);
  9454. if (start < end)
  9455. {
  9456. uint32 len = end - start;
  9457. if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
  9458. {
  9459. // Won't overflow, use faster small_index version
  9460. InternalCopyNativeFloatArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
  9461. }
  9462. else
  9463. {
  9464. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9465. }
  9466. }
  9467. }
  9468. //
  9469. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9470. //
  9471. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9472. {
  9473. end = min(end, srcArray->length);
  9474. if (start < end)
  9475. {
  9476. Assert(end - start <= MaxArrayLength - dstIndex);
  9477. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9478. }
  9479. }
  9480. bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9481. {
  9482. end = min(end, srcArray->length);
  9483. if (start >= end)
  9484. {
  9485. return false;
  9486. }
  9487. Assert(end - start <= MaxArrayLength - dstIndex);
  9488. Assert(start < end && end <= srcArray->length);
  9489. uint32 count = 0;
  9490. // iterate on the array itself
  9491. ArrayElementEnumerator e(srcArray, start, end);
  9492. while(e.MoveNext<double>())
  9493. {
  9494. uint n = dstIndex + (e.GetIndex() - start);
  9495. dstArray->DirectSetItemAt(n, e.GetItem<double>());
  9496. count++;
  9497. }
  9498. // iterate on the array's prototypes only if not all elements found
  9499. if (start + count != end)
  9500. {
  9501. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9502. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9503. return true;
  9504. }
  9505. return false;
  9506. }
  9507. JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
  9508. {
  9509. if (JavascriptNativeIntArray::Is(arr))
  9510. {
  9511. arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
  9512. }
  9513. else if (JavascriptNativeFloatArray::Is(arr))
  9514. {
  9515. arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
  9516. }
  9517. return arr;
  9518. }
  9519. BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9520. {
  9521. ScriptContext* requestContext = type->GetScriptContext();
  9522. if (JavascriptNativeIntArray::GetItem(this, index, outVal, requestContext))
  9523. {
  9524. return TRUE;
  9525. }
  9526. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9527. }
  9528. BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  9529. {
  9530. ScriptContext* requestContext = type->GetScriptContext();
  9531. if (JavascriptNativeFloatArray::GetItem(this, index, outVal, requestContext))
  9532. {
  9533. return TRUE;
  9534. }
  9535. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  9536. }
  9537. template<typename T>
  9538. void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9539. {
  9540. Assert(start < end && end <= srcArray->length);
  9541. uint32 count = 0;
  9542. // iterate on the array itself
  9543. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9544. ArrayElementEnumerator e(srcArray, start, end);
  9545. while(e.MoveNext<int32>())
  9546. {
  9547. T n = dstIndex + (e.GetIndex() - start);
  9548. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
  9549. count++;
  9550. }
  9551. // iterate on the array's prototypes only if not all elements found
  9552. if (start + count != end)
  9553. {
  9554. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9555. }
  9556. }
  9557. template<typename T>
  9558. void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9559. {
  9560. Assert(start < end && end <= srcArray->length);
  9561. uint32 count = 0;
  9562. // iterate on the array itself
  9563. ScriptContext *scriptContext = dstArray->GetScriptContext();
  9564. ArrayElementEnumerator e(srcArray, start, end);
  9565. while(e.MoveNext<double>())
  9566. {
  9567. T n = dstIndex + (e.GetIndex() - start);
  9568. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
  9569. count++;
  9570. }
  9571. // iterate on the array's prototypes only if not all elements found
  9572. if (start + count != end)
  9573. {
  9574. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9575. }
  9576. }
  9577. template<typename T>
  9578. void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, const T& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
  9579. {
  9580. RecyclableObject* prototype = srcArray->GetPrototype();
  9581. while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  9582. {
  9583. ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
  9584. T n = dstIndex + (index - start);
  9585. dstArray->DirectSetItemAt(n, value);
  9586. count++;
  9587. });
  9588. prototype = prototype->GetPrototype();
  9589. }
  9590. }
  9591. Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  9592. {
  9593. // At this stage we have an array literal with some arguments to be spread.
  9594. // First we need to calculate the real size of the final literal.
  9595. #if ENABLE_COPYONACCESS_ARRAY
  9596. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
  9597. #endif
  9598. JavascriptArray *array = FromVar(arrayToSpread);
  9599. uint32 actualLength = array->GetLength();
  9600. for (unsigned i = 0; i < spreadIndices->count; ++i)
  9601. {
  9602. actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext));
  9603. }
  9604. JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
  9605. // Now we copy each element and expand the spread parameters inline.
  9606. for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < array->GetLength() && resultIndex < actualLength; ++i)
  9607. {
  9608. uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
  9609. // An array needs a slow copy if it is a cross-site object or we have missing values that need to be set to undefined.
  9610. auto needArraySlowCopy = [&](Var instance) {
  9611. if (JavascriptArray::Is(instance))
  9612. {
  9613. JavascriptArray *arr = JavascriptArray::FromVar(instance);
  9614. return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes();
  9615. }
  9616. return false;
  9617. };
  9618. // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
  9619. auto slowCopy = [&scriptContext, &needArraySlowCopy](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
  9620. Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
  9621. RecyclableObject *propertyObject;
  9622. if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
  9623. {
  9624. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
  9625. }
  9626. for (uint32 j = start; j < end; j++)
  9627. {
  9628. Var element;
  9629. if (!JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext))
  9630. {
  9631. // Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
  9632. element = scriptContext->GetLibrary()->GetUndefined();
  9633. }
  9634. dstArray->DirectSetItemAt(dstIndex++, element);
  9635. }
  9636. };
  9637. if (i < spreadIndex)
  9638. {
  9639. // Any non-spread elements can be copied in bulk.
  9640. if (needArraySlowCopy(array))
  9641. {
  9642. slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
  9643. }
  9644. else
  9645. {
  9646. CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex);
  9647. }
  9648. resultIndex += spreadIndex - i;
  9649. i = spreadIndex - 1;
  9650. continue;
  9651. }
  9652. else if (i > spreadIndex)
  9653. {
  9654. // Any non-spread elements terminating the array can also be copied in bulk.
  9655. Assert(spreadArrIndex == spreadIndices->count - 1);
  9656. if (needArraySlowCopy(array))
  9657. {
  9658. slowCopy(result, resultIndex, array, i, array->GetLength());
  9659. }
  9660. else
  9661. {
  9662. CopyAnyArrayElementsToVar(result, resultIndex, array, i, array->GetLength());
  9663. }
  9664. break;
  9665. }
  9666. else
  9667. {
  9668. Var instance = array->DirectGetItem(i);
  9669. if (SpreadArgument::Is(instance))
  9670. {
  9671. SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
  9672. uint32 len = spreadArgument->GetArgumentSpreadCount();
  9673. const Var* spreadItems = spreadArgument->GetArgumentSpread();
  9674. for (uint32 j = 0; j < len; j++)
  9675. {
  9676. result->DirectSetItemAt(resultIndex++, spreadItems[j]);
  9677. }
  9678. }
  9679. else
  9680. {
  9681. AssertMsg(JavascriptArray::Is(instance) || TypedArrayBase::Is(instance), "Only SpreadArgument, TypedArray, and JavascriptArray should be listed as spread arguments");
  9682. // We first try to interpret the spread parameter as a JavascriptArray.
  9683. JavascriptArray *arr = nullptr;
  9684. if (JavascriptArray::Is(instance))
  9685. {
  9686. arr = JavascriptArray::FromVar(instance);
  9687. }
  9688. if (arr != nullptr)
  9689. {
  9690. if (arr->GetLength() > 0)
  9691. {
  9692. if (needArraySlowCopy(arr))
  9693. {
  9694. slowCopy(result, resultIndex, arr, 0, arr->GetLength());
  9695. }
  9696. else
  9697. {
  9698. CopyAnyArrayElementsToVar(result, resultIndex, arr, 0, arr->GetLength());
  9699. }
  9700. resultIndex += arr->GetLength();
  9701. }
  9702. }
  9703. else
  9704. {
  9705. uint32 len = GetSpreadArgLen(instance, scriptContext);
  9706. slowCopy(result, resultIndex, instance, 0, len);
  9707. resultIndex += len;
  9708. }
  9709. }
  9710. if (spreadArrIndex < spreadIndices->count - 1)
  9711. {
  9712. spreadArrIndex++;
  9713. }
  9714. }
  9715. }
  9716. return result;
  9717. }
  9718. uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
  9719. {
  9720. // A spread argument can be anything that returns a 'length' property, even if that
  9721. // property is null or undefined.
  9722. spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
  9723. if (JavascriptArray::Is(spreadArg))
  9724. {
  9725. JavascriptArray *arr = JavascriptArray::FromVar(spreadArg);
  9726. return arr->GetLength();
  9727. }
  9728. if (TypedArrayBase::Is(spreadArg))
  9729. {
  9730. TypedArrayBase *tarr = TypedArrayBase::FromVar(spreadArg);
  9731. return tarr->GetLength();
  9732. }
  9733. if (SpreadArgument::Is(spreadArg))
  9734. {
  9735. SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
  9736. return spreadFunctionArgs->GetArgumentSpreadCount();
  9737. }
  9738. AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
  9739. Throw::FatalInternalError();
  9740. }
  9741. #ifdef VALIDATE_ARRAY
  9742. class ArraySegmentsVisitor
  9743. {
  9744. private:
  9745. SparseArraySegmentBase* seg;
  9746. public:
  9747. ArraySegmentsVisitor(SparseArraySegmentBase* head)
  9748. : seg(head)
  9749. {
  9750. }
  9751. void operator()(SparseArraySegmentBase* s)
  9752. {
  9753. Assert(seg == s);
  9754. if (seg)
  9755. {
  9756. seg = seg->next;
  9757. }
  9758. }
  9759. };
  9760. void JavascriptArray::ValidateArrayCommon()
  9761. {
  9762. SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
  9763. AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
  9764. AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
  9765. // Simple segments validation
  9766. bool foundLastUsedSegment = false;
  9767. SparseArraySegmentBase *seg = head;
  9768. while(seg != nullptr)
  9769. {
  9770. if (seg == lastUsedSegment)
  9771. {
  9772. foundLastUsedSegment = true;
  9773. }
  9774. AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
  9775. SparseArraySegmentBase* next = seg->next;
  9776. if (next != nullptr)
  9777. {
  9778. AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
  9779. AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
  9780. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  9781. }
  9782. else
  9783. {
  9784. AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
  9785. AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
  9786. }
  9787. seg = next;
  9788. }
  9789. AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
  9790. // Validate segmentMap if present
  9791. if (HasSegmentMap())
  9792. {
  9793. ArraySegmentsVisitor visitor(head);
  9794. GetSegmentMap()->Walk(visitor);
  9795. }
  9796. }
  9797. void JavascriptArray::ValidateArray()
  9798. {
  9799. if (!Js::Configuration::Global.flags.ArrayValidate)
  9800. {
  9801. return;
  9802. }
  9803. ValidateArrayCommon();
  9804. // Detailed segments validation
  9805. JavascriptArray::ValidateVarSegment((SparseArraySegment<Var>*)head);
  9806. }
  9807. void JavascriptNativeIntArray::ValidateArray()
  9808. {
  9809. if (!Js::Configuration::Global.flags.ArrayValidate)
  9810. {
  9811. #if DBG
  9812. SparseArraySegmentBase *seg = head;
  9813. while (seg)
  9814. {
  9815. if (seg->next != nullptr)
  9816. {
  9817. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  9818. }
  9819. seg = seg->next;
  9820. }
  9821. #endif
  9822. return;
  9823. }
  9824. ValidateArrayCommon();
  9825. // Detailed segments validation
  9826. JavascriptArray::ValidateSegment<int32>((SparseArraySegment<int32>*)head);
  9827. }
  9828. void JavascriptNativeFloatArray::ValidateArray()
  9829. {
  9830. if (!Js::Configuration::Global.flags.ArrayValidate)
  9831. {
  9832. #if DBG
  9833. SparseArraySegmentBase *seg = head;
  9834. while (seg)
  9835. {
  9836. if (seg->next != nullptr)
  9837. {
  9838. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  9839. }
  9840. seg = seg->next;
  9841. }
  9842. #endif
  9843. return;
  9844. }
  9845. ValidateArrayCommon();
  9846. // Detailed segments validation
  9847. JavascriptArray::ValidateSegment<double>((SparseArraySegment<double>*)head);
  9848. }
  9849. void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
  9850. {
  9851. if (!Js::Configuration::Global.flags.ArrayValidate)
  9852. {
  9853. return;
  9854. }
  9855. int32 inspect;
  9856. double inspectDouble;
  9857. while (seg)
  9858. {
  9859. uint32 i = 0;
  9860. for (i = 0; i < seg->length; i++)
  9861. {
  9862. if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
  9863. {
  9864. continue;
  9865. }
  9866. if (TaggedInt::Is(seg->elements[i]))
  9867. {
  9868. inspect = TaggedInt::ToInt32(seg->elements[i]);
  9869. }
  9870. else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
  9871. {
  9872. inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
  9873. }
  9874. else
  9875. {
  9876. AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
  9877. }
  9878. }
  9879. ValidateSegment(seg);
  9880. seg = (SparseArraySegment<Var>*)seg->next;
  9881. }
  9882. }
  9883. template<typename T>
  9884. void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
  9885. {
  9886. if (!Js::Configuration::Global.flags.ArrayValidate)
  9887. {
  9888. return;
  9889. }
  9890. while (seg)
  9891. {
  9892. uint32 i = seg->length;
  9893. while (i < seg->size)
  9894. {
  9895. AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
  9896. i++;
  9897. }
  9898. seg = (SparseArraySegment<T>*)seg->next;
  9899. }
  9900. }
  9901. #endif
  9902. template <typename T>
  9903. void JavascriptArray::InitBoxedInlineHeadSegment(SparseArraySegment<T> * dst, SparseArraySegment<T> * src)
  9904. {
  9905. // Don't copy the segment map, we will build it again
  9906. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  9907. SetHeadAndLastUsedSegment(dst);
  9908. dst->left = src->left;
  9909. dst->length = src->length;
  9910. dst->size = src->size;
  9911. dst->next = src->next;
  9912. js_memcpy_s(dst->elements, sizeof(T) * dst->size, src->elements, sizeof(T) * src->size);
  9913. }
  9914. JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead)
  9915. : ArrayObject(instance)
  9916. {
  9917. if (boxHead)
  9918. {
  9919. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), (SparseArraySegment<Var>*)instance->head);
  9920. }
  9921. else
  9922. {
  9923. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  9924. head = instance->head;
  9925. SetLastUsedSegment(instance->GetLastUsedSegment());
  9926. }
  9927. }
  9928. template <typename T>
  9929. T * JavascriptArray::BoxStackInstance(T * instance)
  9930. {
  9931. Assert(ThreadContext::IsOnStack(instance));
  9932. // On the stack, the we reserved a pointer before the object as to store the boxed value
  9933. T ** boxedInstanceRef = ((T **)instance) - 1;
  9934. T * boxedInstance = *boxedInstanceRef;
  9935. if (boxedInstance)
  9936. {
  9937. return boxedInstance;
  9938. }
  9939. const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  9940. if (ThreadContext::IsOnStack(instance->head))
  9941. {
  9942. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
  9943. inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
  9944. T, instance, true);
  9945. }
  9946. else if(inlineSlotsSize)
  9947. {
  9948. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false);
  9949. }
  9950. else
  9951. {
  9952. boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false);
  9953. }
  9954. *boxedInstanceRef = boxedInstance;
  9955. return boxedInstance;
  9956. }
  9957. JavascriptArray *
  9958. JavascriptArray::BoxStackInstance(JavascriptArray * instance)
  9959. {
  9960. return BoxStackInstance<JavascriptArray>(instance);
  9961. }
  9962. JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
  9963. JavascriptArray(instance, false),
  9964. weakRefToFuncBody(instance->weakRefToFuncBody)
  9965. {
  9966. }
  9967. JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead) :
  9968. JavascriptNativeArray(instance)
  9969. {
  9970. if (boxHead)
  9971. {
  9972. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), (SparseArraySegment<int>*)instance->head);
  9973. }
  9974. else
  9975. {
  9976. // Base class ctor should have copied these
  9977. Assert(head == instance->head);
  9978. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  9979. }
  9980. }
  9981. JavascriptNativeIntArray *
  9982. JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance)
  9983. {
  9984. return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance);
  9985. }
  9986. JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead) :
  9987. JavascriptNativeArray(instance)
  9988. {
  9989. if (boxHead)
  9990. {
  9991. InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), (SparseArraySegment<double>*)instance->head);
  9992. }
  9993. else
  9994. {
  9995. // Base class ctor should have copied these
  9996. Assert(head == instance->head);
  9997. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  9998. }
  9999. }
  10000. JavascriptNativeFloatArray *
  10001. JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
  10002. {
  10003. return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
  10004. }
  10005. template<typename T>
  10006. RecyclableObject*
  10007. JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool* pIsIntArray, bool* pIsFloatArray)
  10008. {
  10009. if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
  10010. {
  10011. return nullptr;
  10012. }
  10013. if (JavascriptArray::Is(originalArray)
  10014. && !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
  10015. && DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
  10016. && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
  10017. {
  10018. return nullptr;
  10019. }
  10020. Var constructor = scriptContext->GetLibrary()->GetUndefined();
  10021. if (JavascriptOperators::IsArray(originalArray))
  10022. {
  10023. if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
  10024. {
  10025. return nullptr;
  10026. }
  10027. if (JavascriptOperators::IsConstructor(constructor))
  10028. {
  10029. ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
  10030. if (constructorScriptContext != scriptContext)
  10031. {
  10032. if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
  10033. {
  10034. constructor = scriptContext->GetLibrary()->GetUndefined();
  10035. }
  10036. }
  10037. }
  10038. if (JavascriptOperators::IsObject(constructor))
  10039. {
  10040. if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
  10041. {
  10042. return nullptr;
  10043. }
  10044. if (constructor == scriptContext->GetLibrary()->GetNull())
  10045. {
  10046. constructor = scriptContext->GetLibrary()->GetUndefined();
  10047. }
  10048. }
  10049. }
  10050. if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
  10051. {
  10052. if (length > UINT_MAX)
  10053. {
  10054. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  10055. }
  10056. if (nullptr == pIsIntArray)
  10057. {
  10058. return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  10059. }
  10060. else
  10061. {
  10062. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  10063. JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
  10064. pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
  10065. return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
  10066. }
  10067. }
  10068. if (!JavascriptOperators::IsConstructor(constructor))
  10069. {
  10070. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  10071. }
  10072. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  10073. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  10074. return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  10075. }
  10076. /*static*/
  10077. PropertyId const JavascriptArray::specialPropertyIds[] =
  10078. {
  10079. PropertyIds::length
  10080. };
  10081. BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  10082. {
  10083. if (propertyId == PropertyIds::length)
  10084. {
  10085. return false;
  10086. }
  10087. return DynamicObject::DeleteProperty(propertyId, flags);
  10088. }
  10089. BOOL JavascriptArray::HasProperty(PropertyId propertyId)
  10090. {
  10091. if (propertyId == PropertyIds::length)
  10092. {
  10093. return true;
  10094. }
  10095. ScriptContext* scriptContext = GetScriptContext();
  10096. uint32 index;
  10097. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10098. {
  10099. return this->HasItem(index);
  10100. }
  10101. return DynamicObject::HasProperty(propertyId);
  10102. }
  10103. BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
  10104. {
  10105. if (propertyId == PropertyIds::length)
  10106. {
  10107. return false;
  10108. }
  10109. return DynamicObject::IsEnumerable(propertyId);
  10110. }
  10111. BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
  10112. {
  10113. if (propertyId == PropertyIds::length)
  10114. {
  10115. return false;
  10116. }
  10117. return DynamicObject::IsConfigurable(propertyId);
  10118. }
  10119. //
  10120. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10121. // handling and only check instance objectArray for numeric propertyIds.
  10122. //
  10123. BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
  10124. {
  10125. if (propertyId == PropertyIds::length)
  10126. {
  10127. Assert(!value); // Can't change array length enumerable
  10128. return true;
  10129. }
  10130. ScriptContext* scriptContext = this->GetScriptContext();
  10131. uint32 index;
  10132. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10133. {
  10134. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10135. ->SetEnumerable(this, propertyId, value);
  10136. }
  10137. return __super::SetEnumerable(propertyId, value);
  10138. }
  10139. //
  10140. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10141. // handling and only check instance objectArray for numeric propertyIds.
  10142. //
  10143. BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
  10144. {
  10145. ScriptContext* scriptContext = this->GetScriptContext();
  10146. uint32 index;
  10147. bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
  10148. if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
  10149. {
  10150. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10151. ->SetWritable(this, propertyId, value);
  10152. }
  10153. return __super::SetWritable(propertyId, value);
  10154. }
  10155. //
  10156. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10157. // handling and only check instance objectArray for numeric propertyIds.
  10158. //
  10159. BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
  10160. {
  10161. if (propertyId == PropertyIds::length)
  10162. {
  10163. Assert(!value); // Can't change array length configurable
  10164. return true;
  10165. }
  10166. ScriptContext* scriptContext = this->GetScriptContext();
  10167. uint32 index;
  10168. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10169. {
  10170. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10171. ->SetConfigurable(this, propertyId, value);
  10172. }
  10173. return __super::SetConfigurable(propertyId, value);
  10174. }
  10175. //
  10176. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10177. // handling and only check instance objectArray for numeric propertyIds.
  10178. //
  10179. BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
  10180. {
  10181. ScriptContext* scriptContext = this->GetScriptContext();
  10182. // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
  10183. // changed, we need to handle it here.
  10184. Assert(propertyId != PropertyIds::length);
  10185. uint32 index;
  10186. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10187. {
  10188. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10189. ->SetItemAttributes(this, index, attributes);
  10190. }
  10191. return __super::SetAttributes(propertyId, attributes);
  10192. }
  10193. //
  10194. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10195. // handling and only check instance objectArray for numeric propertyIds.
  10196. //
  10197. BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  10198. {
  10199. ScriptContext* scriptContext = this->GetScriptContext();
  10200. uint32 index;
  10201. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10202. {
  10203. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10204. ->SetItemAccessors(this, index, getter, setter);
  10205. }
  10206. return __super::SetAccessors(propertyId, getter, setter, flags);
  10207. }
  10208. //
  10209. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10210. // handling and only check instance objectArray for numeric propertyIds.
  10211. //
  10212. BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
  10213. {
  10214. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10215. ->SetItemWithAttributes(this, index, value, attributes);
  10216. }
  10217. //
  10218. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10219. // handling and only check instance objectArray for numeric propertyIds.
  10220. //
  10221. BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
  10222. {
  10223. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10224. ->SetItemAttributes(this, index, attributes);
  10225. }
  10226. //
  10227. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10228. // handling and only check instance objectArray for numeric propertyIds.
  10229. //
  10230. BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
  10231. {
  10232. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10233. ->SetItemAccessors(this, index, getter, setter);
  10234. }
  10235. // Check if this objectArray isFrozen.
  10236. BOOL JavascriptArray::IsObjectArrayFrozen()
  10237. {
  10238. // If this is still a JavascriptArray, it's not frozen.
  10239. return false;
  10240. }
  10241. BOOL JavascriptArray::GetEnumerator(Var originalInstance, BOOL enumNonEnumerable, Var* enumerator, ScriptContext* requestContext, bool preferSnapshotSemantics, bool enumSymbols)
  10242. {
  10243. // JavascriptArray does not support accessors, discard originalInstance.
  10244. return JavascriptArray::GetEnumerator(enumNonEnumerable, enumerator, requestContext, preferSnapshotSemantics, enumSymbols);
  10245. }
  10246. BOOL JavascriptArray::GetNonIndexEnumerator(Var* enumerator, ScriptContext* requestContext)
  10247. {
  10248. *enumerator = RecyclerNew(GetScriptContext()->GetRecycler(), JavascriptArrayNonIndexSnapshotEnumerator, this, requestContext, false);
  10249. return true;
  10250. }
  10251. BOOL JavascriptArray::IsItemEnumerable(uint32 index)
  10252. {
  10253. return true;
  10254. }
  10255. //
  10256. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10257. // handling and only check instance objectArray for numeric propertyIds.
  10258. //
  10259. BOOL JavascriptArray::PreventExtensions()
  10260. {
  10261. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
  10262. }
  10263. //
  10264. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10265. // handling and only check instance objectArray for numeric propertyIds.
  10266. //
  10267. BOOL JavascriptArray::Seal()
  10268. {
  10269. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
  10270. }
  10271. //
  10272. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10273. // handling and only check instance objectArray for numeric propertyIds.
  10274. //
  10275. BOOL JavascriptArray::Freeze()
  10276. {
  10277. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
  10278. }
  10279. BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, Var *propertyName, ScriptContext * requestContext)
  10280. {
  10281. if (index == 0)
  10282. {
  10283. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  10284. return true;
  10285. }
  10286. return false;
  10287. }
  10288. // Returns the number of special non-enumerable properties this type has.
  10289. uint JavascriptArray::GetSpecialPropertyCount() const
  10290. {
  10291. return _countof(specialPropertyIds);
  10292. }
  10293. // Returns the list of special non-enumerable properties for the type.
  10294. PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
  10295. {
  10296. return specialPropertyIds;
  10297. }
  10298. BOOL JavascriptArray::GetPropertyReference(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10299. {
  10300. return JavascriptArray::GetProperty(originalInstance, propertyId, value, info, requestContext);
  10301. }
  10302. BOOL JavascriptArray::GetProperty(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10303. {
  10304. if (GetPropertyBuiltIns(propertyId, value))
  10305. {
  10306. return true;
  10307. }
  10308. ScriptContext* scriptContext = GetScriptContext();
  10309. uint32 index;
  10310. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10311. {
  10312. return this->GetItem(this, index, value, scriptContext);
  10313. }
  10314. return DynamicObject::GetProperty(originalInstance, propertyId, value, info, requestContext);
  10315. }
  10316. BOOL JavascriptArray::GetProperty(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  10317. {
  10318. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10319. "Numeric property names should have been converted to uint or PropertyRecord*");
  10320. PropertyRecord const* propertyRecord;
  10321. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10322. if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
  10323. {
  10324. return true;
  10325. }
  10326. return DynamicObject::GetProperty(originalInstance, propertyNameString, value, info, requestContext);
  10327. }
  10328. BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
  10329. {
  10330. //
  10331. // length being accessed. Return array length
  10332. //
  10333. if (propertyId == PropertyIds::length)
  10334. {
  10335. *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
  10336. return true;
  10337. }
  10338. return false;
  10339. }
  10340. BOOL JavascriptArray::HasItem(uint32 index)
  10341. {
  10342. Var value;
  10343. return this->DirectGetItemAt<Var>(index, &value);
  10344. }
  10345. BOOL JavascriptArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10346. {
  10347. return this->DirectGetItemAt<Var>(index, value);
  10348. }
  10349. BOOL JavascriptArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10350. {
  10351. return this->DirectGetItemAt<Var>(index, value);
  10352. }
  10353. BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10354. {
  10355. return this->DirectGetItemAt<Var>(index, value);
  10356. }
  10357. BOOL JavascriptNativeIntArray::HasItem(uint32 index)
  10358. {
  10359. #if ENABLE_COPYONACCESS_ARRAY
  10360. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10361. #endif
  10362. int32 value;
  10363. return this->DirectGetItemAt<int32>(index, &value);
  10364. }
  10365. BOOL JavascriptNativeFloatArray::HasItem(uint32 index)
  10366. {
  10367. double dvalue;
  10368. return this->DirectGetItemAt<double>(index, &dvalue);
  10369. }
  10370. BOOL JavascriptNativeIntArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10371. {
  10372. #if ENABLE_COPYONACCESS_ARRAY
  10373. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10374. #endif
  10375. return JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext);
  10376. }
  10377. BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10378. {
  10379. int32 intvalue;
  10380. if (!this->DirectGetItemAt<int32>(index, &intvalue))
  10381. {
  10382. return FALSE;
  10383. }
  10384. *value = JavascriptNumber::ToVar(intvalue, requestContext);
  10385. return TRUE;
  10386. }
  10387. BOOL JavascriptNativeIntArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10388. {
  10389. return JavascriptNativeIntArray::GetItem(originalInstance, index, value, requestContext);
  10390. }
  10391. BOOL JavascriptNativeFloatArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10392. {
  10393. return JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext);
  10394. }
  10395. BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  10396. {
  10397. double dvalue;
  10398. int32 ivalue;
  10399. if (!this->DirectGetItemAt<double>(index, &dvalue))
  10400. {
  10401. return FALSE;
  10402. }
  10403. if (*(uint64*)&dvalue == 0ull)
  10404. {
  10405. *value = TaggedInt::ToVarUnchecked(0);
  10406. }
  10407. else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
  10408. {
  10409. *value = TaggedInt::ToVarUnchecked(ivalue);
  10410. }
  10411. else
  10412. {
  10413. *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
  10414. }
  10415. return TRUE;
  10416. }
  10417. BOOL JavascriptNativeFloatArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  10418. {
  10419. return JavascriptNativeFloatArray::GetItem(originalInstance, index, value, requestContext);
  10420. }
  10421. BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10422. {
  10423. uint32 indexValue;
  10424. if (propertyId == PropertyIds::length)
  10425. {
  10426. return this->SetLength(value);
  10427. }
  10428. else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
  10429. {
  10430. // Call this or subclass method
  10431. return SetItem(indexValue, value, flags);
  10432. }
  10433. else
  10434. {
  10435. return DynamicObject::SetProperty(propertyId, value, flags, info);
  10436. }
  10437. }
  10438. BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  10439. {
  10440. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  10441. "Numeric property names should have been converted to uint or PropertyRecord*");
  10442. PropertyRecord const* propertyRecord;
  10443. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  10444. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
  10445. {
  10446. return this->SetLength(value);
  10447. }
  10448. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  10449. }
  10450. BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  10451. {
  10452. ScriptContext* scriptContext = GetScriptContext();
  10453. if (propertyId == PropertyIds::length)
  10454. {
  10455. Assert(attributes == PropertyWritable);
  10456. Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
  10457. return this->SetLength(value);
  10458. }
  10459. uint32 index;
  10460. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10461. {
  10462. // Call this or subclass method
  10463. return SetItemWithAttributes(index, value, attributes);
  10464. }
  10465. return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  10466. }
  10467. BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10468. {
  10469. this->DirectSetItemAt(index, value);
  10470. return true;
  10471. }
  10472. BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10473. {
  10474. int32 iValue;
  10475. double dValue;
  10476. #if ENABLE_COPYONACCESS_ARRAY
  10477. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10478. #endif
  10479. TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  10480. if (typeId == TypeIds_NativeIntArray)
  10481. {
  10482. this->SetItem(index, iValue);
  10483. }
  10484. else if (typeId == TypeIds_NativeFloatArray)
  10485. {
  10486. reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
  10487. }
  10488. else
  10489. {
  10490. this->DirectSetItemAt<Var>(index, value);
  10491. }
  10492. return TRUE;
  10493. }
  10494. TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
  10495. {
  10496. if (TaggedInt::Is(value))
  10497. {
  10498. int32 i = TaggedInt::ToInt32(value);
  10499. if (i != JavascriptNativeIntArray::MissingItem)
  10500. {
  10501. *iValue = i;
  10502. return TypeIds_NativeIntArray;
  10503. }
  10504. }
  10505. if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10506. {
  10507. bool isInt32;
  10508. int32 i;
  10509. double d = JavascriptNumber::GetValue(value);
  10510. if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
  10511. {
  10512. if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
  10513. {
  10514. *iValue = i;
  10515. return TypeIds_NativeIntArray;
  10516. }
  10517. }
  10518. else
  10519. {
  10520. *dValue = d;
  10521. JavascriptNativeIntArray::ToNativeFloatArray(this);
  10522. return TypeIds_NativeFloatArray;
  10523. }
  10524. }
  10525. JavascriptNativeIntArray::ToVarArray(this);
  10526. return TypeIds_Array;
  10527. }
  10528. BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
  10529. {
  10530. if (iValue == JavascriptNativeIntArray::MissingItem)
  10531. {
  10532. JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
  10533. varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
  10534. return TRUE;
  10535. }
  10536. this->DirectSetItemAt(index, iValue);
  10537. return TRUE;
  10538. }
  10539. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  10540. {
  10541. double dValue;
  10542. TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
  10543. if (typeId == TypeIds_NativeFloatArray)
  10544. {
  10545. this->SetItem(index, dValue);
  10546. }
  10547. else
  10548. {
  10549. this->DirectSetItemAt(index, value);
  10550. }
  10551. return TRUE;
  10552. }
  10553. TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
  10554. {
  10555. if (TaggedInt::Is(value))
  10556. {
  10557. *dValue = (double)TaggedInt::ToInt32(value);
  10558. return TypeIds_NativeFloatArray;
  10559. }
  10560. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  10561. {
  10562. *dValue = JavascriptNumber::GetValue(value);
  10563. return TypeIds_NativeFloatArray;
  10564. }
  10565. JavascriptNativeFloatArray::ToVarArray(this);
  10566. return TypeIds_Array;
  10567. }
  10568. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
  10569. {
  10570. if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
  10571. {
  10572. JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
  10573. varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
  10574. return TRUE;
  10575. }
  10576. this->DirectSetItemAt<double>(index, dValue);
  10577. return TRUE;
  10578. }
  10579. BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10580. {
  10581. return this->DirectDeleteItemAt<Var>(index);
  10582. }
  10583. BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10584. {
  10585. return this->DirectDeleteItemAt<int32>(index);
  10586. }
  10587. BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  10588. {
  10589. return this->DirectDeleteItemAt<double>(index);
  10590. }
  10591. BOOL JavascriptArray::GetEnumerator(BOOL enumNonEnumerable, Var* enumerator, ScriptContext * requestContext, bool preferSnapshotSemantics, bool enumSymbols)
  10592. {
  10593. if (preferSnapshotSemantics)
  10594. {
  10595. *enumerator = RecyclerNew(GetRecycler(), JavascriptArraySnapshotEnumerator, this, requestContext, enumNonEnumerable, enumSymbols);
  10596. }
  10597. else
  10598. {
  10599. *enumerator = RecyclerNew(GetRecycler(), JavascriptArrayEnumerator, this, requestContext, enumNonEnumerable, enumSymbols);
  10600. }
  10601. return true;
  10602. }
  10603. BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10604. {
  10605. stringBuilder->Append(_u('['));
  10606. if (this->length < 10)
  10607. {
  10608. BEGIN_JS_RUNTIME_CALL(requestContext);
  10609. {
  10610. ENTER_PINNED_SCOPE(JavascriptString, valueStr);
  10611. valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
  10612. stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
  10613. LEAVE_PINNED_SCOPE();
  10614. }
  10615. END_JS_RUNTIME_CALL(requestContext);
  10616. }
  10617. else
  10618. {
  10619. stringBuilder->AppendCppLiteral(_u("..."));
  10620. }
  10621. stringBuilder->Append(_u(']'));
  10622. return TRUE;
  10623. }
  10624. BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  10625. {
  10626. stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
  10627. return TRUE;
  10628. }
  10629. bool JavascriptNativeArray::Is(Var aValue)
  10630. {
  10631. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10632. return JavascriptNativeArray::Is(typeId);
  10633. }
  10634. bool JavascriptNativeArray::Is(TypeId typeId)
  10635. {
  10636. return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
  10637. }
  10638. JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
  10639. {
  10640. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
  10641. return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
  10642. }
  10643. bool JavascriptNativeIntArray::Is(Var aValue)
  10644. {
  10645. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10646. return JavascriptNativeIntArray::Is(typeId);
  10647. }
  10648. #if ENABLE_COPYONACCESS_ARRAY
  10649. bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
  10650. {
  10651. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10652. return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
  10653. }
  10654. #endif
  10655. bool JavascriptNativeIntArray::Is(TypeId typeId)
  10656. {
  10657. return typeId == TypeIds_NativeIntArray;
  10658. }
  10659. #if ENABLE_COPYONACCESS_ARRAY
  10660. bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
  10661. {
  10662. return typeId == TypeIds_CopyOnAccessNativeIntArray;
  10663. }
  10664. #endif
  10665. bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
  10666. {
  10667. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
  10668. Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
  10669. return ret;
  10670. }
  10671. JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
  10672. {
  10673. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
  10674. return static_cast<JavascriptNativeIntArray *>(RecyclableObject::FromVar(aValue));
  10675. }
  10676. #if ENABLE_COPYONACCESS_ARRAY
  10677. JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
  10678. {
  10679. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
  10680. return static_cast<JavascriptCopyOnAccessNativeIntArray *>(RecyclableObject::FromVar(aValue));
  10681. }
  10682. #endif
  10683. bool JavascriptNativeFloatArray::Is(Var aValue)
  10684. {
  10685. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  10686. return JavascriptNativeFloatArray::Is(typeId);
  10687. }
  10688. bool JavascriptNativeFloatArray::Is(TypeId typeId)
  10689. {
  10690. return typeId == TypeIds_NativeFloatArray;
  10691. }
  10692. bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
  10693. {
  10694. bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
  10695. Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
  10696. return ret;
  10697. }
  10698. JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
  10699. {
  10700. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
  10701. return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
  10702. }
  10703. template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
  10704. template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
  10705. template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
  10706. template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  10707. template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  10708. } //namespace Js