| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629 |
- //-------------------------------------------------------------------------------------------------------
- // Copyright (C) Microsoft. All rights reserved.
- // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
- //-------------------------------------------------------------------------------------------------------
- #include "RuntimeLibraryPch.h"
- #include "Types/PathTypeHandler.h"
- #include "Types/SpreadArgument.h"
- // TODO: Change this generic fatal error to the descriptive one.
- #define AssertAndFailFast(x) if (!(x)) { Assert(x); Js::Throw::FatalInternalError(); }
- namespace Js
- {
- // Make sure EmptySegment points to read-only memory.
- // Can't do this the easy way because SparseArraySegment has a constructor...
- static const char EmptySegmentData[sizeof(SparseArraySegmentBase)] = {0};
- const SparseArraySegmentBase *JavascriptArray::EmptySegment = (SparseArraySegmentBase *)&EmptySegmentData;
- // col0 : allocation bucket
- // col1 : No. of missing items to set during initialization depending on bucket.
- // col2 : allocation size for elements in given bucket.
- // col1 and col2 is calculated at runtime
- uint JavascriptNativeFloatArray::allocationBuckets[][AllocationBucketsInfoSize] =
- {
- { 3, 0, 0 }, // allocate space for 3 elements for array of length 0,1,2,3
- { 5, 0, 0 }, // allocate space for 5 elements for array of length 4,5
- { 8, 0, 0 }, // allocate space for 8 elements for array of length 6,7,8
- };
- #if defined(_M_X64_OR_ARM64)
- const Var JavascriptArray::MissingItem = (Var)0x8000000280000002;
- uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
- {
- // See comments above on how to read this
- {2, 0, 0},
- {6, 0, 0},
- {8, 0, 0},
- };
- uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
- {
- // See comments above on how to read this
- {4, 0, 0},
- {6, 0, 0},
- {8, 0, 0},
- };
- #else
- const Var JavascriptArray::MissingItem = (Var)0x80000002;
- uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
- {
- // See comments above on how to read this
- { 3, 0, 0 },
- { 7, 0, 0 },
- { 8, 0, 0 },
- };
- uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
- {
- // See comments above on how to read this
- { 4, 0, 0 },
- { 8, 0, 0 },
- };
- #endif
- const int32 JavascriptNativeIntArray::MissingItem = 0x80000002;
- static const uint64 FloatMissingItemPattern = 0x8000000280000002ull;
- const double JavascriptNativeFloatArray::MissingItem = *(double*)&FloatMissingItemPattern;
- // Allocate enough space for 4 inline property slots and 16 inline element slots
- const size_t JavascriptArray::StackAllocationSize = DetermineAllocationSize<JavascriptArray, 4>(16);
- const size_t JavascriptNativeIntArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeIntArray, 4>(16);
- const size_t JavascriptNativeFloatArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeFloatArray, 4>(16);
- SegmentBTree::SegmentBTree()
- : segmentCount(0),
- segments(nullptr),
- keys(nullptr),
- children(nullptr)
- {
- }
- uint32 SegmentBTree::GetLazyCrossOverLimit()
- {
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- if (Js::Configuration::Global.flags.DisableArrayBTree)
- {
- return Js::JavascriptArray::InvalidIndex;
- }
- else if (Js::Configuration::Global.flags.ForceArrayBTree)
- {
- return ARRAY_CROSSOVER_FOR_VALIDATE;
- }
- #endif
- #ifdef VALIDATE_ARRAY
- if (Js::Configuration::Global.flags.ArrayValidate)
- {
- return ARRAY_CROSSOVER_FOR_VALIDATE;
- }
- #endif
- return SegmentBTree::MinDegree * 3;
- }
- BOOL SegmentBTree::IsLeaf() const
- {
- return children == NULL;
- }
- BOOL SegmentBTree::IsFullNode() const
- {
- return segmentCount == MaxKeys;
- }
- void SegmentBTree::InternalFind(SegmentBTree* node, uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
- {
- uint32 i = 0;
- for(; i < node->segmentCount; i++)
- {
- Assert(node->keys[i] == node->segments[i]->left);
- if (itemIndex < node->keys[i])
- {
- break;
- }
- }
- // i indicates the 1st segment in the node past any matching segment.
- // the i'th child is the children to the 'left' of the i'th segment.
- // If itemIndex matches segment i-1 (note that left is always a match even when length == 0)
- bool matches = i > 0 && (itemIndex == node->keys[i-1] || itemIndex < node->keys[i-1] + node->segments[i-1]->length);
- if (matches)
- {
- // Find prev segment
- if (node->IsLeaf())
- {
- if (i > 1)
- {
- // Previous is either sibling or set in a parent
- prev = node->segments[i-2];
- }
- }
- else
- {
- // prev is the right most leaf in children[i-1] tree
- SegmentBTree* child = &node->children[i - 1];
- while (!child->IsLeaf())
- {
- child = &child->children[child->segmentCount];
- }
- prev = child->segments[child->segmentCount - 1];
- }
- // Return the matching segment
- matchOrNext = node->segments[i-1];
- }
- else // itemIndex in between segment i-1 and i
- {
- if (i > 0)
- {
- // Store in previous in case a match or next is the first segment in a child.
- prev = node->segments[i-1];
- }
- if (node->IsLeaf())
- {
- matchOrNext = (i == 0 ? node->segments[0] : PointerValue(prev->next));
- }
- else
- {
- InternalFind(node->children + i, itemIndex, prev, matchOrNext);
- }
- }
- }
- void SegmentBTreeRoot::Find(uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
- {
- prev = matchOrNext = NULL;
- InternalFind(this, itemIndex, prev, matchOrNext);
- Assert(prev == NULL || (prev->next == matchOrNext));// If prev exists it is immediately before matchOrNext in the list of arraysegments
- Assert(prev == NULL || (prev->left < itemIndex && prev->left + prev->length <= itemIndex)); // prev should never be a match (left is a match if length == 0)
- Assert(matchOrNext == NULL || (matchOrNext->left >= itemIndex || matchOrNext->left + matchOrNext->length > itemIndex));
- }
- void SegmentBTreeRoot::Add(Recycler* recycler, SparseArraySegmentBase* newSeg)
- {
- if (IsFullNode())
- {
- SegmentBTree * children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
- children[0] = *this;
- // Even though the segments point to a GC pointer, the main array should keep a references
- // as well. So just make it a leaf allocation
- this->segmentCount = 0;
- this->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
- this->keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
- this->children = children;
- // This split is the only way the tree gets deeper
- SplitChild(recycler, this, 0, &children[0]);
- }
- InsertNonFullNode(recycler, this, newSeg);
- }
- void SegmentBTree::SwapSegment(uint32 originalKey, SparseArraySegmentBase* oldSeg, SparseArraySegmentBase* newSeg)
- {
- // Find old segment
- uint32 itemIndex = originalKey;
- uint32 i = 0;
- for(; i < segmentCount; i++)
- {
- Assert(keys[i] == segments[i]->left || (oldSeg == newSeg && newSeg == segments[i]));
- if (itemIndex < keys[i])
- {
- break;
- }
- }
- // i is 1 past any match
- if (i > 0)
- {
- if (oldSeg == segments[i-1])
- {
- segments[i-1] = newSeg;
- keys[i-1] = newSeg->left;
- return;
- }
- }
- Assert(!IsLeaf());
- children[i].SwapSegment(originalKey, oldSeg, newSeg);
- }
- void SegmentBTree::SplitChild(Recycler* recycler, SegmentBTree* parent, uint32 iChild, SegmentBTree* child)
- {
- // Split child in two, move it's median key up to parent, and put the result of the split
- // on either side of the key moved up into parent
- Assert(child != NULL);
- Assert(parent != NULL);
- Assert(!parent->IsFullNode());
- Assert(child->IsFullNode());
- SegmentBTree newNode;
- newNode.segmentCount = MinKeys;
- // Even though the segments point to a GC pointer, the main array should keep a references
- // as well. So just make it a leaf allocation
- newNode.segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
- newNode.keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
- // Move the keys above the median into the new node
- for(uint32 i = 0; i < MinKeys; i++)
- {
- newNode.segments[i] = child->segments[i+MinDegree];
- newNode.keys[i] = child->keys[i+MinDegree];
- // Do not leave false positive references around in the b-tree
- child->segments[i+MinDegree] = nullptr;
- }
- // If children exist move those as well.
- if (!child->IsLeaf())
- {
- newNode.children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
- for(uint32 j = 0; j < MinDegree; j++)
- {
- newNode.children[j] = child->children[j+MinDegree];
- // Do not leave false positive references around in the b-tree
- child->children[j+MinDegree].segments = nullptr;
- child->children[j+MinDegree].children = nullptr;
- }
- }
- child->segmentCount = MinKeys;
- // Make room for the new child in parent
- for(uint32 j = parent->segmentCount; j > iChild; j--)
- {
- parent->children[j+1] = parent->children[j];
- }
- // Copy the contents of the new node into the correct place in the parent's child array
- parent->children[iChild+1] = newNode;
- // Move the keys to make room for the median key
- for(uint32 k = parent->segmentCount; k > iChild; k--)
- {
- parent->segments[k] = parent->segments[k-1];
- parent->keys[k] = parent->keys[k-1];
- }
- // Move the median key into the proper place in the parent node
- parent->segments[iChild] = child->segments[MinKeys];
- parent->keys[iChild] = child->keys[MinKeys];
- // Do not leave false positive references around in the b-tree
- child->segments[MinKeys] = nullptr;
- parent->segmentCount++;
- }
- void SegmentBTree::InsertNonFullNode(Recycler* recycler, SegmentBTree* node, SparseArraySegmentBase* newSeg)
- {
- Assert(!node->IsFullNode());
- AnalysisAssert(node->segmentCount < MaxKeys); // Same as !node->IsFullNode()
- Assert(newSeg != NULL);
- if (node->IsLeaf())
- {
- // Move the keys
- uint32 i = node->segmentCount - 1;
- while( (i != -1) && (newSeg->left < node->keys[i]))
- {
- node->segments[i+1] = node->segments[i];
- node->keys[i+1] = node->keys[i];
- i--;
- }
- if (!node->segments)
- {
- // Even though the segments point to a GC pointer, the main array should keep a references
- // as well. So just make it a leaf allocation
- node->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
- node->keys = AllocatorNewArrayLeafZ(Recycler, recycler, uint32, MaxKeys);
- }
- node->segments[i + 1] = newSeg;
- node->keys[i + 1] = newSeg->left;
- node->segmentCount++;
- }
- else
- {
- // find the correct child node
- uint32 i = node->segmentCount-1;
- while((i != -1) && (newSeg->left < node->keys[i]))
- {
- i--;
- }
- i++;
- // Make room if full
- if(node->children[i].IsFullNode())
- {
- // This split doesn't make the tree any deeper as node already has children.
- SplitChild(recycler, node, i, node->children+i);
- Assert(node->keys[i] == node->segments[i]->left);
- if (newSeg->left > node->keys[i])
- {
- i++;
- }
- }
- InsertNonFullNode(recycler, node->children+i, newSeg);
- }
- }
- inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure(BOOL operationSucceeded)
- {
- if (IsThrowTypeError(operationSucceeded))
- {
- ThrowTypeErrorOnFailure();
- }
- }
- inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure()
- {
- JavascriptError::ThrowTypeError(m_scriptContext, VBSERR_ActionNotSupported, m_functionName);
- }
- inline BOOL ThrowTypeErrorOnFailureHelper::IsThrowTypeError(BOOL operationSucceeded)
- {
- return !operationSucceeded;
- }
- // Make sure EmptySegment points to read-only memory.
- // Can't do this the easy way because SparseArraySegment has a constructor...
- JavascriptArray::JavascriptArray(DynamicType * type)
- : ArrayObject(type, false, 0)
- {
- 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()));
- Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
- InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
- SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
- }
- JavascriptArray::JavascriptArray(uint32 length, DynamicType * type)
- : ArrayObject(type, false, length)
- {
- Assert(JavascriptArray::Is(type->GetTypeId()));
- Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
- InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
- SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
- }
- JavascriptArray::JavascriptArray(uint32 length, uint32 size, DynamicType * type)
- : ArrayObject(type, false, length)
- {
- Assert(type->GetTypeId() == TypeIds_Array);
- InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
- Recycler* recycler = GetRecycler();
- SetHeadAndLastUsedSegment(SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, size, nullptr));
- }
- JavascriptArray::JavascriptArray(DynamicType * type, uint32 size)
- : ArrayObject(type, false)
- {
- InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
- SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, false>(this));
- head->size = size;
- head->CheckLengthvsSize();
- Var fill = Js::JavascriptArray::MissingItem;
- for (uint i = 0; i < size; i++)
- {
- SparseArraySegment<Var>::From(head)->elements[i] = fill;
- }
- }
- JavascriptNativeIntArray::JavascriptNativeIntArray(uint32 length, uint32 size, DynamicType * type)
- : JavascriptNativeArray(type)
- {
- Assert(type->GetTypeId() == TypeIds_NativeIntArray);
- this->length = length;
- Recycler* recycler = GetRecycler();
- SetHeadAndLastUsedSegment(SparseArraySegment<int32>::AllocateSegment(recycler, 0, 0, size, nullptr));
- }
- JavascriptNativeIntArray::JavascriptNativeIntArray(DynamicType * type, uint32 size)
- : JavascriptNativeArray(type)
- {
- SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, false>(this));
- head->size = size;
- head->CheckLengthvsSize();
- SparseArraySegment<int32>::From(head)->FillSegmentBuffer(0, size);
- }
- JavascriptNativeFloatArray::JavascriptNativeFloatArray(uint32 length, uint32 size, DynamicType * type)
- : JavascriptNativeArray(type)
- {
- Assert(type->GetTypeId() == TypeIds_NativeFloatArray);
- this->length = length;
- Recycler* recycler = GetRecycler();
- SetHeadAndLastUsedSegment(SparseArraySegment<double>::AllocateSegment(recycler, 0, 0, size, nullptr));
- }
- JavascriptNativeFloatArray::JavascriptNativeFloatArray(DynamicType * type, uint32 size)
- : JavascriptNativeArray(type)
- {
- SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, false>(this));
- head->size = size;
- head->CheckLengthvsSize();
- SparseArraySegment<double>::From(head)->FillSegmentBuffer(0, size);
- }
- bool JavascriptArray::Is(Var aValue)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(aValue);
- return JavascriptArray::Is(typeId);
- }
- bool JavascriptArray::Is(TypeId typeId)
- {
- return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
- }
- bool JavascriptArray::IsVarArray(Var aValue)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(aValue);
- return JavascriptArray::IsVarArray(typeId);
- }
- bool JavascriptArray::IsVarArray(TypeId typeId)
- {
- return typeId == TypeIds_Array;
- }
- template<typename T>
- bool JavascriptArray::IsMissingItemAt(uint32 index) const
- {
- SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(this->head);
- return SparseArraySegment<T>::IsMissingItem(&headSeg->elements[index]);
- }
- bool JavascriptArray::IsMissingItem(uint32 index)
- {
- if (this->length <= index)
- {
- return false;
- }
- bool isIntArray = false, isFloatArray = false;
- this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
- if (isIntArray)
- {
- return IsMissingItemAt<int32>(index);
- }
- else if (isFloatArray)
- {
- return IsMissingItemAt<double>(index);
- }
- else
- {
- return IsMissingItemAt<Var>(index);
- }
- }
- JavascriptArray* JavascriptArray::FromVar(Var aValue)
- {
- AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptArray'");
- return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
- }
- // Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
- JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
- {
- AssertMsg(Is(aValue) || ES5Array::Is(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
- return static_cast<JavascriptArray *>(RecyclableObject::FromVar(aValue));
- }
- // Check if a Var is a direct-accessible (fast path) JavascriptArray.
- bool JavascriptArray::IsDirectAccessArray(Var aValue)
- {
- return RecyclableObject::Is(aValue) &&
- (VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
- VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
- VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
- }
- DynamicObjectFlags JavascriptArray::GetFlags() const
- {
- return GetArrayFlags();
- }
- DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
- {
- return GetArrayFlags_Unchecked();
- }
- void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
- {
- SetArrayFlags(flags);
- }
- DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
- {
- return scriptContext->GetLibrary()->GetArrayType();
- }
- JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(const Var var)
- {
- bool isObjectWithArray;
- TypeId arrayTypeId;
- return GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
- }
- JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
- const Var var,
- bool *const isObjectWithArrayRef,
- TypeId *const arrayTypeIdRef)
- {
- // This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
- // (see Lowerer::GenerateArrayTest) to minimize bailouts.
- Assert(var);
- Assert(isObjectWithArrayRef);
- Assert(arrayTypeIdRef);
- *isObjectWithArrayRef = false;
- *arrayTypeIdRef = TypeIds_Undefined;
- if(!RecyclableObject::Is(var))
- {
- return nullptr;
- }
- JavascriptArray *array = nullptr;
- INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
- if(vtable == VirtualTableInfo<DynamicObject>::Address)
- {
- ArrayObject* objectArray = DynamicObject::FromVar(var)->GetObjectArray();
- array = (objectArray && Is(objectArray)) ? FromVar(objectArray) : nullptr;
- if(!array)
- {
- return nullptr;
- }
- *isObjectWithArrayRef = true;
- vtable = VirtualTableInfoBase::GetVirtualTable(array);
- }
- if(vtable == VirtualTableInfo<JavascriptArray>::Address)
- {
- *arrayTypeIdRef = TypeIds_Array;
- }
- else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
- {
- *arrayTypeIdRef = TypeIds_NativeIntArray;
- }
- else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
- {
- *arrayTypeIdRef = TypeIds_NativeFloatArray;
- }
- else
- {
- return nullptr;
- }
- if(!array)
- {
- array = FromVar(var);
- }
- return array;
- }
- const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
- {
- // This is a helper function used by jitted code
- JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
- return array ? array->head : nullptr;
- }
- uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
- {
- // This is a helper function used by jitted code
- return headSegment ? headSegment->length : 0;
- }
- bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
- const SparseArraySegmentBase *const headSegmentBeforeOperation,
- const uint32 headSegmentLengthBeforeOperation,
- const Var varAfterOperation)
- {
- // This is a helper function used by jitted code
- Assert(varAfterOperation);
- if(!headSegmentBeforeOperation)
- {
- return false;
- }
- const SparseArraySegmentBase *const headSegmentAfterOperation =
- Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
- return
- headSegmentAfterOperation != headSegmentBeforeOperation ||
- headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
- }
- uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
- {
- // This is a helper function used by jitted code
- bool isObjectWithArray;
- TypeId arrayTypeId;
- JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray, &arrayTypeId);
- return array && !isObjectWithArray ? array->GetLength() : 0;
- }
- bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
- {
- // This is a helper function used by jitted code
- return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
- }
- DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
- {
- // This is a helper function used by jitted code
- JavascriptArray *const array = GetArrayForArrayOrObjectWithArray(var);
- return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
- }
- bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
- const DynamicObjectFlags flagsBeforeOperation,
- const Var varAfterOperation)
- {
- // This is a helper function used by jitted code
- Assert(varAfterOperation);
- return
- !!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
- !(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
- }
- bool JavascriptArray::HasNoMissingValues() const
- {
- return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
- }
- bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
- {
- return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
- }
- void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
- {
- SetFlags(
- hasNoMissingValues
- ? GetFlags() | DynamicObjectFlags::HasNoMissingValues
- : GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
- }
- template<class T>
- bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
- {
- Assert(index < head->length);
- return SparseArraySegment<T>::IsMissingItem(&SparseArraySegment<T>::From(head)->elements[index]);
- }
- bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
- {
- return IsMissingHeadSegmentItemImpl<Var>(index);
- }
- #if ENABLE_COPYONACCESS_ARRAY
- void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
- {
- Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
- SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
- SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
- #if ENABLE_DEBUG_CONFIG_OPTIONS
- if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
- {
- Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
- Output::Flush();
- }
- #endif
- newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
- this->SetHeadAndLastUsedSegment(newSeg);
- VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
- this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
- ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
- if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
- {
- arrayInfo->isNotCopyOnAccessArray = 1;
- }
- }
- uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
- {
- if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
- {
- return Js::JavascriptArray::InvalidIndex;
- }
- else if (index == Js::JavascriptArray::InvalidIndex)
- {
- return 0;
- }
- else
- {
- return index + 1;
- }
- }
- BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
- {
- Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
- SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
- if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
- {
- return FALSE;
- }
- else
- {
- *outVal = seg->elements[index];
- return TRUE;
- }
- }
- #endif
- bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
- {
- return IsMissingHeadSegmentItemImpl<int32>(index);
- }
- bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
- {
- return IsMissingHeadSegmentItemImpl<double>(index);
- }
- template<typename T>
- void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, const T& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
- {
- RecyclableObject* prototype = srcArray->GetPrototype();
- while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
- {
- ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
- T n = dstIndex + (index - start);
- dstArray->DirectSetItemAt(n, value);
- count++;
- });
- prototype = prototype->GetPrototype();
- }
- }
- template<>
- void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, const uint32& dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
- {
- RecyclableObject* prototype = srcArray->GetPrototype();
- while (start + count != end && JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
- {
- ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
- uint32 n = dstIndex + (index - start);
- dstArray->SetItem(n, value, PropertyOperation_None);
- count++;
- });
- prototype = prototype->GetPrototype();
- }
- }
- /* static */
- bool JavascriptArray::HasInlineHeadSegment(uint32 length)
- {
- return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
- }
- Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
- {
- // Called only to create array literals: size is known.
- return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
- }
- Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
- {
- // Called only to create array literals: size is known.
- JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
- SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
- Assert(elementCount <= head->length);
- CopyArray(head->elements, head->length, elements, elementCount);
- #ifdef VALIDATE_ARRAY
- arr->ValidateArray();
- #endif
- return arr;
- }
- Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
- {
- // Called only to create array literals: size is known.
- JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
- array->SetHasNoMissingValues(false);
- SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(array->head);
- head->FillSegmentBuffer(0, elementCount);
- return array;
- }
- #if ENABLE_PROFILE_INFO
- Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
- {
- if (arrayInfo->IsNativeIntArray())
- {
- JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
- arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
- return arr;
- }
- if (arrayInfo->IsNativeFloatArray())
- {
- JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
- arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
- return arr;
- }
- JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
- return arr;
- }
- #endif
- Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
- {
- uint32 count = ints->count;
- JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
- SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
- Assert(count > 0 && count == head->length);
- for (uint i = 0; i < count; i++)
- {
- head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
- }
- return arr;
- }
- #if ENABLE_PROFILE_INFO
- Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
- {
- // Called only to create array literals: size is known.
- uint32 count = ints->count;
- if (arrayInfo->IsNativeIntArray())
- {
- JavascriptNativeIntArray *arr;
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary *lib = scriptContext->GetLibrary();
- FunctionBody *functionBody = weakFuncRef->Get();
- if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
- {
- Assert(lib->cacheForCopyOnAccessArraySegments);
- arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
- }
- else
- #endif
- {
- arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
- SparseArraySegment<int32> *head = SparseArraySegment<int32>::From(arr->head);
- Assert(count > 0 && count == head->length);
- CopyArray(head->elements, head->length, ints->elements, count);
- }
- arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
- return arr;
- }
- if (arrayInfo->IsNativeFloatArray())
- {
- JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
- SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
- Assert(count > 0 && count == head->length);
- for (uint i = 0; i < count; i++)
- {
- head->elements[i] = (double)ints->elements[i];
- }
- arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
- return arr;
- }
- return OP_NewScIntArray(ints, scriptContext);
- }
- #endif
- Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
- {
- uint32 count = doubles->count;
- JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
- SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
- Assert(count > 0 && count == head->length);
- for (uint i = 0; i < count; i++)
- {
- double dval = doubles->elements[i];
- int32 ival;
- if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
- {
- head->elements[i] = TaggedInt::ToVarUnchecked(ival);
- }
- else
- {
- head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
- }
- }
- return arr;
- }
- #if ENABLE_PROFILE_INFO
- Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
- {
- // Called only to create array literals: size is known.
- if (arrayInfo->IsNativeFloatArray())
- {
- arrayInfo->SetIsNotNativeIntArray();
- uint32 count = doubles->count;
- JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
- SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
- Assert(count > 0 && count == head->length);
- CopyArray(head->elements, head->length, doubles->elements, count);
- arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
- return arr;
- }
- return OP_NewScFltArray(doubles, scriptContext);
- }
- Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
- {
- ARGUMENTS(args, callInfo);
- Assert(JavascriptFunction::Is(function) &&
- JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
- Assert(callInfo.Count >= 2);
- ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
- JavascriptArray* pNew = nullptr;
- if (callInfo.Count == 2)
- {
- // Exactly one argument, which is the array length if it's a uint32.
- Var firstArgument = args[1];
- int elementCount;
- if (TaggedInt::Is(firstArgument))
- {
- elementCount = TaggedInt::ToInt32(firstArgument);
- if (elementCount < 0)
- {
- JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
- }
- if (arrayInfo && arrayInfo->IsNativeArray())
- {
- if (arrayInfo->IsNativeIntArray())
- {
- pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
- }
- else
- {
- pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
- }
- }
- else
- {
- pNew = function->GetLibrary()->CreateArray(elementCount);
- }
- }
- else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
- {
- // Non-tagged-int number: make sure the double value is really a uint32.
- double value = JavascriptNumber::GetValue(firstArgument);
- uint32 uvalue = JavascriptConversion::ToUInt32(value);
- if (value != uvalue)
- {
- JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
- }
- if (arrayInfo && arrayInfo->IsNativeArray())
- {
- if (arrayInfo->IsNativeIntArray())
- {
- pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
- }
- else
- {
- pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
- }
- }
- else
- {
- pNew = function->GetLibrary()->CreateArray(uvalue);
- }
- }
- else
- {
- //
- // First element is not int/double
- // create an array of length 1.
- // Set first element as the passed Var
- //
- pNew = function->GetLibrary()->CreateArray(1);
- pNew->DirectSetItemAt<Var>(0, firstArgument);
- }
- }
- else
- {
- // Called with a list of initial element values.
- // Create an array of the appropriate length and walk the list.
- if (arrayInfo && arrayInfo->IsNativeArray())
- {
- if (arrayInfo->IsNativeIntArray())
- {
- pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
- }
- else
- {
- pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
- }
- }
- else
- {
- pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
- }
- pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
- }
- #ifdef VALIDATE_ARRAY
- pNew->ValidateArray();
- #endif
- return pNew;
- }
- #endif
- Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
- {
- ARGUMENTS(args, callInfo);
- return NewInstance(function, args);
- }
- Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
- {
- // Call to new Array(), possibly under another name.
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- // SkipDefaultNewObject function flag should have prevented the default object
- // being created, except when call true a host dispatch.
- const CallInfo &callInfo = args.Info;
- Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
- bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
- Assert( isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr
- || JavascriptOperators::GetTypeId(args[0]) == TypeIds_HostDispatch);
- ScriptContext* scriptContext = function->GetScriptContext();
- JavascriptArray* pNew = nullptr;
- if (callInfo.Count < 2)
- {
- // No arguments passed to Array(), so create with the default size (0).
- pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
- return isCtorSuperCall ?
- JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
- pNew;
- }
- if (callInfo.Count == 2)
- {
- // Exactly one argument, which is the array length if it's a uint32.
- Var firstArgument = args[1];
- int elementCount;
- if (TaggedInt::Is(firstArgument))
- {
- elementCount = TaggedInt::ToInt32(firstArgument);
- if (elementCount < 0)
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
- }
- pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
- }
- else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
- {
- // Non-tagged-int number: make sure the double value is really a uint32.
- double value = JavascriptNumber::GetValue(firstArgument);
- uint32 uvalue = JavascriptConversion::ToUInt32(value);
- if (value != uvalue)
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
- }
- pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
- }
- else
- {
- //
- // First element is not int/double
- // create an array of length 1.
- // Set first element as the passed Var
- //
- pNew = CreateArrayFromConstructor(function, 1, scriptContext);
- JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
- // If we were passed an uninitialized JavascriptArray as the this argument,
- // we need to set the length. We must do this _after_ setting the first
- // element as the array may have side effects such as a setter for property
- // named '0' which would make the previous length of the array observable.
- // If we weren't passed a JavascriptArray as the this argument, this is no-op.
- pNew->SetLength(1);
- }
- }
- else
- {
- // Called with a list of initial element values.
- // Create an array of the appropriate length and walk the list.
- pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
- pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
- }
- #ifdef VALIDATE_ARRAY
- pNew->ValidateArray();
- #endif
- return isCtorSuperCall ?
- JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pNew, nullptr, scriptContext) :
- pNew;
- }
- JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
- {
- JavascriptLibrary* library = constructor->GetLibrary();
- // Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
- // Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
- // This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
- // constructor.
- return library->CreateArray(length);
- }
- JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
- {
- JavascriptLibrary* library = constructor->GetLibrary();
- return library->CreateArray();
- }
- #if ENABLE_PROFILE_INFO
- Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
- {
- Assert(JavascriptFunction::Is(function) &&
- JavascriptFunction::FromVar(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
- if (arrayInfo->IsNativeIntArray())
- {
- JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
- arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
- return arr;
- }
- if (arrayInfo->IsNativeFloatArray())
- {
- JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
- arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
- return arr;
- }
- return scriptContext->GetLibrary()->CreateArray();
- }
- #endif
- Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
- {
- ARGUMENTS(args, callInfo);
- return NewInstance(function, args);
- }
- Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
- {
- Assert(!PHASE_OFF1(NativeArrayPhase));
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- const CallInfo &callInfo = args.Info;
- if (callInfo.Count < 2)
- {
- // No arguments passed to Array(), so create with the default size (0).
- return function->GetLibrary()->CreateNativeIntArray();
- }
- JavascriptArray* pNew = nullptr;
- if (callInfo.Count == 2)
- {
- // Exactly one argument, which is the array length if it's a uint32.
- Var firstArgument = args[1];
- int elementCount;
- if (TaggedInt::Is(firstArgument))
- {
- elementCount = TaggedInt::ToInt32(firstArgument);
- if (elementCount < 0)
- {
- JavascriptError::ThrowRangeError(
- function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
- }
- pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
- }
- else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
- {
- // Non-tagged-int number: make sure the double value is really a uint32.
- double value = JavascriptNumber::GetValue(firstArgument);
- uint32 uvalue = JavascriptConversion::ToUInt32(value);
- if (value != uvalue)
- {
- JavascriptError::ThrowRangeError(
- function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
- }
- pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
- }
- else
- {
- //
- // First element is not int/double
- // create an array of length 1.
- // Set first element as the passed Var
- //
- pNew = function->GetLibrary()->CreateArray(1);
- pNew->DirectSetItemAt<Var>(0, firstArgument);
- }
- }
- else
- {
- // Called with a list of initial element values.
- // Create an array of the appropriate length and walk the list.
- JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
- pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
- }
- #ifdef VALIDATE_ARRAY
- pNew->ValidateArray();
- #endif
- return pNew;
- }
- Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
- {
- ARGUMENTS(args, callInfo);
- return NewInstance(function, args);
- }
- Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
- {
- Assert(!PHASE_OFF1(NativeArrayPhase));
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- const CallInfo &callInfo = args.Info;
- if (callInfo.Count < 2)
- {
- // No arguments passed to Array(), so create with the default size (0).
- return function->GetLibrary()->CreateNativeFloatArray();
- }
- JavascriptArray* pNew = nullptr;
- if (callInfo.Count == 2)
- {
- // Exactly one argument, which is the array length if it's a uint32.
- Var firstArgument = args[1];
- int elementCount;
- if (TaggedInt::Is(firstArgument))
- {
- elementCount = TaggedInt::ToInt32(firstArgument);
- if (elementCount < 0)
- {
- JavascriptError::ThrowRangeError(
- function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
- }
- pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
- }
- else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
- {
- // Non-tagged-int number: make sure the double value is really a uint32.
- double value = JavascriptNumber::GetValue(firstArgument);
- uint32 uvalue = JavascriptConversion::ToUInt32(value);
- if (value != uvalue)
- {
- JavascriptError::ThrowRangeError(
- function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
- }
- pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
- }
- else
- {
- //
- // First element is not int/double
- // create an array of length 1.
- // Set first element as the passed Var
- //
- pNew = function->GetLibrary()->CreateArray(1);
- pNew->DirectSetItemAt<Var>(0, firstArgument);
- }
- }
- else
- {
- // Called with a list of initial element values.
- // Create an array of the appropriate length and walk the list.
- JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
- pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
- }
- #ifdef VALIDATE_ARRAY
- pNew->ValidateArray();
- #endif
- return pNew;
- }
- #if ENABLE_PROFILE_INFO
- JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
- #else
- JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
- #endif
- {
- uint i;
- for (i = start; i < length; i++)
- {
- Var item = args[i + 1];
- bool isTaggedInt = TaggedInt::Is(item);
- bool isTaggedIntMissingValue = false;
- #ifdef _M_AMD64
- if (isTaggedInt)
- {
- int32 iValue = TaggedInt::ToInt32(item);
- isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
- }
- #endif
- if (isTaggedInt && !isTaggedIntMissingValue)
- {
- // This is taggedInt case and we verified that item is not missing value in AMD64.
- this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
- }
- else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
- {
- double dvalue = JavascriptNumber::GetValue(item);
- int32 ivalue;
- if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
- {
- this->DirectSetItemAt(i, ivalue);
- }
- else
- {
- #if ENABLE_PROFILE_INFO
- if (arrayInfo)
- {
- arrayInfo->SetIsNotNativeIntArray();
- }
- #endif
- if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
- {
- // Avoid shrinking the number of elements in the head segment. We can still create a new
- // array here, so go ahead.
- JavascriptNativeFloatArray *fArr =
- this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
- return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
- }
- JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
- fArr->DirectSetItemAt(i, dvalue);
- #if ENABLE_PROFILE_INFO
- return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
- #else
- return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
- #endif
- }
- }
- else
- {
- #if ENABLE_PROFILE_INFO
- if (arrayInfo)
- {
- arrayInfo->SetIsNotNativeArray();
- }
- #endif
- #pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
- if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
- {
- // Avoid shrinking the number of elements in the head segment. We can still create a new
- // array here, so go ahead.
- JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
- return arr->JavascriptArray::FillFromArgs(length, 0, args);
- }
- JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
- #if ENABLE_PROFILE_INFO
- return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
- #else
- return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
- #endif
- }
- }
- return this;
- }
- #if ENABLE_PROFILE_INFO
- JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
- #else
- JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
- #endif
- {
- uint i;
- for (i = start; i < length; i++)
- {
- Var item = args[i + 1];
- if (TaggedInt::Is(item))
- {
- this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
- }
- else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
- {
- this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
- }
- else
- {
- JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
- #if ENABLE_PROFILE_INFO
- if (arrayInfo)
- {
- arrayInfo->SetIsNotNativeArray();
- }
- return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
- #else
- return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
- #endif
- }
- }
- return this;
- }
- #if ENABLE_PROFILE_INFO
- JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
- #else
- JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
- #endif
- {
- uint32 i;
- for (i = start; i < length; i++)
- {
- Var item = args[i + 1];
- this->DirectSetItemAt(i, item);
- }
- return this;
- }
- DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
- {
- return scriptContext->GetLibrary()->GetNativeIntArrayType();
- }
- #if ENABLE_COPYONACCESS_ARRAY
- DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
- {
- return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
- }
- #endif
- JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
- {
- #if ENABLE_PROFILE_INFO
- ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
- if (arrayInfo)
- {
- #if DBG
- Js::JavascriptStackWalker walker(intArray->GetScriptContext());
- Js::JavascriptFunction* caller = NULL;
- bool foundScriptCaller = false;
- while(walker.GetCaller(&caller))
- {
- if(caller != NULL && Js::ScriptFunction::Is(caller))
- {
- foundScriptCaller = true;
- break;
- }
- }
- if(foundScriptCaller)
- {
- Assert(caller);
- Assert(caller->GetFunctionBody());
- if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
- {
- Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
- Output::Flush();
- }
- }
- else
- {
- if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
- {
- Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
- Output::Flush();
- }
- }
- #else
- if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
- {
- Output::Print(_u("Conversion: Int array to Float array"));
- Output::Flush();
- }
- #endif
- arrayInfo->SetIsNotNativeIntArray();
- }
- #endif
- // Grow the segments
- ScriptContext *scriptContext = intArray->GetScriptContext();
- Recycler *recycler = scriptContext->GetRecycler();
- SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
- for (seg = intArray->head; seg; seg = nextSeg)
- {
- nextSeg = seg->next;
- uint32 size = seg->size;
- if (size == 0)
- {
- continue;
- }
- uint32 left = seg->left;
- uint32 length = seg->length;
- int i;
- int32 ival;
- // The old segment will have size/2 and length capped by the new size.
- uint32 newSegSize = seg->size >> 1;
- if (seg == intArray->head || seg->length > (newSegSize >> 1))
- {
- // Some live elements are being pushed out of this segment, so allocate a new one.
- SparseArraySegment<double> *newSeg =
- SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
- Assert(newSeg != nullptr);
- Assert((prevSeg == nullptr) == (seg == intArray->head));
- newSeg->next = nextSeg;
- intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
- if (intArray->GetLastUsedSegment() == seg)
- {
- intArray->SetLastUsedSegment(newSeg);
- }
- prevSeg = newSeg;
- SegmentBTree * segmentMap = intArray->GetSegmentMap();
- if (segmentMap)
- {
- segmentMap->SwapSegment(left, seg, newSeg);
- }
- // Fill the new segment with the overflow.
- for (i = 0; (uint)i < newSeg->length; i++)
- {
- ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
- if (ival == JavascriptNativeIntArray::MissingItem)
- {
- continue;
- }
- newSeg->elements[i] = (double)ival;
- }
- }
- else
- {
- seg->size = newSegSize >> 1;
- seg->CheckLengthvsSize();
- // Now convert the contents that will remain in the old segment.
- for (i = seg->length - 1; i >= 0; i--)
- {
- ival = ((SparseArraySegment<int32>*)seg)->elements[i];
- if (ival == JavascriptNativeIntArray::MissingItem)
- {
- ((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
- }
- else
- {
- ((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
- }
- }
- prevSeg = seg;
- }
- }
- if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
- {
- intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
- }
- else
- {
- if (intArray->GetDynamicType()->GetIsLocked())
- {
- DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
- if (typeHandler->IsPathTypeHandler())
- {
- // We can't allow a type with the new type ID to be promoted to the old type.
- // So go to a dictionary type handler, which will orphan the new type.
- // This should be a corner case, so the inability to share the new type is unlikely to matter.
- // If it does matter, try building a path from the new type's built-in root.
- static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
- }
- else
- {
- intArray->ChangeType();
- }
- }
- intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
- }
- if (CrossSite::IsCrossSiteObjectTyped(intArray))
- {
- Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
- VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
- }
- else
- {
- Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
- VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
- }
- return (JavascriptNativeFloatArray*)intArray;
- }
- /*
- * JavascriptArray::ChangeArrayTypeToNativeArray<double>
- * - Converts the Var Array's type to NativeFloat.
- * - Sets the VirtualTable to "JavascriptNativeFloatArray"
- */
- template<>
- void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
- {
- AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
- if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
- {
- varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
- }
- else
- {
- if (varArray->GetDynamicType()->GetIsLocked())
- {
- DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
- if (typeHandler->IsPathTypeHandler())
- {
- // We can't allow a type with the new type ID to be promoted to the old type.
- // So go to a dictionary type handler, which will orphan the new type.
- // This should be a corner case, so the inability to share the new type is unlikely to matter.
- // If it does matter, try building a path from the new type's built-in root.
- static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
- }
- else
- {
- varArray->ChangeType();
- }
- }
- varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
- }
- if (CrossSite::IsCrossSiteObjectTyped(varArray))
- {
- Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
- VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
- }
- else
- {
- Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
- VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
- }
- }
- /*
- * JavascriptArray::ChangeArrayTypeToNativeArray<int32>
- * - Converts the Var Array's type to NativeInt.
- * - Sets the VirtualTable to "JavascriptNativeIntArray"
- */
- template<>
- void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
- {
- AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
- if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
- {
- varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
- }
- else
- {
- if (varArray->GetDynamicType()->GetIsLocked())
- {
- DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
- if (typeHandler->IsPathTypeHandler())
- {
- // We can't allow a type with the new type ID to be promoted to the old type.
- // So go to a dictionary type handler, which will orphan the new type.
- // This should be a corner case, so the inability to share the new type is unlikely to matter.
- // If it does matter, try building a path from the new type's built-in root.
- static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
- }
- else
- {
- varArray->ChangeType();
- }
- }
- varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
- }
- if (CrossSite::IsCrossSiteObjectTyped(varArray))
- {
- Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
- VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
- }
- else
- {
- Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
- VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
- }
- }
- template<>
- int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
- {
- return JavascriptConversion::ToInt32(ival, scriptContext);
- }
- template <>
- double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
- {
- return JavascriptConversion::ToNumber(ival, scriptContext);
- }
- /*
- * JavascriptArray::ConvertToNativeArrayInPlace
- * In place conversion of all Var elements to Native Int/Double elements in an array.
- * We do not update the DynamicProfileInfo of the array here.
- */
- template<typename NativeArrayType, typename T>
- NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
- {
- AssertMsg(!JavascriptNativeArray::Is(varArray), "Ensure that the incoming Array is a Var array");
- ScriptContext *scriptContext = varArray->GetScriptContext();
- SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
- for (seg = varArray->head; seg; seg = nextSeg)
- {
- nextSeg = seg->next;
- uint32 size = seg->size;
- if (size == 0)
- {
- continue;
- }
- int i;
- Var ival;
- uint32 growFactor = sizeof(Var) / sizeof(T);
- AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
- // Now convert the contents that will remain in the old segment.
- for (i = seg->length - 1; i >= 0; i--)
- {
- ival = ((SparseArraySegment<Var>*)seg)->elements[i];
- if (ival == JavascriptArray::MissingItem)
- {
- ((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
- }
- else
- {
- ((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
- }
- }
- prevSeg = seg;
- }
- // Update the type of the Array
- ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
- return (NativeArrayType*)varArray;
- }
- JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
- #endif
- ScriptContext *scriptContext = intArray->GetScriptContext();
- Recycler *recycler = scriptContext->GetRecycler();
- SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
- for (seg = intArray->head; seg; seg = nextSeg)
- {
- nextSeg = seg->next;
- uint32 size = seg->size;
- if (size == 0)
- {
- continue;
- }
- uint32 left = seg->left;
- uint32 length = seg->length;
- int i;
- int32 ival;
- // Shrink?
- uint32 growFactor = sizeof(Var) / sizeof(int32);
- if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size / growFactor))) ||
- (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
- {
- // Some live elements are being pushed out of this segment, so allocate a new one.
- // And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
- SparseArraySegment<Var> *newSeg =
- SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
- AnalysisAssert(newSeg);
- Assert((prevSeg == nullptr) == (seg == intArray->head));
- newSeg->next = nextSeg;
- intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
- if (intArray->GetLastUsedSegment() == seg)
- {
- intArray->SetLastUsedSegment(newSeg);
- }
- prevSeg = newSeg;
- SegmentBTree * segmentMap = intArray->GetSegmentMap();
- if (segmentMap)
- {
- segmentMap->SwapSegment(left, seg, newSeg);
- }
- // Fill the new segment with the overflow.
- for (i = 0; (uint)i < newSeg->length; i++)
- {
- ival = ((SparseArraySegment<int32>*)seg)->elements[i];
- if (ival == JavascriptNativeIntArray::MissingItem)
- {
- continue;
- }
- newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
- }
- }
- else
- {
- seg->size = seg->size / growFactor;
- seg->CheckLengthvsSize();
- // Now convert the contents that will remain in the old segment.
- // Walk backward in case we're growing the element size.
- for (i = seg->length - 1; i >= 0; i--)
- {
- ival = ((SparseArraySegment<int32>*)seg)->elements[i];
- if (ival == JavascriptNativeIntArray::MissingItem)
- {
- ((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
- }
- else
- {
- ((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
- }
- }
- prevSeg = seg;
- }
- }
- if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
- {
- intArray->type = scriptContext->GetLibrary()->GetArrayType();
- }
- else
- {
- if (intArray->GetDynamicType()->GetIsLocked())
- {
- DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
- if (typeHandler->IsPathTypeHandler())
- {
- // We can't allow a type with the new type ID to be promoted to the old type.
- // So go to a dictionary type handler, which will orphan the new type.
- // This should be a corner case, so the inability to share the new type is unlikely to matter.
- // If it does matter, try building a path from the new type's built-in root.
- static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
- }
- else
- {
- intArray->ChangeType();
- }
- }
- intArray->GetType()->SetTypeId(TypeIds_Array);
- }
- if (CrossSite::IsCrossSiteObjectTyped(intArray))
- {
- Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
- VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
- }
- else
- {
- Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
- VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
- }
- return intArray;
- }
- JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
- {
- #if ENABLE_PROFILE_INFO
- ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
- if (arrayInfo)
- {
- #if DBG
- Js::JavascriptStackWalker walker(intArray->GetScriptContext());
- Js::JavascriptFunction* caller = NULL;
- bool foundScriptCaller = false;
- while(walker.GetCaller(&caller))
- {
- if(caller != NULL && Js::ScriptFunction::Is(caller))
- {
- foundScriptCaller = true;
- break;
- }
- }
- if(foundScriptCaller)
- {
- Assert(caller);
- Assert(caller->GetFunctionBody());
- if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
- {
- Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
- Output::Flush();
- }
- }
- else
- {
- if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
- {
- Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
- Output::Flush();
- }
- }
- #else
- if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
- {
- Output::Print(_u("Conversion: Int array to Var array"));
- Output::Flush();
- }
- #endif
- arrayInfo->SetIsNotNativeArray();
- }
- #endif
- intArray->ClearArrayCallSiteIndex();
- return ConvertToVarArray(intArray);
- }
- DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
- {
- return scriptContext->GetLibrary()->GetNativeFloatArrayType();
- }
- /*
- * JavascriptNativeFloatArray::ConvertToVarArray
- * This function only converts all Float elements to Var elements in an array.
- * DynamicProfileInfo of the array is not updated in this function.
- */
- JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
- {
- // We can't be growing the size of the element.
- Assert(sizeof(double) >= sizeof(Var));
- uint32 shrinkFactor = sizeof(double) / sizeof(Var);
- ScriptContext *scriptContext = fArray->GetScriptContext();
- Recycler *recycler = scriptContext->GetRecycler();
- SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
- for (seg = fArray->head; seg; seg = nextSeg)
- {
- nextSeg = seg->next;
- if (seg->size == 0)
- {
- continue;
- }
- uint32 left = seg->left;
- uint32 length = seg->length;
- SparseArraySegment<Var> *newSeg;
- if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
- {
- // The old segment is not scanned by the recycler, so we need a new one to hold vars.
- newSeg =
- SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
- Assert((prevSeg == nullptr) == (seg == fArray->head));
- newSeg->next = nextSeg;
- fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
- if (fArray->GetLastUsedSegment() == seg)
- {
- fArray->SetLastUsedSegment(newSeg);
- }
- prevSeg = newSeg;
- SegmentBTree * segmentMap = fArray->GetSegmentMap();
- if (segmentMap)
- {
- segmentMap->SwapSegment(left, seg, newSeg);
- }
- }
- else
- {
- newSeg = (SparseArraySegment<Var>*)seg;
- prevSeg = seg;
- if (shrinkFactor != 1)
- {
- uint32 newSize = seg->size * shrinkFactor;
- uint32 limit;
- if (seg->next)
- {
- limit = seg->next->left;
- }
- else
- {
- limit = JavascriptArray::MaxArrayLength;
- }
- seg->size = min(newSize, limit - seg->left);
- }
- }
- uint32 i;
- for (i = 0; i < seg->length; i++)
- {
- if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
- {
- if (seg == newSeg)
- {
- newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
- }
- Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
- }
- else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
- {
- newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
- }
- else
- {
- int32 ival;
- double dval = ((SparseArraySegment<double>*)seg)->elements[i];
- if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
- {
- newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
- }
- else
- {
- newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
- }
- }
- }
- if (seg == newSeg && shrinkFactor != 1)
- {
- // Fill the remaining slots.
- newSeg->FillSegmentBuffer(i, seg->size);
- }
- }
- if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
- {
- fArray->type = scriptContext->GetLibrary()->GetArrayType();
- }
- else
- {
- if (fArray->GetDynamicType()->GetIsLocked())
- {
- DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
- if (typeHandler->IsPathTypeHandler())
- {
- // We can't allow a type with the new type ID to be promoted to the old type.
- // So go to a dictionary type handler, which will orphan the new type.
- // This should be a corner case, so the inability to share the new type is unlikely to matter.
- // If it does matter, try building a path from the new type's built-in root.
- static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
- }
- else
- {
- fArray->ChangeType();
- }
- }
- fArray->GetType()->SetTypeId(TypeIds_Array);
- }
- if (CrossSite::IsCrossSiteObjectTyped(fArray))
- {
- Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
- VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
- }
- else
- {
- Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
- VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
- }
- return fArray;
- }
- JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
- {
- #if ENABLE_PROFILE_INFO
- ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
- if (arrayInfo)
- {
- #if DBG
- Js::JavascriptStackWalker walker(fArray->GetScriptContext());
- Js::JavascriptFunction* caller = NULL;
- bool foundScriptCaller = false;
- while(walker.GetCaller(&caller))
- {
- if(caller != NULL && Js::ScriptFunction::Is(caller))
- {
- foundScriptCaller = true;
- break;
- }
- }
- if(foundScriptCaller)
- {
- Assert(caller);
- Assert(caller->GetFunctionBody());
- if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
- {
- Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
- Output::Flush();
- }
- }
- else
- {
- if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
- {
- Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
- Output::Flush();
- }
- }
- #else
- if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
- {
- Output::Print(_u("Conversion: Float array to Var array"));
- Output::Flush();
- }
- #endif
- if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
- {
- Assert(!arrayInfo->IsNativeIntArray());
- }
- arrayInfo->SetIsNotNativeArray();
- }
- #endif
- fArray->ClearArrayCallSiteIndex();
- return ConvertToVarArray(fArray);
- }
- // Convert Var to index in the Array.
- // Note: Spec calls out a few rules for these parameters:
- // 1. if (arg > length) { return length; }
- // clamp to length, not length-1
- // 2. if (arg < 0) { return max(0, length + arg); }
- // treat negative arg as index from the end of the array (with -1 mapping to length-1)
- // Effectively, this function will return a value between 0 and length, inclusive.
- int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
- {
- int64 index;
- if (TaggedInt::Is(arg))
- {
- int intValue = TaggedInt::ToInt32(arg);
- if (intValue < 0)
- {
- index = max<int64>(0, length + intValue);
- }
- else
- {
- index = intValue;
- }
- if (index > length)
- {
- index = length;
- }
- }
- else
- {
- double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
- // Handle the Number.POSITIVE_INFINITY case
- if (doubleValue > length)
- {
- return length;
- }
- index = NumberUtilities::TryToInt64(doubleValue);
- if (index < 0)
- {
- index = max<int64>(0, index + length);
- }
- }
- return index;
- }
- TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
- {
- int32 iValue;
- double dValue;
- TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
- if (typeId == TypeIds_NativeIntArray)
- {
- arr->SetArrayLiteralItem(index, iValue);
- }
- else if (typeId == TypeIds_NativeFloatArray)
- {
- arr->SetArrayLiteralItem(index, dValue);
- }
- else
- {
- arr->SetArrayLiteralItem(index, value);
- }
- return typeId;
- }
- TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
- {
- double dValue;
- TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
- if (typeId == TypeIds_NativeFloatArray)
- {
- arr->SetArrayLiteralItem(index, dValue);
- }
- else
- {
- arr->SetArrayLiteralItem(index, value);
- }
- return typeId;
- }
- template<typename T>
- void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
- {
- SparseArraySegment<T> * segment = SparseArraySegment<T>::From(this->head);
- Assert(segment->left == 0);
- Assert(index < segment->length);
- segment->elements[index] = value;
- }
- void JavascriptNativeIntArray::SetIsPrototype()
- {
- // Force the array to be non-native to simplify inspection, filling from proto, etc.
- ToVarArray(this);
- __super::SetIsPrototype();
- }
- void JavascriptNativeFloatArray::SetIsPrototype()
- {
- // Force the array to be non-native to simplify inspection, filling from proto, etc.
- ToVarArray(this);
- __super::SetIsPrototype();
- }
- #if ENABLE_PROFILE_INFO
- ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
- {
- RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
- if (weakRef)
- {
- FunctionBody *functionBody = weakRef->Get();
- if (functionBody)
- {
- if (functionBody->HasDynamicProfileInfo())
- {
- Js::ProfileId profileId = this->GetArrayCallSiteIndex();
- if (profileId < functionBody->GetProfiledArrayCallSiteCount())
- {
- return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
- }
- }
- }
- else
- {
- this->ClearArrayCallSiteIndex();
- }
- }
- return nullptr;
- }
- void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
- {
- Assert(weakRef);
- FunctionBody *functionBody = weakRef->Get();
- if (functionBody && functionBody->HasDynamicProfileInfo())
- {
- ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
- Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
- Assert(index < functionBody->GetProfiledArrayCallSiteCount());
- SetArrayCallSite(index, weakRef);
- }
- }
- void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
- {
- if (baseArray->weakRefToFuncBody)
- {
- if (baseArray->weakRefToFuncBody->Get())
- {
- SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
- }
- else
- {
- baseArray->ClearArrayCallSiteIndex();
- }
- }
- }
- #endif
- Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
- {
- if (JavascriptNativeIntArray::Is(this))
- {
- return this->FindMinOrMax<int32, false>(scriptContext, findMax);
- }
- else
- {
- return this->FindMinOrMax<double, true>(scriptContext, findMax);
- }
- }
- template <typename T, bool checkNaNAndNegZero>
- Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
- {
- AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
- uint len = this->GetLength();
- Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
- uint headSegLen = headSegment->length;
- Assert(headSegLen == len);
- if (headSegment->next == nullptr)
- {
- T currentRes = headSegment->elements[0];
- for (uint i = 0; i < headSegLen; i++)
- {
- T compare = headSegment->elements[i];
- if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
- {
- return scriptContext->GetLibrary()->GetNaN();
- }
- if (findMax ? currentRes < compare : currentRes > compare ||
- (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
- {
- currentRes = compare;
- }
- }
- return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
- }
- else
- {
- AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
- Throw::FatalInternalError();
- }
- }
- SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
- {
- return HasSegmentMap() ?
- PointerValue(segmentUnion.segmentBTreeRoot->lastUsedSegment) :
- PointerValue(segmentUnion.lastUsedSegment);
- }
- void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
- {
- Assert(!HasSegmentMap());
- this->head = this->segmentUnion.lastUsedSegment = segment;
- }
- void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
- {
- if (HasSegmentMap())
- {
- this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
- }
- else
- {
- this->segmentUnion.lastUsedSegment = segment;
- }
- }
- bool JavascriptArray::HasSegmentMap() const
- {
- return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
- }
- SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
- {
- return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
- }
- void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
- {
- Assert(!HasSegmentMap());
- SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
- SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
- segmentUnion.segmentBTreeRoot = segmentMap;
- segmentMap->lastUsedSegment = lastUsedSeg;
- }
- void JavascriptArray::ClearSegmentMap()
- {
- if (HasSegmentMap())
- {
- SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
- SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
- segmentUnion.segmentBTreeRoot = nullptr;
- segmentUnion.lastUsedSegment = lastUsedSeg;
- }
- }
- SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
- {
- Recycler* recycler = GetRecycler();
- SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
- ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
- {
- tmpSegmentMap->Add(recycler, current);
- return false;
- });
- // There could be OOM during building segment map. Save to array only after its successful completion.
- SetSegmentMap(tmpSegmentMap);
- return tmpSegmentMap;
- }
- void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
- {
- SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
- if (savedSegmentMap)
- {
- //
- // We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
- // array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
- // if adding segment succeeds.
- //
- ClearSegmentMap();
- savedSegmentMap->Add(recycler, seg);
- SetSegmentMap(savedSegmentMap);
- }
- }
- void JavascriptArray::InvalidateLastUsedSegment()
- {
- this->SetLastUsedSegment(this->head);
- }
- DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
- {
- DescriptorFlags flags;
- if (GetSetterBuiltIns(propertyId, info, &flags))
- {
- return flags;
- }
- return __super::GetSetter(propertyId, setterValue, info, requestContext);
- }
- DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
- {
- DescriptorFlags flags;
- PropertyRecord const* propertyRecord;
- this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
- if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
- {
- return flags;
- }
- return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
- }
- bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
- {
- if (propertyId == PropertyIds::length)
- {
- PropertyValueInfo::SetNoCache(info, this);
- *descriptorFlags = WritableData;
- return true;
- }
- return false;
- }
- SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
- {
- SparseArraySegmentBase *seg = nullptr;
- SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
- if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
- {
- seg = lastUsedSeg;
- if(index - lastUsedSeg->left < lastUsedSeg->size)
- {
- return seg;
- }
- }
- SegmentBTreeRoot * segmentMap = GetSegmentMap();
- if(!useSegmentMap || !segmentMap)
- {
- return seg ? seg : PointerValue(this->head);
- }
- if(seg)
- {
- // If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
- // segment map, as it is likely to hit
- SparseArraySegmentBase *const nextSeg = seg->next;
- if(nextSeg)
- {
- if(index < nextSeg->left)
- {
- return seg;
- }
- else if(index - nextSeg->left < nextSeg->size)
- {
- return nextSeg;
- }
- }
- }
- SparseArraySegmentBase *matchOrNextSeg;
- segmentMap->Find(index, seg, matchOrNextSeg);
- return seg ? seg : matchOrNextSeg;
- }
- uint32 JavascriptArray::GetNextIndex(uint32 index) const
- {
- if (JavascriptNativeIntArray::Is((Var)this))
- {
- return this->GetNextIndexHelper<int32>(index);
- }
- else if (JavascriptNativeFloatArray::Is((Var)this))
- {
- return this->GetNextIndexHelper<double>(index);
- }
- return this->GetNextIndexHelper<Var>(index);
- }
- template<typename T>
- uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
- {
- AssertMsg(this->head, "array head should never be null");
- uint candidateIndex;
- if (index == JavascriptArray::InvalidIndex)
- {
- candidateIndex = head->left;
- }
- else
- {
- candidateIndex = index + 1;
- }
- SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
- while (current != nullptr)
- {
- if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
- {
- for (uint i = candidateIndex - current->left; i < current->length; i++)
- {
- if (!SparseArraySegment<T>::IsMissingItem(¤t->elements[i]))
- {
- return i + current->left;
- }
- }
- }
- current = SparseArraySegment<T>::From(current->next);
- if (current != NULL)
- {
- if (candidateIndex < current->left)
- {
- candidateIndex = current->left;
- }
- }
- }
- return JavascriptArray::InvalidIndex;
- }
- // If new length > length, we just reset the length
- // If new length < length, we need to remove the rest of the elements and segment
- void JavascriptArray::SetLength(uint32 newLength)
- {
- if (newLength == length)
- return;
- if (head == EmptySegment)
- {
- // Do nothing to the segment.
- }
- else if (newLength == 0)
- {
- this->ClearElements(head, 0);
- head->length = 0;
- head->next = nullptr;
- SetHasNoMissingValues();
- ClearSegmentMap();
- this->InvalidateLastUsedSegment();
- }
- else if (newLength < length)
- {
- // _ _ 2 3 _ _ 6 7 _ _
- // SetLength(0)
- // 0 <= left -> set *prev = null
- // SetLength(2)
- // 2 <= left -> set *prev = null
- // SetLength(3)
- // 3 !<= left; 3 <= right -> truncate to length - 1
- // SetLength(5)
- // 5 <=
- SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
- Field(SparseArraySegmentBase*)* prev = &head;
- while(next != nullptr)
- {
- if (newLength <= next->left)
- {
- ClearSegmentMap(); // truncate segments, null out segmentMap
- *prev = nullptr;
- break;
- }
- else if (newLength <= (next->left + next->length))
- {
- if (next->next)
- {
- ClearSegmentMap(); // Will truncate segments, null out segmentMap
- }
- uint32 newSegmentLength = newLength - next->left;
- this->ClearElements(next, newSegmentLength);
- next->next = nullptr;
- next->length = newSegmentLength;
- next->CheckLengthvsSize();
- break;
- }
- else
- {
- prev = &next->next;
- next = next->next;
- }
- }
- this->InvalidateLastUsedSegment();
- }
- this->length = newLength;
- #ifdef VALIDATE_ARRAY
- ValidateArray();
- #endif
- }
- BOOL JavascriptArray::SetLength(Var newLength)
- {
- ScriptContext *scriptContext;
- if(TaggedInt::Is(newLength))
- {
- int32 lenValue = TaggedInt::ToInt32(newLength);
- if (lenValue < 0)
- {
- scriptContext = GetScriptContext();
- if (scriptContext->GetThreadContext()->RecordImplicitException())
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
- }
- }
- else
- {
- this->SetLength(lenValue);
- }
- return TRUE;
- }
- scriptContext = GetScriptContext();
- uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
- double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
- if (dblValue == uintValue)
- {
- this->SetLength(uintValue);
- }
- else
- {
- ThreadContext* threadContext = scriptContext->GetThreadContext();
- ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
- if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
- {
- // We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
- // Do nothing and let the jitted code bail out.
- return TRUE;
- }
- if (threadContext->RecordImplicitException())
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
- }
- }
- return TRUE;
- }
- void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
- {
- SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
- }
- void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
- {
- SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
- }
- void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
- {
- SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
- }
- Var JavascriptArray::DirectGetItem(uint32 index)
- {
- SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
- uint32 offset = index - seg->left;
- if (index >= seg->left && offset < seg->length)
- {
- if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
- {
- return seg->elements[offset];
- }
- }
- Var element;
- if (DirectGetItemAtFull(index, &element))
- {
- return element;
- }
- return GetType()->GetLibrary()->GetUndefined();
- }
- Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
- uint32 offset = index - seg->left;
- if (index >= seg->left && offset < seg->length)
- {
- if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
- {
- return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
- }
- }
- Var element;
- if (DirectGetItemAtFull(index, &element))
- {
- return element;
- }
- return GetType()->GetLibrary()->GetUndefined();
- }
- DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- int32 value = 0;
- return this->DirectGetItemAt(index, &value) ? WritableData : None;
- }
- Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
- {
- SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
- uint32 offset = index - seg->left;
- if (index >= seg->left && offset < seg->length)
- {
- if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
- {
- return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
- }
- }
- Var element;
- if (DirectGetItemAtFull(index, &element))
- {
- return element;
- }
- return GetType()->GetLibrary()->GetUndefined();
- }
- Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
- {
- PropertyRecord const * propertyRecord;
- scriptContext->GetOrAddPropertyRecord(propName->GetString(), propName->GetLength(), &propertyRecord);
- return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
- }
- BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
- {
- if (this->DirectGetItemAt(index, outVal))
- {
- return TRUE;
- }
- ScriptContext* requestContext = type->GetScriptContext();
- return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
- }
- //
- // Link prev and current. If prev is NULL, make current the head segment.
- //
- void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
- {
- if (prev)
- {
- prev->next = current;
- }
- else
- {
- Assert(current);
- head = current;
- }
- }
- template<typename T>
- BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
- {
- if (itemIndex >= length)
- {
- return true;
- }
- SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
- while(next != nullptr && next->left <= itemIndex)
- {
- uint32 limit = next->left + next->length;
- if (itemIndex < limit)
- {
- next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
- if(itemIndex - next->left == next->length - 1)
- {
- --next->length;
- next->CheckLengthvsSize();
- }
- else if(next == head)
- {
- SetHasNoMissingValues(false);
- }
- break;
- }
- next = SparseArraySegment<T>::From(next->next);
- }
- #ifdef VALIDATE_ARRAY
- ValidateArray();
- #endif
- return true;
- }
- template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
- {
- return idxDest.ToNumber(scriptContext);
- }
- template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
- {
- // Note this is only for setting Array length which is a uint32
- return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
- }
- template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
- {
- return JavascriptNumber::ToVar(idxDest, scriptContext);
- }
- void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
- {
- if (!succeeded)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
- }
- }
- void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
- {
- if (!succeeded)
- {
- uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
- JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
- }
- }
- BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
- {
- return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
- }
- uint64 JavascriptArray::OP_GetLength(Var obj, ScriptContext *scriptContext)
- {
- if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
- {
- // Casting to uint64 is okay as ToLength will always be >= 0.
- return (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
- }
- else
- {
- return (uint64)JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
- }
- }
- template<typename T>
- void JavascriptArray::TryGetArrayAndLength(Var arg,
- ScriptContext *scriptContext,
- PCWSTR methodName,
- __out JavascriptArray** array,
- __out RecyclableObject** obj,
- __out T * length)
- {
- Assert(array != nullptr);
- Assert(obj != nullptr);
- Assert(length != nullptr);
- if (JavascriptArray::Is(arg) && !JavascriptArray::FromVar(arg)->IsCrossSiteObject())
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arg);
- #endif
- *array = JavascriptArray::FromVar(arg);
- *obj = *array;
- *length = (*array)->length;
- }
- else
- {
- if (!JavascriptConversion::ToObject(arg, scriptContext, obj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, methodName);
- }
- *length = OP_GetLength(*obj, scriptContext);
- *array = nullptr;
- }
- }
- BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
- {
- ScriptContext* scriptContext = pDestObj->GetScriptContext();
- if (idxDest.IsSmallIndex())
- {
- return pDestObj->SetItem(idxDest.GetSmallIndex(), aItem, Js::PropertyOperation_ThrowIfNotExtensible);
- }
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
- return pDestObj->SetProperty(propertyRecord->GetPropertyId(), aItem, PropertyOperation_ThrowIfNotExtensible, nullptr);
- }
- template<typename T>
- void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
- Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest,
- BOOL FirstPromotedItemIsSpreadable, BigIndex FirstPromotedItemLength, bool spreadableCheckedAndTrue)
- {
- // This never gets called.
- Throw::InternalError();
- }
- //
- // Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
- //
- template<typename T>
- void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
- Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest,
- BOOL firstPromotedItemIsSpreadable, BigIndex firstPromotedItemLength, bool spreadableCheckedAndTrue)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- JavascriptArray* pDestArray = nullptr;
- if (JavascriptArray::Is(pDestObj))
- {
- pDestArray = JavascriptArray::FromVar(pDestObj);
- }
- T idxDest = startIdxDest;
- for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
- {
- Var aItem = args[idxArg];
- bool spreadable = spreadableCheckedAndTrue;
- if (!spreadable && scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
- {
- // firstPromotedItemIsSpreadable is ONLY used to resume after a type promotion from uint32 to uint64
- // we do this because calls to IsConcatSpreadable are observable (a big deal for proxies) and we don't
- // want to do the work a second time as soon as we record the length we clear the flag.
- JS_REENTRANT(jsReentLock, spreadable = firstPromotedItemIsSpreadable || JavascriptOperators::IsConcatSpreadable(aItem));
- if (!spreadable)
- {
- JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
- ++idxDest;
- continue;
- }
- }
- else
- {
- spreadableCheckedAndTrue = false; // if it was `true`, reset after the first use
- }
- if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
- && BigIndex(idxDest + JavascriptArray::FromVar(aItem)->length).IsSmallIndex() && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
- {
- if (JavascriptNativeIntArray::Is(aItem))
- {
- JavascriptNativeIntArray *pItemArray = JavascriptNativeIntArray::FromVar(aItem);
- JS_REENTRANT(jsReentLock, CopyNativeIntArrayElementsToVar(pDestArray, idxDest, pItemArray));
- idxDest = idxDest + pItemArray->length;
- }
- else if (JavascriptNativeFloatArray::Is(aItem))
- {
- JavascriptNativeFloatArray *pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
- JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElementsToVar(pDestArray, idxDest, pItemArray));
- idxDest = idxDest + pItemArray->length;
- }
- else
- {
- JavascriptArray* pItemArray = JavascriptArray::FromVar(aItem);
- JS_REENTRANT(jsReentLock, CopyArrayElements(pDestArray, idxDest, pItemArray));
- idxDest = idxDest + pItemArray->length;
- }
- }
- else
- {
- // Flatten if other array or remote array (marked with TypeIds_Array)
- if (DynamicObject::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array || spreadable)
- {
- //CONSIDER: enumerating remote array instead of walking all indices
- BigIndex length;
- if (firstPromotedItemIsSpreadable)
- {
- firstPromotedItemIsSpreadable = false;
- length = firstPromotedItemLength;
- }
- else
- {
- JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext));
- }
- if (PromoteToBigIndex(length,idxDest))
- {
- // This is a special case for spreadable objects. We do not pre-calculate the length
- // in EntryConcat like we do with Arrays because a getProperty on an object Length
- // is observable. The result is we have to check for overflows separately for
- // spreadable objects and promote to a bigger index type when we find them.
- ConcatArgs<BigIndex>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, /*firstPromotedItemIsSpreadable*/true, length);
- return;
- }
- if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
- }
- RecyclableObject* itemObject = RecyclableObject::FromVar(aItem);
- Var subItem;
- uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
- for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(itemObject, idxSubItem));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext));
- if (pDestArray)
- {
- pDestArray->DirectSetItemAt(idxDest, subItem);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest));
- }
- }
- ++idxDest;
- }
- for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
- {
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
- JS_REENTRANT(jsReentLock, BOOL hasProp = JavascriptOperators::HasProperty(itemObject, propertyRecord->GetPropertyId()));
- if (hasProp)
- {
- JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext));
- if (pDestArray)
- {
- pDestArray->DirectSetItemAt(idxDest, subItem);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem));
- }
- }
- ++idxDest;
- }
- }
- else // concat 1 item
- {
- JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
- ++idxDest;
- }
- }
- }
- if (!pDestArray)
- {
- JS_REENTRANT(jsReentLock, pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr));
- }
- else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
- {
- pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
- }
- }
- bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
- {
- return false; // already a big index
- }
- bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
- {
- ::Math::RecordOverflowPolicy destLengthOverflow;
- if (lhs.IsSmallIndex())
- {
- UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
- return destLengthOverflow.HasOverflowed();
- }
- return true;
- }
- JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- uint idxDest = 0u;
- for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
- {
- Var aItem = args[idxArg];
- bool spreadableCheckedAndTrue = false;
- if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
- {
- JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
- if (!JavascriptNativeIntArray::Is(pDestArray))
- {
- ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
- return pDestArray;
- }
- if(!spreadableCheckedAndTrue)
- {
- JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
- idxDest = idxDest + 1;
- if (!JavascriptNativeIntArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
- {
- JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
- return pDestArray;
- }
- continue;
- }
- }
- if (JavascriptNativeIntArray::Is(aItem) && !JavascriptNativeIntArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
- {
- JavascriptNativeIntArray* pItemArray = JavascriptNativeIntArray::FromVar(aItem);
- JS_REENTRANT(jsReentLock, bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray));
- idxDest = idxDest + pItemArray->length;
- if (converted)
- {
- // Copying the last array forced a conversion, so switch over to the var version
- // to finish.
- JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
- return pDestArray;
- }
- }
- else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
- {
- if (TaggedInt::Is(aItem))
- {
- pDestArray->DirectSetItemAt(idxDest, TaggedInt::ToInt32(aItem));
- }
- else
- {
- #if DBG
- int32 int32Value;
- Assert(
- JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) &&
- !SparseArraySegment<int32>::IsMissingItem(&int32Value));
- #endif
- pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
- }
- ++idxDest;
- }
- else
- {
- JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
- BigIndex length;
- JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
- ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
- return pVarDestArray;
- }
- }
- if (pDestArray->GetLength() != idxDest)
- {
- pDestArray->SetLength(idxDest);
- }
- return pDestArray;
- }
- JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- uint idxDest = 0u;
- for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
- {
- Var aItem = args[idxArg];
- bool spreadableCheckedAndTrue = false;
- if (scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled())
- {
- JS_REENTRANT(jsReentLock, spreadableCheckedAndTrue = !scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled() || JavascriptOperators::IsConcatSpreadable(aItem));
- if (!JavascriptNativeFloatArray::Is(pDestArray))
- {
- ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue);
- return pDestArray;
- }
- if (!spreadableCheckedAndTrue)
- {
- JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
- idxDest = idxDest + 1;
- if (!JavascriptNativeFloatArray::Is(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
- {
- JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
- return pDestArray;
- }
- continue;
- }
- }
- bool converted = false;
- if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
- {
- if (JavascriptNativeIntArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes()) // Fast path
- {
- JavascriptNativeIntArray *pIntArray = JavascriptNativeIntArray::FromVar(aItem);
- JS_REENTRANT(jsReentLock, converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntArray));
- idxDest = idxDest + pIntArray->length;
- }
- else if (JavascriptNativeFloatArray::Is(aItem) && !JavascriptArray::FromVar(aItem)->IsFillFromPrototypes())
- {
- JavascriptNativeFloatArray* pItemArray = JavascriptNativeFloatArray::FromVar(aItem);
- JS_REENTRANT(jsReentLock, converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pItemArray));
- idxDest = idxDest + pItemArray->length;
- }
- else
- {
- JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
- BigIndex length;
- JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
- ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, spreadableCheckedAndTrue, length));
- return pVarDestArray;
- }
- if (converted)
- {
- // Copying the last array forced a conversion, so switch over to the var version
- // to finish.
- JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest));
- return pDestArray;
- }
- }
- else
- {
- if (TaggedInt::Is(aItem))
- {
- pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
- }
- else
- {
- Assert(JavascriptNumber::Is(aItem));
- pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
- }
- ++idxDest;
- }
- }
- if (pDestArray->GetLength() != idxDest)
- {
- pDestArray->SetLength(idxDest);
- }
- return pDestArray;
- }
- bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
- {
- return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
- }
- Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
- }
- //
- // Compute the destination ScriptArray size:
- // - Each item, flattening only one level if a ScriptArray.
- //
- uint32 cDestLength = 0;
- JavascriptArray * pDestArray = NULL;
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
- TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
- bool isInt = true;
- bool isFloat = true;
- ::Math::RecordOverflowPolicy destLengthOverflow;
- for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
- {
- Var aItem = args[idxArg];
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
- #endif
- if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
- {
- JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
- if (isFloat)
- {
- if (!JavascriptNativeIntArray::Is(pItemArray))
- {
- isInt = false;
- if (!JavascriptNativeFloatArray::Is(pItemArray))
- {
- isFloat = false;
- }
- }
- }
- cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
- }
- else // Get remote array or object length
- {
- // We already checked for types derived from JavascriptArray. These are types that should behave like array
- // i.e. proxy to array and remote array.
- if (JavascriptOperators::IsArray(aItem))
- {
- // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
- // worth it.
- isInt = false;
- isFloat = false;
- if (!JavascriptProxy::Is(aItem))
- {
- if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
- {
- JS_REENTRANT(jsReentLock,
- int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
- // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
- cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
- }
- else
- {
- JS_REENTRANT(jsReentLock,
- uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
- cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
- }
- }
- remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
- }
- else
- {
- if (isFloat)
- {
- if (BoxConcatItem(aItem, idxArg, scriptContext))
- {
- // A primitive will be boxed, so we have to create a var array for the result.
- isInt = false;
- isFloat = false;
- }
- else if (!TaggedInt::Is(aItem))
- {
- if (!JavascriptNumber::Is(aItem))
- {
- isInt = false;
- isFloat = false;
- }
- else if (isInt)
- {
- int32 int32Value;
- if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
- SparseArraySegment<int32>::IsMissingItem(&int32Value))
- {
- isInt = false;
- }
- }
- }
- else if(isInt)
- {
- int32 int32Value = TaggedInt::ToInt32(aItem);
- if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
- {
- isInt = false;
- }
- }
- }
- remoteTypeIds[idxArg] = TypeIds_Limit;
- cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
- }
- }
- }
- if (destLengthOverflow.HasOverflowed())
- {
- cDestLength = MaxArrayLength;
- isInt = false;
- isFloat = false;
- }
- //
- // Create the destination array
- //
- RecyclableObject* pDestObj = nullptr;
- bool isArray = false;
- JS_REENTRANT(jsReentLock, pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext));
- if (pDestObj)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
- #endif
- // Check the thing that species create made. If it's a native array that can't handle the source
- // data, convert it. If it's a more conservative kind of array than the source data, indicate that
- // so that the data will be converted on copy.
- if (isInt)
- {
- if (JavascriptNativeIntArray::Is(pDestObj))
- {
- isArray = true;
- }
- else
- {
- isInt = false;
- isFloat = JavascriptNativeFloatArray::Is(pDestObj);
- isArray = JavascriptArray::Is(pDestObj);
- }
- }
- else if (isFloat)
- {
- if (JavascriptNativeIntArray::Is(pDestObj))
- {
- JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray::FromVar(pDestObj));
- isArray = true;
- }
- else
- {
- isFloat = JavascriptNativeFloatArray::Is(pDestObj);
- isArray = JavascriptArray::Is(pDestObj);
- }
- }
- else
- {
- if (JavascriptNativeIntArray::Is(pDestObj))
- {
- JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray::FromVar(pDestObj));
- isArray = true;
- }
- else if (JavascriptNativeFloatArray::Is(pDestObj))
- {
- JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray::FromVar(pDestObj));
- isArray = true;
- }
- else
- {
- isArray = JavascriptArray::Is(pDestObj);
- }
- }
- }
- if (pDestObj == nullptr || isArray)
- {
- if (isInt)
- {
- JavascriptNativeIntArray *pIntArray = isArray ? JavascriptNativeIntArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
- pIntArray->EnsureHead<int32>();
- JS_REENTRANT(jsReentLock, pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext));
- }
- else if (isFloat)
- {
- JavascriptNativeFloatArray *pFArray = isArray ? JavascriptNativeFloatArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
- pFArray->EnsureHead<double>();
- JS_REENTRANT(jsReentLock, pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext));
- }
- else
- {
- pDestArray = isArray ? JavascriptArray::FromVar(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
- // if the constructor has changed then we no longer specialize for ints and floats
- pDestArray->EnsureHead<Var>();
- JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow));
- }
- //
- // Return the new array instance.
- //
- #ifdef VALIDATE_ARRAY
- pDestArray->ValidateArray();
- #endif
- return pDestArray;
- }
- Assert(pDestObj);
- JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow));
- return pDestObj;
- }
- void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
- {
- if (destLengthOverflow.HasOverflowed())
- {
- ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
- }
- else
- {
- // Use faster uint32 version if no overflow
- ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
- }
- }
- template<typename T>
- /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
- {
- if (BoxConcatItem(aItem, idxArg, scriptContext))
- {
- // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
- RecyclableObject* pObj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
- }
- if (pDestArray)
- {
- pDestArray->DirectSetItemAt(idxDest, pObj);
- }
- else
- {
- SetArrayLikeObjects(pDestObj, idxDest, pObj);
- }
- }
- else
- {
- if (pDestArray)
- {
- pDestArray->DirectSetItemAt(idxDest, aItem);
- }
- else
- {
- SetArrayLikeObjects(pDestObj, idxDest, aItem);
- }
- }
- }
- int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
- {
- int64 fromIndex;
- if (TaggedInt::Is(arg))
- {
- int intValue = TaggedInt::ToInt32(arg);
- if (intValue >= 0)
- {
- fromIndex = min<int64>(intValue, length - 1);
- }
- else if ((uint32)-intValue > length)
- {
- return length;
- }
- else
- {
- fromIndex = intValue + length;
- }
- }
- else
- {
- double value = JavascriptConversion::ToInteger(arg, scriptContext);
- if (value >= 0)
- {
- fromIndex = (int64)min(value, (double)(length - 1));
- }
- else if (value + length < 0)
- {
- return length;
- }
- else
- {
- fromIndex = (int64)(value + length);
- }
- }
- return fromIndex;
- }
- // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
- // Differences
- // 1. Returns boolean true or false value instead of the search hit index
- // 2. Follows SameValueZero algorithm instead of StrictEquals
- // 3. Missing values are scanned if the search value is undefined
- template <bool includesAlgorithm>
- Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- RecyclableObject* obj = nullptr;
- JavascriptArray* pArr = nullptr;
- BigIndex length;
- Var trueValue = scriptContext->GetLibrary()->GetTrue();
- Var falseValue = scriptContext->GetLibrary()->GetFalse();
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.indexOf"), &pArr, &obj, &length));
- Var search;
- uint32 fromIndex = 0;
- uint64 fromIndex64 = 0;
- // The evaluation of method arguments may change the type of the array. Hence, we do that prior to the actual helper method calls.
- // The if clause of the conditional statement below applies to an JavascriptArray or TypedArray instances. The rest of the conditional
- // clauses apply to an ES5Array or other valid Javascript objects.
- if ((pArr || TypedArrayBase::Is(obj)) && (length.IsSmallIndex() || length.IsUint32Max()))
- {
- uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
- JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(len, args, search, fromIndex, scriptContext));
- if (!gotParam)
- {
- return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
- }
- }
- else if (length.IsSmallIndex())
- {
- JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext));
- if (!gotParam)
- {
- return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
- }
- }
- else
- {
- JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex64, scriptContext));
- if (!gotParam)
- {
- return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
- }
- }
- // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- if (pArr)
- {
- if (length.IsSmallIndex() || length.IsUint32Max())
- {
- uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
- int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext);
- // If we found the search value in the head segment, or if we determined there is no need to search other segments,
- // we stop right here.
- if (index != -1 || fromIndex == -1)
- {
- if (includesAlgorithm)
- {
- //Array.prototype.includes
- return (index == -1) ? falseValue : trueValue;
- }
- else
- {
- //Array.prototype.indexOf
- return JavascriptNumber::ToVar(index, scriptContext);
- }
- }
- // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
- switch (pArr->GetTypeId())
- {
- case Js::TypeIds_Array:
- JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
- case Js::TypeIds_NativeIntArray:
- JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, len, scriptContext));
- case Js::TypeIds_NativeFloatArray:
- JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, len, scriptContext));
- default:
- AssertMsg(FALSE, "invalid array typeid");
- JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
- }
- }
- }
- // source object is not a JavascriptArray but source could be a TypedArray
- if (TypedArrayBase::Is(obj))
- {
- if (length.IsSmallIndex() || length.IsUint32Max())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(TypedArrayBase::FromVar(obj), search, fromIndex, length.GetSmallIndex(), scriptContext));
- }
- }
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext));
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex64, length.GetBigIndex(), scriptContext));
- }
- }
- // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
- Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
- JS_REENTRANT_UNLOCK(jsReentLock, Var returnValue = IndexOfHelper<false>(args, scriptContext));
- //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
- Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
- return returnValue;
- }
- Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
- JS_REENTRANT(jsReentLock, Var returnValue = IndexOfHelper<true>(args, scriptContext));
- Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
- return returnValue;
- }
- template<typename T>
- BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
- {
- if (length == 0)
- {
- return false;
- }
- if (args.Info.Count > 2)
- {
- fromIndex = GetFromIndex(args[2], length, scriptContext);
- if (fromIndex >= length)
- {
- return false;
- }
- search = args[1];
- }
- else
- {
- fromIndex = 0;
- search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
- }
- return true;
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- // Note: Sometime cross site array go down this path to get the marshalling
- Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
- && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
- && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
- if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
- {
- return FALSE;
- }
- return JavascriptOperators::GetItem(obj, index, element, scriptContext);
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- // Note: Sometime cross site array go down this path to get the marshalling
- Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
- && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
- && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
- if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
- {
- return FALSE;
- }
- *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
- return *element != scriptContext->GetLibrary()->GetUndefined();
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
- || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
- return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- // This should never get called.
- Assert(false);
- Throw::InternalError();
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
- || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
- return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- // This should never get called.
- Assert(false);
- Throw::InternalError();
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
- || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
- return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- // This should never get called.
- Assert(false);
- Throw::InternalError();
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
- // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
- // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
- // we don't know whether or not length == typedArrayBase->GetLength().
- if (checkHasItem && !typedArrayBase->HasItem(index))
- {
- return false;
- }
- *element = typedArrayBase->DirectGetItem(index);
- return true;
- }
- template <>
- BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
- {
- // This should never get called.
- Assert(false);
- Throw::InternalError();
- }
- template <bool includesAlgorithm, typename T, typename P>
- Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
- {
- Var element = nullptr;
- bool isSearchTaggedInt = TaggedInt::Is(search);
- bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
- Var trueValue = scriptContext->GetLibrary()->GetTrue();
- Var falseValue = scriptContext->GetLibrary()->GetFalse();
- //Consider: enumerating instead of walking all indices
- for (P i = fromIndex; i < toIndex; i++)
- {
- if (!TryTemplatedGetItem(pArr, i, &element, scriptContext, !includesAlgorithm))
- {
- if (doUndefinedSearch)
- {
- return trueValue;
- }
- continue;
- }
- if (isSearchTaggedInt && TaggedInt::Is(element))
- {
- if (element == search)
- {
- return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
- }
- continue;
- }
- if (includesAlgorithm)
- {
- //Array.prototype.includes
- if (JavascriptConversion::SameValueZero(element, search))
- {
- return trueValue;
- }
- }
- else
- {
- //Array.prototype.indexOf
- if (JavascriptOperators::StrictEqual(element, search, scriptContext))
- {
- return JavascriptNumber::ToVar(i, scriptContext);
- }
- }
- }
- return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
- }
- int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
- {
- Assert(Is(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
- if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
- {
- return -1;
- }
- bool isSearchTaggedInt = TaggedInt::Is(search);
- // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
- // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
- // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
- SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
- uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
- for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
- {
- Var element = head->GetElement(i);
- if (isSearchTaggedInt && TaggedInt::Is(element))
- {
- if (search == element)
- {
- return i;
- }
- }
- else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
- {
- //Array.prototype.includes
- return i;
- }
- else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
- {
- //Array.prototype.indexOf
- return i;
- }
- }
- // Element not found in the head segment. Keep looking only if the range of indices extends past
- // the head segment.
- fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
- return -1;
- }
- template<typename T>
- bool AreAllBytesEqual(T value)
- {
- byte* bValue = (byte*)&value;
- byte firstByte = *bValue++;
- for (int i = 1; i < sizeof(T); ++i)
- {
- if (*bValue++ != firstByte)
- {
- return false;
- }
- }
- return true;
- }
- template<>
- void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(double)* buffer, uint32 length, double value)
- {
- if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
- {
- memset(buffer, 0, sizeof(double) * length);
- }
- else
- {
- for (uint32 i = 0; i < length; i++)
- {
- buffer[i] = value;
- }
- }
- }
- template<>
- void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(int32)* buffer, uint32 length, int32 value)
- {
- if (value == 0 || AreAllBytesEqual(value))
- {
- memset(buffer, *(byte*)&value, sizeof(int32)* length);
- }
- else
- {
- for (uint32 i = 0; i < length; i++)
- {
- buffer[i] = value;
- }
- }
- }
- template<>
- void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(Js::Var)* buffer, uint32 length, Js::Var value)
- {
- for (uint32 i = 0; i < length; i++)
- {
- buffer[i] = value;
- }
- }
- int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
- {
- // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
- // 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:
- // 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
- // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
- // 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.
- // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
- if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
- {
- return -1;
- }
- bool isSearchTaggedInt = TaggedInt::Is(search);
- if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
- {
- // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
- // the head segment has no gaps.
- fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
- return -1;
- }
- int32 searchAsInt32;
- if (isSearchTaggedInt)
- {
- searchAsInt32 = TaggedInt::ToInt32(search);
- }
- else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
- {
- // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
- // the head segment has no gaps.
- fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
- return -1;
- }
- // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
- // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
- // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
- SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
- uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
- for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
- {
- int32 element = head->GetElement(i);
- if (searchAsInt32 == element)
- {
- return i;
- }
- }
- // Element not found in the head segment. Keep looking only if the range of indices extends past
- // the head segment.
- fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
- return -1;
- }
- int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
- {
- // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
- // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
- // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
- // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
- // 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.
- // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
- if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
- {
- return -1;
- }
- bool isSearchTaggedInt = TaggedInt::Is(search);
- if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
- {
- // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
- // the head segment has no gaps.
- fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
- return -1;
- }
- double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
- // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
- // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
- // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
- SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
- uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
- bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
- for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
- {
- double element = head->GetElement(i);
- if (element == searchAsDouble)
- {
- return i;
- }
- //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
- if (matchNaN && JavascriptNumber::IsNan(element))
- {
- return i;
- }
- }
- fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
- return -1;
- }
- Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
- }
- JavascriptString* separator;
- if (args.Info.Count >= 2)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
- //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
- if (TypeIds_Undefined != typeId)
- {
- JS_REENTRANT(jsReentLock, separator = JavascriptConversion::ToString(args[1], scriptContext));
- }
- else
- {
- separator = scriptContext->GetLibrary()->GetCommaDisplayString();
- }
- }
- else
- {
- separator = scriptContext->GetLibrary()->GetCommaDisplayString();
- }
- JS_REENTRANT_UNLOCK(jsReentLock, return JoinHelper(args[0], separator, scriptContext));
- }
- JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(value);
- if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
- {
- return scriptContext->GetLibrary()->GetEmptyString();
- }
- else
- {
- return JavascriptConversion::ToString(value, scriptContext);
- }
- }
- JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- bool isArray = JavascriptArray::Is(thisArg) && (scriptContext == JavascriptArray::FromVar(thisArg)->GetScriptContext());
- bool isProxy = JavascriptProxy::Is(thisArg) && (scriptContext == JavascriptProxy::FromVar(thisArg)->GetScriptContext());
- Var target = NULL;
- bool isTargetObjectPushed = false;
- // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
- // call the join helper for the target of this proxy, we will return above.
- if (isProxy)
- {
- JavascriptProxy* proxy = JavascriptProxy::FromVar(thisArg);
- Assert(proxy);
- target = proxy->GetTarget();
- if (target != nullptr)
- {
- // If we end up joining same array, instead of going in infinite loop, return the empty string
- if (scriptContext->CheckObject(target))
- {
- return scriptContext->GetLibrary()->GetEmptyString();
- }
- else
- {
- scriptContext->PushObject(target);
- isTargetObjectPushed = true;
- }
- }
- }
- // If we end up joining same array, instead of going in infinite loop, return the empty string
- else if (scriptContext->CheckObject(thisArg))
- {
- return scriptContext->GetLibrary()->GetEmptyString();
- }
- if (!isTargetObjectPushed)
- {
- scriptContext->PushObject(thisArg);
- }
- JavascriptString* res = nullptr;
- TryFinally([&]()
- {
- if (isArray)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
- #endif
- JavascriptArray * arr = JavascriptArray::FromVar(thisArg);
- switch (arr->GetTypeId())
- {
- case Js::TypeIds_Array:
- JS_REENTRANT(jsReentLock, res = JoinArrayHelper(arr, separator, scriptContext));
- break;
- case Js::TypeIds_NativeIntArray:
- JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeIntArray::FromVar(arr), separator, scriptContext));
- break;
- case Js::TypeIds_NativeFloatArray:
- JS_REENTRANT(jsReentLock, res = JoinArrayHelper(JavascriptNativeFloatArray::FromVar(arr), separator, scriptContext));
- break;
- }
- }
- else if (RecyclableObject::Is(thisArg))
- {
- JS_REENTRANT(jsReentLock, res = JoinOtherHelper(RecyclableObject::FromVar(thisArg), separator, scriptContext));
- }
- else
- {
- JS_REENTRANT(jsReentLock, res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext));
- }
- },
- [&](bool/*hasException*/)
- {
- Var top = scriptContext->PopObject();
- if (isProxy)
- {
- AssertMsg(top == target, "Unmatched operation stack");
- }
- else
- {
- AssertMsg(top == thisArg, "Unmatched operation stack");
- }
- });
- if (res == nullptr)
- {
- res = scriptContext->GetLibrary()->GetEmptyString();
- }
- return res;
- }
- static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
- template <typename T>
- JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
- const uint32 arrLength = arr->length;
- switch(arrLength)
- {
- default:
- {
- CaseDefault:
- bool hasSeparator = (separator->GetLength() != 0);
- const charcount_t estimatedAppendCount =
- min(
- Join_MaxEstimatedAppendCount,
- static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
- CompoundString *const cs =
- CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
- Var item;
- BOOL gotItem;
- JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
- }
- for (uint32 i = 1; i < arrLength; i++)
- {
- if (hasSeparator)
- {
- cs->Append(separator);
- }
- JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, i, &item, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
- }
- }
- return cs;
- }
- case 2:
- {
- bool hasSeparator = (separator->GetLength() != 0);
- BOOL gotItem;
- if(hasSeparator)
- {
- goto CaseDefault;
- }
- JavascriptString *res = nullptr;
- Var item;
- JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(item, scriptContext));
- }
- JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem(arr, 1u, &item, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext));
- return res ? ConcatString::New(res, itemString) : itemString;
- }
- if(res)
- {
- return res;
- }
- goto Case0;
- }
- case 1:
- {
- Var item;
- BOOL gotItem;
- JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(item, scriptContext));
- }
- // fall through
- }
- case 0:
- Case0:
- return scriptContext->GetLibrary()->GetEmptyString();
- }
- }
- JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // In ES6-mode, we always load the length property from the object instead of using the internal slot.
- // Even for arrays, this is now observable via proxies.
- // If source object is not an array, we fall back to this behavior anyway.
- JS_REENTRANT(jsReentLock,
- int64 cSrcLength = (int64)OP_GetLength(object, scriptContext));
- switch (cSrcLength)
- {
- default:
- {
- CaseDefault:
- bool hasSeparator = (separator->GetLength() != 0);
- BOOL gotItem;
- const charcount_t estimatedAppendCount =
- min(
- Join_MaxEstimatedAppendCount,
- static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
- CompoundString *const cs =
- CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
- Var value;
- JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
- }
- for (uint32 i = 1; i < cSrcLength; i++)
- {
- if (hasSeparator)
- {
- cs->Append(separator);
- }
- JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, i, &value, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
- }
- }
- return cs;
- }
- case 2:
- {
- bool hasSeparator = (separator->GetLength() != 0);
- BOOL gotItem;
- if(hasSeparator)
- {
- goto CaseDefault;
- }
- JavascriptString *res = nullptr;
- Var value;
- JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(value, scriptContext));
- }
- JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 1u, &value, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext));
- return res ? ConcatString::New(res, valueString) : valueString;
- }
- if(res)
- {
- return res;
- }
- goto Case0;
- }
- case 1:
- {
- Var value;
- JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(value, scriptContext));
- }
- // fall through
- }
- case 0:
- Case0:
- return scriptContext->GetLibrary()->GetEmptyString();
- }
- }
- Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
- Assert(!(callInfo.Flags & CallFlags_New));
- int64 length;
- JavascriptArray * pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.lastIndexOf"), &pArr, &obj, &length));
- Var search;
- int64 fromIndex;
- JS_REENTRANT(jsReentLock,
- BOOL gotParam = GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext));
- if (!gotParam)
- {
- return TaggedInt::ToVarUnchecked(-1);
- }
- // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- if (pArr)
- {
- switch (pArr->GetTypeId())
- {
- case Js::TypeIds_Array:
- JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
- case Js::TypeIds_NativeIntArray:
- JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeIntArray::FromVar(pArr), search, fromIndex, scriptContext));
- case Js::TypeIds_NativeFloatArray:
- JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(JavascriptNativeFloatArray::FromVar(pArr), search, fromIndex, scriptContext));
- default:
- AssertMsg(FALSE, "invalid array typeid");
- JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
- }
- }
- // source object is not a JavascriptArray but source could be a TypedArray
- if (TypedArrayBase::Is(obj))
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(TypedArrayBase::FromVar(obj), search, fromIndex, scriptContext));
- }
- JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(obj, search, fromIndex, scriptContext));
- }
- // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
- BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
- {
- if (length == 0)
- {
- return false;
- }
- if (args.Info.Count > 2)
- {
- fromIndex = GetFromLastIndex(args[2], length, scriptContext);
- if (fromIndex >= length)
- {
- return false;
- }
- search = args[1];
- }
- else
- {
- search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
- fromIndex = length - 1;
- }
- return true;
- }
- template <typename T>
- Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
- {
- Var element = nullptr;
- bool isSearchTaggedInt = TaggedInt::Is(search);
- // First handle the indices > 2^32
- while (fromIndex >= MaxArrayLength)
- {
- Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
- if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
- {
- element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
- if (isSearchTaggedInt && TaggedInt::Is(element))
- {
- if (element == search)
- {
- return index;
- }
- fromIndex--;
- continue;
- }
- if (JavascriptOperators::StrictEqual(element, search, scriptContext))
- {
- return index;
- }
- }
- fromIndex--;
- }
- Assert(fromIndex < MaxArrayLength);
- // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
- uint32 end = static_cast<uint32>(fromIndex);
- for (uint32 i = 0; i <= end; i++)
- {
- uint32 index = end - i;
- if (!TryTemplatedGetItem(pArr, index, &element, scriptContext))
- {
- continue;
- }
- if (isSearchTaggedInt && TaggedInt::Is(element))
- {
- if (element == search)
- {
- return JavascriptNumber::ToVar(index, scriptContext);
- }
- continue;
- }
- if (JavascriptOperators::StrictEqual(element, search, scriptContext))
- {
- return JavascriptNumber::ToVar(index, scriptContext);
- }
- }
- return TaggedInt::ToVarUnchecked(-1);
- }
- /*
- * PopWithNoDst
- * - For pop calls that do not return a value, we only need to decrement the length of the array.
- */
- void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
- {
- Assert(JavascriptNativeArray::Is(nativeArray));
- JavascriptArray * arr = JavascriptArray::FromVar(nativeArray);
- // we will bailout on length 0
- Assert(arr->GetLength() != 0);
- uint32 index = arr->GetLength() - 1;
- arr->SetLength(index);
- }
- /*
- * JavascriptNativeIntArray::Pop
- * - Returns int32 value from the array.
- * - Returns missing item when the element is not available in the array object.
- * - It doesn't walk up the prototype chain.
- * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
- * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
- */
- int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
- {
- Assert(JavascriptNativeIntArray::Is(object));
- JavascriptNativeIntArray * arr = JavascriptNativeIntArray::FromVar(object);
- Assert(arr->GetLength() != 0);
- uint32 index = arr->length - 1;
- int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
- //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
- if(!SparseArraySegment<int32>::IsMissingItem(&element))
- {
- arr->SetLength(index);
- }
- return element;
- }
- /*
- * JavascriptNativeFloatArray::Pop
- * - Returns double value from the array.
- * - Returns missing item when the element is not available in the array object.
- * - It doesn't walk up the prototype chain.
- * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
- * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
- */
- double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
- {
- Assert(JavascriptNativeFloatArray::Is(object));
- JavascriptNativeFloatArray * arr = JavascriptNativeFloatArray::FromVar(object);
- Assert(arr->GetLength() != 0);
- uint32 index = arr->length - 1;
- double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
- // If it is a missing item then don't update the length - Pre-op Bail out will happen.
- if(!SparseArraySegment<double>::IsMissingItem(&element))
- {
- arr->SetLength(index);
- }
- return element;
- }
- /*
- * JavascriptArray::Pop
- * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
- * - This API may cause implicit calls. Handles Array and non-array objects
- */
- Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
- {
- if (JavascriptArray::Is(object))
- {
- return EntryPopJavascriptArray(scriptContext, object);
- }
- else
- {
- return EntryPopNonJavascriptArray(scriptContext, object);
- }
- }
- Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, Var object)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- JavascriptArray * arr = JavascriptArray::FromVar(object);
- uint32 length = arr->length;
- if (length == 0)
- {
- // If length is 0, return 'undefined'
- return scriptContext->GetLibrary()->GetUndefined();
- }
- uint32 index = length - 1;
- Var element;
- JS_REENTRANT(jsReentLock, BOOL gotItem = arr->DirectGetItemAtFull(index, &element));
- if (!gotItem)
- {
- element = scriptContext->GetLibrary()->GetUndefined();
- }
- else
- {
- element = CrossSite::MarshalVar(scriptContext, element);
- }
- arr->SetLength(index); // SetLength will clear element at index
- #ifdef VALIDATE_ARRAY
- arr->ValidateArray();
- #endif
- return element;
- }
- Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- RecyclableObject* dynamicObject = nullptr;
- if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
- }
- JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
- if (length == 0u)
- {
- // Set length = 0
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- return scriptContext->GetLibrary()->GetUndefined();
- }
- BigIndex index = length;
- --index;
- Var element;
- if (index.IsSmallIndex())
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext));
- if (!gotItem)
- {
- element = scriptContext->GetLibrary()->GetUndefined();
- }
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
- // Set the new length
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- else
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext));
- if (!gotItem)
- {
- element = scriptContext->GetLibrary()->GetUndefined();
- }
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
- // Set the new length
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- return element;
- }
- Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
- }
- if (JavascriptArray::Is(args[0]))
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopJavascriptArray(scriptContext, args.Values[0]));
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopNonJavascriptArray(scriptContext, args.Values[0]));
- }
- }
- /*
- * JavascriptNativeIntArray::Push
- * Pushes Int element in a native Int Array.
- * We call the generic Push, if the array is not native Int or we have a really big array.
- */
- Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
- {
- // Handle non crossSite native int arrays here length within MaxArrayLength.
- // JavascriptArray::Push will handle other cases.
- if (JavascriptNativeIntArray::IsNonCrossSite(array))
- {
- JavascriptNativeIntArray * nativeIntArray = JavascriptNativeIntArray::FromVar(array);
- Assert(!nativeIntArray->IsCrossSiteObject());
- uint32 n = nativeIntArray->length;
- if(n < JavascriptArray::MaxArrayLength)
- {
- nativeIntArray->SetItem(n, value);
- n++;
- AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
- return JavascriptNumber::ToVar(n, scriptContext);
- }
- }
- return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
- }
- /*
- * JavascriptNativeFloatArray::Push
- * Pushes Float element in a native Int Array.
- * We call the generic Push, if the array is not native Float or we have a really big array.
- */
- Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var * array, double value)
- {
- // Handle non crossSite native int arrays here length within MaxArrayLength.
- // JavascriptArray::Push will handle other cases.
- if(JavascriptNativeFloatArray::IsNonCrossSite(array))
- {
- JavascriptNativeFloatArray * nativeFloatArray = JavascriptNativeFloatArray::FromVar(array);
- Assert(!nativeFloatArray->IsCrossSiteObject());
- uint32 n = nativeFloatArray->length;
- if(n < JavascriptArray::MaxArrayLength)
- {
- nativeFloatArray->SetItem(n, value);
- n++;
- AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
- return JavascriptNumber::ToVar(n, scriptContext);
- }
- }
- return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
- }
- /*
- * JavascriptArray::Push
- * Pushes Var element in a Var Array.
- */
- Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
- {
- Var args[2];
- args[0] = object;
- args[1] = value;
- if (JavascriptArray::Is(object))
- {
- return EntryPushJavascriptArray(scriptContext, args, 2);
- }
- else
- {
- return EntryPushNonJavascriptArray(scriptContext, args, 2);
- }
- }
- /*
- * EntryPushNonJavascriptArray
- * - Handles Entry push calls, when Objects are not javascript arrays
- */
- Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- RecyclableObject* obj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
- }
- JS_REENTRANT_UNLOCK(jsReentLock, Var length = JavascriptOperators::OP_GetLength(obj, scriptContext));
- if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
- scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
- {
- return length;
- }
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
- BigIndex n;
- if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
- {
- n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
- }
- else
- {
- n = JavascriptConversion::ToUInt32(length, scriptContext);
- }
- // First handle "small" indices.
- uint index;
- for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
- {
- JS_REENTRANT(jsReentLock,
- BOOL setItem = JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible));
- if (h.IsThrowTypeError(setItem))
- {
- if (scriptContext->GetThreadContext()->RecordImplicitException())
- {
- h.ThrowTypeErrorOnFailure();
- }
- else
- {
- return nullptr;
- }
- }
- }
- // Use BigIndex if we need to push indices >= MaxArrayLength
- if (index < argCount)
- {
- BigIndex big = n;
- for (; index < argCount; ++index, ++big)
- {
- JS_REENTRANT(jsReentLock, BOOL setItem = big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible));
- if (h.IsThrowTypeError(setItem))
- {
- if(scriptContext->GetThreadContext()->RecordImplicitException())
- {
- h.ThrowTypeErrorOnFailure();
- }
- else
- {
- return nullptr;
- }
- }
- }
- // Set the new length; for objects it is all right for this to be >= MaxArrayLength
- JS_REENTRANT(jsReentLock,
- BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
- if (h.IsThrowTypeError(setLength))
- {
- if(scriptContext->GetThreadContext()->RecordImplicitException())
- {
- h.ThrowTypeErrorOnFailure();
- }
- else
- {
- return nullptr;
- }
- }
- return big.ToNumber(scriptContext);
- }
- else
- {
- // Set the new length
- Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
- JS_REENTRANT(jsReentLock,
- BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible));
- if (h.IsThrowTypeError(setLength))
- {
- if(scriptContext->GetThreadContext()->RecordImplicitException())
- {
- h.ThrowTypeErrorOnFailure();
- }
- else
- {
- return nullptr;
- }
- }
- return lengthAsNUmberVar;
- }
- }
- /*
- * JavascriptArray::EntryPushJavascriptArray
- * Pushes Var element in a Var Array.
- * Returns the length of the array.
- */
- Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
- {
- JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
- uint n = arr->length;
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
- // Fast Path for one push for small indexes
- if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
- {
- // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
- h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
- return JavascriptNumber::ToVar(n + 1, scriptContext);
- }
- // Fast Path for multiple push for small indexes
- if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
- {
- uint index;
- for (index = 1; index < argCount; ++index, ++n)
- {
- Assert(n != JavascriptArray::MaxArrayLength);
- // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
- arr->JavascriptArray::DirectSetItemAt(n, args[index]);
- }
- return JavascriptNumber::ToVar(n, scriptContext);
- }
- return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
- }
- Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
- uint n = arr->length;
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
- // First handle "small" indices.
- uint index;
- for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
- {
- // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
- h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
- }
- // Use BigIndex if we need to push indices >= MaxArrayLength
- if (index < argCount)
- {
- // Not supporting native array with BigIndex.
- arr = EnsureNonNativeArray(arr);
- Assert(n == JavascriptArray::MaxArrayLength);
- for (BigIndex big = n; index < argCount; ++index, ++big)
- {
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index])));
- }
- #ifdef VALIDATE_ARRAY
- arr->ValidateArray();
- #endif
- // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
- }
- #ifdef VALIDATE_ARRAY
- arr->ValidateArray();
- #endif
- return JavascriptNumber::ToVar(n, scriptContext);
- }
- /*
- * JavascriptArray::EntryPush
- * Handles Push calls(Script Function)
- */
- Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
- }
- if (JavascriptArray::Is(args[0]))
- {
- return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
- }
- else
- {
- return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
- }
- }
- template <typename T>
- void JavascriptArray::CopyHeadIfInlinedHeadSegment(JavascriptArray *array, Recycler *recycler)
- {
- SparseArraySegmentBase* inlineHeadSegment = nullptr;
- bool hasInlineSegment = false;
- if (JavascriptNativeArray::Is(array))
- {
- if (JavascriptNativeFloatArray::Is(array))
- {
- inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)array);
- }
- else if (JavascriptNativeIntArray::Is(array))
- {
- inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)array);
- }
- Assert(inlineHeadSegment);
- hasInlineSegment = (array->head == (SparseArraySegment<T>*)inlineHeadSegment);
- }
- else
- {
- hasInlineSegment = HasInlineHeadSegment(array->head->length);
- }
- if (hasInlineSegment)
- {
- AnalysisAssert(array->head);
- SparseArraySegment<T>* newHeadSeg = array->ReallocNonLeafSegment((SparseArraySegment<T>*)PointerValue(array->head), array->head->next);
- array->head = newHeadSeg;
- }
- }
- template <typename T>
- void JavascriptArray::ReallocateNonLeafLastSegmentIfLeaf(JavascriptArray * arr, Recycler * recycler)
- {
- Assert(arr->head && arr->head->next); // Doesn't make sense to reallocate a leaf last segment as a non-leaf if its not going to point to any other segments.
- // TODO: Consider utilizing lastUsedSegment once we fix CopyHeadIfInlinedHeadSegment in that respect.
- SparseArraySegmentBase *lastSeg = nullptr;
- SparseArraySegmentBase *seg = arr->head;
- while (seg)
- {
- lastSeg = seg;
- seg = seg->next;
- }
- if (SparseArraySegmentBase::IsLeafSegment(lastSeg, recycler))
- {
- AnalysisAssert(lastSeg);
- arr->ReallocNonLeafSegment((SparseArraySegment<T>*)lastSeg, lastSeg->next, true /*forceNonLeaf*/);
- }
- }
- Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
- }
- BigIndex length = 0u;
- JavascriptArray* pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reverse"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext));
- }
- 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
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext));
- }
- // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
- template <typename T>
- Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- T middle = length / 2;
- Var lowerValue = nullptr, upperValue = nullptr;
- T lowerExists, upperExists;
- const char16* methodName;
- bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
- if (isTypedArrayEntryPoint)
- {
- methodName = _u("[TypedArray].prototype.reverse");
- }
- else
- {
- methodName = _u("Array.prototype.reverse");
- }
- // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
- if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
- if (pArr)
- {
- Recycler * recycler = scriptContext->GetRecycler();
- if (length <= 1)
- {
- return pArr;
- }
- if (pArr->IsFillFromPrototypes())
- {
- // For odd-length arrays, the middle element is unchanged,
- // so we cannot fill it from the prototypes.
- if (length % 2 == 0)
- {
- JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, (uint32)length));
- }
- else
- {
- middle = length / 2;
- JS_REENTRANT(jsReentLock,
- pArr->FillFromPrototypes(0, (uint32)middle),
- pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length));
- }
- }
- if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
- {
- // This function currently does not track missing values in the head segment if there are multiple segments
- pArr->SetHasNoMissingValues(false);
- }
- // Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
- // not work with the stale length. Update the length.
- // Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
- length = pArr->length;
- SparseArraySegmentBase *prevSeg = nullptr;
- SparseArraySegmentBase *nextSeg = nullptr;
- SparseArraySegmentBase *pinPrevSeg = nullptr;
- bool isIntArray = false;
- bool isFloatArray = false;
- pArr->ClearSegmentMap(); // Just dump the segment map on reverse
- if (JavascriptNativeIntArray::Is(pArr))
- {
- isIntArray = true;
- }
- else if (JavascriptNativeFloatArray::Is(pArr))
- {
- isFloatArray = true;
- }
- // During the loop below we are going to reverse the segments list. The head segment will become the last segment.
- // We have to verify that the current head segment is not the inilined segement, otherwise due to shuffling below, the inlined segment will no longer
- // be the head and that can create issue down the line. Create new segment if it is an inilined segment.
- if (pArr->head && pArr->head->next)
- {
- if (isIntArray)
- {
- CopyHeadIfInlinedHeadSegment<int32>(pArr, recycler);
- ReallocateNonLeafLastSegmentIfLeaf<int32>(pArr, recycler);
- }
- else if (isFloatArray)
- {
- CopyHeadIfInlinedHeadSegment<double>(pArr, recycler);
- ReallocateNonLeafLastSegmentIfLeaf<double>(pArr, recycler);
- }
- else
- {
- CopyHeadIfInlinedHeadSegment<Var>(pArr, recycler);
- }
- }
- SparseArraySegmentBase* seg = pArr->head;
- while (seg)
- {
- nextSeg = seg->next;
- // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
- // resulting in 2 segments sharing the same "left".
- if (seg->length > 0)
- {
- if (isIntArray)
- {
- ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
- }
- else if (isFloatArray)
- {
- ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
- }
- else
- {
- ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
- }
- seg->left = ((uint32)length) > (seg->left + seg->length) ? ((uint32)length) - (seg->left + seg->length) : 0;
- seg->next = prevSeg;
- // Make sure size doesn't overlap with next segment.
- // An easy fix is to just truncate the size...
- seg->EnsureSizeInBound();
- // If the last segment is a leaf, then we may be losing our last scanned pointer to its previous
- // segment. Hold onto it with pinPrevSeg until we reallocate below.
- pinPrevSeg = prevSeg;
- prevSeg = seg;
- }
- seg = nextSeg;
- }
- pArr->head = prevSeg;
- pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
- if (isIntArray)
- {
- pArr->EnsureHeadStartsFromZero<int32>(recycler);
- }
- else if (isFloatArray)
- {
- pArr->EnsureHeadStartsFromZero<double>(recycler);
- }
- else
- {
- pArr->EnsureHeadStartsFromZero<Var>(recycler);
- }
- #ifdef VALIDATE_ARRAY
- pArr->ValidateArray();
- #endif
- }
- else if (typedArrayBase)
- {
- Assert(length <= JavascriptArray::MaxArrayLength);
- if (typedArrayBase->GetLength() == length)
- {
- // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
- // and we won't have to check that the elements exist or not.
- for (uint32 lower = 0; lower < (uint32)middle; lower++)
- {
- uint32 upper = (uint32)length - lower - 1;
- lowerValue = typedArrayBase->DirectGetItem(lower);
- upperValue = typedArrayBase->DirectGetItem(upper);
- // We still have to call HasItem even though we know the TypedArray has both lower and upper because
- // there may be a proxy handler trapping HasProperty.
- lowerExists = typedArrayBase->HasItem(lower);
- upperExists = typedArrayBase->HasItem(upper);
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
- h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
- }
- }
- else
- {
- Assert(middle <= UINT_MAX);
- for (uint32 lower = 0; lower < (uint32)middle; lower++)
- {
- uint32 upper = (uint32)length - lower - 1;
- lowerValue = typedArrayBase->DirectGetItem(lower);
- upperValue = typedArrayBase->DirectGetItem(upper);
- lowerExists = typedArrayBase->HasItem(lower);
- upperExists = typedArrayBase->HasItem(upper);
- if (lowerExists)
- {
- if (upperExists)
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
- h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
- }
- else
- {
- // This will always fail for a TypedArray if lower < length
- h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
- }
- }
- else
- {
- if (upperExists)
- {
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)));
- // This will always fail for a TypedArray if upper < length
- h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
- }
- }
- }
- }
- }
- else
- {
- for (T lower = 0; lower < middle; lower++)
- {
- T upper = length - lower - 1;
- JS_REENTRANT(jsReentLock,
- lowerExists = JavascriptOperators::HasItem(obj, lower) && JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext),
- upperExists = JavascriptOperators::HasItem(obj, upper) && JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext));
- if (lowerExists)
- {
- if (upperExists)
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- else
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig)),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- }
- else
- {
- if (upperExists)
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig)));
- }
- }
- }
- }
- return obj;
- }
- template<typename T>
- void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
- {
- Recycler * recycler = scriptContext->GetRecycler();
- SparseArraySegment<T>* next = SparseArraySegment<T>::From(pArr->head->next);
- while (next)
- {
- next->left--;
- next = SparseArraySegment<T>::From(next->next);
- }
- // head and next might overlap as the next segment left is decremented
- next = SparseArraySegment<T>::From(pArr->head->next);
- if (next && (pArr->head->size > next->left))
- {
- AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
- AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
- SparseArraySegment<T> *head = SparseArraySegment<T>::From(pArr->head);
- // Merge the two adjacent segments
- if (next->length != 0)
- {
- uint32 offset = head->size - 1;
- // There is room for one unshifted element in head segment.
- // Hence it's enough if we grow the head segment by next->length - 1
- if (next->next)
- {
- // If we have a next->next, we can't grow pass the left of that
- // If the array had a segment map before, the next->next might just be right after next as well.
- // So we just need to grow to the end of the next segment
- // TODO: merge that segment too?
- Assert(next->next->left >= head->size);
- uint32 maxGrowSize = next->next->left - head->size;
- if (maxGrowSize != 0)
- {
- head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
- }
- else
- {
- // The next segment is only of length one, so we already have space in the header to copy that
- Assert(next->length == 1);
- }
- }
- else
- {
- head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
- }
- MoveArray(head->elements + offset, next->elements, next->length);
- head->length = offset + next->length;
- head->CheckLengthvsSize();
- pArr->head = head;
- }
- head->next = next->next;
- pArr->InvalidateLastUsedSegment();
- }
- #ifdef VALIDATE_ARRAY
- pArr->ValidateArray();
- #endif
- }
- Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- Var res = scriptContext->GetLibrary()->GetUndefined();
- if (args.Info.Count == 0)
- {
- return res;
- }
- if (JavascriptArray::Is(args[0]))
- {
- JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
- #endif
- if (pArr->length == 0)
- {
- return res;
- }
- if(pArr->IsFillFromPrototypes())
- {
- JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
- }
- if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
- {
- // This function currently does not track missing values in the head segment if there are multiple segments
- pArr->SetHasNoMissingValues(false);
- }
- pArr->length--;
- pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
- Recycler * recycler = scriptContext->GetRecycler();
- bool isIntArray = false;
- bool isFloatArray = false;
- if(JavascriptNativeIntArray::Is(pArr))
- {
- isIntArray = true;
- }
- else if(JavascriptNativeFloatArray::Is(pArr))
- {
- isFloatArray = true;
- }
- if (pArr->head->length != 0)
- {
- if(isIntArray)
- {
- int32 nativeResult = SparseArraySegment<int32>::From(pArr->head)->GetElement(0);
- if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
- {
- res = scriptContext->GetLibrary()->GetUndefined();
- }
- else
- {
- res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
- }
- SparseArraySegment<int32>::From(pArr->head)->RemoveElement(recycler, 0);
- }
- else if (isFloatArray)
- {
- double nativeResult = SparseArraySegment<double>::From(pArr->head)->GetElement(0);
- if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
- {
- res = scriptContext->GetLibrary()->GetUndefined();
- }
- else
- {
- res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
- }
- SparseArraySegment<double>::From(pArr->head)->RemoveElement(recycler, 0);
- }
- else
- {
- res = SparseArraySegment<Var>::From(pArr->head)->GetElement(0);
- if(SparseArraySegment<Var>::IsMissingItem(&res))
- {
- res = scriptContext->GetLibrary()->GetUndefined();
- }
- else
- {
- res = CrossSite::MarshalVar(scriptContext, res);
- }
- SparseArraySegment<Var>::From(pArr->head)->RemoveElement(recycler, 0);
- }
- }
- if(isIntArray)
- {
- ShiftHelper<int32>(pArr, scriptContext);
- }
- else if (isFloatArray)
- {
- ShiftHelper<double>(pArr, scriptContext);
- }
- else
- {
- ShiftHelper<Var>(pArr, scriptContext);
- }
- }
- else
- {
- RecyclableObject* dynamicObject = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
- }
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
- JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
- if (length == 0u)
- {
- // If length is 0, return 'undefined'
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- return scriptContext->GetLibrary()->GetUndefined();
- }
- JS_REENTRANT(jsReentLock,
- BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext));
- if (!gotItem)
- {
- res = scriptContext->GetLibrary()->GetUndefined();
- }
- --length;
- uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
- for (uint32 i = 0u; i < lengthToUin32Max; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
- if (hasItem)
- {
- Var element = nullptr;
- JS_REENTRANT(jsReentLock,
- element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true)));
- }
- else
- {
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
- }
- }
- for (uint64 i = MaxArrayLength; length > i; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
- if (hasItem)
- {
- Var element = nullptr;
- JS_REENTRANT(jsReentLock,
- element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- else
- {
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
- }
- }
- if (length.IsSmallIndex())
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- else
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- }
- return res;
- }
- Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
- {
- if (isIntArray)
- {
- Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
- pnewArr->EnsureHead<int32>();
- #if ENABLE_PROFILE_INFO
- pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeIntArray::FromVar(baseArray));
- #endif
- return pnewArr;
- }
- else if (isFloatArray)
- {
- Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
- pnewArr->EnsureHead<double>();
- #if ENABLE_PROFILE_INFO
- pnewArr->CopyArrayProfileInfo(Js::JavascriptNativeFloatArray::FromVar(baseArray));
- #endif
- return pnewArr;
- }
- else
- {
- JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
- pnewArr->EnsureHead<Var>();
- return pnewArr;
- }
- }
- template<typename T>
- void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
- {
- JS_REENTRANCY_LOCK(jsReentLock, pArr->GetScriptContext()->GetThreadContext());
- SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(pArr->head);
- SparseArraySegment<T>* pnewHeadSeg = SparseArraySegment<T>::From(pnewArr->head);
- // Fill the newly created sliced array
- CopyArray(pnewHeadSeg->elements, newLen, headSeg->elements + start, newLen);
- pnewHeadSeg->length = newLen;
- pnewHeadSeg->CheckLengthvsSize();
- Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
- // Prototype lookup for missing elements
- if (!pArr->HasNoMissingValues())
- {
- for (uint32 i = 0; i < newLen && (i + start) < pArr->length; i++)
- {
- // array type might be changed in the below call to DirectGetItemAtFull
- // need recheck array type before checking array item [i + start]
- if (pArr->IsMissingItem(i + start))
- {
- Var element;
- pnewArr->SetHasNoMissingValues(false);
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, pnewArr->SetItem(i, element, PropertyOperation_None));
- }
- }
- }
- }
- #ifdef DBG
- else
- {
- for (uint32 i = 0; i < newLen; i++)
- {
- AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
- }
- }
- #endif
- }
- // If the creating profile data has changed, convert it to the type of array indicated
- // in the profile
- void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
- {
- if (JavascriptNativeIntArray::Is(this))
- {
- #if ENABLE_PROFILE_INFO
- JavascriptNativeIntArray* nativeIntArray = JavascriptNativeIntArray::FromVar(this);
- ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
- if(!info || info->IsNativeIntArray())
- {
- *isIntArray = true;
- }
- else if(info->IsNativeFloatArray())
- {
- JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
- *isFloatArray = true;
- }
- else
- {
- JavascriptNativeIntArray::ToVarArray(nativeIntArray);
- }
- #else
- *isIntArray = true;
- #endif
- }
- else if (JavascriptNativeFloatArray::Is(this))
- {
- #if ENABLE_PROFILE_INFO
- JavascriptNativeFloatArray* nativeFloatArray = JavascriptNativeFloatArray::FromVar(this);
- ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
- if(info && !info->IsNativeArray())
- {
- JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
- }
- else
- {
- *isFloatArray = true;
- }
- #else
- *isFloatArray = true;
- #endif
- }
- }
- Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- Var res = scriptContext->GetLibrary()->GetUndefined();
- if (args.Info.Count == 0)
- {
- return res;
- }
- BigIndex length;
- JavascriptArray* pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.slice"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
- }
- Assert(pArr == nullptr || length.IsUint32Max());
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
- }
- // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
- template <typename T>
- Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- JavascriptArray* newArr = nullptr;
- RecyclableObject* newObj = nullptr;
- bool isIntArray = false;
- bool isFloatArray = false;
- bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
- bool isBuiltinArrayCtor = true;
- T startT = 0;
- T newLenT = length;
- T endT = length;
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
- #endif
- if (args.Info.Count > 1)
- {
- JS_REENTRANT(jsReentLock, startT = GetFromIndex(args[1], length, scriptContext));
- if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
- {
- JS_REENTRANT(jsReentLock, endT = GetFromIndex(args[2], length, scriptContext));
- }
- newLenT = endT > startT ? endT - startT : 0;
- }
- // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments start or end may convert the array to an ES5 array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- if (TypedArrayBase::IsDetachedTypedArray(obj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
- }
- // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
- if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- // 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
- // and use it to construct the return object.
- if (isTypedArrayEntryPoint)
- {
- JS_REENTRANT(jsReentLock,
- Var constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
- isBuiltinArrayCtor = false;
- AssertAndFailFast(pArr == nullptr);
- Assert(JavascriptOperators::IsConstructor(constructor));
- Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
- Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
- JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext)));
- }
- else if (pArr != nullptr)
- {
- JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor));
- }
- // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
- else
- {
- JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
- }
- // If we didn't create a new object above we will create a new array here.
- // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
- if (newObj == nullptr)
- {
- if (pArr)
- {
- pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
- }
- if (newLenT > JavascriptArray::MaxArrayLength)
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
- }
- newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
- #endif
- newObj = newArr;
- }
- else
- {
- // If the new object we created is an array, remember that as it will save us time setting properties in the object below
- if (JavascriptArray::Is(newObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
- #endif
- newArr = JavascriptArray::FromVar(newObj);
- }
- }
- uint32 start = (uint32) startT;
- uint32 newLen = (uint32) newLenT;
- // We at least have to have newObj as a valid object
- Assert(newObj);
- // Bail out early if the new object will have zero length.
- if (newLen == 0)
- {
- return newObj;
- }
- // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
- // we will process the array elements like an ES5Array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- if (pArr)
- {
- // If we constructed a new Array object, we have some nice helpers here
- if (newArr && isBuiltinArrayCtor)
- {
- if (JavascriptArray::IsDirectAccessArray(newArr))
- {
- if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
- {
- if (isIntArray)
- {
- JS_REENTRANT(jsReentLock, SliceHelper<int32>(pArr, newArr, start, newLen));
- }
- else if (isFloatArray)
- {
- JS_REENTRANT(jsReentLock, SliceHelper<double>(pArr, newArr, start, newLen));
- }
- else
- {
- JS_REENTRANT(jsReentLock, SliceHelper<Var>(pArr, newArr, start, newLen));
- }
- }
- else
- {
- if (isIntArray)
- {
- JS_REENTRANT(jsReentLock, CopyNativeIntArrayElements(JavascriptNativeIntArray::FromVar(newArr), 0, JavascriptNativeIntArray::FromVar(pArr), start, start + newLen));
- }
- else if (isFloatArray)
- {
- JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElements(JavascriptNativeFloatArray::FromVar(newArr), 0, JavascriptNativeFloatArray::FromVar(pArr), start, start + newLen));
- }
- else
- {
- JS_REENTRANT(jsReentLock, CopyArrayElements(newArr, 0u, pArr, start, start + newLen));
- }
- }
- }
- else
- {
- AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
- Var element;
- for (uint32 i = 0; i < newLen; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
- if (!gotItem)
- {
- continue;
- }
- newArr->SetItem(i, element, PropertyOperation_None);
- // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
- }
- }
- }
- }
- else
- {
- // The constructed object isn't an array, we'll need to use normal object manipulation
- Var element;
- for (uint32 i = 0; i < newLen; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
- if (!gotItem)
- {
- continue;
- }
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
- // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
- }
- }
- }
- }
- else if (typedArrayBase)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- // 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)
- TypedArrayBase* newTypedArray = nullptr;
- if (TypedArrayBase::Is(newObj))
- {
- newTypedArray = TypedArrayBase::FromVar(newObj);
- }
- else
- {
- AssertAndFailFast(newArr != nullptr);
- }
- Var element;
- for (uint32 i = 0; i < newLen; i++)
- {
- // We only need to call HasItem in the case that we are called from Array.prototype.slice
- if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
- {
- continue;
- }
- element = typedArrayBase->DirectGetItem(i + start);
- // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
- if (newTypedArray)
- {
- JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(i, element));
- }
- else
- {
- newArr->SetItem(i, element, PropertyOperation_None);
- }
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));;
- }
- if (!isTypedArrayEntryPoint)
- {
- JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible);
- }
- #ifdef VALIDATE_ARRAY
- if (JavascriptArray::Is(newObj))
- {
- JavascriptArray::FromVar(newObj)->ValidateArray();
- }
- #endif
- return newObj;
- }
- Var JavascriptArray::SliceObjectHelper(RecyclableObject* obj, uint32 sliceStart, uint32 start, JavascriptArray* newArr, RecyclableObject* newObj, uint32 newLen, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- for (uint32 i = start; i < newLen; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i + sliceStart));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(obj, i + sliceStart, scriptContext));
- if (newArr != nullptr)
- {
- newArr->SetItem(i, element, PropertyOperation_None);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
- }
- }
- }
- JS_REENTRANT(jsReentLock,
- JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
- #ifdef VALIDATE_ARRAY
- if (JavascriptArray::Is(newObj))
- {
- JavascriptArray::FromVar(newObj)->ValidateArray();
- }
- #endif
- return newObj;
- }
- struct CompareVarsInfo
- {
- ScriptContext* scriptContext;
- RecyclableObject* compFn;
- };
- int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
- {
- CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
- ScriptContext* requestContext=cvInfo->scriptContext;
- RecyclableObject* compFn=cvInfo->compFn;
- AssertMsg(*(Var*)aRef, "No null expected in sort");
- AssertMsg(*(Var*)bRef, "No null expected in sort");
- if (compFn != nullptr)
- {
- ScriptContext* scriptContext = compFn->GetScriptContext();
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var undefined = scriptContext->GetLibrary()->GetUndefined();
- Var retVal;
- if (requestContext != scriptContext)
- {
- Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
- Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
- retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
- }
- else
- {
- retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
- }
- if (TaggedInt::Is(retVal))
- {
- return TaggedInt::ToInt32(retVal);
- }
- double dblResult;
- if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
- {
- dblResult = JavascriptNumber::GetValue(retVal);
- }
- else
- {
- dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
- }
- if (dblResult < 0)
- {
- return -1;
- }
- return (dblResult > 0) ? 1 : 0;
- }
- else
- {
- JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
- JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
- return JavascriptString::strcmp(pStr1, pStr2);
- }
- }
- static void hybridSort(__inout_ecount(length) Field(Var) *elements, uint32 length, CompareVarsInfo* compareInfo)
- {
- // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
- // for arrays of more than 512 elements.
- if (length > 512)
- {
- qsort_s(elements, length, compareVars, compareInfo);
- return;
- }
- for (int i = 1; i < (int)length; i++)
- {
- if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
- // binary search for the left-most element greater than value:
- int first = 0;
- int last = i - 1;
- while (first <= last)
- {
- int middle = (first + last) / 2;
- if (compareVars(compareInfo, elements + i, elements + middle) < 0)
- {
- last = middle - 1;
- }
- else
- {
- first = middle + 1;
- }
- }
- // insert value right before first:
- Var value = elements[i];
- MoveArray(elements + first + 1, elements + first, (i - first));
- elements[first] = value;
- }
- }
- }
- void JavascriptArray::Sort(RecyclableObject* compFn)
- {
- JS_REENTRANCY_LOCK(jsReentLock, this->GetScriptContext()->GetThreadContext());
- if (length <= 1)
- {
- return;
- }
- this->EnsureHead<Var>();
- ScriptContext* scriptContext = this->GetScriptContext();
- Recycler* recycler = scriptContext->GetRecycler();
- CompareVarsInfo cvInfo;
- cvInfo.scriptContext = scriptContext;
- cvInfo.compFn = compFn;
- Assert(head != nullptr);
- // Just dump the segment map on sort
- ClearSegmentMap();
- uint32 countUndefined = 0;
- SparseArraySegment<Var>* startSeg = SparseArraySegment<Var>::From(head);
- // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
- uint32 saveLength = length;
- // that if compare function tries to modify the array it won't AV.
- head = const_cast<SparseArraySegmentBase*>(EmptySegment);
- SetFlags(DynamicObjectFlags::None);
- this->InvalidateLastUsedSegment();
- length = 0;
- TryFinally([&]()
- {
- //The array is a continuous array if there is only one segment
- if (startSeg->next == nullptr) // Single segment fast path
- {
- if (compFn != nullptr)
- {
- countUndefined = startSeg->RemoveUndefined(scriptContext);
- #ifdef VALIDATE_ARRAY
- ValidateSegment(startSeg);
- #endif
- JS_REENTRANT(jsReentLock, hybridSort(startSeg->elements, startSeg->length, &cvInfo));
- startSeg->CheckLengthvsSize();
- }
- else
- {
- JS_REENTRANT(jsReentLock, countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext));
- }
- head = startSeg;
- }
- else
- {
- SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
- SparseArraySegment<Var>* next = startSeg;
- uint32 nextIndex = 0;
- // copy all the elements to single segment
- while (next)
- {
- countUndefined += next->RemoveUndefined(scriptContext);
- if (next->length != 0)
- {
- allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
- }
- next = SparseArraySegment<Var>::From(next->next);
- nextIndex = allElements->length;
- #ifdef VALIDATE_ARRAY
- ValidateSegment(allElements);
- #endif
- }
- if (compFn != nullptr)
- {
- JS_REENTRANT(jsReentLock, hybridSort(allElements->elements, allElements->length, &cvInfo));
- }
- else
- {
- JS_REENTRANT(jsReentLock, sort(allElements->elements, &allElements->length, scriptContext));
- allElements->CheckLengthvsSize();
- }
- head = allElements;
- head->next = nullptr;
- }
- },
- [&](bool hasException)
- {
- length = saveLength;
- ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
- if (hasException)
- {
- head = startSeg;
- this->InvalidateLastUsedSegment();
- }
- });
- #if DEBUG
- {
- uint32 countNull = 0;
- uint32 index = head->length - 1;
- while (countNull < head->length)
- {
- if (SparseArraySegment<Var>::From(head)->elements[index] != NULL)
- {
- break;
- }
- index--;
- countNull++;
- }
- AssertMsg(countNull == 0, "No null expected at the end");
- }
- #endif
- if (countUndefined != 0)
- {
- // fill undefined at the end
- uint32 newLength = head->length + countUndefined;
- if (newLength > head->size)
- {
- head = SparseArraySegment<Var>::From(head)->GrowByMin(recycler, newLength - head->size);
- }
- Var undefined = scriptContext->GetLibrary()->GetUndefined();
- for (uint32 i = head->length; i < newLength; i++)
- {
- SparseArraySegment<Var>::From(head)->elements[i] = undefined;
- }
- head->length = newLength;
- head->CheckLengthvsSize();
- }
- SetHasNoMissingValues();
- this->InvalidateLastUsedSegment();
- #ifdef VALIDATE_ARRAY
- ValidateArray();
- #endif
- return;
- }
- uint32 JavascriptArray::sort(__inout_ecount(*len) Field(Var) *orig, uint32 *len, ScriptContext *scriptContext)
- {
- uint32 count = 0, countUndefined = 0;
- Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
- RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
- //
- // Create the Elements array
- //
- for (uint32 i = 0; i < *len; ++i)
- {
- if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
- {
- if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
- {
- elements[count].Value = orig[i];
- elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
- count++;
- }
- else
- {
- countUndefined++;
- }
- }
- }
- if (count > 0)
- {
- SortElements(elements, 0, count - 1);
- for (uint32 i = 0; i < count; ++i)
- {
- orig[i] = elements[i].Value;
- }
- }
- for (uint32 i = count + countUndefined; i < *len; ++i)
- {
- orig[i] = SparseArraySegment<Var>::GetMissingItem();
- }
- *len = count; // set the correct length
- return countUndefined;
- }
- int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
- {
- const Element* element1 = static_cast<const Element*>(elem1);
- const Element* element2 = static_cast<const Element*>(elem2);
- Assert(element1 != NULL);
- Assert(element2 != NULL);
- return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
- }
- void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
- {
- // Note: use write barrier policy of Field(Var)
- qsort_s<Element, Field(Var)>(elements, right - left + 1, CompareElements, this);
- }
- Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
- Assert(!(callInfo.Flags & CallFlags_New));
- AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
- RecyclableObject* compFn = NULL;
- if (args.Info.Count > 1)
- {
- if (JavascriptConversion::IsCallable(args[1]))
- {
- compFn = RecyclableObject::FromVar(args[1]);
- }
- else
- {
- TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
- // Use default comparer:
- // - In ES5 mode if the argument is undefined.
- bool useDefaultComparer = typeId == TypeIds_Undefined;
- if (!useDefaultComparer)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedInternalObject, _u("Array.prototype.sort"));
- }
- }
- }
- if (JavascriptArray::Is(args[0]))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
- #endif
- JavascriptArray *arr = JavascriptArray::FromVar(args[0]);
- if (arr->length <= 1)
- {
- return args[0];
- }
- if(arr->IsFillFromPrototypes())
- {
- JS_REENTRANT(jsReentLock, arr->FillFromPrototypes(0, arr->length)); // We need find all missing value from [[proto]] object
- }
- // Maintain nativity of the array only for the following cases (To favor inplace conversions - keeps the conversion cost less):
- // - int cases for X86 and
- // - FloatArray for AMD64
- // 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)
- #if defined(_M_X64_OR_ARM64)
- if(compFn && JavascriptNativeFloatArray::Is(arr))
- {
- arr = JavascriptNativeFloatArray::ConvertToVarArray((JavascriptNativeFloatArray*)arr);
- JS_REENTRANT(jsReentLock, arr->Sort(compFn));
- arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeFloatArray, double>(arr);
- }
- else
- {
- EnsureNonNativeArray(arr);
- JS_REENTRANT(jsReentLock, arr->Sort(compFn));
- }
- #else
- if(compFn && JavascriptNativeIntArray::Is(arr))
- {
- //EnsureNonNativeArray(arr);
- arr = JavascriptNativeIntArray::ConvertToVarArray((JavascriptNativeIntArray*)arr);
- JS_REENTRANT(jsReentLock, arr->Sort(compFn));
- arr = arr->ConvertToNativeArrayInPlace<JavascriptNativeIntArray, int32>(arr);
- }
- else
- {
- EnsureNonNativeArray(arr);
- JS_REENTRANT(jsReentLock, arr->Sort(compFn));
- }
- #endif
- }
- else
- {
- RecyclableObject* pObj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
- }
- JS_REENTRANT(jsReentLock,
- uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext));
- JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
- sortArray->EnsureHead<Var>();
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
- BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
- {
- JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
- for (uint32 i = 0; i < len; i++)
- {
- Var item;
- JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(pObj, i, &item, scriptContext));
- if (gotItem)
- {
- indexList->Add(i);
- sortArray->DirectSetItemAt(i, item);
- }
- }
- if (indexList->Count() > 0)
- {
- if (sortArray->length > 1)
- {
- sortArray->FillFromPrototypes(0, sortArray->length); // We need find all missing value from [[proto]] object
- }
- JS_REENTRANT(jsReentLock, sortArray->Sort(compFn));
- uint32 removeIndex = sortArray->head->length;
- for (uint32 i = 0; i < removeIndex; i++)
- {
- AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&SparseArraySegment<Var>::From(sortArray->head)->elements[i]), "No gaps expected in sorted array");
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, SparseArraySegment<Var>::From(sortArray->head)->elements[i], scriptContext)));
- }
- for (int i = 0; i < indexList->Count(); i++)
- {
- uint32 value = indexList->Item(i);
- if (value >= removeIndex)
- {
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value))));
- }
- }
- }
- }
- END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
- }
- return args[0];
- }
- Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
- JavascriptArray* pArr = 0;
- RecyclableObject* pObj = 0;
- uint64 start = 0u;
- uint64 deleteLen = 0u;
- uint64 length = 0u;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.splice"), &pArr, &pObj, &length));
- switch (args.Info.Count)
- {
- case 1:
- start = length;
- deleteLen = 0u;
- break;
- case 2:
- JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext));
- deleteLen = length - start;
- break;
- default:
- JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext),
- deleteLen = GetFromIndex(args[2], (length - start), scriptContext, false));
- break;
- }
- // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments start or deleteCount may convert the array to an ES5 array.
- if (pArr && !JavascriptArray::Is(pObj))
- {
- AssertOrFailFastMsg(ES5Array::Is(pObj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
- uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
- if (pArr != nullptr)
- {
- // Since we get the length from an array and that cannot be more than uint32.
- _Analysis_assume_(length <= UINT_MAX);
- JS_REENTRANT_UNLOCK(jsReentLock,
- return TryArraySplice(pArr, (uint32)start, (uint32)length, (uint32)deleteLen, insertArgs, insertLen, scriptContext));
- }
- uint64 newLen = (length - deleteLen) + insertLen;
- if (newLen > UINT_MAX || length > UINT_MAX || (length + insertLen) > UINT_MAX)
- {
- JS_REENTRANT_UNLOCK(jsReentLock,
- return ObjectSpliceHelper<uint64>(pObj, length, start, deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock,
- return ObjectSpliceHelper<uint32>(pObj, (uint32)length, (uint32)start, (uint32)deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
- }
- }
- inline BOOL JavascriptArray::IsSingleSegmentArray() const
- {
- return nullptr == head->next;
- }
- template<typename T>
- void JavascriptArray::ArraySegmentSpliceHelper(JavascriptArray *pnewArr, SparseArraySegment<T> *seg, SparseArraySegment<T> **prev,
- uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
- {
- // book keeping variables
- uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
- //(Missing elements at the beginning)
- uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
- // head if deleteLen overflows the length of head
- uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
- // Save the deleted elements
- if (headDeleteLen != 0)
- {
- pnewArr->InvalidateLastUsedSegment();
- pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, SparseArraySegment<T>::From(pnewArr->head), 0, seg, start, headDeleteLen);
- }
- if (newHeadLen != 0)
- {
- if (seg->size < newHeadLen)
- {
- if (seg->next)
- {
- // If we have "next", require that we haven't adjusted next segments left yet.
- seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
- }
- else
- {
- seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
- }
- #ifdef VALIDATE_ARRAY
- ValidateSegment(seg);
- #endif
- }
- // Move the elements if necessary
- if (headDeleteLen != insertLen)
- {
- uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
- MoveArray(seg->elements + relativeStart + insertLen,
- seg->elements + relativeStart + headDeleteLen,
- noElementsToMove);
- if (newHeadLen < seg->length) // truncate if necessary
- {
- seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
- }
- seg->length = newHeadLen;
- seg->CheckLengthvsSize();
- }
- // Copy the new elements
- if (insertLen > 0)
- {
- Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
- !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
- // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
- CopyArray(seg->elements + relativeStart, insertLen,
- reinterpret_cast<const T*>(insertArgs), insertLen);
- }
- *prev = seg;
- }
- else
- {
- *prev = SparseArraySegment<T>::From(seg->next);
- }
- }
- template<typename T>
- void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
- {
- // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
- Recycler *recycler = scriptContext->GetRecycler();
- Field(SparseArraySegmentBase*)* prevSeg = &pArr->head; // holds the next pointer of previous
- Field(SparseArraySegmentBase*)* prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
- SparseArraySegmentBase* savePrev = nullptr;
- Assert(pArr->head); // We should never have a null head.
- pArr->EnsureHead<T>();
- SparseArraySegment<T>* startSeg = SparseArraySegment<T>::From(pArr->head);
- const uint32 limit = start + deleteLen;
- uint32 rightLimit;
- if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
- {
- rightLimit = JavascriptArray::MaxArrayLength;
- }
- // Find out the segment to start delete
- while (startSeg && (rightLimit <= start))
- {
- savePrev = startSeg;
- prevPrevSeg = prevSeg;
- prevSeg = &startSeg->next;
- startSeg = SparseArraySegment<T>::From(startSeg->next);
- if (startSeg)
- {
- if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
- {
- rightLimit = JavascriptArray::MaxArrayLength;
- }
- }
- }
- // handle inlined segment
- SparseArraySegmentBase* inlineHeadSegment = nullptr;
- bool hasInlineSegment = false;
- // The following if else set is used to determine whether a shallow or hard copy is needed
- if (JavascriptNativeArray::Is(pArr))
- {
- if (JavascriptNativeFloatArray::Is(pArr))
- {
- inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
- }
- else if (JavascriptNativeIntArray::Is(pArr))
- {
- inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
- }
- Assert(inlineHeadSegment);
- hasInlineSegment = (startSeg == (SparseArraySegment<T>*)inlineHeadSegment);
- }
- else
- {
- // This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
- // does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
- // This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
- // so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
- // false positives. It is better than always doing a hard copy.
- hasInlineSegment = HasInlineHeadSegment(pArr->head->length);
- }
- if (startSeg)
- {
- // Delete Phase
- if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
- {
- // All splice happens in one segment.
- SparseArraySegmentBase *nextSeg = startSeg->next;
- // Splice the segment first, which might OOM throw but the array would be intact.
- JavascriptArray::ArraySegmentSpliceHelper(pnewArr, (SparseArraySegment<T>*)startSeg, (SparseArraySegment<T>**)prevSeg, start, deleteLen, insertArgs, insertLen, recycler);
- while (nextSeg)
- {
- // adjust next segments left
- nextSeg->left = nextSeg->left - deleteLen + insertLen;
- if (nextSeg->next == nullptr)
- {
- nextSeg->EnsureSizeInBound();
- }
- nextSeg = nextSeg->next;
- }
- if (*prevSeg)
- {
- (*prevSeg)->EnsureSizeInBound();
- }
- return;
- }
- else
- {
- SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
- Field(SparseArraySegmentBase*)* prevNewHeadSeg = &pnewArr->head;
- // delete till deleteLen and reuse segments for new array if it is possible.
- // 3 steps -
- //1. delete 1st segment (which may be partial delete)
- // 2. delete next n complete segments
- // 3. delete last segment (which again may be partial delete)
- // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
- if (startSeg->left < start)
- {
- if (start < startSeg->left + startSeg->length)
- {
- uint32 headDeleteLen = startSeg->left + startSeg->length - start;
- if (startSeg->next)
- {
- // We know the new segment will have a next segment, so allocate it as non-leaf.
- newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
- }
- else
- {
- newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
- }
- newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
- newHeadSeg->next = nullptr;
- *prevNewHeadSeg = newHeadSeg;
- prevNewHeadSeg = &newHeadSeg->next;
- startSeg->Truncate(start);
- }
- savePrev = startSeg;
- prevPrevSeg = prevSeg;
- prevSeg = &startSeg->next;
- startSeg = SparseArraySegment<T>::From(startSeg->next);
- }
- // Step (2) first we should do a hard copy if we have an inline head Segment
- else if (hasInlineSegment && nullptr != startSeg)
- {
- // start should be in between left and left + length
- if (startSeg->left <= start && start < startSeg->left + startSeg->length)
- {
- uint32 headDeleteLen = startSeg->left + startSeg->length - start;
- if (startSeg->next)
- {
- // We know the new segment will have a next segment, so allocate it as non-leaf.
- newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
- }
- else
- {
- newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
- }
- newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
- *prevNewHeadSeg = newHeadSeg;
- prevNewHeadSeg = &newHeadSeg->next;
- // Remove the entire segment from the original array
- *prevSeg = startSeg->next;
- startSeg = SparseArraySegment<T>::From(startSeg->next);
- }
- // if we have an inline head segment with 0 elements, remove it
- else if (startSeg->left == 0 && startSeg->length == 0)
- {
- Assert(startSeg->size != 0);
- *prevSeg = startSeg->next;
- startSeg = SparseArraySegment<T>::From(startSeg->next);
- }
- }
- // Step (2) proper
- SparseArraySegmentBase *temp = nullptr;
- while (startSeg && (startSeg->left + startSeg->length) <= limit)
- {
- temp = startSeg->next;
- // move that entire segment to new array
- startSeg->left = startSeg->left - start;
- startSeg->next = nullptr;
- *prevNewHeadSeg = startSeg;
- prevNewHeadSeg = &startSeg->next;
- // Remove the entire segment from the original array
- *prevSeg = temp;
- startSeg = (SparseArraySegment<T>*)temp;
- }
- // Step(2) above could delete the original head segment entirely, causing current head not
- // starting from 0. Then if any of the following throw, we have a corrupted array. Need
- // protection here.
- bool dummyHeadNodeInserted = false;
- if (!savePrev && (!startSeg || startSeg->left != 0))
- {
- Assert(pArr->head == startSeg);
- pArr->EnsureHeadStartsFromZero<T>(recycler);
- Assert(pArr->head && pArr->head->next == startSeg);
- savePrev = pArr->head;
- prevPrevSeg = prevSeg;
- prevSeg = &pArr->head->next;
- dummyHeadNodeInserted = true;
- }
- // Step (3)
- if (startSeg && (startSeg->left < limit))
- {
- // copy the first part of the last segment to be deleted to new array
- uint32 headDeleteLen = start + deleteLen - startSeg->left ;
- newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
- newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
- newHeadSeg->next = nullptr;
- *prevNewHeadSeg = newHeadSeg;
- prevNewHeadSeg = &newHeadSeg->next;
- // move the last segment
- MoveArray(startSeg->elements, startSeg->elements + headDeleteLen, startSeg->length - headDeleteLen);
- startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
- startSeg->length = startSeg->length - headDeleteLen;
- startSeg->CheckLengthvsSize();
- startSeg->Truncate(startSeg->left + startSeg->length);
- startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
- }
- if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
- {
- Assert(start + insertLen == 0);
- // Remove the dummy head node to preserve array consistency.
- pArr->head = startSeg;
- savePrev = nullptr;
- prevSeg = &pArr->head;
- }
- while (startSeg)
- {
- startSeg->left = startSeg->left - deleteLen + insertLen ;
- if (startSeg->next == nullptr)
- {
- startSeg->EnsureSizeInBound();
- }
- startSeg = SparseArraySegment<T>::From(startSeg->next);
- }
- }
- }
- // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
- pnewArr->head->EnsureSizeInBound();
- if (savePrev)
- {
- savePrev->EnsureSizeInBound();
- }
- // insert elements
- if (insertLen > 0)
- {
- Assert(!JavascriptNativeIntArray::Is(pArr) && !JavascriptNativeFloatArray::Is(pArr));
- // InsertPhase
- SparseArraySegment<T> *segInsert = nullptr;
- // see if we are just about the right of the previous segment
- Assert(!savePrev || savePrev->left <= start);
- if (savePrev && (start - savePrev->left < savePrev->size))
- {
- segInsert = (SparseArraySegment<T>*)savePrev;
- uint32 spaceLeft = segInsert->size - (start - segInsert->left);
- if(spaceLeft < insertLen)
- {
- if (!segInsert->next)
- {
- segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
- }
- else
- {
- segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
- }
- }
- *prevPrevSeg = segInsert;
- segInsert->length = start + insertLen - segInsert->left;
- segInsert->CheckLengthvsSize();
- }
- else
- {
- segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
- segInsert->next = *prevSeg;
- *prevSeg = segInsert;
- savePrev = segInsert;
- }
- uint32 relativeStart = start - segInsert->left;
- // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
- CopyArray(segInsert->elements + relativeStart, insertLen,
- reinterpret_cast<const T*>(insertArgs), insertLen);
- }
- }
- Var JavascriptArray::TryArraySplice(JavascriptArray* pArr, uint32 start, uint32 len, uint32 deleteLen,
- Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(pArr != nullptr);
- RecyclableObject* newObj = nullptr;
- Recycler *recycler = scriptContext->GetRecycler();
- ::Math::RecordOverflowPolicy newLenOverflow;
- uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
- // If we have missing values then convert to not native array for now
- // In future, we could support this scenario.
- if (deleteLen == insertLen)
- {
- JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, start + deleteLen));
- }
- else if (len)
- {
- JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, len));
- }
- //
- // If newLen overflowed, pre-process to prevent pushing sparse array segments or elements out of
- // max array length, which would result in tons of index overflow and difficult to fix.
- //
- if (newLenOverflow.HasOverflowed())
- {
- pArr = EnsureNonNativeArray(pArr);
- BigIndex dstIndex = MaxArrayLength;
- uint32 maxInsertLen = MaxArrayLength - start;
- if (insertLen > maxInsertLen)
- {
- // Copy overflowing insertArgs to properties
- for (uint32 i = maxInsertLen; i < insertLen; i++)
- {
- pArr->DirectSetItemAt(dstIndex, insertArgs[i]);
- ++dstIndex;
- }
- insertLen = maxInsertLen; // update
- // Truncate elements on the right to properties
- if (start + deleteLen < len)
- {
- pArr->TruncateToProperties(dstIndex, start + deleteLen);
- }
- }
- else
- {
- // Truncate would-overflow elements to properties
- pArr->TruncateToProperties(dstIndex, MaxArrayLength - insertLen + deleteLen);
- }
- len = pArr->length; // update
- newLen = len - deleteLen + insertLen;
- Assert(newLen == MaxArrayLength);
- }
- if (insertArgs)
- {
- pArr = EnsureNonNativeArray(pArr);
- }
- bool isIntArray = false;
- bool isFloatArray = false;
- bool isBuiltinArrayCtor = true;
- JavascriptArray *newArr = nullptr;
- // Just dump the segment map on splice (before any possible allocation and throw)
- pArr->ClearSegmentMap();
- // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
- // and use it to construct the return object.
- JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
- if (newObj != nullptr)
- {
- pArr = EnsureNonNativeArray(pArr);
- // If the new object we created is an array, remember that as it will save us time setting properties in the object below
- if (JavascriptArray::Is(newObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
- #endif
- newArr = JavascriptArray::FromVar(newObj);
- }
- }
- else
- // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
- {
- pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
- newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
- #endif
- }
- // If return object is a JavascriptArray, we can use all the array splice helpers
- if (newArr && isBuiltinArrayCtor && len == pArr->length)
- {
- // Array has a single segment (need not start at 0) and splice start lies in the range
- // of that segment we optimize splice - Fast path.
- if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
- {
- if (isIntArray)
- {
- ArraySegmentSpliceHelper<int32>(newArr, SparseArraySegment<int32>::From(pArr->head), (SparseArraySegment<int32>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
- }
- else if (isFloatArray)
- {
- ArraySegmentSpliceHelper<double>(newArr, SparseArraySegment<double>::From(pArr->head), (SparseArraySegment<double>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
- }
- else
- {
- ArraySegmentSpliceHelper<Var>(newArr, SparseArraySegment<Var>::From(pArr->head), (SparseArraySegment<Var>**)&pArr->head, start, deleteLen, insertArgs, insertLen, recycler);
- }
- // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
- // missing values. If the original array had missing values in the head segment, some of them may have been
- // copied into the array that will be returned; otherwise, the array that is returned will also not have any
- // missing values.
- newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
- }
- else
- {
- if (isIntArray)
- {
- ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
- }
- else if (isFloatArray)
- {
- ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
- }
- else
- {
- ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
- }
- // This function currently does not track missing values in the head segment if there are multiple segments
- pArr->SetHasNoMissingValues(false);
- newArr->SetHasNoMissingValues(false);
- }
- if (isIntArray)
- {
- pArr->EnsureHeadStartsFromZero<int32>(recycler);
- newArr->EnsureHeadStartsFromZero<int32>(recycler);
- }
- else if (isFloatArray)
- {
- pArr->EnsureHeadStartsFromZero<double>(recycler);
- newArr->EnsureHeadStartsFromZero<double>(recycler);
- }
- else
- {
- pArr->EnsureHeadStartsFromZero<Var>(recycler);
- newArr->EnsureHeadStartsFromZero<Var>(recycler);
- }
- pArr->InvalidateLastUsedSegment();
- // it is possible for valueOf accessors for the start or deleteLen
- // arguments to modify the size of the array. Since the resulting size of the array
- // is based on the cached value of length, this might lead to us having to trim
- // excess array segments at the end of the splice operation, which SetLength() will do.
- // However, this is also slower than performing the simple length assignment, so we only
- // do it if we can detect the array length changing.
- if (pArr->length != len)
- {
- pArr->SetLength(newLen);
- }
- else
- {
- pArr->length = newLen;
- }
- if (newArr->length != deleteLen)
- {
- newArr->SetLength(deleteLen);
- }
- else
- {
- newArr->length = deleteLen;
- }
- newArr->InvalidateLastUsedSegment();
- #ifdef VALIDATE_ARRAY
- newArr->ValidateArray();
- pArr->ValidateArray();
- #endif
- if (newLenOverflow.HasOverflowed())
- {
- // ES5 15.4.4.12 16: If new len overflowed, SetLength throws
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
- }
- return newArr;
- }
- if (newLenOverflow.HasOverflowed())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint64>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
- }
- else // Use uint32 version if no overflow
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint32>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
- }
- }
- template<typename T>
- RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, T len, T start,
- T deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- JavascriptArray *pnewArr = nullptr;
- if (pNewObj == nullptr)
- {
- JS_REENTRANT(jsReentLock, pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext));
- if (pNewObj == nullptr)
- {
- if (deleteLen > UINT_MAX)
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
- }
- pnewArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(deleteLen));
- pnewArr->EnsureHead<Var>();
- pNewObj = pnewArr;
- }
- }
- if (JavascriptArray::Is(pNewObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pNewObj);
- #endif
- pnewArr = JavascriptArray::FromVar(pNewObj);
- }
- // copy elements to delete to new array
- if (pnewArr != nullptr)
- {
- for (uint32 i = 0; i < deleteLen; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext));
- pnewArr->SetItem(i, element, PropertyOperation_None);
- }
- }
- }
- else
- {
- BigIndex k = 0u;
- for (T i = 0u; i < deleteLen; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
- if (hasItem)
- {
- Var element = nullptr;
- JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, start + i, scriptContext),
- ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, k, element), scriptContext, k));
- }
- ++k;
- }
- }
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
- // Now we need reserve room if it is necessary
- if (insertLen > deleteLen) // Might overflow max array length
- {
- // Unshift [start + deleteLen, len) to start + insertLen
- JS_REENTRANT(jsReentLock, Unshift<BigIndex, T>(pObj, start + insertLen, start + deleteLen, len, scriptContext));
- }
- else if (insertLen < deleteLen) // Won't overflow max array length
- {
- T j = 0;
- for (T i = start + deleteLen; i < len; i++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, i));
- if (hasItem)
- {
- Var element = nullptr;
- JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, i, scriptContext),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- }
- else
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig)));
- }
- j++;
- }
- // Clean up the rest
- for (T i = len; i > len - deleteLen + insertLen; i--)
- {
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig)));
- }
- }
- if (insertLen > 0)
- {
- T dstIndex = start; // insert index might overflow max array length
- for (uint32 i = 0; i < insertLen; i++)
- {
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(IndexTrace<BigIndex>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible)));
- ++dstIndex;
- }
- }
- // Set up new length
- T newLen = T(len - deleteLen) + insertLen;
- JS_REENTRANT(jsReentLock,
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)),
- h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
- #ifdef VALIDATE_ARRAY
- if (pnewArr)
- {
- pnewArr->ValidateArray();
- }
- #endif
- return pNewObj;
- }
- Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
- }
- if (JavascriptArray::IsDirectAccessArray(args[0]))
- {
- JavascriptArray* arr = JavascriptArray::FromVar(args[0]);
- JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(arr, scriptContext));
- }
- else
- {
- if (TypedArrayBase::IsDetachedTypedArray(args[0]))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
- }
- RecyclableObject* obj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
- }
- JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(obj, scriptContext));
- }
- }
- //
- // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
- //
- template<typename T, typename P>
- void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, P start, P end, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- typedef IndexTrace<T> index_trace;
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
- if (start < end)
- {
- T newEnd = (end - start - 1);// newEnd - 1
- T dst = toIndex + newEnd;
- for (P i = end; i > start; --i)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i - 1));
- if (hasItem)
- {
- Var element = nullptr;
- JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, i - 1, scriptContext),
- h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible)));
- }
- else
- {
- JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig)));
- }
- --dst;
- }
- }
- }
- template<typename T>
- void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
- {
- SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
- Recycler* recycler = scriptContext->GetRecycler();
- if (nextToHeadSeg == nullptr)
- {
- pArr->EnsureHead<T>();
- pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMin(recycler, unshiftElements);
- }
- else
- {
- pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
- }
- }
- template<typename T>
- void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
- {
- SparseArraySegment<T>* head = SparseArraySegment<T>::From(pArr->head);
- // Make enough room in the head segment to insert new elements at the front
- MoveArray(head->elements + unshiftElements, head->elements, pArr->head->length);
- uint32 oldHeadLength = head->length;
- head->length += unshiftElements;
- head->CheckLengthvsSize();
- /* Set head segment as the last used segment */
- pArr->InvalidateLastUsedSegment();
- bool hasNoMissingValues = pArr->HasNoMissingValues();
- /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
- if(unshiftElements > oldHeadLength)
- {
- pArr->SetHasNoMissingValues(false);
- }
- #if ENABLE_PROFILE_INFO
- pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
- #else
- pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
- #endif
- // Setting back to the old value
- pArr->SetHasNoMissingValues(hasNoMissingValues);
- }
- Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- Var res = scriptContext->GetLibrary()->GetUndefined();
- if (args.Info.Count == 0)
- {
- return res;
- }
- if (JavascriptArray::Is(args[0]) && !JavascriptArray::FromVar(args[0])->IsCrossSiteObject())
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
- #endif
- JavascriptArray * pArr = JavascriptArray::FromVar(args[0]);
- uint32 unshiftElements = args.Info.Count - 1;
- if (unshiftElements > 0)
- {
- if (pArr->IsFillFromPrototypes())
- {
- JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(0, pArr->length)); // We need find all missing value from [[proto]] object
- }
- // Pre-process: truncate overflowing elements to properties
- bool newLenOverflowed = false;
- uint32 maxLen = MaxArrayLength - unshiftElements;
- if (pArr->length > maxLen)
- {
- newLenOverflowed = true;
- // Ensure the array is non-native when overflow happens
- EnsureNonNativeArray(pArr);
- pArr->TruncateToProperties(MaxArrayLength, maxLen);
- Assert(pArr->length + unshiftElements == MaxArrayLength);
- }
- pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
- Assert(pArr->length <= MaxArrayLength - unshiftElements);
- bool isIntArray = false;
- bool isFloatArray = false;
- if (JavascriptNativeIntArray::Is(pArr))
- {
- isIntArray = true;
- }
- else if (JavascriptNativeFloatArray::Is(pArr))
- {
- isFloatArray = true;
- }
- // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
- // If there is OOM in array allocation, then array consistency is maintained.
- if (pArr->head->size < pArr->head->length + unshiftElements)
- {
- if (isIntArray)
- {
- GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
- }
- else if (isFloatArray)
- {
- GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
- }
- else
- {
- GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
- }
- }
- if (isIntArray)
- {
- UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
- }
- else if (isFloatArray)
- {
- UnshiftHelper<double>(pArr, unshiftElements, args.Values);
- }
- else
- {
- UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
- }
- SparseArraySegmentBase* renumberSeg = pArr->head->next;
- while (renumberSeg)
- {
- renumberSeg->left += unshiftElements;
- if (renumberSeg->next == nullptr)
- {
- // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
- renumberSeg->EnsureSizeInBound();
- }
- renumberSeg = renumberSeg->next;
- }
- pArr->InvalidateLastUsedSegment();
- pArr->length += unshiftElements;
- #ifdef VALIDATE_ARRAY
- pArr->ValidateArray();
- #endif
- if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
- }
- }
- res = JavascriptNumber::ToVar(pArr->length, scriptContext);
- }
- else
- {
- RecyclableObject* dynamicObject = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
- }
- JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
- uint32 unshiftElements = args.Info.Count - 1;
- if (unshiftElements > 0)
- {
- uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
- // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
- // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
- BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
- if (end < length)
- {
- // Unshift [end, length) to MaxArrayLength
- // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
- if (length.IsSmallIndex())
- {
- JS_REENTRANT(jsReentLock, Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext));
- }
- else
- {
- JS_REENTRANT(jsReentLock, Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, (uint64)end.GetSmallIndex(), length.GetBigIndex(), scriptContext));
- }
- }
- // Unshift [0, end) to unshiftElements
- // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
- JS_REENTRANT(jsReentLock, Unshift<uint32>(dynamicObject, unshiftElements, (uint32)0, end.GetSmallIndex(), scriptContext));
- for (uint32 i = 0; i < unshiftElements; i++)
- {
- JS_REENTRANT(jsReentLock,
- JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true));
- }
- }
- ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
- //ES6 - update 'length' even if unshiftElements == 0;
- BigIndex newLen = length + unshiftElements;
- res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
- JS_REENTRANT(jsReentLock,
- BOOL setLength = JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
- h.ThrowTypeErrorOnFailure(setLength);
- }
- return res;
- }
- Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
- }
- // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
- RecyclableObject* obj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
- }
- // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
- JS_REENTRANT(jsReentLock, Var join = JavascriptOperators::GetProperty(obj, PropertyIds::join, scriptContext));
- if (JavascriptConversion::IsCallable(join))
- {
- RecyclableObject* func = RecyclableObject::FromVar(join);
- // We need to record implicit call here, because marked the Array.toString as no side effect,
- // but if we call user code here which may have side effect
- ThreadContext * threadContext = scriptContext->GetThreadContext();
- JS_REENTRANT(jsReentLock,
- Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
- {
- // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
- Assert(!ThreadContext::IsOnStack(obj));
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- return CALL_FUNCTION(threadContext, func, CallInfo(flags, 1), obj);
- }));
- if(!result)
- {
- // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
- Assert(threadContext->IsDisableImplicitCall());
- result = scriptContext->GetLibrary()->GetNull();
- }
- return result;
- }
- else
- {
- // call built-in Object.prototype.toString
- JS_REENTRANT_UNLOCK(jsReentLock,
- return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj));
- }
- }
- #if DEBUG
- BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
- {
- uint32 lu, luDig;
- int32 cch = (int32)wcslen(propName);
- char16* pch = const_cast<char16 *>(propName);
- lu = *pch - '0';
- if (lu > 9)
- return FALSE;
- if (0 == lu)
- {
- *pIndex = 0;
- return 1 == cch;
- }
- while ((luDig = *++pch - '0') < 10)
- {
- // If we overflow 32 bits, ignore the item
- if (lu > 0x19999999)
- return FALSE;
- lu *= 10;
- if(lu > (ULONG_MAX - luDig))
- return FALSE;
- lu += luDig;
- }
- if (pch - propName != cch)
- return FALSE;
- if (lu == JavascriptArray::InvalidIndex)
- {
- // 0xFFFFFFFF is not treated as an array index so that the length can be
- // capped at 32 bits.
- return FALSE;
- }
- *pIndex = lu;
- return TRUE;
- }
- #endif
- JavascriptString* JavascriptArray::GetLocaleSeparator(ScriptContext* scriptContext)
- {
- #ifdef ENABLE_GLOBALIZATION
- LCID lcid = GetUserDefaultLCID();
- int count = 0;
- char16 szSeparator[6];
- // According to the document for GetLocaleInfo this is a sufficient buffer size.
- count = GetLocaleInfoW(lcid, LOCALE_SLIST, szSeparator, 5);
- if( !count)
- {
- AssertMsg(FALSE, "GetLocaleInfo failed");
- return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
- }
- else
- {
- // Append ' ' if necessary
- if( count < 2 || szSeparator[count-2] != ' ')
- {
- szSeparator[count-1] = ' ';
- szSeparator[count] = '\0';
- }
- return JavascriptString::NewCopyBuffer(szSeparator, count, scriptContext);
- }
- #else
- // xplat-todo: Support locale-specific seperator
- return scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
- #endif
- }
- template <typename T>
- JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- uint32 length = 0;
- if (TypedArrayBase::Is(arr))
- {
- // For a TypedArray use the actual length of the array.
- length = TypedArrayBase::FromVar(arr)->GetLength();
- }
- else
- {
- //For anything else, use the "length" property if present.
- JS_REENTRANT(jsReentLock, length = ItemTrace<T>::GetLength(arr, scriptContext));
- }
- if (length == 0 || scriptContext->CheckObject(arr))
- {
- return scriptContext->GetLibrary()->GetEmptyString();
- }
- JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
- bool pushedObject = false;
- TryFinally([&]()
- {
- scriptContext->PushObject(arr);
- pushedObject = true;
- Var element;
- JS_REENTRANT(jsReentLock, BOOL gotItem = ItemTrace<T>::GetItem(arr, 0, &element, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, res = JavascriptArray::ToLocaleStringHelper(element, scriptContext));
- }
- if (length > 1)
- {
- JavascriptString* separator = GetLocaleSeparator(scriptContext);
- for (uint32 i = 1; i < length; i++)
- {
- res = JavascriptString::Concat(res, separator);
- JS_REENTRANT(jsReentLock, gotItem = ItemTrace<T>::GetItem(arr, i, &element, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext)));
- }
- }
- }
- },
- [&](bool/*hasException*/)
- {
- if (pushedObject)
- {
- Var top = scriptContext->PopObject();
- AssertMsg(top == arr, "Unmatched operation stack");
- }
- });
- if (res == nullptr)
- {
- res = scriptContext->GetLibrary()->GetEmptyString();
- }
- return res;
- }
- Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
- if (args.Info.Count < 2)
- {
- return scriptContext->GetLibrary()->GetFalse();
- }
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
- #endif
- if (JavascriptOperators::IsArray(args[1]))
- {
- return scriptContext->GetLibrary()->GetTrue();
- }
- return scriptContext->GetLibrary()->GetFalse();
- }
- ///----------------------------------------------------------------------------
- /// Find() calls the given predicate callback on each element of the array, in
- /// order, and returns the first element that makes the predicate return true,
- /// as described in (ES6.0: S22.1.3.8).
- ///----------------------------------------------------------------------------
- Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
- }
- int64 length;
- JavascriptArray * pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.find"), &pArr, &obj, &length));
- return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
- }
- template <bool findIndex>
- Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
- if (typedArrayBase != nullptr)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
- }
- else
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
- }
- }
- RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
- Var thisArg;
- if (args.Info.Count > 2)
- {
- thisArg = args[2];
- }
- else
- {
- thisArg = scriptContext->GetLibrary()->GetUndefined();
- }
- // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
- if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var element = nullptr;
- Var testResult = nullptr;
- if (pArr)
- {
- Var undefined = scriptContext->GetLibrary()->GetUndefined();
- Assert(length <= UINT_MAX);
- for (uint32 k = 0; k < (uint32)length; k++)
- {
- element = undefined;
- JS_REENTRANT(jsReentLock, pArr->DirectGetItemAtFull(k, &element));
- Var index = JavascriptNumber::ToVar(k, scriptContext);
- JS_REENTRANT(jsReentLock,
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- index,
- pArr));
- if (JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return findIndex ? index : element;
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
- }
- }
- }
- else if (typedArrayBase)
- {
- Assert(length <= UINT_MAX);
- for (uint32 k = 0; k < (uint32)length; k++)
- {
- // Spec does not ask to call HasItem, so we need to go to visit the whole length
- element = typedArrayBase->DirectGetItem(k);
- Var index = JavascriptNumber::ToVar(k, scriptContext);
- JS_REENTRANT(jsReentLock,
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- index,
- typedArrayBase));
- if (JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return findIndex ? index : element;
- }
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, 0u, callBackFn, thisArg, scriptContext));
- }
- return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
- }
- template <bool findIndex>
- Var JavascriptArray::FindObjectHelper(RecyclableObject* obj, int64 length, int64 start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var element = nullptr;
- Var testResult = nullptr;
- for (int64 k = start; k < length; k++)
- {
- JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, (uint64)k, scriptContext));
- Var index = JavascriptNumber::ToVar(k, scriptContext);
- JS_REENTRANT(jsReentLock,
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- index,
- obj));
- if (JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return findIndex ? index : element;
- }
- }
- return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
- }
- ///----------------------------------------------------------------------------
- /// FindIndex() calls the given predicate callback on each element of the
- /// array, in order, and returns the index of the first element that makes the
- /// predicate return true, as described in (ES6.0: S22.1.3.9).
- ///----------------------------------------------------------------------------
- Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
- }
- int64 length;
- JavascriptArray * pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT_UNLOCK(jsReentLock,
- TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.findIndex"), &pArr, &obj, &length));
- return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
- }
- ///----------------------------------------------------------------------------
- /// Entries() returns a new ArrayIterator object configured to return key-
- /// value pairs matching the elements of the this array/array-like object,
- /// as described in (ES6.0: S22.1.3.4).
- ///----------------------------------------------------------------------------
- Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
- }
- RecyclableObject* thisObj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
- }
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
- #endif
- JS_REENTRANT_UNLOCK(jsReentLock,
- return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue));
- }
- ///----------------------------------------------------------------------------
- /// Keys() returns a new ArrayIterator object configured to return the keys
- /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
- ///----------------------------------------------------------------------------
- Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
- }
- RecyclableObject* thisObj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
- }
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
- #endif
- JS_REENTRANT_UNLOCK(jsReentLock,
- return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key));
- }
- ///----------------------------------------------------------------------------
- /// Values() returns a new ArrayIterator object configured to return the values
- /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
- ///----------------------------------------------------------------------------
- Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
- }
- RecyclableObject* thisObj = nullptr;
- if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
- }
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
- #endif
- JS_REENTRANT_UNLOCK(jsReentLock,
- return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value));
- }
- Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
- Assert(!(callInfo.Flags & CallFlags_New));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
- }
- BigIndex length;
- JavascriptArray* pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.every"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
- }
- 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
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
- }
- // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
- template <typename T>
- Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
- if (typedArrayBase != nullptr)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
- }
- else
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
- }
- }
- RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
- Var thisArg = nullptr;
- if (args.Info.Count > 2)
- {
- thisArg = args[2];
- }
- else
- {
- thisArg = scriptContext->GetLibrary()->GetUndefined();
- }
- // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
- if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- Var element = nullptr;
- Var testResult = nullptr;
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- if (pArr)
- {
- Assert(length <= UINT_MAX);
- for (uint32 k = 0; k < (uint32)length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
- if (!gotItem)
- {
- continue;
- }
- JS_REENTRANT(jsReentLock,
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- pArr));
- if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return scriptContext->GetLibrary()->GetFalse();
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
- }
- }
- }
- else if (typedArrayBase)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
- for (uint32 k = 0; k < end; k++)
- {
- // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
- element = typedArrayBase->DirectGetItem(k);
- JS_REENTRANT(jsReentLock,
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- typedArrayBase));
- if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return scriptContext->GetLibrary()->GetFalse();
- }
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
- }
- return scriptContext->GetLibrary()->GetTrue();
- }
- template <typename T>
- Var JavascriptArray::EveryObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var element = nullptr;
- Var testResult = nullptr;
- for (T k = start; k < length; k++)
- {
- // According to es6 spec, we need to call Has first before calling Get
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock,
- element = JavascriptOperators::GetItem(obj, k, scriptContext),
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- obj));
- if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return scriptContext->GetLibrary()->GetFalse();
- }
- }
- }
- return scriptContext->GetLibrary()->GetTrue();
- }
- Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
- }
- BigIndex length;
- JavascriptArray* pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.some"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
- }
- 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
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
- }
- // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
- template <typename T>
- Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
- if (typedArrayBase != nullptr)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
- }
- else
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
- }
- }
- RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
- Var thisArg = nullptr;
- if (args.Info.Count > 2)
- {
- thisArg = args[2];
- }
- else
- {
- thisArg = scriptContext->GetLibrary()->GetUndefined();
- }
- // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
- if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var element = nullptr;
- Var testResult = nullptr;
- if (pArr)
- {
- Assert(length <= UINT_MAX);
- for (uint32 k = 0; k < (uint32)length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
- if (!gotItem)
- {
- continue;
- }
- JS_REENTRANT_UNLOCK(jsReentLock,
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- pArr));
- if (JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return scriptContext->GetLibrary()->GetTrue();
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
- }
- }
- }
- else if (typedArrayBase)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
- for (uint32 k = 0; k < end; k++)
- {
- // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
- element = typedArrayBase->DirectGetItem(k);
- JS_REENTRANT_UNLOCK(jsReentLock,
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- typedArrayBase));
- if (JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return scriptContext->GetLibrary()->GetTrue();
- }
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
- }
- return scriptContext->GetLibrary()->GetFalse();
- }
- template <typename T>
- Var JavascriptArray::SomeObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var element = nullptr;
- Var testResult = nullptr;
- for (T k = start; k < length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
- if (hasItem)
- {
- JS_REENTRANT_UNLOCK(jsReentLock,
- element = JavascriptOperators::GetItem(obj, k, scriptContext),
- testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- obj));
- if (JavascriptConversion::ToBoolean(testResult, scriptContext))
- {
- return scriptContext->GetLibrary()->GetTrue();
- }
- }
- }
- return scriptContext->GetLibrary()->GetFalse();
- }
- Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
- }
- BigIndex length;
- JavascriptArray* pArr = nullptr;
- RecyclableObject* dynamicObject = nullptr;
- RecyclableObject* callBackFn = nullptr;
- Var thisArg = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.forEach"), &pArr, &dynamicObject, &length));
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
- }
- callBackFn = RecyclableObject::FromVar(args[1]);
- if (args.Info.Count > 2)
- {
- thisArg = args[2];
- }
- else
- {
- thisArg = scriptContext->GetLibrary()->GetUndefined();
- }
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- auto fn32 = [dynamicObject, callBackFn, flags, thisArg,
- scriptContext](uint32 k, Var element)
- {
- CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- dynamicObject);
- };
- auto fn64 = [dynamicObject, callBackFn, flags, thisArg,
- scriptContext](uint64 k, Var element)
- {
- CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- dynamicObject);
- };
- if (pArr)
- {
- Assert(pArr == dynamicObject);
- JS_REENTRANT(jsReentLock, pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32));
- }
- else
- {
- if (length.IsSmallIndex())
- {
- JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32));
- }
- else
- {
- JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64));
- }
- }
- return scriptContext->GetLibrary()->GetUndefined();
- }
- Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- RecyclableObject* obj = nullptr;
- JavascriptArray* pArr = nullptr;
- int64 length;
- JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.copyWithin"), &pArr, &obj, &length));
- return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
- }
- // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
- Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(args.Info.Count > 0);
- JavascriptLibrary* library = scriptContext->GetLibrary();
- int64 fromVal = 0;
- int64 toVal = 0;
- int64 finalVal = length;
- // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
- if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- if (args.Info.Count > 1)
- {
- JS_REENTRANT(jsReentLock, toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext));
- if (args.Info.Count > 2)
- {
- JS_REENTRANT(jsReentLock, fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
- if (args.Info.Count > 3 && args[3] != library->GetUndefined())
- {
- JS_REENTRANT(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
- }
- }
- }
- // If count would be negative or zero, we won't do anything so go ahead and return early.
- if (finalVal <= fromVal || length <= toVal)
- {
- return obj;
- }
- // Make sure we won't underflow during the count calculation
- Assert(finalVal > fromVal && length > toVal);
- int64 count = min(finalVal - fromVal, length - toVal);
- // We shouldn't have made it here if the count was going to be zero
- Assert(count > 0);
- int direction;
- if (fromVal < toVal && toVal < (fromVal + count))
- {
- direction = -1;
- fromVal += count - 1;
- toVal += count - 1;
- }
- else
- {
- direction = 1;
- }
- // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments may convert the array to an ES5 array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
- // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
- if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
- || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
- {
- while (count > 0)
- {
- Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::OP_HasItem(obj, index, scriptContext));
- if (hasItem)
- {
- Var val = nullptr;
- JS_REENTRANT(jsReentLock,
- val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext),
- JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
- }
- else
- {
- JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig);
- }
- fromVal += direction;
- toVal += direction;
- count--;
- }
- }
- else
- {
- Assert(fromVal < MaxArrayLength);
- Assert(toVal < MaxArrayLength);
- Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
- uint32 fromIndex = static_cast<uint32>(fromVal);
- uint32 toIndex = static_cast<uint32>(toVal);
- while (count > 0)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = obj->HasItem(fromIndex));
- if (hasItem)
- {
- if (typedArrayBase)
- {
- Var val = typedArrayBase->DirectGetItem(fromIndex);
- JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(toIndex, val));
- }
- else if (pArr)
- {
- JS_REENTRANT(jsReentLock, Var val = pArr->DirectGetItem(fromIndex));
- pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible);
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- }
- else
- {
- Var val = nullptr;
- JS_REENTRANT(jsReentLock,
- val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext),
- JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
- }
- }
- else
- {
- obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig);
- }
- fromIndex += direction;
- toIndex += direction;
- count--;
- }
- }
- return obj;
- }
- Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- RecyclableObject* obj = nullptr;
- JavascriptArray* pArr = nullptr;
- int64 length;
- JS_REENTRANT_UNLOCK(jsReentLock,
- TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.fill"), &pArr, &obj, &length));
- return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
- }
- // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
- Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(args.Info.Count > 0);
- JavascriptLibrary* library = scriptContext->GetLibrary();
- // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
- if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- Var fillValue;
- if (args.Info.Count > 1)
- {
- fillValue = args[1];
- }
- else
- {
- fillValue = library->GetUndefined();
- }
- int64 k = 0;
- int64 finalVal = length;
- if (args.Info.Count > 2)
- {
- JS_REENTRANT_UNLOCK(jsReentLock, k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
- if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
- {
- JS_REENTRANT_UNLOCK(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the array elements like an ES5Array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- }
- if (k < MaxArrayLength)
- {
- int64 end = min<int64>(finalVal, MaxArrayLength);
- uint32 u32k = static_cast<uint32>(k);
- while (u32k < end)
- {
- if (typedArrayBase)
- {
- JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(u32k, fillValue));
- }
- else if (pArr)
- {
- pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
- }
- else
- {
- JS_REENTRANT(jsReentLock,
- JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
- }
- u32k++;
- }
- BigIndex dstIndex = MaxArrayLength;
- for (int64 i = end; i < finalVal; ++i)
- {
- if (pArr)
- {
- pArr->DirectSetItemAt(dstIndex, fillValue);
- ++dstIndex;
- }
- else
- {
- JS_REENTRANT(jsReentLock,
- JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
- }
- }
- }
- else
- {
- BigIndex dstIndex = static_cast<uint64>(k);
- for (int64 i = k; i < finalVal; i++)
- {
- if (pArr)
- {
- pArr->DirectSetItemAt(dstIndex, fillValue);
- ++dstIndex;
- }
- else
- {
- JS_REENTRANT(jsReentLock,
- JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
- }
- }
- }
- return obj;
- }
- // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
- Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
- }
- BigIndex length;
- JavascriptArray* pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.map"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
- }
- 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
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
- }
- template<typename T>
- Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- RecyclableObject* newObj = nullptr;
- JavascriptArray* newArr = nullptr;
- bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
- bool isBuiltinArrayCtor = true;
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- if (isTypedArrayEntryPoint)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
- }
- else
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
- }
- }
- RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
- Var thisArg;
- if (args.Info.Count > 2)
- {
- thisArg = args[2];
- }
- else
- {
- thisArg = scriptContext->GetLibrary()->GetUndefined();
- }
- // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
- if (!isTypedArrayEntryPoint && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- // 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
- // and use it to construct the return object.
- if (isTypedArrayEntryPoint)
- {
- JS_REENTRANT(jsReentLock,
- Var constructor = JavascriptOperators::SpeciesConstructor(
- typedArrayBase, TypedArrayBase::GetDefaultConstructor(args[0], scriptContext), scriptContext));
- isBuiltinArrayCtor = false;
- Assert(JavascriptOperators::IsConstructor(constructor));
- Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
- Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
- JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext)));
- }
- // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
- else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
- {
- JS_REENTRANT(jsReentLock, newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
- }
- if (newObj == nullptr)
- {
- if (length > UINT_MAX)
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
- }
- newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
- newArr->EnsureHead<Var>();
- newObj = newArr;
- }
- else
- {
- // If the new object we created is an array, remember that as it will save us time setting properties in the object below
- if (JavascriptArray::Is(newObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
- #endif
- newArr = JavascriptArray::FromVar(newObj);
- }
- }
- Var element = nullptr;
- Var mappedValue = nullptr;
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags callBackFnflags = CallFlags_Value;
- CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
- // We at least have to have newObj as a valid object
- Assert(newObj);
- // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
- // we will process the array elements like an ES5Array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- if (pArr != nullptr)
- {
- // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
- Assert(length <= UINT_MAX);
- for (uint32 k = 0; k < (uint32)length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
- if (!gotItem)
- {
- continue;
- }
- JS_REENTRANT(jsReentLock,
- mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- pArr));
- // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
- if (newArr && isBuiltinArrayCtor)
- {
- newArr->DirectSetItemAt(k, mappedValue);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, mappedValue), scriptContext, k));
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, k + 1, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
- }
- }
- }
- else if (typedArrayBase != nullptr)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
- TypedArrayBase* newTypedArray = nullptr;
- if (TypedArrayBase::Is(newObj))
- {
- newTypedArray = TypedArrayBase::FromVar(newObj);
- }
- else
- {
- AssertAndFailFast(newArr != nullptr);
- }
- Assert(length <= UINT_MAX);
- uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
- for (uint32 k = 0; k < end; k++)
- {
- // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
- element = typedArrayBase->DirectGetItem(k);
- JS_REENTRANT(jsReentLock,
- mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- obj));
- // If newObj is a TypedArray, set the mappedValue directly, otherwise it should be an array, set that item to that array
- if (newTypedArray)
- {
- JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, mappedValue));
- }
- else
- {
- newArr->SetItem(k, mappedValue, PropertyOperation_None);
- }
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, 0u, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
- }
- #ifdef VALIDATE_ARRAY
- if (JavascriptArray::Is(newObj))
- {
- newArr->ValidateArray();
- }
- #endif
- return newObj;
- }
- template<typename T>
- Var JavascriptArray::MapObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* newObj, JavascriptArray* newArr,
- bool isBuiltinArrayCtor, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags callBackFnflags = CallFlags_Value;
- CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
- Var element = nullptr;
- Var mappedValue = nullptr;
- for (T k = start; k < length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock,
- element = JavascriptOperators::GetItem(obj, k, scriptContext),
- mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- obj));
- if (newArr && isBuiltinArrayCtor)
- {
- newArr->SetItem((uint32)k, mappedValue, PropertyOperation_None);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, BigIndex(k), mappedValue), scriptContext, BigIndex(k)));
- }
- }
- }
- #ifdef VALIDATE_ARRAY
- if (JavascriptArray::Is(newObj))
- {
- newArr->ValidateArray();
- }
- #endif
- return newObj;
- }
- Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
- }
- BigIndex length;
- JavascriptArray* pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.filter"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetSmallIndex(), args, scriptContext));
- }
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetBigIndex(), args, scriptContext));
- }
- template <typename T>
- Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
- }
- RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
- Var thisArg = nullptr;
- if (args.Info.Count > 2)
- {
- thisArg = args[2];
- }
- else
- {
- thisArg = scriptContext->GetLibrary()->GetUndefined();
- }
- // 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.
- bool isBuiltinArrayCtor = true;
- JS_REENTRANT(jsReentLock, RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
- JavascriptArray* newArr = nullptr;
- if (newObj == nullptr)
- {
- newArr = scriptContext->GetLibrary()->CreateArray(0);
- newArr->EnsureHead<Var>();
- newObj = newArr;
- }
- else
- {
- // If the new object we created is an array, remember that as it will save us time setting properties in the object below
- if (JavascriptArray::Is(newObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
- #endif
- newArr = JavascriptArray::FromVar(newObj);
- }
- }
- // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
- // we will process the array elements like an ES5Array.
- if (pArr && !JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- Var element = nullptr;
- Var selected = nullptr;
- if (pArr)
- {
- Assert(length <= MaxArrayLength);
- uint32 i = 0;
- Assert(length <= UINT_MAX);
- for (uint32 k = 0; k < (uint32)length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
- if (!gotItem)
- {
- continue;
- }
- JS_REENTRANT(jsReentLock,
- selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
- callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
- thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- pArr));
- if (JavascriptConversion::ToBoolean(selected, scriptContext))
- {
- // Try to fast path if the return object is an array
- if (newArr && isBuiltinArrayCtor)
- {
- newArr->DirectSetItemAt(i, element);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
- }
- ++i;
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, k + 1, newArr, newObj, i, callBackFn, thisArg, scriptContext));
- }
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, 0u, newArr, newObj, 0u, callBackFn, thisArg, scriptContext));
- }
- #ifdef VALIDATE_ARRAY
- if (newArr)
- {
- newArr->ValidateArray();
- }
- #endif
- return newObj;
- }
- template <typename T>
- Var JavascriptArray::FilterObjectHelper(RecyclableObject* obj, T length, T start, JavascriptArray* newArr, RecyclableObject* newObj, T newStart,
- RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Var element = nullptr;
- Var selected = nullptr;
- BigIndex i = BigIndex(newStart);
- for (T k = start; k < length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock,
- element = JavascriptOperators::GetItem(obj, k, scriptContext),
- selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
- callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
- thisArg,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- obj));
- if (JavascriptConversion::ToBoolean(selected, scriptContext))
- {
- if (newArr)
- {
- newArr->DirectSetItemAt(i, element);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
- }
- ++i;
- }
- }
- }
- #ifdef VALIDATE_ARRAY
- if (newArr)
- {
- newArr->ValidateArray();
- }
- #endif
- return newObj;
- }
- Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
- }
- BigIndex length;
- JavascriptArray * pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduce"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
- }
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
- }
- // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
- template <typename T>
- Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- if (typedArrayBase != nullptr)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
- }
- else
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
- }
- }
- // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
- if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- T k = 0;
- RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
- Var accumulator = nullptr;
- Var element = nullptr;
- if (args.Info.Count > 2)
- {
- accumulator = args[2];
- }
- else
- {
- if (length == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
- }
- bool bPresent = false;
- if (pArr)
- {
- for (; k < length && bPresent == false; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
- if (!gotItem)
- {
- continue;
- }
- bPresent = true;
- accumulator = element;
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- }
- else if (typedArrayBase)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
- for (; k < end && bPresent == false; k++)
- {
- // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
- element = typedArrayBase->DirectGetItem((uint32)k);
- bPresent = true;
- accumulator = element;
- }
- }
- else
- {
- for (; k < length && bPresent == false; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, k, scriptContext));
- bPresent = true;
- }
- }
- }
- if (bPresent == false)
- {
- JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
- }
- }
- Assert(accumulator);
- Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- if (pArr)
- {
- for (; k < length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)k, &element));
- if (!gotItem)
- {
- continue;
- }
- JS_REENTRANT(jsReentLock,
- accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
- accumulator,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- pArr));
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
- }
- }
- }
- else if (typedArrayBase)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
- for (; k < end; k++)
- {
- // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
- element = typedArrayBase->DirectGetItem((uint32)k);
- JS_REENTRANT(jsReentLock,
- accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
- accumulator,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- typedArrayBase));
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
- }
- return accumulator;
- }
- template <typename T>
- Var JavascriptArray::ReduceObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var element = nullptr;
- for (T k = start; k < length; k++)
- {
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock,
- element = JavascriptOperators::GetItem(obj, k, scriptContext),
- accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
- accumulator,
- element,
- JavascriptNumber::ToVar(k, scriptContext),
- obj));
- }
- }
- return accumulator;
- }
- Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
- CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
- }
- BigIndex length;
- JavascriptArray * pArr = nullptr;
- RecyclableObject* obj = nullptr;
- JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduceRight"), &pArr, &obj, &length));
- if (length.IsSmallIndex())
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
- }
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
- }
- // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
- template <typename T>
- Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
- {
- if (typedArrayBase != nullptr)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
- }
- else
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
- }
- }
- // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
- if (typedArrayBase == nullptr && pArr == nullptr && TypedArrayBase::Is(obj))
- {
- typedArrayBase = TypedArrayBase::FromVar(obj);
- }
- RecyclableObject* callBackFn = RecyclableObject::FromVar(args[1]);
- Var accumulator = nullptr;
- Var element = nullptr;
- T k = 0;
- T index = 0;
- if (args.Info.Count > 2)
- {
- accumulator = args[2];
- }
- else
- {
- if (length == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
- }
- bool bPresent = false;
- if (pArr)
- {
- for (; k < length && bPresent == false; k++)
- {
- index = length - k - 1;
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
- if (!gotItem)
- {
- continue;
- }
- bPresent = true;
- accumulator = element;
- }
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- pArr = nullptr;
- }
- }
- else if (typedArrayBase)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
- for (; k < end && bPresent == false; k++)
- {
- // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
- index = length - k - 1;
- element = typedArrayBase->DirectGetItem((uint32)index);
- bPresent = true;
- accumulator = element;
- }
- }
- else
- {
- for (; k < length && bPresent == false; k++)
- {
- index = length - k - 1;
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, index, scriptContext));
- bPresent = true;
- }
- }
- }
- if (bPresent == false)
- {
- JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
- }
- }
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
- if (pArr)
- {
- for (; k < length; k++)
- {
- index = length - k - 1;
- JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull((uint32)index, &element));
- if (!gotItem)
- {
- continue;
- }
- JS_REENTRANT(jsReentLock,
- accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
- accumulator,
- element,
- JavascriptNumber::ToVar(index, scriptContext),
- pArr));
- // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
- // we will process the rest of the array elements like an ES5Array.
- if (!JavascriptArray::Is(obj))
- {
- AssertOrFailFastMsg(ES5Array::Is(obj), "The array should have been converted to an ES5Array");
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k + 1, callBackFn, accumulator, scriptContext));
- }
- }
- }
- else if (typedArrayBase)
- {
- AssertAndFailFast(TypedArrayBase::Is(typedArrayBase));
- uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
- for (; k < end; k++)
- {
- // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
- index = length - k - 1;
- element = typedArrayBase->DirectGetItem((uint32)index);
- JS_REENTRANT(jsReentLock,
- accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
- accumulator,
- element,
- JavascriptNumber::ToVar(index, scriptContext),
- typedArrayBase));
- }
- }
- else
- {
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
- }
- return accumulator;
- }
- template <typename T>
- Var JavascriptArray::ReduceRightObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
- CallFlags flags = CallFlags_Value;
- Var element = nullptr;
- T index = 0;
- for (T k = start; k < length; k++)
- {
- index = length - k - 1;
- JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
- if (hasItem)
- {
- JS_REENTRANT(jsReentLock,
- element = JavascriptOperators::GetItem(obj, index, scriptContext),
- accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(),
- callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
- accumulator,
- element,
- JavascriptNumber::ToVar(index, scriptContext),
- obj));
- }
- }
- return accumulator;
- }
- Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
- Assert(!(callInfo.Flags & CallFlags_New));
- JavascriptLibrary* library = scriptContext->GetLibrary();
- RecyclableObject* constructor = nullptr;
- if (JavascriptOperators::IsConstructor(args[0]))
- {
- constructor = RecyclableObject::FromVar(args[0]);
- }
- RecyclableObject* items = nullptr;
- if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
- }
- JavascriptArray* itemsArr = nullptr;
- if (JavascriptArray::Is(items))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(items);
- #endif
- itemsArr = JavascriptArray::FromVar(items);
- }
- bool mapping = false;
- JavascriptFunction* mapFn = nullptr;
- Var mapFnThisArg = nullptr;
- if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
- {
- if (!JavascriptFunction::Is(args[2]))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
- }
- mapFn = JavascriptFunction::FromVar(args[2]);
- if (args.Info.Count >= 4)
- {
- mapFnThisArg = args[3];
- }
- else
- {
- mapFnThisArg = library->GetUndefined();
- }
- mapping = true;
- }
- RecyclableObject* newObj = nullptr;
- JavascriptArray* newArr = nullptr;
- JS_REENTRANT(jsReentLock, RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */));
- if (iterator != nullptr)
- {
- if (constructor)
- {
- Js::Var constructorArgs[] = { constructor };
- Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
- JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
- if (JavascriptArray::Is(newObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
- #endif
- newArr = JavascriptArray::FromVar(newObj);
- }
- }
- else
- {
- newArr = scriptContext->GetLibrary()->CreateArray(0);
- newArr->EnsureHead<Var>();
- newObj = newArr;
- }
- uint32 k = 0;
- JS_REENTRANT(jsReentLock, JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
- if (mapping)
- {
- Assert(mapFn != nullptr);
- Assert(mapFnThisArg != nullptr);
- Js::Var mapFnArgs[] = { mapFnThisArg, nextValue, JavascriptNumber::ToVar(k, scriptContext) };
- Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
- nextValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs));
- }
- if (newArr)
- {
- newArr->SetItem(k, nextValue, PropertyOperation_None);
- }
- else
- {
- ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, nextValue), scriptContext, k);
- }
- k++;
- }));
- JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
- }
- else
- {
- JS_REENTRANT(jsReentLock, int64 len = (int64)OP_GetLength(items, scriptContext));
- if (constructor)
- {
- Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
- Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
- JS_REENTRANT(jsReentLock, newObj = RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext)));
- if (JavascriptArray::Is(newObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
- #endif
- newArr = JavascriptArray::FromVar(newObj);
- }
- }
- else
- {
- // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
- if (len > MaxArrayLength)
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
- }
- // Static cast len should be valid (len < 2^32) or we would throw above
- newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
- newArr->EnsureHead<Var>();
- newObj = newArr;
- }
- uint32 k = 0;
- for ( ; k < len; k++)
- {
- Var kValue;
- if (itemsArr)
- {
- JS_REENTRANT(jsReentLock, kValue = itemsArr->DirectGetItem(k));
- }
- else
- {
- JS_REENTRANT(jsReentLock, kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext));
- }
- if (mapping)
- {
- Assert(mapFn != nullptr);
- Assert(mapFnThisArg != nullptr);
- Js::Var mapFnArgs[] = { mapFnThisArg, kValue, JavascriptNumber::ToVar(k, scriptContext) };
- Js::CallInfo mapFnCallInfo(Js::CallFlags_Value, _countof(mapFnArgs));
- JS_REENTRANT(jsReentLock, kValue = mapFn->CallFunction(Js::Arguments(mapFnCallInfo, mapFnArgs)));
- }
- if (newArr)
- {
- newArr->SetItem(k, kValue, PropertyOperation_None);
- }
- else
- {
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, kValue), scriptContext, k));
- }
- }
- JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
- }
- return newObj;
- }
- Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
- {
- PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
- ARGUMENTS(args, callInfo);
- ScriptContext* scriptContext = function->GetScriptContext();
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(!(callInfo.Flags & CallFlags_New));
- if (args.Info.Count == 0)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
- }
- JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::OfHelper(false, args, scriptContext));
- }
- Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
- {
- ARGUMENTS(args, callInfo);
- Assert(args.Info.Count > 0);
- return args[0];
- }
- // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
- Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- Assert(args.Info.Count > 0);
- // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
- uint32 len = args.Info.Count - 1;
- Var newObj = nullptr;
- JavascriptArray* newArr = nullptr;
- TypedArrayBase* newTypedArray = nullptr;
- bool isBuiltinArrayCtor = true;
- if (JavascriptOperators::IsConstructor(args[0]))
- {
- RecyclableObject* constructor = RecyclableObject::FromVar(args[0]);
- isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
- Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
- Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
- if (isTypedArrayEntryPoint)
- {
- JS_REENTRANT(jsReentLock, newObj = TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext));
- }
- else
- {
- JS_REENTRANT(jsReentLock, newObj = JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
- }
- // If the new object we created is an array, remember that as it will save us time setting properties in the object below
- if (JavascriptArray::Is(newObj))
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newObj);
- #endif
- newArr = JavascriptArray::FromVar(newObj);
- }
- else if (TypedArrayBase::Is(newObj))
- {
- newTypedArray = TypedArrayBase::FromVar(newObj);
- }
- }
- else
- {
- // We only throw when the constructor property is not a constructor function in the TypedArray version
- if (isTypedArrayEntryPoint)
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
- }
- newArr = scriptContext->GetLibrary()->CreateArray(len);
- newArr->EnsureHead<Var>();
- newObj = newArr;
- }
- // At least we have a new object of some kind
- Assert(newObj);
- if (isBuiltinArrayCtor)
- {
- for (uint32 k = 0; k < len; k++)
- {
- Var kValue = args[k + 1];
- newArr->DirectSetItemAt(k, kValue);
- }
- }
- else if (newTypedArray)
- {
- for (uint32 k = 0; k < len; k++)
- {
- Var kValue = args[k + 1];
- JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, kValue));
- }
- }
- else
- {
- for (uint32 k = 0; k < len; k++)
- {
- Var kValue = args[k + 1];
- JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(RecyclableObject::FromVar(newObj), k, kValue), scriptContext, k));
- }
- }
- if (!isTypedArrayEntryPoint)
- {
- // Set length if we are in the Array version of the function
- JS_REENTRANT(jsReentLock, JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible));
- }
- return newObj;
- }
- JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(value);
- if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
- {
- return scriptContext->GetLibrary()->GetEmptyString();
- }
- else
- {
- return JavascriptConversion::ToLocaleString(value, scriptContext);
- }
- }
- inline BOOL JavascriptArray::IsFullArray() const
- {
- if (head && head->length == length)
- {
- AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
- return true;
- }
- return (0 == length);
- }
- /*
- * IsFillFromPrototypes
- * - Check the array has no missing values and only head segment.
- * - Also ensure if the lengths match.
- */
- bool JavascriptArray::IsFillFromPrototypes()
- {
- return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
- }
- // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
- // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
- void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
- {
- if (startIndex >= limitIndex)
- {
- return;
- }
- RecyclableObject* prototype = this->GetPrototype();
- // Fill all missing values by walking through prototype
- while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
- {
- ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
- this->SetItem(index, value, PropertyOperation_None);
- });
- prototype = prototype->GetPrototype();
- }
- #ifdef VALIDATE_ARRAY
- ValidateArray();
- #endif
- }
- //
- // JavascriptArray requires head->left == 0 for fast path Get.
- //
- template<typename T>
- void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
- {
- if (head == nullptr || head->left != 0)
- {
- // This is used to fix up altered arrays.
- // any SegmentMap would be invalid at this point.
- ClearSegmentMap();
- //
- // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
- // some protection here. Save the head and switch this array to EmptySegment. Will be restored
- // correctly if allocating new segment succeeds.
- //
- SparseArraySegment<T>* savedHead = SparseArraySegment<T>::From(this->head);
- SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
- SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
- SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
- newSeg->next = savedHead;
- this->head = newSeg;
- SetHasNoMissingValues();
- this->SetLastUsedSegment(savedLastUsedSegment);
- }
- }
- #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
- void JavascriptArray::CheckForceES5Array()
- {
- if (Configuration::Global.flags.ForceES5Array)
- {
- // There's a bad interaction with the jitted code for native array creation here.
- // ForceES5Array doesn't interact well with native arrays
- if (PHASE_OFF1(NativeArrayPhase))
- {
- GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
- }
- }
- }
- #endif
- template <typename T, typename Fn>
- void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, T destIndex, Fn fn)
- {
- JS_REENTRANCY_LOCK(jsReentLock, baseArray->GetScriptContext()->GetThreadContext());
- Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
- Var oldValue;
- JavascriptArray* arr = nullptr;
- if (DynamicObject::IsAnyArray(obj))
- {
- arr = JavascriptArray::FromAnyArray(obj);
- }
- else if (DynamicType::Is(obj->GetTypeId()))
- {
- DynamicObject* dynobj = DynamicObject::FromVar(obj);
- ArrayObject* objectArray = dynobj->GetObjectArray();
- arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::FromAnyArray(objectArray) : nullptr;
- }
- if (arr != nullptr)
- {
- if (JavascriptArray::Is(arr))
- {
- arr = EnsureNonNativeArray(arr);
- ArrayElementEnumerator e(arr, startIndex, limitIndex);
- while(e.MoveNext<Var>())
- {
- uint32 index = e.GetIndex();
- if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
- {
- T n = destIndex + (index - startIndex);
- if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
- {
- JS_REENTRANT(jsReentLock, fn(index, e.GetItem<Var>()));
- }
- }
- }
- }
- else
- {
- ScriptContext* scriptContext = obj->GetScriptContext();
- Assert(ES5Array::Is(arr));
- ES5Array* es5Array = ES5Array::FromVar(arr);
- ES5ArrayIndexStaticEnumerator<true> e(es5Array);
- while (e.MoveNext())
- {
- uint32 index = e.GetIndex();
- if (index < startIndex) continue;
- else if (index >= limitIndex) break;
- if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
- {
- T n = destIndex + (index - startIndex);
- if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
- {
- Var value = nullptr;
- JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext));
- if (gotItem)
- {
- JS_REENTRANT(jsReentLock, fn(index, value));
- }
- }
- }
- }
- }
- }
- }
- //
- // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
- //
- JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
- : start(start), end(min(end, arr->length))
- {
- Init(arr);
- }
- //
- // Initialize this enumerator and prepare for the first MoveNext.
- //
- void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
- {
- // Find start segment
- seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
- while (seg && (seg->left + seg->length <= start))
- {
- seg = seg->next;
- }
- // Set start index and endIndex
- if (seg)
- {
- if (seg->left >= end)
- {
- seg = nullptr;
- }
- else
- {
- // set index to be at target index - 1, so MoveNext will move to target
- index = max(seg->left, start) - seg->left - 1;
- endIndex = min(end - seg->left, seg->length);
- }
- }
- }
- //
- // Move to the next element if available.
- //
- template<typename T>
- inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
- {
- while (seg)
- {
- // Look for next non-null item in current segment
- while (++index < endIndex)
- {
- if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
- {
- return true;
- }
- }
- // Move to next segment
- seg = seg->next;
- if (seg)
- {
- if (seg->left >= end)
- {
- seg = nullptr;
- break;
- }
- else
- {
- index = static_cast<uint32>(-1);
- endIndex = min(end - seg->left, seg->length);
- }
- }
- }
- return false;
- }
- //
- // Get current array element index.
- //
- uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
- {
- Assert(seg && index < seg->length && index < endIndex);
- return seg->left + index;
- }
- //
- // Get current array element value.
- //
- template<typename T>
- T JavascriptArray::ArrayElementEnumerator::GetItem() const
- {
- Assert(seg && index < seg->length && index < endIndex &&
- !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
- return ((SparseArraySegment<T>*)seg)->elements[index];
- }
- //
- // Construct a BigIndex initialized to a given uint32 (small index).
- //
- JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
- : index(initIndex), bigIndex(InvalidIndex)
- {
- //ok if initIndex == InvalidIndex
- }
- //
- // Construct a BigIndex initialized to a given uint64 (large or small index).
- //
- JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
- : index(InvalidIndex), bigIndex(initIndex)
- {
- if (bigIndex < InvalidIndex) // if it's actually small index
- {
- index = static_cast<uint32>(bigIndex);
- bigIndex = InvalidIndex;
- }
- }
- bool JavascriptArray::BigIndex::IsUint32Max() const
- {
- return index == InvalidIndex && bigIndex == InvalidIndex;
- }
- bool JavascriptArray::BigIndex::IsSmallIndex() const
- {
- return index < InvalidIndex;
- }
- uint32 JavascriptArray::BigIndex::GetSmallIndex() const
- {
- Assert(IsSmallIndex());
- return index;
- }
- uint64 JavascriptArray::BigIndex::GetBigIndex() const
- {
- Assert(!IsSmallIndex());
- return bigIndex;
- }
- //
- // Convert this index value to a JS number
- //
- Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
- {
- if (IsSmallIndex())
- {
- return small_index::ToNumber(index, scriptContext);
- }
- else
- {
- return JavascriptNumber::ToVar(bigIndex, scriptContext);
- }
- }
- //
- // Increment this index by 1.
- //
- const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
- {
- if (IsSmallIndex())
- {
- ++index;
- // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
- }
- else
- {
- bigIndex = bigIndex + 1;
- }
- return *this;
- }
- //
- // Decrement this index by 1.
- //
- const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
- {
- if (IsSmallIndex())
- {
- --index;
- }
- else
- {
- Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
- --bigIndex;
- if (bigIndex < InvalidIndex)
- {
- index = InvalidIndex - 1;
- bigIndex = InvalidIndex;
- }
- }
- return *this;
- }
- JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
- {
- if (delta.IsSmallIndex())
- {
- return operator+(delta.GetSmallIndex());
- }
- if (IsSmallIndex())
- {
- return index + delta.GetBigIndex();
- }
- return bigIndex + delta.GetBigIndex();
- }
- //
- // Get a new BigIndex representing this + delta.
- //
- JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
- {
- if (IsSmallIndex())
- {
- uint32 newIndex;
- if (UInt32Math::Add(index, delta, &newIndex))
- {
- return static_cast<uint64>(index) + static_cast<uint64>(delta);
- }
- else
- {
- return newIndex; // ok if newIndex == InvalidIndex
- }
- }
- else
- {
- return bigIndex + static_cast<uint64>(delta);
- }
- }
- bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
- {
- if (rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- return this->GetSmallIndex() == rhs.GetSmallIndex();
- }
- else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
- {
- // if lhs is big promote rhs
- return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
- }
- else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- // if rhs is big promote lhs
- return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
- }
- return this->GetBigIndex() == rhs.GetBigIndex();
- }
- bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
- {
- if (rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- return this->GetSmallIndex() > rhs.GetSmallIndex();
- }
- else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
- {
- // if lhs is big promote rhs
- return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
- }
- else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- // if rhs is big promote lhs
- return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
- }
- return this->GetBigIndex() > rhs.GetBigIndex();
- }
- bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
- {
- if (rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- return this->GetSmallIndex() < rhs.GetSmallIndex();
- }
- else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
- {
- // if lhs is big promote rhs
- return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
- }
- else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- // if rhs is big promote lhs
- return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
- }
- return this->GetBigIndex() < rhs.GetBigIndex();
- }
- bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
- {
- if (rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- return this->GetSmallIndex() <= rhs.GetSmallIndex();
- }
- else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
- {
- // if lhs is big promote rhs
- return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
- }
- else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
- {
- // if rhs is big promote lhs
- return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
- }
- return this->GetBigIndex() <= rhs.GetBigIndex();
- }
- bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
- {
- if (rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- return this->GetSmallIndex() >= rhs.GetSmallIndex();
- }
- else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
- {
- // if lhs is big promote rhs
- return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
- }
- else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
- {
- // if rhs is big promote lhs
- return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
- }
- return this->GetBigIndex() >= rhs.GetBigIndex();
- }
- BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
- {
- if (IsSmallIndex())
- {
- return small_index::GetItem(arr, index, outVal);
- }
- else
- {
- ScriptContext* scriptContext = arr->GetScriptContext();
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
- return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
- }
- }
- BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
- {
- if (IsSmallIndex())
- {
- return small_index::SetItem(arr, index, newValue);
- }
- else
- {
- ScriptContext* scriptContext = arr->GetScriptContext();
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
- return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
- }
- }
- void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
- {
- if (IsSmallIndex())
- {
- small_index::SetItemIfNotExist(arr, index, newValue);
- }
- else
- {
- ScriptContext* scriptContext = arr->GetScriptContext();
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
- Var oldValue;
- PropertyId propertyId = propertyRecord->GetPropertyId();
- if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
- {
- arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
- }
- }
- }
- BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
- {
- if (IsSmallIndex())
- {
- return small_index::DeleteItem(arr, index);
- }
- else
- {
- ScriptContext* scriptContext = arr->GetScriptContext();
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
- return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
- }
- }
- BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
- {
- if (IsSmallIndex())
- {
- return small_index::SetItem(obj, index, newValue, flags);
- }
- else
- {
- ScriptContext* scriptContext = obj->GetScriptContext();
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
- return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
- }
- }
- BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
- {
- if (IsSmallIndex())
- {
- return small_index::DeleteItem(obj, index, flags);
- }
- else
- {
- PropertyRecord const * propertyRecord;
- JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
- return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
- }
- }
- //
- // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
- //
- void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
- {
- Assert(!dstIndex.IsSmallIndex());
- typedef IndexTrace<BigIndex> index_trace;
- BigIndex dst = dstIndex;
- uint32 i = start;
- ArrayElementEnumerator e(this, start);
- while(e.MoveNext<Var>())
- {
- // delete all items not enumerated
- while (i < e.GetIndex())
- {
- index_trace::DeleteItem(this, dst);
- ++i;
- ++dst;
- }
- // Copy over the item
- index_trace::SetItem(this, dst, e.GetItem<Var>());
- ++i;
- ++dst;
- }
- // Delete the rest till length
- while (i < this->length)
- {
- index_trace::DeleteItem(this, dst);
- ++i;
- ++dst;
- }
- // Elements moved, truncate the array at start
- SetLength(start);
- }
- //
- // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
- //
- template<typename T>
- void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
- {
- Assert(start < end && end <= srcArray->length);
- uint32 count = 0;
- // iterate on the array itself
- ArrayElementEnumerator e(srcArray, start, end);
- while(e.MoveNext<Var>())
- {
- T n = dstIndex + (e.GetIndex() - start);
- dstArray->DirectSetItemAt(n, e.GetItem<Var>());
- count++;
- }
- // iterate on the array's prototypes only if not all elements found
- if (start + count != end)
- {
- InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
- }
- }
- //
- // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index. If the index grows larger than
- // "array index", it will automatically turn to SetProperty using the index as property name.
- //
- void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start < end)
- {
- uint32 len = end - start;
- if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
- {
- // Won't overflow, use faster small_index version
- InternalCopyArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
- }
- else
- {
- InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
- }
- }
- }
- //
- // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
- //
- void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start < end)
- {
- Assert(end - start <= MaxArrayLength - dstIndex);
- InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
- }
- }
- template <typename T>
- void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
- #endif
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
- #endif
- if (JavascriptNativeIntArray::Is(srcArray))
- {
- CopyNativeIntArrayElementsToVar(dstArray, dstIndex, JavascriptNativeIntArray::FromVar(srcArray), start, end);
- }
- else if (JavascriptNativeFloatArray::Is(srcArray))
- {
- CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, JavascriptNativeFloatArray::FromVar(srcArray), start, end);
- }
- else
- {
- CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
- }
- }
- void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start < end)
- {
- uint32 len = end - start;
- if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
- {
- // Won't overflow, use faster small_index version
- InternalCopyNativeIntArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
- }
- else
- {
- InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
- }
- }
- }
- //
- // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
- //
- void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start < end)
- {
- Assert(end - start <= MaxArrayLength - dstIndex);
- InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
- }
- }
- bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start >= end)
- {
- return false;
- }
- Assert(end - start <= MaxArrayLength - dstIndex);
- Assert(start < end && end <= srcArray->length);
- uint32 count = 0;
- // iterate on the array itself
- ArrayElementEnumerator e(srcArray, start, end);
- while(e.MoveNext<int32>())
- {
- uint n = dstIndex + (e.GetIndex() - start);
- dstArray->DirectSetItemAt(n, e.GetItem<int32>());
- count++;
- }
- // iterate on the array's prototypes only if not all elements found
- if (start + count != end)
- {
- JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
- InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
- return true;
- }
- return false;
- }
- bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start >= end)
- {
- return false;
- }
- Assert(end - start <= MaxArrayLength - dstIndex);
- Assert(start < end && end <= srcArray->length);
- uint32 count = 0;
- // iterate on the array itself
- ArrayElementEnumerator e(srcArray, start, end);
- while(e.MoveNext<int32>())
- {
- uint n = dstIndex + (e.GetIndex() - start);
- dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
- count++;
- }
- // iterate on the array's prototypes only if not all elements found
- if (start + count != end)
- {
- JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
- InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
- return true;
- }
- return false;
- }
- void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, const BigIndex& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start < end)
- {
- uint32 len = end - start;
- if (dstIndex.IsSmallIndex() && (len < MaxArrayLength - dstIndex.GetSmallIndex()))
- {
- // Won't overflow, use faster small_index version
- InternalCopyNativeFloatArrayElements(dstArray, dstIndex.GetSmallIndex(), srcArray, start, end);
- }
- else
- {
- InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
- }
- }
- }
- //
- // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
- //
- void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start < end)
- {
- Assert(end - start <= MaxArrayLength - dstIndex);
- InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
- }
- }
- bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
- {
- end = min(end, srcArray->length);
- if (start >= end)
- {
- return false;
- }
- Assert(end - start <= MaxArrayLength - dstIndex);
- Assert(start < end && end <= srcArray->length);
- uint32 count = 0;
- // iterate on the array itself
- ArrayElementEnumerator e(srcArray, start, end);
- while(e.MoveNext<double>())
- {
- uint n = dstIndex + (e.GetIndex() - start);
- dstArray->DirectSetItemAt(n, e.GetItem<double>());
- count++;
- }
- // iterate on the array's prototypes only if not all elements found
- if (start + count != end)
- {
- JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
- InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
- return true;
- }
- return false;
- }
- JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
- #endif
- if (JavascriptNativeIntArray::Is(arr))
- {
- arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
- }
- else if (JavascriptNativeFloatArray::Is(arr))
- {
- arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
- }
- return arr;
- }
- BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
- {
- ScriptContext* requestContext = type->GetScriptContext();
- if (JavascriptNativeIntArray::GetItem(this, index, outVal, requestContext))
- {
- return TRUE;
- }
- return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
- }
- BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
- {
- ScriptContext* requestContext = type->GetScriptContext();
- if (JavascriptNativeFloatArray::GetItem(this, index, outVal, requestContext))
- {
- return TRUE;
- }
- return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
- }
- template<typename T>
- void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
- {
- Assert(start < end && end <= srcArray->length);
- uint32 count = 0;
- // iterate on the array itself
- ScriptContext *scriptContext = dstArray->GetScriptContext();
- ArrayElementEnumerator e(srcArray, start, end);
- while(e.MoveNext<int32>())
- {
- T n = dstIndex + (e.GetIndex() - start);
- dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
- count++;
- }
- // iterate on the array's prototypes only if not all elements found
- if (start + count != end)
- {
- InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
- }
- }
- template<typename T>
- void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, const T& dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
- {
- Assert(start < end && end <= srcArray->length);
- uint32 count = 0;
- // iterate on the array itself
- ScriptContext *scriptContext = dstArray->GetScriptContext();
- ArrayElementEnumerator e(srcArray, start, end);
- while(e.MoveNext<double>())
- {
- T n = dstIndex + (e.GetIndex() - start);
- dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
- count++;
- }
- // iterate on the array's prototypes only if not all elements found
- if (start + count != end)
- {
- InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
- }
- }
- Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
- {
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- // At this stage we have an array literal with some arguments to be spread.
- // First we need to calculate the real size of the final literal.
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
- #endif
- JavascriptArray *array = FromVar(arrayToSpread);
- uint32 arrayLength = array->GetLength();
- uint32 actualLength = arrayLength;
- for (unsigned i = 0; i < spreadIndices->count; ++i)
- {
- JS_REENTRANT(jsReentLock,
- actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext)));
- }
- JavascriptArray *result = FromVar(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
- // Now we copy each element and expand the spread parameters inline.
- for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < arrayLength && resultIndex < actualLength; ++i)
- {
- uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
- // 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.
- auto needArraySlowCopy = [&](Var instance) {
- if (JavascriptArray::Is(instance))
- {
- JavascriptArray *arr = JavascriptArray::FromVar(instance);
- JS_REENTRANT_UNLOCK(jsReentLock, return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes());
- }
- return false;
- };
- // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
- auto slowCopy = [&scriptContext, &needArraySlowCopy
- ](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
- Assert(needArraySlowCopy(srcArray) || ArgumentsObject::Is(srcArray) || TypedArrayBase::Is(srcArray) || JavascriptString::Is(srcArray));
- JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
- RecyclableObject *propertyObject;
- if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
- }
- for (uint32 j = start; j < end; j++)
- {
- Var element;
- JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext));
- if (!gotItem)
- {
- // Copy across missing values as undefined as per 12.2.5.2 SpreadElement : ... AssignmentExpression 5f.
- element = scriptContext->GetLibrary()->GetUndefined();
- }
- dstArray->DirectSetItemAt(dstIndex++, element);
- }
- };
- if (i < spreadIndex)
- {
- // Any non-spread elements can be copied in bulk.
- if (needArraySlowCopy(array))
- {
- slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
- }
- else
- {
- JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex));
- }
- resultIndex += spreadIndex - i;
- i = spreadIndex - 1;
- continue;
- }
- else if (i > spreadIndex)
- {
- // Any non-spread elements terminating the array can also be copied in bulk.
- Assert(spreadArrIndex == spreadIndices->count - 1);
- if (needArraySlowCopy(array))
- {
- slowCopy(result, resultIndex, array, i, arrayLength);
- }
- else
- {
- JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, arrayLength));
- }
- break;
- }
- else
- {
- JS_REENTRANT(jsReentLock, Var instance = array->DirectGetItem(i));
- if (SpreadArgument::Is(instance))
- {
- SpreadArgument* spreadArgument = SpreadArgument::FromVar(instance);
- uint32 len = spreadArgument->GetArgumentSpreadCount();
- const Var* spreadItems = spreadArgument->GetArgumentSpread();
- for (uint32 j = 0; j < len; j++)
- {
- result->DirectSetItemAt(resultIndex++, spreadItems[j]);
- }
- }
- else
- {
- Assert(JavascriptOperators::IsUndefinedObject(instance));
- result->DirectSetItemAt(resultIndex++, instance);
- }
- if (spreadArrIndex < spreadIndices->count - 1)
- {
- spreadArrIndex++;
- }
- }
- }
- AssertMsg(arrayLength == array->GetLength(), "Array's length should not have changed");
- return result;
- }
- uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
- {
- // A spread argument can be anything that returns a 'length' property, even if that
- // property is null or undefined.
- spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
- if (JavascriptArray::Is(spreadArg))
- {
- JavascriptArray *arr = JavascriptArray::FromVar(spreadArg);
- return arr->GetLength();
- }
- if (TypedArrayBase::Is(spreadArg))
- {
- TypedArrayBase *tarr = TypedArrayBase::FromVar(spreadArg);
- return tarr->GetLength();
- }
- if (SpreadArgument::Is(spreadArg))
- {
- SpreadArgument *spreadFunctionArgs = SpreadArgument::FromVar(spreadArg);
- return spreadFunctionArgs->GetArgumentSpreadCount();
- }
- AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
- Throw::FatalInternalError();
- }
- #ifdef VALIDATE_ARRAY
- class ArraySegmentsVisitor
- {
- private:
- SparseArraySegmentBase* seg;
- public:
- ArraySegmentsVisitor(SparseArraySegmentBase* head)
- : seg(head)
- {
- }
- void operator()(SparseArraySegmentBase* s)
- {
- Assert(seg == s);
- if (seg)
- {
- seg = seg->next;
- }
- }
- };
- void JavascriptArray::ValidateArrayCommon()
- {
- SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
- AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
- AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
- // Simple segments validation
- bool foundLastUsedSegment = false;
- SparseArraySegmentBase *seg = head;
- while(seg != nullptr)
- {
- if (seg == lastUsedSegment)
- {
- foundLastUsedSegment = true;
- }
- AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
- SparseArraySegmentBase* next = seg->next;
- if (next != nullptr)
- {
- AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
- AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
- AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
- }
- else
- {
- AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
- AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
- }
- seg = next;
- }
- AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
- // Validate segmentMap if present
- if (HasSegmentMap())
- {
- ArraySegmentsVisitor visitor(head);
- GetSegmentMap()->Walk(visitor);
- }
- }
- void JavascriptArray::ValidateArray()
- {
- if (!Js::Configuration::Global.flags.ArrayValidate)
- {
- return;
- }
- ValidateArrayCommon();
- // Detailed segments validation
- JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>::From(head));
- }
- void JavascriptNativeIntArray::ValidateArray()
- {
- if (!Js::Configuration::Global.flags.ArrayValidate)
- {
- #if DBG
- SparseArraySegmentBase *seg = head;
- while (seg)
- {
- if (seg->next != nullptr)
- {
- AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
- }
- seg = seg->next;
- }
- #endif
- return;
- }
- ValidateArrayCommon();
- // Detailed segments validation
- JavascriptArray::ValidateSegment<int32>(SparseArraySegment<int32>::From(head));
- }
- void JavascriptNativeFloatArray::ValidateArray()
- {
- if (!Js::Configuration::Global.flags.ArrayValidate)
- {
- #if DBG
- SparseArraySegmentBase *seg = head;
- while (seg)
- {
- if (seg->next != nullptr)
- {
- AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
- }
- seg = seg->next;
- }
- #endif
- return;
- }
- ValidateArrayCommon();
- // Detailed segments validation
- JavascriptArray::ValidateSegment<double>(SparseArraySegment<double>::From(head));
- }
- void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
- {
- if (!Js::Configuration::Global.flags.ArrayValidate)
- {
- return;
- }
- int32 inspect;
- double inspectDouble;
- while (seg)
- {
- uint32 i = 0;
- for (i = 0; i < seg->length; i++)
- {
- if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
- {
- continue;
- }
- if (TaggedInt::Is(seg->elements[i]))
- {
- inspect = TaggedInt::ToInt32(seg->elements[i]);
- }
- else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
- {
- inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
- }
- else
- {
- AssertMsg(RecyclableObject::Is(seg->elements[i]), "Invalid entry in segment");
- }
- }
- ValidateSegment(seg);
- seg = SparseArraySegment<Var>::From(seg->next);
- }
- }
- template<typename T>
- void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
- {
- if (!Js::Configuration::Global.flags.ArrayValidate)
- {
- return;
- }
- while (seg)
- {
- uint32 i = seg->length;
- while (i < seg->size)
- {
- AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
- i++;
- }
- seg = SparseArraySegment<T>::From(seg->next);
- }
- }
- #endif
- template <typename T>
- void JavascriptArray::InitBoxedInlineHeadSegment(SparseArraySegment<T> * dst, SparseArraySegment<T> * src)
- {
- // Don't copy the segment map, we will build it again
- SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
- SetHeadAndLastUsedSegment(dst);
- dst->left = src->left;
- dst->length = src->length;
- dst->size = src->size;
- dst->CheckLengthvsSize();
- dst->next = src->next;
- CopyArray(dst->elements, dst->size, src->elements, src->size);
- }
- JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead)
- : ArrayObject(instance)
- {
- if (boxHead)
- {
- InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, true>(this), SparseArraySegment<Var>::From(instance->head));
- }
- else
- {
- SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
- head = instance->head;
- SetLastUsedSegment(instance->GetLastUsedSegment());
- }
- }
- template <typename T>
- T * JavascriptArray::BoxStackInstance(T * instance)
- {
- Assert(ThreadContext::IsOnStack(instance));
- // On the stack, the we reserved a pointer before the object as to store the boxed value
- T ** boxedInstanceRef = ((T **)instance) - 1;
- T * boxedInstance = *boxedInstanceRef;
- if (boxedInstance)
- {
- return boxedInstance;
- }
- const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
- if (ThreadContext::IsOnStack(instance->head))
- {
- boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
- inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
- T, instance, true);
- }
- else if(inlineSlotsSize)
- {
- boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false);
- }
- else
- {
- boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false);
- }
- *boxedInstanceRef = boxedInstance;
- return boxedInstance;
- }
- JavascriptArray *
- JavascriptArray::BoxStackInstance(JavascriptArray * instance)
- {
- return BoxStackInstance<JavascriptArray>(instance);
- }
- #if ENABLE_TTD
- void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
- {
- TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
- ScriptContext* ctx = this->GetScriptContext();
- uint32 index = Js::JavascriptArray::InvalidIndex;
- while(true)
- {
- index = this->GetNextIndex(index);
- if(index == Js::JavascriptArray::InvalidIndex) // End of array
- {
- break;
- }
- Js::Var aval = nullptr;
- if(this->DirectGetVarItemAt(index, &aval, ctx))
- {
- extractor->MarkVisitVar(aval);
- }
- }
- }
- void JavascriptArray::ProcessCorePaths()
- {
- TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
- ScriptContext* ctx = this->GetScriptContext();
- uint32 index = Js::JavascriptArray::InvalidIndex;
- while(true)
- {
- index = this->GetNextIndex(index);
- if(index == Js::JavascriptArray::InvalidIndex) // End of array
- {
- break;
- }
- Js::Var aval = nullptr;
- if(this->DirectGetVarItemAt(index, &aval, ctx))
- {
- TTD::UtilSupport::TTAutoString pathExt;
- ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
- ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
- }
- }
- }
- TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
- {
- return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
- }
- void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
- {
- TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
- TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
- TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
- }
- #endif
- JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance) :
- JavascriptArray(instance, false),
- weakRefToFuncBody(instance->weakRefToFuncBody)
- {
- }
- JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead) :
- JavascriptNativeArray(instance)
- {
- if (boxHead)
- {
- InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>(this), SparseArraySegment<int>::From(instance->head));
- }
- else
- {
- // Base class ctor should have copied these
- Assert(head == instance->head);
- Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
- }
- }
- JavascriptNativeIntArray *
- JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance)
- {
- return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance);
- }
- #if ENABLE_TTD
- TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
- {
- return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
- }
- void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
- {
- TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
- TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
- }
- #if ENABLE_COPYONACCESS_ARRAY
- TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
- {
- return TTD::NSSnapObjects::SnapObjectType::Invalid;
- }
- void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
- {
- TTDAssert(false, "Not implemented yet!!!");
- }
- #endif
- #endif
- JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead) :
- JavascriptNativeArray(instance)
- {
- if (boxHead)
- {
- InitBoxedInlineHeadSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>(this), SparseArraySegment<double>::From(instance->head));
- }
- else
- {
- // Base class ctor should have copied these
- Assert(head == instance->head);
- Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
- }
- }
- JavascriptNativeFloatArray *
- JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance)
- {
- return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance);
- }
- #if ENABLE_TTD
- TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
- {
- return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
- }
- void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
- {
- TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
- TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
- TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
- }
- #endif
- template<typename T>
- RecyclableObject*
- JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
- {
- if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
- {
- return nullptr;
- }
- if (JavascriptArray::Is(originalArray)
- && !DynamicObject::FromVar(originalArray)->GetDynamicType()->GetTypeHandler()->GetIsNotPathTypeHandlerOrHasUserDefinedCtor()
- && DynamicObject::FromVar(originalArray)->GetPrototype() == scriptContext->GetLibrary()->GetArrayPrototype()
- && !scriptContext->GetLibrary()->GetArrayObjectHasUserDefinedSpecies())
- {
- return nullptr;
- }
- Var constructor = scriptContext->GetLibrary()->GetUndefined();
- if (JavascriptOperators::IsArray(originalArray))
- {
- if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(originalArray), PropertyIds::constructor, &constructor, scriptContext))
- {
- return nullptr;
- }
- if (JavascriptOperators::IsConstructor(constructor))
- {
- ScriptContext* constructorScriptContext = RecyclableObject::FromVar(constructor)->GetScriptContext();
- if (constructorScriptContext != scriptContext)
- {
- if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
- {
- constructor = scriptContext->GetLibrary()->GetUndefined();
- }
- }
- }
- if (JavascriptOperators::IsObject(constructor))
- {
- if (!JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext))
- {
- if (pIsBuiltinArrayCtor != nullptr)
- {
- *pIsBuiltinArrayCtor = false;
- }
- return nullptr;
- }
- if (constructor == scriptContext->GetLibrary()->GetNull())
- {
- constructor = scriptContext->GetLibrary()->GetUndefined();
- }
- }
- }
- if (constructor == scriptContext->GetLibrary()->GetUndefined() || constructor == scriptContext->GetLibrary()->GetArrayConstructor())
- {
- if (length > UINT_MAX)
- {
- JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
- }
- if (nullptr == pIsIntArray)
- {
- return scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
- }
- else
- {
- // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
- JavascriptArray* pArr = JavascriptArray::FromVar(originalArray);
- pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
- return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
- }
- }
- if (!JavascriptOperators::IsConstructor(constructor))
- {
- JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
- }
- if (pIsBuiltinArrayCtor != nullptr)
- {
- *pIsBuiltinArrayCtor = false;
- }
- Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
- Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
- return RecyclableObject::FromVar(JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
- }
- /*static*/
- PropertyId const JavascriptArray::specialPropertyIds[] =
- {
- PropertyIds::length
- };
- BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
- {
- if (propertyId == PropertyIds::length)
- {
- return false;
- }
- return DynamicObject::DeleteProperty(propertyId, flags);
- }
- BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
- {
- JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
- if (BuiltInPropertyRecords::length.Equals(propertyName))
- {
- return false;
- }
- return DynamicObject::DeleteProperty(propertyNameString, flags);
- }
- BOOL JavascriptArray::HasProperty(PropertyId propertyId)
- {
- if (propertyId == PropertyIds::length)
- {
- return true;
- }
- ScriptContext* scriptContext = GetScriptContext();
- uint32 index;
- if (scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- return this->HasItem(index);
- }
- return DynamicObject::HasProperty(propertyId);
- }
- BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
- {
- if (propertyId == PropertyIds::length)
- {
- return false;
- }
- return DynamicObject::IsEnumerable(propertyId);
- }
- BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
- {
- if (propertyId == PropertyIds::length)
- {
- return false;
- }
- return DynamicObject::IsConfigurable(propertyId);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
- {
- if (propertyId == PropertyIds::length)
- {
- Assert(!value); // Can't change array length enumerable
- return true;
- }
- ScriptContext* scriptContext = this->GetScriptContext();
- uint32 index;
- if (scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetEnumerable(this, propertyId, value);
- }
- return __super::SetEnumerable(propertyId, value);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
- {
- ScriptContext* scriptContext = this->GetScriptContext();
- uint32 index;
- bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
- if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetWritable(this, propertyId, value);
- }
- return __super::SetWritable(propertyId, value);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
- {
- if (propertyId == PropertyIds::length)
- {
- Assert(!value); // Can't change array length configurable
- return true;
- }
- ScriptContext* scriptContext = this->GetScriptContext();
- uint32 index;
- if (scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetConfigurable(this, propertyId, value);
- }
- return __super::SetConfigurable(propertyId, value);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
- {
- ScriptContext* scriptContext = this->GetScriptContext();
- // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
- // changed, we need to handle it here.
- Assert(propertyId != PropertyIds::length);
- uint32 index;
- if (scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetItemAttributes(this, index, attributes);
- }
- return __super::SetAttributes(propertyId, attributes);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
- {
- ScriptContext* scriptContext = this->GetScriptContext();
- uint32 index;
- if (scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetItemAccessors(this, index, getter, setter);
- }
- return __super::SetAccessors(propertyId, getter, setter, flags);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetItemWithAttributes(this, index, value, attributes);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetItemAttributes(this, index, attributes);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
- ->SetItemAccessors(this, index, getter, setter);
- }
- // Check if this objectArray isFrozen.
- BOOL JavascriptArray::IsObjectArrayFrozen()
- {
- // If this is still a JavascriptArray, it's not frozen.
- return false;
- }
- JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
- {
- if (!!(flags & EnumeratorFlags::SnapShotSemantics))
- {
- return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
- }
- return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
- }
- BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
- {
- return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
- }
- BOOL JavascriptArray::IsItemEnumerable(uint32 index)
- {
- return true;
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::PreventExtensions()
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::Seal()
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
- }
- //
- // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
- // handling and only check instance objectArray for numeric propertyIds.
- //
- BOOL JavascriptArray::Freeze()
- {
- return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
- }
- BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, Var *propertyName, ScriptContext * requestContext)
- {
- if (index == 0)
- {
- *propertyName = requestContext->GetPropertyString(PropertyIds::length);
- return true;
- }
- return false;
- }
- // Returns the number of special non-enumerable properties this type has.
- uint JavascriptArray::GetSpecialPropertyCount() const
- {
- return _countof(specialPropertyIds);
- }
- // Returns the list of special non-enumerable properties for the type.
- PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
- {
- return specialPropertyIds;
- }
- BOOL JavascriptArray::GetPropertyReference(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
- {
- return JavascriptArray::GetProperty(originalInstance, propertyId, value, info, requestContext);
- }
- BOOL JavascriptArray::GetProperty(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
- {
- if (GetPropertyBuiltIns(propertyId, value))
- {
- return true;
- }
- ScriptContext* scriptContext = GetScriptContext();
- uint32 index;
- if (scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- return this->GetItem(this, index, value, scriptContext);
- }
- return DynamicObject::GetProperty(originalInstance, propertyId, value, info, requestContext);
- }
- BOOL JavascriptArray::GetProperty(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
- {
- AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
- "Numeric property names should have been converted to uint or PropertyRecord*");
- PropertyRecord const* propertyRecord;
- this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
- if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
- {
- return true;
- }
- return DynamicObject::GetProperty(originalInstance, propertyNameString, value, info, requestContext);
- }
- BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
- {
- //
- // length being accessed. Return array length
- //
- if (propertyId == PropertyIds::length)
- {
- *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
- return true;
- }
- return false;
- }
- BOOL JavascriptArray::HasItem(uint32 index)
- {
- Var value;
- return this->DirectGetItemAt<Var>(index, &value);
- }
- BOOL JavascriptArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
- {
- return this->DirectGetItemAt<Var>(index, value);
- }
- BOOL JavascriptArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
- {
- return this->DirectGetItemAt<Var>(index, value);
- }
- BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
- {
- return this->DirectGetItemAt<Var>(index, value);
- }
- BOOL JavascriptNativeIntArray::HasItem(uint32 index)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- int32 value;
- return this->DirectGetItemAt<int32>(index, &value);
- }
- BOOL JavascriptNativeFloatArray::HasItem(uint32 index)
- {
- double dvalue;
- return this->DirectGetItemAt<double>(index, &dvalue);
- }
- BOOL JavascriptNativeIntArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- return JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext);
- }
- BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
- {
- int32 intvalue;
- if (!this->DirectGetItemAt<int32>(index, &intvalue))
- {
- return FALSE;
- }
- *value = JavascriptNumber::ToVar(intvalue, requestContext);
- return TRUE;
- }
- BOOL JavascriptNativeIntArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
- {
- return JavascriptNativeIntArray::GetItem(originalInstance, index, value, requestContext);
- }
- BOOL JavascriptNativeFloatArray::GetItem(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
- {
- return JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext);
- }
- BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
- {
- double dvalue;
- int32 ivalue;
- if (!this->DirectGetItemAt<double>(index, &dvalue))
- {
- return FALSE;
- }
- if (*(uint64*)&dvalue == 0ull)
- {
- *value = TaggedInt::ToVarUnchecked(0);
- }
- else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
- {
- *value = TaggedInt::ToVarUnchecked(ivalue);
- }
- else
- {
- *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
- }
- return TRUE;
- }
- BOOL JavascriptNativeFloatArray::GetItemReference(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
- {
- return JavascriptNativeFloatArray::GetItem(originalInstance, index, value, requestContext);
- }
- BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- uint32 indexValue;
- if (propertyId == PropertyIds::length)
- {
- return this->SetLength(value);
- }
- else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
- {
- // Call this or subclass method
- return SetItem(indexValue, value, flags);
- }
- else
- {
- return DynamicObject::SetProperty(propertyId, value, flags, info);
- }
- }
- BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
- {
- AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
- "Numeric property names should have been converted to uint or PropertyRecord*");
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- PropertyRecord const* propertyRecord;
- this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
- if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
- {
- return this->SetLength(value);
- }
- return DynamicObject::SetProperty(propertyNameString, value, flags, info);
- }
- BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
- {
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- ScriptContext* scriptContext = GetScriptContext();
- if (propertyId == PropertyIds::length)
- {
- Assert(attributes == PropertyWritable);
- Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
- return this->SetLength(value);
- }
- uint32 index;
- if (scriptContext->IsNumericPropertyId(propertyId, &index))
- {
- // Call this or subclass method
- return SetItemWithAttributes(index, value, attributes);
- }
- return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
- }
- BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
- {
- this->DirectSetItemAt(index, value);
- return true;
- }
- BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
- {
- int32 iValue;
- double dValue;
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
- #endif
- TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
- if (typeId == TypeIds_NativeIntArray)
- {
- this->SetItem(index, iValue);
- }
- else if (typeId == TypeIds_NativeFloatArray)
- {
- reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
- }
- else
- {
- this->DirectSetItemAt<Var>(index, value);
- }
- return TRUE;
- }
- TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
- {
- if (TaggedInt::Is(value))
- {
- int32 i = TaggedInt::ToInt32(value);
- if (i != JavascriptNativeIntArray::MissingItem)
- {
- *iValue = i;
- return TypeIds_NativeIntArray;
- }
- }
- if (JavascriptNumber::Is_NoTaggedIntCheck(value))
- {
- bool isInt32;
- int32 i;
- double d = JavascriptNumber::GetValue(value);
- if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
- {
- if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
- {
- *iValue = i;
- return TypeIds_NativeIntArray;
- }
- }
- else
- {
- *dValue = d;
- JavascriptNativeIntArray::ToNativeFloatArray(this);
- return TypeIds_NativeFloatArray;
- }
- }
- JavascriptNativeIntArray::ToVarArray(this);
- return TypeIds_Array;
- }
- BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
- {
- if (iValue == JavascriptNativeIntArray::MissingItem)
- {
- JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
- varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
- return TRUE;
- }
- this->DirectSetItemAt(index, iValue);
- return TRUE;
- }
- BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
- {
- double dValue;
- TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
- if (typeId == TypeIds_NativeFloatArray)
- {
- this->SetItem(index, dValue);
- }
- else
- {
- this->DirectSetItemAt(index, value);
- }
- return TRUE;
- }
- TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
- {
- if (TaggedInt::Is(value))
- {
- *dValue = (double)TaggedInt::ToInt32(value);
- return TypeIds_NativeFloatArray;
- }
- else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
- {
- *dValue = JavascriptNumber::GetValue(value);
- return TypeIds_NativeFloatArray;
- }
- JavascriptNativeFloatArray::ToVarArray(this);
- return TypeIds_Array;
- }
- BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
- {
- if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
- {
- JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
- varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
- return TRUE;
- }
- this->DirectSetItemAt<double>(index, dValue);
- return TRUE;
- }
- BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
- {
- return this->DirectDeleteItemAt<Var>(index);
- }
- BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
- {
- return this->DirectDeleteItemAt<int32>(index);
- }
- BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
- {
- return this->DirectDeleteItemAt<double>(index);
- }
- BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, ForInCache * forInCache)
- {
- return enumerator->Initialize(nullptr, this, this, flags, requestContext, forInCache);
- }
- BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
- {
- stringBuilder->Append(_u('['));
- if (this->length < 10)
- {
- auto funcPtr = [&]()
- {
- ENTER_PINNED_SCOPE(JavascriptString, valueStr);
- valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
- stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
- LEAVE_PINNED_SCOPE();
- };
- if (!requestContext->GetThreadContext()->IsScriptActive())
- {
- BEGIN_JS_RUNTIME_CALL(requestContext);
- {
- funcPtr();
- }
- END_JS_RUNTIME_CALL(requestContext);
- }
- else
- {
- funcPtr();
- }
- }
- else
- {
- stringBuilder->AppendCppLiteral(_u("..."));
- }
- stringBuilder->Append(_u(']'));
- return TRUE;
- }
- BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
- {
- stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
- return TRUE;
- }
- bool JavascriptNativeArray::Is(Var aValue)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(aValue);
- return JavascriptNativeArray::Is(typeId);
- }
- bool JavascriptNativeArray::Is(TypeId typeId)
- {
- return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
- }
- JavascriptNativeArray* JavascriptNativeArray::FromVar(Var aValue)
- {
- AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeArray'");
- return static_cast<JavascriptNativeArray *>(RecyclableObject::FromVar(aValue));
- }
- bool JavascriptNativeIntArray::Is(Var aValue)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(aValue);
- return JavascriptNativeIntArray::Is(typeId);
- }
- #if ENABLE_COPYONACCESS_ARRAY
- bool JavascriptCopyOnAccessNativeIntArray::Is(Var aValue)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(aValue);
- return JavascriptCopyOnAccessNativeIntArray::Is(typeId);
- }
- #endif
- bool JavascriptNativeIntArray::Is(TypeId typeId)
- {
- return typeId == TypeIds_NativeIntArray;
- }
- #if ENABLE_COPYONACCESS_ARRAY
- bool JavascriptCopyOnAccessNativeIntArray::Is(TypeId typeId)
- {
- return typeId == TypeIds_CopyOnAccessNativeIntArray;
- }
- #endif
- bool JavascriptNativeIntArray::IsNonCrossSite(Var aValue)
- {
- bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue);
- Assert(ret == (JavascriptNativeIntArray::Is(aValue) && !JavascriptNativeIntArray::FromVar(aValue)->IsCrossSiteObject()));
- return ret;
- }
- JavascriptNativeIntArray* JavascriptNativeIntArray::FromVar(Var aValue)
- {
- AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeIntArray'");
- return static_cast<JavascriptNativeIntArray *>(RecyclableObject::FromVar(aValue));
- }
- #if ENABLE_COPYONACCESS_ARRAY
- JavascriptCopyOnAccessNativeIntArray* JavascriptCopyOnAccessNativeIntArray::FromVar(Var aValue)
- {
- AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptCopyOnAccessNativeIntArray'");
- return static_cast<JavascriptCopyOnAccessNativeIntArray *>(RecyclableObject::FromVar(aValue));
- }
- #endif
- bool JavascriptNativeFloatArray::Is(Var aValue)
- {
- TypeId typeId = JavascriptOperators::GetTypeId(aValue);
- return JavascriptNativeFloatArray::Is(typeId);
- }
- bool JavascriptNativeFloatArray::Is(TypeId typeId)
- {
- return typeId == TypeIds_NativeFloatArray;
- }
- bool JavascriptNativeFloatArray::IsNonCrossSite(Var aValue)
- {
- bool ret = !TaggedInt::Is(aValue) && VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue);
- Assert(ret == (JavascriptNativeFloatArray::Is(aValue) && !JavascriptNativeFloatArray::FromVar(aValue)->IsCrossSiteObject()));
- return ret;
- }
- JavascriptNativeFloatArray* JavascriptNativeFloatArray::FromVar(Var aValue)
- {
- AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptNativeFloatArray'");
- return static_cast<JavascriptNativeFloatArray *>(RecyclableObject::FromVar(aValue));
- }
- template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
- template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
- template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
- template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
- template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
- } //namespace Js
|