Parse.cpp 494 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "ParserPch.h"
  6. #include "FormalsUtil.h"
  7. #include "../Runtime/Language/SourceDynamicProfileManager.h"
  8. #include "ByteCode/ByteCodeSerializer.h"
  9. #if DBG_DUMP
  10. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt);
  11. #endif
  12. const char* const nopNames[knopLim] = {
  13. #define PTNODE(nop,sn,pc,nk,grfnop,json) sn,
  14. #include "ptlist.h"
  15. };
  16. void printNop(int nop) {
  17. Output::Print(_u("%S\n"), nopNames[nop]);
  18. }
  19. const uint ParseNode::mpnopgrfnop[knopLim] =
  20. {
  21. #define PTNODE(nop,sn,pc,nk,grfnop,json) grfnop,
  22. #include "ptlist.h"
  23. };
  24. bool Parser::IsES6DestructuringEnabled() const
  25. {
  26. return m_scriptContext->GetConfig()->IsES6DestructuringEnabled();
  27. }
  28. struct BlockInfoStack
  29. {
  30. StmtNest pstmt;
  31. ParseNodeBlock *pnodeBlock;
  32. ParseNodePtr *m_ppnodeLex; // lexical variable list tail
  33. BlockInfoStack *pBlockInfoOuter; // containing block's BlockInfoStack
  34. BlockInfoStack *pBlockInfoFunction; // nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)
  35. };
  36. #if DEBUG
  37. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)
  38. #else
  39. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)
  40. #endif
  41. : m_nodeAllocator(_u("Parser"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),
  42. m_cactIdentToNodeLookup(0),
  43. m_grfscr(fscrNil),
  44. m_length(0),
  45. m_originalLength(0),
  46. m_nextFunctionId(nullptr),
  47. m_sourceContextInfo(nullptr),
  48. #if ENABLE_BACKGROUND_PARSING
  49. m_isInBackground(isBackground),
  50. m_hasParallelJob(false),
  51. m_doingFastScan(false),
  52. #endif
  53. m_nextBlockId(0),
  54. m_tempGuestArenaReleased(false),
  55. m_tempGuestArena(scriptContext->GetTemporaryGuestAllocator(_u("ParserRegex")), scriptContext->GetRecycler()),
  56. // use the GuestArena directly for keeping the RegexPattern* alive during byte code generation
  57. m_registeredRegexPatterns(m_tempGuestArena->GetAllocator()),
  58. m_scriptContext(scriptContext),
  59. m_token(), // should initialize to 0/nullptrs
  60. m_scan(this, &m_token, scriptContext),
  61. m_currentNodeNonLambdaFunc(nullptr),
  62. m_currentNodeNonLambdaDeferredFunc(nullptr),
  63. m_currentNodeFunc(nullptr),
  64. m_currentNodeDeferredFunc(nullptr),
  65. m_currentNodeProg(nullptr),
  66. m_currDeferredStub(nullptr),
  67. m_currDeferredStubCount(0),
  68. m_pCurrentAstSize(nullptr),
  69. m_ppnodeScope(nullptr),
  70. m_ppnodeExprScope(nullptr),
  71. m_ppnodeVar(nullptr),
  72. m_inDeferredNestedFunc(false),
  73. m_reparsingLambdaParams(false),
  74. m_disallowImportExportStmt(false),
  75. m_isInParsingArgList(false),
  76. m_hasDestructuringPattern(false),
  77. m_hasDeferredShorthandInitError(false),
  78. m_deferCommaError(false),
  79. m_pnestedCount(nullptr),
  80. wellKnownPropertyPids(), // should initialize to nullptrs
  81. m_sourceLim(0),
  82. m_functionBody(nullptr),
  83. m_parseType(ParseType_Upfront),
  84. m_arrayDepth(0),
  85. m_funcInArrayDepth(0),
  86. m_funcInArray(0),
  87. m_scopeCountNoAst(0),
  88. m_funcParenExprDepth(0),
  89. m_deferEllipsisError(false),
  90. m_deferEllipsisErrorLoc(), // calls default initializer
  91. m_deferCommaErrorLoc(),
  92. m_tryCatchOrFinallyDepth(0),
  93. m_pstmtCur(nullptr),
  94. m_currentBlockInfo(nullptr),
  95. m_currentScope(nullptr),
  96. currBackgroundParseItem(nullptr),
  97. backgroundParseItems(nullptr),
  98. fastScannedRegExpNodes(nullptr),
  99. m_currentDynamicBlock(nullptr),
  100. m_UsesArgumentsAtGlobal(false),
  101. m_fUseStrictMode(strictMode),
  102. m_InAsmMode(false),
  103. m_deferAsmJs(true),
  104. m_fExpectExternalSource(FALSE),
  105. m_deferringAST(FALSE),
  106. m_stoppedDeferredParse(FALSE)
  107. {
  108. AssertMsg(size == sizeof(Parser), "verify conditionals affecting the size of Parser agree");
  109. Assert(scriptContext != nullptr);
  110. // init PID members
  111. InitPids();
  112. }
  113. Parser::~Parser(void)
  114. {
  115. this->ReleaseTemporaryGuestArena();
  116. #if ENABLE_BACKGROUND_PARSING
  117. if (this->m_hasParallelJob)
  118. {
  119. // Let the background threads know that they can decommit their arena pages.
  120. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  121. Assert(bgp);
  122. if (bgp->Processor()->ProcessesInBackground())
  123. {
  124. JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());
  125. bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {
  126. threadData->canDecommit = true;
  127. return false;
  128. });
  129. Assert(result);
  130. }
  131. }
  132. #endif
  133. }
  134. void Parser::OutOfMemory()
  135. {
  136. throw ParseExceptionObject(ERRnoMemory);
  137. }
  138. LPCWSTR Parser::GetTokenString(tokens token)
  139. {
  140. switch (token)
  141. {
  142. case tkNone : return _u("");
  143. case tkEOF : return _u("end of script");
  144. case tkIntCon : return _u("integer literal");
  145. case tkFltCon : return _u("float literal");
  146. case tkStrCon : return _u("string literal");
  147. case tkRegExp : return _u("regular expression literal");
  148. // keywords
  149. case tkABSTRACT : return _u("abstract");
  150. case tkASSERT : return _u("assert");
  151. case tkAWAIT : return _u("await");
  152. case tkBOOLEAN : return _u("boolean");
  153. case tkBREAK : return _u("break");
  154. case tkBYTE : return _u("byte");
  155. case tkCASE : return _u("case");
  156. case tkCATCH : return _u("catch");
  157. case tkCHAR : return _u("char");
  158. case tkCONTINUE : return _u("continue");
  159. case tkDEBUGGER : return _u("debugger");
  160. case tkDECIMAL : return _u("decimal");
  161. case tkDEFAULT : return _u("default");
  162. case tkDELETE : return _u("delete");
  163. case tkDO : return _u("do");
  164. case tkDOUBLE : return _u("double");
  165. case tkELSE : return _u("else");
  166. case tkENSURE : return _u("ensure");
  167. case tkEVENT : return _u("event");
  168. case tkFALSE : return _u("false");
  169. case tkFINAL : return _u("final");
  170. case tkFINALLY : return _u("finally");
  171. case tkFLOAT : return _u("float");
  172. case tkFOR : return _u("for");
  173. case tkFUNCTION : return _u("function");
  174. case tkGET : return _u("get");
  175. case tkGOTO : return _u("goto");
  176. case tkIF : return _u("if");
  177. case tkIN : return _u("in");
  178. case tkINSTANCEOF : return _u("instanceof");
  179. case tkINT : return _u("int");
  180. case tkINTERNAL : return _u("internal");
  181. case tkINVARIANT : return _u("invariant");
  182. case tkLONG : return _u("long");
  183. case tkNAMESPACE : return _u("namespace");
  184. case tkNATIVE : return _u("native");
  185. case tkNEW : return _u("new");
  186. case tkNULL : return _u("null");
  187. case tkREQUIRE : return _u("require");
  188. case tkRETURN : return _u("return");
  189. case tkSBYTE : return _u("sbyte");
  190. case tkSET : return _u("set");
  191. case tkSHORT : return _u("short");
  192. case tkSWITCH : return _u("switch");
  193. case tkSYNCHRONIZED : return _u("synchronized");
  194. case tkTHIS : return _u("this");
  195. case tkTHROW : return _u("throw");
  196. case tkTHROWS : return _u("throws");
  197. case tkTRANSIENT : return _u("transient");
  198. case tkTRUE : return _u("true");
  199. case tkTRY : return _u("try");
  200. case tkTYPEOF : return _u("typeof");
  201. case tkUINT : return _u("uint");
  202. case tkULONG : return _u("ulong");
  203. case tkUSE : return _u("use");
  204. case tkUSHORT : return _u("ushort");
  205. case tkVAR : return _u("var");
  206. case tkVOID : return _u("void");
  207. case tkVOLATILE : return _u("volatile");
  208. case tkWHILE : return _u("while");
  209. case tkWITH : return _u("with");
  210. // Future reserved words that become keywords in ES6
  211. case tkCLASS : return _u("class");
  212. case tkCONST : return _u("const");
  213. case tkEXPORT : return _u("export");
  214. case tkEXTENDS : return _u("extends");
  215. case tkIMPORT : return _u("import");
  216. case tkLET : return _u("let");
  217. case tkSUPER : return _u("super");
  218. case tkYIELD : return _u("yield");
  219. // Future reserved words in strict and non-strict modes
  220. case tkENUM : return _u("enum");
  221. // Additional future reserved words in strict mode
  222. case tkIMPLEMENTS : return _u("implements");
  223. case tkINTERFACE : return _u("interface");
  224. case tkPACKAGE : return _u("package");
  225. case tkPRIVATE : return _u("private");
  226. case tkPROTECTED : return _u("protected");
  227. case tkPUBLIC : return _u("public");
  228. case tkSTATIC : return _u("static");
  229. case tkID: return _u("identifier");
  230. // Non-operator non-identifier tokens
  231. case tkSColon: return _u(";");
  232. case tkRParen: return _u(")");
  233. case tkRBrack: return _u("]");
  234. case tkLCurly: return _u("{");
  235. case tkRCurly: return _u("}");
  236. // Operator non-identifier tokens
  237. case tkComma: return _u(",");
  238. case tkDArrow: return _u("=>");
  239. case tkAsg: return _u("=");
  240. case tkAsgAdd: return _u("+=");
  241. case tkAsgSub: return _u("-=");
  242. case tkAsgMul: return _u("*=");
  243. case tkAsgDiv: return _u("/=");
  244. case tkAsgExpo: return _u("**=");
  245. case tkAsgMod: return _u("%=");
  246. case tkAsgAnd: return _u("&=");
  247. case tkAsgXor: return _u("^=");
  248. case tkAsgOr: return _u("|=");
  249. case tkAsgLsh: return _u("<<=");
  250. case tkAsgRsh: return _u(">>=");
  251. case tkAsgRs2: return _u(">>>=");
  252. case tkQMark: return _u("?");
  253. case tkColon: return _u(":");
  254. case tkLogOr: return _u("||");
  255. case tkLogAnd: return _u("&&");
  256. case tkOr: return _u("|");
  257. case tkXor: return _u("^");
  258. case tkAnd: return _u("&");
  259. case tkEQ: return _u("==");
  260. case tkNE: return _u("!=");
  261. case tkEqv: return _u("===");
  262. case tkNEqv: return _u("!==");
  263. case tkLT: return _u("<");
  264. case tkLE: return _u("<=");
  265. case tkGT: return _u(">");
  266. case tkGE: return _u(">=");
  267. case tkLsh: return _u("<<");
  268. case tkRsh: return _u(">>");
  269. case tkRs2: return _u(">>>");
  270. case tkAdd: return _u("+");
  271. case tkSub: return _u("-");
  272. case tkExpo: return _u("**");
  273. case tkStar: return _u("*");
  274. case tkDiv: return _u("/");
  275. case tkPct: return _u("%");
  276. case tkTilde: return _u("~");
  277. case tkBang: return _u("!");
  278. case tkInc: return _u("++");
  279. case tkDec: return _u("--");
  280. case tkEllipsis: return _u("...");
  281. case tkLParen: return _u("(");
  282. case tkLBrack: return _u("[");
  283. case tkDot: return _u(".");
  284. default:
  285. return _u("unknown token");
  286. }
  287. }
  288. void Parser::Error(HRESULT hr, LPCWSTR stringOne, LPCWSTR stringTwo)
  289. {
  290. throw ParseExceptionObject(hr, stringOne, stringTwo);
  291. }
  292. void Parser::Error(HRESULT hr, ParseNodePtr pnode)
  293. {
  294. if (pnode && pnode->ichLim)
  295. {
  296. Error(hr, pnode->ichMin, pnode->ichLim);
  297. }
  298. else
  299. {
  300. Error(hr);
  301. }
  302. }
  303. void Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim)
  304. {
  305. this->GetScanner()->SetErrorPosition(ichMin, ichLim);
  306. Error(hr);
  307. }
  308. void Parser::IdentifierExpectedError(const Token& token)
  309. {
  310. Assert(token.tk != tkID);
  311. HRESULT hr;
  312. if (token.IsReservedWord())
  313. {
  314. if (token.IsKeyword())
  315. {
  316. hr = ERRKeywordNotId;
  317. }
  318. else
  319. {
  320. Assert(token.IsFutureReservedWord(true));
  321. if (token.IsFutureReservedWord(false))
  322. {
  323. // Future reserved word in strict and non-strict modes
  324. hr = ERRFutureReservedWordNotId;
  325. }
  326. else
  327. {
  328. // Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not
  329. // in strict mode.
  330. Assert(IsStrictMode());
  331. hr = ERRFutureReservedWordInStrictModeNotId;
  332. }
  333. }
  334. }
  335. else
  336. {
  337. hr = ERRnoIdent;
  338. }
  339. Error(hr);
  340. }
  341. HRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())
  342. {
  343. Assert(pszSrc);
  344. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  345. HRESULT hr;
  346. SmartFPUControl smartFpuControl;
  347. bool handled = false;
  348. BOOL fDeferSave = m_deferringAST;
  349. try
  350. {
  351. hr = NOERROR;
  352. m_length = encodedCharCount;
  353. m_originalLength = encodedCharCount;
  354. // make sure deferred parsing is turned off
  355. ULONG grfscr = fscrNil;
  356. // Give the scanner the source and get the first token
  357. this->GetScanner()->SetText(pszSrc, 0, encodedCharCount, 0, false, grfscr);
  358. this->GetScanner()->SetYieldIsKeywordRegion(isGenerator);
  359. this->GetScanner()->SetAwaitIsKeywordRegion(isAsync);
  360. this->GetScanner()->Scan();
  361. uint nestedCount = 0;
  362. m_pnestedCount = &nestedCount;
  363. ParseNodePtr pnodeScope = nullptr;
  364. m_ppnodeScope = &pnodeScope;
  365. m_ppnodeExprScope = nullptr;
  366. uint nextFunctionId = 0;
  367. m_nextFunctionId = &nextFunctionId;
  368. m_inDeferredNestedFunc = false;
  369. m_deferringAST = true;
  370. m_nextBlockId = 0;
  371. ParseNodeFnc *pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  372. pnodeFnc->SetIsGenerator(isGenerator);
  373. pnodeFnc->SetIsAsync(isAsync);
  374. m_ppnodeVar = &pnodeFnc->pnodeVars;
  375. m_currentNodeFunc = pnodeFnc;
  376. m_currentNodeDeferredFunc = NULL;
  377. m_sourceContextInfo = nullptr;
  378. AssertMsg(m_pstmtCur == NULL, "Statement stack should be empty when we start parse function body");
  379. ParseNodeBlock * block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);
  380. (this->*validateFunction)();
  381. FinishParseBlock(block);
  382. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  383. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  384. pnodeFnc->pnodeVars = nullptr;
  385. // there should be nothing after successful parsing for a given construct
  386. if (m_token.tk != tkEOF)
  387. Error(ERRsyntax);
  388. m_deferringAST = fDeferSave;
  389. }
  390. catch (ParseExceptionObject& e)
  391. {
  392. m_deferringAST = fDeferSave;
  393. hr = e.GetError();
  394. hr = pse->ProcessError(this->GetScanner(), hr, /* pnodeBase */ NULL, e.GetStringOne(), e.GetStringTwo());
  395. handled = true;
  396. }
  397. if (handled == false && nullptr != pse && FAILED(hr))
  398. {
  399. hr = pse->ProcessError(this->GetScanner(), hr, /* pnodeBase */ NULL);
  400. }
  401. return hr;
  402. }
  403. HRESULT Parser::ParseSourceInternal(
  404. __out ParseNodeProg ** parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,
  405. bool isUtf8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)
  406. {
  407. Assert(parseTree);
  408. Assert(pszSrc);
  409. if (this->IsBackgroundParser())
  410. {
  411. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  412. }
  413. else
  414. {
  415. PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);
  416. }
  417. #ifdef PROFILE_EXEC
  418. m_scriptContext->ProfileBegin(Js::ParsePhase);
  419. #endif
  420. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_START(m_scriptContext, 0));
  421. *parseTree = NULL;
  422. m_sourceLim = 0;
  423. m_grfscr = grfscr;
  424. m_sourceContextInfo = sourceContextInfo;
  425. ParseNodeProg * pnodeBase = NULL;
  426. HRESULT hr;
  427. SmartFPUControl smartFpuControl;
  428. bool handled = false;
  429. try
  430. {
  431. if ((grfscr & fscrIsModuleCode) != 0)
  432. {
  433. // Module source flag should not be enabled unless module is enabled
  434. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  435. // Module code is always strict mode code.
  436. this->m_fUseStrictMode = TRUE;
  437. }
  438. // parse the source
  439. pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, isUtf8, grfscr, lineNumber, nextFunctionId, pse);
  440. Assert(pnodeBase);
  441. // Record the actual number of words parsed.
  442. m_sourceLim = pnodeBase->ichLim - offsetInChars;
  443. // TODO: The assert can be false positive in some scenarios and chuckj to fix it later
  444. // Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, isUtf8 ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);
  445. #if DBG_DUMP
  446. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))
  447. {
  448. PrintPnodeWIndent(pnodeBase, 4);
  449. fflush(stdout);
  450. }
  451. #endif
  452. *parseTree = pnodeBase;
  453. hr = NOERROR;
  454. }
  455. catch (ParseExceptionObject& e)
  456. {
  457. hr = e.GetError();
  458. hr = pse->ProcessError(this->GetScanner(), hr, pnodeBase, e.GetStringOne(), e.GetStringTwo());
  459. handled = true;
  460. }
  461. catch (Js::AsmJsParseException&)
  462. {
  463. hr = JSERR_AsmJsCompileError;
  464. }
  465. if (handled == false && FAILED(hr))
  466. {
  467. hr = pse->ProcessError(this->GetScanner(), hr, pnodeBase);
  468. }
  469. #if ENABLE_BACKGROUND_PARSING
  470. if (this->m_hasParallelJob)
  471. {
  472. ///// Wait here for remaining jobs to finish. Then look for errors, do final const bindings.
  473. // pleath TODO: If there are remaining jobs, let the main thread help finish them.
  474. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  475. Assert(bgp);
  476. CompileScriptException se;
  477. this->WaitForBackgroundJobs(bgp, &se);
  478. BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();
  479. if (failedItem)
  480. {
  481. CompileScriptException *bgPse = failedItem->GetPSE();
  482. Assert(bgPse);
  483. *pse = *bgPse;
  484. hr = failedItem->GetHR();
  485. bgp->SetFailedBackgroundParseItem(nullptr);
  486. }
  487. if (this->fastScannedRegExpNodes != nullptr)
  488. {
  489. this->FinishBackgroundRegExpNodes();
  490. }
  491. for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())
  492. {
  493. Parser *parser = item->GetParser();
  494. parser->FinishBackgroundPidRefs(item, this != parser);
  495. }
  496. }
  497. #endif
  498. // done with the scanner
  499. this->GetScanner()->Clear();
  500. #ifdef PROFILE_EXEC
  501. m_scriptContext->ProfileEnd(Js::ParsePhase);
  502. #endif
  503. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));
  504. return hr;
  505. }
  506. #if ENABLE_BACKGROUND_PARSING
  507. void Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)
  508. {
  509. // The scan of the script is done, but there may be unfinished background jobs in the queue.
  510. // Enlist the main thread to help with those.
  511. BackgroundParseItem *item;
  512. if (!*bgp->GetPendingBackgroundItemsPtr())
  513. {
  514. // We're done.
  515. return;
  516. }
  517. // Save parser state, since we'll need to restore it in order to bind references correctly later.
  518. this->m_isInBackground = true;
  519. this->SetCurrBackgroundParseItem(nullptr);
  520. uint blockIdSave = this->m_nextBlockId;
  521. uint functionIdSave = *this->m_nextFunctionId;
  522. StmtNest *pstmtSave = this->m_pstmtCur;
  523. if (!bgp->Processor()->ProcessesInBackground())
  524. {
  525. // No background thread. Just walk the jobs with no locking and process them.
  526. for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())
  527. {
  528. bgp->Processor()->RemoveJob(item);
  529. bool succeeded = bgp->Process(item, this, pse);
  530. bgp->JobProcessed(item, succeeded);
  531. }
  532. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  533. }
  534. else
  535. {
  536. // Background threads. We need to have the critical section in order to:
  537. // - Check for unprocessed jobs;
  538. // - Remove jobs from the processor queue;
  539. // - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).
  540. CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();
  541. pcs->Enter();
  542. for (;;)
  543. {
  544. // Grab a job (in lock)
  545. item = bgp->GetNextUnprocessedItem();
  546. if (item == nullptr)
  547. {
  548. break;
  549. }
  550. bgp->Processor()->RemoveJob(item);
  551. pcs->Leave();
  552. // Process job (if there is one) (outside lock)
  553. bool succeeded = bgp->Process(item, this, pse);
  554. pcs->Enter();
  555. bgp->JobProcessed(item, succeeded);
  556. }
  557. pcs->Leave();
  558. // Wait for the background threads to finish jobs they're already processing (if any).
  559. // TODO: Replace with a proper semaphore.
  560. while (*bgp->GetPendingBackgroundItemsPtr());
  561. }
  562. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  563. // Restore parser state.
  564. this->m_pstmtCur = pstmtSave;
  565. this->m_isInBackground = false;
  566. this->m_nextBlockId = blockIdSave;
  567. *this->m_nextFunctionId = functionIdSave;
  568. }
  569. void Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)
  570. {
  571. for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)
  572. {
  573. if (isOtherParser)
  574. {
  575. this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());
  576. }
  577. else
  578. {
  579. this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());
  580. }
  581. }
  582. }
  583. void Parser::FinishBackgroundRegExpNodes()
  584. {
  585. // We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,
  586. // and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.
  587. // We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the
  588. // background nodes.
  589. // There may be UI thread nodes for which there are no background thread equivalents, because the UI thread
  590. // has to assume that the background thread won't defer anything.
  591. // Note that because these lists (and the list of background jobs) are SList's built by prepending, they are
  592. // all in reverse lexical order.
  593. Assert(!this->IsBackgroundParser());
  594. Assert(this->fastScannedRegExpNodes);
  595. Assert(this->backgroundParseItems != nullptr);
  596. BackgroundParseItem *currBackgroundItem;
  597. #if DBG
  598. for (currBackgroundItem = this->backgroundParseItems;
  599. currBackgroundItem;
  600. currBackgroundItem = currBackgroundItem->GetNext())
  601. {
  602. if (currBackgroundItem->RegExpNodeList())
  603. {
  604. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  605. {
  606. Assert(pnode->AsParseNodeRegExp()->regexPattern == nullptr);
  607. }
  608. NEXT_DLIST_ENTRY;
  609. }
  610. }
  611. #endif
  612. // Hook up the patterns allocated on the main thread to the nodes created on the background thread.
  613. // Walk the list of foreground nodes, advancing through the work items and looking up each item.
  614. // Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground
  615. // node will have a matching background node. Doesn't matter for correctness.
  616. // (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's
  617. // list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how
  618. // to start the inner loop from a known internal node within the list if that turns out to be important.)
  619. currBackgroundItem = this->backgroundParseItems;
  620. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)
  621. {
  622. Assert(pnodeFgnd->nop == knopRegExp);
  623. Assert(pnodeFgnd->AsParseNodeRegExp()->regexPattern != nullptr);
  624. bool quit = false;
  625. while (!quit)
  626. {
  627. // Find the next work item with a RegEx in it.
  628. while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)
  629. {
  630. currBackgroundItem = currBackgroundItem->GetNext();
  631. }
  632. if (!currBackgroundItem)
  633. {
  634. break;
  635. }
  636. // Walk the RegExps in the work item.
  637. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())
  638. {
  639. Assert(pnodeBgnd->nop == knopRegExp);
  640. if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)
  641. {
  642. // Either we found a match, or the next background node is past the foreground node.
  643. // In any case, we can stop searching.
  644. if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)
  645. {
  646. Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);
  647. pnodeBgnd->AsParseNodeRegExp()->regexPattern = pnodeFgnd->AsParseNodeRegExp()->regexPattern;
  648. }
  649. quit = true;
  650. break;
  651. }
  652. }
  653. NEXT_DLIST_ENTRY;
  654. if (!quit)
  655. {
  656. // Need to advance to the next work item.
  657. currBackgroundItem = currBackgroundItem->GetNext();
  658. }
  659. }
  660. }
  661. NEXT_DLIST_ENTRY;
  662. #if DBG
  663. for (currBackgroundItem = this->backgroundParseItems;
  664. currBackgroundItem;
  665. currBackgroundItem = currBackgroundItem->GetNext())
  666. {
  667. if (currBackgroundItem->RegExpNodeList())
  668. {
  669. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  670. {
  671. Assert(pnode->AsParseNodeRegExp()->regexPattern != nullptr);
  672. }
  673. NEXT_DLIST_ENTRY;
  674. }
  675. }
  676. #endif
  677. }
  678. #endif
  679. LabelId* Parser::CreateLabelId(IdentPtr pid)
  680. {
  681. LabelId* pLabelId;
  682. pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));
  683. if (NULL == pLabelId)
  684. Error(ERRnoMemory);
  685. pLabelId->pid = pid;
  686. pLabelId->next = NULL;
  687. return pLabelId;
  688. }
  689. /*****************************************************************************
  690. The following set of routines allocate parse tree nodes of various kinds.
  691. They catch an exception on out of memory.
  692. *****************************************************************************/
  693. void
  694. Parser::AddAstSize(int size)
  695. {
  696. Assert(!this->m_deferringAST);
  697. Assert(m_pCurrentAstSize != NULL);
  698. *m_pCurrentAstSize += size;
  699. }
  700. void
  701. Parser::AddAstSizeAllowDefer(int size)
  702. {
  703. if (!this->m_deferringAST)
  704. {
  705. AddAstSize(size);
  706. }
  707. }
  708. // StaticCreate
  709. ParseNodeVar * Parser::StaticCreateTempNode(ParseNode* initExpr, ArenaAllocator * alloc)
  710. {
  711. ParseNodeVar * pnode = Anew(alloc, ParseNodeVar, knopTemp, 0, 0, nullptr);
  712. pnode->pnodeInit = initExpr;
  713. return pnode;
  714. }
  715. ParseNodeUni * Parser::StaticCreateTempRef(ParseNode* tempNode, ArenaAllocator * alloc)
  716. {
  717. return Anew(alloc, ParseNodeUni, knopTempRef, 0, 0, tempNode);
  718. }
  719. // Create Node with limit
  720. template <OpCode nop>
  721. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  722. {
  723. Assert(!this->m_deferringAST);
  724. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  725. AddAstSize(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  726. return pnode;
  727. }
  728. template <OpCode nop>
  729. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateAllowDeferNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  730. {
  731. CompileAssert(OpCodeTrait<nop>::AllowDefer);
  732. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  733. AddAstSizeAllowDefer(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  734. return pnode;
  735. }
  736. #if DBG
  737. static const int g_mpnopcbNode[] =
  738. {
  739. #define PTNODE(nop,sn,pc,nk,ok,json) sizeof(ParseNode##nk),
  740. #include "ptlist.h"
  741. };
  742. void VerifyNodeSize(OpCode nop, int size)
  743. {
  744. Assert(nop >= 0 && nop < knopLim);
  745. __analysis_assume(nop < knopLim);
  746. Assert(g_mpnopcbNode[nop] == size);
  747. }
  748. #endif
  749. // Create ParseNodeUni
  750. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)
  751. {
  752. charcount_t ichMin;
  753. charcount_t ichLim;
  754. if (nullptr == pnode1)
  755. {
  756. // no ops
  757. ichMin = this->GetScanner()->IchMinTok();
  758. ichLim = this->GetScanner()->IchLimTok();
  759. }
  760. else
  761. {
  762. // 1 op
  763. ichMin = pnode1->ichMin;
  764. ichLim = pnode1->ichLim;
  765. this->CheckArguments(pnode1);
  766. }
  767. return CreateUniNode(nop, pnode1, ichMin, ichLim);
  768. }
  769. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin, charcount_t ichLim)
  770. {
  771. Assert(!this->m_deferringAST);
  772. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeUni)));
  773. ParseNodeUni * pnode = Anew(&m_nodeAllocator, ParseNodeUni, nop, ichMin, ichLim, pnode1);
  774. AddAstSize(sizeof(ParseNodeUni));
  775. return pnode;
  776. }
  777. // Create ParseNodeBin
  778. ParseNodeBin * Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim)
  779. {
  780. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeBin)));
  781. return Anew(alloc, ParseNodeBin, nop, ichMin, ichLim, pnode1, pnode2);
  782. }
  783. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  784. {
  785. Assert(!this->m_deferringAST);
  786. charcount_t ichMin;
  787. charcount_t ichLim;
  788. if (nullptr == pnode1)
  789. {
  790. // no ops
  791. Assert(nullptr == pnode2);
  792. ichMin = this->GetScanner()->IchMinTok();
  793. ichLim = this->GetScanner()->IchLimTok();
  794. }
  795. else
  796. {
  797. if (nullptr == pnode2)
  798. {
  799. // 1 op
  800. ichMin = pnode1->ichMin;
  801. ichLim = pnode1->ichLim;
  802. }
  803. else
  804. {
  805. // 2 ops
  806. ichMin = pnode1->ichMin;
  807. ichLim = pnode2->ichLim;
  808. if (nop != knopDot && nop != knopIndex)
  809. {
  810. this->CheckArguments(pnode2);
  811. }
  812. }
  813. if (nop != knopDot && nop != knopIndex)
  814. {
  815. this->CheckArguments(pnode1);
  816. }
  817. }
  818. return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
  819. }
  820. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
  821. ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  822. {
  823. Assert(!this->m_deferringAST);
  824. ParseNodeBin * pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator, ichMin, ichLim);
  825. AddAstSize(sizeof(ParseNodeBin));
  826. return pnode;
  827. }
  828. // Create ParseNodeTri
  829. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  830. ParseNodePtr pnode2, ParseNodePtr pnode3)
  831. {
  832. charcount_t ichMin;
  833. charcount_t ichLim;
  834. if (nullptr == pnode1)
  835. {
  836. // no ops
  837. Assert(nullptr == pnode2);
  838. Assert(nullptr == pnode3);
  839. ichMin = this->GetScanner()->IchMinTok();
  840. ichLim = this->GetScanner()->IchLimTok();
  841. }
  842. else if (nullptr == pnode2)
  843. {
  844. // 1 op
  845. Assert(nullptr == pnode3);
  846. ichMin = pnode1->ichMin;
  847. ichLim = pnode1->ichLim;
  848. }
  849. else if (nullptr == pnode3)
  850. {
  851. // 2 op
  852. ichMin = pnode1->ichMin;
  853. ichLim = pnode2->ichLim;
  854. }
  855. else
  856. {
  857. // 3 ops
  858. ichMin = pnode1->ichMin;
  859. ichLim = pnode3->ichLim;
  860. }
  861. return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);
  862. }
  863. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  864. ParseNodePtr pnode2, ParseNodePtr pnode3,
  865. charcount_t ichMin, charcount_t ichLim)
  866. {
  867. Assert(!this->m_deferringAST);
  868. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeTri)));
  869. ParseNodeTri * pnode = Anew(&m_nodeAllocator, ParseNodeTri, nop, ichMin, ichLim);
  870. AddAstSize(sizeof(ParseNodeTri));
  871. pnode->pnode1 = pnode1;
  872. pnode->pnode2 = pnode2;
  873. pnode->pnode3 = pnode3;
  874. return pnode;
  875. }
  876. // Create ParseNodeBlock
  877. ParseNodeBlock *
  878. Parser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim, int blockId, PnodeBlockType blockType)
  879. {
  880. return Anew(alloc, ParseNodeBlock, ichMin, ichLim, blockId, blockType);
  881. }
  882. ParseNodeBlock * Parser::CreateBlockNode(PnodeBlockType blockType)
  883. {
  884. return CreateBlockNode(this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), blockType);
  885. }
  886. ParseNodeBlock * Parser::CreateBlockNode(charcount_t ichMin, charcount_t ichLim, PnodeBlockType blockType)
  887. {
  888. Assert(OpCodeTrait<knopBlock>::AllowDefer);
  889. ParseNodeBlock * pnode = StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);
  890. AddAstSizeAllowDefer(sizeof(ParseNodeBlock));
  891. return pnode;
  892. }
  893. // Create ParseNodeVar
  894. ParseNodeVar * Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  895. {
  896. Assert(nop == knopVarDecl || nop == knopLetDecl || nop == knopConstDecl);
  897. ParseNodeVar * pnode = Anew(&m_nodeAllocator, ParseNodeVar, nop, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  898. if (symbolType != STUnknown)
  899. {
  900. pnode->sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);
  901. }
  902. return pnode;
  903. }
  904. ParseNodeInt * Parser::CreateIntNode(int32 lw)
  905. {
  906. Assert(!this->m_deferringAST);
  907. ParseNodeInt * pnode = Anew(&m_nodeAllocator, ParseNodeInt, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), lw);
  908. AddAstSize(sizeof(ParseNodeInt));
  909. return pnode;
  910. }
  911. ParseNodeStr * Parser::CreateStrNode(IdentPtr pid)
  912. {
  913. Assert(!this->m_deferringAST);
  914. ParseNodeStr * pnode = Anew(&m_nodeAllocator, ParseNodeStr, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  915. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  916. AddAstSize(sizeof(ParseNodeStr));
  917. return pnode;
  918. }
  919. ParseNodeName * Parser::CreateNameNode(IdentPtr pid)
  920. {
  921. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  922. AddAstSizeAllowDefer(sizeof(ParseNodeName));
  923. return pnode;
  924. }
  925. ParseNodeName * Parser::CreateNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  926. {
  927. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, ichMin, ichLim, pid);
  928. pnode->SetSymRef(ref);
  929. AddAstSize(sizeof(ParseNodeName));
  930. return pnode;
  931. }
  932. ParseNodeSpecialName * Parser::CreateSpecialNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  933. {
  934. Assert(!this->m_deferringAST);
  935. ParseNodeSpecialName * pnode = Anew(&m_nodeAllocator, ParseNodeSpecialName, ichMin, ichLim, pid);
  936. pnode->SetSymRef(ref);
  937. if (pid == wellKnownPropertyPids._this)
  938. {
  939. pnode->isThis = true;
  940. }
  941. else if (pid == wellKnownPropertyPids._super || pid == wellKnownPropertyPids._superConstructor)
  942. {
  943. pnode->isSuper = true;
  944. }
  945. AddAstSize(sizeof(ParseNodeSpecialName));
  946. return pnode;
  947. }
  948. ParseNodeSuperReference * Parser::CreateSuperReferenceNode(OpCode nop, ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  949. {
  950. Assert(!this->m_deferringAST);
  951. Assert(pnode1 && pnode1->isSuper);
  952. Assert(pnode2 != nullptr);
  953. Assert(nop == knopDot || nop == knopIndex);
  954. ParseNodeSuperReference * pnode = Anew(&m_nodeAllocator, ParseNodeSuperReference, nop, pnode1->ichMin, pnode2->ichLim, pnode1, pnode2);
  955. AddAstSize(sizeof(ParseNodeSuperReference));
  956. return pnode;
  957. }
  958. ParseNodeProg * Parser::CreateProgNode(bool isModuleSource, ULONG lineNumber)
  959. {
  960. ParseNodeProg * pnodeProg;
  961. if (isModuleSource)
  962. {
  963. pnodeProg = CreateNodeForOpT<knopModule>();
  964. // knopModule is not actually handled anywhere since we would need to handle it everywhere we could
  965. // have knopProg and it would be treated exactly the same except for import/export statements.
  966. // We are only using it as a way to get the correct size for PnModule.
  967. // Consider: Should we add a flag to PnProg which is false but set to true in PnModule?
  968. // If we do, it can't be a virtual method since the parse nodes are all in a union.
  969. pnodeProg->nop = knopProg;
  970. }
  971. else
  972. {
  973. pnodeProg = CreateNodeForOpT<knopProg>();
  974. }
  975. pnodeProg->cbMin = this->GetScanner()->IecpMinTok();
  976. pnodeProg->cbStringMin = pnodeProg->cbMin;
  977. pnodeProg->lineNumber = lineNumber;
  978. pnodeProg->homeObjLocation = Js::Constants::NoRegister;
  979. pnodeProg->superRestrictionState = SuperRestrictionState::Disallowed;
  980. return pnodeProg;
  981. }
  982. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  983. {
  984. charcount_t ichMin;
  985. charcount_t ichLim;
  986. if (nullptr == pnode1)
  987. {
  988. Assert(nullptr == pnode2);
  989. ichMin = this->GetScanner()->IchMinTok();
  990. ichLim = this->GetScanner()->IchLimTok();
  991. }
  992. else
  993. {
  994. ichMin = pnode1->ichMin;
  995. ichLim = pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim;
  996. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  997. {
  998. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  999. }
  1000. }
  1001. return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);
  1002. }
  1003. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  1004. {
  1005. Assert(!this->m_deferringAST);
  1006. // Classes, derived from ParseNodeCall, can be created here as well,
  1007. // as long as their size matches kcbPnCall (that is, they don't add
  1008. // any data members of their own).
  1009. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeCall)));
  1010. ParseNodeCall* pnode = Anew(&m_nodeAllocator, ParseNodeCall, nop, ichMin, ichLim, pnode1, pnode2);
  1011. AddAstSize(sizeof(ParseNodeCall));
  1012. return pnode;
  1013. }
  1014. ParseNodeSuperCall * Parser::CreateSuperCallNode(ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  1015. {
  1016. Assert(!this->m_deferringAST);
  1017. Assert(pnode1 && pnode1->isSuper);
  1018. ParseNodeSuperCall* pnode = Anew(&m_nodeAllocator, ParseNodeSuperCall, knopCall, pnode1->ichMin, pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim, pnode1, pnode2);
  1019. AddAstSize(sizeof(ParseNodeSuperCall));
  1020. return pnode;
  1021. }
  1022. ParseNodeParamPattern * Parser::CreateParamPatternNode(ParseNode * pnode1)
  1023. {
  1024. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(pnode1->ichMin, pnode1->ichLim);
  1025. paramPatternNode->pnode1 = pnode1;
  1026. paramPatternNode->pnodeNext = nullptr;
  1027. paramPatternNode->location = Js::Constants::NoRegister;
  1028. return paramPatternNode;
  1029. }
  1030. ParseNodeParamPattern * Parser::CreateDummyParamPatternNode(charcount_t ichMin)
  1031. {
  1032. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(ichMin);
  1033. paramPatternNode->pnode1 = nullptr;
  1034. paramPatternNode->pnodeNext = nullptr;
  1035. paramPatternNode->location = Js::Constants::NoRegister;
  1036. return paramPatternNode;
  1037. }
  1038. ParseNodeObjLit * Parser::CreateObjectPatternNode(ParseNodePtr pnodeMemberList, charcount_t ichMin, charcount_t ichLim, bool convertToPattern) {
  1039. // Count the number of non-rest members in the object
  1040. uint32 staticCount = 0;
  1041. uint32 computedCount = 0;
  1042. bool hasRest = false;
  1043. ParseNodePtr pnodeMemberNodeList = convertToPattern ? nullptr : pnodeMemberList;
  1044. if (pnodeMemberList != nullptr)
  1045. {
  1046. Assert(pnodeMemberList->nop == knopList ||
  1047. (!convertToPattern && pnodeMemberList->nop == knopObjectPatternMember) ||
  1048. convertToPattern ||
  1049. pnodeMemberList->nop == knopEllipsis);
  1050. ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {
  1051. ParseNodePtr memberNode = convertToPattern ? ConvertMemberToMemberPattern(item) : item;
  1052. if (convertToPattern)
  1053. {
  1054. AppendToList(&pnodeMemberNodeList, memberNode);
  1055. }
  1056. if (memberNode->nop != knopEllipsis)
  1057. {
  1058. ParseNodePtr nameNode = memberNode->AsParseNodeBin()->pnode1;
  1059. Assert(nameNode->nop == knopComputedName || nameNode->nop == knopStr);
  1060. if (nameNode->nop == knopComputedName)
  1061. {
  1062. computedCount++;
  1063. }
  1064. else
  1065. {
  1066. staticCount++;
  1067. }
  1068. }
  1069. else
  1070. {
  1071. hasRest = true;
  1072. }
  1073. });
  1074. }
  1075. ParseNodeObjLit * objectPatternNode = CreateNodeForOpT<knopObjectPattern>(ichMin, ichLim);
  1076. objectPatternNode->pnode1 = pnodeMemberNodeList;
  1077. objectPatternNode->computedCount = computedCount;
  1078. objectPatternNode->staticCount = staticCount;
  1079. objectPatternNode->hasRest = hasRest;
  1080. return objectPatternNode;
  1081. }
  1082. Symbol* Parser::AddDeclForPid(ParseNodeVar * pnodeVar, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  1083. {
  1084. Assert(pnodeVar->IsVarLetOrConst());
  1085. PidRefStack *refForUse = nullptr, *refForDecl = nullptr;
  1086. BlockInfoStack *blockInfo;
  1087. bool fBlockScope = false;
  1088. if (pnodeVar->nop != knopVarDecl || symbolType == STFunction)
  1089. {
  1090. Assert(m_pstmtCur);
  1091. if (m_pstmtCur->GetNop() != knopBlock)
  1092. {
  1093. // Let/const declared in a bare statement context.
  1094. Error(ERRDeclOutOfStmt);
  1095. }
  1096. if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->GetNop() == knopSwitch)
  1097. {
  1098. // Let/const declared inside a switch block (requiring conservative use-before-decl check).
  1099. pnodeVar->isSwitchStmtDecl = true;
  1100. }
  1101. fBlockScope = pnodeVar->nop != knopVarDecl ||
  1102. (
  1103. !GetCurrentBlockInfo()->pnodeBlock->scope ||
  1104. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock
  1105. );
  1106. }
  1107. if (fBlockScope)
  1108. {
  1109. blockInfo = GetCurrentBlockInfo();
  1110. }
  1111. else
  1112. {
  1113. blockInfo = GetCurrentFunctionBlockInfo();
  1114. }
  1115. refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->blockId, GetCurrentFunctionNode()->functionId);
  1116. if (refForDecl == nullptr)
  1117. {
  1118. Error(ERRnoMemory);
  1119. }
  1120. if (refForDecl->funcId != GetCurrentFunctionNode()->functionId)
  1121. {
  1122. // Fix up the function id, which is incorrect if we're reparsing lambda parameters
  1123. Assert(this->m_reparsingLambdaParams);
  1124. refForDecl->funcId = GetCurrentFunctionNode()->functionId;
  1125. }
  1126. if (blockInfo == GetCurrentBlockInfo())
  1127. {
  1128. refForUse = refForDecl;
  1129. }
  1130. else
  1131. {
  1132. refForUse = this->PushPidRef(pid);
  1133. }
  1134. pnodeVar->symRef = refForUse->GetSymRef();
  1135. Symbol *sym = refForDecl->GetSym();
  1136. if (sym != nullptr)
  1137. {
  1138. // Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.
  1139. switch (pnodeVar->nop)
  1140. {
  1141. case knopLetDecl:
  1142. case knopConstDecl:
  1143. if (!sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar && !sym->IsArguments())
  1144. {
  1145. // If the built-in arguments is shadowed then don't throw
  1146. Assert(errorOnRedecl);
  1147. // Redeclaration error.
  1148. Error(ERRRedeclaration);
  1149. }
  1150. else
  1151. {
  1152. // (New) let/const hides the (old) var
  1153. sym->SetSymbolType(symbolType);
  1154. sym->SetDecl(pnodeVar);
  1155. }
  1156. break;
  1157. case knopVarDecl:
  1158. if (m_currentScope->GetScopeType() == ScopeType_Parameter && !sym->IsArguments())
  1159. {
  1160. // If this is a parameter list, mark the scope to indicate that it has duplicate definition unless it is shadowing the default arguments symbol.
  1161. // If later this turns out to be a non-simple param list (like function f(a, a, c = 1) {}) then it is a SyntaxError to have duplicate formals.
  1162. m_currentScope->SetHasDuplicateFormals();
  1163. }
  1164. if (sym->GetDecl() == nullptr)
  1165. {
  1166. sym->SetDecl(pnodeVar);
  1167. break;
  1168. }
  1169. switch (sym->GetDecl()->nop)
  1170. {
  1171. case knopLetDecl:
  1172. case knopConstDecl:
  1173. // Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.
  1174. if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))
  1175. {
  1176. Error(ERRRedeclaration);
  1177. }
  1178. // If !errorOnRedecl, (old) let/const hides the (new) var, so do nothing.
  1179. break;
  1180. case knopVarDecl:
  1181. // Legal redeclaration. Who wins?
  1182. if (errorOnRedecl || sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsArguments())
  1183. {
  1184. if (symbolType == STFormal ||
  1185. (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||
  1186. sym->GetSymbolType() == STVariable)
  1187. {
  1188. // New decl wins.
  1189. sym->SetSymbolType(symbolType);
  1190. sym->SetDecl(pnodeVar);
  1191. }
  1192. }
  1193. break;
  1194. }
  1195. break;
  1196. }
  1197. }
  1198. else
  1199. {
  1200. Scope *scope = blockInfo->pnodeBlock->scope;
  1201. if (scope == nullptr)
  1202. {
  1203. Assert(blockInfo->pnodeBlock->blockType == PnodeBlockType::Regular);
  1204. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);
  1205. if (this->IsCurBlockInLoop())
  1206. {
  1207. scope->SetIsBlockInLoop();
  1208. }
  1209. blockInfo->pnodeBlock->scope = scope;
  1210. PushScope(scope);
  1211. }
  1212. ParseNodeFnc * pnodeFnc = GetCurrentFunctionNode();
  1213. if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)
  1214. {
  1215. Assert(fBlockScope);
  1216. Assert(scope->GetEnclosingScope() == m_currentNodeProg->scope);
  1217. // Check for same-named decl in Global scope.
  1218. CheckRedeclarationErrorForBlockId(pid, 0);
  1219. }
  1220. else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&
  1221. !(m_functionBody && m_functionBody->GetScopeInfo()))
  1222. {
  1223. // Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary
  1224. // if we're compiling a deferred nested function and the global scope was restored from cached info,
  1225. // because in that case we don't need a GlobalEvalScope.
  1226. Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);
  1227. CheckRedeclarationErrorForBlockId(pid, 1);
  1228. }
  1229. else if (!pnodeFnc->IsBodyAndParamScopeMerged()
  1230. && scope->GetScopeType() == ScopeType_FunctionBody
  1231. && (pnodeVar->nop == knopLetDecl || pnodeVar->nop == knopConstDecl))
  1232. {
  1233. // In case of split scope function when we add a new let or const declaration to the body
  1234. // we have to check whether the param scope already has the same symbol defined.
  1235. CheckRedeclarationErrorForBlockId(pid, pnodeFnc->pnodeScopes->blockId);
  1236. }
  1237. if (!sym)
  1238. {
  1239. const char16 *name = reinterpret_cast<const char16*>(pid->Psz());
  1240. int nameLength = pid->Cch();
  1241. SymbolName const symName(name, nameLength);
  1242. Assert(!scope->FindLocalSymbol(symName));
  1243. sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeVar, symbolType);
  1244. scope->AddNewSymbol(sym);
  1245. sym->SetPid(pid);
  1246. }
  1247. refForDecl->SetSym(sym);
  1248. }
  1249. return sym;
  1250. }
  1251. void Parser::CheckRedeclarationErrorForBlockId(IdentPtr pid, int blockId)
  1252. {
  1253. // If the ref stack entry for the blockId contains a sym then throw redeclaration error
  1254. PidRefStack *pidRefOld = pid->GetPidRefForScopeId(blockId);
  1255. if (pidRefOld && pidRefOld->GetSym() && !pidRefOld->GetSym()->IsArguments())
  1256. {
  1257. Error(ERRRedeclaration);
  1258. }
  1259. }
  1260. bool Parser::IsCurBlockInLoop() const
  1261. {
  1262. for (StmtNest *stmt = this->m_pstmtCur; stmt != nullptr; stmt = stmt->pstmtOuter)
  1263. {
  1264. OpCode nop = stmt->GetNop();
  1265. if (ParseNode::Grfnop(nop) & fnopContinue)
  1266. {
  1267. return true;
  1268. }
  1269. if (nop == knopFncDecl)
  1270. {
  1271. return false;
  1272. }
  1273. }
  1274. return false;
  1275. }
  1276. void Parser::RestorePidRefForSym(Symbol *sym)
  1277. {
  1278. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());
  1279. Assert(pid);
  1280. sym->SetPid(pid);
  1281. PidRefStack *ref = this->PushPidRef(pid);
  1282. ref->SetSym(sym);
  1283. }
  1284. void Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)
  1285. {
  1286. if (IsStrictMode())
  1287. {
  1288. // in strict mode, variable named 'eval' cannot be created
  1289. if (pid == wellKnownPropertyPids.eval)
  1290. {
  1291. Error(ERREvalUsage);
  1292. }
  1293. else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)
  1294. {
  1295. Error(ERRArgsUsage);
  1296. }
  1297. }
  1298. }
  1299. // CreateVarDecl needs m_ppnodeVar to be pointing to the right function.
  1300. // Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.
  1301. // This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.
  1302. // This prevents accidentally adding var declarations to the last parsed function.
  1303. ParseNodeVar * Parser::AddVarDeclNode(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1304. {
  1305. AnalysisAssert(pnodeFnc);
  1306. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  1307. m_ppnodeVar = &pnodeFnc->pnodeVars;
  1308. while (*m_ppnodeVar != nullptr)
  1309. {
  1310. m_ppnodeVar = &(*m_ppnodeVar)->AsParseNodeVar()->pnodeNext;
  1311. }
  1312. ParseNodeVar * pnode = CreateVarDeclNode(pid, STUnknown, false, 0, /* checkReDecl = */ false);
  1313. m_ppnodeVar = ppnodeVarSave;
  1314. return pnode;
  1315. }
  1316. ParseNodeVar * Parser::CreateModuleImportDeclNode(IdentPtr localName)
  1317. {
  1318. ParseNodeVar * declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);
  1319. Symbol* sym = declNode->sym;
  1320. sym->SetIsModuleExportStorage(true);
  1321. sym->SetIsModuleImport(true);
  1322. return declNode;
  1323. }
  1324. ParseNodeVar * Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)
  1325. {
  1326. ParseNodeVar * pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);
  1327. // Append the variable to the end of the current variable list.
  1328. Assert(m_ppnodeVar);
  1329. pnode->pnodeNext = *m_ppnodeVar;
  1330. *m_ppnodeVar = pnode;
  1331. if (nullptr != pid)
  1332. {
  1333. // this is not a temp - make sure temps go after this node
  1334. Assert(pid);
  1335. m_ppnodeVar = &pnode->pnodeNext;
  1336. CheckPidIsValid(pid, autoArgumentsObject);
  1337. }
  1338. return pnode;
  1339. }
  1340. ParseNodeVar * Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)
  1341. {
  1342. Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);
  1343. ParseNodeVar * pnode = CreateDeclNode(nodeType, pid, STVariable, true);
  1344. if (nullptr != pid)
  1345. {
  1346. Assert(pid);
  1347. AddVarDeclToBlock(pnode);
  1348. CheckPidIsValid(pid);
  1349. }
  1350. return pnode;
  1351. }
  1352. void Parser::AddVarDeclToBlock(ParseNodeVar *pnode)
  1353. {
  1354. Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);
  1355. // Maintain a combined list of let and const declarations to keep
  1356. // track of declaration order.
  1357. Assert(m_currentBlockInfo->m_ppnodeLex);
  1358. *m_currentBlockInfo->m_ppnodeLex = pnode;
  1359. m_currentBlockInfo->m_ppnodeLex = &pnode->pnodeNext;
  1360. pnode->pnodeNext = nullptr;
  1361. }
  1362. void Parser::SetCurrentStatement(StmtNest *stmt)
  1363. {
  1364. m_pstmtCur = stmt;
  1365. }
  1366. template<bool buildAST>
  1367. ParseNodeBlock * Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)
  1368. {
  1369. Scope *scope = nullptr;
  1370. // Block scopes are not created lazily in the case where we're repopulating a persisted scope.
  1371. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);
  1372. PushScope(scope);
  1373. return StartParseBlockHelper<buildAST>(blockType, scope, nullptr);
  1374. }
  1375. template<bool buildAST>
  1376. ParseNodeBlock * Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, LabelId* pLabelId)
  1377. {
  1378. Scope *scope = nullptr;
  1379. // Block scopes are created lazily when we discover block-scoped content.
  1380. if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)
  1381. {
  1382. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);
  1383. PushScope(scope);
  1384. }
  1385. return StartParseBlockHelper<buildAST>(blockType, scope, pLabelId);
  1386. }
  1387. template<bool buildAST>
  1388. ParseNodeBlock * Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, LabelId* pLabelId)
  1389. {
  1390. ParseNodeBlock * pnodeBlock = CreateBlockNode(blockType);
  1391. pnodeBlock->scope = scope;
  1392. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);
  1393. PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pLabelId);
  1394. return pnodeBlock;
  1395. }
  1396. void Parser::PushScope(Scope *scope)
  1397. {
  1398. Assert(scope);
  1399. scope->SetEnclosingScope(m_currentScope);
  1400. m_currentScope = scope;
  1401. }
  1402. void Parser::PopScope(Scope *scope)
  1403. {
  1404. Assert(scope == m_currentScope);
  1405. m_currentScope = scope->GetEnclosingScope();
  1406. scope->SetEnclosingScope(nullptr);
  1407. }
  1408. void Parser::PushFuncBlockScope(ParseNodeBlock * pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)
  1409. {
  1410. // Maintain the scope tree.
  1411. pnodeBlock->pnodeScopes = nullptr;
  1412. pnodeBlock->pnodeNext = nullptr;
  1413. // Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).
  1414. // Save the current block's "next" pointer as the new endpoint of that list.
  1415. if (m_ppnodeExprScope)
  1416. {
  1417. *ppnodeScopeSave = m_ppnodeScope;
  1418. Assert(*m_ppnodeExprScope == nullptr);
  1419. *m_ppnodeExprScope = pnodeBlock;
  1420. *ppnodeExprScopeSave = &pnodeBlock->pnodeNext;
  1421. }
  1422. else
  1423. {
  1424. Assert(m_ppnodeScope);
  1425. Assert(*m_ppnodeScope == nullptr);
  1426. *m_ppnodeScope = pnodeBlock;
  1427. *ppnodeScopeSave = &pnodeBlock->pnodeNext;
  1428. *ppnodeExprScopeSave = m_ppnodeExprScope;
  1429. }
  1430. // Advance the global scope list pointer to the new block's child list.
  1431. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  1432. // Set m_ppnodeExprScope to NULL to make that list inactive.
  1433. m_ppnodeExprScope = nullptr;
  1434. }
  1435. void Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)
  1436. {
  1437. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  1438. m_ppnodeExprScope = ppnodeExprScopeSave;
  1439. Assert(m_ppnodeScope);
  1440. Assert(nullptr == *m_ppnodeScope);
  1441. m_ppnodeScope = ppnodeScopeSave;
  1442. }
  1443. template<bool buildAST>
  1444. ParseNodeBlock * Parser::ParseBlock(LabelId* pLabelId)
  1445. {
  1446. ParseNodeBlock * pnodeBlock = nullptr;
  1447. ParseNodePtr *ppnodeScopeSave = nullptr;
  1448. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  1449. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pLabelId);
  1450. BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1451. if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr
  1452. && outerBlockInfo->pnodeBlock->scope != nullptr
  1453. && outerBlockInfo->pnodeBlock->scope->GetScopeType() == ScopeType_CatchParamPattern)
  1454. {
  1455. // If we are parsing the catch block then destructured params can have let declarations. Let's add them to the new block.
  1456. for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1457. {
  1458. PidRefStack* ref = PushPidRef(pnode->AsParseNodeVar()->sym->GetPid());
  1459. ref->SetSym(pnode->AsParseNodeVar()->sym);
  1460. }
  1461. }
  1462. ChkCurTok(tkLCurly, ERRnoLcurly);
  1463. ParseNodePtr * ppnodeList = nullptr;
  1464. if (buildAST)
  1465. {
  1466. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  1467. ppnodeList = &pnodeBlock->pnodeStmt;
  1468. }
  1469. ParseStmtList<buildAST>(ppnodeList);
  1470. if (buildAST)
  1471. {
  1472. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  1473. }
  1474. FinishParseBlock(pnodeBlock);
  1475. ChkCurTok(tkRCurly, ERRnoRcurly);
  1476. return pnodeBlock;
  1477. }
  1478. bool Parser::IsSpecialName(IdentPtr pid)
  1479. {
  1480. return pid == wellKnownPropertyPids._this ||
  1481. pid == wellKnownPropertyPids._super ||
  1482. pid == wellKnownPropertyPids._superConstructor ||
  1483. pid == wellKnownPropertyPids._newTarget;
  1484. }
  1485. ParseNodeSpecialName * Parser::ReferenceSpecialName(IdentPtr pid, charcount_t ichMin, charcount_t ichLim, bool createNode)
  1486. {
  1487. PidRefStack* ref = this->PushPidRef(pid);
  1488. if (!createNode)
  1489. {
  1490. return nullptr;
  1491. }
  1492. return CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  1493. }
  1494. ParseNodeVar * Parser::CreateSpecialVarDeclIfNeeded(ParseNodeFnc * pnodeFnc, IdentPtr pid, bool forceCreate)
  1495. {
  1496. Assert(pid != nullptr);
  1497. PidRefStack* ref = pid->GetTopRef();
  1498. // If the function has a reference to pid or we set forceCreate, make a special var decl
  1499. if (forceCreate || (ref && ref->GetScopeId() >= m_currentBlockInfo->pnodeBlock->blockId))
  1500. {
  1501. return this->CreateSpecialVarDeclNode(pnodeFnc, pid);
  1502. }
  1503. return nullptr;
  1504. }
  1505. void Parser::CreateSpecialSymbolDeclarations(ParseNodeFnc * pnodeFnc)
  1506. {
  1507. // Lambda function cannot have any special bindings.
  1508. if (pnodeFnc->IsLambda())
  1509. {
  1510. return;
  1511. }
  1512. bool isTopLevelEventHandler = (this->m_grfscr & fscrImplicitThis) && !pnodeFnc->IsNested();
  1513. // Create a 'this' symbol for non-lambda functions with references to 'this', and all class constructors and top level event hanlders.
  1514. ParseNodePtr varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._this, pnodeFnc->IsClassConstructor() || isTopLevelEventHandler);
  1515. if (varDeclNode)
  1516. {
  1517. varDeclNode->AsParseNodeVar()->sym->SetIsThis(true);
  1518. if (pnodeFnc->IsDerivedClassConstructor())
  1519. {
  1520. varDeclNode->AsParseNodeVar()->sym->SetNeedDeclaration(true);
  1521. }
  1522. }
  1523. // Create a 'new.target' symbol for any ordinary function with a reference and all class constructors.
  1524. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._newTarget, pnodeFnc->IsClassConstructor());
  1525. if (varDeclNode)
  1526. {
  1527. varDeclNode->AsParseNodeVar()->sym->SetIsNewTarget(true);
  1528. }
  1529. // Create a 'super' (as a reference) symbol.
  1530. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._super);
  1531. if (varDeclNode)
  1532. {
  1533. varDeclNode->AsParseNodeVar()->sym->SetIsSuper(true);
  1534. }
  1535. // Create a 'super' (as the call target for super()) symbol only for derived class constructors.
  1536. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._superConstructor);
  1537. if (varDeclNode)
  1538. {
  1539. varDeclNode->AsParseNodeVar()->sym->SetIsSuperConstructor(true);
  1540. }
  1541. }
  1542. void Parser::FinishParseBlock(ParseNodeBlock *pnodeBlock, bool needScanRCurly)
  1543. {
  1544. Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);
  1545. if (needScanRCurly)
  1546. {
  1547. // Only update the ichLim if we were expecting an RCurly. If there is an
  1548. // expression body without a necessary RCurly, the correct ichLim will
  1549. // have been set already.
  1550. pnodeBlock->ichLim = this->GetScanner()->IchLimTok();
  1551. }
  1552. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  1553. PopStmt(&m_currentBlockInfo->pstmt);
  1554. PopBlockInfo();
  1555. Scope *scope = pnodeBlock->scope;
  1556. if (scope)
  1557. {
  1558. PopScope(scope);
  1559. }
  1560. }
  1561. void Parser::FinishParseFncExprScope(ParseNodeFnc * pnodeFnc, ParseNodeBlock * pnodeFncExprScope)
  1562. {
  1563. int fncExprScopeId = pnodeFncExprScope->blockId;
  1564. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  1565. if (pnodeName)
  1566. {
  1567. Assert(pnodeName->nop == knopVarDecl);
  1568. BindPidRefsInScope(pnodeName->AsParseNodeVar()->pid, pnodeName->AsParseNodeVar()->sym, fncExprScopeId, m_nextBlockId - 1);
  1569. }
  1570. FinishParseBlock(pnodeFncExprScope);
  1571. }
  1572. template <const bool backgroundPidRef>
  1573. void Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)
  1574. {
  1575. // We need to bind all assignments in order to emit assignment to 'const' error
  1576. int blockId = blockInfo->pnodeBlock->blockId;
  1577. Scope *scope = blockInfo->pnodeBlock->scope;
  1578. if (scope)
  1579. {
  1580. auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)
  1581. {
  1582. ParseNodePtr pnode = sym->GetDecl();
  1583. IdentPtr pid;
  1584. #if PROFILE_DICTIONARY
  1585. int depth = 0;
  1586. #endif
  1587. Assert(pnode);
  1588. switch (pnode->nop)
  1589. {
  1590. case knopVarDecl:
  1591. case knopLetDecl:
  1592. case knopConstDecl:
  1593. pid = pnode->AsParseNodeVar()->pid;
  1594. if (backgroundPidRef)
  1595. {
  1596. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1597. #if PROFILE_DICTIONARY
  1598. , depth
  1599. #endif
  1600. );
  1601. if (pid == nullptr)
  1602. {
  1603. break;
  1604. }
  1605. }
  1606. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1607. break;
  1608. case knopName:
  1609. pid = pnode->AsParseNodeName()->pid;
  1610. if (backgroundPidRef)
  1611. {
  1612. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1613. #if PROFILE_DICTIONARY
  1614. , depth
  1615. #endif
  1616. );
  1617. if (pid == nullptr)
  1618. {
  1619. break;
  1620. }
  1621. }
  1622. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1623. break;
  1624. default:
  1625. Assert(0);
  1626. break;
  1627. }
  1628. };
  1629. scope->ForEachSymbol(bindPidRefs);
  1630. }
  1631. }
  1632. void Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)
  1633. {
  1634. PidRefStack *ref, *nextRef, *lastRef = nullptr;
  1635. Js::LocalFunctionId funcId = GetCurrentFunctionNode()->functionId;
  1636. Assert(sym);
  1637. if (pid->GetIsModuleExport() && IsTopLevelModuleFunc())
  1638. {
  1639. sym->SetIsModuleExportStorage(true);
  1640. }
  1641. bool hasFuncAssignment = sym->GetHasFuncAssignment();
  1642. bool doesEscape = false;
  1643. for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)
  1644. {
  1645. // Fix up sym* on PID ref.
  1646. Assert(!ref->GetSym() || ref->GetSym() == sym);
  1647. nextRef = ref->prev;
  1648. Assert(ref->GetScopeId() >= 0);
  1649. if ((uint)ref->GetScopeId() > maxBlockId)
  1650. {
  1651. lastRef = ref;
  1652. continue;
  1653. }
  1654. ref->SetSym(sym);
  1655. this->RemovePrevPidRef(pid, lastRef);
  1656. if (ref->IsUsedInLdElem())
  1657. {
  1658. sym->SetIsUsedInLdElem(true);
  1659. }
  1660. if (ref->IsAssignment())
  1661. {
  1662. sym->PromoteAssignmentState();
  1663. if (sym->GetIsFormal())
  1664. {
  1665. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  1666. }
  1667. }
  1668. if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1669. {
  1670. Assert(ref->GetFuncScopeId() > funcId);
  1671. sym->SetHasNonLocalReference();
  1672. if (ref->IsDynamicBinding())
  1673. {
  1674. sym->SetNeedsScopeObject();
  1675. }
  1676. }
  1677. if (ref->IsFuncAssignment())
  1678. {
  1679. hasFuncAssignment = true;
  1680. }
  1681. if (ref->IsEscape())
  1682. {
  1683. doesEscape = true;
  1684. }
  1685. if (m_currentNodeFunc && doesEscape && hasFuncAssignment)
  1686. {
  1687. if (m_sourceContextInfo ?
  1688. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1689. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1690. {
  1691. m_currentNodeFunc->SetNestedFuncEscapes();
  1692. }
  1693. }
  1694. if (ref->GetScopeId() == blockId)
  1695. {
  1696. break;
  1697. }
  1698. }
  1699. }
  1700. void Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)
  1701. {
  1702. if (m_currentNodeFunc == nullptr)
  1703. {
  1704. return;
  1705. }
  1706. if (pnode && pnode->nop == knopFncDecl)
  1707. {
  1708. this->SetNestedFuncEscapes();
  1709. }
  1710. else if (pToken->pid)
  1711. {
  1712. PidRefStack *pidRef = pToken->pid->GetTopRef();
  1713. if (pidRef->sym)
  1714. {
  1715. if (pidRef->sym->GetSymbolType() == STFunction)
  1716. {
  1717. this->SetNestedFuncEscapes();
  1718. }
  1719. }
  1720. else
  1721. {
  1722. pidRef->isEscape = true;
  1723. }
  1724. }
  1725. }
  1726. void Parser::SetNestedFuncEscapes() const
  1727. {
  1728. if (m_sourceContextInfo ?
  1729. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1730. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1731. {
  1732. m_currentNodeFunc->SetNestedFuncEscapes();
  1733. }
  1734. }
  1735. void Parser::PopStmt(StmtNest *pStmt)
  1736. {
  1737. Assert(pStmt == m_pstmtCur);
  1738. SetCurrentStatement(m_pstmtCur->pstmtOuter);
  1739. }
  1740. BlockInfoStack *Parser::PushBlockInfo(ParseNodeBlock * pnodeBlock)
  1741. {
  1742. BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));
  1743. Assert(nullptr != newBlockInfo);
  1744. newBlockInfo->pnodeBlock = pnodeBlock;
  1745. newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;
  1746. newBlockInfo->m_ppnodeLex = &pnodeBlock->pnodeLexVars;
  1747. if (pnodeBlock->blockType != PnodeBlockType::Regular)
  1748. {
  1749. newBlockInfo->pBlockInfoFunction = newBlockInfo;
  1750. }
  1751. else
  1752. {
  1753. Assert(m_currentBlockInfo);
  1754. newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;
  1755. }
  1756. m_currentBlockInfo = newBlockInfo;
  1757. return newBlockInfo;
  1758. }
  1759. void Parser::PopBlockInfo()
  1760. {
  1761. Assert(m_currentBlockInfo);
  1762. PopDynamicBlock();
  1763. m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1764. }
  1765. void Parser::PushDynamicBlock()
  1766. {
  1767. Assert(GetCurrentBlock());
  1768. int blockId = GetCurrentBlock()->blockId;
  1769. if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)
  1770. {
  1771. return;
  1772. }
  1773. BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));
  1774. if (nullptr == info)
  1775. {
  1776. Error(ERRnoMemory);
  1777. }
  1778. info->id = blockId;
  1779. info->prev = m_currentDynamicBlock;
  1780. m_currentDynamicBlock = info;
  1781. }
  1782. void Parser::PopDynamicBlock()
  1783. {
  1784. int blockId = GetCurrentDynamicBlockId();
  1785. if (GetCurrentBlock()->blockId != blockId || blockId == -1)
  1786. {
  1787. return;
  1788. }
  1789. Assert(m_currentDynamicBlock);
  1790. this->GetHashTbl()->VisitPids([&](IdentPtr pid) {
  1791. for (PidRefStack *ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = ref->prev)
  1792. {
  1793. ref->SetDynamicBinding();
  1794. }
  1795. });
  1796. m_currentDynamicBlock = m_currentDynamicBlock->prev;
  1797. }
  1798. int Parser::GetCurrentDynamicBlockId() const
  1799. {
  1800. return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;
  1801. }
  1802. ParseNodeFnc *Parser::GetCurrentFunctionNode()
  1803. {
  1804. if (m_currentNodeDeferredFunc != nullptr)
  1805. {
  1806. return m_currentNodeDeferredFunc;
  1807. }
  1808. else if (m_currentNodeFunc != nullptr)
  1809. {
  1810. return m_currentNodeFunc;
  1811. }
  1812. else
  1813. {
  1814. AssertMsg(GetFunctionBlock()->blockType == PnodeBlockType::Global,
  1815. "Most likely we are trying to find a syntax error, related to 'let' or 'const' in deferred parsing mode with disabled support of 'let' and 'const'");
  1816. return m_currentNodeProg;
  1817. }
  1818. }
  1819. ParseNodeFnc *Parser::GetCurrentNonLambdaFunctionNode()
  1820. {
  1821. if (m_currentNodeNonLambdaDeferredFunc != nullptr)
  1822. {
  1823. return m_currentNodeNonLambdaDeferredFunc;
  1824. }
  1825. return m_currentNodeNonLambdaFunc;
  1826. }
  1827. void Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)
  1828. {
  1829. Assert(regexPattern);
  1830. // ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator
  1831. if (!m_registeredRegexPatterns.PrependNoThrow(m_tempGuestArena->GetAllocator(), regexPattern))
  1832. {
  1833. Parser::Error(ERRnoMemory);
  1834. }
  1835. }
  1836. void Parser::CaptureState(ParserState *state)
  1837. {
  1838. Assert(state != nullptr);
  1839. state->m_funcInArraySave = m_funcInArray;
  1840. state->m_funcInArrayDepthSave = m_funcInArrayDepth;
  1841. state->m_nestedCountSave = *m_pnestedCount;
  1842. state->m_ppnodeScopeSave = m_ppnodeScope;
  1843. state->m_ppnodeExprScopeSave = m_ppnodeExprScope;
  1844. state->m_pCurrentAstSizeSave = m_pCurrentAstSize;
  1845. state->m_nextBlockId = m_nextBlockId;
  1846. Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);
  1847. Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);
  1848. #if DEBUG
  1849. state->m_currentBlockInfo = m_currentBlockInfo;
  1850. #endif
  1851. }
  1852. void Parser::RestoreStateFrom(ParserState *state)
  1853. {
  1854. Assert(state != nullptr);
  1855. Assert(state->m_currentBlockInfo == m_currentBlockInfo);
  1856. m_funcInArray = state->m_funcInArraySave;
  1857. m_funcInArrayDepth = state->m_funcInArrayDepthSave;
  1858. *m_pnestedCount = state->m_nestedCountSave;
  1859. m_pCurrentAstSize = state->m_pCurrentAstSizeSave;
  1860. m_nextBlockId = state->m_nextBlockId;
  1861. if (state->m_ppnodeScopeSave != nullptr)
  1862. {
  1863. *state->m_ppnodeScopeSave = nullptr;
  1864. }
  1865. if (state->m_ppnodeExprScopeSave != nullptr)
  1866. {
  1867. *state->m_ppnodeExprScopeSave = nullptr;
  1868. }
  1869. m_ppnodeScope = state->m_ppnodeScopeSave;
  1870. m_ppnodeExprScope = state->m_ppnodeExprScopeSave;
  1871. }
  1872. void Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1873. ParseNode * pnodeAdd)
  1874. {
  1875. AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);
  1876. pnodeAdd->SetIsInList();
  1877. }
  1878. void Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1879. ParseNode * pnodeAdd)
  1880. {
  1881. Assert(!this->m_deferringAST);
  1882. if (nullptr == *pppnodeLast)
  1883. {
  1884. // should be an empty list
  1885. Assert(nullptr == *ppnodeList);
  1886. *ppnodeList = pnodeAdd;
  1887. *pppnodeLast = ppnodeList;
  1888. }
  1889. else
  1890. {
  1891. //
  1892. Assert(*ppnodeList);
  1893. Assert(**pppnodeLast);
  1894. ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);
  1895. **pppnodeLast = pnodeT;
  1896. *pppnodeLast = &pnodeT->AsParseNodeBin()->pnode2;
  1897. }
  1898. }
  1899. // Check reference to "arguments" that indicates the object may escape.
  1900. void Parser::CheckArguments(ParseNodePtr pnode)
  1901. {
  1902. if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))
  1903. {
  1904. m_currentNodeFunc->SetHasHeapArguments();
  1905. }
  1906. }
  1907. // Check use of "arguments" that requires instantiation of the object.
  1908. void Parser::CheckArgumentsUse(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1909. {
  1910. if (pid == wellKnownPropertyPids.arguments)
  1911. {
  1912. if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)
  1913. {
  1914. pnodeFnc->SetUsesArguments(TRUE);
  1915. }
  1916. else
  1917. {
  1918. m_UsesArgumentsAtGlobal = true;
  1919. }
  1920. }
  1921. }
  1922. void Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)
  1923. {
  1924. if (pid != nullptr)
  1925. {
  1926. // In strict mode, 'eval' / 'arguments' cannot be assigned to.
  1927. if (pid == wellKnownPropertyPids.eval)
  1928. {
  1929. Error(ERREvalUsage, pnode);
  1930. }
  1931. if (pid == wellKnownPropertyPids.arguments)
  1932. {
  1933. Error(ERRArgsUsage, pnode);
  1934. }
  1935. }
  1936. }
  1937. void Parser::ReduceDeferredScriptLength(size_t chars)
  1938. {
  1939. // If we're in deferred mode, subtract the given char count from the total length,
  1940. // and see if this puts us under the deferral threshold.
  1941. if (((m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse)) == (fscrCanDeferFncParse | fscrWillDeferFncParse)) &&
  1942. (
  1943. PHASE_OFF1(Js::DeferEventHandlersPhase) ||
  1944. (m_grfscr & fscrGlobalCode)
  1945. )
  1946. )
  1947. {
  1948. if (m_length > chars)
  1949. {
  1950. m_length -= chars;
  1951. }
  1952. else
  1953. {
  1954. m_length = 0;
  1955. }
  1956. if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))
  1957. {
  1958. // Stop deferring.
  1959. m_grfscr &= ~fscrWillDeferFncParse;
  1960. m_stoppedDeferredParse = TRUE;
  1961. }
  1962. }
  1963. }
  1964. void Parser::EnsureStackAvailable()
  1965. {
  1966. bool isInterrupt = false;
  1967. if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile, &isInterrupt))
  1968. {
  1969. Error(isInterrupt ? E_ABORT : VBSERR_OutOfStack);
  1970. }
  1971. }
  1972. void Parser::ThrowNewTargetSyntaxErrForGlobalScope()
  1973. {
  1974. // If we are parsing a previously deferred function, we can skip throwing the SyntaxError for `new.target` at global scope.
  1975. // If we are at global scope, we would have thrown a SyntaxError when we did the Upfront parse pass and we would not have
  1976. // deferred the function in order to come back now and reparse it.
  1977. if (m_parseType == ParseType_Deferred)
  1978. {
  1979. return;
  1980. }
  1981. if (GetCurrentNonLambdaFunctionNode() != nullptr)
  1982. {
  1983. return;
  1984. }
  1985. if ((this->m_grfscr & fscrEval) != 0)
  1986. {
  1987. Js::JavascriptFunction * caller = nullptr;
  1988. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  1989. {
  1990. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  1991. Assert(callerBody);
  1992. if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))
  1993. {
  1994. return;
  1995. }
  1996. }
  1997. }
  1998. Error(ERRInvalidNewTarget);
  1999. }
  2000. template<bool buildAST>
  2001. IdentPtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)
  2002. {
  2003. AssertMsg(metaParentKeyword == tkNEW, "Only supported for tkNEW parent keywords");
  2004. AssertMsg(this->m_token.tk == tkDot, "We must be currently sitting on the dot after the parent keyword");
  2005. this->GetScanner()->Scan();
  2006. if (this->m_token.tk == tkID && this->m_token.GetIdentifier(this->GetHashTbl()) == this->GetTargetPid())
  2007. {
  2008. ThrowNewTargetSyntaxErrForGlobalScope();
  2009. if (pfCanAssign)
  2010. {
  2011. *pfCanAssign = FALSE;
  2012. }
  2013. return wellKnownPropertyPids._newTarget;
  2014. }
  2015. else
  2016. {
  2017. Error(ERRValidIfFollowedBy, _u("'new.'"), _u("'target'"));
  2018. }
  2019. }
  2020. template<bool buildAST>
  2021. void Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)
  2022. {
  2023. Assert(m_token.tk == tkLCurly);
  2024. Assert(importOrExportEntryList != nullptr);
  2025. this->GetScanner()->Scan();
  2026. while (m_token.tk != tkRCurly && m_token.tk != tkEOF)
  2027. {
  2028. tokens firstToken = m_token.tk;
  2029. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  2030. {
  2031. Error(ERRsyntax);
  2032. }
  2033. IdentPtr identifierName = m_token.GetIdentifier(this->GetHashTbl());
  2034. IdentPtr identifierAs = identifierName;
  2035. this->GetScanner()->Scan();
  2036. if (m_token.tk == tkID)
  2037. {
  2038. // We have the pattern "IdentifierName as"
  2039. if (wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  2040. {
  2041. Error(ERRsyntax);
  2042. }
  2043. this->GetScanner()->Scan();
  2044. // If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.
  2045. if (!isExportClause)
  2046. {
  2047. ChkCurTokNoScan(tkID, ERRsyntax);
  2048. }
  2049. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  2050. {
  2051. Error(ERRsyntax);
  2052. }
  2053. identifierAs = m_token.GetIdentifier(this->GetHashTbl());
  2054. // Scan to the next token.
  2055. this->GetScanner()->Scan();
  2056. }
  2057. else if (!isExportClause && firstToken != tkID)
  2058. {
  2059. // If we are parsing an import statement and this ImportSpecifier clause did not have
  2060. // 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.
  2061. Error(ERRsyntax);
  2062. }
  2063. if (m_token.tk == tkComma)
  2064. {
  2065. // Consume a trailing comma
  2066. this->GetScanner()->Scan();
  2067. }
  2068. if (buildAST)
  2069. {
  2070. // The name we will use 'as' this import/export is a binding identifier in import statements.
  2071. if (!isExportClause)
  2072. {
  2073. CreateModuleImportDeclNode(identifierAs);
  2074. AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);
  2075. }
  2076. else
  2077. {
  2078. identifierName->SetIsModuleExport();
  2079. AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr);
  2080. }
  2081. }
  2082. }
  2083. // Final token in a named import or export clause must be a '}'
  2084. ChkCurTokNoScan(tkRCurly, ERRsyntax);
  2085. }
  2086. IdentPtrList* Parser::GetRequestedModulesList()
  2087. {
  2088. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  2089. }
  2090. ModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()
  2091. {
  2092. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  2093. }
  2094. ModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()
  2095. {
  2096. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  2097. }
  2098. ModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()
  2099. {
  2100. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  2101. }
  2102. ModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()
  2103. {
  2104. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  2105. }
  2106. IdentPtrList* Parser::EnsureRequestedModulesList()
  2107. {
  2108. if (m_currentNodeProg->AsParseNodeModule()->requestedModules == nullptr)
  2109. {
  2110. m_currentNodeProg->AsParseNodeModule()->requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);
  2111. }
  2112. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  2113. }
  2114. ModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()
  2115. {
  2116. if (m_currentNodeProg->AsParseNodeModule()->importEntries == nullptr)
  2117. {
  2118. m_currentNodeProg->AsParseNodeModule()->importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2119. }
  2120. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  2121. }
  2122. ModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()
  2123. {
  2124. if (m_currentNodeProg->AsParseNodeModule()->localExportEntries == nullptr)
  2125. {
  2126. m_currentNodeProg->AsParseNodeModule()->localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2127. }
  2128. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  2129. }
  2130. ModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()
  2131. {
  2132. if (m_currentNodeProg->AsParseNodeModule()->indirectExportEntries == nullptr)
  2133. {
  2134. m_currentNodeProg->AsParseNodeModule()->indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2135. }
  2136. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  2137. }
  2138. ModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()
  2139. {
  2140. if (m_currentNodeProg->AsParseNodeModule()->starExportEntries == nullptr)
  2141. {
  2142. m_currentNodeProg->AsParseNodeModule()->starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2143. }
  2144. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  2145. }
  2146. void Parser::AddModuleSpecifier(IdentPtr moduleRequest)
  2147. {
  2148. IdentPtrList* requestedModulesList = EnsureRequestedModulesList();
  2149. if (!requestedModulesList->Has(moduleRequest))
  2150. {
  2151. requestedModulesList->Prepend(moduleRequest);
  2152. }
  2153. }
  2154. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)
  2155. {
  2156. if (importOrExportEntry->exportName != nullptr)
  2157. {
  2158. CheckForDuplicateExportEntry(importOrExportEntryList, importOrExportEntry->exportName);
  2159. }
  2160. importOrExportEntryList->Prepend(*importOrExportEntry);
  2161. return importOrExportEntry;
  2162. }
  2163. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest)
  2164. {
  2165. ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);
  2166. importOrExportEntry->importName = importName;
  2167. importOrExportEntry->localName = localName;
  2168. importOrExportEntry->exportName = exportName;
  2169. importOrExportEntry->moduleRequest = moduleRequest;
  2170. return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);
  2171. }
  2172. void Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)
  2173. {
  2174. AssertOrFailFast(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);
  2175. IdentPtr localName = varDeclNode->AsParseNodeVar()->pid;
  2176. varDeclNode->AsParseNodeVar()->sym->SetIsModuleExportStorage(true);
  2177. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2178. }
  2179. void Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)
  2180. {
  2181. ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)
  2182. {
  2183. if (exportName == exportEntry.exportName)
  2184. {
  2185. return true;
  2186. }
  2187. return false;
  2188. });
  2189. if (findResult != nullptr)
  2190. {
  2191. Error(ERRsyntax);
  2192. }
  2193. }
  2194. template<bool buildAST>
  2195. void Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)
  2196. {
  2197. bool parsedNamespaceOrNamedImport = false;
  2198. switch (m_token.tk)
  2199. {
  2200. case tkID:
  2201. // This is the default binding identifier.
  2202. // If we already saw a comma in the import clause, this is a syntax error.
  2203. if (parsingAfterComma)
  2204. {
  2205. Error(ERRsyntax);
  2206. }
  2207. if (buildAST)
  2208. {
  2209. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2210. IdentPtr importName = wellKnownPropertyPids._default;
  2211. CreateModuleImportDeclNode(localName);
  2212. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2213. }
  2214. break;
  2215. case tkLCurly:
  2216. // This begins a list of named imports.
  2217. ParseNamedImportOrExportClause<buildAST>(importEntryList, false);
  2218. parsedNamespaceOrNamedImport = true;
  2219. break;
  2220. case tkStar:
  2221. // This begins a namespace import clause.
  2222. // "* as ImportedBinding"
  2223. // Token following * must be the identifier 'as'
  2224. this->GetScanner()->Scan();
  2225. if (m_token.tk != tkID || wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  2226. {
  2227. Error(ERRsyntax);
  2228. }
  2229. // Token following 'as' must be a binding identifier.
  2230. this->GetScanner()->Scan();
  2231. ChkCurTokNoScan(tkID, ERRsyntax);
  2232. if (buildAST)
  2233. {
  2234. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2235. IdentPtr importName = wellKnownPropertyPids._star;
  2236. CreateModuleImportDeclNode(localName);
  2237. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2238. }
  2239. parsedNamespaceOrNamedImport = true;
  2240. break;
  2241. default:
  2242. Error(ERRsyntax);
  2243. }
  2244. this->GetScanner()->Scan();
  2245. if (m_token.tk == tkComma)
  2246. {
  2247. // There cannot be more than one comma in a module import clause.
  2248. // There cannot be a namespace import or named imports list on the left of the comma in a module import clause.
  2249. if (parsingAfterComma || parsedNamespaceOrNamedImport)
  2250. {
  2251. Error(ERRTokenAfter, _u(","), GetTokenString(this->GetScanner()->GetPrevious()));
  2252. }
  2253. this->GetScanner()->Scan();
  2254. ParseImportClause<buildAST>(importEntryList, true);
  2255. }
  2256. }
  2257. bool Parser::IsImportOrExportStatementValidHere()
  2258. {
  2259. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2260. // Import must be located in the top scope of the module body.
  2261. return curFunc->nop == knopFncDecl
  2262. && curFunc->IsModule()
  2263. && this->m_currentBlockInfo->pnodeBlock == curFunc->pnodeBodyScope
  2264. && (this->m_grfscr & fscrEvalCode) != fscrEvalCode
  2265. && this->m_tryCatchOrFinallyDepth == 0
  2266. && !this->m_disallowImportExportStmt;
  2267. }
  2268. bool Parser::IsTopLevelModuleFunc()
  2269. {
  2270. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2271. return curFunc->nop == knopFncDecl && curFunc->IsModule();
  2272. }
  2273. template<bool buildAST> ParseNodePtr Parser::ParseImportCall()
  2274. {
  2275. this->GetScanner()->Scan();
  2276. ParseNodePtr specifier = ParseExpr<buildAST>(koplCma, nullptr, /* fAllowIn */FALSE, /* fAllowEllipsis */FALSE);
  2277. if (m_token.tk != tkRParen)
  2278. {
  2279. Error(ERRnoRparen);
  2280. }
  2281. this->GetScanner()->Scan();
  2282. return buildAST ? CreateCallNode(knopCall, CreateNodeForOpT<knopImport>(), specifier) : nullptr;
  2283. }
  2284. template<bool buildAST>
  2285. ParseNodePtr Parser::ParseImport()
  2286. {
  2287. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2288. Assert(m_token.tk == tkIMPORT);
  2289. RestorePoint parsedImport;
  2290. this->GetScanner()->Capture(&parsedImport);
  2291. this->GetScanner()->Scan();
  2292. // import()
  2293. if (m_token.tk == tkLParen)
  2294. {
  2295. if (!m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2296. {
  2297. Error(ERRExperimental);
  2298. }
  2299. ParseNodePtr pnode = ParseImportCall<buildAST>();
  2300. BOOL fCanAssign;
  2301. IdentToken token;
  2302. return ParsePostfixOperators<buildAST>(pnode, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  2303. }
  2304. this->GetScanner()->SeekTo(parsedImport);
  2305. if (!IsImportOrExportStatementValidHere())
  2306. {
  2307. Error(ERRInvalidModuleImportOrExport);
  2308. }
  2309. // We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.
  2310. this->GetScanner()->Scan();
  2311. if (m_token.tk == tkStrCon)
  2312. {
  2313. // This import declaration has no import clause.
  2314. // "import ModuleSpecifier;"
  2315. if (buildAST)
  2316. {
  2317. AddModuleSpecifier(m_token.GetStr());
  2318. }
  2319. // Scan past the module identifier.
  2320. this->GetScanner()->Scan();
  2321. }
  2322. else
  2323. {
  2324. ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);
  2325. // Parse the import clause (default binding can only exist before the comma).
  2326. ParseImportClause<buildAST>(&importEntryList);
  2327. // Token following import clause must be the identifier 'from'
  2328. IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);
  2329. if (buildAST)
  2330. {
  2331. Assert(moduleSpecifier != nullptr);
  2332. AddModuleSpecifier(moduleSpecifier);
  2333. importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {
  2334. importEntry.moduleRequest = moduleSpecifier;
  2335. AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);
  2336. });
  2337. }
  2338. importEntryList.Clear();
  2339. }
  2340. // Import statement is actually a nop, we hoist all the imported bindings to the top of the module.
  2341. return nullptr;
  2342. }
  2343. template<bool buildAST>
  2344. IdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)
  2345. {
  2346. IdentPtr moduleSpecifier = nullptr;
  2347. if (m_token.tk == tkID && wellKnownPropertyPids.from == m_token.GetIdentifier(this->GetHashTbl()))
  2348. {
  2349. this->GetScanner()->Scan();
  2350. // Token following the 'from' token must be a string constant - the module specifier.
  2351. ChkCurTokNoScan(tkStrCon, ERRsyntax);
  2352. if (buildAST)
  2353. {
  2354. moduleSpecifier = m_token.GetStr();
  2355. }
  2356. this->GetScanner()->Scan();
  2357. }
  2358. else if (throwIfNotFound)
  2359. {
  2360. Error(ERRsyntax);
  2361. }
  2362. return moduleSpecifier;
  2363. }
  2364. template<bool buildAST>
  2365. ParseNodePtr Parser::ParseDefaultExportClause()
  2366. {
  2367. Assert(m_token.tk == tkDEFAULT);
  2368. this->GetScanner()->Scan();
  2369. ParseNodePtr pnode = nullptr;
  2370. ushort flags = fFncNoFlgs;
  2371. switch (m_token.tk)
  2372. {
  2373. case tkCLASS:
  2374. {
  2375. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2376. {
  2377. goto LDefault;
  2378. }
  2379. // Before we parse the class itself we need to know if the class has an identifier name.
  2380. // If it does, we'll treat this class as an ordinary class declaration which will bind
  2381. // it to that name. Otherwise the class should parse as a nameless class expression and
  2382. // bind only to the export binding.
  2383. BOOL classHasName = false;
  2384. RestorePoint parsedClass;
  2385. this->GetScanner()->Capture(&parsedClass);
  2386. this->GetScanner()->Scan();
  2387. if (m_token.tk == tkID)
  2388. {
  2389. classHasName = true;
  2390. }
  2391. this->GetScanner()->SeekTo(parsedClass);
  2392. ParseNodeClass * pnodeClass;
  2393. pnode = pnodeClass = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);
  2394. if (buildAST)
  2395. {
  2396. AnalysisAssert(pnode != nullptr);
  2397. Assert(pnode->nop == knopClassDecl);
  2398. pnodeClass->SetIsDefaultModuleExport(true);
  2399. }
  2400. break;
  2401. }
  2402. case tkID:
  2403. // If we parsed an async token, it could either modify the next token (if it is a
  2404. // function token) or it could be an identifier (let async = 0; export default async;).
  2405. // To handle both cases, when we parse an async token we need to keep the parser state
  2406. // and rewind if the next token is not function.
  2407. if (wellKnownPropertyPids.async == m_token.GetIdentifier(this->GetHashTbl()))
  2408. {
  2409. RestorePoint parsedAsync;
  2410. this->GetScanner()->Capture(&parsedAsync);
  2411. this->GetScanner()->Scan();
  2412. if (m_token.tk == tkFUNCTION)
  2413. {
  2414. // Token after async is function, consume the async token and continue to parse the
  2415. // function as an async function.
  2416. flags |= fFncAsync;
  2417. goto LFunction;
  2418. }
  2419. // Token after async is not function, no idea what the async token is supposed to mean
  2420. // so rewind and let the default case handle it.
  2421. this->GetScanner()->SeekTo(parsedAsync);
  2422. }
  2423. goto LDefault;
  2424. break;
  2425. case tkFUNCTION:
  2426. {
  2427. LFunction:
  2428. // We just parsed a function token but we need to figure out if the function
  2429. // has an identifier name or not before we call the helper.
  2430. RestorePoint parsedFunction;
  2431. this->GetScanner()->Capture(&parsedFunction);
  2432. this->GetScanner()->Scan();
  2433. if (m_token.tk == tkStar)
  2434. {
  2435. // If we saw 'function*' that indicates we are going to parse a generator,
  2436. // but doesn't tell us if the generator has an identifier or not.
  2437. // Skip the '*' token for now as it doesn't matter yet.
  2438. this->GetScanner()->Scan();
  2439. }
  2440. // We say that if the function has an identifier name, it is a 'normal' declaration
  2441. // and should create a binding to that identifier as well as one for our default export.
  2442. if (m_token.tk == tkID)
  2443. {
  2444. flags |= fFncDeclaration;
  2445. }
  2446. else
  2447. {
  2448. flags |= fFncNoName;
  2449. }
  2450. // Rewind back to the function token and let the helper handle the parsing.
  2451. this->GetScanner()->SeekTo(parsedFunction);
  2452. pnode = ParseFncDeclCheckScope<buildAST>(flags);
  2453. if (buildAST)
  2454. {
  2455. AnalysisAssert(pnode != nullptr);
  2456. Assert(pnode->nop == knopFncDecl);
  2457. pnode->AsParseNodeFnc()->SetIsDefaultModuleExport(true);
  2458. }
  2459. break;
  2460. }
  2461. default:
  2462. LDefault:
  2463. {
  2464. ParseNodePtr pnodeExpression = ParseExpr<buildAST>();
  2465. // Consider: Can we detect this syntax error earlier?
  2466. if (pnodeExpression && pnodeExpression->nop == knopComma)
  2467. {
  2468. Error(ERRsyntax);
  2469. }
  2470. if (buildAST)
  2471. {
  2472. AnalysisAssert(pnodeExpression != nullptr);
  2473. // Mark this node as the default module export. We need to make sure it is put into the correct
  2474. // module export slot when we emit the node.
  2475. ParseNodeExportDefault * pnodeExportDefault;
  2476. pnode = pnodeExportDefault = CreateNodeForOpT<knopExportDefault>();
  2477. pnode->AsParseNodeExportDefault()->pnodeExpr = pnodeExpression;
  2478. }
  2479. break;
  2480. }
  2481. }
  2482. IdentPtr exportName = wellKnownPropertyPids._default;
  2483. IdentPtr localName = wellKnownPropertyPids._starDefaultStar;
  2484. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, exportName, nullptr);
  2485. return pnode;
  2486. }
  2487. template<bool buildAST>
  2488. ParseNodePtr Parser::ParseExportDeclaration(bool *needTerminator)
  2489. {
  2490. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2491. Assert(m_token.tk == tkEXPORT);
  2492. if (!IsImportOrExportStatementValidHere())
  2493. {
  2494. Error(ERRInvalidModuleImportOrExport);
  2495. }
  2496. ParseNodePtr pnode = nullptr;
  2497. IdentPtr moduleIdentifier = nullptr;
  2498. tokens declarationType;
  2499. if (needTerminator != nullptr)
  2500. {
  2501. *needTerminator = false;
  2502. }
  2503. // We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.
  2504. this->GetScanner()->Scan();
  2505. switch (m_token.tk)
  2506. {
  2507. case tkStar:
  2508. this->GetScanner()->Scan();
  2509. // A star token in an export declaration must be followed by a from clause which begins with a token 'from'.
  2510. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);
  2511. if (buildAST)
  2512. {
  2513. Assert(moduleIdentifier != nullptr);
  2514. AddModuleSpecifier(moduleIdentifier);
  2515. IdentPtr importName = wellKnownPropertyPids._star;
  2516. AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), importName, nullptr, nullptr, moduleIdentifier);
  2517. }
  2518. if (needTerminator != nullptr)
  2519. {
  2520. *needTerminator = true;
  2521. }
  2522. break;
  2523. case tkLCurly:
  2524. {
  2525. ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);
  2526. ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);
  2527. this->GetScanner()->Scan();
  2528. // Export clause may be followed by a from clause.
  2529. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);
  2530. if (buildAST)
  2531. {
  2532. if (moduleIdentifier != nullptr)
  2533. {
  2534. AddModuleSpecifier(moduleIdentifier);
  2535. }
  2536. exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {
  2537. if (moduleIdentifier != nullptr)
  2538. {
  2539. exportEntry.moduleRequest = moduleIdentifier;
  2540. // We need to swap localname and importname when this is a re-export.
  2541. exportEntry.importName = exportEntry.localName;
  2542. exportEntry.localName = nullptr;
  2543. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);
  2544. }
  2545. else
  2546. {
  2547. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);
  2548. }
  2549. });
  2550. exportEntryList.Clear();
  2551. }
  2552. }
  2553. if (needTerminator != nullptr)
  2554. {
  2555. *needTerminator = true;
  2556. }
  2557. break;
  2558. case tkID:
  2559. {
  2560. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  2561. if (wellKnownPropertyPids.let == pid)
  2562. {
  2563. declarationType = tkLET;
  2564. goto ParseVarDecl;
  2565. }
  2566. if (wellKnownPropertyPids.async == pid && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2567. {
  2568. // In module export statements, async token is only valid if it's followed by function.
  2569. // We need to check here because ParseStatement would think 'async = 20' is a var decl.
  2570. RestorePoint parsedAsync;
  2571. this->GetScanner()->Capture(&parsedAsync);
  2572. this->GetScanner()->Scan();
  2573. if (m_token.tk == tkFUNCTION)
  2574. {
  2575. // Token after async is function, rewind to the async token and let ParseStatement handle it.
  2576. this->GetScanner()->SeekTo(parsedAsync);
  2577. goto ParseFunctionDecl;
  2578. }
  2579. // Token after async is not function, it's a syntax error.
  2580. }
  2581. goto ErrorToken;
  2582. }
  2583. case tkVAR:
  2584. case tkLET:
  2585. case tkCONST:
  2586. {
  2587. declarationType = m_token.tk;
  2588. ParseVarDecl:
  2589. this->GetScanner()->Scan();
  2590. pnode = ParseVariableDeclaration<buildAST>(declarationType, this->GetScanner()->IchMinTok());
  2591. if (buildAST)
  2592. {
  2593. ForEachItemInList(pnode, [&](ParseNodePtr item) {
  2594. if (item->nop == knopAsg)
  2595. {
  2596. Parser::MapBindIdentifier(item, [&](ParseNodePtr subItem)
  2597. {
  2598. AddModuleLocalExportEntry(subItem);
  2599. });
  2600. }
  2601. else
  2602. {
  2603. AddModuleLocalExportEntry(item);
  2604. }
  2605. });
  2606. }
  2607. }
  2608. break;
  2609. case tkFUNCTION:
  2610. case tkCLASS:
  2611. {
  2612. ParseFunctionDecl:
  2613. pnode = ParseStatement<buildAST>();
  2614. if (buildAST)
  2615. {
  2616. IdentPtr localName;
  2617. if (pnode->nop == knopClassDecl)
  2618. {
  2619. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  2620. pnodeClass->pnodeDeclName->sym->SetIsModuleExportStorage(true);
  2621. localName = pnodeClass->pnodeName->pid;
  2622. }
  2623. else
  2624. {
  2625. Assert(pnode->nop == knopFncDecl);
  2626. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  2627. pnodeFnc->GetFuncSymbol()->SetIsModuleExportStorage(true);
  2628. localName = pnodeFnc->pid;
  2629. }
  2630. Assert(localName != nullptr);
  2631. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2632. }
  2633. }
  2634. break;
  2635. case tkDEFAULT:
  2636. {
  2637. pnode = ParseDefaultExportClause<buildAST>();
  2638. }
  2639. break;
  2640. default:
  2641. {
  2642. ErrorToken:
  2643. Error(ERRsyntax);
  2644. }
  2645. }
  2646. return pnode;
  2647. }
  2648. /***************************************************************************
  2649. Parse an expression term.
  2650. ***************************************************************************/
  2651. template<bool buildAST>
  2652. ParseNodePtr Parser::ParseTerm(BOOL fAllowCall,
  2653. LPCOLESTR pNameHint,
  2654. uint32 *pHintLength,
  2655. uint32 *pShortNameOffset,
  2656. _Inout_opt_ IdentToken* pToken /*= nullptr*/,
  2657. bool fUnaryOrParen /*= false*/,
  2658. BOOL fCanAssignToCall /*= TRUE*/,
  2659. _Out_opt_ BOOL* pfCanAssign /*= nullptr*/,
  2660. _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/,
  2661. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/,
  2662. _Inout_opt_ charcount_t *plastRParen /*= nullptr*/)
  2663. {
  2664. ParseNodePtr pnode = nullptr;
  2665. PidRefStack *savedTopAsyncRef = nullptr;
  2666. charcount_t ichMin = 0;
  2667. charcount_t ichLim = 0;
  2668. size_t iecpMin = 0;
  2669. size_t iecpLim = 0;
  2670. size_t iuMin;
  2671. IdentToken term;
  2672. BOOL fInNew = FALSE;
  2673. BOOL fCanAssign = TRUE;
  2674. bool isAsyncExpr = false;
  2675. bool isLambdaExpr = false;
  2676. bool isSpecialName = false;
  2677. IdentPtr pid = nullptr;
  2678. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  2679. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);
  2680. switch (m_token.tk)
  2681. {
  2682. case tkID:
  2683. {
  2684. pid = m_token.GetIdentifier(this->GetHashTbl());
  2685. ichMin = this->GetScanner()->IchMinTok();
  2686. iecpMin = this->GetScanner()->IecpMinTok();
  2687. ichLim = this->GetScanner()->IchLimTok();
  2688. iecpLim = this->GetScanner()->IecpLimTok();
  2689. if (pid == wellKnownPropertyPids.async &&
  2690. m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2691. {
  2692. isAsyncExpr = true;
  2693. }
  2694. // Put this into a block to avoid previousAwaitIsKeyword being not initialized after jump to LIdentifier
  2695. {
  2696. bool previousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(isAsyncExpr);
  2697. this->GetScanner()->Scan();
  2698. this->GetScanner()->SetAwaitIsKeywordRegion(previousAwaitIsKeyword);
  2699. }
  2700. // We search for an Async expression (a function declaration or an async lambda expression)
  2701. if (isAsyncExpr && !this->GetScanner()->FHadNewLine())
  2702. {
  2703. if (m_token.tk == tkFUNCTION)
  2704. {
  2705. goto LFunction;
  2706. }
  2707. else if (m_token.tk == tkID || m_token.tk == tkAWAIT)
  2708. {
  2709. isLambdaExpr = true;
  2710. goto LFunction;
  2711. }
  2712. else if (m_token.tk == tkLParen)
  2713. {
  2714. // This is potentially an async arrow function. Save the state of the async references
  2715. // in case it needs to be restored. (Note that the case of a single parameter with no ()'s
  2716. // is detected upstream and need not be handled here.)
  2717. savedTopAsyncRef = pid->GetTopRef();
  2718. }
  2719. }
  2720. CheckArgumentsUse(pid, GetCurrentFunctionNode());
  2721. // Assume this pid is not special - overwrite when we parse a special name
  2722. isSpecialName = false;
  2723. LIdentifier:
  2724. PidRefStack * ref = nullptr;
  2725. // Don't push a reference if this is a single lambda parameter, because we'll reparse with
  2726. // a correct function ID.
  2727. if (m_token.tk != tkDArrow)
  2728. {
  2729. ref = this->PushPidRef(pid);
  2730. }
  2731. if (buildAST)
  2732. {
  2733. if (isSpecialName)
  2734. {
  2735. pnode = CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  2736. }
  2737. else
  2738. {
  2739. pnode = CreateNameNode(pid, ref, ichMin, ichLim);
  2740. }
  2741. }
  2742. else
  2743. {
  2744. // Remember the identifier start and end in case it turns out to be a statement label.
  2745. term.tk = tkID;
  2746. term.pid = pid; // Record the identifier for detection of eval
  2747. term.ichMin = static_cast<charcount_t>(iecpMin);
  2748. term.ichLim = static_cast<charcount_t>(iecpLim);
  2749. }
  2750. break;
  2751. }
  2752. case tkSUPER:
  2753. ichMin = this->GetScanner()->IchMinTok();
  2754. iecpMin = this->GetScanner()->IecpMinTok();
  2755. ichLim = this->GetScanner()->IchLimTok();
  2756. iecpLim = this->GetScanner()->IecpLimTok();
  2757. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2758. {
  2759. goto LUnknown;
  2760. }
  2761. this->GetScanner()->Scan();
  2762. pid = ParseSuper<buildAST>(!!fAllowCall);
  2763. isSpecialName = true;
  2764. // Super reference and super call need to push a pid ref to 'this' even when not building an AST
  2765. ReferenceSpecialName(wellKnownPropertyPids._this, ichMin, ichLim);
  2766. // Super call needs to reference 'new.target'
  2767. if (pid == wellKnownPropertyPids._superConstructor)
  2768. {
  2769. ReferenceSpecialName(wellKnownPropertyPids._newTarget, ichMin, ichLim);
  2770. }
  2771. goto LIdentifier;
  2772. case tkTHIS:
  2773. ichMin = this->GetScanner()->IchMinTok();
  2774. iecpMin = this->GetScanner()->IecpMinTok();
  2775. ichLim = this->GetScanner()->IchLimTok();
  2776. iecpLim = this->GetScanner()->IecpLimTok();
  2777. pid = wellKnownPropertyPids._this;
  2778. this->GetScanner()->Scan();
  2779. isSpecialName = true;
  2780. goto LIdentifier;
  2781. case tkLParen:
  2782. {
  2783. ichMin = this->GetScanner()->IchMinTok();
  2784. iuMin = this->GetScanner()->IecpMinTok();
  2785. // If we are undeferring a function which has deferred stubs, we can check to see if the next deferred stub
  2786. // is a lambda at the current character. If it is, we know this LParen is the beginning of a lambda nested
  2787. // function and we can avoid parsing the next series of tokens as a parenthetical expression and reparsing
  2788. // after finding the => token.
  2789. if (buildAST && m_currDeferredStub != nullptr && GetCurrentFunctionNode() != nullptr && GetCurrentFunctionNode()->nestedCount < m_currDeferredStubCount)
  2790. {
  2791. DeferredFunctionStub* stub = m_currDeferredStub + GetCurrentFunctionNode()->nestedCount;
  2792. if (stub->ichMin == ichMin)
  2793. {
  2794. Assert((stub->fncFlags & kFunctionIsLambda) == kFunctionIsLambda);
  2795. pnode = ParseFncDeclCheckScope<true>(fFncLambda);
  2796. break;
  2797. }
  2798. }
  2799. this->GetScanner()->Scan();
  2800. if (m_token.tk == tkRParen)
  2801. {
  2802. // Empty parens can only be legal as an empty parameter list to a lambda declaration.
  2803. // We're in a lambda if the next token is =>.
  2804. fAllowCall = FALSE;
  2805. this->GetScanner()->Scan();
  2806. // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error
  2807. if (!IsDoingFastScan() && (m_token.tk != tkDArrow || this->GetScanner()->FHadNewLine()))
  2808. {
  2809. Error(ERRValidIfFollowedBy, _u("Lambda parameter list"), _u("'=>' on the same line"));
  2810. }
  2811. if (buildAST)
  2812. {
  2813. pnode = CreateNodeForOpT<knopEmpty>();
  2814. }
  2815. break;
  2816. }
  2817. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  2818. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  2819. // up function ID's.
  2820. uint saveNextBlockId = m_nextBlockId;
  2821. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  2822. GetCurrentBlock()->blockId = m_nextBlockId++;
  2823. AutoDeferErrorsRestore deferErrorRestore(this);
  2824. this->m_funcParenExprDepth++;
  2825. pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen);
  2826. this->m_funcParenExprDepth--;
  2827. if (buildAST && plastRParen)
  2828. {
  2829. *plastRParen = this->GetScanner()->IchLimTok();
  2830. }
  2831. ChkCurTok(tkRParen, ERRnoRparen);
  2832. GetCurrentBlock()->blockId = saveCurrBlockId;
  2833. if (m_token.tk == tkDArrow)
  2834. {
  2835. // We're going to rewind and reinterpret the expression as a parameter list.
  2836. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  2837. m_nextBlockId = saveNextBlockId;
  2838. }
  2839. else
  2840. {
  2841. // Emit a deferred ... error if one was parsed.
  2842. if (m_deferEllipsisError)
  2843. {
  2844. this->GetScanner()->SeekTo(m_deferEllipsisErrorLoc);
  2845. Error(ERRInvalidSpreadUse);
  2846. }
  2847. else if (m_deferCommaError)
  2848. {
  2849. // Emit a comma error if that was deferred.
  2850. this->GetScanner()->SeekTo(m_deferCommaErrorLoc);
  2851. Error(ERRsyntax);
  2852. }
  2853. }
  2854. break;
  2855. }
  2856. case tkIntCon:
  2857. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2858. {
  2859. Error(ERRES5NoOctal);
  2860. }
  2861. if (buildAST)
  2862. {
  2863. pnode = CreateIntNode(m_token.GetLong());
  2864. }
  2865. fCanAssign = FALSE;
  2866. this->GetScanner()->Scan();
  2867. break;
  2868. case tkFltCon:
  2869. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2870. {
  2871. Error(ERRES5NoOctal);
  2872. }
  2873. if (buildAST)
  2874. {
  2875. ParseNodeFloat * pnodeFloat;
  2876. pnode = pnodeFloat = CreateNodeForOpT<knopFlt>();
  2877. pnodeFloat->dbl = m_token.GetDouble();
  2878. pnodeFloat->maybeInt = m_token.GetDoubleMayBeInt();
  2879. }
  2880. fCanAssign = FALSE;
  2881. this->GetScanner()->Scan();
  2882. break;
  2883. case tkStrCon:
  2884. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2885. {
  2886. Error(ERRES5NoOctal);
  2887. }
  2888. if (buildAST)
  2889. {
  2890. pnode = CreateStrNode(m_token.GetStr());
  2891. }
  2892. else
  2893. {
  2894. // Subtract the string literal length from the total char count for the purpose
  2895. // of deciding whether to defer parsing and byte code generation.
  2896. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok());
  2897. }
  2898. fCanAssign = FALSE;
  2899. this->GetScanner()->Scan();
  2900. break;
  2901. case tkTRUE:
  2902. if (buildAST)
  2903. {
  2904. pnode = CreateNodeForOpT<knopTrue>();
  2905. }
  2906. fCanAssign = FALSE;
  2907. this->GetScanner()->Scan();
  2908. break;
  2909. case tkFALSE:
  2910. if (buildAST)
  2911. {
  2912. pnode = CreateNodeForOpT<knopFalse>();
  2913. }
  2914. fCanAssign = FALSE;
  2915. this->GetScanner()->Scan();
  2916. break;
  2917. case tkNULL:
  2918. if (buildAST)
  2919. {
  2920. pnode = CreateNodeForOpT<knopNull>();
  2921. }
  2922. fCanAssign = FALSE;
  2923. this->GetScanner()->Scan();
  2924. break;
  2925. case tkDiv:
  2926. case tkAsgDiv:
  2927. pnode = ParseRegExp<buildAST>();
  2928. fCanAssign = FALSE;
  2929. this->GetScanner()->Scan();
  2930. break;
  2931. case tkNEW:
  2932. {
  2933. ichMin = this->GetScanner()->IchMinTok();
  2934. iecpMin = this->GetScanner()->IecpMinTok();
  2935. this->GetScanner()->Scan();
  2936. if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2937. {
  2938. pid = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);
  2939. ichLim = this->GetScanner()->IchLimTok();
  2940. iecpLim = this->GetScanner()->IecpLimTok();
  2941. this->GetScanner()->Scan();
  2942. isSpecialName = true;
  2943. goto LIdentifier;
  2944. }
  2945. else
  2946. {
  2947. ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset, nullptr, false, TRUE, nullptr, nullptr, nullptr, plastRParen);
  2948. if (buildAST)
  2949. {
  2950. pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);
  2951. pnode->ichMin = ichMin;
  2952. }
  2953. fInNew = TRUE;
  2954. fCanAssign = FALSE;
  2955. }
  2956. break;
  2957. }
  2958. case tkLBrack:
  2959. {
  2960. ichMin = this->GetScanner()->IchMinTok();
  2961. this->GetScanner()->Scan();
  2962. pnode = ParseArrayLiteral<buildAST>();
  2963. if (buildAST)
  2964. {
  2965. pnode->ichMin = ichMin;
  2966. pnode->ichLim = this->GetScanner()->IchLimTok();
  2967. }
  2968. if (this->m_arrayDepth == 0)
  2969. {
  2970. Assert(this->GetScanner()->IchLimTok() - ichMin > m_funcInArray);
  2971. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - ichMin - this->m_funcInArray);
  2972. this->m_funcInArray = 0;
  2973. this->m_funcInArrayDepth = 0;
  2974. }
  2975. ChkCurTok(tkRBrack, ERRnoRbrack);
  2976. if (!IsES6DestructuringEnabled())
  2977. {
  2978. fCanAssign = FALSE;
  2979. }
  2980. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2981. {
  2982. *pfLikelyPattern = TRUE;
  2983. }
  2984. break;
  2985. }
  2986. case tkLCurly:
  2987. {
  2988. ichMin = this->GetScanner()->IchMinTok();
  2989. this->GetScanner()->ScanForcingPid();
  2990. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);
  2991. if (buildAST)
  2992. {
  2993. pnode = CreateUniNode(knopObject, pnodeMemberList);
  2994. pnode->ichMin = ichMin;
  2995. pnode->ichLim = this->GetScanner()->IchLimTok();
  2996. }
  2997. ChkCurTok(tkRCurly, ERRnoRcurly);
  2998. if (!IsES6DestructuringEnabled())
  2999. {
  3000. fCanAssign = FALSE;
  3001. }
  3002. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  3003. {
  3004. *pfLikelyPattern = TRUE;
  3005. }
  3006. break;
  3007. }
  3008. case tkFUNCTION:
  3009. {
  3010. LFunction:
  3011. if (m_grfscr & fscrDeferredFncExpression)
  3012. {
  3013. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  3014. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  3015. // first time we see it.
  3016. //
  3017. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  3018. // token of the source code of the function may not a 'function' token though, so we still need to reset this flag
  3019. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  3020. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  3021. m_grfscr &= ~fscrDeferredFncExpression;
  3022. }
  3023. ushort flags = fFncNoFlgs;
  3024. if (isLambdaExpr)
  3025. {
  3026. flags |= fFncLambda;
  3027. }
  3028. if (isAsyncExpr)
  3029. {
  3030. flags |= fFncAsync;
  3031. }
  3032. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::Disallowed, pNameHint, /* needsPIDOnRCurlyScan */ false, fUnaryOrParen);
  3033. if (isAsyncExpr)
  3034. {
  3035. pnode->AsParseNodeFnc()->cbStringMin = iecpMin;
  3036. }
  3037. fCanAssign = FALSE;
  3038. break;
  3039. }
  3040. case tkCLASS:
  3041. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  3042. {
  3043. pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);
  3044. }
  3045. else
  3046. {
  3047. goto LUnknown;
  3048. }
  3049. fCanAssign = FALSE;
  3050. break;
  3051. case tkStrTmplBasic:
  3052. case tkStrTmplBegin:
  3053. pnode = ParseStringTemplateDecl<buildAST>(nullptr);
  3054. fCanAssign = FALSE;
  3055. break;
  3056. case tkIMPORT:
  3057. if (m_scriptContext->GetConfig()->IsES6ModuleEnabled() && m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  3058. {
  3059. this->GetScanner()->Scan();
  3060. ChkCurTokNoScan(tkLParen, ERRnoLparen);
  3061. pnode = ParseImportCall<buildAST>();
  3062. }
  3063. else
  3064. {
  3065. goto LUnknown;
  3066. }
  3067. break;
  3068. #if ENABLE_BACKGROUND_PARSING
  3069. case tkCASE:
  3070. {
  3071. if (!m_doingFastScan)
  3072. {
  3073. goto LUnknown;
  3074. }
  3075. ParseNodePtr pnodeUnused;
  3076. pnode = ParseCase<buildAST>(&pnodeUnused);
  3077. break;
  3078. }
  3079. case tkELSE:
  3080. if (!m_doingFastScan)
  3081. {
  3082. goto LUnknown;
  3083. }
  3084. this->GetScanner()->Scan();
  3085. ParseStatement<buildAST>();
  3086. break;
  3087. #endif
  3088. default:
  3089. LUnknown:
  3090. if (m_token.tk == tkNone)
  3091. {
  3092. Error(ERRInvalidIdentifier, m_token.GetIdentifier(this->GetHashTbl())->Psz(), GetTokenString(GetScanner()->GetPrevious()));
  3093. }
  3094. else if (m_token.IsKeyword())
  3095. {
  3096. Error(ERRKeywordAfter, GetTokenString(m_token.tk), GetTokenString(GetScanner()->GetPrevious()));
  3097. }
  3098. else
  3099. {
  3100. Error(ERRTokenAfter, GetTokenString(m_token.tk), GetTokenString(GetScanner()->GetPrevious()));
  3101. }
  3102. break;
  3103. }
  3104. pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, fCanAssignToCall, &fCanAssign, &term, pfIsDotOrIndex);
  3105. if (savedTopAsyncRef != nullptr &&
  3106. this->m_token.tk == tkDArrow)
  3107. {
  3108. // This is an async arrow function; we're going to back up and reparse it.
  3109. // Make sure we don't leave behind a bogus reference to the 'async' identifier.
  3110. for (pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;)
  3111. {
  3112. Assert(pid->GetTopRef() != nullptr);
  3113. pid->RemovePrevPidRef(nullptr);
  3114. }
  3115. }
  3116. // Pass back identifier if requested
  3117. if (pToken && term.tk == tkID)
  3118. {
  3119. *pToken = term;
  3120. }
  3121. if (pfCanAssign)
  3122. {
  3123. *pfCanAssign = fCanAssign;
  3124. }
  3125. return pnode;
  3126. }
  3127. template <bool buildAST>
  3128. ParseNodeRegExp * Parser::ParseRegExp()
  3129. {
  3130. ParseNodeRegExp * pnode = nullptr;
  3131. if (buildAST || IsDoingFastScan())
  3132. {
  3133. this->GetScanner()->RescanRegExp();
  3134. #if ENABLE_BACKGROUND_PARSING
  3135. BOOL saveDeferringAST = this->m_deferringAST;
  3136. if (m_doingFastScan)
  3137. {
  3138. this->m_deferringAST = false;
  3139. }
  3140. #endif
  3141. pnode = CreateNodeForOpT<knopRegExp>();
  3142. pnode->regexPattern = m_token.GetRegex();
  3143. #if ENABLE_BACKGROUND_PARSING
  3144. if (m_doingFastScan)
  3145. {
  3146. this->m_deferringAST = saveDeferringAST;
  3147. this->AddFastScannedRegExpNode(pnode);
  3148. if (!buildAST)
  3149. {
  3150. pnode = nullptr;
  3151. }
  3152. }
  3153. else if (this->IsBackgroundParser())
  3154. {
  3155. Assert(pnode->regexPattern == nullptr);
  3156. this->AddBackgroundRegExpNode(pnode);
  3157. }
  3158. #endif
  3159. }
  3160. else
  3161. {
  3162. this->GetScanner()->RescanRegExpNoAST();
  3163. }
  3164. Assert(m_token.tk == tkRegExp);
  3165. return pnode;
  3166. }
  3167. BOOL Parser::NodeIsEvalName(ParseNodePtr pnode)
  3168. {
  3169. //WOOB 1107758 Special case of indirect eval binds to local scope in standards mode
  3170. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids.eval);
  3171. }
  3172. BOOL Parser::NodeIsSuperName(ParseNodePtr pnode)
  3173. {
  3174. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids._superConstructor);
  3175. }
  3176. BOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)
  3177. {
  3178. return pnode->nop == knopName &&
  3179. pnode->AsParseNodeName()->pid->Cch() == cch &&
  3180. !wmemcmp(pnode->AsParseNodeName()->pid->Psz(), sz, cch);
  3181. }
  3182. BOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)
  3183. {
  3184. for (;;)
  3185. {
  3186. switch (pnode->nop)
  3187. {
  3188. case knopName:
  3189. return (pnode->AsParseNodeName()->pid == pid);
  3190. case knopComma:
  3191. pnode = pnode->AsParseNodeBin()->pnode2;
  3192. break;
  3193. default:
  3194. return FALSE;
  3195. }
  3196. }
  3197. }
  3198. template<bool buildAST>
  3199. ParseNodePtr Parser::ParsePostfixOperators(
  3200. ParseNodePtr pnode,
  3201. BOOL fAllowCall,
  3202. BOOL fInNew,
  3203. BOOL isAsyncExpr,
  3204. BOOL fCanAssignToCallResult,
  3205. BOOL *pfCanAssign,
  3206. _Inout_ IdentToken* pToken,
  3207. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr */)
  3208. {
  3209. uint16 count = 0;
  3210. bool callOfConstants = false;
  3211. if (pfIsDotOrIndex)
  3212. {
  3213. *pfIsDotOrIndex = false;
  3214. }
  3215. for (;;)
  3216. {
  3217. uint16 spreadArgCount = 0;
  3218. switch (m_token.tk)
  3219. {
  3220. case tkLParen:
  3221. {
  3222. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3223. if (fInNew)
  3224. {
  3225. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3226. if (buildAST)
  3227. {
  3228. Assert(pnode->nop == knopNew);
  3229. Assert(pnode->AsParseNodeCall()->pnodeArgs == nullptr);
  3230. pnode->AsParseNodeCall()->pnodeArgs = pnodeArgs;
  3231. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3232. pnode->AsParseNodeCall()->isApplyCall = false;
  3233. pnode->AsParseNodeCall()->isEvalCall = false;
  3234. pnode->AsParseNodeCall()->isSuperCall = false;
  3235. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3236. Assert(!m_hasDestructuringPattern || count > 0);
  3237. pnode->AsParseNodeCall()->argCount = count;
  3238. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3239. pnode->ichLim = this->GetScanner()->IchLimTok();
  3240. }
  3241. else
  3242. {
  3243. pnode = nullptr;
  3244. pToken->tk = tkNone; // This is no longer an identifier
  3245. }
  3246. fInNew = FALSE;
  3247. ChkCurTok(tkRParen, ERRnoRparen);
  3248. }
  3249. else
  3250. {
  3251. if (!fAllowCall)
  3252. {
  3253. return pnode;
  3254. }
  3255. uint saveNextBlockId = m_nextBlockId;
  3256. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  3257. if (isAsyncExpr)
  3258. {
  3259. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  3260. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  3261. // up function ID's.
  3262. GetCurrentBlock()->blockId = m_nextBlockId++;
  3263. }
  3264. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3265. // We used to un-defer a deferred function body here if it was called as part of the expression that declared it.
  3266. // We now detect this case up front in ParseFncDecl, which is cheaper and simpler.
  3267. if (buildAST)
  3268. {
  3269. bool fCallIsEval = false;
  3270. // Detect super()
  3271. if (this->NodeIsSuperName(pnode))
  3272. {
  3273. pnode = CreateSuperCallNode(pnode->AsParseNodeSpecialName(), pnodeArgs);
  3274. Assert(pnode);
  3275. pnode->AsParseNodeSuperCall()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3276. pnode->AsParseNodeSuperCall()->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3277. }
  3278. else
  3279. {
  3280. pnode = CreateCallNode(knopCall, pnode, pnodeArgs);
  3281. Assert(pnode);
  3282. }
  3283. // Detect call to "eval" and record it on the function.
  3284. // Note: we used to leave it up to the byte code generator to detect eval calls
  3285. // at global scope, but now it relies on the flag the parser sets, so set it here.
  3286. if (count > 0 && this->NodeIsEvalName(pnode->AsParseNodeCall()->pnodeTarget))
  3287. {
  3288. this->MarkEvalCaller();
  3289. fCallIsEval = true;
  3290. // Eval may reference any of the special symbols so we need to push refs to them here.
  3291. ReferenceSpecialName(wellKnownPropertyPids._this);
  3292. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3293. ReferenceSpecialName(wellKnownPropertyPids._super);
  3294. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3295. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3296. }
  3297. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3298. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3299. pnode->AsParseNodeCall()->isApplyCall = false;
  3300. pnode->AsParseNodeCall()->isEvalCall = fCallIsEval;
  3301. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3302. Assert(!m_hasDestructuringPattern || count > 0);
  3303. pnode->AsParseNodeCall()->argCount = count;
  3304. pnode->ichLim = this->GetScanner()->IchLimTok();
  3305. }
  3306. else
  3307. {
  3308. pnode = nullptr;
  3309. if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) // Detect eval
  3310. {
  3311. this->MarkEvalCaller();
  3312. ReferenceSpecialName(wellKnownPropertyPids._this);
  3313. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3314. ReferenceSpecialName(wellKnownPropertyPids._super);
  3315. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3316. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3317. }
  3318. pToken->tk = tkNone; // This is no longer an identifier
  3319. }
  3320. ChkCurTok(tkRParen, ERRnoRparen);
  3321. if (isAsyncExpr)
  3322. {
  3323. GetCurrentBlock()->blockId = saveCurrBlockId;
  3324. if (m_token.tk == tkDArrow)
  3325. {
  3326. // We're going to rewind and reinterpret the expression as a parameter list.
  3327. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  3328. m_nextBlockId = saveNextBlockId;
  3329. }
  3330. }
  3331. }
  3332. if (pfCanAssign)
  3333. {
  3334. *pfCanAssign = fCanAssignToCallResult &&
  3335. (m_sourceContextInfo ?
  3336. !PHASE_ON_RAW(Js::EarlyErrorOnAssignToCallPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId) :
  3337. !PHASE_ON1(Js::EarlyErrorOnAssignToCallPhase));
  3338. }
  3339. if (pfIsDotOrIndex)
  3340. {
  3341. *pfIsDotOrIndex = false;
  3342. }
  3343. break;
  3344. }
  3345. case tkLBrack:
  3346. {
  3347. this->GetScanner()->Scan();
  3348. IdentToken tok;
  3349. ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
  3350. if (buildAST)
  3351. {
  3352. AnalysisAssert(pnodeExpr);
  3353. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3354. {
  3355. pnode = CreateSuperReferenceNode(knopIndex, pnode->AsParseNodeSpecialName(), pnodeExpr);
  3356. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3357. }
  3358. else
  3359. {
  3360. pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
  3361. }
  3362. AnalysisAssert(pnode);
  3363. pnode->ichLim = this->GetScanner()->IchLimTok();
  3364. }
  3365. else
  3366. {
  3367. pnode = nullptr;
  3368. pToken->tk = tkNone; // This is no longer an identifier
  3369. }
  3370. ChkCurTok(tkRBrack, ERRnoRbrack);
  3371. if (pfCanAssign)
  3372. {
  3373. *pfCanAssign = TRUE;
  3374. }
  3375. if (pfIsDotOrIndex)
  3376. {
  3377. *pfIsDotOrIndex = true;
  3378. }
  3379. PidRefStack * topPidRef = nullptr;
  3380. if (buildAST)
  3381. {
  3382. if (pnodeExpr && pnodeExpr->nop == knopName)
  3383. {
  3384. topPidRef = pnodeExpr->AsParseNodeName()->pid->GetTopRef();
  3385. }
  3386. }
  3387. else if (tok.tk == tkID)
  3388. {
  3389. topPidRef = tok.pid->GetTopRef();
  3390. }
  3391. if (topPidRef)
  3392. {
  3393. topPidRef->SetIsUsedInLdElem(true);
  3394. }
  3395. if (!buildAST)
  3396. {
  3397. break;
  3398. }
  3399. bool shouldConvertToDot = false;
  3400. if (pnode->AsParseNodeBin()->pnode2->nop == knopStr)
  3401. {
  3402. // if the string is empty or contains escape character, we will not convert them to dot node
  3403. shouldConvertToDot = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch() > 0 && !this->GetScanner()->IsEscapeOnLastTkStrCon();
  3404. }
  3405. if (shouldConvertToDot)
  3406. {
  3407. LPCOLESTR str = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Psz();
  3408. // See if we can convert o["p"] into o.p and o["0"] into o[0] since they're equivalent and the latter forms
  3409. // are faster
  3410. uint32 uintValue;
  3411. if (Js::JavascriptOperators::TryConvertToUInt32(
  3412. str,
  3413. pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch(),
  3414. &uintValue) &&
  3415. !Js::TaggedInt::IsOverflow(uintValue)) // the optimization is not very useful if the number can't be represented as a TaggedInt
  3416. {
  3417. // No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes
  3418. auto intNode = CreateIntNode(uintValue); // implicit conversion from uint32 to int32
  3419. pnode->AsParseNodeBin()->pnode2 = intNode;
  3420. }
  3421. // Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,
  3422. // and since NaN/Infinity is a number it won't kill o.NaN/o.Infinity which would cause a problem
  3423. // if we decide to hoist o.NaN/o.Infinity.
  3424. // We need to keep o["NaN"] and o["+/-Infinity"] as array element access (we don't hoist that but we may hoist field access),
  3425. // so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.
  3426. // We need to follow same logic for strings that convert to a floating point number.
  3427. else
  3428. {
  3429. bool doConvertToProperty = false; // Convert a["x"] -> a.x.
  3430. if (!Parser::IsNaNOrInfinityLiteral<true>(str))
  3431. {
  3432. const OLECHAR* terminalChar;
  3433. double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);
  3434. bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);
  3435. doConvertToProperty = !convertsToFloat;
  3436. }
  3437. if (doConvertToProperty)
  3438. {
  3439. ParseNodeName * pnodeNewExpr = CreateNameNode(pnodeExpr->AsParseNodeStr()->pid);
  3440. pnodeNewExpr->ichMin = pnodeExpr->ichMin;
  3441. pnodeNewExpr->ichLim = pnodeExpr->ichLim;
  3442. pnode->AsParseNodeBin()->pnode2 = pnodeNewExpr;
  3443. pnode->nop = knopDot;
  3444. pnode->grfpn |= PNodeFlags::fpnIndexOperator;
  3445. }
  3446. }
  3447. }
  3448. }
  3449. break;
  3450. case tkDot:
  3451. {
  3452. ParseNodePtr name = nullptr;
  3453. OpCode opCode = knopDot;
  3454. this->GetScanner()->Scan();
  3455. if (!m_token.IsIdentifier())
  3456. {
  3457. //allow reserved words in ES5 mode
  3458. if (!(m_token.IsReservedWord()))
  3459. {
  3460. IdentifierExpectedError(m_token);
  3461. }
  3462. }
  3463. // Note: see comment above about field optimization WRT NaN/Infinity/-Infinity.
  3464. // Convert a.Nan, a.Infinity into a["NaN"], a["Infinity"].
  3465. // We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.
  3466. // Both NaN and Infinity are identifiers.
  3467. else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(this->GetHashTbl())->Psz()))
  3468. {
  3469. opCode = knopIndex;
  3470. }
  3471. if (buildAST)
  3472. {
  3473. if (opCode == knopDot)
  3474. {
  3475. name = CreateNameNode(m_token.GetIdentifier(this->GetHashTbl()));
  3476. }
  3477. else
  3478. {
  3479. Assert(opCode == knopIndex);
  3480. name = CreateStrNode(m_token.GetIdentifier(this->GetHashTbl()));
  3481. }
  3482. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3483. {
  3484. pnode = CreateSuperReferenceNode(opCode, pnode->AsParseNodeSpecialName(), name);
  3485. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3486. }
  3487. else
  3488. {
  3489. pnode = CreateBinNode(opCode, pnode, name);
  3490. }
  3491. }
  3492. else
  3493. {
  3494. pnode = nullptr;
  3495. pToken->tk = tkNone;
  3496. }
  3497. if (pfCanAssign)
  3498. {
  3499. *pfCanAssign = TRUE;
  3500. }
  3501. if (pfIsDotOrIndex)
  3502. {
  3503. *pfIsDotOrIndex = true;
  3504. }
  3505. this->GetScanner()->Scan();
  3506. break;
  3507. }
  3508. case tkStrTmplBasic:
  3509. case tkStrTmplBegin:
  3510. {
  3511. ParseNode* templateNode = nullptr;
  3512. if (pnode != nullptr)
  3513. {
  3514. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3515. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3516. }
  3517. else
  3518. {
  3519. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3520. }
  3521. if (!buildAST)
  3522. {
  3523. pToken->tk = tkNone; // This is no longer an identifier
  3524. }
  3525. pnode = templateNode;
  3526. if (pfCanAssign)
  3527. {
  3528. *pfCanAssign = FALSE;
  3529. }
  3530. if (pfIsDotOrIndex)
  3531. {
  3532. *pfIsDotOrIndex = false;
  3533. }
  3534. break;
  3535. }
  3536. default:
  3537. return pnode;
  3538. }
  3539. }
  3540. }
  3541. /***************************************************************************
  3542. Look for an existing label with the given name.
  3543. ***************************************************************************/
  3544. bool Parser::LabelExists(IdentPtr pid, LabelId* pLabelIdList)
  3545. {
  3546. StmtNest dummy;
  3547. dummy.pLabelId = pLabelIdList;
  3548. dummy.pstmtOuter = m_pstmtCur;
  3549. // Look through each label list for the current stack of statements
  3550. for (StmtNest* pStmt = &dummy; pStmt != nullptr; pStmt = pStmt->pstmtOuter)
  3551. {
  3552. for (LabelId* pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)
  3553. {
  3554. if (pLabelId->pid == pid)
  3555. return true;
  3556. }
  3557. }
  3558. return false;
  3559. }
  3560. // Currently only ints and floats are treated as constants in function call
  3561. // TODO: Check if we need for other constants as well
  3562. BOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)
  3563. {
  3564. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3565. {
  3566. return TRUE;
  3567. }
  3568. if (pnode->nop == knopFlt)
  3569. {
  3570. return TRUE;
  3571. }
  3572. return FALSE;
  3573. }
  3574. /***************************************************************************
  3575. Parse a list of arguments.
  3576. ***************************************************************************/
  3577. template<bool buildAST>
  3578. ParseNodePtr Parser::ParseArgList(bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)
  3579. {
  3580. ParseNodePtr pnodeArg;
  3581. ParseNodePtr pnodeList = nullptr;
  3582. ParseNodePtr *lastNodeRef = nullptr;
  3583. // Check for an empty list
  3584. Assert(m_token.tk == tkLParen);
  3585. if (this->GetScanner()->Scan() == tkRParen)
  3586. {
  3587. return nullptr;
  3588. }
  3589. *pCallOfConstants = true;
  3590. *pSpreadArgCount = 0;
  3591. int count = 0;
  3592. while (true)
  3593. {
  3594. if (count >= Js::Constants::MaxAllowedArgs)
  3595. {
  3596. Error(ERRTooManyArgs);
  3597. }
  3598. // Allow spread in argument lists.
  3599. IdentToken token;
  3600. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */TRUE, NULL, nullptr, nullptr, &token);
  3601. ++count;
  3602. this->MarkEscapingRef(pnodeArg, &token);
  3603. if (buildAST)
  3604. {
  3605. this->CheckArguments(pnodeArg);
  3606. if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))
  3607. {
  3608. *pCallOfConstants = false;
  3609. }
  3610. if (pnodeArg->nop == knopEllipsis)
  3611. {
  3612. (*pSpreadArgCount)++;
  3613. }
  3614. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3615. }
  3616. if (m_token.tk != tkComma)
  3617. {
  3618. break;
  3619. }
  3620. this->GetScanner()->Scan();
  3621. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  3622. {
  3623. break;
  3624. }
  3625. }
  3626. if (pSpreadArgCount != nullptr && (*pSpreadArgCount) > 0) {
  3627. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3628. }
  3629. *pCount = static_cast<uint16>(count);
  3630. if (buildAST)
  3631. {
  3632. Assert(lastNodeRef);
  3633. Assert(*lastNodeRef);
  3634. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3635. }
  3636. return pnodeList;
  3637. }
  3638. // Currently only ints are treated as constants in ArrayLiterals
  3639. BOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)
  3640. {
  3641. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3642. {
  3643. return TRUE;
  3644. }
  3645. return FALSE;
  3646. }
  3647. template<bool buildAST>
  3648. ParseNodeArrLit * Parser::ParseArrayLiteral()
  3649. {
  3650. ParseNodeArrLit * pnode = nullptr;
  3651. bool arrayOfTaggedInts = false;
  3652. bool arrayOfInts = false;
  3653. bool arrayOfNumbers = false;
  3654. bool hasMissingValues = false;
  3655. uint count = 0;
  3656. uint spreadCount = 0;
  3657. ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);
  3658. if (buildAST)
  3659. {
  3660. pnode = CreateNodeForOpT<knopArray>();
  3661. pnode->pnode1 = pnode1;
  3662. pnode->arrayOfTaggedInts = arrayOfTaggedInts;
  3663. pnode->arrayOfInts = arrayOfInts;
  3664. pnode->arrayOfNumbers = arrayOfNumbers;
  3665. pnode->hasMissingValues = hasMissingValues;
  3666. pnode->count = count;
  3667. pnode->spreadCount = spreadCount;
  3668. if (pnode->pnode1)
  3669. {
  3670. this->CheckArguments(pnode->pnode1);
  3671. }
  3672. }
  3673. return pnode;
  3674. }
  3675. /***************************************************************************
  3676. Create an ArrayLiteral node
  3677. Parse a list of array elements. [ a, b, , c, ]
  3678. ***************************************************************************/
  3679. template<bool buildAST>
  3680. ParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)
  3681. {
  3682. ParseNodePtr pnodeArg = nullptr;
  3683. ParseNodePtr pnodeList = nullptr;
  3684. ParseNodePtr *lastNodeRef = nullptr;
  3685. *count = 0;
  3686. // Check for an empty list
  3687. if (tkRBrack == m_token.tk)
  3688. {
  3689. return nullptr;
  3690. }
  3691. this->m_arrayDepth++;
  3692. bool arrayOfTaggedInts = buildAST;
  3693. bool arrayOfInts = buildAST;
  3694. bool arrayOfNumbers = buildAST;
  3695. bool arrayOfVarInts = false;
  3696. bool hasMissingValues = false;
  3697. for (;;)
  3698. {
  3699. (*count)++;
  3700. if (tkComma == m_token.tk || tkRBrack == m_token.tk)
  3701. {
  3702. hasMissingValues = true;
  3703. arrayOfTaggedInts = false;
  3704. arrayOfInts = false;
  3705. arrayOfNumbers = false;
  3706. if (buildAST)
  3707. {
  3708. pnodeArg = CreateNodeForOpT<knopEmpty>();
  3709. }
  3710. }
  3711. else
  3712. {
  3713. // Allow Spread in array literals.
  3714. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  3715. if (buildAST)
  3716. {
  3717. if (pnodeArg->nop == knopEllipsis)
  3718. {
  3719. (*spreadCount)++;
  3720. }
  3721. this->CheckArguments(pnodeArg);
  3722. }
  3723. }
  3724. #if DEBUG
  3725. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))
  3726. {
  3727. Error(ERRsyntax);
  3728. }
  3729. #endif
  3730. if (buildAST)
  3731. {
  3732. if (arrayOfNumbers)
  3733. {
  3734. if (pnodeArg->nop != knopInt)
  3735. {
  3736. arrayOfTaggedInts = false;
  3737. if (pnodeArg->nop != knopFlt)
  3738. {
  3739. // Not an array of constants.
  3740. arrayOfInts = false;
  3741. arrayOfNumbers = false;
  3742. }
  3743. else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->AsParseNodeFloat()->dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->AsParseNodeFloat()->dbl) || pnodeArg->AsParseNodeFloat()->dbl == -2147483648.0))
  3744. {
  3745. // We've seen nothing but ints, and this is a uint32 but not an int32.
  3746. // Unless we see an actual float at some point, we want an array of vars
  3747. // so we can work with tagged ints.
  3748. arrayOfVarInts = true;
  3749. }
  3750. else
  3751. {
  3752. // Not an int array, but it may still be a float array.
  3753. arrayOfInts = false;
  3754. }
  3755. }
  3756. else
  3757. {
  3758. if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->AsParseNodeInt()->lw))
  3759. {
  3760. arrayOfInts = false;
  3761. }
  3762. if (Js::TaggedInt::IsOverflow(pnodeArg->AsParseNodeInt()->lw))
  3763. {
  3764. arrayOfTaggedInts = false;
  3765. }
  3766. }
  3767. }
  3768. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3769. }
  3770. if (tkComma != m_token.tk)
  3771. {
  3772. break;
  3773. }
  3774. this->GetScanner()->Scan();
  3775. if (tkRBrack == m_token.tk)
  3776. {
  3777. break;
  3778. }
  3779. }
  3780. if (spreadCount != nullptr && *spreadCount > 0) {
  3781. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3782. }
  3783. if (buildAST)
  3784. {
  3785. Assert(lastNodeRef);
  3786. Assert(*lastNodeRef);
  3787. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3788. if (arrayOfVarInts && arrayOfInts)
  3789. {
  3790. arrayOfInts = false;
  3791. arrayOfNumbers = false;
  3792. }
  3793. *pArrayOfTaggedInts = arrayOfTaggedInts;
  3794. *pArrayOfInts = arrayOfInts;
  3795. *pArrayOfNumbers = arrayOfNumbers;
  3796. *pHasMissingValues = hasMissingValues;
  3797. }
  3798. this->m_arrayDepth--;
  3799. return pnodeList;
  3800. }
  3801. Parser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)
  3802. {
  3803. Assert(pAllocator);
  3804. return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);
  3805. }
  3806. template<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)
  3807. {
  3808. this->GetScanner()->Scan();
  3809. ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);
  3810. if (buildAST)
  3811. {
  3812. *ppnodeName = CreateUniNode(knopComputedName, pnodeNameExpr, pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);
  3813. }
  3814. if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))
  3815. {
  3816. *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);
  3817. }
  3818. ChkCurTokNoScan(tkRBrack, ERRnoRbrack);
  3819. }
  3820. /***************************************************************************
  3821. Parse a list of object set/get members, e.g.:
  3822. { get foo(){ ... }, set bar(arg) { ... } }
  3823. ***************************************************************************/
  3824. template<bool buildAST>
  3825. ParseNodeBin * Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint, size_t iecpMin, charcount_t ichMin)
  3826. {
  3827. ParseNodePtr pnodeName = nullptr;
  3828. Assert(nop == knopGetMember || nop == knopSetMember);
  3829. Assert(ppNameHint);
  3830. IdentPtr pid = nullptr;
  3831. bool isComputedName = false;
  3832. *ppNameHint = nullptr;
  3833. switch (m_token.tk)
  3834. {
  3835. default:
  3836. if (!m_token.IsReservedWord())
  3837. {
  3838. Error(ERRnoMemberIdent);
  3839. }
  3840. // fall through
  3841. case tkID:
  3842. pid = m_token.GetIdentifier(this->GetHashTbl());
  3843. *ppNameHint = pid->Psz();
  3844. if (buildAST)
  3845. {
  3846. pnodeName = CreateStrNode(pid);
  3847. }
  3848. break;
  3849. case tkStrCon:
  3850. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3851. {
  3852. Error(ERRES5NoOctal);
  3853. }
  3854. pid = m_token.GetStr();
  3855. *ppNameHint = pid->Psz();
  3856. if (buildAST)
  3857. {
  3858. pnodeName = CreateStrNode(pid);
  3859. }
  3860. break;
  3861. case tkIntCon:
  3862. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3863. {
  3864. Error(ERRES5NoOctal);
  3865. }
  3866. pid = this->GetScanner()->PidFromLong(m_token.GetLong());
  3867. if (buildAST)
  3868. {
  3869. pnodeName = CreateStrNode(pid);
  3870. }
  3871. break;
  3872. case tkFltCon:
  3873. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3874. {
  3875. Error(ERRES5NoOctal);
  3876. }
  3877. pid = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  3878. if (buildAST)
  3879. {
  3880. pnodeName = CreateStrNode(pid);
  3881. }
  3882. break;
  3883. case tkLBrack:
  3884. // Computed property name: get|set [expr] () { }
  3885. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3886. {
  3887. Error(ERRnoMemberIdent);
  3888. }
  3889. LPCOLESTR emptyHint = nullptr;
  3890. uint32 offset = 0;
  3891. ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);
  3892. isComputedName = true;
  3893. break;
  3894. }
  3895. MemberType memberType;
  3896. ushort flags = fFncMethod | fFncNoName;
  3897. if (nop == knopGetMember)
  3898. {
  3899. memberType = MemberTypeGetter;
  3900. flags |= fFncNoArg;
  3901. }
  3902. else
  3903. {
  3904. Assert(nop == knopSetMember);
  3905. memberType = MemberTypeSetter;
  3906. flags |= fFncOneArg;
  3907. }
  3908. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::PropertyAllowed, *ppNameHint,
  3909. /*needsPIDOnRCurlyScan*/ false);
  3910. pnodeFnc->cbStringMin = iecpMin;
  3911. if (isComputedName)
  3912. {
  3913. pnodeFnc->SetHasComputedName();
  3914. }
  3915. pnodeFnc->SetHasHomeObj();
  3916. pnodeFnc->SetIsAccessor();
  3917. if (buildAST)
  3918. {
  3919. return CreateBinNode(nop, pnodeName, pnodeFnc);
  3920. }
  3921. else
  3922. {
  3923. return nullptr;
  3924. }
  3925. }
  3926. /***************************************************************************
  3927. Parse a list of object members. e.g. { x:foo, 'y me':bar }
  3928. ***************************************************************************/
  3929. template<bool buildAST>
  3930. ParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)
  3931. {
  3932. ParseNodeBin * pnodeArg = nullptr;
  3933. ParseNodePtr pnodeEllipsis = nullptr;
  3934. ParseNodePtr pnodeName = nullptr;
  3935. ParseNodePtr pnodeList = nullptr;
  3936. ParseNodePtr *lastNodeRef = nullptr;
  3937. LPCOLESTR pFullNameHint = nullptr; // A calculated full name
  3938. uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;
  3939. uint32 shortNameOffset = 0;
  3940. bool isProtoDeclared = false;
  3941. bool seenRest = false;
  3942. // we get declaration tkLCurly - when the possible object pattern found under the expression.
  3943. bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();
  3944. // Check for an empty list
  3945. if (tkRCurly == m_token.tk)
  3946. {
  3947. return nullptr;
  3948. }
  3949. ArenaAllocator tempAllocator(_u("MemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  3950. bool hasDeferredInitError = false;
  3951. for (;;)
  3952. {
  3953. bool isComputedName = false;
  3954. #if DEBUG
  3955. if ((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(this->GetScanner()->IsDoubleQuoteOnLastTkStrCon())))
  3956. {
  3957. Error(ERRsyntax);
  3958. }
  3959. #endif
  3960. bool isAsyncMethod = false;
  3961. charcount_t ichMin = this->GetScanner()->IchMinTok();
  3962. size_t iecpMin = this->GetScanner()->IecpMinTok();
  3963. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  3964. {
  3965. RestorePoint parsedAsync;
  3966. this->GetScanner()->Capture(&parsedAsync);
  3967. ichMin = this->GetScanner()->IchMinTok();
  3968. iecpMin = this->GetScanner()->IecpMinTok();
  3969. this->GetScanner()->ScanForcingPid();
  3970. if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || this->GetScanner()->FHadNewLine() || m_token.tk == tkComma)
  3971. {
  3972. this->GetScanner()->SeekTo(parsedAsync);
  3973. }
  3974. else
  3975. {
  3976. isAsyncMethod = true;
  3977. }
  3978. }
  3979. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  3980. m_token.tk == tkStar;
  3981. ushort fncDeclFlags = fFncNoName | fFncMethod;
  3982. if (isGenerator)
  3983. {
  3984. if (isAsyncMethod)
  3985. {
  3986. Error(ERRsyntax);
  3987. }
  3988. // Include star character in the function extents
  3989. ichMin = this->GetScanner()->IchMinTok();
  3990. iecpMin = this->GetScanner()->IecpMinTok();
  3991. this->GetScanner()->ScanForcingPid();
  3992. fncDeclFlags |= fFncGenerator;
  3993. }
  3994. IdentPtr pidHint = nullptr; // A name scoped to current expression
  3995. Token tkHint = m_token;
  3996. charcount_t idHintIchMin = static_cast<charcount_t>(this->GetScanner()->IecpMinTok());
  3997. charcount_t idHintIchLim = static_cast<charcount_t>(this->GetScanner()->IecpLimTok());
  3998. bool wrapInBrackets = false;
  3999. bool seenEllipsis = false;
  4000. switch (m_token.tk)
  4001. {
  4002. default:
  4003. if (!m_token.IsReservedWord())
  4004. {
  4005. Error(ERRnoMemberIdent);
  4006. }
  4007. // allow reserved words
  4008. wrapInBrackets = true;
  4009. // fall-through
  4010. case tkID:
  4011. pidHint = m_token.GetIdentifier(this->GetHashTbl());
  4012. if (buildAST)
  4013. {
  4014. pnodeName = CreateStrNode(pidHint);
  4015. }
  4016. break;
  4017. case tkStrCon:
  4018. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4019. {
  4020. Error(ERRES5NoOctal);
  4021. }
  4022. wrapInBrackets = true;
  4023. pidHint = m_token.GetStr();
  4024. if (buildAST)
  4025. {
  4026. pnodeName = CreateStrNode(pidHint);
  4027. }
  4028. break;
  4029. case tkIntCon:
  4030. // Object initializers with numeric labels allowed in JS6
  4031. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4032. {
  4033. Error(ERRES5NoOctal);
  4034. }
  4035. pidHint = this->GetScanner()->PidFromLong(m_token.GetLong());
  4036. if (buildAST)
  4037. {
  4038. pnodeName = CreateStrNode(pidHint);
  4039. }
  4040. break;
  4041. case tkFltCon:
  4042. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4043. {
  4044. Error(ERRES5NoOctal);
  4045. }
  4046. pidHint = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  4047. if (buildAST)
  4048. {
  4049. pnodeName = CreateStrNode(pidHint);
  4050. }
  4051. wrapInBrackets = true;
  4052. break;
  4053. case tkLBrack:
  4054. // Computed property name: [expr] : value
  4055. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4056. {
  4057. Error(ERRnoMemberIdent);
  4058. }
  4059. ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4060. isComputedName = true;
  4061. break;
  4062. case tkEllipsis:
  4063. if (CONFIG_FLAG(ES2018ObjectRestSpread))
  4064. {
  4065. seenEllipsis = true;
  4066. }
  4067. else
  4068. {
  4069. Error(ERRnoMemberIdent);
  4070. }
  4071. break;
  4072. }
  4073. if (pFullNameHint == nullptr)
  4074. {
  4075. if (CONFIG_FLAG(UseFullName))
  4076. {
  4077. pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);
  4078. }
  4079. else
  4080. {
  4081. pFullNameHint = pidHint ? pidHint->Psz() : nullptr;
  4082. fullNameHintLength = pidHint ? pidHint->Cch() : 0;
  4083. shortNameOffset = 0;
  4084. }
  4085. }
  4086. RestorePoint atPid;
  4087. // Only move to next token if spread op was not seen
  4088. if (!seenEllipsis)
  4089. {
  4090. this->GetScanner()->Capture(&atPid);
  4091. this->GetScanner()->ScanForcingPid();
  4092. }
  4093. if (isGenerator && m_token.tk != tkLParen)
  4094. {
  4095. Error(ERRnoLparen);
  4096. }
  4097. if (tkColon == m_token.tk)
  4098. {
  4099. // It is a syntax error if the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.
  4100. // Note that previous scan is important because only after that we can determine we have a variable.
  4101. if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)
  4102. {
  4103. if (isProtoDeclared)
  4104. {
  4105. Error(ERRsyntax);
  4106. }
  4107. else
  4108. {
  4109. isProtoDeclared = true;
  4110. }
  4111. }
  4112. this->GetScanner()->Scan();
  4113. ParseNodePtr pnodeExpr = nullptr;
  4114. if (isObjectPattern)
  4115. {
  4116. if (m_token.tk == tkEllipsis)
  4117. {
  4118. Error(ERRUnexpectedEllipsis);
  4119. }
  4120. RestorePoint atExpression;
  4121. if (!buildAST && declarationType == tkLCurly && IsPossiblePatternStart())
  4122. {
  4123. this->GetScanner()->Capture(&atExpression);
  4124. int saveNextBlockId = m_nextBlockId;
  4125. // It is possible that we might encounter the shorthand init error. Lets find that out.
  4126. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  4127. m_hasDeferredShorthandInitError = false;
  4128. IdentToken token;
  4129. BOOL fLikelyPattern = false;
  4130. // First identify that the current expression is indeed the object/array literal. Otherwise we will just use the ParsrExpr to parse that.
  4131. ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false /*fUnaryOrParen*/,
  4132. TRUE, nullptr /*pfCanAssign*/, &fLikelyPattern);
  4133. m_nextBlockId = saveNextBlockId;
  4134. this->GetScanner()->SeekTo(atExpression);
  4135. if (fLikelyPattern)
  4136. {
  4137. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4138. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4139. {
  4140. if (m_token.IsOperator())
  4141. {
  4142. Error(ERRDestructNoOper);
  4143. }
  4144. Error(ERRsyntax);
  4145. }
  4146. }
  4147. else
  4148. {
  4149. if (m_hasDeferredShorthandInitError)
  4150. {
  4151. Error(ERRnoColon);
  4152. }
  4153. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4154. }
  4155. m_hasDeferredShorthandInitError = savedDeferredInitError;
  4156. }
  4157. else
  4158. {
  4159. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4160. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4161. {
  4162. if (m_token.IsOperator())
  4163. {
  4164. Error(ERRDestructNoOper);
  4165. }
  4166. Error(ERRsyntax);
  4167. }
  4168. }
  4169. }
  4170. else
  4171. {
  4172. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4173. if (pnodeExpr && pnodeExpr->nop == knopFncDecl)
  4174. {
  4175. ParseNodeFnc* funcNode = pnodeExpr->AsParseNodeFnc();
  4176. if (isComputedName)
  4177. {
  4178. funcNode->SetHasComputedName();
  4179. }
  4180. funcNode->SetHasHomeObj();
  4181. }
  4182. }
  4183. #if DEBUG
  4184. if ((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))
  4185. {
  4186. Error(ERRsyntax);
  4187. }
  4188. #endif
  4189. if (buildAST)
  4190. {
  4191. pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);
  4192. if (pnodeArg->pnode1->nop == knopStr)
  4193. {
  4194. pnodeArg->pnode1->AsParseNodeStr()->pid->PromoteAssignmentState();
  4195. }
  4196. }
  4197. }
  4198. else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4199. {
  4200. if (isObjectPattern)
  4201. {
  4202. Error(ERRInvalidAssignmentTarget);
  4203. }
  4204. // Shorthand syntax: foo() {} -> foo: function() {}
  4205. // Rewind to the PID and parse a function expression.
  4206. this->GetScanner()->SeekTo(atPid);
  4207. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), SuperRestrictionState::PropertyAllowed, pFullNameHint,
  4208. /*needsPIDOnRCurlyScan*/ false);
  4209. if (isAsyncMethod || isGenerator)
  4210. {
  4211. pnodeFnc->cbStringMin = iecpMin;
  4212. }
  4213. if (isComputedName)
  4214. {
  4215. pnodeFnc->SetHasComputedName();
  4216. pnodeFnc->cbStringMin = iecpMin;
  4217. }
  4218. pnodeFnc->SetHasHomeObj();
  4219. if (buildAST)
  4220. {
  4221. pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFnc);
  4222. }
  4223. }
  4224. else if (seenEllipsis)
  4225. {
  4226. if (!isObjectPattern)
  4227. {
  4228. pnodeEllipsis = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  4229. }
  4230. else
  4231. {
  4232. pnodeEllipsis = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4233. }
  4234. if (buildAST)
  4235. {
  4236. this->CheckArguments(pnodeEllipsis);
  4237. }
  4238. }
  4239. else if (nullptr != pidHint) //It's either tkID/tkStrCon/tkFloatCon/tkIntCon
  4240. {
  4241. Assert(pidHint->Psz() != nullptr);
  4242. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&
  4243. // get/set are only pseudo keywords when they are identifiers (i.e. not strings)
  4244. tkHint.tk == tkID && NextTokenIsPropertyNameStart())
  4245. {
  4246. if (isObjectPattern)
  4247. {
  4248. Error(ERRInvalidAssignmentTarget);
  4249. }
  4250. LPCOLESTR pNameGetOrSet = nullptr;
  4251. OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;
  4252. pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet, iecpMin, ichMin);
  4253. if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->pnode2->nop == knopFncDecl)
  4254. {
  4255. // displays as "get object.funcname" or "set object.funcname"
  4256. uint32 getOrSetOffset = 0;
  4257. LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);
  4258. pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);
  4259. shortNameOffset += getOrSetOffset;
  4260. }
  4261. }
  4262. else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4263. {
  4264. // Shorthand {foo} -> {foo:foo} syntax.
  4265. // {foo = <initializer>} supported only when on object pattern rules are being applied
  4266. if (tkHint.tk != tkID)
  4267. {
  4268. Assert(tkHint.IsReservedWord()
  4269. || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);
  4270. // All keywords are banned in non-strict mode.
  4271. // Future reserved words are banned in strict mode.
  4272. if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))
  4273. {
  4274. IdentifierExpectedError(tkHint);
  4275. }
  4276. }
  4277. if (buildAST)
  4278. {
  4279. CheckArgumentsUse(pidHint, GetCurrentFunctionNode());
  4280. }
  4281. bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;
  4282. // Saving the current state as we may change the isObjectPattern down below.
  4283. bool oldState = isObjectPattern;
  4284. if (couldBeObjectPattern)
  4285. {
  4286. declarationType = tkLCurly;
  4287. isObjectPattern = true;
  4288. // This may be an error but we are deferring for favouring destructuring.
  4289. hasDeferredInitError = true;
  4290. }
  4291. ParseNodePtr pnodeIdent = nullptr;
  4292. if (isObjectPattern)
  4293. {
  4294. this->GetScanner()->SeekTo(atPid);
  4295. pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4296. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4297. {
  4298. if (m_token.IsOperator())
  4299. {
  4300. Error(ERRDestructNoOper);
  4301. }
  4302. Error(ERRsyntax);
  4303. }
  4304. }
  4305. else
  4306. {
  4307. // Add a reference to the hinted name so we can bind it properly.
  4308. PidRefStack *ref = PushPidRef(pidHint);
  4309. if (buildAST)
  4310. {
  4311. pnodeIdent = CreateNameNode(pidHint, ref, idHintIchMin, idHintIchLim);
  4312. }
  4313. }
  4314. if (buildAST)
  4315. {
  4316. pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);
  4317. }
  4318. isObjectPattern = oldState;
  4319. }
  4320. else
  4321. {
  4322. Error(ERRnoColon);
  4323. }
  4324. }
  4325. else
  4326. {
  4327. Error(ERRnoColon);
  4328. }
  4329. if (buildAST)
  4330. {
  4331. if (seenEllipsis)
  4332. {
  4333. Assert(pnodeEllipsis != nullptr);
  4334. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeEllipsis);
  4335. }
  4336. else
  4337. {
  4338. Assert(pnodeArg->pnode2 != nullptr);
  4339. if (pnodeArg->pnode2->nop == knopFncDecl)
  4340. {
  4341. Assert(fullNameHintLength >= shortNameOffset);
  4342. ParseNodeFnc * pnodeFunc = pnodeArg->pnode2->AsParseNodeFnc();
  4343. pnodeFunc->hint = pFullNameHint;
  4344. pnodeFunc->hintLength = fullNameHintLength;
  4345. pnodeFunc->hintOffset = shortNameOffset;
  4346. }
  4347. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  4348. }
  4349. }
  4350. pidHint = nullptr;
  4351. pFullNameHint = nullptr;
  4352. if (tkComma != m_token.tk)
  4353. {
  4354. break;
  4355. }
  4356. this->GetScanner()->ScanForcingPid();
  4357. if (tkRCurly == m_token.tk)
  4358. {
  4359. break;
  4360. }
  4361. if (seenRest) // Rest must be in the last position.
  4362. {
  4363. Error(ERRDestructRestLast);
  4364. }
  4365. }
  4366. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;
  4367. if (buildAST)
  4368. {
  4369. Assert(lastNodeRef);
  4370. Assert(*lastNodeRef);
  4371. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  4372. }
  4373. return pnodeList;
  4374. }
  4375. BOOL Parser::WillDeferParse(Js::LocalFunctionId functionId)
  4376. {
  4377. if ((m_grfscr & fscrWillDeferFncParse) != 0)
  4378. {
  4379. if (m_stoppedDeferredParse)
  4380. {
  4381. return false;
  4382. }
  4383. if (!PHASE_ENABLED_RAW(DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))
  4384. {
  4385. return false;
  4386. }
  4387. if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId)
  4388. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4389. || Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag)
  4390. #endif
  4391. )
  4392. {
  4393. return true;
  4394. }
  4395. #if ENABLE_PROFILE_INFO
  4396. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4397. if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)
  4398. {
  4399. Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);
  4400. return flags != Js::ExecutionFlags_Executed;
  4401. }
  4402. #endif
  4403. #endif
  4404. return true;
  4405. }
  4406. return false;
  4407. }
  4408. //
  4409. // Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred
  4410. // function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.
  4411. //
  4412. BOOL Parser::IsDeferredFnc()
  4413. {
  4414. if (m_grfscr & fscrDeferredFnc)
  4415. {
  4416. m_grfscr &= ~fscrDeferredFnc;
  4417. return true;
  4418. }
  4419. return false;
  4420. }
  4421. template<bool buildAST>
  4422. ParseNode * Parser::ParseFncDeclCheckScope(ushort flags, bool fAllowIn)
  4423. {
  4424. ParseNodeBlock * pnodeFncBlockScope = nullptr;
  4425. ParseNodePtr *ppnodeScopeSave = nullptr;
  4426. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4427. bool fDeclaration = flags & fFncDeclaration;
  4428. bool noStmtContext = false;
  4429. if (fDeclaration)
  4430. {
  4431. noStmtContext = m_pstmtCur->GetNop() != knopBlock;
  4432. if (noStmtContext)
  4433. {
  4434. // We have a function declaration like "if (a) function f() {}". We didn't see
  4435. // a block scope on the way in, so we need to pretend we did. Note that this is a syntax error
  4436. // in strict mode.
  4437. if (!this->FncDeclAllowedWithoutContext(flags))
  4438. {
  4439. Error(ERRsyntax);
  4440. }
  4441. pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  4442. if (buildAST)
  4443. {
  4444. PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);
  4445. }
  4446. }
  4447. }
  4448. ParseNodeFnc * pnodeFnc = ParseFncDeclInternal<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan */ false, /* fUnaryOrParen */ false, noStmtContext, SuperRestrictionState::Disallowed, fAllowIn);
  4449. if (pnodeFncBlockScope)
  4450. {
  4451. Assert(pnodeFncBlockScope->pnodeStmt == nullptr);
  4452. pnodeFncBlockScope->pnodeStmt = pnodeFnc;
  4453. if (buildAST)
  4454. {
  4455. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  4456. }
  4457. FinishParseBlock(pnodeFncBlockScope);
  4458. return pnodeFncBlockScope;
  4459. }
  4460. return pnodeFnc;
  4461. }
  4462. template<bool buildAST>
  4463. ParseNodeFnc * Parser::ParseFncDeclNoCheckScope(ushort flags, SuperRestrictionState::State superRestrictionState, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool fUnaryOrParen, bool fAllowIn)
  4464. {
  4465. Assert((flags & fFncDeclaration) == 0);
  4466. return ParseFncDeclInternal<buildAST>(flags, pNameHint, needsPIDOnRCurlyScan, fUnaryOrParen, /* noStmtContext */ false, superRestrictionState, fAllowIn);
  4467. }
  4468. template<bool buildAST>
  4469. ParseNodeFnc * Parser::ParseFncDeclInternal(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool fUnaryOrParen, bool noStmtContext, SuperRestrictionState::State superRestrictionState, bool fAllowIn)
  4470. {
  4471. ParseNodeFnc * pnodeFnc = nullptr;
  4472. ParseNodePtr *ppnodeVarSave = nullptr;
  4473. bool fDeclaration = flags & fFncDeclaration;
  4474. bool fModule = (flags & fFncModule) != 0;
  4475. bool fLambda = (flags & fFncLambda) != 0;
  4476. charcount_t ichMin = this->GetScanner()->IchMinTok();
  4477. bool wasInDeferredNestedFunc = false;
  4478. uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;
  4479. this->m_tryCatchOrFinallyDepth = 0;
  4480. if (this->m_arrayDepth)
  4481. {
  4482. this->m_funcInArrayDepth++; // Count function depth within array literal
  4483. }
  4484. // Update the count of functions nested in the current parent.
  4485. Assert(m_pnestedCount || !buildAST);
  4486. uint *pnestedCountSave = m_pnestedCount;
  4487. if (buildAST || m_pnestedCount)
  4488. {
  4489. (*m_pnestedCount)++;
  4490. }
  4491. uint scopeCountNoAstSave = m_scopeCountNoAst;
  4492. m_scopeCountNoAst = 0;
  4493. // Create the node.
  4494. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  4495. pnodeFnc->SetDeclaration(fDeclaration);
  4496. pnodeFnc->nestedFuncEscapes = false;
  4497. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  4498. pnodeFnc->cbStringMin = pnodeFnc->cbMin;
  4499. pnodeFnc->functionId = (*m_nextFunctionId)++;
  4500. pnodeFnc->superRestrictionState = superRestrictionState;
  4501. // Push new parser state with this new function node
  4502. AppendFunctionToScopeList(fDeclaration, pnodeFnc);
  4503. // Start the argument list.
  4504. ppnodeVarSave = m_ppnodeVar;
  4505. if (buildAST)
  4506. {
  4507. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  4508. pnodeFnc->columnNumber = CalculateFunctionColumnNumber();
  4509. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  4510. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  4511. m_pCurrentAstSize = &pnodeFnc->astSize;
  4512. }
  4513. else // if !buildAST
  4514. {
  4515. wasInDeferredNestedFunc = m_inDeferredNestedFunc;
  4516. m_inDeferredNestedFunc = true;
  4517. }
  4518. m_pnestedCount = &pnodeFnc->nestedCount;
  4519. AnalysisAssert(pnodeFnc);
  4520. pnodeFnc->SetIsAsync((flags & fFncAsync) != 0);
  4521. pnodeFnc->SetIsLambda(fLambda);
  4522. pnodeFnc->SetIsMethod((flags & fFncMethod) != 0);
  4523. pnodeFnc->SetIsClassMember((flags & fFncClassMember) != 0);
  4524. pnodeFnc->SetIsModule(fModule);
  4525. pnodeFnc->SetIsClassConstructor((flags & fFncClassConstructor) != 0);
  4526. pnodeFnc->SetIsBaseClassConstructor((flags & fFncBaseClassConstructor) != 0);
  4527. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  4528. IdentPtr pFncNamePid = nullptr;
  4529. bool needScanRCurly = true;
  4530. ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule, &pFncNamePid, fAllowIn);
  4531. AddNestedCapturedNames(pnodeFnc);
  4532. AnalysisAssert(pnodeFnc);
  4533. *m_ppnodeVar = nullptr;
  4534. m_ppnodeVar = ppnodeVarSave;
  4535. if (m_currentNodeFunc && (pnodeFnc->CallsEval() || pnodeFnc->ChildCallsEval()))
  4536. {
  4537. GetCurrentFunctionNode()->SetChildCallsEval(true);
  4538. }
  4539. // Lambdas do not have "arguments" and instead capture their parent's
  4540. // binding of "arguments. To ensure the arguments object of the enclosing
  4541. // non-lambda function is loaded propagate the UsesArguments flag up to
  4542. // the parent function
  4543. if (fLambda && (pnodeFnc->UsesArguments() || pnodeFnc->CallsEval()))
  4544. {
  4545. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4546. if (pnodeFncParent != nullptr)
  4547. {
  4548. pnodeFncParent->SetUsesArguments();
  4549. }
  4550. else
  4551. {
  4552. m_UsesArgumentsAtGlobal = true;
  4553. }
  4554. }
  4555. if (needScanRCurly && !fModule)
  4556. {
  4557. // Consume the next token now that we're back in the enclosing function (whose strictness may be
  4558. // different from the function we just finished).
  4559. #if DBG
  4560. bool expectedTokenValid = m_token.tk == tkRCurly;
  4561. AssertMsg(expectedTokenValid, "Invalid token expected for RCurly match");
  4562. #endif
  4563. // The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.
  4564. if (needsPIDOnRCurlyScan)
  4565. {
  4566. this->GetScanner()->ScanForcingPid();
  4567. }
  4568. else
  4569. {
  4570. this->GetScanner()->Scan();
  4571. }
  4572. }
  4573. m_pnestedCount = pnestedCountSave;
  4574. Assert(!buildAST || !wasInDeferredNestedFunc);
  4575. m_inDeferredNestedFunc = wasInDeferredNestedFunc;
  4576. if (this->m_arrayDepth)
  4577. {
  4578. this->m_funcInArrayDepth--;
  4579. if (this->m_funcInArrayDepth == 0)
  4580. {
  4581. // We disable deferred parsing if array literals dominate.
  4582. // But don't do this if the array literal is dominated by function bodies.
  4583. if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)
  4584. {
  4585. // Class member methods have optional separators. We need to check whether we are
  4586. // getting the IchLim of the correct token.
  4587. Assert(this->GetScanner()->m_tkPrevious == tkRCurly && needScanRCurly);
  4588. this->m_funcInArray += this->GetScanner()->IchMinTok() - /*tkRCurly*/ 1 - ichMin;
  4589. }
  4590. else
  4591. {
  4592. this->m_funcInArray += this->GetScanner()->IchLimTok() - ichMin;
  4593. }
  4594. }
  4595. }
  4596. m_scopeCountNoAst = scopeCountNoAstSave;
  4597. if (fDeclaration && !IsStrictMode())
  4598. {
  4599. if (pFncNamePid != nullptr &&
  4600. GetCurrentBlock() &&
  4601. GetCurrentBlock()->blockType == PnodeBlockType::Regular)
  4602. {
  4603. // Add a function-scoped VarDecl with the same name as the function for
  4604. // back compat with pre-ES6 code that declares functions in blocks. The
  4605. // idea is that the last executed declaration wins at the function scope
  4606. // level and we accomplish this by having each block scoped function
  4607. // declaration assign to both the block scoped "let" binding, as well
  4608. // as the function scoped "var" binding.
  4609. ParseNodeVar * vardecl = CreateVarDeclNode(pFncNamePid, STVariable, false, nullptr, false);
  4610. vardecl->isBlockScopeFncDeclVar = true;
  4611. if (GetCurrentFunctionNode() && vardecl->sym->GetIsFormal())
  4612. {
  4613. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4614. }
  4615. }
  4616. }
  4617. if (buildAST && fDeclaration)
  4618. {
  4619. Symbol* funcSym = pnodeFnc->GetFuncSymbol();
  4620. if (funcSym->GetIsFormal())
  4621. {
  4622. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4623. }
  4624. } this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;
  4625. return pnodeFnc;
  4626. }
  4627. bool Parser::FncDeclAllowedWithoutContext(ushort flags)
  4628. {
  4629. // Statement context required for strict mode, async functions, and generators.
  4630. // Note that generators aren't detected yet when this method is called; they're checked elsewhere.
  4631. return !IsStrictMode() && !(flags & fFncAsync);
  4632. }
  4633. uint Parser::CalculateFunctionColumnNumber()
  4634. {
  4635. uint columnNumber;
  4636. charcount_t ichMinTok = this->GetScanner()->IchMinTok();
  4637. charcount_t ichMinLine = this->GetScanner()->IchMinLine();
  4638. if (ichMinTok >= ichMinLine)
  4639. {
  4640. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  4641. columnNumber = ichMinTok - ichMinLine;
  4642. if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == this->GetScanner()->LineCur())
  4643. {
  4644. // Adjust the column if it falls on the first line, where the re-parse is happening.
  4645. columnNumber += m_functionBody->GetRelativeColumnNumber();
  4646. }
  4647. }
  4648. else if (m_currentNodeFunc)
  4649. {
  4650. // For the first line after defer parse, compute the column relative to the column number
  4651. // of the lexically parent function.
  4652. ULONG offsetFromCurrentFunction = ichMinTok - m_currentNodeFunc->ichMin;
  4653. columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  4654. }
  4655. else
  4656. {
  4657. // if there is no current function, lets give a default of 0.
  4658. columnNumber = 0;
  4659. }
  4660. return columnNumber;
  4661. }
  4662. void Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodeFnc * pnodeFnc)
  4663. {
  4664. if (!fDeclaration && m_ppnodeExprScope)
  4665. {
  4666. // We're tracking function expressions separately from declarations in this scope
  4667. // (e.g., inside a catch scope in standards mode).
  4668. Assert(*m_ppnodeExprScope == nullptr);
  4669. *m_ppnodeExprScope = pnodeFnc;
  4670. m_ppnodeExprScope = &pnodeFnc->pnodeNext;
  4671. }
  4672. else
  4673. {
  4674. Assert(*m_ppnodeScope == nullptr);
  4675. *m_ppnodeScope = pnodeFnc;
  4676. m_ppnodeScope = &pnodeFnc->pnodeNext;
  4677. }
  4678. }
  4679. /***************************************************************************
  4680. Parse a function definition.
  4681. ***************************************************************************/
  4682. template<bool buildAST>
  4683. void Parser::ParseFncDeclHelper(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals, IdentPtr* pFncNamePid, bool fAllowIn)
  4684. {
  4685. Assert(pnodeFnc);
  4686. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4687. // is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred
  4688. ParseNodeFnc * pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4689. ParseNodeFnc * pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;
  4690. int32* pAstSizeSave = m_pCurrentAstSize;
  4691. bool fDeclaration = (flags & fFncDeclaration) != 0;
  4692. bool fLambda = (flags & fFncLambda) != 0;
  4693. bool fAsync = (flags & fFncAsync) != 0;
  4694. bool fModule = (flags & fFncModule) != 0;
  4695. bool fDeferred = false;
  4696. StmtNest *pstmtSave;
  4697. bool fFunctionInBlock = false;
  4698. if (buildAST)
  4699. {
  4700. fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&
  4701. (GetCurrentBlockInfo()->pnodeBlock->scope == nullptr ||
  4702. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock);
  4703. }
  4704. // Save the position of the scanner in case we need to inspect the name hint later
  4705. RestorePoint beginNameHint;
  4706. this->GetScanner()->Capture(&beginNameHint);
  4707. ParseNodeBlock * pnodeFncExprScope = nullptr;
  4708. Scope *fncExprScope = nullptr;
  4709. if (!fDeclaration)
  4710. {
  4711. if (!fLambda)
  4712. {
  4713. pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);
  4714. fncExprScope = pnodeFncExprScope->scope;
  4715. }
  4716. // Function expression: push the new function onto the stack now so that the name (if any) will be
  4717. // local to the new function.
  4718. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4719. }
  4720. if (!fLambda && !fModule)
  4721. {
  4722. this->ParseFncName<buildAST>(pnodeFnc, flags, pFncNamePid);
  4723. }
  4724. if (fDeclaration)
  4725. {
  4726. // Declaration statement: push the new function now, after parsing the name, so the name is local to the
  4727. // enclosing function.
  4728. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4729. }
  4730. if (noStmtContext && pnodeFnc->IsGenerator())
  4731. {
  4732. // Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to
  4733. // detect generator.)
  4734. Error(ERRsyntax, pnodeFnc);
  4735. }
  4736. // switch scanner to treat 'yield' as keyword in generator functions
  4737. // or as an identifier in non-generator functions
  4738. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc->IsGenerator());
  4739. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync);
  4740. if (pnodeFnc->IsGenerator())
  4741. {
  4742. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Generator, m_scriptContext);
  4743. }
  4744. if (fncExprScope && pnodeFnc->pnodeName == nullptr)
  4745. {
  4746. FinishParseBlock(pnodeFncExprScope);
  4747. m_nextBlockId--;
  4748. Adelete(&m_nodeAllocator, fncExprScope);
  4749. fncExprScope = nullptr;
  4750. pnodeFncExprScope = nullptr;
  4751. }
  4752. pnodeFnc->scope = fncExprScope;
  4753. // Start a new statement stack.
  4754. bool topLevelStmt =
  4755. buildAST &&
  4756. !fFunctionInBlock &&
  4757. (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);
  4758. pstmtSave = m_pstmtCur;
  4759. SetCurrentStatement(nullptr);
  4760. RestorePoint beginFormals;
  4761. this->GetScanner()->Capture(&beginFormals);
  4762. BOOL fWasAlreadyStrictMode = IsStrictMode();
  4763. BOOL oldStrictMode = this->m_fUseStrictMode;
  4764. if (fLambda)
  4765. {
  4766. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Lambda, m_scriptContext);
  4767. }
  4768. uint uCanDeferSave = m_grfscr & fscrCanDeferFncParse;
  4769. uint uDeferSave = m_grfscr & fscrWillDeferFncParse;
  4770. if (flags & fFncClassMember)
  4771. {
  4772. // Disable deferral on class members or other construct with unusual text bounds
  4773. // as these are usually trivial, and re-parsing is problematic.
  4774. // NOTE: It is probably worth supporting these cases for memory and load-time purposes,
  4775. // especially as they become more and more common.
  4776. m_grfscr &= ~(fscrCanDeferFncParse | fscrWillDeferFncParse);
  4777. }
  4778. bool isTopLevelDeferredFunc = false;
  4779. #if ENABLE_BACKGROUND_PARSING
  4780. struct AutoFastScanFlag {
  4781. bool savedDoingFastScan;
  4782. AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }
  4783. ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }
  4784. Parser *m_parser;
  4785. } flag(this);
  4786. #endif
  4787. bool doParallel = false;
  4788. #if ENABLE_BACKGROUND_PARSING
  4789. bool parallelJobStarted = false;
  4790. #endif
  4791. if (buildAST)
  4792. {
  4793. bool isLikelyIIFE = !fDeclaration && fUnaryOrParen;
  4794. BOOL isDeferredFnc = IsDeferredFnc();
  4795. // These are the conditions that prohibit upfront deferral *and* redeferral.
  4796. isTopLevelDeferredFunc =
  4797. (m_grfscr & fscrCanDeferFncParse)
  4798. && !m_InAsmMode
  4799. // Don't defer a module function wrapper because we need to do export resolution at parse time
  4800. && !fModule;
  4801. pnodeFnc->SetCanBeDeferred(isTopLevelDeferredFunc && ParseNodeFnc::CanBeRedeferred(pnodeFnc->fncFlags));
  4802. // These are heuristic conditions that prohibit upfront deferral but not redeferral.
  4803. isTopLevelDeferredFunc = isTopLevelDeferredFunc && !isDeferredFnc && WillDeferParse(pnodeFnc->functionId) &&
  4804. (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId));
  4805. #if ENABLE_BACKGROUND_PARSING
  4806. if (!fLambda &&
  4807. !isDeferredFnc &&
  4808. !isLikelyIIFE &&
  4809. !this->IsBackgroundParser() &&
  4810. !this->m_doingFastScan &&
  4811. !(pnodeFncSave && m_currDeferredStub) &&
  4812. !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))
  4813. {
  4814. doParallel = DoParallelParse(pnodeFnc);
  4815. if (doParallel)
  4816. {
  4817. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  4818. Assert(bgp);
  4819. if (bgp->HasFailedBackgroundParseItem())
  4820. {
  4821. Error(ERRsyntax);
  4822. }
  4823. doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);
  4824. if (doParallel)
  4825. {
  4826. parallelJobStarted = true;
  4827. this->m_hasParallelJob = true;
  4828. this->m_doingFastScan = true;
  4829. doParallel = FastScanFormalsAndBody();
  4830. if (doParallel)
  4831. {
  4832. // Let the foreground thread take care of marking the limit on the function node,
  4833. // because in some cases this function's caller will want to change that limit,
  4834. // so we don't want the background thread to try and touch it.
  4835. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  4836. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  4837. }
  4838. }
  4839. }
  4840. }
  4841. #endif
  4842. }
  4843. if (!doParallel)
  4844. {
  4845. #if ENABLE_BACKGROUND_PARSING
  4846. // We don't want to, or couldn't, let the main thread scan past this function body, so parse
  4847. // it for real.
  4848. ParseNodeFnc * pnodeRealFnc = pnodeFnc;
  4849. if (parallelJobStarted)
  4850. {
  4851. // We have to deal with a failure to fast-scan the function (due to syntax error? "/"?) when
  4852. // a background thread may already have begun to work on the job. Both threads can't be allowed to
  4853. // operate on the same node.
  4854. pnodeFnc = CreateDummyFuncNode(fDeclaration);
  4855. }
  4856. #endif
  4857. AnalysisAssert(pnodeFnc);
  4858. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  4859. AnalysisAssert(pnodeBlock != nullptr);
  4860. pnodeFnc->pnodeScopes = pnodeBlock;
  4861. m_ppnodeVar = &pnodeFnc->pnodeParams;
  4862. pnodeFnc->pnodeVars = nullptr;
  4863. ParseNodePtr* varNodesList = &pnodeFnc->pnodeVars;
  4864. ParseNodeVar * argNode = nullptr;
  4865. if (!fModule && !fLambda)
  4866. {
  4867. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  4868. m_ppnodeVar = &pnodeFnc->pnodeVars;
  4869. // Create the built-in arguments symbol
  4870. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  4871. // Save the updated var list
  4872. varNodesList = m_ppnodeVar;
  4873. m_ppnodeVar = ppnodeVarSave;
  4874. }
  4875. ParseNodePtr *ppnodeScopeSave = nullptr;
  4876. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4877. ppnodeScopeSave = m_ppnodeScope;
  4878. if (pnodeBlock)
  4879. {
  4880. // This synthetic block scope will contain all the nested scopes.
  4881. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  4882. pnodeBlock->pnodeStmt = pnodeFnc;
  4883. }
  4884. // Keep nested function declarations and expressions in the same list at function scope.
  4885. // (Indicate this by nulling out the current function expressions list.)
  4886. ppnodeExprScopeSave = m_ppnodeExprScope;
  4887. m_ppnodeExprScope = nullptr;
  4888. uint parenExprDepthSave = m_funcParenExprDepth;
  4889. m_funcParenExprDepth = 0;
  4890. if (!skipFormals)
  4891. {
  4892. bool fLambdaParamsSave = m_reparsingLambdaParams;
  4893. if (fLambda)
  4894. {
  4895. m_reparsingLambdaParams = true;
  4896. }
  4897. uint savedStubCount = m_currDeferredStubCount;
  4898. DeferredFunctionStub* savedStub = m_currDeferredStub;
  4899. ShiftCurrDeferredStubToChildFunction(pnodeFnc, pnodeFncParent);
  4900. this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags, isTopLevelDeferredFunc);
  4901. m_currDeferredStub = savedStub;
  4902. m_currDeferredStubCount = savedStubCount;
  4903. m_reparsingLambdaParams = fLambdaParamsSave;
  4904. }
  4905. // Create function body scope
  4906. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  4907. // Set the parameter block's child to the function body block.
  4908. // The pnodeFnc->pnodeScopes list is constructed in such a way that it includes all the scopes in this list.
  4909. // For example if the param scope has one function and body scope has one function then the list will look like below,
  4910. // param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.
  4911. *m_ppnodeScope = pnodeInnerBlock;
  4912. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  4913. // This synthetic block scope will contain all the nested scopes.
  4914. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  4915. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  4916. // DEFER: Begin deferral here (after names are parsed and name nodes created).
  4917. // Create no more AST nodes until we're done.
  4918. // Try to defer this func if all these are true:
  4919. // 0. We are not already in deferred parsing (i.e. buildAST is true)
  4920. // 1. We are not re-parsing a deferred func which is being invoked.
  4921. // 2. Dynamic profile suggests this func can be deferred (and deferred parse is on).
  4922. // 3. This func is top level or defer nested func is on.
  4923. // 4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,
  4924. // or the function is sufficiently long. (I.e., don't defer little nested functions unless we're
  4925. // confident they'll never be executed, because un-deferring nested functions is more expensive.)
  4926. // NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,
  4927. // and we don't want to create function bodies aggressively for little functions.
  4928. // We will also temporarily defer all asm.js functions, except for the asm.js
  4929. // module itself, which we will never defer
  4930. bool strictModeTurnedOn = false;
  4931. if (isTopLevelDeferredFunc &&
  4932. !(this->m_grfscr & fscrEvalCode) &&
  4933. pnodeFnc->IsNested() &&
  4934. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4935. m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&
  4936. #endif
  4937. PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) &&
  4938. (
  4939. !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) ||
  4940. PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId)
  4941. ))
  4942. {
  4943. // Try to scan ahead to the end of the function. If we get there before we've scanned a minimum
  4944. // number of tokens, don't bother deferring, because it's too small.
  4945. if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))
  4946. {
  4947. isTopLevelDeferredFunc = false;
  4948. }
  4949. }
  4950. Scope* paramScope = pnodeFnc->pnodeScopes ? pnodeFnc->pnodeScopes->scope : nullptr;
  4951. if (paramScope != nullptr)
  4952. {
  4953. if (CONFIG_FLAG(ForceSplitScope))
  4954. {
  4955. pnodeFnc->ResetBodyAndParamScopeMerged();
  4956. }
  4957. else if (pnodeFnc->HasNonSimpleParameterList() && pnodeFnc->IsBodyAndParamScopeMerged())
  4958. {
  4959. paramScope->ForEachSymbolUntil([this, paramScope, pnodeFnc](Symbol* sym) {
  4960. if (sym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  4961. {
  4962. // One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.
  4963. pnodeFnc->ResetBodyAndParamScopeMerged();
  4964. return true;
  4965. }
  4966. return false;
  4967. });
  4968. if (pnodeFnc->IsBodyAndParamScopeMerged() && !fDeclaration && pnodeFnc->pnodeName != nullptr)
  4969. {
  4970. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  4971. Symbol* funcSym = pnodeFnc->pnodeName->sym;
  4972. if (funcSym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  4973. {
  4974. // This is a function expression with name captured in the param scope. In non-eval, non-split cases the function
  4975. // name symbol is added to the body scope to make it accessible in the body. But if there is a function or var
  4976. // declaration with the same name in the body then adding to the body will fail. So in this case we have to add
  4977. // the name symbol to the param scope by splitting it.
  4978. pnodeFnc->ResetBodyAndParamScopeMerged();
  4979. }
  4980. }
  4981. }
  4982. }
  4983. // If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.
  4984. // So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice
  4985. // in the same pid ref stack.
  4986. if (paramScope != nullptr && pnodeFnc->IsBodyAndParamScopeMerged())
  4987. {
  4988. paramScope->ForEachSymbol([this](Symbol* paramSym)
  4989. {
  4990. PidRefStack* ref = PushPidRef(paramSym->GetPid());
  4991. ref->SetSym(paramSym);
  4992. });
  4993. }
  4994. AssertMsg(m_funcParenExprDepth == 0, "Paren exprs should have been resolved by the time we finish function formals");
  4995. if (fLambda)
  4996. {
  4997. #ifdef ASMJS_PLAT
  4998. if (m_InAsmMode && (isTopLevelDeferredFunc && m_deferAsmJs))
  4999. {
  5000. // asm.js doesn't support lambda functions
  5001. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Lambda functions are not supported."));
  5002. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Asm.js compilation failed."));
  5003. throw Js::AsmJsParseException();
  5004. }
  5005. #endif
  5006. }
  5007. if (m_token.tk == tkRParen)
  5008. {
  5009. this->GetScanner()->Scan();
  5010. }
  5011. if (fLambda)
  5012. {
  5013. BOOL hadNewLine = this->GetScanner()->FHadNewLine();
  5014. // it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side
  5015. // of the fat arrow, but that expression does not parse as a parameter list. E.g.
  5016. // a.x => { }
  5017. // Therefore check for it and error if not found.
  5018. ChkCurTok(tkDArrow, ERRnoDArrow);
  5019. // Newline character between arrow parameters and fat arrow is a syntax error but we want to check for
  5020. // this after verifying there was a => token. Otherwise we would throw the wrong error.
  5021. if (hadNewLine)
  5022. {
  5023. Error(ERRValidIfFollowedBy, _u("Lambda parameter list"), _u("'=>' on the same line"));
  5024. }
  5025. }
  5026. if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))
  5027. {
  5028. fDeferred = true;
  5029. this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint, fLambda, pNeedScanRCurly, fAllowIn);
  5030. }
  5031. else
  5032. {
  5033. AnalysisAssert(pnodeFnc);
  5034. // Shouldn't be any temps in the arg list.
  5035. Assert(*m_ppnodeVar == nullptr);
  5036. // Start the var list.
  5037. m_ppnodeVar = varNodesList;
  5038. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  5039. {
  5040. OUTPUT_TRACE_DEBUGONLY(Js::ParsePhase, _u("The param and body scope of the function %s cannot be merged\n"), pnodeFnc->pnodeName ? pnodeFnc->pnodeName->pid->Psz() : _u("Anonymous function"));
  5041. }
  5042. // Keep nested function declarations and expressions in the same list at function scope.
  5043. // (Indicate this by nulling out the current function expressions list.)
  5044. m_ppnodeExprScope = nullptr;
  5045. if (buildAST)
  5046. {
  5047. if (m_token.tk != tkLCurly && fLambda)
  5048. {
  5049. *pNeedScanRCurly = false;
  5050. }
  5051. uint savedStubCount = m_currDeferredStubCount;
  5052. DeferredFunctionStub* savedStub = m_currDeferredStub;
  5053. ShiftCurrDeferredStubToChildFunction(pnodeFnc, pnodeFncSave);
  5054. this->FinishFncDecl(pnodeFnc, pNameHint, fLambda, skipFormals, fAllowIn);
  5055. m_currDeferredStub = savedStub;
  5056. m_currDeferredStubCount = savedStubCount;
  5057. }
  5058. else
  5059. {
  5060. this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn, fAllowIn);
  5061. }
  5062. }
  5063. // Restore the paren count for any outer spread/rest error checking.
  5064. m_funcParenExprDepth = parenExprDepthSave;
  5065. if (pnodeInnerBlock)
  5066. {
  5067. FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);
  5068. }
  5069. if (!fModule && (m_token.tk == tkLCurly || !fLambda))
  5070. {
  5071. UpdateArgumentsNode(pnodeFnc, argNode);
  5072. }
  5073. CreateSpecialSymbolDeclarations(pnodeFnc);
  5074. // Restore the lists of scopes that contain function expressions.
  5075. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  5076. m_ppnodeExprScope = ppnodeExprScopeSave;
  5077. Assert(m_ppnodeScope);
  5078. Assert(nullptr == *m_ppnodeScope);
  5079. m_ppnodeScope = ppnodeScopeSave;
  5080. if (pnodeBlock)
  5081. {
  5082. FinishParseBlock(pnodeBlock, *pNeedScanRCurly);
  5083. }
  5084. if (IsStrictMode() || strictModeTurnedOn)
  5085. {
  5086. this->m_fUseStrictMode = TRUE; // Now we know this function is in strict mode
  5087. if (!fWasAlreadyStrictMode)
  5088. {
  5089. // If this function turned on strict mode then we didn't check the formal
  5090. // parameters or function name hint for future reserved word usage. So do that now.
  5091. RestorePoint afterFnc;
  5092. this->GetScanner()->Capture(&afterFnc);
  5093. if (pnodeFnc->pnodeName != nullptr)
  5094. {
  5095. // Rewind to the function name hint and check if the token is a reserved word.
  5096. this->GetScanner()->SeekTo(beginNameHint);
  5097. this->GetScanner()->Scan();
  5098. if (pnodeFnc->IsGenerator())
  5099. {
  5100. Assert(m_token.tk == tkStar);
  5101. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5102. Assert(!(flags & fFncClassMember));
  5103. this->GetScanner()->Scan();
  5104. }
  5105. if (m_token.IsReservedWord())
  5106. {
  5107. IdentifierExpectedError(m_token);
  5108. }
  5109. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  5110. }
  5111. // Fast forward to formal parameter list, check for future reserved words,
  5112. // then restore scanner as it was.
  5113. this->GetScanner()->SeekToForcingPid(beginFormals);
  5114. CheckStrictFormalParameters();
  5115. this->GetScanner()->SeekTo(afterFnc);
  5116. }
  5117. if (buildAST)
  5118. {
  5119. if (pnodeFnc->pnodeName != nullptr)
  5120. {
  5121. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  5122. CheckStrictModeEvalArgumentsUsage(pnodeFnc->pnodeName->pid, pnodeFnc->pnodeName);
  5123. }
  5124. }
  5125. this->m_fUseStrictMode = oldStrictMode;
  5126. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StrictModeFunction, m_scriptContext);
  5127. }
  5128. ProcessCapturedNames(pnodeFnc);
  5129. if (fDeferred)
  5130. {
  5131. AnalysisAssert(pnodeFnc);
  5132. pnodeFnc->pnodeVars = nullptr;
  5133. }
  5134. #if ENABLE_BACKGROUND_PARSING
  5135. if (parallelJobStarted)
  5136. {
  5137. pnodeFnc = pnodeRealFnc;
  5138. m_currentNodeFunc = pnodeRealFnc;
  5139. // Let the foreground thread take care of marking the limit on the function node,
  5140. // because in some cases this function's caller will want to change that limit,
  5141. // so we don't want the background thread to try and touch it.
  5142. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5143. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5144. }
  5145. #endif
  5146. }
  5147. // after parsing asm.js module, we want to reset asm.js state before continuing
  5148. AnalysisAssert(pnodeFnc);
  5149. if (pnodeFnc->GetAsmjsMode())
  5150. {
  5151. m_InAsmMode = false;
  5152. }
  5153. // Restore the statement stack.
  5154. Assert(nullptr == m_pstmtCur);
  5155. SetCurrentStatement(pstmtSave);
  5156. if (pnodeFncExprScope)
  5157. {
  5158. FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);
  5159. }
  5160. m_grfscr |= uCanDeferSave;
  5161. if (!m_stoppedDeferredParse)
  5162. {
  5163. m_grfscr |= uDeferSave;
  5164. }
  5165. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5166. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5167. // Restore the current function.
  5168. if (buildAST)
  5169. {
  5170. Assert(pnodeFnc == m_currentNodeFunc);
  5171. m_currentNodeFunc = pnodeFncSave;
  5172. m_pCurrentAstSize = pAstSizeSave;
  5173. if (!fLambda)
  5174. {
  5175. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  5176. m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;
  5177. }
  5178. }
  5179. else
  5180. {
  5181. Assert(pnodeFnc == m_currentNodeDeferredFunc);
  5182. if (!fLambda)
  5183. {
  5184. Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);
  5185. m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;
  5186. }
  5187. m_currentNodeDeferredFunc = pnodeFncSave;
  5188. }
  5189. if (m_currentNodeFunc && pnodeFnc->HasWithStmt())
  5190. {
  5191. GetCurrentFunctionNode()->SetHasWithStmt(true);
  5192. }
  5193. }
  5194. template<bool buildAST>
  5195. void Parser::UpdateCurrentNodeFunc(ParseNodeFnc * pnodeFnc, bool fLambda)
  5196. {
  5197. if (buildAST)
  5198. {
  5199. // Make this the current function and start its sub-function list.
  5200. m_currentNodeFunc = pnodeFnc;
  5201. Assert(m_currentNodeDeferredFunc == nullptr);
  5202. if (!fLambda)
  5203. {
  5204. m_currentNodeNonLambdaFunc = pnodeFnc;
  5205. }
  5206. }
  5207. else // if !buildAST
  5208. {
  5209. AnalysisAssert(pnodeFnc);
  5210. if (!fLambda)
  5211. {
  5212. m_currentNodeNonLambdaDeferredFunc = pnodeFnc;
  5213. }
  5214. m_currentNodeDeferredFunc = pnodeFnc;
  5215. }
  5216. }
  5217. void Parser::ParseTopLevelDeferredFunc(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeFncParent, LPCOLESTR pNameHint, bool fLambda, bool *pNeedScanRCurly, bool fAllowIn)
  5218. {
  5219. // Parse a function body that is a transition point from building AST to doing fast syntax check.
  5220. pnodeFnc->pnodeVars = nullptr;
  5221. pnodeFnc->pnodeBody = nullptr;
  5222. this->m_deferringAST = TRUE;
  5223. // Put the scanner into "no hashing" mode.
  5224. BYTE deferFlags = this->GetScanner()->SetDeferredParse(TRUE);
  5225. if (!fLambda)
  5226. {
  5227. ChkCurTok(tkLCurly, ERRnoLcurly);
  5228. }
  5229. else
  5230. {
  5231. // Lambda may consist of a single expression instead of a block
  5232. if (this->GetScanner()->m_ptoken->tk == tkLCurly)
  5233. {
  5234. this->GetScanner()->Scan();
  5235. }
  5236. else
  5237. {
  5238. *pNeedScanRCurly = false;
  5239. }
  5240. }
  5241. ParseNodePtr *ppnodeVarSave = m_ppnodeVar;
  5242. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5243. // Don't try and skip scanning nested deferred lambdas which have only a single expression in the body.
  5244. // Their more-complicated text extents won't match the deferred-stub and the single expression should be fast to scan, anyway.
  5245. if (fLambda && !*pNeedScanRCurly)
  5246. {
  5247. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5248. }
  5249. else if (pnodeFncParent != nullptr && m_currDeferredStub != nullptr)
  5250. {
  5251. // We've already parsed this function body for syntax errors on the initial parse of the script.
  5252. // We have information that allows us to skip it, so do so.
  5253. Assert(pnodeFncParent->nestedCount != 0);
  5254. DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->nestedCount - 1);
  5255. Assert(pnodeFnc->ichMin == stub->ichMin
  5256. || (stub->fncFlags & kFunctionIsAsync) == kFunctionIsAsync
  5257. || ((stub->fncFlags & kFunctionIsMethod) == kFunctionIsMethod && (
  5258. (stub->fncFlags & kFunctionIsAccessor) == kFunctionIsAccessor
  5259. || (stub->fncFlags & kFunctionIsGenerator) == kFunctionIsGenerator
  5260. || (stub->fncFlags & kFunctionHasComputedName) == kFunctionHasComputedName
  5261. )));
  5262. if (stub->fncFlags & kFunctionCallsEval)
  5263. {
  5264. this->MarkEvalCaller();
  5265. }
  5266. PHASE_PRINT_TRACE1(
  5267. Js::SkipNestedDeferredPhase,
  5268. _u("Skipping nested deferred function %d. %s: %d...%d\n"),
  5269. pnodeFnc->functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);
  5270. this->GetScanner()->SeekTo(stub->restorePoint, m_nextFunctionId);
  5271. for (uint i = 0; i < stub->capturedNameCount; i++)
  5272. {
  5273. int stringId = stub->capturedNameSerializedIds[i];
  5274. uint32 stringLength = 0;
  5275. LPCWSTR stringVal = Js::ByteCodeSerializer::DeserializeString(stub, stringId, stringLength);
  5276. OUTPUT_TRACE_DEBUGONLY(Js::SkipNestedDeferredPhase, _u("\tPushing a reference to '%s'\n"), stringVal);
  5277. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(stringVal, stringLength);
  5278. PushPidRef(pid);
  5279. }
  5280. pnodeFnc->nestedCount = stub->nestedCount;
  5281. pnodeFnc->deferredStub = stub->deferredStubs;
  5282. pnodeFnc->fncFlags = (FncFlags)(pnodeFnc->fncFlags | stub->fncFlags);
  5283. }
  5284. else
  5285. {
  5286. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */);
  5287. }
  5288. if (!fLambda || *pNeedScanRCurly)
  5289. {
  5290. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5291. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5292. }
  5293. m_ppnodeVar = ppnodeVarSave;
  5294. // Restore the scanner's default hashing mode.
  5295. // Do this before we consume the next token.
  5296. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  5297. if (*pNeedScanRCurly)
  5298. {
  5299. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5300. }
  5301. #if DBG
  5302. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  5303. #endif
  5304. this->m_deferringAST = FALSE;
  5305. }
  5306. bool Parser::DoParallelParse(ParseNodeFnc * pnodeFnc) const
  5307. {
  5308. #if ENABLE_BACKGROUND_PARSING
  5309. if (!PHASE_ENABLED_RAW(ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId))
  5310. {
  5311. return false;
  5312. }
  5313. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  5314. return bgp != nullptr;
  5315. #else
  5316. return false;
  5317. #endif
  5318. }
  5319. bool Parser::ScanAheadToFunctionEnd(uint count)
  5320. {
  5321. bool found = false;
  5322. uint curlyDepth = 0;
  5323. RestorePoint funcStart;
  5324. this->GetScanner()->Capture(&funcStart);
  5325. for (uint i = 0; i < count; i++)
  5326. {
  5327. switch (m_token.tk)
  5328. {
  5329. case tkStrTmplBegin:
  5330. case tkStrTmplMid:
  5331. case tkStrTmplEnd:
  5332. case tkDiv:
  5333. case tkAsgDiv:
  5334. case tkScanError:
  5335. case tkEOF:
  5336. goto LEnd;
  5337. case tkLCurly:
  5338. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5339. break;
  5340. case tkRCurly:
  5341. if (curlyDepth == 1)
  5342. {
  5343. found = true;
  5344. goto LEnd;
  5345. }
  5346. if (curlyDepth == 0)
  5347. {
  5348. goto LEnd;
  5349. }
  5350. curlyDepth--;
  5351. break;
  5352. }
  5353. this->GetScanner()->ScanAhead();
  5354. }
  5355. LEnd:
  5356. this->GetScanner()->SeekTo(funcStart);
  5357. return found;
  5358. }
  5359. #if ENABLE_BACKGROUND_PARSING
  5360. bool Parser::FastScanFormalsAndBody()
  5361. {
  5362. // The scanner is currently pointing just past the name of a function.
  5363. // The idea here is to find the end of the function body as quickly as possible,
  5364. // by tokenizing and tracking {}'s if possible.
  5365. // String templates require some extra logic but can be handled.
  5366. // The real wrinkle is "/" and "/=", which may indicate either a RegExp literal or a division, depending
  5367. // on the context.
  5368. // To handle this with minimal work, keep track of the last ";" seen at each {} depth. If we see one of the
  5369. // difficult tokens, rewind to the last ";" at the current {} depth and parse statements until we pass the
  5370. // point where we had to rewind. This will process the "/" as required.
  5371. RestorePoint funcStart;
  5372. this->GetScanner()->Capture(&funcStart);
  5373. const int maxRestorePointDepth = 16;
  5374. struct FastScanRestorePoint
  5375. {
  5376. RestorePoint restorePoint;
  5377. uint parenDepth;
  5378. Js::LocalFunctionId functionId;
  5379. int blockId;
  5380. FastScanRestorePoint() : restorePoint(), parenDepth(0) {};
  5381. };
  5382. FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];
  5383. charcount_t ichStart = this->GetScanner()->IchMinTok();
  5384. uint blockIdSave = m_nextBlockId;
  5385. uint functionIdSave = *m_nextFunctionId;
  5386. uint curlyDepth = 0;
  5387. uint strTmplDepth = 0;
  5388. for (;;)
  5389. {
  5390. switch (m_token.tk)
  5391. {
  5392. case tkStrTmplBegin:
  5393. UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);
  5394. // Fall through
  5395. case tkStrTmplMid:
  5396. case tkLCurly:
  5397. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5398. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5399. break;
  5400. case tkStrTmplEnd:
  5401. // We can assert here, because the scanner will only return this token if we've told it we're
  5402. // in a string template.
  5403. Assert(strTmplDepth > 0);
  5404. strTmplDepth--;
  5405. break;
  5406. case tkRCurly:
  5407. if (curlyDepth == 1)
  5408. {
  5409. Assert(strTmplDepth == 0);
  5410. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5411. {
  5412. Output::Print(_u("Finished fast seek: %d. %s -- %d...%d\n"),
  5413. m_currentNodeFunc->functionId,
  5414. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5415. ichStart, this->GetScanner()->IchLimTok());
  5416. }
  5417. return true;
  5418. }
  5419. if (curlyDepth < maxRestorePointDepth)
  5420. {
  5421. lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;
  5422. }
  5423. curlyDepth--;
  5424. if (strTmplDepth > 0)
  5425. {
  5426. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  5427. }
  5428. break;
  5429. case tkSColon:
  5430. // Track the location of the ";" (if it's outside parens, as we don't, for instance, want
  5431. // to track the ";"'s in a for-loop header. If we find it's important to rewind within a paren
  5432. // expression, we can do something more sophisticated.)
  5433. if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)
  5434. {
  5435. this->GetScanner()->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);
  5436. lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;
  5437. lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;
  5438. }
  5439. break;
  5440. case tkLParen:
  5441. if (curlyDepth < maxRestorePointDepth)
  5442. {
  5443. UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);
  5444. }
  5445. break;
  5446. case tkRParen:
  5447. if (curlyDepth < maxRestorePointDepth)
  5448. {
  5449. Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);
  5450. lastSColonAtCurlyDepth[curlyDepth].parenDepth--;
  5451. }
  5452. break;
  5453. case tkID:
  5454. {
  5455. charcount_t tokLength = this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok();
  5456. // Detect the function and class keywords so we can track function ID's.
  5457. // (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token
  5458. // to a PID.)
  5459. // Detect try/catch/for to increment block count for them.
  5460. switch (tokLength)
  5461. {
  5462. case 3:
  5463. if (!memcmp(this->GetScanner()->PchMinTok(), "try", 3) || !memcmp(this->GetScanner()->PchMinTok(), "for", 3))
  5464. {
  5465. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5466. }
  5467. break;
  5468. case 5:
  5469. if (!memcmp(this->GetScanner()->PchMinTok(), "catch", 5))
  5470. {
  5471. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5472. }
  5473. else if (!memcmp(this->GetScanner()->PchMinTok(), "class", 5))
  5474. {
  5475. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5476. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5477. }
  5478. break;
  5479. case 8:
  5480. if (!memcmp(this->GetScanner()->PchMinTok(), "function", 8))
  5481. {
  5482. // Account for the possible func expr scope or dummy block for missing {}'s around a declaration
  5483. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5484. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5485. }
  5486. break;
  5487. }
  5488. break;
  5489. }
  5490. case tkDArrow:
  5491. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5492. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5493. break;
  5494. case tkDiv:
  5495. case tkAsgDiv:
  5496. {
  5497. int opl;
  5498. OpCode nop;
  5499. tokens tkPrev = this->GetScanner()->m_tkPrevious;
  5500. if ((this->GetHashTbl()->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||
  5501. (this->GetHashTbl()->TokIsUnop(tkPrev, &opl, &nop) &&
  5502. nop != knopNone &&
  5503. tkPrev != tkInc &&
  5504. tkPrev != tkDec) ||
  5505. tkPrev == tkColon ||
  5506. tkPrev == tkLParen ||
  5507. tkPrev == tkLBrack ||
  5508. tkPrev == tkRETURN)
  5509. {
  5510. // Previous token indicates that we're starting an expression here and can't have a
  5511. // binary operator now.
  5512. // Assume this is a RegExp.
  5513. ParseRegExp<false>();
  5514. break;
  5515. }
  5516. uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;
  5517. for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)
  5518. {
  5519. // We don't know whether we've got a RegExp or a divide. Rewind to the last safe ";"
  5520. // if we can and parse statements until we pass this point.
  5521. if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)
  5522. {
  5523. break;
  5524. }
  5525. }
  5526. if (tempCurlyDepth != (uint)-1)
  5527. {
  5528. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5529. int32 *pastSizeSave = m_pCurrentAstSize;
  5530. uint *pnestedCountSave = m_pnestedCount;
  5531. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  5532. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  5533. ParseNodeFnc * pnodeFnc = CreateDummyFuncNode(true);
  5534. charcount_t ichStop = this->GetScanner()->IchLimTok();
  5535. curlyDepth = tempCurlyDepth;
  5536. this->GetScanner()->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);
  5537. m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;
  5538. *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;
  5539. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5540. pnodeFnc->pnodeScopes = pnodeBlock;
  5541. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  5542. m_ppnodeExprScope = nullptr;
  5543. this->GetScanner()->Scan();
  5544. do
  5545. {
  5546. ParseStatement<false>();
  5547. } while (this->GetScanner()->IchMinTok() < ichStop);
  5548. FinishParseBlock(pnodeBlock);
  5549. m_currentNodeFunc = pnodeFncSave;
  5550. m_pCurrentAstSize = pastSizeSave;
  5551. m_pnestedCount = pnestedCountSave;
  5552. m_ppnodeScope = ppnodeScopeSave;
  5553. m_ppnodeExprScope = ppnodeExprScopeSave;
  5554. // We've already consumed the first token of the next statement, so just continue
  5555. // without a further scan.
  5556. continue;
  5557. }
  5558. }
  5559. // fall through to rewind to function start
  5560. case tkScanError:
  5561. case tkEOF:
  5562. // Unexpected token.
  5563. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5564. {
  5565. Output::Print(_u("Failed fast seek: %d. %s -- %d...%d\n"),
  5566. m_currentNodeFunc->functionId,
  5567. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5568. ichStart, this->GetScanner()->IchLimTok());
  5569. }
  5570. m_nextBlockId = blockIdSave;
  5571. *m_nextFunctionId = functionIdSave;
  5572. this->GetScanner()->SeekTo(funcStart);
  5573. return false;
  5574. }
  5575. this->GetScanner()->ScanNoKeywords();
  5576. }
  5577. }
  5578. #endif
  5579. ParseNodeFnc * Parser::CreateDummyFuncNode(bool fDeclaration)
  5580. {
  5581. // Create a dummy node and make it look like the current function declaration.
  5582. // Do this in situations where we want to parse statements without impacting
  5583. // the state of the "real" AST.
  5584. ParseNodeFnc * pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5585. pnodeFnc->SetDeclaration(fDeclaration);
  5586. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  5587. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  5588. m_pCurrentAstSize = &pnodeFnc->astSize;
  5589. m_currentNodeFunc = pnodeFnc;
  5590. m_pnestedCount = &pnodeFnc->nestedCount;
  5591. return pnodeFnc;
  5592. }
  5593. void Parser::ParseNestedDeferredFunc(ParseNodeFnc * pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn, bool fAllowIn)
  5594. {
  5595. // Parse a function nested inside another deferred function.
  5596. size_t lengthBeforeBody = this->GetSourceLength();
  5597. if (m_token.tk != tkLCurly && fLambda)
  5598. {
  5599. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5600. *pNeedScanRCurly = false;
  5601. }
  5602. else
  5603. {
  5604. ChkCurTok(tkLCurly, ERRnoLcurly);
  5605. bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;
  5606. m_ppnodeVar = &m_currentNodeDeferredFunc->pnodeVars;
  5607. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */, detectStrictModeOn);
  5608. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5609. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5610. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5611. }
  5612. if (*pStrictModeTurnedOn)
  5613. {
  5614. pnodeFnc->SetStrictMode(true);
  5615. }
  5616. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  5617. {
  5618. // Record the end of the function and the function ID increment that happens inside the function.
  5619. // Byte code gen will use this to build stub information to allow us to skip this function when the
  5620. // enclosing function is fully parsed.
  5621. RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);
  5622. this->GetScanner()->Capture(restorePoint,
  5623. *m_nextFunctionId - pnodeFnc->functionId - 1,
  5624. lengthBeforeBody - this->GetSourceLength());
  5625. pnodeFnc->pRestorePoint = restorePoint;
  5626. }
  5627. }
  5628. template<bool buildAST>
  5629. void Parser::ParseFncName(ParseNodeFnc * pnodeFnc, ushort flags, IdentPtr* pFncNamePid)
  5630. {
  5631. Assert(pnodeFnc);
  5632. BOOL fDeclaration = flags & fFncDeclaration;
  5633. BOOL fIsAsync = flags & fFncAsync;
  5634. this->GetScanner()->Scan();
  5635. // If generators are enabled then we are in a recent enough version
  5636. // that deferred parsing will create a parse node for pnodeFnc and
  5637. // it is safe to assume it is not null.
  5638. if (flags & fFncGenerator)
  5639. {
  5640. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5641. pnodeFnc->SetIsGenerator();
  5642. }
  5643. else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  5644. m_token.tk == tkStar &&
  5645. !(flags & fFncClassMember))
  5646. {
  5647. if (!fDeclaration)
  5648. {
  5649. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(!fDeclaration);
  5650. this->GetScanner()->Scan();
  5651. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5652. }
  5653. else
  5654. {
  5655. this->GetScanner()->Scan();
  5656. }
  5657. pnodeFnc->SetIsGenerator();
  5658. }
  5659. if (fIsAsync)
  5660. {
  5661. if (pnodeFnc->IsGenerator())
  5662. {
  5663. Error(ERRsyntax);
  5664. }
  5665. pnodeFnc->SetIsAsync();
  5666. }
  5667. pnodeFnc->pnodeName = nullptr;
  5668. if ((m_token.tk != tkID || flags & fFncNoName)
  5669. && (IsStrictMode() || fDeclaration
  5670. || pnodeFnc->IsGenerator() || pnodeFnc->IsAsync()
  5671. || (m_token.tk != tkYIELD && m_token.tk != tkAWAIT))) // Function expressions can have the name yield/await even inside generator/async functions
  5672. {
  5673. if (fDeclaration ||
  5674. m_token.IsReservedWord()) // For example: var x = (function break(){});
  5675. {
  5676. IdentifierExpectedError(m_token);
  5677. }
  5678. return;
  5679. }
  5680. Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration) || (m_token.tk == tkAWAIT && !fDeclaration));
  5681. if (IsStrictMode())
  5682. {
  5683. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  5684. }
  5685. IdentPtr pidBase = m_token.GetIdentifier(this->GetHashTbl());
  5686. pnodeFnc->pnodeName = CreateDeclNode(knopVarDecl, pidBase, STFunction);
  5687. pnodeFnc->pid = pnodeFnc->pnodeName->pid;
  5688. if (pFncNamePid != nullptr)
  5689. {
  5690. *pFncNamePid = pidBase;
  5691. }
  5692. this->GetScanner()->Scan();
  5693. }
  5694. void Parser::ValidateFormals()
  5695. {
  5696. ParseFncFormals<false>(this->GetCurrentFunctionNode(), nullptr, fFncNoFlgs);
  5697. // Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.
  5698. this->GetScanner()->Scan();
  5699. }
  5700. void Parser::ValidateSourceElementList()
  5701. {
  5702. ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);
  5703. }
  5704. void Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)
  5705. {
  5706. bool isStrictMode = IsStrictMode();
  5707. if (isStrictMode)
  5708. {
  5709. CheckStrictModeEvalArgumentsUsage(pid);
  5710. }
  5711. if (formals->Has(pid))
  5712. {
  5713. if (isStrictMode)
  5714. {
  5715. Error(ERRES5ArgSame);
  5716. }
  5717. else
  5718. {
  5719. Error(ERRFormalSame);
  5720. }
  5721. }
  5722. else
  5723. {
  5724. formals->Prepend(pid);
  5725. }
  5726. }
  5727. template<bool buildAST>
  5728. void Parser::ParseFncFormals(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeParentFnc, ushort flags, bool isTopLevelDeferredFunc)
  5729. {
  5730. bool fLambda = (flags & fFncLambda) != 0;
  5731. bool fMethod = (flags & fFncMethod) != 0;
  5732. bool fNoArg = (flags & fFncNoArg) != 0;
  5733. bool fOneArg = (flags & fFncOneArg) != 0;
  5734. bool fAsync = (flags & fFncAsync) != 0;
  5735. bool fPreviousYieldIsKeyword = false;
  5736. bool fPreviousAwaitIsKeyword = false;
  5737. if (fLambda)
  5738. {
  5739. fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeParentFnc != nullptr && pnodeParentFnc->IsGenerator());
  5740. fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->IsAsync()));
  5741. }
  5742. Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.
  5743. // strictFormals corresponds to the StrictFormalParameters grammar production
  5744. // in the ES spec which just means duplicate names are not allowed
  5745. bool fStrictFormals = IsStrictMode() || fLambda || fMethod;
  5746. // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
  5747. bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
  5748. AutoTempForcePid autoForcePid(this->GetScanner(), forcePid);
  5749. // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
  5750. if (fLambda && m_token.tk == tkID)
  5751. {
  5752. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5753. CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5754. CheckPidIsValid(pid);
  5755. this->GetScanner()->Scan();
  5756. if (m_token.tk != tkDArrow)
  5757. {
  5758. Error(ERRsyntax, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  5759. }
  5760. if (fLambda)
  5761. {
  5762. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5763. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5764. }
  5765. return;
  5766. }
  5767. else if (fLambda && m_token.tk == tkAWAIT)
  5768. {
  5769. // async await => {}
  5770. IdentifierExpectedError(m_token);
  5771. }
  5772. // Otherwise, must have a parameter list within parens.
  5773. ChkCurTok(tkLParen, ERRnoLparen);
  5774. // Now parse the list of arguments, if present
  5775. if (m_token.tk == tkRParen)
  5776. {
  5777. if (fOneArg)
  5778. {
  5779. Error(ERRSetterMustHaveOneParameter);
  5780. }
  5781. }
  5782. else
  5783. {
  5784. if (fNoArg)
  5785. {
  5786. Error(ERRGetterMustHaveNoParameters);
  5787. }
  5788. SList<IdentPtr> formals(&m_nodeAllocator);
  5789. ParseNodeVar * pnodeT = nullptr;
  5790. bool seenRestParameter = false;
  5791. bool isNonSimpleParameterList = false;
  5792. for (Js::ArgSlot argPos = 0; ; ++argPos)
  5793. {
  5794. bool isBindingPattern = false;
  5795. if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
  5796. {
  5797. // Possible rest parameter
  5798. this->GetScanner()->Scan();
  5799. seenRestParameter = true;
  5800. }
  5801. if (m_token.tk != tkID)
  5802. {
  5803. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  5804. {
  5805. // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
  5806. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5807. this->GetCurrentFunctionNode()->SetHasDestructuredParams();
  5808. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5809. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5810. ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
  5811. Assert(ppNodeLex != nullptr);
  5812. ParseNodeParamPattern * paramPattern = nullptr;
  5813. ParseNode * pnodePattern = nullptr;
  5814. if (isTopLevelDeferredFunc)
  5815. {
  5816. pnodePattern = ParseDestructuredLiteral<false>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5817. }
  5818. else
  5819. {
  5820. pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5821. }
  5822. // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
  5823. for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->AsParseNodeVar()->pnodeNext)
  5824. {
  5825. Assert(lexNode->IsVarLetOrConst());
  5826. UpdateOrCheckForDuplicateInFormals(lexNode->AsParseNodeVar()->pid, &formals);
  5827. lexNode->AsParseNodeVar()->sym->SetSymbolType(STFormal);
  5828. if (lexNode->AsParseNodeVar()->pid == wellKnownPropertyPids.arguments)
  5829. {
  5830. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5831. }
  5832. }
  5833. m_ppnodeVar = ppnodeVarSave;
  5834. if (buildAST)
  5835. {
  5836. if (isTopLevelDeferredFunc)
  5837. {
  5838. Assert(pnodePattern == nullptr);
  5839. // Create a dummy pattern node as we need the node to be considered for the param count
  5840. paramPattern = CreateDummyParamPatternNode(this->GetScanner()->IchMinTok());
  5841. }
  5842. else
  5843. {
  5844. Assert(pnodePattern);
  5845. paramPattern = CreateParamPatternNode(pnodePattern);
  5846. }
  5847. // Linking the current formal parameter (which is pattern parameter) with other formals.
  5848. *m_ppnodeVar = paramPattern;
  5849. paramPattern->pnodeNext = nullptr;
  5850. m_ppnodeVar = &paramPattern->pnodeNext;
  5851. }
  5852. isBindingPattern = true;
  5853. isNonSimpleParameterList = true;
  5854. }
  5855. else
  5856. {
  5857. IdentifierExpectedError(m_token);
  5858. }
  5859. }
  5860. if (!isBindingPattern)
  5861. {
  5862. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5863. LPCOLESTR pNameHint = pid->Psz();
  5864. uint32 nameHintLength = pid->Cch();
  5865. uint32 nameHintOffset = 0;
  5866. if (seenRestParameter)
  5867. {
  5868. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5869. if (flags & fFncOneArg)
  5870. {
  5871. // The parameter of a setter cannot be a rest parameter.
  5872. Error(ERRUnexpectedEllipsis);
  5873. }
  5874. pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
  5875. pnodeT->sym->SetIsNonSimpleParameter(true);
  5876. if (buildAST)
  5877. {
  5878. // When only validating formals, we won't have a function node.
  5879. pnodeFnc->pnodeRest = pnodeT;
  5880. if (!isNonSimpleParameterList)
  5881. {
  5882. // This is the first non-simple parameter we've seen. We need to go back
  5883. // and set the Symbols of all previous parameters.
  5884. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5885. }
  5886. }
  5887. isNonSimpleParameterList = true;
  5888. }
  5889. else
  5890. {
  5891. pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5892. if (isNonSimpleParameterList)
  5893. {
  5894. pnodeT->sym->SetIsNonSimpleParameter(true);
  5895. }
  5896. }
  5897. if (buildAST && pid == wellKnownPropertyPids.arguments)
  5898. {
  5899. // This formal parameter overrides the built-in 'arguments' object
  5900. m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5901. }
  5902. if (fStrictFormals)
  5903. {
  5904. UpdateOrCheckForDuplicateInFormals(pid, &formals);
  5905. }
  5906. this->GetScanner()->Scan();
  5907. if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)
  5908. {
  5909. Error(ERRRestLastArg);
  5910. }
  5911. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5912. {
  5913. if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
  5914. {
  5915. Error(ERRRestWithDefault);
  5916. }
  5917. // In defer parse mode we have to flag the function node to indicate that it has default arguments
  5918. // so that it will be considered for any syntax error scenario.
  5919. // Also mark it before parsing the expression as it may contain functions.
  5920. ParseNodeFnc * currentFncNode = GetCurrentFunctionNode();
  5921. if (!currentFncNode->HasDefaultArguments())
  5922. {
  5923. currentFncNode->SetHasDefaultArguments();
  5924. currentFncNode->SetHasNonSimpleParameterList();
  5925. currentFncNode->firstDefaultArg = argPos;
  5926. }
  5927. this->GetScanner()->Scan();
  5928. ParseNodePtr pnodeInit;
  5929. if (isTopLevelDeferredFunc)
  5930. {
  5931. // Defer default expressions if the function will be deferred, since we know they can't be evaluated
  5932. // until the function is fully compiled, and generating code for a function nested inside a deferred function
  5933. // creates inconsistencies.
  5934. pnodeInit = ParseExpr<false>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5935. }
  5936. else
  5937. {
  5938. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5939. }
  5940. if (buildAST && pnodeInit && pnodeInit->nop == knopFncDecl)
  5941. {
  5942. Assert(nameHintLength >= nameHintOffset);
  5943. ParseNodeFnc * pnodeFncInit = pnodeInit->AsParseNodeFnc();
  5944. pnodeFncInit->hint = pNameHint;
  5945. pnodeFncInit->hintLength = nameHintLength;
  5946. pnodeFncInit->hintOffset = nameHintOffset;
  5947. }
  5948. AnalysisAssert(pnodeT);
  5949. pnodeT->sym->SetIsNonSimpleParameter(true);
  5950. if (!isNonSimpleParameterList)
  5951. {
  5952. if (buildAST)
  5953. {
  5954. // This is the first non-simple parameter we've seen. We need to go back
  5955. // and set the Symbols of all previous parameters.
  5956. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5957. }
  5958. // There may be previous parameters that need to be checked for duplicates.
  5959. isNonSimpleParameterList = true;
  5960. }
  5961. if (buildAST)
  5962. {
  5963. if (!m_currentNodeFunc->HasDefaultArguments())
  5964. {
  5965. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, DefaultArgFunction, m_scriptContext);
  5966. }
  5967. pnodeT->pnodeInit = pnodeInit;
  5968. pnodeT->ichLim = this->GetScanner()->IchLimTok();
  5969. }
  5970. }
  5971. }
  5972. if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
  5973. {
  5974. Error(ERRFormalSame);
  5975. }
  5976. if (flags & fFncOneArg)
  5977. {
  5978. if (m_token.tk != tkRParen)
  5979. {
  5980. Error(ERRSetterMustHaveOneParameter);
  5981. }
  5982. break; //enforce only one arg
  5983. }
  5984. if (m_token.tk != tkComma)
  5985. {
  5986. break;
  5987. }
  5988. this->GetScanner()->Scan();
  5989. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5990. {
  5991. break;
  5992. }
  5993. }
  5994. if (seenRestParameter)
  5995. {
  5996. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Rest, m_scriptContext);
  5997. }
  5998. if (m_token.tk != tkRParen)
  5999. {
  6000. Error(ERRnoRparen);
  6001. }
  6002. if (this->GetCurrentFunctionNode()->CallsEval() || this->GetCurrentFunctionNode()->ChildCallsEval())
  6003. {
  6004. Assert(pnodeFnc->HasNonSimpleParameterList());
  6005. pnodeFnc->ResetBodyAndParamScopeMerged();
  6006. }
  6007. }
  6008. Assert(m_token.tk == tkRParen);
  6009. if (fLambda)
  6010. {
  6011. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6012. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6013. }
  6014. }
  6015. template<bool buildAST>
  6016. ParseNodePtr Parser::GenerateModuleFunctionWrapper()
  6017. {
  6018. ParseNodePtr pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fFncModule, SuperRestrictionState::Disallowed, nullptr, /* needsPIDOnRCurlyScan */ false, /* fUnaryOrParen */ true);
  6019. ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);
  6020. return callNode;
  6021. }
  6022. template<bool buildAST>
  6023. ParseNodeFnc * Parser::GenerateEmptyConstructor(bool extends)
  6024. {
  6025. ParseNodeFnc * pnodeFnc;
  6026. // Create the node.
  6027. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  6028. pnodeFnc->SetNested(NULL != m_currentNodeFunc);
  6029. pnodeFnc->SetStrictMode();
  6030. pnodeFnc->SetDeclaration(TRUE);
  6031. pnodeFnc->SetIsMethod(TRUE);
  6032. pnodeFnc->SetIsClassMember(TRUE);
  6033. pnodeFnc->SetIsClassConstructor(TRUE);
  6034. pnodeFnc->SetIsBaseClassConstructor(!extends);
  6035. pnodeFnc->SetHasNonThisStmt();
  6036. pnodeFnc->SetIsGeneratedDefault(TRUE);
  6037. pnodeFnc->SetHasComputedName();
  6038. pnodeFnc->SetHasHomeObj();
  6039. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  6040. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  6041. pnodeFnc->ichMin = this->GetScanner()->IchMinTok();
  6042. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  6043. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  6044. pnodeFnc->cbStringMin = pnodeFnc->cbMin;
  6045. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  6046. pnodeFnc->functionId = (*m_nextFunctionId);
  6047. // In order to (re-)defer the default constructor, we need to, for instance, track
  6048. // deferred class expression the way we track function expression, since we lose the part of the source
  6049. // that tells us which we have.
  6050. Assert(!pnodeFnc->canBeDeferred);
  6051. #ifdef DBG
  6052. pnodeFnc->deferredParseNextFunctionId = *(this->m_nextFunctionId);
  6053. #endif
  6054. AppendFunctionToScopeList(true, pnodeFnc);
  6055. if (m_nextFunctionId)
  6056. {
  6057. (*m_nextFunctionId)++;
  6058. }
  6059. // Update the count of functions nested in the current parent.
  6060. if (m_pnestedCount)
  6061. {
  6062. (*m_pnestedCount)++;
  6063. }
  6064. if (this->GetScanner()->IchMinTok() >= this->GetScanner()->IchMinLine())
  6065. {
  6066. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  6067. pnodeFnc->columnNumber = this->GetScanner()->IchMinTok() - this->GetScanner()->IchMinLine();
  6068. }
  6069. else if (m_currentNodeFunc)
  6070. {
  6071. // For the first line after defer parse, compute the column relative to the column number
  6072. // of the lexically parent function.
  6073. ULONG offsetFromCurrentFunction = this->GetScanner()->IchMinTok() - m_currentNodeFunc->ichMin;
  6074. pnodeFnc->columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  6075. }
  6076. else
  6077. {
  6078. // if there is no current function, lets give a default of 0.
  6079. pnodeFnc->columnNumber = 0;
  6080. }
  6081. int32 * pAstSizeSave = m_pCurrentAstSize;
  6082. m_pCurrentAstSize = &(pnodeFnc->astSize);
  6083. // Make this the current function.
  6084. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  6085. m_currentNodeFunc = pnodeFnc;
  6086. ParseNodeName * argsId = nullptr;
  6087. ParseNodePtr *lastNodeRef = nullptr;
  6088. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  6089. if (buildAST && extends)
  6090. {
  6091. // constructor(...args) { super(...args); }
  6092. // ^^^^^^^
  6093. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  6094. m_ppnodeVar = &pnodeFnc->pnodeVars;
  6095. IdentPtr pidargs = this->GetHashTbl()->PidHashNameLen(_u("args"), sizeof("args") - 1);
  6096. ParseNodeVar * pnodeT = CreateVarDeclNode(pidargs, STFormal);
  6097. pnodeT->sym->SetIsNonSimpleParameter(true);
  6098. pnodeFnc->pnodeRest = pnodeT;
  6099. PidRefStack *ref = this->PushPidRef(pidargs);
  6100. argsId = CreateNameNode(pidargs, ref, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6101. m_ppnodeVar = ppnodeVarSave;
  6102. }
  6103. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  6104. pnodeBlock->pnodeScopes = pnodeInnerBlock;
  6105. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  6106. pnodeFnc->pnodeScopes = pnodeBlock;
  6107. if (buildAST)
  6108. {
  6109. if (extends)
  6110. {
  6111. // constructor(...args) { super(...args); }
  6112. // ^^^^^^^^^^^^^^^
  6113. Assert(argsId);
  6114. ParseNodeUni * spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6115. ParseNodeSpecialName * superRef = ReferenceSpecialName(wellKnownPropertyPids._superConstructor, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6116. pnodeFnc->SetHasSuperReference(TRUE);
  6117. ParseNodeSuperCall * callNode = CreateSuperCallNode(superRef, spreadArg);
  6118. callNode->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6119. callNode->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6120. callNode->spreadArgCount = 1;
  6121. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, callNode);
  6122. }
  6123. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  6124. }
  6125. FinishParseBlock(pnodeInnerBlock);
  6126. CreateSpecialSymbolDeclarations(pnodeFnc);
  6127. FinishParseBlock(pnodeBlock);
  6128. m_currentNodeFunc = pnodeFncSave;
  6129. m_pCurrentAstSize = pAstSizeSave;
  6130. return pnodeFnc;
  6131. }
  6132. template<bool buildAST>
  6133. void Parser::ParseExpressionLambdaBody(ParseNodeFnc * pnodeLambda, bool fAllowIn)
  6134. {
  6135. ParseNodePtr *lastNodeRef = nullptr;
  6136. // The lambda body is a single expression, the result of which is the return value.
  6137. ParseNodeReturn * pnodeRet = nullptr;
  6138. if (buildAST)
  6139. {
  6140. pnodeRet = CreateNodeForOpT<knopReturn>();
  6141. pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;
  6142. pnodeLambda->pnodeScopes->pnodeStmt = pnodeRet;
  6143. }
  6144. IdentToken token;
  6145. charcount_t lastRParen = 0;
  6146. // We need to disable deferred parse mode in the scanner because the lambda body doesn't end with a right paren.
  6147. // The scanner needs to create a pid in the case of a string constant token immediately following the lambda body expression.
  6148. // Otherwise, we'll save null for the string constant pid which will AV during ByteCode generation.
  6149. BYTE fScanDeferredFlagsSave = this->GetScanner()->SetDeferredParse(FALSE);
  6150. ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, fAllowIn, FALSE, nullptr, nullptr, nullptr, &token, false, nullptr, &lastRParen);
  6151. this->GetScanner()->SetDeferredParseFlags(fScanDeferredFlagsSave);
  6152. this->MarkEscapingRef(result, &token);
  6153. if (buildAST)
  6154. {
  6155. pnodeRet->pnodeExpr = result;
  6156. pnodeRet->ichMin = pnodeRet->pnodeExpr->ichMin;
  6157. pnodeRet->ichLim = pnodeRet->pnodeExpr->ichLim;
  6158. // Pushing a statement node with PushStmt<>() normally does this initialization
  6159. // but do it here manually since we know there is no outer statement node.
  6160. pnodeRet->grfnop = 0;
  6161. pnodeRet->pnodeOuter = nullptr;
  6162. pnodeLambda->ichLim = max(pnodeRet->ichLim, lastRParen);
  6163. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  6164. pnodeLambda->pnodeScopes->ichLim = pnodeRet->ichLim;
  6165. pnodeLambda->pnodeBody = nullptr;
  6166. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, pnodeRet);
  6167. // Append an EndCode node.
  6168. ParseNodePtr end = CreateNodeForOpT<knopEndCode>(pnodeRet->ichLim);
  6169. end->ichLim = end->ichMin; // make end code zero width at the immediate end of lambda body
  6170. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, end);
  6171. // Lambda's do not have arguments binding
  6172. pnodeLambda->SetHasReferenceableBuiltInArguments(false);
  6173. }
  6174. else
  6175. {
  6176. pnodeLambda->ichLim = max(this->GetScanner()->IchLimTokPrevious(), lastRParen);
  6177. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  6178. }
  6179. }
  6180. void Parser::CheckStrictFormalParameters()
  6181. {
  6182. if (m_token.tk == tkID)
  6183. {
  6184. // single parameter arrow function case
  6185. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  6186. CheckStrictModeEvalArgumentsUsage(pid);
  6187. return;
  6188. }
  6189. Assert(m_token.tk == tkLParen);
  6190. this->GetScanner()->ScanForcingPid();
  6191. if (m_token.tk != tkRParen)
  6192. {
  6193. SList<IdentPtr> formals(&m_nodeAllocator);
  6194. for (;;)
  6195. {
  6196. if (m_token.tk != tkID)
  6197. {
  6198. IdentifierExpectedError(m_token);
  6199. }
  6200. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  6201. CheckStrictModeEvalArgumentsUsage(pid);
  6202. if (formals.Has(pid))
  6203. {
  6204. Error(ERRES5ArgSame, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  6205. }
  6206. else
  6207. {
  6208. formals.Prepend(pid);
  6209. }
  6210. this->GetScanner()->Scan();
  6211. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  6212. {
  6213. this->GetScanner()->Scan();
  6214. // We can avoid building the AST since we are just checking the default expression.
  6215. ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);
  6216. Assert(pnodeInit == nullptr);
  6217. }
  6218. if (m_token.tk != tkComma)
  6219. {
  6220. break;
  6221. }
  6222. this->GetScanner()->ScanForcingPid();
  6223. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6224. {
  6225. break;
  6226. }
  6227. }
  6228. }
  6229. Assert(m_token.tk == tkRParen);
  6230. }
  6231. void Parser::FinishFncNode(ParseNodeFnc * pnodeFnc, bool fAllowIn)
  6232. {
  6233. AnalysisAssert(pnodeFnc);
  6234. // Finish the AST for a function that was deferred earlier, but which we decided
  6235. // to finish after the fact.
  6236. // We assume that the name(s) and arg(s) have already got parse nodes, so
  6237. // we just have to do the function body.
  6238. // Save the current next function Id, and resume from the old one.
  6239. Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;
  6240. Js::LocalFunctionId tempNextFunctionId = pnodeFnc->functionId + 1;
  6241. this->m_nextFunctionId = &tempNextFunctionId;
  6242. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  6243. uint *pnestedCountSave = m_pnestedCount;
  6244. int32* pAstSizeSave = m_pCurrentAstSize;
  6245. m_currentNodeFunc = pnodeFnc;
  6246. m_pCurrentAstSize = &(pnodeFnc->astSize);
  6247. pnodeFnc->nestedCount = 0;
  6248. m_pnestedCount = &pnodeFnc->nestedCount;
  6249. bool fLambda = pnodeFnc->IsLambda();
  6250. bool fMethod = pnodeFnc->IsMethod();
  6251. // Cue up the parser to the start of the function body.
  6252. if (pnodeFnc->pnodeName)
  6253. {
  6254. // Skip the name(s).
  6255. this->GetScanner()->SetCurrentCharacter(pnodeFnc->pnodeName->ichLim, pnodeFnc->lineNumber);
  6256. }
  6257. else
  6258. {
  6259. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->lineNumber);
  6260. if (fMethod)
  6261. {
  6262. // Method. Skip identifier name, computed property name, "async", "get", "set", and '*' or '(' characters.
  6263. for (;;)
  6264. {
  6265. this->GetScanner()->Scan();
  6266. // '[' character indicates a computed property name for this method. We should consume it.
  6267. if (m_token.tk == tkLBrack)
  6268. {
  6269. // We don't care what the name expr is.
  6270. this->GetScanner()->Scan();
  6271. ParseExpr<false>();
  6272. Assert(m_token.tk == tkRBrack);
  6273. continue;
  6274. }
  6275. // Quit scanning ahead when we reach a '(' character which opens the arg list.
  6276. if (m_token.tk == tkLParen)
  6277. {
  6278. break;
  6279. }
  6280. }
  6281. }
  6282. else if (pnodeFnc->IsAccessor())
  6283. {
  6284. // Getter/setter. The node text starts with the name, so eat that.
  6285. this->GetScanner()->ScanNoKeywords();
  6286. }
  6287. else if (!fLambda)
  6288. {
  6289. // Anonymous function. Skip "async", "function", and '(' or '*' characters.
  6290. for (;;)
  6291. {
  6292. this->GetScanner()->Scan();
  6293. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6294. {
  6295. Assert(pnodeFnc->IsAsync());
  6296. continue;
  6297. }
  6298. // Quit scanning ahead when we reach a 'function' keyword which precedes the arg list.
  6299. if (m_token.tk == tkFUNCTION)
  6300. {
  6301. break;
  6302. }
  6303. Assert(m_token.tk == tkLParen || m_token.tk == tkStar);
  6304. }
  6305. }
  6306. }
  6307. // switch scanner to treat 'yield' as keyword in generator functions
  6308. // or as an identifier in non-generator functions
  6309. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->IsGenerator());
  6310. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(pnodeFnc && pnodeFnc->IsAsync());
  6311. // Skip the arg list.
  6312. if (!fMethod)
  6313. {
  6314. // If this is a method, we've already advanced to the '(' token.
  6315. this->GetScanner()->Scan();
  6316. }
  6317. if (m_token.tk == tkStar)
  6318. {
  6319. Assert(pnodeFnc->IsGenerator());
  6320. this->GetScanner()->ScanNoKeywords();
  6321. }
  6322. if (fLambda && m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6323. {
  6324. Assert(pnodeFnc->IsAsync());
  6325. this->GetScanner()->ScanNoKeywords();
  6326. }
  6327. Assert(m_token.tk == tkLParen || (fLambda && m_token.tk == tkID));
  6328. this->GetScanner()->ScanNoKeywords();
  6329. if (m_token.tk != tkRParen && m_token.tk != tkDArrow)
  6330. {
  6331. for (;;)
  6332. {
  6333. if (m_token.tk == tkEllipsis)
  6334. {
  6335. this->GetScanner()->ScanNoKeywords();
  6336. }
  6337. if (m_token.tk == tkID)
  6338. {
  6339. this->GetScanner()->ScanNoKeywords();
  6340. if (m_token.tk == tkAsg)
  6341. {
  6342. // Eat the default expression
  6343. this->GetScanner()->Scan();
  6344. ParseExpr<false>(koplCma);
  6345. }
  6346. }
  6347. else if (IsPossiblePatternStart())
  6348. {
  6349. ParseDestructuredLiteralWithScopeSave(tkLET, false/*isDecl*/, false /*topLevel*/);
  6350. }
  6351. else
  6352. {
  6353. AssertMsg(false, "Unexpected identifier prefix while fast-scanning formals");
  6354. }
  6355. if (m_token.tk != tkComma)
  6356. {
  6357. break;
  6358. }
  6359. this->GetScanner()->ScanNoKeywords();
  6360. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6361. {
  6362. break;
  6363. }
  6364. }
  6365. }
  6366. if (m_token.tk == tkRParen)
  6367. {
  6368. this->GetScanner()->Scan();
  6369. }
  6370. if (fLambda && m_token.tk == tkDArrow)
  6371. {
  6372. this->GetScanner()->Scan();
  6373. }
  6374. // Finish the function body.
  6375. {
  6376. // Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. "( function x(){} )".
  6377. // We lose that context here since we start from middle of function body. So save and restore source range info.
  6378. const charcount_t ichLim = pnodeFnc->ichLim;
  6379. const size_t cbLim = pnodeFnc->cbLim;
  6380. this->FinishFncDecl(pnodeFnc, NULL, fLambda, /* skipCurlyBraces */ false, fAllowIn);
  6381. #if DBG
  6382. // The pnode extent may not match the original extent.
  6383. // We expect this to happen only when there are trailing ")"'s.
  6384. // Consume them and make sure that's all we've got.
  6385. if (pnodeFnc->ichLim != ichLim)
  6386. {
  6387. Assert(pnodeFnc->ichLim < ichLim);
  6388. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichLim);
  6389. while (this->GetScanner()->IchLimTok() != ichLim)
  6390. {
  6391. this->GetScanner()->ScanNoKeywords();
  6392. Assert(m_token.tk == tkRParen);
  6393. }
  6394. }
  6395. #endif
  6396. pnodeFnc->ichLim = ichLim;
  6397. pnodeFnc->cbLim = cbLim;
  6398. }
  6399. m_currentNodeFunc = pnodeFncSave;
  6400. m_pCurrentAstSize = pAstSizeSave;
  6401. m_pnestedCount = pnestedCountSave;
  6402. Assert(m_pnestedCount);
  6403. Assert(tempNextFunctionId == pnodeFnc->deferredParseNextFunctionId);
  6404. this->m_nextFunctionId = nextFunctionIdSave;
  6405. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6406. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6407. }
  6408. void Parser::FinishFncDecl(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, bool fLambda, bool skipCurlyBraces, bool fAllowIn)
  6409. {
  6410. LPCOLESTR name = NULL;
  6411. JS_ETW(int32 startAstSize = *m_pCurrentAstSize);
  6412. if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))
  6413. {
  6414. name = GetFunctionName(pnodeFnc, pNameHint);
  6415. m_functionBody = NULL; // for nested functions we do not want to get the name of the top deferred function return name;
  6416. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, 0, m_parseType, name));
  6417. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), name, pnodeFnc->functionId);
  6418. }
  6419. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->functionId, /*Undefer*/FALSE));
  6420. // Do the work of creating an AST for a function body.
  6421. // This is common to the un-deferred case and the case in which we un-defer late in the game.
  6422. Assert(pnodeFnc->nop == knopFncDecl);
  6423. if (fLambda && m_token.tk != tkLCurly)
  6424. {
  6425. ParseExpressionLambdaBody<true>(pnodeFnc, fAllowIn);
  6426. }
  6427. else
  6428. {
  6429. if (!skipCurlyBraces)
  6430. {
  6431. ChkCurTok(tkLCurly, ERRnoLcurly);
  6432. }
  6433. ParseNodePtr * lastNodeRef = nullptr;
  6434. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true /* isSourceElementList */);
  6435. // Append an EndCode node.
  6436. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  6437. if (!skipCurlyBraces)
  6438. {
  6439. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6440. }
  6441. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  6442. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  6443. }
  6444. #ifdef ENABLE_JS_ETW
  6445. int32 astSize = *m_pCurrentAstSize - startAstSize;
  6446. EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, astSize, m_parseType, name);
  6447. #endif
  6448. }
  6449. ParseNodeVar * Parser::CreateSpecialVarDeclNode(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6450. {
  6451. ParseNodeVar * pnode = InsertVarAtBeginning(pnodeFnc, pid);
  6452. pnode->grfpn |= fpnSpecialSymbol;
  6453. // special symbol must not be global
  6454. pnode->sym->SetIsGlobal(false);
  6455. return pnode;
  6456. }
  6457. ParseNodeVar * Parser::InsertVarAtBeginning(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6458. {
  6459. ParseNodeVar * pnode = nullptr;
  6460. if (m_ppnodeVar == &pnodeFnc->pnodeVars)
  6461. {
  6462. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6463. }
  6464. else
  6465. {
  6466. ParseNodePtr * const ppnodeVarSave = m_ppnodeVar;
  6467. m_ppnodeVar = &pnodeFnc->pnodeVars;
  6468. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6469. m_ppnodeVar = ppnodeVarSave;
  6470. }
  6471. Assert(pnode);
  6472. return pnode;
  6473. }
  6474. ParseNodeVar * Parser::AddArgumentsNodeToVars(ParseNodeFnc * pnodeFnc)
  6475. {
  6476. Assert(!GetCurrentFunctionNode()->IsLambda());
  6477. ParseNodeVar * argNode = InsertVarAtBeginning(pnodeFnc, wellKnownPropertyPids.arguments);
  6478. argNode->grfpn |= PNodeFlags::fpnArguments; // Flag this as the built-in arguments node
  6479. return argNode;
  6480. }
  6481. void Parser::UpdateArgumentsNode(ParseNodeFnc * pnodeFnc, ParseNodeVar * argNode)
  6482. {
  6483. if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam) || pnodeFnc->IsLambda())
  6484. {
  6485. // There is a parameter named arguments. So we don't have to create the built-in arguments.
  6486. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6487. }
  6488. else if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) && pnodeFnc->IsBodyAndParamScopeMerged())
  6489. {
  6490. // In non-split scope case there is a var or function definition named arguments in the body
  6491. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6492. }
  6493. else
  6494. {
  6495. pnodeFnc->SetHasReferenceableBuiltInArguments(true);
  6496. Assert(argNode);
  6497. }
  6498. if (argNode != nullptr && !argNode->sym->IsArguments())
  6499. {
  6500. // A duplicate definition has updated the declaration node. Need to reset it back.
  6501. argNode->grfpn |= PNodeFlags::fpnArguments;
  6502. argNode->sym->SetDecl(argNode);
  6503. }
  6504. }
  6505. LPCOLESTR Parser::GetFunctionName(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint)
  6506. {
  6507. LPCOLESTR name = nullptr;
  6508. if (pnodeFnc->pnodeName != nullptr)
  6509. {
  6510. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  6511. name = pnodeFnc->pnodeName->pid->Psz();
  6512. }
  6513. if (name == nullptr && pNameHint != nullptr)
  6514. {
  6515. name = pNameHint;
  6516. }
  6517. if (name == nullptr && (pnodeFnc->IsLambda() ||
  6518. (!pnodeFnc->IsDeclaration() && !pnodeFnc->IsMethod())))
  6519. {
  6520. name = Js::Constants::AnonymousFunction;
  6521. }
  6522. if (name == nullptr && m_functionBody != nullptr)
  6523. {
  6524. name = m_functionBody->GetExternalDisplayName();
  6525. }
  6526. else if (name == nullptr)
  6527. {
  6528. name = Js::Constants::AnonymousFunction;
  6529. }
  6530. return name;
  6531. }
  6532. IdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)
  6533. {
  6534. if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())
  6535. {
  6536. IdentPtr pid;
  6537. if (m_token.tk == tkStrCon)
  6538. {
  6539. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6540. {
  6541. Error(ERRES5NoOctal);
  6542. }
  6543. pid = m_token.GetStr();
  6544. }
  6545. else
  6546. {
  6547. pid = m_token.GetIdentifier(this->GetHashTbl());
  6548. }
  6549. *pidHint = pid;
  6550. return pid;
  6551. }
  6552. else if (m_token.tk == tkIntCon)
  6553. {
  6554. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6555. {
  6556. Error(ERRES5NoOctal);
  6557. }
  6558. return this->GetScanner()->PidFromLong(m_token.GetLong());
  6559. }
  6560. else if (m_token.tk == tkFltCon)
  6561. {
  6562. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6563. {
  6564. Error(ERRES5NoOctal);
  6565. }
  6566. return this->GetScanner()->PidFromDbl(m_token.GetDouble());
  6567. }
  6568. Error(ERRnoMemberIdent);
  6569. }
  6570. LPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)
  6571. {
  6572. if ((pMemberName == nullptr && !isComputedName) ||
  6573. (pMemberNameHint == nullptr && isComputedName) ||
  6574. !CONFIG_FLAG(UseFullName))
  6575. {
  6576. return nullptr;
  6577. }
  6578. LPCOLESTR pFinalName = isComputedName ? pMemberNameHint : pMemberName->Psz();
  6579. uint32 fullNameHintLength = (uint32)wcslen(pFinalName);
  6580. uint32 shortNameOffset = 0;
  6581. if (!isStatic)
  6582. {
  6583. // Add prototype.
  6584. pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);
  6585. }
  6586. if (pClassName)
  6587. {
  6588. uint32 classNameOffset = 0;
  6589. pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);
  6590. shortNameOffset += classNameOffset;
  6591. }
  6592. if (pGetSet)
  6593. {
  6594. // displays as get/set prototype.funcname
  6595. uint32 getSetOffset = 0;
  6596. pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);
  6597. shortNameOffset += getSetOffset;
  6598. }
  6599. *nameLength = fullNameHintLength;
  6600. *pShortNameOffset = shortNameOffset;
  6601. return pFinalName;
  6602. }
  6603. template<bool buildAST>
  6604. ParseNodeClass * Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)
  6605. {
  6606. bool hasConstructor = false;
  6607. bool hasExtends = false;
  6608. IdentPtr name = nullptr;
  6609. ParseNodeVar * pnodeName = nullptr;
  6610. ParseNodeFnc * pnodeConstructor = nullptr;
  6611. ParseNodePtr pnodeExtends = nullptr;
  6612. ParseNodePtr pnodeMembers = nullptr;
  6613. ParseNodePtr *lastMemberNodeRef = nullptr;
  6614. ParseNodePtr pnodeStaticMembers = nullptr;
  6615. ParseNodePtr *lastStaticMemberNodeRef = nullptr;
  6616. uint32 nameHintLength = pHintLength ? *pHintLength : 0;
  6617. uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;
  6618. ArenaAllocator tempAllocator(_u("ClassMemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  6619. size_t cbMinConstructor = 0;
  6620. ParseNodeClass * pnodeClass = nullptr;
  6621. if (buildAST)
  6622. {
  6623. pnodeClass = CreateNodeForOpT<knopClassDecl>();
  6624. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Class, m_scriptContext);
  6625. cbMinConstructor = this->GetScanner()->IecpMinTok();
  6626. }
  6627. this->GetScanner()->Scan();
  6628. if (m_token.tk == tkID)
  6629. {
  6630. name = m_token.GetIdentifier(this->GetHashTbl());
  6631. this->GetScanner()->Scan();
  6632. }
  6633. else if (isDeclaration)
  6634. {
  6635. IdentifierExpectedError(m_token);
  6636. }
  6637. if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  6638. {
  6639. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  6640. }
  6641. BOOL strictSave = m_fUseStrictMode;
  6642. m_fUseStrictMode = TRUE;
  6643. ParseNodeVar * pnodeDeclName = nullptr;
  6644. if (isDeclaration)
  6645. {
  6646. pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);
  6647. }
  6648. ParseNodePtr *ppnodeScopeSave = nullptr;
  6649. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  6650. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  6651. if (buildAST)
  6652. {
  6653. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  6654. pnodeClass->pnodeBlock = pnodeBlock;
  6655. }
  6656. if (name)
  6657. {
  6658. pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);
  6659. }
  6660. if (m_token.tk == tkEXTENDS)
  6661. {
  6662. this->GetScanner()->Scan();
  6663. pnodeExtends = ParseTerm<buildAST>();
  6664. hasExtends = true;
  6665. }
  6666. if (m_token.tk != tkLCurly)
  6667. {
  6668. Error(ERRnoLcurly);
  6669. }
  6670. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Parsing class (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6671. RestorePoint beginClass;
  6672. this->GetScanner()->Capture(&beginClass);
  6673. this->GetScanner()->ScanForcingPid();
  6674. IdentPtr pClassNamePid = pnodeName ? pnodeName->pid : nullptr;
  6675. for (;;)
  6676. {
  6677. if (m_token.tk == tkSColon)
  6678. {
  6679. this->GetScanner()->ScanForcingPid();
  6680. continue;
  6681. }
  6682. if (m_token.tk == tkRCurly)
  6683. {
  6684. break;
  6685. }
  6686. bool isStatic = false;
  6687. if (m_token.tk == tkSTATIC)
  6688. {
  6689. // 'static' can be used as an IdentifierName here, even in strict mode code. We need to see the next token before we know
  6690. // if this is being used as a keyword. This is similar to the way we treat 'let' in some cases.
  6691. // See https://tc39.github.io/ecma262/#sec-keywords for more info.
  6692. RestorePoint beginStatic;
  6693. this->GetScanner()->Capture(&beginStatic);
  6694. this->GetScanner()->ScanForcingPid();
  6695. if (m_token.tk == tkLParen)
  6696. {
  6697. this->GetScanner()->SeekTo(beginStatic);
  6698. }
  6699. else
  6700. {
  6701. isStatic = true;
  6702. }
  6703. }
  6704. ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;
  6705. charcount_t ichMin = this->GetScanner()->IchMinTok();
  6706. size_t iecpMin = this->GetScanner()->IecpMinTok();
  6707. ParseNodePtr pnodeMemberName = nullptr;
  6708. IdentPtr pidHint = nullptr;
  6709. IdentPtr memberPid = nullptr;
  6710. LPCOLESTR pMemberNameHint = nullptr;
  6711. uint32 memberNameHintLength = 0;
  6712. uint32 memberNameOffset = 0;
  6713. bool isComputedName = false;
  6714. bool isAsyncMethod = false;
  6715. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  6716. {
  6717. RestorePoint parsedAsync;
  6718. this->GetScanner()->Capture(&parsedAsync);
  6719. ichMin = this->GetScanner()->IchMinTok();
  6720. iecpMin = this->GetScanner()->IecpMinTok();
  6721. this->GetScanner()->Scan();
  6722. if (m_token.tk == tkLParen || this->GetScanner()->FHadNewLine())
  6723. {
  6724. this->GetScanner()->SeekTo(parsedAsync);
  6725. }
  6726. else
  6727. {
  6728. isAsyncMethod = true;
  6729. }
  6730. }
  6731. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  6732. m_token.tk == tkStar;
  6733. if (isGenerator)
  6734. {
  6735. fncDeclFlags |= fFncGenerator;
  6736. this->GetScanner()->ScanForcingPid();
  6737. }
  6738. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6739. {
  6740. // Computed member name: [expr] () { }
  6741. LPCOLESTR emptyHint = nullptr;
  6742. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6743. isComputedName = true;
  6744. }
  6745. else // not computed name
  6746. {
  6747. memberPid = this->ParseClassPropertyName(&pidHint);
  6748. if (pidHint)
  6749. {
  6750. pMemberNameHint = pidHint->Psz();
  6751. memberNameHintLength = pidHint->Cch();
  6752. }
  6753. }
  6754. if (buildAST && memberPid)
  6755. {
  6756. pnodeMemberName = CreateStrNode(memberPid);
  6757. }
  6758. if (!isStatic && memberPid == wellKnownPropertyPids.constructor)
  6759. {
  6760. if (hasConstructor || isAsyncMethod)
  6761. {
  6762. Error(ERRsyntax);
  6763. }
  6764. hasConstructor = true;
  6765. LPCOLESTR pConstructorName = nullptr;
  6766. uint32 constructorNameLength = 0;
  6767. uint32 constructorShortNameHintOffset = 0;
  6768. if (pnodeName && pnodeName->pid)
  6769. {
  6770. pConstructorName = pnodeName->pid->Psz();
  6771. constructorNameLength = pnodeName->pid->Cch();
  6772. }
  6773. else
  6774. {
  6775. pConstructorName = pNameHint;
  6776. constructorNameLength = nameHintLength;
  6777. constructorShortNameHintOffset = nameHintOffset;
  6778. }
  6779. {
  6780. SuperRestrictionState::State state = hasExtends ? SuperRestrictionState::CallAndPropertyAllowed : SuperRestrictionState::PropertyAllowed;
  6781. // Add the class constructor flag and base class constructor flag if pnodeExtends is nullptr
  6782. fncDeclFlags |= fFncClassConstructor | (hasExtends ? kFunctionNone : fFncBaseClassConstructor);
  6783. pnodeConstructor = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, state, pConstructorName, /* needsPIDOnRCurlyScan */ true);
  6784. }
  6785. if (pnodeConstructor->IsGenerator())
  6786. {
  6787. Error(ERRConstructorCannotBeGenerator);
  6788. }
  6789. Assert(constructorNameLength >= constructorShortNameHintOffset);
  6790. // The constructor function will get the same name as class.
  6791. pnodeConstructor->hint = pConstructorName;
  6792. pnodeConstructor->hintLength = constructorNameLength;
  6793. pnodeConstructor->hintOffset = constructorShortNameHintOffset;
  6794. pnodeConstructor->pid = pnodeName && pnodeName->pid ? pnodeName->pid : wellKnownPropertyPids.constructor;
  6795. pnodeConstructor->SetHasNonThisStmt();
  6796. pnodeConstructor->SetHasComputedName();
  6797. pnodeConstructor->SetHasHomeObj();
  6798. }
  6799. else
  6800. {
  6801. ParseNodePtr pnodeMember = nullptr;
  6802. bool isMemberNamedGetOrSet = false;
  6803. RestorePoint beginMethodName;
  6804. this->GetScanner()->Capture(&beginMethodName);
  6805. if (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set)
  6806. {
  6807. this->GetScanner()->ScanForcingPid();
  6808. }
  6809. if (m_token.tk == tkLParen)
  6810. {
  6811. this->GetScanner()->SeekTo(beginMethodName);
  6812. isMemberNamedGetOrSet = true;
  6813. }
  6814. if ((memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set) && !isMemberNamedGetOrSet)
  6815. {
  6816. bool isGetter = (memberPid == wellKnownPropertyPids.get);
  6817. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6818. {
  6819. // Computed get/set member name: get|set [expr] () { }
  6820. LPCOLESTR emptyHint = nullptr;
  6821. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6822. isComputedName = true;
  6823. }
  6824. else // not computed name
  6825. {
  6826. memberPid = this->ParseClassPropertyName(&pidHint);
  6827. }
  6828. if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)
  6829. {
  6830. Error(ERRsyntax);
  6831. }
  6832. if (buildAST && memberPid && !isComputedName)
  6833. {
  6834. pnodeMemberName = CreateStrNode(memberPid);
  6835. }
  6836. ParseNodeFnc * pnodeFnc = nullptr;
  6837. {
  6838. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),
  6839. SuperRestrictionState::PropertyAllowed, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true);
  6840. }
  6841. pnodeFnc->SetIsStaticMember(isStatic);
  6842. if (isComputedName)
  6843. {
  6844. pnodeFnc->SetHasComputedName();
  6845. }
  6846. pnodeFnc->SetHasHomeObj();
  6847. if (buildAST)
  6848. {
  6849. pnodeFnc->SetIsAccessor();
  6850. pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);
  6851. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,
  6852. isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,
  6853. &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6854. }
  6855. }
  6856. else
  6857. {
  6858. if (isStatic && (memberPid == wellKnownPropertyPids.prototype))
  6859. {
  6860. Error(ERRsyntax);
  6861. }
  6862. ParseNodeFnc * pnodeFnc = nullptr;
  6863. {
  6864. if (isAsyncMethod)
  6865. {
  6866. fncDeclFlags |= fFncAsync;
  6867. }
  6868. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, SuperRestrictionState::PropertyAllowed, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true);
  6869. if (isAsyncMethod)
  6870. {
  6871. pnodeFnc->cbMin = iecpMin;
  6872. pnodeFnc->ichMin = ichMin;
  6873. }
  6874. if (isAsyncMethod || isGenerator || isComputedName)
  6875. {
  6876. pnodeFnc->cbStringMin = iecpMin;
  6877. }
  6878. }
  6879. pnodeFnc->SetIsStaticMember(isStatic);
  6880. if (isComputedName)
  6881. {
  6882. pnodeFnc->SetHasComputedName();
  6883. }
  6884. pnodeFnc->SetHasHomeObj();
  6885. if (buildAST)
  6886. {
  6887. pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);
  6888. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr /*pgetset*/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6889. }
  6890. }
  6891. if (buildAST)
  6892. {
  6893. Assert(memberNameHintLength >= memberNameOffset);
  6894. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pMemberNameHint; // Fully qualified name
  6895. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = memberNameHintLength;
  6896. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = memberNameOffset;
  6897. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->pid = memberPid; // Short name
  6898. AddToNodeList(isStatic ? &pnodeStaticMembers : &pnodeMembers, isStatic ? &lastStaticMemberNodeRef : &lastMemberNodeRef, pnodeMember);
  6899. }
  6900. }
  6901. }
  6902. size_t cbLimConstructor = 0;
  6903. if (buildAST)
  6904. {
  6905. pnodeClass->ichLim = this->GetScanner()->IchLimTok();
  6906. cbLimConstructor = this->GetScanner()->IecpLimTok();
  6907. }
  6908. if (!hasConstructor)
  6909. {
  6910. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Generating constructor (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6911. RestorePoint endClass;
  6912. this->GetScanner()->Capture(&endClass);
  6913. this->GetScanner()->SeekTo(beginClass);
  6914. pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);
  6915. if (buildAST)
  6916. {
  6917. if (pClassNamePid)
  6918. {
  6919. pnodeConstructor->hint = pClassNamePid->Psz();
  6920. pnodeConstructor->hintLength = pClassNamePid->Cch();
  6921. pnodeConstructor->hintOffset = 0;
  6922. }
  6923. else
  6924. {
  6925. Assert(nameHintLength >= nameHintOffset);
  6926. pnodeConstructor->hint = pNameHint;
  6927. pnodeConstructor->hintLength = nameHintLength;
  6928. pnodeConstructor->hintOffset = nameHintOffset;
  6929. }
  6930. pnodeConstructor->pid = pClassNamePid;
  6931. }
  6932. this->GetScanner()->SeekTo(endClass);
  6933. }
  6934. if (buildAST)
  6935. {
  6936. pnodeConstructor->cbMin = cbMinConstructor;
  6937. pnodeConstructor->cbStringMin = cbMinConstructor;
  6938. pnodeConstructor->cbLim = cbLimConstructor;
  6939. pnodeConstructor->ichMin = pnodeClass->ichMin;
  6940. pnodeConstructor->ichLim = pnodeClass->ichLim;
  6941. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  6942. pnodeClass->pnodeDeclName = pnodeDeclName;
  6943. pnodeClass->pnodeName = pnodeName;
  6944. pnodeClass->pnodeConstructor = pnodeConstructor;
  6945. pnodeClass->pnodeExtends = pnodeExtends;
  6946. pnodeClass->pnodeMembers = pnodeMembers;
  6947. pnodeClass->pnodeStaticMembers = pnodeStaticMembers;
  6948. pnodeClass->isDefaultModuleExport = false;
  6949. }
  6950. FinishParseBlock(pnodeBlock);
  6951. m_fUseStrictMode = strictSave;
  6952. this->GetScanner()->Scan();
  6953. return pnodeClass;
  6954. }
  6955. template<bool buildAST>
  6956. ParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)
  6957. {
  6958. ParseNodePtr pnodeStringLiterals = nullptr;
  6959. ParseNodePtr* lastStringLiteralNodeRef = nullptr;
  6960. ParseNodePtr pnodeRawStringLiterals = nullptr;
  6961. ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;
  6962. ParseNodePtr pnodeSubstitutionExpressions = nullptr;
  6963. ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;
  6964. ParseNodePtr pnodeTagFncArgs = nullptr;
  6965. ParseNodePtr* lastTagFncArgNodeRef = nullptr;
  6966. ParseNodeStr * stringLiteral = nullptr;
  6967. ParseNodeStr * stringLiteralRaw = nullptr;
  6968. ParseNodeStrTemplate * pnodeStringTemplate = nullptr;
  6969. ParseNode * pnodeReturn = nullptr;
  6970. bool templateClosed = false;
  6971. const bool isTagged = pnodeTagFnc != nullptr;
  6972. uint16 stringConstantCount = 0;
  6973. charcount_t ichMin = 0;
  6974. Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);
  6975. if (buildAST)
  6976. {
  6977. pnodeReturn = pnodeStringTemplate = CreateNodeForOpT<knopStrTemplate>();
  6978. pnodeStringTemplate->countStringLiterals = 0;
  6979. pnodeStringTemplate->isTaggedTemplate = isTagged ? TRUE : FALSE;
  6980. // If this is a tagged string template, we need to start building the arg list for the call
  6981. if (isTagged)
  6982. {
  6983. ichMin = pnodeTagFnc->ichMin;
  6984. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);
  6985. }
  6986. }
  6987. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StringTemplates, m_scriptContext);
  6988. OUTPUT_TRACE_DEBUGONLY(
  6989. Js::StringTemplateParsePhase,
  6990. _u("Starting to parse a string template (%s)...\n\tis tagged = %s\n"),
  6991. GetParseType(),
  6992. isTagged ? _u("true") : _u("false (Raw and cooked strings will not differ!)"));
  6993. // String template grammar
  6994. // `...` Simple string template
  6995. // `...${ String template beginning
  6996. // }...${ String template middle
  6997. // }...` String template end
  6998. while (!templateClosed)
  6999. {
  7000. // First, extract the string constant part - we always have one
  7001. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  7002. {
  7003. Error(ERRES5NoOctal);
  7004. }
  7005. // We are not able to pass more than a ushort worth of arguments to the tag
  7006. // so use that as a logical limit on the number of string constant pieces.
  7007. if (stringConstantCount >= Js::Constants::MaxAllowedArgs)
  7008. {
  7009. Error(ERRTooManyArgs);
  7010. }
  7011. // Keep track of the string literal count (must be the same for raw strings)
  7012. // We use this in code gen so we don't need to count the string literals list
  7013. stringConstantCount++;
  7014. // If we are not creating parse nodes, there is no need to create strings
  7015. if (buildAST)
  7016. {
  7017. stringLiteral = CreateStrNode(m_token.GetStr());
  7018. AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);
  7019. // We only need to collect a raw string when we are going to pass the string template to a tag
  7020. if (isTagged)
  7021. {
  7022. // Make the scanner create a PID for the raw string constant for the preceding scan
  7023. IdentPtr pid = this->GetScanner()->GetSecondaryBufferAsPid();
  7024. stringLiteralRaw = CreateStrNode(pid);
  7025. // Should have gotten a raw string literal above
  7026. AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);
  7027. }
  7028. else
  7029. {
  7030. #if DBG
  7031. // Assign the raw string for debug tracing below
  7032. stringLiteralRaw = stringLiteral;
  7033. #endif
  7034. }
  7035. OUTPUT_TRACE_DEBUGONLY(
  7036. Js::StringTemplateParsePhase,
  7037. _u("Parsed string constant: \n\tcooked = \"%s\" \n\traw = \"%s\" \n\tdiffer = %d\n"),
  7038. stringLiteral->pid->Psz(),
  7039. stringLiteralRaw->pid->Psz(),
  7040. stringLiteral->pid->Psz() == stringLiteralRaw->pid->Psz() ? 0 : 1);
  7041. }
  7042. switch (m_token.tk)
  7043. {
  7044. case tkStrTmplEnd:
  7045. case tkStrTmplBasic:
  7046. // We do not need to parse an expression for either the end or basic string template tokens
  7047. templateClosed = true;
  7048. break;
  7049. case tkStrTmplBegin:
  7050. case tkStrTmplMid:
  7051. {
  7052. // In the middle or begin string template token case, we need to parse an expression next
  7053. this->GetScanner()->Scan();
  7054. // Parse the contents of the curly braces as an expression
  7055. ParseNodePtr expression = ParseExpr<buildAST>(0);
  7056. // After parsing expression, scan should leave us with an RCurly token.
  7057. // Use the NoScan version so we do not automatically perform a scan - we need to
  7058. // set the scan state before next scan but we don't want to set that state if
  7059. // the token is not as expected since we'll error in that case.
  7060. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  7061. // Notify the scanner that it should scan for a middle or end string template token
  7062. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  7063. this->GetScanner()->Scan();
  7064. if (buildAST)
  7065. {
  7066. // If we are going to call the tag function, add this expression into the list of args
  7067. if (isTagged)
  7068. {
  7069. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);
  7070. }
  7071. else
  7072. {
  7073. // Otherwise add it to the substitution expression list
  7074. // TODO: Store the arguments and substitution expressions in a single list?
  7075. AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);
  7076. }
  7077. }
  7078. if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))
  7079. {
  7080. // Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return
  7081. // tkStrTmpMid/End unless it is EOF or tkScanError
  7082. Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);
  7083. Error(ERRsyntax);
  7084. }
  7085. OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u("Parsed expression\n"));
  7086. }
  7087. break;
  7088. default:
  7089. Assert(false);
  7090. break;
  7091. }
  7092. }
  7093. if (buildAST)
  7094. {
  7095. pnodeStringTemplate->pnodeStringLiterals = pnodeStringLiterals;
  7096. pnodeStringTemplate->pnodeStringRawLiterals = pnodeRawStringLiterals;
  7097. pnodeStringTemplate->pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;
  7098. pnodeStringTemplate->countStringLiterals = stringConstantCount;
  7099. // We should still have the last string literal.
  7100. // Use the char offset of the end of that constant as the end of the string template.
  7101. pnodeStringTemplate->ichLim = stringLiteral->ichLim;
  7102. // If this is a tagged template, we now have the argument list and can construct a call node
  7103. if (isTagged)
  7104. {
  7105. // Return the call node here and let the byte code generator Emit the string template automagically
  7106. ParseNodeCall * pnodeCall;
  7107. pnodeReturn = pnodeCall = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);
  7108. // We need to set the arg count explicitly
  7109. pnodeCall->argCount = stringConstantCount;
  7110. pnodeCall->hasDestructuring = m_hasDestructuringPattern;
  7111. }
  7112. }
  7113. this->GetScanner()->Scan();
  7114. return pnodeReturn;
  7115. }
  7116. LPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)
  7117. {
  7118. // propertyString could be null, such as 'this.foo' =
  7119. // propertyString could be empty, found in pattern as in (-1)[""][(x = z)]
  7120. OpCode op = pNode->nop;
  7121. LPCOLESTR rightNode = nullptr;
  7122. if (propertyString == nullptr)
  7123. {
  7124. propertyString = _u("");
  7125. }
  7126. if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)
  7127. {
  7128. rightNode = _u("");
  7129. }
  7130. else if (op == knopStr)
  7131. {
  7132. return AppendNameHints(propertyString, pNode->AsParseNodeStr()->pid, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7133. }
  7134. else if (op == knopFlt)
  7135. {
  7136. rightNode = this->GetScanner()->StringFromDbl(pNode->AsParseNodeFloat()->dbl);
  7137. }
  7138. else
  7139. {
  7140. rightNode = op == knopInt ? this->GetScanner()->StringFromLong(pNode->AsParseNodeInt()->lw)
  7141. : pNode->AsParseNodeName()->pid->Psz();
  7142. }
  7143. return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7144. }
  7145. LPCOLESTR Parser::ConstructNameHint(ParseNodeBin * pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)
  7146. {
  7147. Assert(pNode != nullptr);
  7148. Assert(pNode->nop == knopDot || pNode->nop == knopIndex);
  7149. // This method recursively visits nodes in the AST and could cause an SOE crash for long knopDot chains.
  7150. // Although this method could be made non-recursive, Emit (ByteCodeEmitter.cpp) hits a stack probe
  7151. // for shorter chains than which cause SOE here, so add a stack probe to throw SOE rather than crash on SOE.
  7152. // Because of that correspondence, use Js::Constants::MinStackByteCodeVisitor (which is used in Emit)
  7153. // for the stack probe here. See OS#14711878.
  7154. PROBE_STACK_NO_DISPOSE(this->m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  7155. LPCOLESTR leftNode = nullptr;
  7156. if (pNode->pnode1->nop == knopDot || pNode->pnode1->nop == knopIndex)
  7157. {
  7158. leftNode = ConstructNameHint(pNode->pnode1->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  7159. }
  7160. else if (pNode->pnode1->nop == knopName && !pNode->pnode1->AsParseNodeName()->IsSpecialName())
  7161. {
  7162. // We need to skip special names like 'this' because those shouldn't be appended to the
  7163. // name hint in the debugger stack trace.
  7164. // function ctor() {
  7165. // this.func = function() {
  7166. // // If we break here, the stack should say we are in 'func' and not 'this.func'
  7167. // }
  7168. // }
  7169. IdentPtr pid = pNode->pnode1->AsParseNodeName()->pid;
  7170. leftNode = pid->Psz();
  7171. *fullNameHintLength = pid->Cch();
  7172. *pShortNameOffset = 0;
  7173. }
  7174. if (pNode->nop == knopIndex)
  7175. {
  7176. return FormatPropertyString(
  7177. leftNode ? leftNode : Js::Constants::AnonymousFunction, // e.g. f()[0] = function () {}
  7178. pNode->pnode2, fullNameHintLength, pShortNameOffset);
  7179. }
  7180. Assert(pNode->pnode2->nop == knopDot || pNode->pnode2->nop == knopName);
  7181. LPCOLESTR rightNode = nullptr;
  7182. bool wrapWithBrackets = false;
  7183. if (pNode->pnode2->nop == knopDot)
  7184. {
  7185. rightNode = ConstructNameHint(pNode->pnode2->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  7186. }
  7187. else
  7188. {
  7189. rightNode = pNode->pnode2->AsParseNodeName()->pid->Psz();
  7190. wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);
  7191. }
  7192. Assert(rightNode != nullptr);
  7193. return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);
  7194. }
  7195. LPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7196. {
  7197. Assert(rightStr != nullptr);
  7198. Assert(leftLen != 0 || wrapInBrackets);
  7199. Assert(rightLen != 0 || wrapInBrackets);
  7200. bool ignoreDot = rightStr[0] == _u('[') && !wrapInBrackets;//if we wrap in brackets it can be a string literal which can have brackets at the first char
  7201. uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); // 1 (for dot or [) + 1 (for null termination)
  7202. if (wrapInBrackets)
  7203. {
  7204. totalLength++; //1 for ']';
  7205. }
  7206. WCHAR * finalName = AllocateStringOfLength(totalLength);
  7207. if (leftStr != nullptr && leftLen != 0)
  7208. {
  7209. wcscpy_s(finalName, leftLen + 1, leftStr);
  7210. }
  7211. if (ignoreAddDotWithSpace)
  7212. {
  7213. finalName[leftLen++] = (OLECHAR)_u(' ');
  7214. }
  7215. // mutually exclusive from ignoreAddDotWithSpace which is used for getters/setters
  7216. else if (wrapInBrackets)
  7217. {
  7218. finalName[leftLen++] = (OLECHAR)_u('[');
  7219. finalName[totalLength - 2] = (OLECHAR)_u(']');
  7220. }
  7221. else if (!ignoreDot)
  7222. {
  7223. finalName[leftLen++] = (OLECHAR)_u('.');
  7224. }
  7225. //ignore case falls through
  7226. js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);
  7227. finalName[totalLength - 1] = (OLECHAR)_u('\0');
  7228. if (pNameLength != nullptr)
  7229. {
  7230. *pNameLength = totalLength - 1;
  7231. }
  7232. if (pShortNameOffset != nullptr)
  7233. {
  7234. *pShortNameOffset = leftLen;
  7235. }
  7236. return finalName;
  7237. }
  7238. WCHAR * Parser::AllocateStringOfLength(ULONG length)
  7239. {
  7240. Assert(length > 0);
  7241. ULONG totalBytes;
  7242. if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)
  7243. {
  7244. Error(ERRnoMemory);
  7245. }
  7246. WCHAR* finalName = (WCHAR*)this->GetHashTbl()->GetAllocator()->Alloc(totalBytes);
  7247. if (finalName == nullptr)
  7248. {
  7249. Error(ERRnoMemory);
  7250. }
  7251. return finalName;
  7252. }
  7253. LPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7254. {
  7255. if (pShortNameOffset != nullptr)
  7256. {
  7257. *pShortNameOffset = 0;
  7258. }
  7259. if (left == nullptr && !wrapInBrackets)
  7260. {
  7261. if (right)
  7262. {
  7263. *pNameLength = right->Cch();
  7264. return right->Psz();
  7265. }
  7266. return nullptr;
  7267. }
  7268. uint32 leftLen = 0;
  7269. LPCOLESTR leftStr = _u("");
  7270. if (left != nullptr) // if wrapInBrackets is true
  7271. {
  7272. leftStr = left->Psz();
  7273. leftLen = left->Cch();
  7274. }
  7275. if (right == nullptr)
  7276. {
  7277. *pNameLength = leftLen;
  7278. return left->Psz();
  7279. }
  7280. uint32 rightLen = right->Cch();
  7281. return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7282. }
  7283. LPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7284. {
  7285. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7286. if (pShortNameOffset != nullptr)
  7287. {
  7288. *pShortNameOffset = 0;
  7289. }
  7290. Assert(rightLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7291. if (left == nullptr && !wrapInBrackets)
  7292. {
  7293. *pNameLength = rightLen;
  7294. return right;
  7295. }
  7296. LPCOLESTR leftStr = _u("");
  7297. uint32 leftLen = 0;
  7298. if (left != nullptr) // if wrapInBrackets is true
  7299. {
  7300. leftStr = left->Psz();
  7301. leftLen = left->Cch();
  7302. }
  7303. if (rightLen == 0 && !wrapInBrackets)
  7304. {
  7305. *pNameLength = leftLen;
  7306. return left->Psz();
  7307. }
  7308. return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7309. }
  7310. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7311. {
  7312. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7313. if (pShortNameOffset != nullptr)
  7314. {
  7315. *pShortNameOffset = 0;
  7316. }
  7317. Assert(leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7318. if (left == nullptr || (leftLen == 0 && !wrapInBrackets))
  7319. {
  7320. if (right != nullptr)
  7321. {
  7322. *pNameLength = right->Cch();
  7323. return right->Psz();
  7324. }
  7325. return nullptr;
  7326. }
  7327. if (right == nullptr)
  7328. {
  7329. *pNameLength = leftLen;
  7330. return left;
  7331. }
  7332. uint32 rightLen = right->Cch();
  7333. return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7334. }
  7335. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7336. {
  7337. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7338. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7339. if (pShortNameOffset != nullptr)
  7340. {
  7341. *pShortNameOffset = 0;
  7342. }
  7343. Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7344. if (leftLen == 0 && !wrapInBrackets)
  7345. {
  7346. *pNameLength = right ? rightLen : 0;
  7347. return right;
  7348. }
  7349. if (rightLen == 0 && !wrapInBrackets)
  7350. {
  7351. *pNameLength = leftLen;
  7352. return left;
  7353. }
  7354. return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7355. }
  7356. /**
  7357. * Emits a spread error if there is no ambiguity, or marks defers the error for
  7358. * when we can determine if it is a rest error or a spread error.
  7359. *
  7360. * The ambiguity arises when we are parsing a lambda parameter list but we have
  7361. * not seen the => token. At this point, we are either in a parenthesized
  7362. * expression or a parameter list, and cannot issue an error until the matching
  7363. * RParen has been scanned.
  7364. *
  7365. * The actual emission of the error happens in ParseExpr, when we first know if
  7366. * the expression is a lambda parameter list or not.
  7367. *
  7368. */
  7369. void Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)
  7370. {
  7371. if (m_funcParenExprDepth > 0)
  7372. {
  7373. if (m_token.tk == tkRParen)
  7374. {
  7375. if (!m_deferEllipsisError)
  7376. {
  7377. // Capture only the first error instance. Because a lambda will cause a reparse in a formals context, we can assume
  7378. // that this will be a spread error. Nested paren exprs will have their own error instance.
  7379. this->GetScanner()->Capture(&m_deferEllipsisErrorLoc);
  7380. m_deferEllipsisError = true;
  7381. }
  7382. }
  7383. else
  7384. {
  7385. Error(ERRUnexpectedEllipsis);
  7386. }
  7387. }
  7388. else
  7389. {
  7390. Error(ERRInvalidSpreadUse);
  7391. }
  7392. }
  7393. bool Parser::IsTerminateToken(bool fAllowIn)
  7394. {
  7395. return (m_token.tk == tkRCurly ||
  7396. m_token.tk == tkRBrack ||
  7397. m_token.tk == tkRParen ||
  7398. m_token.tk == tkSColon ||
  7399. m_token.tk == tkColon ||
  7400. m_token.tk == tkComma ||
  7401. m_token.tk == tkLimKwd ||
  7402. (m_token.tk == tkIN && fAllowIn) ||
  7403. this->GetScanner()->FHadNewLine());
  7404. }
  7405. /***************************************************************************
  7406. Parse an optional sub expression returning null if there was no expression.
  7407. Checks for no expression by looking for a token that can follow an
  7408. Expression grammar production.
  7409. ***************************************************************************/
  7410. template<bool buildAST>
  7411. bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
  7412. {
  7413. *pnode = nullptr;
  7414. if (IsTerminateToken(!fAllowIn))
  7415. {
  7416. return false;
  7417. }
  7418. IdentToken token;
  7419. ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
  7420. // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
  7421. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7422. // is not detected at byte code gen time because of deferred parsing.
  7423. this->MarkEscapingRef(pnodeT, &token);
  7424. if (pToken)
  7425. {
  7426. *pToken = token;
  7427. }
  7428. *pnode = pnodeT;
  7429. return true;
  7430. }
  7431. /***************************************************************************
  7432. Parse a sub expression.
  7433. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7434. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7435. ***************************************************************************/
  7436. template<bool buildAST>
  7437. ParseNodePtr Parser::ParseExpr(int oplMin,
  7438. BOOL *pfCanAssign,
  7439. BOOL fAllowIn,
  7440. BOOL fAllowEllipsis,
  7441. LPCOLESTR pNameHint,
  7442. uint32 *pHintLength,
  7443. uint32 *pShortNameOffset,
  7444. _Inout_opt_ IdentToken* pToken,
  7445. bool fUnaryOrParen,
  7446. _Inout_opt_ bool* pfLikelyPattern,
  7447. _Inout_opt_ charcount_t *plastRParen)
  7448. {
  7449. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  7450. int opl;
  7451. OpCode nop;
  7452. charcount_t ichMin;
  7453. ParseNodePtr pnode = nullptr;
  7454. ParseNodePtr pnodeT = nullptr;
  7455. BOOL fCanAssign = TRUE;
  7456. bool assignmentStmt = false;
  7457. bool fIsDotOrIndex = false;
  7458. IdentToken term;
  7459. RestorePoint termStart;
  7460. uint32 hintLength = 0;
  7461. uint32 hintOffset = 0;
  7462. BOOL fLikelyPattern = FALSE;
  7463. ParserState parserState;
  7464. if (pHintLength != nullptr)
  7465. {
  7466. hintLength = *pHintLength;
  7467. }
  7468. if (pShortNameOffset != nullptr)
  7469. {
  7470. hintOffset = *pShortNameOffset;
  7471. }
  7472. EnsureStackAvailable();
  7473. // Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.
  7474. CaptureState(&parserState);
  7475. this->GetScanner()->Capture(&termStart);
  7476. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  7477. m_hasDeferredShorthandInitError = false;
  7478. // Is the current token a unary operator?
  7479. if (this->GetHashTbl()->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)
  7480. {
  7481. IdentToken operandToken;
  7482. ichMin = this->GetScanner()->IchMinTok();
  7483. if (nop == knopYield)
  7484. {
  7485. if (!this->GetScanner()->YieldIsKeywordRegion() || oplMin > opl)
  7486. {
  7487. // The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner
  7488. // is not treating yield as a keyword (!this->GetScanner()->YieldIsKeywordRegion()) occurs
  7489. // in strict mode non-generator function contexts.
  7490. //
  7491. // That is, 'yield' is a keyword because of strict mode, but YieldExpression
  7492. // is not a grammar production outside of generator functions.
  7493. //
  7494. // Otherwise it is an error for a yield to appear in the context of a higher level
  7495. // binding operator, be it unary or binary.
  7496. Error(ERRsyntax);
  7497. }
  7498. if (m_currentScope->GetScopeType() == ScopeType_Parameter
  7499. || (m_currentScope->GetScopeType() == ScopeType_Block && m_currentScope->GetEnclosingScope()->GetScopeType() == ScopeType_Parameter)) // Check whether this is a class definition inside param scope
  7500. {
  7501. Error(ERRsyntax);
  7502. }
  7503. }
  7504. else if (nop == knopAwait)
  7505. {
  7506. if (!this->GetScanner()->AwaitIsKeywordRegion() ||
  7507. m_currentScope->GetScopeType() == ScopeType_Parameter ||
  7508. (m_currentScope->GetScopeType() == ScopeType_Block && m_currentScope->GetEnclosingScope()->GetScopeType() == ScopeType_Parameter)) // Check whether this is a class definition inside param scope
  7509. {
  7510. // As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)
  7511. // but the scanner is not treating await as a keyword (!this->GetScanner()->AwaitIsKeyword())
  7512. // occurs in strict mode non-async function contexts.
  7513. //
  7514. // That is, 'await' is a keyword because of strict mode, but AwaitExpression
  7515. // is not a grammar production outside of async functions.
  7516. //
  7517. // Further, await expressions are disallowed within parameter scopes.
  7518. Error(ERRBadAwait);
  7519. }
  7520. }
  7521. this->GetScanner()->Scan();
  7522. if (m_token.tk == tkEllipsis) {
  7523. // ... cannot have a unary prefix.
  7524. Error(ERRUnexpectedEllipsis);
  7525. }
  7526. if (nop == knopYield && !this->GetScanner()->FHadNewLine() && m_token.tk == tkStar)
  7527. {
  7528. this->GetScanner()->Scan();
  7529. nop = knopYieldStar;
  7530. }
  7531. if (nop == knopYield)
  7532. {
  7533. if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, fAllowIn, fAllowEllipsis))
  7534. {
  7535. nop = knopYieldLeaf;
  7536. if (buildAST)
  7537. {
  7538. pnode = CreateNodeForOpT<knopYieldLeaf>(ichMin, this->GetScanner()->IchLimTok());
  7539. }
  7540. }
  7541. }
  7542. else if (nop == knopAwait && m_token.tk == tkColon)
  7543. {
  7544. Error(ERRAwaitAsLabelInAsync);
  7545. }
  7546. else
  7547. {
  7548. // Disallow spread after a unary operator.
  7549. pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr /*hint*/, nullptr /*hintLength*/, nullptr /*hintOffset*/, &operandToken, true, nullptr, plastRParen);
  7550. }
  7551. if (nop != knopYieldLeaf)
  7552. {
  7553. if ((nop == knopIncPre || nop == knopDecPre) && (m_token.tk != tkDArrow))
  7554. {
  7555. if (!fCanAssign &&
  7556. (m_sourceContextInfo
  7557. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7558. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7559. {
  7560. Error(JSERR_CantAssignTo);
  7561. }
  7562. TrackAssignment<buildAST>(pnodeT, &operandToken);
  7563. if (buildAST)
  7564. {
  7565. if (IsStrictMode() && pnodeT->nop == knopName)
  7566. {
  7567. CheckStrictModeEvalArgumentsUsage(pnodeT->AsParseNodeName()->pid);
  7568. }
  7569. }
  7570. else
  7571. {
  7572. if (IsStrictMode() && operandToken.tk == tkID)
  7573. {
  7574. CheckStrictModeEvalArgumentsUsage(operandToken.pid);
  7575. }
  7576. }
  7577. }
  7578. else if (nop == knopEllipsis)
  7579. {
  7580. if (!fAllowEllipsis)
  7581. {
  7582. DeferOrEmitPotentialSpreadError(pnodeT);
  7583. }
  7584. }
  7585. else if (m_token.tk == tkExpo)
  7586. {
  7587. //Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...
  7588. Error(ERRInvalidUseofExponentiationOperator);
  7589. }
  7590. if (buildAST)
  7591. {
  7592. //Do not do the folding for Asm in case of KnopPos as we need this to determine the type
  7593. if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)
  7594. {
  7595. // Fold away a unary '+' on a number.
  7596. pnode = pnodeT;
  7597. }
  7598. else if (nop == knopNeg &&
  7599. ((pnodeT->nop == knopInt && pnodeT->AsParseNodeInt()->lw != 0) ||
  7600. (pnodeT->nop == knopFlt && (pnodeT->AsParseNodeFloat()->dbl != 0 || this->m_InAsmMode))))
  7601. {
  7602. // Fold a unary '-' on a number into the value of the number itself.
  7603. pnode = pnodeT;
  7604. if (pnode->nop == knopInt)
  7605. {
  7606. pnode->AsParseNodeInt()->lw = -pnode->AsParseNodeInt()->lw;
  7607. }
  7608. else
  7609. {
  7610. pnode->AsParseNodeFloat()->dbl = -pnode->AsParseNodeFloat()->dbl;
  7611. }
  7612. }
  7613. else
  7614. {
  7615. pnode = CreateUniNode(nop, pnodeT);
  7616. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  7617. }
  7618. pnode->ichMin = ichMin;
  7619. }
  7620. if (nop == knopDelete)
  7621. {
  7622. if (IsStrictMode())
  7623. {
  7624. if ((buildAST && pnode->AsParseNodeUni()->pnode1->IsUserIdentifier()) ||
  7625. (!buildAST && operandToken.tk == tkID && !this->IsSpecialName(operandToken.pid)))
  7626. {
  7627. Error(ERRInvalidDelete);
  7628. }
  7629. }
  7630. if (buildAST)
  7631. {
  7632. ParseNodePtr pnode1 = pnode->AsParseNodeUni()->pnode1;
  7633. if (m_currentNodeFunc)
  7634. {
  7635. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  7636. {
  7637. // If we delete an arguments property, use the conservative,
  7638. // heap-allocated arguments object.
  7639. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  7640. }
  7641. }
  7642. }
  7643. }
  7644. }
  7645. fCanAssign = FALSE;
  7646. }
  7647. else
  7648. {
  7649. ichMin = this->GetScanner()->IchMinTok();
  7650. pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, TRUE, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex, plastRParen);
  7651. if (pfLikelyPattern != nullptr)
  7652. {
  7653. *pfLikelyPattern = !!fLikelyPattern;
  7654. }
  7655. if (m_token.tk == tkDArrow
  7656. // If we have introduced shorthand error above in the ParseExpr, we need to reset if next token is the assignment.
  7657. || (m_token.tk == tkAsg && oplMin <= koplAsg))
  7658. {
  7659. m_hasDeferredShorthandInitError = false;
  7660. }
  7661. if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)
  7662. {
  7663. this->GetScanner()->SeekTo(termStart);
  7664. // As we are reparsing from the beginning of the destructured literal we need to reset the Block IDs as well to make sure the Block IDs
  7665. // on the pidref stack match.
  7666. int saveNextBlockId = m_nextBlockId;
  7667. m_nextBlockId = parserState.m_nextBlockId;
  7668. ParseDestructuredLiteralWithScopeSave(tkLCurly, false/*isDecl*/, false /*topLevel*/, DIC_ShouldNotParseInitializer);
  7669. // Restore the Block ID at the end of the reparsing so it matches the one at the end of the first pass. We need to do this
  7670. // because we don't parse initializers during reparse and there may be additional blocks (e.g. a class declaration)
  7671. // in the initializers that will cause the next Block ID at the end of the reparsing to be different.
  7672. m_nextBlockId = saveNextBlockId;
  7673. if (buildAST)
  7674. {
  7675. this->SetHasDestructuringPattern(true);
  7676. pnode = ConvertToPattern(pnode);
  7677. }
  7678. }
  7679. if (buildAST)
  7680. {
  7681. pNameHint = NULL;
  7682. if (pnode->nop == knopName)
  7683. {
  7684. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7685. pNameHint = pid->Psz();
  7686. hintLength = pid->Cch();
  7687. hintOffset = 0;
  7688. }
  7689. else if (pnode->nop == knopDot || pnode->nop == knopIndex)
  7690. {
  7691. if (CONFIG_FLAG(UseFullName))
  7692. {
  7693. pNameHint = ConstructNameHint(pnode->AsParseNodeBin(), &hintLength, &hintOffset);
  7694. }
  7695. else
  7696. {
  7697. ParseNodePtr pnodeName = pnode;
  7698. while (pnodeName->nop == knopDot)
  7699. {
  7700. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  7701. }
  7702. if (pnodeName->nop == knopName)
  7703. {
  7704. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7705. pNameHint = pid->Psz();
  7706. hintLength = pid->Cch();
  7707. hintOffset = 0;
  7708. }
  7709. }
  7710. }
  7711. }
  7712. // Check for postfix unary operators.
  7713. if (!this->GetScanner()->FHadNewLine() &&
  7714. (tkInc == m_token.tk || tkDec == m_token.tk))
  7715. {
  7716. if (!fCanAssign &&
  7717. (m_sourceContextInfo
  7718. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7719. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7720. {
  7721. Error(JSERR_CantAssignTo);
  7722. }
  7723. TrackAssignment<buildAST>(pnode, &term);
  7724. fCanAssign = FALSE;
  7725. if (buildAST)
  7726. {
  7727. if (IsStrictMode() && pnode->nop == knopName)
  7728. {
  7729. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7730. }
  7731. this->CheckArguments(pnode);
  7732. pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);
  7733. pnode->ichLim = this->GetScanner()->IchLimTok();
  7734. }
  7735. else
  7736. {
  7737. if (IsStrictMode() && term.tk == tkID)
  7738. {
  7739. CheckStrictModeEvalArgumentsUsage(term.pid);
  7740. }
  7741. // This expression is not an identifier
  7742. term.tk = tkNone;
  7743. }
  7744. this->GetScanner()->Scan();
  7745. }
  7746. }
  7747. // Process a sequence of operators and operands.
  7748. for (;;)
  7749. {
  7750. if (!this->GetHashTbl()->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)
  7751. {
  7752. break;
  7753. }
  7754. if (!fAllowIn && nop == knopIn)
  7755. {
  7756. break;
  7757. }
  7758. Assert(opl != koplNo);
  7759. if (opl == koplAsg)
  7760. {
  7761. if (m_token.tk != tkDArrow)
  7762. {
  7763. // Assignment operator. These are the only right associative
  7764. // binary operators. We also need to special case the left
  7765. // operand - it should only be a LeftHandSideExpression.
  7766. Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);
  7767. TrackAssignment<buildAST>(pnode, &term);
  7768. if (buildAST)
  7769. {
  7770. if (IsStrictMode() && pnode->nop == knopName)
  7771. {
  7772. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7773. }
  7774. // Assignment stmt of the form "this.<id> = <expr>"
  7775. if (nop == knopAsg
  7776. && pnode->nop == knopDot
  7777. && pnode->AsParseNodeBin()->pnode1->nop == knopName
  7778. && pnode->AsParseNodeBin()->pnode1->AsParseNodeName()->pid == wellKnownPropertyPids._this
  7779. && pnode->AsParseNodeBin()->pnode2->nop == knopName)
  7780. {
  7781. if (pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->pid != wellKnownPropertyPids.__proto__)
  7782. {
  7783. assignmentStmt = true;
  7784. }
  7785. }
  7786. }
  7787. else
  7788. {
  7789. if (IsStrictMode() && term.tk == tkID)
  7790. {
  7791. CheckStrictModeEvalArgumentsUsage(term.pid);
  7792. }
  7793. }
  7794. }
  7795. if (opl < oplMin)
  7796. {
  7797. break;
  7798. }
  7799. if (m_token.tk != tkDArrow && !fCanAssign &&
  7800. (m_sourceContextInfo
  7801. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7802. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7803. {
  7804. Error(JSERR_CantAssignTo);
  7805. // No recovery necessary since this is a semantic, not structural, error.
  7806. }
  7807. }
  7808. else if (opl == koplExpo)
  7809. {
  7810. // ** operator is right associative
  7811. if (opl < oplMin)
  7812. {
  7813. break;
  7814. }
  7815. }
  7816. else if (opl <= oplMin)
  7817. {
  7818. break;
  7819. }
  7820. // This expression is not an identifier
  7821. term.tk = tkNone;
  7822. // Precedence is high enough. Consume the operator token.
  7823. this->GetScanner()->Scan();
  7824. fCanAssign = !!fLikelyPattern;
  7825. // Special case the "?:" operator
  7826. if (nop == knopQmark)
  7827. {
  7828. pnodeT = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);
  7829. ChkCurTok(tkColon, ERRnoColon);
  7830. ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, plastRParen);
  7831. if (buildAST)
  7832. {
  7833. pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);
  7834. this->CheckArguments(pnode->AsParseNodeTri()->pnode2);
  7835. this->CheckArguments(pnode->AsParseNodeTri()->pnode3);
  7836. }
  7837. }
  7838. else if (nop == knopFncDecl)
  7839. {
  7840. ushort flags = fFncLambda;
  7841. size_t iecpMin = 0;
  7842. bool isAsyncMethod = false;
  7843. RestoreStateFrom(&parserState);
  7844. this->GetScanner()->SeekTo(termStart);
  7845. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  7846. {
  7847. ichMin = this->GetScanner()->IchMinTok();
  7848. iecpMin = this->GetScanner()->IecpMinTok();
  7849. this->GetScanner()->Scan();
  7850. if ((m_token.tk == tkID || m_token.tk == tkLParen) && !this->GetScanner()->FHadNewLine())
  7851. {
  7852. flags |= fFncAsync;
  7853. isAsyncMethod = true;
  7854. }
  7855. else
  7856. {
  7857. this->GetScanner()->SeekTo(termStart);
  7858. }
  7859. }
  7860. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::Disallowed, nullptr, /* needsPIDOnRCurlyScan = */false, /* fUnaryOrParen = */ false, fAllowIn);
  7861. if (isAsyncMethod)
  7862. {
  7863. pnode->AsParseNodeFnc()->cbStringMin = iecpMin;
  7864. }
  7865. // ArrowFunction/AsyncArrowFunction is part of AssignmentExpression, which should terminate the expression unless followed by a comma
  7866. if (m_token.tk != tkComma && m_token.tk != tkIN)
  7867. {
  7868. if (!(IsTerminateToken(false)))
  7869. {
  7870. Error(ERRnoSemic);
  7871. }
  7872. break;
  7873. }
  7874. }
  7875. else // a binary operator
  7876. {
  7877. if (nop == knopComma && m_token.tk == tkRParen)
  7878. {
  7879. // Trailing comma
  7880. this->GetScanner()->Capture(&m_deferCommaErrorLoc);
  7881. m_deferCommaError = true;
  7882. break;
  7883. }
  7884. ParseNode* pnode1 = pnode;
  7885. // Parse the operand, make a new node, and look for more
  7886. IdentToken token;
  7887. ParseNode* pnode2 = ParseExpr<buildAST>(
  7888. opl, nullptr, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token, false, nullptr, plastRParen);
  7889. // Detect nested function escapes of the pattern "o.f = function(){...}" or "o[s] = function(){...}".
  7890. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7891. // is not detected at byte code gen time because of deferred parsing.
  7892. if (fIsDotOrIndex && nop == knopAsg)
  7893. {
  7894. this->MarkEscapingRef(pnodeT, &token);
  7895. }
  7896. if (buildAST)
  7897. {
  7898. Assert(pnode2 != nullptr);
  7899. if (pnode2->nop == knopFncDecl)
  7900. {
  7901. Assert(hintLength >= hintOffset);
  7902. pnode2->AsParseNodeFnc()->hint = pNameHint;
  7903. pnode2->AsParseNodeFnc()->hintLength = hintLength;
  7904. pnode2->AsParseNodeFnc()->hintOffset = hintOffset;
  7905. if (pnode1->nop == knopDot)
  7906. {
  7907. pnode2->AsParseNodeFnc()->isNameIdentifierRef = false;
  7908. }
  7909. else if (pnode1->nop == knopName)
  7910. {
  7911. PidRefStack *pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7912. pidRef->isFuncAssignment = true;
  7913. }
  7914. }
  7915. else if (pnode2->nop == knopClassDecl && pnode1->nop == knopDot)
  7916. {
  7917. Assert(pnode2->AsParseNodeClass()->pnodeConstructor);
  7918. if (!pnode2->AsParseNodeClass()->pnodeConstructor->pid)
  7919. {
  7920. pnode2->AsParseNodeClass()->pnodeConstructor->isNameIdentifierRef = false;
  7921. }
  7922. }
  7923. else if (pnode1->nop == knopName && nop == knopIn)
  7924. {
  7925. PidRefStack* pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7926. pidRef->SetIsUsedInLdElem(true);
  7927. }
  7928. pnode = CreateBinNode(nop, pnode1, pnode2);
  7929. }
  7930. pNameHint = nullptr;
  7931. }
  7932. }
  7933. if (buildAST)
  7934. {
  7935. if (!assignmentStmt)
  7936. {
  7937. // Don't set the flag for following nodes
  7938. switch (pnode->nop)
  7939. {
  7940. case knopName:
  7941. case knopInt:
  7942. case knopFlt:
  7943. case knopStr:
  7944. case knopRegExp:
  7945. case knopNull:
  7946. case knopFalse:
  7947. case knopTrue:
  7948. break;
  7949. default:
  7950. if (m_currentNodeFunc)
  7951. {
  7952. m_currentNodeFunc->SetHasNonThisStmt();
  7953. }
  7954. else if (m_currentNodeProg)
  7955. {
  7956. m_currentNodeProg->SetHasNonThisStmt();
  7957. }
  7958. }
  7959. }
  7960. }
  7961. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;
  7962. if (NULL != pfCanAssign)
  7963. {
  7964. *pfCanAssign = fCanAssign;
  7965. }
  7966. // Pass back identifier if requested
  7967. if (pToken && term.tk == tkID)
  7968. {
  7969. *pToken = term;
  7970. }
  7971. //Track "obj.a" assignment patterns here - Promote the Assignment state for the property's PID.
  7972. // This includes =, += etc.
  7973. if (pnode != NULL)
  7974. {
  7975. uint nodeType = ParseNode::Grfnop(pnode->nop);
  7976. if (nodeType & fnopAsg)
  7977. {
  7978. if (nodeType & fnopBin)
  7979. {
  7980. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  7981. Assert(lhs);
  7982. if (lhs->nop == knopDot)
  7983. {
  7984. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7985. if (propertyNode->nop == knopName)
  7986. {
  7987. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  7988. }
  7989. }
  7990. }
  7991. else if (nodeType & fnopUni)
  7992. {
  7993. // cases like obj.a++, ++obj.a
  7994. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  7995. if (lhs->nop == knopDot)
  7996. {
  7997. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7998. if (propertyNode->nop == knopName)
  7999. {
  8000. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  8001. }
  8002. }
  8003. }
  8004. }
  8005. }
  8006. return pnode;
  8007. }
  8008. template<bool buildAST>
  8009. void Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)
  8010. {
  8011. if (buildAST)
  8012. {
  8013. Assert(pnodeT != nullptr);
  8014. if (pnodeT->nop == knopName)
  8015. {
  8016. PidRefStack *ref = pnodeT->AsParseNodeName()->pid->GetTopRef();
  8017. Assert(ref);
  8018. ref->isAsg = true;
  8019. }
  8020. }
  8021. else
  8022. {
  8023. Assert(pToken != nullptr);
  8024. if (pToken->tk == tkID)
  8025. {
  8026. PidRefStack *ref = pToken->pid->GetTopRef();
  8027. Assert(ref);
  8028. ref->isAsg = true;
  8029. }
  8030. }
  8031. }
  8032. PidRefStack* Parser::PushPidRef(IdentPtr pid)
  8033. {
  8034. ParseNodeFnc* currentFnc = GetCurrentFunctionNode();
  8035. if (this->IsCreatingStateCache())
  8036. {
  8037. IdentPtrSet* capturedNames = currentFnc->EnsureCapturedNames(&m_nodeAllocator);
  8038. capturedNames->AddNew(pid);
  8039. }
  8040. if (PHASE_ON1(Js::ParallelParsePhase))
  8041. {
  8042. // NOTE: the phase check is here to protect perf. See OSG 1020424.
  8043. // In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather
  8044. // than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.
  8045. return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->blockId, currentFnc->functionId);
  8046. }
  8047. Assert(GetCurrentBlock() != nullptr);
  8048. AssertMsg(pid != nullptr, "PID should be created");
  8049. PidRefStack *ref = pid->GetTopRef(m_nextBlockId - 1);
  8050. int blockId = GetCurrentBlock()->blockId;
  8051. int funcId = currentFnc->functionId;
  8052. if (!ref || (ref->GetScopeId() < blockId))
  8053. {
  8054. ref = Anew(&m_nodeAllocator, PidRefStack);
  8055. if (ref == nullptr)
  8056. {
  8057. Error(ERRnoMemory);
  8058. }
  8059. pid->PushPidRef(blockId, funcId, ref);
  8060. }
  8061. else if (m_reparsingLambdaParams)
  8062. {
  8063. // If we're reparsing params, then we may have pid refs left behind from the first pass. Make sure we're
  8064. // working with the right ref at this point.
  8065. ref = this->FindOrAddPidRef(pid, blockId, funcId);
  8066. // Fix up the function ID if we're reparsing lambda parameters.
  8067. ref->funcId = funcId;
  8068. }
  8069. return ref;
  8070. }
  8071. PidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)
  8072. {
  8073. PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);
  8074. if (ref == NULL)
  8075. {
  8076. Error(ERRnoMemory);
  8077. }
  8078. return ref;
  8079. }
  8080. void Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)
  8081. {
  8082. PidRefStack *prevRef = pid->RemovePrevPidRef(ref);
  8083. Assert(prevRef);
  8084. if (prevRef->GetSym() == nullptr)
  8085. {
  8086. AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);
  8087. }
  8088. }
  8089. void Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)
  8090. {
  8091. PidRefStack *ref = pid->GetTopRef();
  8092. while (ref && ref->GetScopeId() >= blockId)
  8093. {
  8094. ref->SetDynamicBinding();
  8095. ref = ref->prev;
  8096. }
  8097. }
  8098. ParseNodeBlock* Parser::GetFunctionBlock()
  8099. {
  8100. Assert(m_currentBlockInfo != nullptr);
  8101. return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;
  8102. }
  8103. ParseNodeBlock* Parser::GetCurrentBlock()
  8104. {
  8105. return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;
  8106. }
  8107. BlockInfoStack* Parser::GetCurrentBlockInfo()
  8108. {
  8109. return m_currentBlockInfo;
  8110. }
  8111. BlockInfoStack* Parser::GetCurrentFunctionBlockInfo()
  8112. {
  8113. return m_currentBlockInfo->pBlockInfoFunction;
  8114. }
  8115. /***************************************************************************
  8116. Parse a variable declaration.
  8117. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  8118. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  8119. ***************************************************************************/
  8120. template<bool buildAST>
  8121. ParseNodePtr Parser::ParseVariableDeclaration(
  8122. tokens declarationType, charcount_t ichMin,
  8123. BOOL fAllowIn/* = TRUE*/,
  8124. BOOL* pfForInOk/* = nullptr*/,
  8125. BOOL singleDefOnly/* = FALSE*/,
  8126. BOOL allowInit/* = TRUE*/,
  8127. BOOL isTopVarParse/* = TRUE*/,
  8128. BOOL isFor/* = FALSE*/,
  8129. BOOL* nativeForOk /*= nullptr*/)
  8130. {
  8131. ParseNodePtr pnodeThis = nullptr;
  8132. ParseNodePtr pnodeInit;
  8133. ParseNodePtr pnodeList = nullptr;
  8134. ParseNodePtr *lastNodeRef = nullptr;
  8135. LPCOLESTR pNameHint = nullptr;
  8136. uint32 nameHintLength = 0;
  8137. uint32 nameHintOffset = 0;
  8138. Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);
  8139. for (;;)
  8140. {
  8141. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  8142. {
  8143. pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);
  8144. if (pnodeThis != nullptr)
  8145. {
  8146. pnodeThis->ichMin = ichMin;
  8147. pnodeThis->SetIsPatternDeclaration();
  8148. }
  8149. }
  8150. else
  8151. {
  8152. if (m_token.tk != tkID)
  8153. {
  8154. IdentifierExpectedError(m_token);
  8155. }
  8156. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  8157. Assert(pid);
  8158. pNameHint = pid->Psz();
  8159. nameHintLength = pid->Cch();
  8160. nameHintOffset = 0;
  8161. if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))
  8162. {
  8163. Error(ERRLetIDInLexicalDecl, pnodeThis);
  8164. }
  8165. if (declarationType == tkVAR)
  8166. {
  8167. pnodeThis = CreateVarDeclNode(pid, STVariable);
  8168. }
  8169. else if (declarationType == tkCONST)
  8170. {
  8171. pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);
  8172. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Const, m_scriptContext);
  8173. }
  8174. else
  8175. {
  8176. pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);
  8177. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Let, m_scriptContext);
  8178. }
  8179. if (pid == wellKnownPropertyPids.arguments)
  8180. {
  8181. // This var declaration may change the way an 'arguments' identifier in the function is resolved
  8182. if (declarationType == tkVAR)
  8183. {
  8184. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_varDeclaration;
  8185. }
  8186. else
  8187. {
  8188. if (GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  8189. {
  8190. // Only override arguments if we are at the function block level.
  8191. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  8192. }
  8193. }
  8194. }
  8195. if (pnodeThis)
  8196. {
  8197. pnodeThis->ichMin = ichMin;
  8198. }
  8199. this->GetScanner()->Scan();
  8200. if (m_token.tk == tkAsg)
  8201. {
  8202. if (!allowInit)
  8203. {
  8204. Error(ERRUnexpectedDefault);
  8205. }
  8206. if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))
  8207. {
  8208. *pfForInOk = FALSE;
  8209. }
  8210. this->GetScanner()->Scan();
  8211. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  8212. if (buildAST)
  8213. {
  8214. AnalysisAssert(pnodeThis);
  8215. pnodeThis->AsParseNodeVar()->pnodeInit = pnodeInit;
  8216. pnodeThis->ichLim = pnodeInit->ichLim;
  8217. if (pnodeInit->nop == knopFncDecl)
  8218. {
  8219. Assert(nameHintLength >= nameHintOffset);
  8220. pnodeInit->AsParseNodeFnc()->hint = pNameHint;
  8221. pnodeInit->AsParseNodeFnc()->hintLength = nameHintLength;
  8222. pnodeInit->AsParseNodeFnc()->hintOffset = nameHintOffset;
  8223. pnodeThis->AsParseNodeVar()->pid->GetTopRef()->isFuncAssignment = true;
  8224. }
  8225. else
  8226. {
  8227. this->CheckArguments(pnodeInit);
  8228. }
  8229. pNameHint = nullptr;
  8230. }
  8231. //Track var a =, let a= , const a =
  8232. // This is for FixedFields Constant Heuristics
  8233. if (pnodeThis && pnodeThis->AsParseNodeVar()->pnodeInit != nullptr)
  8234. {
  8235. pnodeThis->AsParseNodeVar()->sym->PromoteAssignmentState();
  8236. }
  8237. }
  8238. else if (declarationType == tkCONST /*pnodeThis->nop == knopConstDecl*/
  8239. && !singleDefOnly
  8240. && !(isFor && TokIsForInOrForOf()))
  8241. {
  8242. Error(ERRUninitializedConst);
  8243. }
  8244. if (m_currentNodeFunc && pnodeThis && pnodeThis->AsParseNodeVar()->sym->GetIsFormal())
  8245. {
  8246. m_currentNodeFunc->SetHasAnyWriteToFormals(true);
  8247. }
  8248. }
  8249. if (singleDefOnly)
  8250. {
  8251. return pnodeThis;
  8252. }
  8253. if (buildAST)
  8254. {
  8255. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);
  8256. }
  8257. if (m_token.tk != tkComma)
  8258. {
  8259. return pnodeList;
  8260. }
  8261. if (pfForInOk)
  8262. {
  8263. // don't allow "for (var a, b in c)"
  8264. *pfForInOk = FALSE;
  8265. }
  8266. this->GetScanner()->Scan();
  8267. ichMin = this->GetScanner()->IchMinTok();
  8268. }
  8269. }
  8270. /***************************************************************************
  8271. Parse try-catch-finally statement
  8272. ***************************************************************************/
  8273. // The try-catch-finally tree nests the try-catch within a try-finally.
  8274. // This matches the new runtime implementation.
  8275. template<bool buildAST>
  8276. ParseNodeStmt * Parser::ParseTryCatchFinally()
  8277. {
  8278. this->m_tryCatchOrFinallyDepth++;
  8279. ParseNodeTry * pnodeT = ParseTry<buildAST>();
  8280. ParseNodeTryCatch * pnodeTC = nullptr;
  8281. StmtNest stmt;
  8282. bool hasCatch = false;
  8283. if (tkCATCH == m_token.tk)
  8284. {
  8285. hasCatch = true;
  8286. if (buildAST)
  8287. {
  8288. pnodeTC = CreateNodeForOpT<knopTryCatch>();
  8289. pnodeT->pnodeOuter = pnodeTC;
  8290. pnodeTC->pnodeTry = pnodeT;
  8291. }
  8292. PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr);
  8293. ParseNodeCatch * pnodeCatch = ParseCatch<buildAST>();
  8294. if (buildAST)
  8295. {
  8296. pnodeTC->pnodeCatch = pnodeCatch;
  8297. }
  8298. PopStmt(&stmt);
  8299. }
  8300. if (tkFINALLY != m_token.tk)
  8301. {
  8302. if (!hasCatch)
  8303. {
  8304. Error(ERRnoCatch);
  8305. }
  8306. Assert(!buildAST || pnodeTC);
  8307. this->m_tryCatchOrFinallyDepth--;
  8308. return pnodeTC;
  8309. }
  8310. ParseNodeTryFinally * pnodeTF = nullptr;
  8311. if (buildAST)
  8312. {
  8313. pnodeTF = CreateNodeForOpT<knopTryFinally>();
  8314. }
  8315. PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr);
  8316. ParseNodeFinally * pnodeFinally = ParseFinally<buildAST>();
  8317. if (buildAST)
  8318. {
  8319. if (!hasCatch)
  8320. {
  8321. pnodeTF->pnodeTry = pnodeT;
  8322. pnodeT->pnodeOuter = pnodeTF;
  8323. }
  8324. else
  8325. {
  8326. pnodeTF->pnodeTry = CreateNodeForOpT<knopTry>();
  8327. pnodeTF->pnodeTry->pnodeOuter = pnodeTF;
  8328. pnodeTF->pnodeTry->pnodeBody = pnodeTC;
  8329. pnodeTC->pnodeOuter = pnodeTF->pnodeTry;
  8330. }
  8331. pnodeTF->pnodeFinally = pnodeFinally;
  8332. }
  8333. PopStmt(&stmt);
  8334. this->m_tryCatchOrFinallyDepth--;
  8335. return pnodeTF;
  8336. }
  8337. template<bool buildAST>
  8338. ParseNodeTry * Parser::ParseTry()
  8339. {
  8340. ParseNodeTry * pnode = nullptr;
  8341. StmtNest stmt;
  8342. Assert(tkTRY == m_token.tk);
  8343. if (buildAST)
  8344. {
  8345. pnode = CreateNodeForOpT<knopTry>();
  8346. }
  8347. this->GetScanner()->Scan();
  8348. if (tkLCurly != m_token.tk)
  8349. {
  8350. Error(ERRnoLcurly);
  8351. }
  8352. PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr);
  8353. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8354. if (buildAST)
  8355. {
  8356. pnode->pnodeBody = pnodeBody;
  8357. if (pnode->pnodeBody)
  8358. pnode->ichLim = pnode->pnodeBody->ichLim;
  8359. }
  8360. PopStmt(&stmt);
  8361. return pnode;
  8362. }
  8363. template<bool buildAST>
  8364. ParseNodeFinally * Parser::ParseFinally()
  8365. {
  8366. ParseNodeFinally * pnode = nullptr;
  8367. StmtNest stmt;
  8368. Assert(tkFINALLY == m_token.tk);
  8369. if (buildAST)
  8370. {
  8371. pnode = CreateNodeForOpT<knopFinally>();
  8372. }
  8373. this->GetScanner()->Scan();
  8374. if (tkLCurly != m_token.tk)
  8375. {
  8376. Error(ERRnoLcurly);
  8377. }
  8378. PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr);
  8379. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8380. if (buildAST)
  8381. {
  8382. pnode->pnodeBody = pnodeBody;
  8383. if (!pnode->pnodeBody)
  8384. // Will only occur due to error correction.
  8385. pnode->pnodeBody = CreateNodeForOpT<knopEmpty>();
  8386. else
  8387. pnode->ichLim = pnode->pnodeBody->ichLim;
  8388. }
  8389. PopStmt(&stmt);
  8390. return pnode;
  8391. }
  8392. template<bool buildAST>
  8393. ParseNodeCatch * Parser::ParseCatch()
  8394. {
  8395. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8396. ParseNodeCatch * pnode = nullptr;
  8397. ParseNodeBlock * pnodeCatchScope = nullptr;
  8398. StmtNest stmt;
  8399. IdentPtr pidCatch = nullptr;
  8400. if (tkCATCH == m_token.tk)
  8401. {
  8402. charcount_t ichMin;
  8403. if (buildAST)
  8404. {
  8405. ichMin = this->GetScanner()->IchMinTok();
  8406. }
  8407. this->GetScanner()->Scan(); //catch
  8408. ChkCurTok(tkLParen, ERRnoLparen); //catch(
  8409. bool isPattern = false;
  8410. if (tkID != m_token.tk)
  8411. {
  8412. isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();
  8413. if (!isPattern)
  8414. {
  8415. IdentifierExpectedError(m_token);
  8416. }
  8417. }
  8418. if (buildAST)
  8419. {
  8420. pnode = CreateNodeForOpT<knopCatch>(ichMin);
  8421. pnode->pnodeNext = nullptr;
  8422. PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr);
  8423. }
  8424. pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);
  8425. if (buildAST)
  8426. {
  8427. // Add this catch to the current scope list.
  8428. if (m_ppnodeExprScope)
  8429. {
  8430. Assert(*m_ppnodeExprScope == nullptr);
  8431. *m_ppnodeExprScope = pnode;
  8432. m_ppnodeExprScope = &pnode->pnodeNext;
  8433. }
  8434. else
  8435. {
  8436. Assert(m_ppnodeScope);
  8437. Assert(*m_ppnodeScope == nullptr);
  8438. *m_ppnodeScope = pnode;
  8439. m_ppnodeScope = &pnode->pnodeNext;
  8440. }
  8441. // Keep a list of function expressions (not declarations) at this scope.
  8442. ppnodeExprScopeSave = m_ppnodeExprScope;
  8443. m_ppnodeExprScope = &pnode->pnodeScopes;
  8444. pnode->pnodeScopes = nullptr;
  8445. }
  8446. if (isPattern)
  8447. {
  8448. ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, true /*topLevel*/, DIC_ForceErrorOnInitializer);
  8449. if (buildAST)
  8450. {
  8451. pnode->SetParam(CreateParamPatternNode(pnodePattern));
  8452. Scope *scope = pnodeCatchScope->scope;
  8453. pnode->scope = scope;
  8454. }
  8455. }
  8456. else
  8457. {
  8458. if (IsStrictMode())
  8459. {
  8460. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  8461. if (pid == wellKnownPropertyPids.eval)
  8462. {
  8463. Error(ERREvalUsage);
  8464. }
  8465. else if (pid == wellKnownPropertyPids.arguments)
  8466. {
  8467. Error(ERRArgsUsage);
  8468. }
  8469. }
  8470. pidCatch = m_token.GetIdentifier(this->GetHashTbl());
  8471. PidRefStack *ref = this->FindOrAddPidRef(pidCatch, GetCurrentBlock()->blockId, GetCurrentFunctionNode()->functionId);
  8472. ParseNodeName * pnodeParam = CreateNameNode(pidCatch);
  8473. pnodeParam->SetSymRef(ref);
  8474. const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());
  8475. int nameLength = pidCatch->Cch();
  8476. SymbolName const symName(name, nameLength);
  8477. Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);
  8478. if (sym == nullptr)
  8479. {
  8480. Error(ERRnoMemory);
  8481. }
  8482. sym->SetPid(pidCatch);
  8483. Assert(ref->GetSym() == nullptr);
  8484. ref->SetSym(sym);
  8485. Scope *scope = pnodeCatchScope->scope;
  8486. scope->AddNewSymbol(sym);
  8487. if (buildAST)
  8488. {
  8489. pnode->SetParam(pnodeParam);
  8490. pnode->scope = scope;
  8491. }
  8492. this->GetScanner()->Scan();
  8493. }
  8494. charcount_t ichLim;
  8495. if (buildAST)
  8496. {
  8497. ichLim = this->GetScanner()->IchLimTok();
  8498. }
  8499. ChkCurTok(tkRParen, ERRnoRparen); //catch(id[:expr])
  8500. if (tkLCurly != m_token.tk)
  8501. {
  8502. Error(ERRnoLcurly);
  8503. }
  8504. ParseNodePtr pnodeBody = ParseStatement<buildAST>(); //catch(id[:expr]) {block}
  8505. if (buildAST)
  8506. {
  8507. pnode->pnodeBody = pnodeBody;
  8508. pnode->ichLim = ichLim;
  8509. }
  8510. if (pnodeCatchScope != nullptr)
  8511. {
  8512. FinishParseBlock(pnodeCatchScope);
  8513. }
  8514. if (pnodeCatchScope->GetCallsEval() || pnodeCatchScope->GetChildCallsEval())
  8515. {
  8516. GetCurrentBlock()->SetChildCallsEval(true);
  8517. }
  8518. if (buildAST)
  8519. {
  8520. PopStmt(&stmt);
  8521. // Restore the lists of function expression scopes.
  8522. Assert(m_ppnodeExprScope);
  8523. Assert(*m_ppnodeExprScope == nullptr);
  8524. m_ppnodeExprScope = ppnodeExprScopeSave;
  8525. }
  8526. }
  8527. return pnode;
  8528. }
  8529. template<bool buildAST>
  8530. ParseNodeCase * Parser::ParseCase(ParseNodePtr *ppnodeBody)
  8531. {
  8532. ParseNodeCase * pnodeT = nullptr;
  8533. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8534. this->GetScanner()->Scan();
  8535. ParseNodePtr pnodeExpr = ParseExpr<buildAST>();
  8536. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8537. ChkCurTok(tkColon, ERRnoColon);
  8538. if (buildAST)
  8539. {
  8540. pnodeT = CreateNodeForOpT<knopCase>(ichMinT);
  8541. pnodeT->pnodeExpr = pnodeExpr;
  8542. pnodeT->ichLim = ichLim;
  8543. }
  8544. ParseStmtList<buildAST>(ppnodeBody);
  8545. return pnodeT;
  8546. }
  8547. /***************************************************************************
  8548. Parse a single statement. Digest a trailing semicolon.
  8549. ***************************************************************************/
  8550. template<bool buildAST>
  8551. ParseNodePtr Parser::ParseStatement()
  8552. {
  8553. ParseNodePtr pnode = nullptr;
  8554. LabelId* pLabelIdList = nullptr;
  8555. charcount_t ichMin = 0;
  8556. size_t iecpMin = 0;
  8557. StmtNest stmt;
  8558. StmtNest *pstmt;
  8559. BOOL fForInOrOfOkay;
  8560. BOOL fCanAssign;
  8561. IdentPtr pid;
  8562. uint fnop;
  8563. bool expressionStmt = false;
  8564. bool isAsyncMethod = false;
  8565. bool labelledStatement = false;
  8566. tokens tok;
  8567. #if EXCEPTION_RECOVERY
  8568. ParseNodeTryCatch * pParentTryCatch = nullptr;
  8569. ParseNodeBlock * pTryBlock = nullptr;
  8570. ParseNodeTry * pTry = nullptr;
  8571. ParseNodeBlock * pParentTryCatchBlock = nullptr;
  8572. StmtNest stmtTryCatchBlock;
  8573. StmtNest stmtTryCatch;
  8574. StmtNest stmtTry;
  8575. StmtNest stmtTryBlock;
  8576. #endif
  8577. if (buildAST)
  8578. {
  8579. #if EXCEPTION_RECOVERY
  8580. if (Js::Configuration::Global.flags.SwallowExceptions)
  8581. {
  8582. // If we're swallowing exceptions, surround this statement with a try/catch block:
  8583. //
  8584. // Before: x.y = 3;
  8585. // After: try { x.y = 3; } catch(__ehobj) { }
  8586. //
  8587. // This is done to force the runtime to recover from exceptions at the most granular
  8588. // possible point. Recovering from EH dramatically improves coverage of testing via
  8589. // fault injection.
  8590. // create and push the try-catch node
  8591. pParentTryCatchBlock = CreateBlockNode();
  8592. PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr);
  8593. pParentTryCatch = CreateNodeForOpT<knopTryCatch>();
  8594. PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr);
  8595. // create and push a try node
  8596. pTry = CreateNodeForOpT<knopTry>();
  8597. PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr);
  8598. pTryBlock = CreateBlockNode();
  8599. PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr);
  8600. // these nodes will be closed after the statement is parsed.
  8601. }
  8602. #endif // EXCEPTION_RECOVERY
  8603. }
  8604. EnsureStackAvailable();
  8605. LRestart:
  8606. tok = m_token.tk;
  8607. switch (tok)
  8608. {
  8609. case tkEOF:
  8610. if (labelledStatement)
  8611. {
  8612. Error(ERRLabelFollowedByEOF);
  8613. }
  8614. if (buildAST)
  8615. {
  8616. pnode = nullptr;
  8617. }
  8618. break;
  8619. case tkFUNCTION:
  8620. {
  8621. LFunctionStatement:
  8622. if (m_grfscr & fscrDeferredFncExpression)
  8623. {
  8624. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  8625. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  8626. // first time we see it.
  8627. m_grfscr &= ~fscrDeferredFncExpression;
  8628. pnode = ParseFncDeclNoCheckScope<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs);
  8629. }
  8630. else
  8631. {
  8632. pnode = ParseFncDeclCheckScope<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs));
  8633. }
  8634. Assert(pnode != nullptr);
  8635. ParseNodeFnc* pNodeFnc = (ParseNodeFnc*)pnode;
  8636. if (labelledStatement)
  8637. {
  8638. if (IsStrictMode())
  8639. {
  8640. Error(ERRFunctionAfterLabelInStrict);
  8641. }
  8642. else if (pNodeFnc->IsAsync())
  8643. {
  8644. Error(ERRLabelBeforeAsyncFncDeclaration);
  8645. }
  8646. else if (pNodeFnc->IsGenerator())
  8647. {
  8648. Error(ERRLabelBeforeGeneratorDeclaration);
  8649. }
  8650. }
  8651. if (isAsyncMethod)
  8652. {
  8653. pnode->AsParseNodeFnc()->cbStringMin = iecpMin;
  8654. }
  8655. break;
  8656. }
  8657. case tkCLASS:
  8658. if (labelledStatement)
  8659. {
  8660. Error(ERRLabelBeforeClassDeclaration);
  8661. }
  8662. else if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  8663. {
  8664. pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);
  8665. }
  8666. else
  8667. {
  8668. goto LDefaultToken;
  8669. }
  8670. break;
  8671. case tkID:
  8672. case tkLET:
  8673. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.let)
  8674. {
  8675. // We see "let" at the start of a statement. This could either be a declaration or an identifier
  8676. // reference. The next token determines which.
  8677. RestorePoint parsedLet;
  8678. this->GetScanner()->Capture(&parsedLet);
  8679. ichMin = this->GetScanner()->IchMinTok();
  8680. this->GetScanner()->Scan();
  8681. if (labelledStatement)
  8682. {
  8683. if (!this->GetScanner()->FHadNewLine() || m_token.tk == tkLBrack)
  8684. {
  8685. // In the case where a label is followed by a let, we want to fail when parsing if there is no new line after let,
  8686. // otherwise fail at runtime as let will be viewed as undefined. A left bracket after a let signifies a syntax error regardless.
  8687. Error(ERRLabelBeforeLexicalDeclaration);
  8688. }
  8689. }
  8690. else if (this->NextTokenConfirmsLetDecl())
  8691. {
  8692. pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);
  8693. goto LNeedTerminator;
  8694. }
  8695. this->GetScanner()->SeekTo(parsedLet);
  8696. }
  8697. else if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8698. {
  8699. RestorePoint parsedAsync;
  8700. this->GetScanner()->Capture(&parsedAsync);
  8701. ichMin = this->GetScanner()->IchMinTok();
  8702. iecpMin = this->GetScanner()->IecpMinTok();
  8703. this->GetScanner()->Scan();
  8704. if (m_token.tk == tkFUNCTION && !this->GetScanner()->FHadNewLine())
  8705. {
  8706. isAsyncMethod = true;
  8707. goto LFunctionStatement;
  8708. }
  8709. this->GetScanner()->SeekTo(parsedAsync);
  8710. }
  8711. goto LDefaultToken;
  8712. case tkCONST:
  8713. if (labelledStatement)
  8714. {
  8715. Error(ERRLabelBeforeLexicalDeclaration);
  8716. }
  8717. ichMin = this->GetScanner()->IchMinTok();
  8718. this->GetScanner()->Scan();
  8719. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8720. goto LNeedTerminator;
  8721. case tkVAR:
  8722. ichMin = this->GetScanner()->IchMinTok();
  8723. this->GetScanner()->Scan();
  8724. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8725. goto LNeedTerminator;
  8726. case tkFOR:
  8727. {
  8728. ParseNodeBlock * pnodeBlock = nullptr;
  8729. ParseNodePtr *ppnodeScopeSave = nullptr;
  8730. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8731. ichMin = this->GetScanner()->IchMinTok();
  8732. ChkNxtTok(tkLParen, ERRnoLparen);
  8733. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8734. if (buildAST)
  8735. {
  8736. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8737. }
  8738. RestorePoint startExprOrIdentifier;
  8739. fForInOrOfOkay = TRUE;
  8740. fCanAssign = TRUE;
  8741. tok = m_token.tk;
  8742. BOOL nativeForOkay = TRUE;
  8743. ParseNodePtr pnodeT;
  8744. switch (tok)
  8745. {
  8746. case tkID:
  8747. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.let)
  8748. {
  8749. // We see "let" in the init part of a for loop. This could either be a declaration or an identifier
  8750. // reference. The next token determines which.
  8751. RestorePoint parsedLet;
  8752. this->GetScanner()->Capture(&parsedLet);
  8753. auto ichMinInner = this->GetScanner()->IchMinTok();
  8754. this->GetScanner()->Scan();
  8755. if (IsPossiblePatternStart())
  8756. {
  8757. this->GetScanner()->Capture(&startExprOrIdentifier);
  8758. }
  8759. if (this->NextTokenConfirmsLetDecl() && m_token.tk != tkIN)
  8760. {
  8761. pnodeT = ParseVariableDeclaration<buildAST>(tkLET, ichMinInner
  8762. , /*fAllowIn = */FALSE
  8763. , /*pfForInOk = */&fForInOrOfOkay
  8764. , /*singleDefOnly*/FALSE
  8765. , /*allowInit*/TRUE
  8766. , /*isTopVarParse*/TRUE
  8767. , /*isFor*/TRUE
  8768. , &nativeForOkay);
  8769. break;
  8770. }
  8771. this->GetScanner()->SeekTo(parsedLet);
  8772. }
  8773. goto LDefaultTokenFor;
  8774. case tkLET:
  8775. case tkCONST:
  8776. case tkVAR:
  8777. {
  8778. auto ichMinInner = this->GetScanner()->IchMinTok();
  8779. this->GetScanner()->Scan();
  8780. if (IsPossiblePatternStart())
  8781. {
  8782. this->GetScanner()->Capture(&startExprOrIdentifier);
  8783. }
  8784. pnodeT = ParseVariableDeclaration<buildAST>(tok, ichMinInner
  8785. , /*fAllowIn = */FALSE
  8786. , /*pfForInOk = */&fForInOrOfOkay
  8787. , /*singleDefOnly*/FALSE
  8788. , /*allowInit*/TRUE
  8789. , /*isTopVarParse*/TRUE
  8790. , /*isFor*/TRUE
  8791. , &nativeForOkay);
  8792. }
  8793. break;
  8794. case tkSColon:
  8795. pnodeT = nullptr;
  8796. fForInOrOfOkay = FALSE;
  8797. break;
  8798. default:
  8799. {
  8800. LDefaultTokenFor:
  8801. RestorePoint exprStart;
  8802. tokens beforeToken = tok;
  8803. this->GetScanner()->Capture(&exprStart);
  8804. if (IsPossiblePatternStart())
  8805. {
  8806. this->GetScanner()->Capture(&startExprOrIdentifier);
  8807. }
  8808. bool fLikelyPattern = false;
  8809. if (IsES6DestructuringEnabled() && (beforeToken == tkLBrack || beforeToken == tkLCurly))
  8810. {
  8811. pnodeT = ParseExpr<buildAST>(koplNo,
  8812. &fCanAssign,
  8813. /*fAllowIn = */FALSE,
  8814. /*fAllowEllipsis*/FALSE,
  8815. /*pHint*/nullptr,
  8816. /*pHintLength*/nullptr,
  8817. /*pShortNameOffset*/nullptr,
  8818. /*pToken*/nullptr,
  8819. /**fUnaryOrParen*/false,
  8820. &fLikelyPattern);
  8821. }
  8822. else
  8823. {
  8824. pnodeT = ParseExpr<buildAST>(koplNo, &fCanAssign, /*fAllowIn = */FALSE);
  8825. }
  8826. // We would veryfiy the grammar as destructuring grammar only when for..in/of case. As in the native for loop case the above ParseExpr call
  8827. // has already converted them appropriately.
  8828. if (fLikelyPattern && TokIsForInOrForOf())
  8829. {
  8830. this->GetScanner()->SeekTo(exprStart);
  8831. ParseDestructuredLiteralWithScopeSave(tkNone, false/*isDecl*/, false /*topLevel*/, DIC_None, false /*allowIn*/);
  8832. if (buildAST)
  8833. {
  8834. pnodeT = ConvertToPattern(pnodeT);
  8835. }
  8836. }
  8837. if (buildAST)
  8838. {
  8839. Assert(pnodeT);
  8840. pnodeT->isUsed = false;
  8841. }
  8842. }
  8843. break;
  8844. }
  8845. if (TokIsForInOrForOf())
  8846. {
  8847. bool isForOf = (m_token.tk != tkIN);
  8848. Assert(!isForOf || (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.of));
  8849. if ((buildAST && nullptr == pnodeT) || !fForInOrOfOkay)
  8850. {
  8851. if (isForOf)
  8852. {
  8853. Error(ERRForOfNoInitAllowed);
  8854. }
  8855. else
  8856. {
  8857. Error(ERRForInNoInitAllowed);
  8858. }
  8859. }
  8860. if (!fCanAssign &&
  8861. (m_sourceContextInfo
  8862. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  8863. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  8864. {
  8865. Error(ERRInvalidLHSInFor);
  8866. }
  8867. this->GetScanner()->Scan();
  8868. ParseNodePtr pnodeObj = ParseExpr<buildAST>(isForOf ? koplCma : koplNo);
  8869. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8870. ChkCurTok(tkRParen, ERRnoRparen);
  8871. ParseNodeForInOrForOf * pnodeForInOrForOf = nullptr;
  8872. if (buildAST)
  8873. {
  8874. if (isForOf)
  8875. {
  8876. pnodeForInOrForOf = CreateNodeForOpT<knopForOf>(ichMin);
  8877. }
  8878. else
  8879. {
  8880. pnodeForInOrForOf = CreateNodeForOpT<knopForIn>(ichMin);
  8881. }
  8882. pnodeForInOrForOf->pnodeBlock = pnodeBlock;
  8883. pnodeForInOrForOf->pnodeLval = pnodeT;
  8884. pnodeForInOrForOf->pnodeObj = pnodeObj;
  8885. pnodeForInOrForOf->ichLim = ichLim;
  8886. TrackAssignment<true>(pnodeT, nullptr);
  8887. }
  8888. PushStmt<buildAST>(&stmt, pnodeForInOrForOf, isForOf ? knopForOf : knopForIn, pLabelIdList);
  8889. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8890. if (buildAST)
  8891. {
  8892. pnodeForInOrForOf->pnodeBody = pnodeBody;
  8893. pnode = pnodeForInOrForOf;
  8894. }
  8895. PopStmt(&stmt);
  8896. }
  8897. else
  8898. {
  8899. if (!nativeForOkay)
  8900. {
  8901. Error(ERRDestructInit);
  8902. }
  8903. ChkCurTok(tkSColon, ERRnoSemic);
  8904. ParseNodePtr pnodeCond = nullptr;
  8905. if (m_token.tk != tkSColon)
  8906. {
  8907. pnodeCond = ParseExpr<buildAST>();
  8908. if (m_token.tk != tkSColon)
  8909. {
  8910. Error(ERRnoSemic);
  8911. }
  8912. }
  8913. tokens tk;
  8914. tk = this->GetScanner()->Scan();
  8915. ParseNodePtr pnodeIncr = nullptr;
  8916. if (tk != tkRParen)
  8917. {
  8918. pnodeIncr = ParseExpr<buildAST>();
  8919. if (pnodeIncr)
  8920. {
  8921. pnodeIncr->isUsed = false;
  8922. }
  8923. }
  8924. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8925. ChkCurTok(tkRParen, ERRnoRparen);
  8926. ParseNodeFor * pnodeFor = nullptr;
  8927. if (buildAST)
  8928. {
  8929. pnodeFor = CreateNodeForOpT<knopFor>(ichMin);
  8930. pnodeFor->pnodeBlock = pnodeBlock;
  8931. pnodeFor->pnodeInverted = nullptr;
  8932. pnodeFor->pnodeInit = pnodeT;
  8933. pnodeFor->pnodeCond = pnodeCond;
  8934. pnodeFor->pnodeIncr = pnodeIncr;
  8935. pnodeFor->ichLim = ichLim;
  8936. }
  8937. PushStmt<buildAST>(&stmt, pnodeFor, knopFor, pLabelIdList);
  8938. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8939. if (buildAST)
  8940. {
  8941. pnodeFor->pnodeBody = pnodeBody;
  8942. pnode = pnodeFor;
  8943. }
  8944. PopStmt(&stmt);
  8945. }
  8946. if (buildAST)
  8947. {
  8948. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8949. }
  8950. FinishParseBlock(pnodeBlock);
  8951. break;
  8952. }
  8953. case tkSWITCH:
  8954. {
  8955. BOOL fSeenDefault = FALSE;
  8956. ParseNodeBlock * pnodeBlock = nullptr;
  8957. ParseNodePtr *ppnodeScopeSave = nullptr;
  8958. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8959. ichMin = this->GetScanner()->IchMinTok();
  8960. ChkNxtTok(tkLParen, ERRnoLparen);
  8961. ParseNodePtr pnodeVal = ParseExpr<buildAST>();
  8962. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8963. ChkCurTok(tkRParen, ERRnoRparen);
  8964. ChkCurTok(tkLCurly, ERRnoLcurly);
  8965. ParseNodeSwitch * pnodeSwitch = nullptr;
  8966. if (buildAST)
  8967. {
  8968. pnodeSwitch = CreateNodeForOpT<knopSwitch>(ichMin);
  8969. }
  8970. PushStmt<buildAST>(&stmt, pnodeSwitch, knopSwitch, pLabelIdList);
  8971. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8972. ParseNodeCase ** ppnodeCase = nullptr;
  8973. if (buildAST)
  8974. {
  8975. pnodeSwitch->pnodeVal = pnodeVal;
  8976. pnodeSwitch->pnodeBlock = pnodeBlock;
  8977. pnodeSwitch->ichLim = ichLim;
  8978. PushFuncBlockScope(pnodeSwitch->pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8979. pnodeSwitch->pnodeDefault = nullptr;
  8980. ppnodeCase = &pnodeSwitch->pnodeCases;
  8981. pnode = pnodeSwitch;
  8982. }
  8983. for (;;)
  8984. {
  8985. ParseNodeCase * pnodeCase;
  8986. ParseNodePtr pnodeBody = nullptr;
  8987. switch (m_token.tk)
  8988. {
  8989. default:
  8990. goto LEndSwitch;
  8991. case tkCASE:
  8992. {
  8993. pnodeCase = this->ParseCase<buildAST>(&pnodeBody);
  8994. break;
  8995. }
  8996. case tkDEFAULT:
  8997. if (fSeenDefault)
  8998. {
  8999. Error(ERRdupDefault);
  9000. // No recovery necessary since this is a semantic, not structural, error
  9001. }
  9002. fSeenDefault = TRUE;
  9003. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  9004. this->GetScanner()->Scan();
  9005. charcount_t ichMinInner = this->GetScanner()->IchLimTok();
  9006. ChkCurTok(tkColon, ERRnoColon);
  9007. if (buildAST)
  9008. {
  9009. pnodeCase = CreateNodeForOpT<knopCase>(ichMinT);
  9010. pnodeSwitch->pnodeDefault = pnodeCase;
  9011. pnodeCase->ichLim = ichMinInner;
  9012. pnodeCase->pnodeExpr = nullptr;
  9013. }
  9014. ParseStmtList<buildAST>(&pnodeBody);
  9015. break;
  9016. }
  9017. // Create a block node to contain the statement list for this case.
  9018. // This helps us insert byte code to return the right value from
  9019. // global/eval code.
  9020. ParseNodeBlock * pnodeFakeBlock = CreateBlockNode();
  9021. if (buildAST)
  9022. {
  9023. if (pnodeBody)
  9024. {
  9025. pnodeFakeBlock->ichMin = pnodeCase->ichMin;
  9026. pnodeFakeBlock->ichLim = pnodeCase->ichLim;
  9027. pnodeCase->pnodeBody = pnodeFakeBlock;
  9028. pnodeCase->pnodeBody->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  9029. pnodeCase->pnodeBody->pnodeStmt = pnodeBody;
  9030. }
  9031. else
  9032. {
  9033. pnodeCase->pnodeBody = nullptr;
  9034. }
  9035. *ppnodeCase = pnodeCase;
  9036. ppnodeCase = &pnodeCase->pnodeNext;
  9037. }
  9038. }
  9039. LEndSwitch:
  9040. ChkCurTok(tkRCurly, ERRnoRcurly);
  9041. if (buildAST)
  9042. {
  9043. *ppnodeCase = nullptr;
  9044. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  9045. FinishParseBlock(pnode->AsParseNodeSwitch()->pnodeBlock);
  9046. }
  9047. else
  9048. {
  9049. FinishParseBlock(pnodeBlock);
  9050. }
  9051. PopStmt(&stmt);
  9052. break;
  9053. }
  9054. case tkWHILE:
  9055. {
  9056. ichMin = this->GetScanner()->IchMinTok();
  9057. ChkNxtTok(tkLParen, ERRnoLparen);
  9058. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  9059. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9060. ChkCurTok(tkRParen, ERRnoRparen);
  9061. ParseNodeWhile * pnodeWhile = nullptr;
  9062. if (buildAST)
  9063. {
  9064. pnodeWhile = CreateNodeForOpT<knopWhile>(ichMin);
  9065. pnodeWhile->pnodeCond = pnodeCond;
  9066. pnodeWhile->ichLim = ichLim;
  9067. }
  9068. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  9069. m_disallowImportExportStmt = true;
  9070. PushStmt<buildAST>(&stmt, pnodeWhile, knopWhile, pLabelIdList);
  9071. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9072. PopStmt(&stmt);
  9073. if (buildAST)
  9074. {
  9075. pnodeWhile->pnodeBody = pnodeBody;
  9076. pnode = pnodeWhile;
  9077. }
  9078. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  9079. break;
  9080. }
  9081. case tkDO:
  9082. {
  9083. ParseNodeWhile * pnodeWhile = nullptr;
  9084. if (buildAST)
  9085. {
  9086. pnodeWhile = CreateNodeForOpT<knopDoWhile>();
  9087. }
  9088. PushStmt<buildAST>(&stmt, pnodeWhile, knopDoWhile, pLabelIdList);
  9089. this->GetScanner()->Scan();
  9090. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  9091. m_disallowImportExportStmt = true;
  9092. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9093. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  9094. PopStmt(&stmt);
  9095. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  9096. ChkCurTok(tkWHILE, ERRnoWhile);
  9097. ChkCurTok(tkLParen, ERRnoLparen);
  9098. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  9099. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9100. ChkCurTok(tkRParen, ERRnoRparen);
  9101. if (buildAST)
  9102. {
  9103. pnodeWhile->pnodeBody = pnodeBody;
  9104. pnodeWhile->pnodeCond = pnodeCond;
  9105. pnodeWhile->ichLim = ichLim;
  9106. pnodeWhile->ichMin = ichMinT;
  9107. pnode = pnodeWhile;
  9108. }
  9109. // REVIEW: Allow do...while statements to be embedded in other compound statements like if..else, or do..while?
  9110. // goto LNeedTerminator;
  9111. // For now just eat the trailing semicolon if present.
  9112. if (m_token.tk == tkSColon)
  9113. {
  9114. if (pnode)
  9115. {
  9116. pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9117. }
  9118. this->GetScanner()->Scan();
  9119. }
  9120. else if (pnode)
  9121. {
  9122. pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9123. }
  9124. break;
  9125. }
  9126. case tkIF:
  9127. {
  9128. ichMin = this->GetScanner()->IchMinTok();
  9129. ChkNxtTok(tkLParen, ERRnoLparen);
  9130. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  9131. ParseNodeIf * pnodeIf = nullptr;
  9132. if (buildAST)
  9133. {
  9134. pnodeIf = CreateNodeForOpT<knopIf>(ichMin);
  9135. pnodeIf->ichLim = this->GetScanner()->IchLimTok();
  9136. pnodeIf->pnodeCond = pnodeCond;
  9137. }
  9138. ChkCurTok(tkRParen, ERRnoRparen);
  9139. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  9140. m_disallowImportExportStmt = true;
  9141. PushStmt<buildAST>(&stmt, pnodeIf, knopIf, pLabelIdList);
  9142. ParseNodePtr pnodeTrue = ParseStatement<buildAST>();
  9143. ParseNodePtr pnodeFalse = nullptr;
  9144. if (m_token.tk == tkELSE)
  9145. {
  9146. this->GetScanner()->Scan();
  9147. pnodeFalse = ParseStatement<buildAST>();
  9148. }
  9149. if (buildAST)
  9150. {
  9151. pnodeIf->pnodeTrue = pnodeTrue;
  9152. pnodeIf->pnodeFalse = pnodeFalse;
  9153. pnode = pnodeIf;
  9154. }
  9155. PopStmt(&stmt);
  9156. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  9157. break;
  9158. }
  9159. case tkTRY:
  9160. {
  9161. ParseNodeBlock * pnodeBlock = CreateBlockNode();
  9162. pnodeBlock->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  9163. PushStmt<buildAST>(&stmt, pnodeBlock, knopBlock, pLabelIdList);
  9164. ParseNodePtr pnodeStmt = ParseTryCatchFinally<buildAST>();
  9165. if (buildAST)
  9166. {
  9167. pnodeBlock->pnodeStmt = pnodeStmt;
  9168. }
  9169. PopStmt(&stmt);
  9170. pnode = pnodeBlock;
  9171. break;
  9172. }
  9173. case tkWITH:
  9174. {
  9175. if (IsStrictMode())
  9176. {
  9177. Error(ERRES5NoWith);
  9178. }
  9179. if (m_currentNodeFunc)
  9180. {
  9181. GetCurrentFunctionNode()->SetHasWithStmt(); // Used by DeferNested
  9182. }
  9183. ichMin = this->GetScanner()->IchMinTok();
  9184. ChkNxtTok(tkLParen, ERRnoLparen);
  9185. ParseNodePtr pnodeObj = ParseExpr<buildAST>();
  9186. if (!buildAST)
  9187. {
  9188. m_scopeCountNoAst++;
  9189. }
  9190. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9191. ChkCurTok(tkRParen, ERRnoRparen);
  9192. ParseNodeWith * pnodeWith = nullptr;
  9193. if (buildAST)
  9194. {
  9195. pnodeWith = CreateNodeForOpT<knopWith>(ichMin);
  9196. }
  9197. PushStmt<buildAST>(&stmt, pnodeWith, knopWith, pLabelIdList);
  9198. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9199. if (buildAST)
  9200. {
  9201. pnodeWith->pnodeObj = pnodeObj;
  9202. this->CheckArguments(pnodeWith->pnodeObj);
  9203. if (m_ppnodeExprScope)
  9204. {
  9205. Assert(*m_ppnodeExprScope == nullptr);
  9206. *m_ppnodeExprScope = pnodeWith;
  9207. m_ppnodeExprScope = &pnodeWith->pnodeNext;
  9208. }
  9209. else
  9210. {
  9211. Assert(m_ppnodeScope);
  9212. Assert(*m_ppnodeScope == nullptr);
  9213. *m_ppnodeScope = pnodeWith;
  9214. m_ppnodeScope = &pnodeWith->pnodeNext;
  9215. }
  9216. pnodeWith->pnodeNext = nullptr;
  9217. pnodeWith->scope = nullptr;
  9218. ppnodeExprScopeSave = m_ppnodeExprScope;
  9219. m_ppnodeExprScope = &pnodeWith->pnodeScopes;
  9220. pnodeWith->pnodeScopes = nullptr;
  9221. pnodeWith->ichLim = ichLim;
  9222. pnode = pnodeWith;
  9223. }
  9224. PushBlockInfo(CreateBlockNode());
  9225. PushDynamicBlock();
  9226. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9227. if (buildAST)
  9228. {
  9229. pnode->AsParseNodeWith()->pnodeBody = pnodeBody;
  9230. m_ppnodeExprScope = ppnodeExprScopeSave;
  9231. }
  9232. else
  9233. {
  9234. m_scopeCountNoAst--;
  9235. }
  9236. // The dynamic block is not stored in the actual parse tree and so will not
  9237. // be visited by the byte code generator. Grab the callsEval flag off it and
  9238. // pass on to outer block in case of:
  9239. // with (...) eval(...); // i.e. blockless form of with
  9240. bool callsEval = GetCurrentBlock()->GetCallsEval();
  9241. PopBlockInfo();
  9242. if (callsEval)
  9243. {
  9244. // be careful not to overwrite an existing true with false
  9245. GetCurrentBlock()->SetCallsEval(true);
  9246. }
  9247. PopStmt(&stmt);
  9248. break;
  9249. }
  9250. case tkLCurly:
  9251. pnode = ParseBlock<buildAST>(pLabelIdList);
  9252. break;
  9253. case tkSColon:
  9254. pnode = nullptr;
  9255. this->GetScanner()->Scan();
  9256. break;
  9257. case tkBREAK:
  9258. if (buildAST)
  9259. {
  9260. pnode = CreateNodeForOpT<knopBreak>();
  9261. }
  9262. fnop = fnopBreak;
  9263. goto LGetJumpStatement;
  9264. case tkCONTINUE:
  9265. if (buildAST)
  9266. {
  9267. pnode = CreateNodeForOpT<knopContinue>();
  9268. }
  9269. fnop = fnopContinue;
  9270. LGetJumpStatement:
  9271. this->GetScanner()->ScanForcingPid();
  9272. if (tkID == m_token.tk && !this->GetScanner()->FHadNewLine())
  9273. {
  9274. // Labeled break or continue.
  9275. pid = m_token.GetIdentifier(this->GetHashTbl());
  9276. if (buildAST)
  9277. {
  9278. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9279. pnodeJump->hasExplicitTarget = true;
  9280. pnodeJump->ichLim = this->GetScanner()->IchLimTok();
  9281. this->GetScanner()->Scan();
  9282. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9283. Assert(pnodeJump->grfnop == 0);
  9284. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9285. {
  9286. for (LabelId* label = pstmt->pLabelId; label != nullptr; label = label->next)
  9287. {
  9288. if (pid == label->pid)
  9289. {
  9290. // Found the label. Make sure we can use it. We can
  9291. // break out of any statement, but we can only
  9292. // continue loops.
  9293. if (fnop == fnopContinue &&
  9294. !(pstmt->pnodeStmt->Grfnop() & fnop))
  9295. {
  9296. Error(ERRbadContinue);
  9297. }
  9298. else
  9299. {
  9300. pstmt->pnodeStmt->grfnop |= fnop;
  9301. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9302. }
  9303. PopStmt(&stmt);
  9304. goto LNeedTerminator;
  9305. }
  9306. }
  9307. pnodeJump->grfnop |=
  9308. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9309. }
  9310. }
  9311. else
  9312. {
  9313. this->GetScanner()->Scan();
  9314. // Check if label is found within the current label id list.
  9315. auto checkLabelList = [&](LabelId* list, StmtNest* checkStmtOp)
  9316. {
  9317. for (LabelId* pLabelId = list; pLabelId; pLabelId = pLabelId->next)
  9318. {
  9319. if (pid == pLabelId->pid)
  9320. {
  9321. // Found the label. Make sure we can use it. We can
  9322. // break out of any statement, but we can only
  9323. // continue loops.
  9324. if (fnop == fnopContinue &&
  9325. !(ParseNode::Grfnop(checkStmtOp->op) & fnop))
  9326. {
  9327. Error(ERRbadContinue);
  9328. }
  9329. return true;
  9330. }
  9331. }
  9332. return false;
  9333. };
  9334. if (checkLabelList(pLabelIdList, m_pstmtCur)) goto LNeedTerminator;
  9335. for (pstmt = m_pstmtCur; pstmt; pstmt = pstmt->pstmtOuter)
  9336. {
  9337. if (checkLabelList(pstmt->pLabelId, pstmt)) goto LNeedTerminator;
  9338. }
  9339. }
  9340. Error(ERRnoLabel);
  9341. }
  9342. else
  9343. {
  9344. // If we're doing a fast scan, we're not tracking labels, so we can't accurately do this analysis.
  9345. // Let the thread that's doing the full parse detect the error, if there is one.
  9346. if (!this->IsDoingFastScan())
  9347. {
  9348. // Unlabeled break or continue.
  9349. ParseNodeJump * pnodeJump = nullptr;
  9350. if (buildAST)
  9351. {
  9352. pnodeJump = pnode->AsParseNodeJump();
  9353. pnodeJump->hasExplicitTarget = false;
  9354. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9355. Assert(pnodeJump->grfnop == 0);
  9356. }
  9357. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9358. {
  9359. if (buildAST)
  9360. {
  9361. AnalysisAssert(pstmt->pnodeStmt);
  9362. if (pstmt->pnodeStmt->Grfnop() & fnop)
  9363. {
  9364. pstmt->pnodeStmt->grfnop |= fnop;
  9365. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9366. PopStmt(&stmt);
  9367. goto LNeedTerminator;
  9368. }
  9369. pnodeJump->grfnop |=
  9370. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9371. }
  9372. else
  9373. {
  9374. if (ParseNode::Grfnop(pstmt->GetNop()) & fnop)
  9375. {
  9376. if (!pstmt->isDeferred)
  9377. {
  9378. AnalysisAssert(pstmt->pnodeStmt);
  9379. pstmt->pnodeStmt->grfnop |= fnop;
  9380. }
  9381. goto LNeedTerminator;
  9382. }
  9383. }
  9384. }
  9385. Error(fnop == fnopBreak ? ERRbadBreak : ERRbadContinue);
  9386. }
  9387. goto LNeedTerminator;
  9388. }
  9389. case tkRETURN:
  9390. {
  9391. ParseNodeReturn * pnodeReturn;
  9392. if (buildAST)
  9393. {
  9394. if (nullptr == m_currentNodeFunc || IsTopLevelModuleFunc())
  9395. {
  9396. Error(ERRbadReturn);
  9397. }
  9398. pnodeReturn = CreateNodeForOpT<knopReturn>();
  9399. }
  9400. this->GetScanner()->Scan();
  9401. ParseNodePtr pnodeExpr = nullptr;
  9402. ParseOptionalExpr<buildAST>(&pnodeExpr, true);
  9403. // Class constructors have special semantics regarding return statements.
  9404. // This might require a reference to 'this'
  9405. if (GetCurrentFunctionNode()->IsClassConstructor())
  9406. {
  9407. ReferenceSpecialName(wellKnownPropertyPids._this);
  9408. }
  9409. if (buildAST)
  9410. {
  9411. pnodeReturn->pnodeExpr = pnodeExpr;
  9412. if (pnodeExpr)
  9413. {
  9414. this->CheckArguments(pnodeReturn->pnodeExpr);
  9415. pnodeReturn->ichLim = pnodeReturn->pnodeExpr->ichLim;
  9416. }
  9417. // See if return should call finally
  9418. PushStmt<buildAST>(&stmt, pnodeReturn, knopReturn, pLabelIdList);
  9419. Assert(pnodeReturn->grfnop == 0);
  9420. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9421. {
  9422. if (pstmt->pnodeStmt->Grfnop() & fnopCleanup)
  9423. {
  9424. pnodeReturn->grfnop |= fnopCleanup;
  9425. break;
  9426. }
  9427. }
  9428. PopStmt(&stmt);
  9429. pnode = pnodeReturn;
  9430. }
  9431. goto LNeedTerminator;
  9432. }
  9433. case tkTHROW:
  9434. {
  9435. if (buildAST)
  9436. {
  9437. pnode = CreateUniNode(knopThrow, nullptr);
  9438. }
  9439. this->GetScanner()->Scan();
  9440. ParseNodePtr pnode1 = nullptr;
  9441. if (m_token.tk != tkSColon &&
  9442. m_token.tk != tkRCurly &&
  9443. !this->GetScanner()->FHadNewLine())
  9444. {
  9445. pnode1 = ParseExpr<buildAST>();
  9446. }
  9447. else
  9448. {
  9449. Error(ERRdanglingThrow);
  9450. }
  9451. if (buildAST)
  9452. {
  9453. pnode->AsParseNodeUni()->pnode1 = pnode1;
  9454. if (pnode1)
  9455. {
  9456. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  9457. pnode->ichLim = pnode->AsParseNodeUni()->pnode1->ichLim;
  9458. }
  9459. }
  9460. goto LNeedTerminator;
  9461. }
  9462. case tkDEBUGGER:
  9463. if (buildAST)
  9464. {
  9465. pnode = CreateNodeForOpT<knopDebugger>();
  9466. }
  9467. this->GetScanner()->Scan();
  9468. goto LNeedTerminator;
  9469. case tkIMPORT:
  9470. pnode = ParseImport<buildAST>();
  9471. goto LNeedTerminator;
  9472. case tkEXPORT:
  9473. {
  9474. if (!(m_grfscr & fscrIsModuleCode))
  9475. {
  9476. goto LDefaultToken;
  9477. }
  9478. bool needTerminator = false;
  9479. pnode = ParseExportDeclaration<buildAST>(&needTerminator);
  9480. if (needTerminator)
  9481. {
  9482. goto LNeedTerminator;
  9483. }
  9484. else
  9485. {
  9486. break;
  9487. }
  9488. }
  9489. LDefaultToken:
  9490. default:
  9491. {
  9492. // First check for a label via lookahead. If not found,
  9493. // rewind and reparse as expression statement.
  9494. if (m_token.tk == tkID)
  9495. {
  9496. RestorePoint idStart;
  9497. this->GetScanner()->Capture(&idStart);
  9498. IdentPtr pidInner = m_token.GetIdentifier(this->GetHashTbl());
  9499. this->GetScanner()->Scan();
  9500. if (m_token.tk == tkColon)
  9501. {
  9502. // We have a label.
  9503. if (LabelExists(pidInner, pLabelIdList))
  9504. {
  9505. Error(ERRbadLabel);
  9506. }
  9507. LabelId* pLabelId = CreateLabelId(pidInner);
  9508. pLabelId->next = pLabelIdList;
  9509. pLabelIdList = pLabelId;
  9510. this->GetScanner()->Scan();
  9511. labelledStatement = true;
  9512. goto LRestart;
  9513. }
  9514. // No label, rewind back to the tkID and parse an expression
  9515. this->GetScanner()->SeekTo(idStart);
  9516. }
  9517. // Must be an expression statement.
  9518. pnode = ParseExpr<buildAST>();
  9519. if (m_hasDeferredShorthandInitError)
  9520. {
  9521. Error(ERRnoColon);
  9522. }
  9523. if (buildAST)
  9524. {
  9525. expressionStmt = true;
  9526. AnalysisAssert(pnode);
  9527. pnode->isUsed = false;
  9528. }
  9529. }
  9530. LNeedTerminator:
  9531. // Need a semicolon, new-line, } or end-of-file.
  9532. // We digest a semicolon if it's there.
  9533. switch (m_token.tk)
  9534. {
  9535. case tkSColon:
  9536. this->GetScanner()->Scan();
  9537. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9538. break;
  9539. case tkEOF:
  9540. case tkRCurly:
  9541. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9542. break;
  9543. default:
  9544. if (!this->GetScanner()->FHadNewLine())
  9545. {
  9546. Error(ERRnoSemic);
  9547. }
  9548. else
  9549. {
  9550. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9551. }
  9552. break;
  9553. }
  9554. break;
  9555. }
  9556. if (m_hasDeferredShorthandInitError)
  9557. {
  9558. Error(ERRnoColon);
  9559. }
  9560. if (buildAST)
  9561. {
  9562. // All non expression statements excluded from the "this.x" optimization
  9563. // Another check while parsing expressions
  9564. if (!expressionStmt)
  9565. {
  9566. if (m_currentNodeFunc)
  9567. {
  9568. m_currentNodeFunc->SetHasNonThisStmt();
  9569. }
  9570. else if (m_currentNodeProg)
  9571. {
  9572. m_currentNodeProg->SetHasNonThisStmt();
  9573. }
  9574. }
  9575. #if EXCEPTION_RECOVERY
  9576. // close the try/catch block
  9577. if (Js::Configuration::Global.flags.SwallowExceptions)
  9578. {
  9579. // pop the try block and fill in the body
  9580. PopStmt(&stmtTryBlock);
  9581. pTryBlock->pnodeStmt = pnode;
  9582. PopStmt(&stmtTry);
  9583. if (pnode != nullptr)
  9584. {
  9585. pTry->ichLim = pnode->ichLim;
  9586. }
  9587. pTry->pnodeBody = pTryBlock;
  9588. // create a catch block with an empty body
  9589. StmtNest stmtCatch;
  9590. ParseNodeCatch * pCatch;
  9591. pCatch = CreateNodeForOpT<knopCatch>();
  9592. PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr);
  9593. pCatch->pnodeBody = nullptr;
  9594. if (pnode != nullptr)
  9595. {
  9596. pCatch->ichLim = pnode->ichLim;
  9597. }
  9598. pCatch->grfnop = 0;
  9599. pCatch->pnodeNext = nullptr;
  9600. // create a fake name for the catch var.
  9601. const WCHAR *uniqueNameStr = _u("__ehobj");
  9602. IdentPtr uniqueName = this->GetHashTbl()->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));
  9603. pCatch->SetParam(CreateNameNode(uniqueName));
  9604. // Add this catch to the current list. We don't bother adjusting the catch and function expression
  9605. // lists here because the catch is just an empty statement.
  9606. if (m_ppnodeExprScope)
  9607. {
  9608. Assert(*m_ppnodeExprScope == nullptr);
  9609. *m_ppnodeExprScope = pCatch;
  9610. m_ppnodeExprScope = &pCatch->pnodeNext;
  9611. }
  9612. else
  9613. {
  9614. Assert(m_ppnodeScope);
  9615. Assert(*m_ppnodeScope == nullptr);
  9616. *m_ppnodeScope = pCatch;
  9617. m_ppnodeScope = &pCatch->pnodeNext;
  9618. }
  9619. pCatch->pnodeScopes = nullptr;
  9620. PopStmt(&stmtCatch);
  9621. // fill in and pop the try-catch
  9622. pParentTryCatch->pnodeTry = pTry;
  9623. pParentTryCatch->pnodeCatch = pCatch;
  9624. PopStmt(&stmtTryCatch);
  9625. PopStmt(&stmtTryCatchBlock);
  9626. // replace the node that's being returned
  9627. pParentTryCatchBlock->pnodeStmt = pParentTryCatch;
  9628. pnode = pParentTryCatchBlock;
  9629. }
  9630. #endif // EXCEPTION_RECOVERY
  9631. }
  9632. return pnode;
  9633. }
  9634. BOOL
  9635. Parser::TokIsForInOrForOf()
  9636. {
  9637. return m_token.tk == tkIN ||
  9638. (m_token.tk == tkID &&
  9639. m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.of);
  9640. }
  9641. /***************************************************************************
  9642. Parse a sequence of statements.
  9643. ***************************************************************************/
  9644. template<bool buildAST>
  9645. void Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)
  9646. {
  9647. BOOL doneDirectives = !isSourceElementList; // directives may only exist in a SourceElementList, not a StatementList
  9648. BOOL seenDirectiveContainingOctal = false; // Have we seen an octal directive before a use strict directive?
  9649. BOOL old_UseStrictMode = m_fUseStrictMode;
  9650. ParseNodePtr pnodeStmt;
  9651. ParseNodePtr *lastNodeRef = nullptr;
  9652. if (buildAST)
  9653. {
  9654. Assert(ppnodeList);
  9655. *ppnodeList = nullptr;
  9656. }
  9657. if (CONFIG_FLAG(ForceStrictMode))
  9658. {
  9659. m_fUseStrictMode = TRUE;
  9660. }
  9661. for (;;)
  9662. {
  9663. switch (m_token.tk)
  9664. {
  9665. case tkCASE:
  9666. case tkDEFAULT:
  9667. case tkRCurly:
  9668. case tkEOF:
  9669. if (buildAST && nullptr != pppnodeLast)
  9670. {
  9671. *pppnodeLast = lastNodeRef;
  9672. }
  9673. if (!buildAST)
  9674. {
  9675. m_fUseStrictMode = old_UseStrictMode;
  9676. }
  9677. return;
  9678. }
  9679. if (doneDirectives == FALSE)
  9680. {
  9681. bool isOctalInString = false;
  9682. bool isUseStrictDirective = false;
  9683. bool isUseAsmDirective = false;
  9684. if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))
  9685. {
  9686. // Ignore "use asm" statement when not building the AST
  9687. isUseAsmDirective &= buildAST;
  9688. if (isUseStrictDirective)
  9689. {
  9690. // Functions with non-simple parameter list cannot be made strict mode
  9691. if (GetCurrentFunctionNode()->HasNonSimpleParameterList())
  9692. {
  9693. Error(ERRNonSimpleParamListInStrictMode);
  9694. }
  9695. if (seenDirectiveContainingOctal)
  9696. {
  9697. // Directives seen before a "use strict" cannot contain an octal.
  9698. Error(ERRES5NoOctal);
  9699. }
  9700. if (!buildAST)
  9701. {
  9702. // Turning on strict mode in deferred code.
  9703. m_fUseStrictMode = TRUE;
  9704. if (!m_inDeferredNestedFunc)
  9705. {
  9706. // Top-level deferred function, so there's a parse node
  9707. Assert(m_currentNodeFunc != nullptr);
  9708. m_currentNodeFunc->SetStrictMode();
  9709. }
  9710. else if (strictModeOn)
  9711. {
  9712. // This turns on strict mode in a deferred function, we need to go back
  9713. // and re-check duplicated formals.
  9714. *strictModeOn = true;
  9715. }
  9716. }
  9717. else
  9718. {
  9719. if (smEnvironment == SM_OnGlobalCode)
  9720. {
  9721. // Turning on strict mode at the top level
  9722. m_fUseStrictMode = TRUE;
  9723. }
  9724. else
  9725. {
  9726. // i.e. smEnvironment == SM_OnFunctionCode
  9727. Assert(m_currentNodeFunc != nullptr);
  9728. m_currentNodeFunc->SetStrictMode();
  9729. }
  9730. }
  9731. }
  9732. else if (isUseAsmDirective)
  9733. {
  9734. if (smEnvironment != SM_OnGlobalCode) //Top level use asm doesn't mean anything.
  9735. {
  9736. // i.e. smEnvironment == SM_OnFunctionCode
  9737. Assert(m_currentNodeFunc != nullptr);
  9738. m_currentNodeFunc->SetAsmjsMode();
  9739. m_currentNodeFunc->SetCanBeDeferred(false);
  9740. m_InAsmMode = true;
  9741. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, AsmJSFunction, m_scriptContext);
  9742. }
  9743. }
  9744. else if (isOctalInString)
  9745. {
  9746. seenDirectiveContainingOctal = TRUE;
  9747. }
  9748. }
  9749. else
  9750. {
  9751. // The first time we see anything other than a directive we can have no more directives.
  9752. doneDirectives = TRUE;
  9753. }
  9754. }
  9755. if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))
  9756. {
  9757. if (buildAST)
  9758. {
  9759. AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);
  9760. }
  9761. }
  9762. }
  9763. }
  9764. template <class Fn>
  9765. void Parser::FinishFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)
  9766. {
  9767. Scope * scope;
  9768. Scope * origCurrentScope = this->m_currentScope;
  9769. ParseNodePtr pnodeScope;
  9770. ParseNodeBlock * pnodeBlock;
  9771. for (pnodeScope = pnodeScopeList; pnodeScope;)
  9772. {
  9773. switch (pnodeScope->nop)
  9774. {
  9775. case knopBlock:
  9776. {
  9777. ParseNodeBlock * pnodeBlockScope = pnodeScope->AsParseNodeBlock();
  9778. m_nextBlockId = pnodeBlockScope->blockId + 1;
  9779. PushBlockInfo(pnodeBlockScope);
  9780. scope = pnodeBlockScope->scope;
  9781. if (scope && scope != origCurrentScope)
  9782. {
  9783. PushScope(scope);
  9784. }
  9785. FinishFunctionsInScope(pnodeBlockScope->pnodeScopes, fn);
  9786. if (scope && scope != origCurrentScope)
  9787. {
  9788. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9789. PopScope(scope);
  9790. }
  9791. PopBlockInfo();
  9792. pnodeScope = pnodeBlockScope->pnodeNext;
  9793. break;
  9794. }
  9795. case knopFncDecl:
  9796. fn(pnodeScope->AsParseNodeFnc());
  9797. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  9798. break;
  9799. case knopCatch:
  9800. scope = pnodeScope->AsParseNodeCatch()->scope;
  9801. if (scope)
  9802. {
  9803. PushScope(scope);
  9804. }
  9805. pnodeBlock = CreateBlockNode(PnodeBlockType::Regular);
  9806. pnodeBlock->scope = scope;
  9807. PushBlockInfo(pnodeBlock);
  9808. FinishFunctionsInScope(pnodeScope->AsParseNodeCatch()->pnodeScopes, fn);
  9809. if (scope)
  9810. {
  9811. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9812. PopScope(scope);
  9813. }
  9814. PopBlockInfo();
  9815. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  9816. break;
  9817. case knopWith:
  9818. PushBlockInfo(CreateBlockNode());
  9819. PushDynamicBlock();
  9820. FinishFunctionsInScope(pnodeScope->AsParseNodeWith()->pnodeScopes, fn);
  9821. PopBlockInfo();
  9822. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  9823. break;
  9824. default:
  9825. AssertMsg(false, "Unexpected node with scope list");
  9826. return;
  9827. }
  9828. }
  9829. }
  9830. // Scripts above this size (minus string literals and comments) will have parsing of
  9831. // function bodies deferred.
  9832. ULONG Parser::GetDeferralThreshold(bool isProfileLoaded)
  9833. {
  9834. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9835. if (CONFIG_FLAG(ForceDeferParse) ||
  9836. PHASE_FORCE1(Js::DeferParsePhase) ||
  9837. Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  9838. {
  9839. return 0;
  9840. }
  9841. else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))
  9842. {
  9843. return Js::Configuration::Global.flags.DeferParse;
  9844. }
  9845. else
  9846. #endif
  9847. {
  9848. if (isProfileLoaded)
  9849. {
  9850. return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;
  9851. }
  9852. return DEFAULT_CONFIG_DeferParseThreshold;
  9853. }
  9854. }
  9855. void Parser::FinishDeferredFunction(ParseNodeBlock * pnodeScopeList)
  9856. {
  9857. uint saveNextBlockId = m_nextBlockId;
  9858. m_nextBlockId = pnodeScopeList->blockId + 1;
  9859. FinishFunctionsInScope(pnodeScopeList,
  9860. [this](ParseNodeFnc * pnodeFnc)
  9861. {
  9862. Assert(pnodeFnc->nop == knopFncDecl);
  9863. // Non-simple params (such as default) require a good amount of logic to put vars on appropriate scopes. ParseFncDecl handles it
  9864. // properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param
  9865. // will remain deferred until they are called.
  9866. if (pnodeFnc->pnodeBody == nullptr && !pnodeFnc->HasNonSimpleParameterList())
  9867. {
  9868. // Go back and generate an AST for this function.
  9869. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->functionId, /*Undefer*/TRUE));
  9870. ParseNodeFnc * pnodeFncSave = this->m_currentNodeFunc;
  9871. this->m_currentNodeFunc = pnodeFnc;
  9872. ParseNodeBlock * pnodeFncExprBlock = nullptr;
  9873. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  9874. if (pnodeName)
  9875. {
  9876. Assert(pnodeName->nop == knopVarDecl);
  9877. ParseNodeVar * pnodeVarName = pnodeName->AsParseNodeVar();
  9878. Assert(pnodeVarName->pnodeNext == nullptr);
  9879. if (!pnodeFnc->IsDeclaration())
  9880. {
  9881. // Set up the named function expression symbol so references inside the function can be bound.
  9882. pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);
  9883. PidRefStack *ref = this->PushPidRef(pnodeVarName->pid);
  9884. pnodeVarName->symRef = ref->GetSymRef();
  9885. ref->SetSym(pnodeVarName->sym);
  9886. Scope *fncExprScope = pnodeFncExprBlock->scope;
  9887. fncExprScope->AddNewSymbol(pnodeVarName->sym);
  9888. pnodeFnc->scope = fncExprScope;
  9889. }
  9890. }
  9891. ParseNodeBlock * pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);
  9892. pnodeFnc->pnodeScopes = pnodeBlock;
  9893. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  9894. pnodeBlock->pnodeStmt = pnodeFnc;
  9895. ParseNodePtr * varNodesList = &pnodeFnc->pnodeVars;
  9896. ParseNodeVar * argNode = nullptr;
  9897. if (!pnodeFnc->IsModule() && !pnodeFnc->IsLambda() && !(pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam))
  9898. {
  9899. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  9900. m_ppnodeVar = &pnodeFnc->pnodeVars;
  9901. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  9902. varNodesList = m_ppnodeVar;
  9903. m_ppnodeVar = ppnodeVarSave;
  9904. }
  9905. // Add the args to the scope, since we won't re-parse those.
  9906. Scope *scope = pnodeBlock->scope;
  9907. uint blockId = GetCurrentBlock()->blockId;
  9908. uint funcId = GetCurrentFunctionNode()->functionId;
  9909. auto addArgsToScope = [&](ParseNodePtr pnodeArg) {
  9910. if (pnodeArg->IsVarLetOrConst())
  9911. {
  9912. ParseNodeVar * pnodeVarArg = pnodeArg->AsParseNodeVar();
  9913. PidRefStack *ref = this->FindOrAddPidRef(pnodeVarArg->pid, blockId, funcId);
  9914. pnodeVarArg->symRef = ref->GetSymRef();
  9915. if (ref->GetSym() != nullptr)
  9916. {
  9917. // Duplicate parameter in a configuration that allows them.
  9918. // The symbol is already in the scope, just point it to the right declaration.
  9919. Assert(ref->GetSym() == pnodeVarArg->sym);
  9920. ref->GetSym()->SetDecl(pnodeVarArg);
  9921. }
  9922. else
  9923. {
  9924. ref->SetSym(pnodeArg->AsParseNodeVar()->sym);
  9925. scope->AddNewSymbol(pnodeVarArg->sym);
  9926. }
  9927. }
  9928. };
  9929. MapFormals(pnodeFnc, addArgsToScope);
  9930. MapFormalsFromPattern(pnodeFnc, addArgsToScope);
  9931. ParseNodeBlock * pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  9932. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  9933. // Set the parameter block's child to the function body block.
  9934. *m_ppnodeScope = pnodeInnerBlock;
  9935. ParseNodePtr *ppnodeScopeSave = nullptr;
  9936. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9937. ppnodeScopeSave = m_ppnodeScope;
  9938. // This synthetic block scope will contain all the nested scopes.
  9939. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  9940. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  9941. // Keep nested function declarations and expressions in the same list at function scope.
  9942. // (Indicate this by nulling out the current function expressions list.)
  9943. ppnodeExprScopeSave = m_ppnodeExprScope;
  9944. m_ppnodeExprScope = nullptr;
  9945. // Shouldn't be any temps in the arg list.
  9946. Assert(*m_ppnodeVar == nullptr);
  9947. // Start the var list.
  9948. m_ppnodeVar = varNodesList;
  9949. if (scope != nullptr)
  9950. {
  9951. Assert(pnodeFnc->IsBodyAndParamScopeMerged());
  9952. blockId = GetCurrentBlock()->blockId;
  9953. funcId = GetCurrentFunctionNode()->functionId;
  9954. scope->ForEachSymbol([this, blockId, funcId](Symbol* paramSym)
  9955. {
  9956. PidRefStack* ref = this->FindOrAddPidRef(paramSym->GetPid(), blockId, funcId);
  9957. ref->SetSym(paramSym);
  9958. });
  9959. }
  9960. Assert(m_currentNodeNonLambdaFunc == nullptr);
  9961. m_currentNodeNonLambdaFunc = pnodeFnc;
  9962. this->FinishFncNode(pnodeFnc);
  9963. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  9964. m_currentNodeNonLambdaFunc = nullptr;
  9965. m_ppnodeExprScope = ppnodeExprScopeSave;
  9966. Assert(m_ppnodeScope);
  9967. Assert(nullptr == *m_ppnodeScope);
  9968. m_ppnodeScope = ppnodeScopeSave;
  9969. this->FinishParseBlock(pnodeInnerBlock);
  9970. if (!pnodeFnc->IsModule() && (m_token.tk == tkLCurly || !pnodeFnc->IsLambda()))
  9971. {
  9972. UpdateArgumentsNode(pnodeFnc, argNode);
  9973. }
  9974. CreateSpecialSymbolDeclarations(pnodeFnc);
  9975. this->FinishParseBlock(pnodeBlock);
  9976. if (pnodeFncExprBlock)
  9977. {
  9978. this->FinishParseBlock(pnodeFncExprBlock);
  9979. }
  9980. this->m_currentNodeFunc = pnodeFncSave;
  9981. }
  9982. });
  9983. m_nextBlockId = saveNextBlockId;
  9984. }
  9985. void Parser::InitPids()
  9986. {
  9987. wellKnownPropertyPids.arguments = this->GetHashTbl()->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);
  9988. wellKnownPropertyPids.async = this->GetHashTbl()->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);
  9989. wellKnownPropertyPids.eval = this->GetHashTbl()->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);
  9990. wellKnownPropertyPids.get = this->GetHashTbl()->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);
  9991. wellKnownPropertyPids.set = this->GetHashTbl()->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);
  9992. wellKnownPropertyPids.let = this->GetHashTbl()->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);
  9993. wellKnownPropertyPids.constructor = this->GetHashTbl()->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);
  9994. wellKnownPropertyPids.prototype = this->GetHashTbl()->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);
  9995. wellKnownPropertyPids.__proto__ = this->GetHashTbl()->PidHashNameLen(_u("__proto__"), sizeof("__proto__") - 1);
  9996. wellKnownPropertyPids.of = this->GetHashTbl()->PidHashNameLen(_u("of"), sizeof("of") - 1);
  9997. wellKnownPropertyPids.target = this->GetHashTbl()->PidHashNameLen(_u("target"), sizeof("target") - 1);
  9998. wellKnownPropertyPids.as = this->GetHashTbl()->PidHashNameLen(_u("as"), sizeof("as") - 1);
  9999. wellKnownPropertyPids.from = this->GetHashTbl()->PidHashNameLen(_u("from"), sizeof("from") - 1);
  10000. wellKnownPropertyPids._default = this->GetHashTbl()->PidHashNameLen(_u("default"), sizeof("default") - 1);
  10001. wellKnownPropertyPids._starDefaultStar = this->GetHashTbl()->PidHashNameLen(_u("*default*"), sizeof("*default*") - 1);
  10002. wellKnownPropertyPids._star = this->GetHashTbl()->PidHashNameLen(_u("*"), sizeof("*") - 1);
  10003. wellKnownPropertyPids._this = this->GetHashTbl()->PidHashNameLen(_u("*this*"), sizeof("*this*") - 1);
  10004. wellKnownPropertyPids._newTarget = this->GetHashTbl()->PidHashNameLen(_u("*new.target*"), sizeof("*new.target*") - 1);
  10005. wellKnownPropertyPids._super = this->GetHashTbl()->PidHashNameLen(_u("*super*"), sizeof("*super*") - 1);
  10006. wellKnownPropertyPids._superConstructor = this->GetHashTbl()->PidHashNameLen(_u("*superconstructor*"), sizeof("*superconstructor*") - 1);
  10007. }
  10008. void Parser::RestoreScopeInfo(Js::ScopeInfo * scopeInfo)
  10009. {
  10010. if (!scopeInfo)
  10011. {
  10012. return;
  10013. }
  10014. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  10015. RestoreScopeInfo(scopeInfo->GetParentScopeInfo()); // Recursively restore outer func scope info
  10016. scopeInfo->SetScopeId(m_nextBlockId);
  10017. ParseNodeBlock * pnodeScope = nullptr;
  10018. ScopeType scopeType = scopeInfo->GetScopeType();
  10019. PnodeBlockType blockType;
  10020. switch (scopeType)
  10021. {
  10022. case ScopeType_With:
  10023. PushDynamicBlock();
  10024. // fall through
  10025. case ScopeType_Block:
  10026. case ScopeType_Catch:
  10027. case ScopeType_CatchParamPattern:
  10028. case ScopeType_GlobalEvalBlock:
  10029. blockType = PnodeBlockType::Regular;
  10030. break;
  10031. case ScopeType_FunctionBody:
  10032. case ScopeType_FuncExpr:
  10033. blockType = PnodeBlockType::Function;
  10034. break;
  10035. case ScopeType_Parameter:
  10036. blockType = PnodeBlockType::Parameter;
  10037. break;
  10038. default:
  10039. Assert(0);
  10040. return;
  10041. }
  10042. pnodeScope = StartParseBlockWithCapacity<true>(blockType, scopeType, scopeInfo->GetSymbolCount());
  10043. Scope *scope = pnodeScope->scope;
  10044. scope->SetScopeInfo(scopeInfo);
  10045. scopeInfo->ExtractScopeInfo(this, /*nullptr, nullptr,*/ scope);
  10046. }
  10047. void Parser::FinishScopeInfo(Js::ScopeInfo * scopeInfo)
  10048. {
  10049. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  10050. for (; scopeInfo != nullptr; scopeInfo = scopeInfo->GetParentScopeInfo())
  10051. {
  10052. int scopeId = scopeInfo->GetScopeId();
  10053. scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)
  10054. {
  10055. this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);
  10056. });
  10057. PopScope(scopeInfo->GetScope());
  10058. PopStmt(&m_currentBlockInfo->pstmt);
  10059. PopBlockInfo();
  10060. }
  10061. }
  10062. /***************************************************************************
  10063. Parse the code.
  10064. ***************************************************************************/
  10065. ParseNodeProg * Parser::Parse(LPCUTF8 pszSrc, size_t offset, size_t length, charcount_t charOffset, bool isUtf8, ULONG grfscr, ULONG lineNumber, Js::LocalFunctionId * nextFunctionId, CompileScriptException *pse)
  10066. {
  10067. ParseNodeProg * pnodeProg;
  10068. ParseNodePtr *lastNodeRef = nullptr;
  10069. m_nextBlockId = 0;
  10070. bool isDeferred = (grfscr & fscrDeferredFnc) != 0;
  10071. bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;
  10072. bool isGlobalCode = (grfscr & fscrGlobalCode) != 0;
  10073. if (this->m_scriptContext->IsScriptContextInDebugMode()
  10074. #ifdef ENABLE_PREJIT
  10075. || Js::Configuration::Global.flags.Prejit
  10076. #endif
  10077. || ((grfscr & fscrNoDeferParse) != 0)
  10078. )
  10079. {
  10080. // Don't do deferred parsing if debugger is attached or feature is disabled
  10081. // by command-line switch.
  10082. grfscr &= ~fscrWillDeferFncParse;
  10083. }
  10084. else if (!isGlobalCode &&
  10085. (
  10086. PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||
  10087. this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  10088. )
  10089. )
  10090. {
  10091. // Don't defer event handlers in debug/rundown mode, because we need to register the document,
  10092. // so we need to create a full FunctionBody for the script body.
  10093. grfscr &= ~fscrWillDeferFncParse;
  10094. }
  10095. m_grfscr = grfscr;
  10096. m_length = length;
  10097. m_originalLength = length;
  10098. m_nextFunctionId = nextFunctionId;
  10099. if (m_parseType != ParseType_Deferred)
  10100. {
  10101. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));
  10102. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);
  10103. }
  10104. // Give the scanner the source and get the first token
  10105. this->GetScanner()->SetText(pszSrc, offset, length, charOffset, isUtf8, grfscr, lineNumber);
  10106. this->GetScanner()->Scan();
  10107. // Make the main 'knopProg' node
  10108. int32 initSize = 0;
  10109. m_pCurrentAstSize = &initSize;
  10110. pnodeProg = CreateProgNode(isModuleSource, lineNumber);
  10111. if (!isDeferred || (isDeferred && isGlobalCode))
  10112. {
  10113. // In the deferred case, if the global function is deferred parse (which is in no-refresh case),
  10114. // we will re-use the same function body, so start with the correct functionId.
  10115. pnodeProg->functionId = (*m_nextFunctionId)++;
  10116. }
  10117. if (isModuleSource)
  10118. {
  10119. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  10120. pnodeProg->AsParseNodeModule()->localExportEntries = nullptr;
  10121. pnodeProg->AsParseNodeModule()->indirectExportEntries = nullptr;
  10122. pnodeProg->AsParseNodeModule()->starExportEntries = nullptr;
  10123. pnodeProg->AsParseNodeModule()->importEntries = nullptr;
  10124. pnodeProg->AsParseNodeModule()->requestedModules = nullptr;
  10125. }
  10126. m_pCurrentAstSize = &(pnodeProg->astSize);
  10127. // initialize parsing variables
  10128. m_currentNodeFunc = nullptr;
  10129. m_currentNodeDeferredFunc = nullptr;
  10130. m_currentNodeProg = pnodeProg;
  10131. m_cactIdentToNodeLookup = 1;
  10132. m_pnestedCount = &pnodeProg->nestedCount;
  10133. m_inDeferredNestedFunc = false;
  10134. m_ppnodeVar = &pnodeProg->pnodeVars;
  10135. SetCurrentStatement(nullptr);
  10136. AssertMsg(m_pstmtCur == nullptr, "Statement stack should be empty when we start parse global code");
  10137. // Create block for const's and let's
  10138. ParseNodeBlock * pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);
  10139. pnodeProg->scope = pnodeGlobalBlock->scope;
  10140. ParseNodeBlock * pnodeGlobalEvalBlock = nullptr;
  10141. // Don't track function expressions separately from declarations at global scope.
  10142. m_ppnodeExprScope = nullptr;
  10143. // This synthetic block scope will contain all the nested scopes.
  10144. pnodeProg->pnodeScopes = pnodeGlobalBlock;
  10145. m_ppnodeScope = &pnodeGlobalBlock->pnodeScopes;
  10146. if ((this->m_grfscr & fscrEvalCode) &&
  10147. !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))
  10148. {
  10149. pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);
  10150. pnodeProg->pnodeScopes = pnodeGlobalEvalBlock;
  10151. m_ppnodeScope = &pnodeGlobalEvalBlock->pnodeScopes;
  10152. }
  10153. Js::ScopeInfo *scopeInfo = nullptr;
  10154. if (m_parseType == ParseType_Deferred && m_functionBody)
  10155. {
  10156. // this->m_functionBody can be cleared during parsing, but we need access to the scope info later.
  10157. scopeInfo = m_functionBody->GetScopeInfo();
  10158. if (scopeInfo)
  10159. {
  10160. // Create an enclosing function context.
  10161. m_currentNodeFunc = CreateNodeForOpT<knopFncDecl>();
  10162. m_currentNodeFunc->functionId = m_functionBody->GetLocalFunctionId();
  10163. m_currentNodeFunc->nestedCount = m_functionBody->GetNestedCount();
  10164. m_currentNodeFunc->SetStrictMode(!!this->m_fUseStrictMode);
  10165. this->RestoreScopeInfo(scopeInfo);
  10166. m_currentNodeFunc->SetIsGenerator(scopeInfo->IsGeneratorFunctionBody());
  10167. m_currentNodeFunc->SetIsAsync(scopeInfo->IsAsyncFunctionBody());
  10168. }
  10169. }
  10170. // It's possible for the module global to be defer-parsed in debug scenarios.
  10171. if (isModuleSource && (!isDeferred || (isDeferred && isGlobalCode)))
  10172. {
  10173. ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();
  10174. pnodeProg->pnodeBody = nullptr;
  10175. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, moduleFunction);
  10176. }
  10177. else
  10178. {
  10179. if (isDeferred && !isGlobalCode)
  10180. {
  10181. // Defer parse for a single function should just parse that one function - there are no other statements.
  10182. ushort flags = fFncNoFlgs;
  10183. bool isAsync = false;
  10184. bool isGenerator = false;
  10185. bool isMethod = false;
  10186. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  10187. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  10188. // first time we see it.
  10189. //
  10190. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  10191. // token of the source code of the function may not be a 'function' token though, so we still need to reset this flag
  10192. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  10193. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  10194. if (m_grfscr & fscrDeferredFncExpression)
  10195. {
  10196. m_grfscr &= ~fscrDeferredFncExpression;
  10197. }
  10198. else
  10199. {
  10200. flags |= fFncDeclaration;
  10201. }
  10202. if (m_grfscr & fscrDeferredFncIsMethod)
  10203. {
  10204. m_grfscr &= ~fscrDeferredFncIsMethod;
  10205. isMethod = true;
  10206. flags |= fFncNoName | fFncMethod;
  10207. if (m_grfscr & fscrDeferredFncIsGenerator)
  10208. {
  10209. m_grfscr &= ~fscrDeferredFncIsGenerator;
  10210. isGenerator = true;
  10211. flags |= fFncGenerator;
  10212. }
  10213. if (m_token.tk == tkStar && m_scriptContext->GetConfig()->IsES6GeneratorsEnabled())
  10214. {
  10215. Assert(isGenerator && !isMethod);
  10216. this->GetScanner()->Scan();
  10217. }
  10218. }
  10219. if (m_grfscr & fscrDeferredFncIsAsync)
  10220. {
  10221. m_grfscr &= ~fscrDeferredFncIsAsync;
  10222. isAsync = true;
  10223. flags |= fFncAsync;
  10224. }
  10225. #if DBG
  10226. if (isMethod && m_token.tk == tkID)
  10227. {
  10228. RestorePoint atPid;
  10229. IdentPtr pidHint = m_token.GetIdentifier(this->GetHashTbl());
  10230. this->GetScanner()->Capture(&atPid);
  10231. this->GetScanner()->Scan();
  10232. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) && NextTokenIsPropertyNameStart())
  10233. {
  10234. // Getter/setter
  10235. // Skip the get/set keyword and continue normally
  10236. AssertMsg(false, "We should not be re-parsing the get/set part of member accessor functions");
  10237. }
  10238. else
  10239. {
  10240. // Not a getter/setter; rewind and treat the token as a name.
  10241. this->GetScanner()->SeekTo(atPid);
  10242. }
  10243. }
  10244. #endif
  10245. // Ensure this isn't a computed name
  10246. AssertMsg(!(m_token.tk == tkLBrack && isMethod), "Can't defer parse a computed name expression, we should have started after this");
  10247. if (!isMethod && (m_token.tk == tkID || m_token.tk == tkLParen))
  10248. {
  10249. // If first token of the function is tkID or tkLParen, this is a lambda.
  10250. flags |= fFncLambda;
  10251. }
  10252. ParseNode * pnodeFnc = ParseFncDeclCheckScope<true>(flags);
  10253. pnodeProg->pnodeBody = nullptr;
  10254. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, pnodeFnc);
  10255. // No need to update the cbStringMin property since no ParseableFunctionInfo will be created from this defer-parsed pnodeFnc
  10256. }
  10257. else
  10258. {
  10259. // Process a sequence of statements/declarations
  10260. ParseStmtList<true>(
  10261. &pnodeProg->pnodeBody,
  10262. &lastNodeRef,
  10263. SM_OnGlobalCode,
  10264. !(m_grfscr & fscrDeferredFncExpression) /* isSourceElementList */);
  10265. }
  10266. }
  10267. if (m_parseType == ParseType_Deferred)
  10268. {
  10269. if (scopeInfo)
  10270. {
  10271. this->FinishScopeInfo(scopeInfo);
  10272. }
  10273. }
  10274. pnodeProg->m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;
  10275. if (IsStrictMode())
  10276. {
  10277. pnodeProg->SetStrictMode();
  10278. }
  10279. #if DEBUG
  10280. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->pnodeBody))
  10281. {
  10282. Error(ERRsyntax);
  10283. }
  10284. #endif
  10285. if (tkEOF != m_token.tk)
  10286. Error(ERRsyntax);
  10287. // Append an EndCode node.
  10288. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef,
  10289. CreateNodeForOpT<knopEndCode>());
  10290. Assert(lastNodeRef);
  10291. Assert(*lastNodeRef);
  10292. Assert((*lastNodeRef)->nop == knopEndCode);
  10293. (*lastNodeRef)->ichMin = 0;
  10294. (*lastNodeRef)->ichLim = 0;
  10295. // Get the extent of the code.
  10296. pnodeProg->ichLim = this->GetScanner()->IchLimTok();
  10297. pnodeProg->cbLim = this->GetScanner()->IecpLimTok();
  10298. // Terminate the local list
  10299. *m_ppnodeVar = nullptr;
  10300. Assert(nullptr == *m_ppnodeScope);
  10301. Assert(nullptr == pnodeProg->pnodeNext);
  10302. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10303. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10304. {
  10305. m_stoppedDeferredParse = true;
  10306. }
  10307. #endif
  10308. if (m_stoppedDeferredParse)
  10309. {
  10310. #if ENABLE_BACKGROUND_PARSING
  10311. if (this->m_hasParallelJob)
  10312. {
  10313. BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());
  10314. Assert(bgp);
  10315. this->WaitForBackgroundJobs(bgp, pse);
  10316. }
  10317. #endif
  10318. // Do any remaining bindings of globals referenced in non-deferred functions.
  10319. if (pnodeGlobalEvalBlock)
  10320. {
  10321. FinishParseBlock(pnodeGlobalEvalBlock);
  10322. }
  10323. FinishParseBlock(pnodeGlobalBlock);
  10324. // Clear out references to undeclared identifiers.
  10325. this->GetHashTbl()->VisitPids([&](IdentPtr pid) { pid->SetTopRef(nullptr); });
  10326. // Restore global scope and blockinfo stacks preparatory to reparsing deferred functions.
  10327. PushScope(pnodeGlobalBlock->scope);
  10328. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeGlobalBlock);
  10329. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalBlock, knopBlock, nullptr);
  10330. if (pnodeGlobalEvalBlock)
  10331. {
  10332. PushScope(pnodeGlobalEvalBlock->scope);
  10333. newBlockInfo = PushBlockInfo(pnodeGlobalEvalBlock);
  10334. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalEvalBlock, knopBlock, nullptr);
  10335. }
  10336. // Finally, see if there are any function bodies we now want to generate because we
  10337. // decided to stop deferring.
  10338. FinishDeferredFunction(pnodeProg->pnodeScopes);
  10339. }
  10340. if (pnodeGlobalEvalBlock)
  10341. {
  10342. FinishParseBlock(pnodeGlobalEvalBlock);
  10343. }
  10344. // Append block as body of pnodeProg
  10345. FinishParseBlock(pnodeGlobalBlock);
  10346. m_scriptContext->AddSourceSize(m_length);
  10347. if (m_parseType != ParseType_Deferred)
  10348. {
  10349. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));
  10350. }
  10351. return pnodeProg;
  10352. }
  10353. bool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)
  10354. {
  10355. // A directive is a string constant followed by a statement terminating token
  10356. if (m_token.tk != tkStrCon)
  10357. return false;
  10358. // Careful, need to check for octal before calling this->GetScanner()->Scan()
  10359. // because Scan() clears the "had octal" flag on the scanner and
  10360. // this->GetScanner()->Restore() does not restore this flag.
  10361. if (pIsOctalInString != nullptr)
  10362. {
  10363. *pIsOctalInString = this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber();
  10364. }
  10365. Ident* pidDirective = m_token.GetStr();
  10366. RestorePoint start;
  10367. this->GetScanner()->Capture(&start);
  10368. this->GetScanner()->Scan();
  10369. bool isDirective = true;
  10370. switch (m_token.tk)
  10371. {
  10372. case tkSColon:
  10373. case tkEOF:
  10374. case tkLCurly:
  10375. case tkRCurly:
  10376. break;
  10377. default:
  10378. if (!this->GetScanner()->FHadNewLine())
  10379. {
  10380. isDirective = false;
  10381. }
  10382. break;
  10383. }
  10384. if (isDirective)
  10385. {
  10386. if (pIsUseStrict != nullptr)
  10387. {
  10388. *pIsUseStrict = CheckStrictModeStrPid(pidDirective);
  10389. }
  10390. if (pIsUseAsm != nullptr)
  10391. {
  10392. *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);
  10393. }
  10394. }
  10395. this->GetScanner()->SeekTo(start);
  10396. return isDirective;
  10397. }
  10398. bool Parser::CheckStrictModeStrPid(IdentPtr pid)
  10399. {
  10400. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10401. if (Js::Configuration::Global.flags.NoStrictMode)
  10402. return false;
  10403. #endif
  10404. return pid != nullptr &&
  10405. pid->Cch() == 10 &&
  10406. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10407. wcsncmp(pid->Psz(), _u("use strict"), 10) == 0;
  10408. }
  10409. bool Parser::CheckAsmjsModeStrPid(IdentPtr pid)
  10410. {
  10411. #ifdef ASMJS_PLAT
  10412. if (!CONFIG_FLAG(AsmJs))
  10413. {
  10414. return false;
  10415. }
  10416. bool isAsmCandidate = (pid != nullptr &&
  10417. AutoSystemInfo::Data.SSE2Available() &&
  10418. pid->Cch() == 7 &&
  10419. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10420. wcsncmp(pid->Psz(), _u("use asm"), 10) == 0);
  10421. #ifdef ENABLE_SCRIPT_DEBUGGING
  10422. if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())
  10423. {
  10424. // We would like to report this to debugger - they may choose to disable debugging.
  10425. // TODO : localization of the string?
  10426. m_scriptContext->RaiseMessageToDebugger(DEIT_ASMJS_IN_DEBUGGING, _u("AsmJs initialization error - AsmJs disabled due to script debugger"), m_sourceContextInfo && !m_sourceContextInfo->IsDynamic() ? m_sourceContextInfo->url : nullptr);
  10427. return false;
  10428. }
  10429. #endif
  10430. return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);
  10431. #else
  10432. return false;
  10433. #endif
  10434. }
  10435. HRESULT Parser::ParseUtf8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10436. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10437. {
  10438. m_functionBody = nullptr;
  10439. m_parseType = ParseType_Upfront;
  10440. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10441. }
  10442. HRESULT Parser::ParseCesu8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10443. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10444. {
  10445. m_functionBody = nullptr;
  10446. m_parseType = ParseType_Upfront;
  10447. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10448. }
  10449. #if ENABLE_BACKGROUND_PARSING
  10450. void Parser::PrepareForBackgroundParse()
  10451. {
  10452. this->GetScanner()->PrepareForBackgroundParse(m_scriptContext);
  10453. }
  10454. void Parser::AddBackgroundParseItem(BackgroundParseItem *const item)
  10455. {
  10456. if (currBackgroundParseItem == nullptr)
  10457. {
  10458. backgroundParseItems = item;
  10459. }
  10460. else
  10461. {
  10462. currBackgroundParseItem->SetNext(item);
  10463. }
  10464. currBackgroundParseItem = item;
  10465. }
  10466. void Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)
  10467. {
  10468. Assert(!IsBackgroundParser());
  10469. Assert(m_doingFastScan);
  10470. if (fastScannedRegExpNodes == nullptr)
  10471. {
  10472. fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);
  10473. }
  10474. fastScannedRegExpNodes->Append(pnode);
  10475. }
  10476. void Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)
  10477. {
  10478. Assert(IsBackgroundParser());
  10479. Assert(currBackgroundParseItem != nullptr);
  10480. currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);
  10481. }
  10482. HRESULT Parser::ParseFunctionInBackground(ParseNodeFnc * pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)
  10483. {
  10484. m_functionBody = nullptr;
  10485. m_parseType = ParseType_Upfront;
  10486. HRESULT hr = S_OK;
  10487. SmartFPUControl smartFpuControl;
  10488. uint nextFunctionId = pnodeFnc->functionId + 1;
  10489. this->RestoreContext(parseContext);
  10490. m_nextFunctionId = &nextFunctionId;
  10491. m_deferringAST = topLevelDeferred;
  10492. m_inDeferredNestedFunc = false;
  10493. m_scopeCountNoAst = 0;
  10494. SetCurrentStatement(nullptr);
  10495. pnodeFnc->pnodeVars = nullptr;
  10496. pnodeFnc->pnodeParams = nullptr;
  10497. pnodeFnc->pnodeBody = nullptr;
  10498. pnodeFnc->nestedCount = 0;
  10499. ParseNodeFnc * pnodeParentFnc = GetCurrentFunctionNode();
  10500. m_currentNodeFunc = pnodeFnc;
  10501. m_currentNodeDeferredFunc = nullptr;
  10502. m_ppnodeScope = nullptr;
  10503. m_ppnodeExprScope = nullptr;
  10504. m_pnestedCount = &pnodeFnc->nestedCount;
  10505. m_pCurrentAstSize = &pnodeFnc->astSize;
  10506. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10507. pnodeFnc->pnodeScopes = pnodeBlock;
  10508. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  10509. bool handled = false;
  10510. uint uDeferSave = m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse);
  10511. try
  10512. {
  10513. this->GetScanner()->Scan();
  10514. m_ppnodeVar = &pnodeFnc->pnodeParams;
  10515. this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);
  10516. if (m_token.tk == tkRParen)
  10517. {
  10518. this->GetScanner()->Scan();
  10519. }
  10520. ChkCurTok(tkLCurly, ERRnoLcurly);
  10521. m_ppnodeVar = &pnodeFnc->pnodeVars;
  10522. // Put the scanner into "no hashing" mode.
  10523. BYTE deferFlags = this->GetScanner()->SetDeferredParse(topLevelDeferred);
  10524. // Process a sequence of statements/declarations
  10525. if (topLevelDeferred)
  10526. {
  10527. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);
  10528. }
  10529. else
  10530. {
  10531. ParseNodePtr *lastNodeRef = nullptr;
  10532. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);
  10533. AddArgumentsNodeToVars(pnodeFnc);
  10534. // Append an EndCode node.
  10535. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  10536. }
  10537. // Restore the scanner's default hashing mode.
  10538. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  10539. #if DBG
  10540. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  10541. #endif
  10542. this->m_deferringAST = FALSE;
  10543. // Append block as body of pnodeProg
  10544. FinishParseBlock(pnodeBlock);
  10545. }
  10546. catch (ParseExceptionObject& e)
  10547. {
  10548. hr = e.GetError();
  10549. hr = pse->ProcessError(this->GetScanner(), hr, nullptr, e.GetStringOne(), e.GetStringTwo());
  10550. handled = true;
  10551. }
  10552. if (handled == false && FAILED(hr))
  10553. {
  10554. hr = pse->ProcessError(this->GetScanner(), hr, nullptr);
  10555. }
  10556. if (IsStrictMode())
  10557. {
  10558. pnodeFnc->SetStrictMode();
  10559. }
  10560. if (topLevelDeferred)
  10561. {
  10562. pnodeFnc->pnodeVars = nullptr;
  10563. }
  10564. m_grfscr |= uDeferSave;
  10565. Assert(nullptr == *m_ppnodeScope);
  10566. return hr;
  10567. }
  10568. #endif
  10569. HRESULT Parser::ParseSourceWithOffset(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,
  10570. bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,
  10571. Js::ParseableFunctionInfo* functionInfo)
  10572. {
  10573. m_functionBody = functionInfo;
  10574. if (m_functionBody)
  10575. {
  10576. m_currDeferredStub = m_functionBody->GetDeferredStubs();
  10577. m_currDeferredStubCount = m_currDeferredStub != nullptr ? m_functionBody->GetNestedCount() : 0;
  10578. m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();
  10579. }
  10580. m_deferAsmJs = !m_InAsmMode;
  10581. m_parseType = ParseType_Deferred;
  10582. return ParseSourceInternal(parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);
  10583. }
  10584. bool Parser::IsStrictMode() const
  10585. {
  10586. return (m_fUseStrictMode ||
  10587. (m_currentNodeFunc != nullptr && m_currentNodeFunc->GetStrictMode()));
  10588. }
  10589. BOOL Parser::ExpectingExternalSource()
  10590. {
  10591. return m_fExpectExternalSource;
  10592. }
  10593. Symbol *ParseNodeFnc::GetFuncSymbol()
  10594. {
  10595. if (pnodeName)
  10596. {
  10597. Assert(pnodeName->nop == knopVarDecl);
  10598. return pnodeName->sym;
  10599. }
  10600. return nullptr;
  10601. }
  10602. void ParseNodeFnc::SetFuncSymbol(Symbol *sym)
  10603. {
  10604. Assert(pnodeName);
  10605. Assert(pnodeName->nop == knopVarDecl);
  10606. pnodeName->sym = sym;
  10607. }
  10608. ParseNodePtr ParseNodeFnc::GetParamScope() const
  10609. {
  10610. if (this->pnodeScopes == nullptr)
  10611. {
  10612. return nullptr;
  10613. }
  10614. Assert(this->pnodeScopes->nop == knopBlock &&
  10615. this->pnodeScopes->pnodeNext == nullptr);
  10616. return this->pnodeScopes->pnodeScopes;
  10617. }
  10618. ParseNodePtr ParseNodeFnc::GetBodyScope() const
  10619. {
  10620. if (this->pnodeBodyScope == nullptr)
  10621. {
  10622. return nullptr;
  10623. }
  10624. Assert(this->pnodeBodyScope->nop == knopBlock &&
  10625. this->pnodeBodyScope->pnodeNext == nullptr);
  10626. return this->pnodeBodyScope->pnodeScopes;
  10627. }
  10628. bool ParseNodeBlock::HasBlockScopedContent() const
  10629. {
  10630. // A block has its own content if a let, const, or function is declared there.
  10631. if (this->pnodeLexVars != nullptr || this->blockType == Parameter)
  10632. {
  10633. return true;
  10634. }
  10635. // The enclosing scopes can contain functions and other things, so walk the list
  10636. // looking specifically for functions.
  10637. for (ParseNodePtr pnode = this->pnodeScopes; pnode;)
  10638. {
  10639. switch (pnode->nop) {
  10640. case knopFncDecl:
  10641. return true;
  10642. case knopBlock:
  10643. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  10644. break;
  10645. case knopCatch:
  10646. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  10647. break;
  10648. case knopWith:
  10649. pnode = pnode->AsParseNodeWith()->pnodeNext;
  10650. break;
  10651. default:
  10652. Assert(UNREACHED);
  10653. return true;
  10654. }
  10655. }
  10656. return false;
  10657. }
  10658. class ByteCodeGenerator;
  10659. // Copy AST; this works mostly on expressions for now
  10660. ParseNode* Parser::CopyPnode(ParseNode *pnode) {
  10661. if (pnode == NULL)
  10662. return NULL;
  10663. switch (pnode->nop) {
  10664. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  10665. case knopName: {
  10666. ParseNodeName * nameNode = CreateNameNode(pnode->AsParseNodeName()->pid);
  10667. nameNode->ichMin = pnode->ichMin;
  10668. nameNode->ichLim = pnode->ichLim;
  10669. nameNode->sym = pnode->AsParseNodeName()->sym;
  10670. return nameNode;
  10671. }
  10672. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  10673. case knopInt:
  10674. return pnode;
  10675. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  10676. case knopFlt:
  10677. return pnode;
  10678. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  10679. case knopStr:
  10680. return pnode;
  10681. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  10682. case knopRegExp:
  10683. return pnode;
  10684. break;
  10685. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  10686. case knopNull:
  10687. return pnode;
  10688. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  10689. case knopFalse:
  10690. {
  10691. ParseNode* ret = CreateNodeForOpT<knopFalse>(pnode->ichMin, pnode->ichLim);
  10692. ret->location = pnode->location;
  10693. return ret;
  10694. }
  10695. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  10696. case knopTrue:
  10697. {
  10698. ParseNode* ret = CreateNodeForOpT<knopTrue>(pnode->ichMin, pnode->ichLim);
  10699. ret->location = pnode->location;
  10700. return ret;
  10701. }
  10702. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  10703. case knopEmpty:
  10704. return CreateNodeForOpT<knopEmpty>(pnode->ichMin, pnode->ichLim);
  10705. // Unary operators.
  10706. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  10707. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  10708. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  10709. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  10710. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  10711. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  10712. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  10713. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  10714. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  10715. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  10716. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  10717. case knopNot:
  10718. case knopNeg:
  10719. case knopPos:
  10720. case knopLogNot:
  10721. case knopEllipsis:
  10722. case knopIncPost:
  10723. case knopDecPost:
  10724. case knopIncPre:
  10725. case knopDecPre:
  10726. case knopTypeof:
  10727. case knopVoid:
  10728. case knopDelete:
  10729. return CreateUniNode(pnode->nop, CopyPnode(pnode->AsParseNodeUni()->pnode1), pnode->ichMin, pnode->ichLim);
  10730. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  10731. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  10732. case knopArray:
  10733. case knopObject:
  10734. // TODO: need to copy arr
  10735. Assert(false);
  10736. break;
  10737. // Binary operators
  10738. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  10739. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  10740. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  10741. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  10742. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  10743. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  10744. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  10745. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  10746. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  10747. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  10748. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  10749. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  10750. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  10751. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  10752. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  10753. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  10754. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  10755. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  10756. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  10757. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  10758. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10759. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10760. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  10761. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  10762. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  10763. case knopAdd:
  10764. case knopSub:
  10765. case knopMul:
  10766. case knopExpo:
  10767. case knopDiv:
  10768. case knopMod:
  10769. case knopOr:
  10770. case knopXor:
  10771. case knopAnd:
  10772. case knopEq:
  10773. case knopNe:
  10774. case knopLt:
  10775. case knopLe:
  10776. case knopGe:
  10777. case knopGt:
  10778. case knopEqv:
  10779. case knopIn:
  10780. case knopInstOf:
  10781. case knopNEqv:
  10782. case knopComma:
  10783. case knopLogOr:
  10784. case knopLogAnd:
  10785. case knopLsh:
  10786. case knopRsh:
  10787. case knopRs2:
  10788. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10789. case knopAsg:
  10790. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  10791. case knopDot:
  10792. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  10793. case knopAsgAdd:
  10794. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  10795. case knopAsgSub:
  10796. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  10797. case knopAsgMul:
  10798. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  10799. case knopAsgExpo:
  10800. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  10801. case knopAsgDiv:
  10802. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  10803. case knopAsgMod:
  10804. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  10805. case knopAsgAnd:
  10806. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  10807. case knopAsgXor:
  10808. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  10809. case knopAsgOr:
  10810. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  10811. case knopAsgLsh:
  10812. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  10813. case knopAsgRsh:
  10814. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  10815. case knopAsgRs2:
  10816. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  10817. case knopMember:
  10818. case knopMemberShort:
  10819. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  10820. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  10821. case knopIndex:
  10822. case knopList:
  10823. return CreateBinNode(pnode->nop, CopyPnode(pnode->AsParseNodeBin()->pnode1),
  10824. CopyPnode(pnode->AsParseNodeBin()->pnode2), pnode->ichMin, pnode->ichLim);
  10825. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  10826. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  10827. case knopNew:
  10828. case knopCall:
  10829. return CreateCallNode(pnode->nop, CopyPnode(pnode->AsParseNodeCall()->pnodeTarget),
  10830. CopyPnode(pnode->AsParseNodeCall()->pnodeArgs), pnode->ichMin, pnode->ichLim);
  10831. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10832. case knopQmark:
  10833. return CreateTriNode(pnode->nop, CopyPnode(pnode->AsParseNodeTri()->pnode1),
  10834. CopyPnode(pnode->AsParseNodeTri()->pnode2), CopyPnode(pnode->AsParseNodeTri()->pnode3),
  10835. pnode->ichMin, pnode->ichLim);
  10836. // General nodes.
  10837. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10838. case knopVarDecl: {
  10839. ParseNodeVar* copyNode = Anew(&m_nodeAllocator, ParseNodeVar, knopVarDecl, pnode->ichMin, pnode->ichLim, nullptr);
  10840. copyNode->pnodeInit = CopyPnode(pnode->AsParseNodeVar()->pnodeInit);
  10841. copyNode->sym = pnode->AsParseNodeVar()->sym;
  10842. // TODO: mult-decl
  10843. Assert(pnode->AsParseNodeVar()->pnodeNext == NULL);
  10844. copyNode->pnodeNext = NULL;
  10845. return copyNode;
  10846. }
  10847. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10848. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  10849. case knopFncDecl:
  10850. case knopProg:
  10851. Assert(false);
  10852. break;
  10853. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  10854. case knopEndCode:
  10855. break;
  10856. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10857. case knopDebugger:
  10858. break;
  10859. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10860. case knopFor: {
  10861. ParseNode* copyNode = CreateNodeForOpT<knopFor>(pnode->ichMin, pnode->ichLim);
  10862. copyNode->AsParseNodeFor()->pnodeInverted = NULL;
  10863. copyNode->AsParseNodeFor()->pnodeInit = CopyPnode(pnode->AsParseNodeFor()->pnodeInit);
  10864. copyNode->AsParseNodeFor()->pnodeCond = CopyPnode(pnode->AsParseNodeFor()->pnodeCond);
  10865. copyNode->AsParseNodeFor()->pnodeIncr = CopyPnode(pnode->AsParseNodeFor()->pnodeIncr);
  10866. copyNode->AsParseNodeFor()->pnodeBody = CopyPnode(pnode->AsParseNodeFor()->pnodeBody);
  10867. return copyNode;
  10868. }
  10869. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10870. case knopIf:
  10871. Assert(false);
  10872. break;
  10873. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  10874. case knopWhile:
  10875. Assert(false);
  10876. break;
  10877. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10878. case knopDoWhile:
  10879. Assert(false);
  10880. break;
  10881. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10882. case knopForIn:
  10883. Assert(false);
  10884. break;
  10885. case knopForOf:
  10886. Assert(false);
  10887. break;
  10888. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10889. case knopReturn: {
  10890. ParseNode* copyNode = CreateNodeForOpT<knopReturn>(pnode->ichMin, pnode->ichLim);
  10891. copyNode->AsParseNodeReturn()->pnodeExpr = CopyPnode(pnode->AsParseNodeReturn()->pnodeExpr);
  10892. return copyNode;
  10893. }
  10894. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10895. case knopBlock: {
  10896. ParseNodeBlock* copyNode = CreateBlockNode(pnode->ichMin, pnode->ichLim, pnode->AsParseNodeBlock()->blockType);
  10897. if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {
  10898. // fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which
  10899. // CreateBlockNode() will not automatically set for us, so set it here if it's
  10900. // specified on the source node.
  10901. copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;
  10902. }
  10903. copyNode->pnodeStmt = CopyPnode(pnode->AsParseNodeBlock()->pnodeStmt);
  10904. return copyNode;
  10905. }
  10906. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10907. case knopWith:
  10908. Assert(false);
  10909. break;
  10910. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10911. case knopBreak:
  10912. Assert(false);
  10913. break;
  10914. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10915. case knopContinue:
  10916. Assert(false);
  10917. break;
  10918. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  10919. case knopSwitch:
  10920. Assert(false);
  10921. break;
  10922. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  10923. case knopCase:
  10924. Assert(false);
  10925. break;
  10926. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  10927. case knopTryFinally:
  10928. Assert(false);
  10929. break;
  10930. case knopFinally:
  10931. Assert(false);
  10932. break;
  10933. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  10934. case knopCatch:
  10935. Assert(false);
  10936. break;
  10937. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  10938. case knopTryCatch:
  10939. Assert(false);
  10940. break;
  10941. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  10942. case knopTry:
  10943. Assert(false);
  10944. break;
  10945. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  10946. case knopThrow:
  10947. Assert(false);
  10948. break;
  10949. default:
  10950. Assert(false);
  10951. break;
  10952. }
  10953. return NULL;
  10954. }
  10955. // Returns true when str is string for Nan, Infinity or -Infinity.
  10956. // Does not check for double number value being in NaN/Infinity range.
  10957. // static
  10958. template<bool CheckForNegativeInfinity>
  10959. inline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)
  10960. {
  10961. // Note: wcscmp crashes when one of the parameters is NULL.
  10962. return str &&
  10963. (wcscmp(_u("NaN"), str) == 0 ||
  10964. wcscmp(_u("Infinity"), str) == 0 ||
  10965. (CheckForNegativeInfinity && wcscmp(_u("-Infinity"), str) == 0));
  10966. }
  10967. template <bool buildAST>
  10968. IdentPtr Parser::ParseSuper(bool fAllowCall)
  10969. {
  10970. ParseNodeFnc * currentNodeFunc = GetCurrentFunctionNode();
  10971. ParseNodeFnc * currentNonLambdaFunc = GetCurrentNonLambdaFunctionNode();
  10972. IdentPtr superPid = nullptr;
  10973. switch (m_token.tk)
  10974. {
  10975. case tkDot: // super.prop
  10976. case tkLBrack: // super[foo]
  10977. superPid = wellKnownPropertyPids._super;
  10978. break;
  10979. case tkLParen: // super(args)
  10980. superPid = wellKnownPropertyPids._superConstructor;
  10981. break;
  10982. default:
  10983. Error(ERRInvalidSuper);
  10984. break;
  10985. }
  10986. currentNodeFunc->SetHasSuperReference(TRUE);
  10987. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Super, m_scriptContext);
  10988. // If we are defer parsing, we can skip verifying that the super reference is valid.
  10989. // If it wasn't the parser would have thrown during upfront parsing and we wouldn't be defer parsing the function.
  10990. if (m_parseType == ParseType_Deferred)
  10991. {
  10992. return superPid;
  10993. }
  10994. if (!fAllowCall && (m_token.tk == tkLParen))
  10995. {
  10996. Error(ERRInvalidSuper); // new super() is not allowed
  10997. }
  10998. else if ((currentNodeFunc->IsConstructor() && currentNodeFunc->superRestrictionState == SuperRestrictionState::CallAndPropertyAllowed)
  10999. || (currentNonLambdaFunc != nullptr && currentNonLambdaFunc->superRestrictionState == SuperRestrictionState::CallAndPropertyAllowed))
  11000. {
  11001. // Any super access is good within a class constructor
  11002. }
  11003. else if ((this->m_grfscr & fscrEval) == fscrEval || (currentNonLambdaFunc != nullptr && currentNonLambdaFunc->superRestrictionState == SuperRestrictionState::PropertyAllowed))
  11004. {
  11005. // Currently for eval cases during compile time we use propertyallowed and throw during runtime for error cases
  11006. if (m_token.tk == tkLParen)
  11007. {
  11008. if ((this->m_grfscr & fscrEval) == fscrNil)
  11009. {
  11010. // Cannot call super within a class member
  11011. Error(ERRInvalidSuper);
  11012. }
  11013. else
  11014. {
  11015. Js::JavascriptFunction * caller = nullptr;
  11016. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  11017. {
  11018. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  11019. Assert(callerBody);
  11020. if (!callerBody->GetFunctionInfo()->GetAllowDirectSuper())
  11021. {
  11022. Error(ERRInvalidSuper);
  11023. }
  11024. }
  11025. }
  11026. }
  11027. }
  11028. else
  11029. {
  11030. // Anything else is an error
  11031. Error(ERRInvalidSuper);
  11032. }
  11033. return superPid;
  11034. }
  11035. void Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)
  11036. {
  11037. Assert(nodeToAppend);
  11038. ParseNodePtr* lastPtr = node;
  11039. while ((*lastPtr) && (*lastPtr)->nop == knopList)
  11040. {
  11041. lastPtr = &(*lastPtr)->AsParseNodeBin()->pnode2;
  11042. }
  11043. auto last = (*lastPtr);
  11044. if (last)
  11045. {
  11046. *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);
  11047. }
  11048. else
  11049. {
  11050. *lastPtr = nodeToAppend;
  11051. }
  11052. }
  11053. ParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)
  11054. {
  11055. Assert(pnode->nop == knopArray);
  11056. pnode->nop = knopArrayPattern;
  11057. ForEachItemRefInList(&pnode->AsParseNodeArrLit()->pnode1, [&](ParseNodePtr *itemRef) {
  11058. ParseNodePtr item = *itemRef;
  11059. if (item->nop == knopEllipsis)
  11060. {
  11061. itemRef = &item->AsParseNodeUni()->pnode1;
  11062. item = *itemRef;
  11063. if (!(item->nop == knopName
  11064. || item->nop == knopDot
  11065. || item->nop == knopIndex
  11066. || item->nop == knopArray
  11067. || item->nop == knopObject))
  11068. {
  11069. Error(ERRInvalidAssignmentTarget);
  11070. }
  11071. }
  11072. else if (item->nop == knopAsg)
  11073. {
  11074. itemRef = &item->AsParseNodeBin()->pnode1;
  11075. item = *itemRef;
  11076. }
  11077. if (item->nop == knopArray)
  11078. {
  11079. ConvertArrayToArrayPattern(item);
  11080. }
  11081. else if (item->nop == knopObject)
  11082. {
  11083. *itemRef = ConvertObjectToObjectPattern(item);
  11084. }
  11085. else if (item->nop == knopName)
  11086. {
  11087. TrackAssignment<true>(item, nullptr);
  11088. }
  11089. });
  11090. return pnode;
  11091. }
  11092. ParseNodeUni * Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)
  11093. {
  11094. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11095. charcount_t ichLim = this->GetScanner()->IchLimTok();
  11096. if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)
  11097. {
  11098. ichMin = pnodeMemberList->ichMin;
  11099. ichLim = pnodeMemberList->ichLim;
  11100. pnodeMemberList = pnodeMemberList->AsParseNodeUni()->pnode1;
  11101. }
  11102. ParseNodeObjLit * objectPatternNode = CreateObjectPatternNode(pnodeMemberList, ichMin, ichLim, true/*convertToPattern*/);
  11103. return objectPatternNode;
  11104. }
  11105. ParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)
  11106. {
  11107. Assert(pnode != nullptr);
  11108. ParseNodePtr rightNode = nullptr;
  11109. OpCode op = pnode->nop;
  11110. if (op == knopObject)
  11111. {
  11112. rightNode = ConvertObjectToObjectPattern(pnode);
  11113. }
  11114. else if (op == knopArray)
  11115. {
  11116. rightNode = ConvertArrayToArrayPattern(pnode);
  11117. }
  11118. else
  11119. {
  11120. rightNode = pnode;
  11121. if (op == knopName)
  11122. {
  11123. TrackAssignment<true>(pnode, nullptr);
  11124. }
  11125. else if (op == knopAsg)
  11126. {
  11127. TrackAssignment<true>(pnode->AsParseNodeBin()->pnode1, nullptr);
  11128. }
  11129. }
  11130. return rightNode;
  11131. }
  11132. ParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)
  11133. {
  11134. if (pnodeMember->nop == knopObjectPatternMember || pnodeMember->nop == knopEllipsis)
  11135. {
  11136. return pnodeMember;
  11137. }
  11138. Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);
  11139. ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->AsParseNodeBin()->pnode2);
  11140. ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->AsParseNodeBin()->pnode1, rightNode);
  11141. resultNode->ichMin = pnodeMember->ichMin;
  11142. resultNode->ichLim = pnodeMember->ichLim;
  11143. return resultNode;
  11144. }
  11145. ParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)
  11146. {
  11147. if (pnode != nullptr)
  11148. {
  11149. if (pnode->nop == knopArray)
  11150. {
  11151. ConvertArrayToArrayPattern(pnode);
  11152. }
  11153. else if (pnode->nop == knopObject)
  11154. {
  11155. pnode = ConvertObjectToObjectPattern(pnode);
  11156. }
  11157. }
  11158. return pnode;
  11159. }
  11160. // This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.
  11161. void Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,
  11162. bool isDecl,
  11163. bool topLevel,
  11164. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11165. bool allowIn /*= true*/)
  11166. {
  11167. // We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and
  11168. // AST related information before the validation parsing and later they will be restored.
  11169. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  11170. ParseNodeFnc * pnodeDeferredFncSave = m_currentNodeDeferredFunc;
  11171. if (m_currentNodeDeferredFunc == nullptr)
  11172. {
  11173. m_currentNodeDeferredFunc = m_currentNodeFunc;
  11174. }
  11175. int32 *pAstSizeSave = m_pCurrentAstSize;
  11176. uint *pNestedCountSave = m_pnestedCount;
  11177. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  11178. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  11179. ParseNodePtr newTempScope = nullptr;
  11180. m_ppnodeScope = &newTempScope;
  11181. int32 newTempAstSize = 0;
  11182. m_pCurrentAstSize = &newTempAstSize;
  11183. uint newTempNestedCount = 0;
  11184. m_pnestedCount = &newTempNestedCount;
  11185. m_ppnodeExprScope = nullptr;
  11186. charcount_t funcInArraySave = m_funcInArray;
  11187. uint funcInArrayDepthSave = m_funcInArrayDepth;
  11188. // we need to reset this as we are going to parse the grammar again.
  11189. m_hasDeferredShorthandInitError = false;
  11190. ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);
  11191. m_currentNodeFunc = pnodeFncSave;
  11192. m_currentNodeDeferredFunc = pnodeDeferredFncSave;
  11193. m_pCurrentAstSize = pAstSizeSave;
  11194. m_pnestedCount = pNestedCountSave;
  11195. m_ppnodeScope = ppnodeScopeSave;
  11196. m_ppnodeExprScope = ppnodeExprScopeSave;
  11197. m_funcInArray = funcInArraySave;
  11198. m_funcInArrayDepth = funcInArrayDepthSave;
  11199. }
  11200. template <bool buildAST>
  11201. ParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,
  11202. bool isDecl,
  11203. bool topLevel/* = true*/,
  11204. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11205. bool allowIn/* = true*/,
  11206. BOOL *forInOfOkay/* = nullptr*/,
  11207. BOOL *nativeForOkay/* = nullptr*/)
  11208. {
  11209. ParseNodeUni * pnode = nullptr;
  11210. Assert(IsPossiblePatternStart());
  11211. if (m_token.tk == tkLCurly)
  11212. {
  11213. pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);
  11214. }
  11215. else
  11216. {
  11217. pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);
  11218. }
  11219. return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);
  11220. }
  11221. template <bool buildAST>
  11222. ParseNodePtr Parser::ParseDestructuredInitializer(ParseNodeUni * lhsNode,
  11223. bool isDecl,
  11224. bool topLevel,
  11225. DestructuringInitializerContext initializerContext,
  11226. bool allowIn,
  11227. BOOL *forInOfOkay,
  11228. BOOL *nativeForOkay)
  11229. {
  11230. this->GetScanner()->Scan();
  11231. if (topLevel && nativeForOkay == nullptr)
  11232. {
  11233. if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)
  11234. {
  11235. // e.g. var {x};
  11236. Error(ERRDestructInit);
  11237. }
  11238. else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)
  11239. {
  11240. // e.g. catch([x] = [0])
  11241. Error(ERRDestructNotInit);
  11242. }
  11243. }
  11244. if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)
  11245. {
  11246. if (topLevel && nativeForOkay != nullptr)
  11247. {
  11248. // Native loop should have destructuring initializer
  11249. *nativeForOkay = FALSE;
  11250. }
  11251. return lhsNode;
  11252. }
  11253. if (forInOfOkay)
  11254. {
  11255. *forInOfOkay = FALSE;
  11256. }
  11257. this->GetScanner()->Scan();
  11258. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11259. ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);
  11260. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11261. {
  11262. Error(ERRnoColon);
  11263. }
  11264. ParseNodeBin * pnodeDestructAsg = nullptr;
  11265. if (buildAST)
  11266. {
  11267. Assert(lhsNode != nullptr);
  11268. pnodeDestructAsg = CreateBinNode(knopAsg, lhsNode, pnodeDefault, lhsNode->ichMin, pnodeDefault->ichLim);
  11269. }
  11270. return pnodeDestructAsg;
  11271. }
  11272. template <bool buildAST>
  11273. ParseNodeUni * Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel/* = true*/)
  11274. {
  11275. Assert(m_token.tk == tkLCurly);
  11276. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11277. this->GetScanner()->Scan();
  11278. if (!isDecl)
  11279. {
  11280. declarationType = tkLCurly;
  11281. }
  11282. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr/*pNameHint*/, nullptr/*pHintLength*/, declarationType);
  11283. charcount_t ichLim = this->GetScanner()->IchLimTok();
  11284. ParseNodeObjLit * objectPatternNode = buildAST ? CreateObjectPatternNode(pnodeMemberList, ichMin, ichLim) : nullptr;
  11285. Assert(m_token.tk == tkRCurly);
  11286. return objectPatternNode;
  11287. }
  11288. template <bool buildAST>
  11289. ParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel/* = true*/, bool allowEmptyExpression/* = true*/, bool isObjectPattern/* =false*/)
  11290. {
  11291. ParseNodePtr pnodeElem = nullptr;
  11292. int parenCount = 0;
  11293. bool seenRest = false;
  11294. // Save the Block ID prior to the increments, so we can restore it back.
  11295. int originalCurrentBlockId = GetCurrentBlock()->blockId;
  11296. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11297. if (!isDecl)
  11298. {
  11299. while (m_token.tk == tkLParen)
  11300. {
  11301. this->GetScanner()->Scan();
  11302. ++parenCount;
  11303. // Match the block increment we do upon entering parenthetical expressions
  11304. // so that the block ID's will match on reparsing of parameters.
  11305. GetCurrentBlock()->blockId = m_nextBlockId++;
  11306. }
  11307. }
  11308. if (m_token.tk == tkEllipsis)
  11309. {
  11310. // As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed
  11311. // But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.
  11312. seenRest = true;
  11313. this->GetScanner()->Scan();
  11314. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11315. if (!isDecl)
  11316. {
  11317. while (m_token.tk == tkLParen)
  11318. {
  11319. this->GetScanner()->Scan();
  11320. ++parenCount;
  11321. // Match the block increment we do upon entering parenthetical expressions
  11322. // so that the block ID's will match on reparsing of parameters.
  11323. GetCurrentBlock()->blockId = m_nextBlockId++;
  11324. }
  11325. }
  11326. if (m_token.tk != tkID && m_token.tk != tkTHIS && m_token.tk != tkSUPER)
  11327. {
  11328. bool nestedDestructuring = m_token.tk == tkLCurly || m_token.tk == tkLBrack;
  11329. if ((isObjectPattern && nestedDestructuring) || (!isObjectPattern && !nestedDestructuring))
  11330. {
  11331. if (isDecl)
  11332. {
  11333. Error(ERRnoIdent);
  11334. }
  11335. else
  11336. {
  11337. Error(ERRInvalidAssignmentTarget);
  11338. }
  11339. }
  11340. }
  11341. }
  11342. if (IsPossiblePatternStart())
  11343. {
  11344. // For the possible pattern start we do not allow the parens before
  11345. if (parenCount != 0)
  11346. {
  11347. Error(ERRDestructIDRef);
  11348. }
  11349. // Go recursively
  11350. pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false /*topLevel*/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);
  11351. if (!isDecl)
  11352. {
  11353. BOOL fCanAssign;
  11354. IdentToken token;
  11355. // Look for postfix operator
  11356. pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  11357. }
  11358. }
  11359. else if (m_token.tk == tkSUPER || m_token.tk == tkID || m_token.tk == tkTHIS)
  11360. {
  11361. if (isDecl)
  11362. {
  11363. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11364. pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin
  11365. ,/* fAllowIn */false, /* pfForInOk */nullptr, /* singleDefOnly */true, /* allowInit */!seenRest, false /*topLevelParse*/);
  11366. }
  11367. else
  11368. {
  11369. BOOL fCanAssign;
  11370. IdentToken token;
  11371. // We aren't declaring anything, so scan the ID reference manually.
  11372. pnodeElem = ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false,
  11373. FALSE, &fCanAssign);
  11374. // In this destructuring case we can force error here as we cannot assign.
  11375. if (!fCanAssign)
  11376. {
  11377. Error(ERRInvalidAssignmentTarget);
  11378. }
  11379. if (buildAST)
  11380. {
  11381. if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)
  11382. {
  11383. CheckStrictModeEvalArgumentsUsage(pnodeElem->AsParseNodeName()->pid);
  11384. }
  11385. }
  11386. else
  11387. {
  11388. if (IsStrictMode() && token.tk == tkID)
  11389. {
  11390. CheckStrictModeEvalArgumentsUsage(token.pid);
  11391. }
  11392. token.tk = tkNone;
  11393. }
  11394. }
  11395. }
  11396. else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))
  11397. {
  11398. if (m_token.IsOperator())
  11399. {
  11400. Error(ERRDestructNoOper);
  11401. }
  11402. Error(ERRDestructIDRef);
  11403. }
  11404. // Swallow RParens before a default expression, if any.
  11405. // We eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early. We need to do the same for right parentheses.
  11406. if (!isDecl)
  11407. {
  11408. while (m_token.tk == tkRParen)
  11409. {
  11410. this->GetScanner()->Scan();
  11411. --parenCount;
  11412. }
  11413. // Restore the Block ID of the current block after the parsing of destructured variable declarations and initializers.
  11414. GetCurrentBlock()->blockId = originalCurrentBlockId;
  11415. }
  11416. if (parenCount != 0)
  11417. {
  11418. Error(ERRnoRparen);
  11419. }
  11420. if (hasSeenRest != nullptr)
  11421. {
  11422. *hasSeenRest = seenRest;
  11423. }
  11424. if (m_token.tk == tkAsg)
  11425. {
  11426. // Parse the initializer.
  11427. if (seenRest)
  11428. {
  11429. Error(ERRRestWithDefault);
  11430. }
  11431. this->GetScanner()->Scan();
  11432. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11433. ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);
  11434. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11435. {
  11436. Error(ERRnoColon);
  11437. }
  11438. if (buildAST)
  11439. {
  11440. pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);
  11441. }
  11442. }
  11443. if (buildAST && seenRest)
  11444. {
  11445. ParseNodePtr pnodeRest = CreateUniNode(knopEllipsis, pnodeElem);
  11446. pnodeElem = pnodeRest;
  11447. }
  11448. if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))
  11449. {
  11450. if (m_token.IsOperator())
  11451. {
  11452. Error(ERRDestructNoOper);
  11453. }
  11454. Error(ERRsyntax);
  11455. }
  11456. return pnodeElem;
  11457. }
  11458. template <bool buildAST>
  11459. ParseNodeUni * Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)
  11460. {
  11461. Assert(m_token.tk == tkLBrack);
  11462. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11463. this->GetScanner()->Scan();
  11464. ParseNodeArrLit * pnodeDestructArr = nullptr;
  11465. ParseNodePtr pnodeList = nullptr;
  11466. ParseNodePtr *lastNodeRef = nullptr;
  11467. uint count = 0;
  11468. bool hasMissingValues = false;
  11469. bool seenRest = false;
  11470. if (m_token.tk != tkRBrack)
  11471. {
  11472. while (true)
  11473. {
  11474. ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);
  11475. if (buildAST)
  11476. {
  11477. if (pnodeElem == nullptr && buildAST)
  11478. {
  11479. pnodeElem = CreateNodeForOpT<knopEmpty>();
  11480. hasMissingValues = true;
  11481. }
  11482. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);
  11483. }
  11484. count++;
  11485. if (m_token.tk == tkRBrack)
  11486. {
  11487. break;
  11488. }
  11489. if (m_token.tk != tkComma)
  11490. {
  11491. Error(ERRDestructNoOper);
  11492. }
  11493. if (seenRest) // Rest must be in the last position.
  11494. {
  11495. Error(ERRDestructRestLast);
  11496. }
  11497. this->GetScanner()->Scan();
  11498. // break if we have the trailing comma as well, eg. [a,]
  11499. if (m_token.tk == tkRBrack)
  11500. {
  11501. break;
  11502. }
  11503. }
  11504. }
  11505. if (buildAST)
  11506. {
  11507. pnodeDestructArr = CreateNodeForOpT<knopArrayPattern>(ichMin);
  11508. pnodeDestructArr->pnode1 = pnodeList;
  11509. pnodeDestructArr->arrayOfTaggedInts = false;
  11510. pnodeDestructArr->arrayOfInts = false;
  11511. pnodeDestructArr->arrayOfNumbers = false;
  11512. pnodeDestructArr->hasMissingValues = hasMissingValues;
  11513. pnodeDestructArr->count = count;
  11514. pnodeDestructArr->spreadCount = seenRest ? 1 : 0;
  11515. if (pnodeDestructArr->pnode1)
  11516. {
  11517. this->CheckArguments(pnodeDestructArr->pnode1);
  11518. }
  11519. }
  11520. return pnodeDestructArr;
  11521. }
  11522. void Parser::CaptureContext(ParseContext *parseContext) const
  11523. {
  11524. parseContext->pszSrc = this->GetScanner()->PchBase();
  11525. parseContext->length = this->m_originalLength;
  11526. parseContext->characterOffset = this->GetScanner()->IchMinTok();
  11527. parseContext->offset = parseContext->characterOffset + this->GetScanner()->m_cMultiUnits;
  11528. parseContext->grfscr = this->m_grfscr;
  11529. parseContext->lineNumber = this->GetScanner()->LineCur();
  11530. parseContext->pnodeProg = this->m_currentNodeProg;
  11531. parseContext->isUtf8 = this->GetScanner()->IsUtf8();
  11532. parseContext->strictMode = this->IsStrictMode();
  11533. parseContext->sourceContextInfo = this->m_sourceContextInfo;
  11534. parseContext->currentBlockInfo = this->m_currentBlockInfo;
  11535. parseContext->nextBlockId = this->m_nextBlockId;
  11536. }
  11537. void Parser::RestoreContext(ParseContext *const parseContext)
  11538. {
  11539. m_sourceContextInfo = parseContext->sourceContextInfo;
  11540. m_currentBlockInfo = parseContext->currentBlockInfo;
  11541. m_nextBlockId = parseContext->nextBlockId;
  11542. m_grfscr = parseContext->grfscr;
  11543. m_length = parseContext->length;
  11544. this->GetScanner()->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->isUtf8, parseContext->grfscr, parseContext->lineNumber);
  11545. m_currentNodeProg = parseContext->pnodeProg;
  11546. m_fUseStrictMode = parseContext->strictMode;
  11547. }
  11548. class ByteCodeGenerator;
  11549. #if DBG_DUMP
  11550. #define INDENT_SIZE 2
  11551. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt);
  11552. void PrintFormalsWIndent(ParseNode *pnode, int indentAmt);
  11553. void Indent(int indentAmt) {
  11554. for (int i = 0; i < indentAmt; i++) {
  11555. Output::Print(_u(" "));
  11556. }
  11557. }
  11558. void PrintBlockType(PnodeBlockType type)
  11559. {
  11560. switch (type)
  11561. {
  11562. case Global:
  11563. Output::Print(_u("(Global)"));
  11564. break;
  11565. case Function:
  11566. Output::Print(_u("(Function)"));
  11567. break;
  11568. case Regular:
  11569. Output::Print(_u("(Regular)"));
  11570. break;
  11571. case Parameter:
  11572. Output::Print(_u("(Parameter)"));
  11573. break;
  11574. default:
  11575. Output::Print(_u("(unknown blocktype)"));
  11576. break;
  11577. }
  11578. }
  11579. void PrintScopesWIndent(ParseNode *pnode, int indentAmt) {
  11580. ParseNode *scope = nullptr;
  11581. bool firstOnly = false;
  11582. switch (pnode->nop)
  11583. {
  11584. case knopProg:
  11585. case knopFncDecl: scope = pnode->AsParseNodeFnc()->pnodeScopes; break;
  11586. case knopBlock: scope = pnode->AsParseNodeBlock()->pnodeScopes; break;
  11587. case knopCatch: scope = pnode->AsParseNodeCatch()->pnodeScopes; break;
  11588. case knopWith: scope = pnode->AsParseNodeWith()->pnodeScopes; break;
  11589. case knopSwitch: scope = pnode->AsParseNodeSwitch()->pnodeBlock; firstOnly = true; break;
  11590. case knopFor: scope = pnode->AsParseNodeFor()->pnodeBlock; firstOnly = true; break;
  11591. case knopForIn: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11592. case knopForOf: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11593. }
  11594. if (scope) {
  11595. Output::Print(_u("[%4d, %4d): "), scope->ichMin, scope->ichLim);
  11596. Indent(indentAmt);
  11597. Output::Print(_u("Scopes: "));
  11598. ParseNode *next = nullptr;
  11599. ParseNode *syntheticBlock = nullptr;
  11600. while (scope) {
  11601. switch (scope->nop) {
  11602. case knopFncDecl: Output::Print(_u("knopFncDecl")); next = scope->AsParseNodeFnc()->pnodeNext; break;
  11603. case knopBlock: Output::Print(_u("knopBlock")); PrintBlockType(scope->AsParseNodeBlock()->blockType); next = scope->AsParseNodeBlock()->pnodeNext; break;
  11604. case knopCatch: Output::Print(_u("knopCatch")); next = scope->AsParseNodeCatch()->pnodeNext; break;
  11605. case knopWith: Output::Print(_u("knopWith")); next = scope->AsParseNodeWith()->pnodeNext; break;
  11606. default: Output::Print(_u("unknown")); break;
  11607. }
  11608. if (firstOnly) {
  11609. next = nullptr;
  11610. syntheticBlock = scope;
  11611. }
  11612. if (scope->grfpn & fpnSyntheticNode) {
  11613. Output::Print(_u(" synthetic"));
  11614. if (scope->nop == knopBlock)
  11615. syntheticBlock = scope;
  11616. }
  11617. Output::Print(_u(" (%d-%d)"), scope->ichMin, scope->ichLim);
  11618. if (next) Output::Print(_u(", "));
  11619. scope = next;
  11620. }
  11621. Output::Print(_u("\n"));
  11622. if (syntheticBlock || firstOnly) {
  11623. PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);
  11624. }
  11625. }
  11626. }
  11627. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt) {
  11628. if (pnode == NULL)
  11629. return;
  11630. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11631. switch (pnode->nop) {
  11632. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  11633. case knopName:
  11634. Indent(indentAmt);
  11635. if (pnode->AsParseNodeName()->pid != NULL) {
  11636. Output::Print(_u("id: %s\n"), pnode->AsParseNodeName()->pid->Psz());
  11637. }
  11638. else {
  11639. Output::Print(_u("name node\n"));
  11640. }
  11641. break;
  11642. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11643. case knopInt:
  11644. Indent(indentAmt);
  11645. Output::Print(_u("%d\n"), pnode->AsParseNodeInt()->lw);
  11646. break;
  11647. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  11648. case knopFlt:
  11649. Indent(indentAmt);
  11650. Output::Print(_u("%lf\n"), pnode->AsParseNodeFloat()->dbl);
  11651. break;
  11652. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  11653. case knopStr:
  11654. Indent(indentAmt);
  11655. Output::Print(_u("\"%s\"\n"), pnode->AsParseNodeStr()->pid->Psz());
  11656. break;
  11657. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  11658. case knopRegExp:
  11659. Indent(indentAmt);
  11660. Output::Print(_u("/%x/\n"), pnode->AsParseNodeRegExp()->regexPattern);
  11661. break;
  11662. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  11663. case knopNull:
  11664. Indent(indentAmt);
  11665. Output::Print(_u("null\n"));
  11666. break;
  11667. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  11668. case knopFalse:
  11669. Indent(indentAmt);
  11670. Output::Print(_u("false\n"));
  11671. break;
  11672. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  11673. case knopTrue:
  11674. Indent(indentAmt);
  11675. Output::Print(_u("true\n"));
  11676. break;
  11677. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  11678. case knopEmpty:
  11679. Indent(indentAmt);
  11680. Output::Print(_u("empty\n"));
  11681. break;
  11682. // Unary operators.
  11683. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  11684. case knopNot:
  11685. Indent(indentAmt);
  11686. Output::Print(_u("~\n"));
  11687. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11688. break;
  11689. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  11690. case knopNeg:
  11691. Indent(indentAmt);
  11692. Output::Print(_u("U-\n"));
  11693. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11694. break;
  11695. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  11696. case knopPos:
  11697. Indent(indentAmt);
  11698. Output::Print(_u("U+\n"));
  11699. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11700. break;
  11701. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  11702. case knopLogNot:
  11703. Indent(indentAmt);
  11704. Output::Print(_u("!\n"));
  11705. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11706. break;
  11707. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  11708. case knopEllipsis:
  11709. Indent(indentAmt);
  11710. Output::Print(_u("...<expr>\n"));
  11711. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11712. break;
  11713. //PTNODE(knopIncPost , "++ post" ,Inc ,Uni ,fnopUni|fnopAsg)
  11714. case knopIncPost:
  11715. Indent(indentAmt);
  11716. Output::Print(_u("<expr>++\n"));
  11717. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11718. break;
  11719. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  11720. case knopDecPost:
  11721. Indent(indentAmt);
  11722. Output::Print(_u("<expr>--\n"));
  11723. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11724. break;
  11725. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  11726. case knopIncPre:
  11727. Indent(indentAmt);
  11728. Output::Print(_u("++<expr>\n"));
  11729. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11730. break;
  11731. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  11732. case knopDecPre:
  11733. Indent(indentAmt);
  11734. Output::Print(_u("--<expr>\n"));
  11735. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11736. break;
  11737. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  11738. case knopTypeof:
  11739. Indent(indentAmt);
  11740. Output::Print(_u("typeof\n"));
  11741. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11742. break;
  11743. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  11744. case knopVoid:
  11745. Indent(indentAmt);
  11746. Output::Print(_u("void\n"));
  11747. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11748. break;
  11749. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  11750. case knopDelete:
  11751. Indent(indentAmt);
  11752. Output::Print(_u("delete\n"));
  11753. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11754. break;
  11755. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  11756. case knopArrayPattern:
  11757. Indent(indentAmt);
  11758. Output::Print(_u("Array Pattern\n"));
  11759. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11760. break;
  11761. case knopObjectPattern:
  11762. Indent(indentAmt);
  11763. Output::Print(_u("Object Pattern\n"));
  11764. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11765. break;
  11766. case knopArray:
  11767. Indent(indentAmt);
  11768. Output::Print(_u("Array Literal\n"));
  11769. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11770. break;
  11771. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  11772. case knopObject:
  11773. Indent(indentAmt);
  11774. Output::Print(_u("Object Literal\n"));
  11775. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11776. break;
  11777. // Binary and Ternary Operators
  11778. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  11779. case knopAdd:
  11780. Indent(indentAmt);
  11781. Output::Print(_u("+\n"));
  11782. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11783. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11784. break;
  11785. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  11786. case knopSub:
  11787. Indent(indentAmt);
  11788. Output::Print(_u("-\n"));
  11789. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11790. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11791. break;
  11792. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  11793. case knopMul:
  11794. Indent(indentAmt);
  11795. Output::Print(_u("*\n"));
  11796. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11797. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11798. break;
  11799. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  11800. case knopExpo:
  11801. Indent(indentAmt);
  11802. Output::Print(_u("**\n"));
  11803. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11804. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11805. break;
  11806. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  11807. case knopDiv:
  11808. Indent(indentAmt);
  11809. Output::Print(_u("/\n"));
  11810. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11811. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11812. break;
  11813. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  11814. case knopMod:
  11815. Indent(indentAmt);
  11816. Output::Print(_u("%%\n"));
  11817. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11818. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11819. break;
  11820. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  11821. case knopOr:
  11822. Indent(indentAmt);
  11823. Output::Print(_u("|\n"));
  11824. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11825. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11826. break;
  11827. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  11828. case knopXor:
  11829. Indent(indentAmt);
  11830. Output::Print(_u("^\n"));
  11831. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11832. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11833. break;
  11834. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  11835. case knopAnd:
  11836. Indent(indentAmt);
  11837. Output::Print(_u("&\n"));
  11838. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11839. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11840. break;
  11841. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  11842. case knopEq:
  11843. Indent(indentAmt);
  11844. Output::Print(_u("==\n"));
  11845. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11846. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11847. break;
  11848. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  11849. case knopNe:
  11850. Indent(indentAmt);
  11851. Output::Print(_u("!=\n"));
  11852. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11853. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11854. break;
  11855. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  11856. case knopLt:
  11857. Indent(indentAmt);
  11858. Output::Print(_u("<\n"));
  11859. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11860. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11861. break;
  11862. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  11863. case knopLe:
  11864. Indent(indentAmt);
  11865. Output::Print(_u("<=\n"));
  11866. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11867. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11868. break;
  11869. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  11870. case knopGe:
  11871. Indent(indentAmt);
  11872. Output::Print(_u(">=\n"));
  11873. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11874. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11875. break;
  11876. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  11877. case knopGt:
  11878. Indent(indentAmt);
  11879. Output::Print(_u(">\n"));
  11880. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11881. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11882. break;
  11883. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  11884. case knopCall:
  11885. Indent(indentAmt);
  11886. Output::Print(_u("Call\n"));
  11887. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11888. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11889. break;
  11890. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  11891. case knopDot:
  11892. Indent(indentAmt);
  11893. Output::Print(_u(".\n"));
  11894. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11895. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11896. break;
  11897. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  11898. case knopAsg:
  11899. Indent(indentAmt);
  11900. Output::Print(_u("=\n"));
  11901. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11902. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11903. break;
  11904. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  11905. case knopInstOf:
  11906. Indent(indentAmt);
  11907. Output::Print(_u("instanceof\n"));
  11908. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11909. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11910. break;
  11911. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  11912. case knopIn:
  11913. Indent(indentAmt);
  11914. Output::Print(_u("in\n"));
  11915. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11916. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11917. break;
  11918. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  11919. case knopEqv:
  11920. Indent(indentAmt);
  11921. Output::Print(_u("===\n"));
  11922. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11923. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11924. break;
  11925. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  11926. case knopNEqv:
  11927. Indent(indentAmt);
  11928. Output::Print(_u("!==\n"));
  11929. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11930. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11931. break;
  11932. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  11933. case knopComma:
  11934. Indent(indentAmt);
  11935. Output::Print(_u(",\n"));
  11936. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11937. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11938. break;
  11939. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  11940. case knopLogOr:
  11941. Indent(indentAmt);
  11942. Output::Print(_u("||\n"));
  11943. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11944. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11945. break;
  11946. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  11947. case knopLogAnd:
  11948. Indent(indentAmt);
  11949. Output::Print(_u("&&\n"));
  11950. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11951. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11952. break;
  11953. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  11954. case knopLsh:
  11955. Indent(indentAmt);
  11956. Output::Print(_u("<<\n"));
  11957. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11958. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11959. break;
  11960. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  11961. case knopRsh:
  11962. Indent(indentAmt);
  11963. Output::Print(_u(">>\n"));
  11964. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11965. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11966. break;
  11967. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  11968. case knopRs2:
  11969. Indent(indentAmt);
  11970. Output::Print(_u(">>>\n"));
  11971. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11972. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11973. break;
  11974. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  11975. case knopNew:
  11976. Indent(indentAmt);
  11977. Output::Print(_u("new\n"));
  11978. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11979. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11980. break;
  11981. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  11982. case knopIndex:
  11983. Indent(indentAmt);
  11984. Output::Print(_u("[]\n"));
  11985. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11986. PrintPnodeListWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11987. break;
  11988. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  11989. case knopQmark:
  11990. Indent(indentAmt);
  11991. Output::Print(_u("?:\n"));
  11992. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode1, indentAmt + INDENT_SIZE);
  11993. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode2, indentAmt + INDENT_SIZE);
  11994. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode3, indentAmt + INDENT_SIZE);
  11995. break;
  11996. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  11997. case knopAsgAdd:
  11998. Indent(indentAmt);
  11999. Output::Print(_u("+=\n"));
  12000. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12001. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12002. break;
  12003. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  12004. case knopAsgSub:
  12005. Indent(indentAmt);
  12006. Output::Print(_u("-=\n"));
  12007. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12008. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12009. break;
  12010. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  12011. case knopAsgMul:
  12012. Indent(indentAmt);
  12013. Output::Print(_u("*=\n"));
  12014. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12015. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12016. break;
  12017. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  12018. case knopAsgExpo:
  12019. Indent(indentAmt);
  12020. Output::Print(_u("**=\n"));
  12021. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12022. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12023. break;
  12024. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  12025. case knopAsgDiv:
  12026. Indent(indentAmt);
  12027. Output::Print(_u("/=\n"));
  12028. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12029. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12030. break;
  12031. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  12032. case knopAsgMod:
  12033. Indent(indentAmt);
  12034. Output::Print(_u("%=\n"));
  12035. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12036. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12037. break;
  12038. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  12039. case knopAsgAnd:
  12040. Indent(indentAmt);
  12041. Output::Print(_u("&=\n"));
  12042. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12043. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12044. break;
  12045. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  12046. case knopAsgXor:
  12047. Indent(indentAmt);
  12048. Output::Print(_u("^=\n"));
  12049. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12050. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12051. break;
  12052. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  12053. case knopAsgOr:
  12054. Indent(indentAmt);
  12055. Output::Print(_u("|=\n"));
  12056. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12057. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12058. break;
  12059. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  12060. case knopAsgLsh:
  12061. Indent(indentAmt);
  12062. Output::Print(_u("<<=\n"));
  12063. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12064. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12065. break;
  12066. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  12067. case knopAsgRsh:
  12068. Indent(indentAmt);
  12069. Output::Print(_u(">>=\n"));
  12070. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12071. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12072. break;
  12073. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  12074. case knopAsgRs2:
  12075. Indent(indentAmt);
  12076. Output::Print(_u(">>>=\n"));
  12077. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12078. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12079. break;
  12080. case knopComputedName:
  12081. Indent(indentAmt);
  12082. Output::Print(_u("ComputedProperty\n"));
  12083. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12084. break;
  12085. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  12086. case knopMember:
  12087. case knopMemberShort:
  12088. case knopObjectPatternMember:
  12089. Indent(indentAmt);
  12090. Output::Print(_u(":\n"));
  12091. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12092. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12093. break;
  12094. // General nodes.
  12095. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  12096. case knopList:
  12097. Indent(indentAmt);
  12098. Output::Print(_u("List\n"));
  12099. PrintPnodeListWIndent(pnode, indentAmt + INDENT_SIZE);
  12100. break;
  12101. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  12102. case knopVarDecl:
  12103. Indent(indentAmt);
  12104. Output::Print(_u("var %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  12105. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  12106. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  12107. break;
  12108. case knopConstDecl:
  12109. Indent(indentAmt);
  12110. Output::Print(_u("const %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  12111. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  12112. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  12113. break;
  12114. case knopLetDecl:
  12115. Indent(indentAmt);
  12116. Output::Print(_u("let %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  12117. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  12118. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  12119. break;
  12120. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  12121. case knopFncDecl:
  12122. Indent(indentAmt);
  12123. if (pnode->AsParseNodeFnc()->pid != NULL)
  12124. {
  12125. Output::Print(_u("fn decl %d nested %d name %s (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(),
  12126. pnode->AsParseNodeFnc()->pid->Psz(), pnode->ichMin, pnode->ichLim);
  12127. }
  12128. else
  12129. {
  12130. Output::Print(_u("fn decl %d nested %d anonymous (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(), pnode->ichMin, pnode->ichLim);
  12131. }
  12132. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12133. PrintFormalsWIndent(pnode->AsParseNodeFnc()->pnodeParams, indentAmt + INDENT_SIZE);
  12134. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeRest, indentAmt + INDENT_SIZE);
  12135. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  12136. if (pnode->AsParseNodeFnc()->pnodeBody == nullptr)
  12137. {
  12138. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  12139. Indent(indentAmt + INDENT_SIZE);
  12140. Output::Print(_u("<parse deferred body>\n"));
  12141. }
  12142. break;
  12143. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  12144. case knopProg:
  12145. Indent(indentAmt);
  12146. Output::Print(_u("program\n"));
  12147. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12148. PrintPnodeListWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  12149. break;
  12150. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  12151. case knopEndCode:
  12152. Indent(indentAmt);
  12153. Output::Print(_u("<endcode>\n"));
  12154. break;
  12155. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  12156. case knopDebugger:
  12157. Indent(indentAmt);
  12158. Output::Print(_u("<debugger>\n"));
  12159. break;
  12160. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  12161. case knopFor:
  12162. Indent(indentAmt);
  12163. Output::Print(_u("for\n"));
  12164. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12165. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeInit, indentAmt + INDENT_SIZE);
  12166. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeCond, indentAmt + INDENT_SIZE);
  12167. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeIncr, indentAmt + INDENT_SIZE);
  12168. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeBody, indentAmt + INDENT_SIZE);
  12169. break;
  12170. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  12171. case knopIf:
  12172. Indent(indentAmt);
  12173. Output::Print(_u("if\n"));
  12174. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeCond, indentAmt + INDENT_SIZE);
  12175. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeTrue, indentAmt + INDENT_SIZE);
  12176. if (pnode->AsParseNodeIf()->pnodeFalse != NULL)
  12177. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeFalse, indentAmt + INDENT_SIZE);
  12178. break;
  12179. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  12180. case knopWhile:
  12181. Indent(indentAmt);
  12182. Output::Print(_u("while\n"));
  12183. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  12184. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  12185. break;
  12186. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  12187. case knopDoWhile:
  12188. Indent(indentAmt);
  12189. Output::Print(_u("do\n"));
  12190. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  12191. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  12192. break;
  12193. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  12194. case knopForIn:
  12195. Indent(indentAmt);
  12196. Output::Print(_u("forIn\n"));
  12197. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12198. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  12199. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  12200. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  12201. break;
  12202. case knopForOf:
  12203. Indent(indentAmt);
  12204. Output::Print(_u("forOf\n"));
  12205. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12206. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  12207. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  12208. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  12209. break;
  12210. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  12211. case knopReturn:
  12212. Indent(indentAmt);
  12213. Output::Print(_u("return\n"));
  12214. if (pnode->AsParseNodeReturn()->pnodeExpr != NULL)
  12215. PrintPnodeWIndent(pnode->AsParseNodeReturn()->pnodeExpr, indentAmt + INDENT_SIZE);
  12216. break;
  12217. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  12218. case knopBlock:
  12219. Indent(indentAmt);
  12220. Output::Print(_u("block "));
  12221. if (pnode->grfpn & fpnSyntheticNode)
  12222. Output::Print(_u("synthetic "));
  12223. PrintBlockType(pnode->AsParseNodeBlock()->blockType);
  12224. Output::Print(_u("(%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12225. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12226. if (pnode->AsParseNodeBlock()->pnodeStmt != NULL)
  12227. PrintPnodeWIndent(pnode->AsParseNodeBlock()->pnodeStmt, indentAmt + INDENT_SIZE);
  12228. break;
  12229. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  12230. case knopWith:
  12231. Indent(indentAmt);
  12232. Output::Print(_u("with (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12233. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12234. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeObj, indentAmt + INDENT_SIZE);
  12235. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeBody, indentAmt + INDENT_SIZE);
  12236. break;
  12237. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  12238. case knopBreak:
  12239. Indent(indentAmt);
  12240. Output::Print(_u("break\n"));
  12241. // TODO: some representation of target
  12242. break;
  12243. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  12244. case knopContinue:
  12245. Indent(indentAmt);
  12246. Output::Print(_u("continue\n"));
  12247. // TODO: some representation of target
  12248. break;
  12249. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  12250. case knopSwitch:
  12251. Indent(indentAmt);
  12252. Output::Print(_u("switch\n"));
  12253. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12254. for (ParseNodeCase *pnodeT = pnode->AsParseNodeSwitch()->pnodeCases; NULL != pnodeT; pnodeT = pnodeT->pnodeNext) {
  12255. PrintPnodeWIndent(pnodeT, indentAmt + 2);
  12256. }
  12257. break;
  12258. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  12259. case knopCase:
  12260. Indent(indentAmt);
  12261. Output::Print(_u("case\n"));
  12262. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeExpr, indentAmt + INDENT_SIZE);
  12263. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeBody, indentAmt + INDENT_SIZE);
  12264. break;
  12265. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  12266. case knopTryFinally:
  12267. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeTry, indentAmt);
  12268. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeFinally, indentAmt);
  12269. break;
  12270. case knopFinally:
  12271. Indent(indentAmt);
  12272. Output::Print(_u("finally\n"));
  12273. PrintPnodeWIndent(pnode->AsParseNodeFinally()->pnodeBody, indentAmt + INDENT_SIZE);
  12274. break;
  12275. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  12276. case knopCatch:
  12277. Indent(indentAmt);
  12278. Output::Print(_u("catch (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12279. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12280. PrintPnodeWIndent(pnode->AsParseNodeCatch()->GetParam(), indentAmt + INDENT_SIZE);
  12281. // if (pnode->AsParseNodeCatch()->pnodeGuard!=NULL)
  12282. // PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeGuard,indentAmt+INDENT_SIZE);
  12283. PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeBody, indentAmt + INDENT_SIZE);
  12284. break;
  12285. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  12286. case knopTryCatch:
  12287. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeTry, indentAmt);
  12288. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeCatch, indentAmt);
  12289. break;
  12290. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  12291. case knopTry:
  12292. Indent(indentAmt);
  12293. Output::Print(_u("try\n"));
  12294. PrintPnodeWIndent(pnode->AsParseNodeTry()->pnodeBody, indentAmt + INDENT_SIZE);
  12295. break;
  12296. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  12297. case knopThrow:
  12298. Indent(indentAmt);
  12299. Output::Print(_u("throw\n"));
  12300. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12301. break;
  12302. //PTNODE(knopClassDecl, "classDecl", None , Class, fnopLeaf)
  12303. case knopClassDecl:
  12304. Indent(indentAmt);
  12305. Output::Print(_u("class %s"), pnode->AsParseNodeClass()->pnodeName->pid->Psz());
  12306. if (pnode->AsParseNodeClass()->pnodeExtends != nullptr)
  12307. {
  12308. Output::Print(_u(" extends "));
  12309. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeExtends, 0);
  12310. }
  12311. else {
  12312. Output::Print(_u("\n"));
  12313. }
  12314. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeConstructor, indentAmt + INDENT_SIZE);
  12315. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeMembers, indentAmt + INDENT_SIZE);
  12316. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeStaticMembers, indentAmt + INDENT_SIZE);
  12317. break;
  12318. case knopStrTemplate:
  12319. Indent(indentAmt);
  12320. Output::Print(_u("string template\n"));
  12321. PrintPnodeListWIndent(pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);
  12322. break;
  12323. case knopYieldStar:
  12324. Indent(indentAmt);
  12325. Output::Print(_u("yield*\n"));
  12326. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12327. break;
  12328. case knopYield:
  12329. case knopYieldLeaf:
  12330. Indent(indentAmt);
  12331. Output::Print(_u("yield\n"));
  12332. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12333. break;
  12334. case knopAwait:
  12335. Indent(indentAmt);
  12336. Output::Print(_u("await\n"));
  12337. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12338. break;
  12339. case knopExportDefault:
  12340. Indent(indentAmt);
  12341. Output::Print(_u("export default\n"));
  12342. PrintPnodeListWIndent(pnode->AsParseNodeExportDefault()->pnodeExpr, indentAmt + INDENT_SIZE);
  12343. break;
  12344. default:
  12345. Output::Print(_u("unhandled pnode op %d\n"), pnode->nop);
  12346. break;
  12347. }
  12348. }
  12349. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt) {
  12350. if (pnode != NULL) {
  12351. while (pnode->nop == knopList) {
  12352. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt);
  12353. pnode = pnode->AsParseNodeBin()->pnode2;
  12354. }
  12355. PrintPnodeWIndent(pnode, indentAmt);
  12356. }
  12357. }
  12358. void PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)
  12359. {
  12360. for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())
  12361. {
  12362. PrintPnodeWIndent(pnode->nop == knopParamPattern ? pnode->AsParseNodeParamPattern()->pnode1 : pnode, indentAmt);
  12363. }
  12364. }
  12365. void PrintPnode(ParseNode *pnode) {
  12366. PrintPnodeWIndent(pnode, 0);
  12367. }
  12368. void ParseNode::Dump()
  12369. {
  12370. switch (nop)
  12371. {
  12372. case knopFncDecl:
  12373. case knopProg:
  12374. LPCOLESTR name = Js::Constants::AnonymousFunction;
  12375. if (this->AsParseNodeFnc()->pnodeName)
  12376. {
  12377. Assert(this->AsParseNodeFnc()->pnodeName->nop == knopVarDecl);
  12378. name = this->AsParseNodeFnc()->pnodeName->pid->Psz();
  12379. }
  12380. Output::Print(_u("%s (%d) [%d, %d]:\n"), name, this->AsParseNodeFnc()->functionId, this->AsParseNodeFnc()->lineNumber, this->AsParseNodeFnc()->columnNumber);
  12381. Output::Print(_u("hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasOnlyThis:%s \n"),
  12382. IsTrueOrFalse(this->AsParseNodeFnc()->HasHeapArguments()),
  12383. IsTrueOrFalse(this->AsParseNodeFnc()->CallsEval()),
  12384. IsTrueOrFalse(this->AsParseNodeFnc()->ChildCallsEval()),
  12385. IsTrueOrFalse(this->AsParseNodeFnc()->HasReferenceableBuiltInArguments()),
  12386. IsTrueOrFalse(this->AsParseNodeFnc()->GetArgumentsObjectEscapes()),
  12387. IsTrueOrFalse(this->AsParseNodeFnc()->HasWithStmt()),
  12388. IsTrueOrFalse(this->AsParseNodeFnc()->HasOnlyThisStmts()));
  12389. if (this->AsParseNodeFnc()->funcInfo)
  12390. {
  12391. this->AsParseNodeFnc()->funcInfo->Dump();
  12392. }
  12393. break;
  12394. }
  12395. }
  12396. void DumpCapturedNames(ParseNodeFnc* pnodeFnc, IdentPtrSet* capturedNames, ArenaAllocator* alloc)
  12397. {
  12398. auto sortedNames = JsUtil::List<IdentPtr, ArenaAllocator>::New(alloc);
  12399. capturedNames->Map([=](const IdentPtr& pid) -> void {
  12400. sortedNames->Add(pid);
  12401. });
  12402. sortedNames->Sort([](void* context, const void* left, const void* right) -> int {
  12403. const IdentPtr leftIdentPtr = *(const IdentPtr*)(left);
  12404. const IdentPtr rightIdentPtr = *(const IdentPtr*)(right);
  12405. return ::wcscmp(leftIdentPtr->Psz(), rightIdentPtr->Psz());
  12406. }, nullptr);
  12407. sortedNames->Map([=](int index, const IdentPtr pid) -> void {
  12408. OUTPUT_TRACE_DEBUGONLY(Js::CreateParserStatePhase, _u(" Function %u captured name \"%s\"\n"), pnodeFnc->functionId, pid->Psz());
  12409. });
  12410. }
  12411. #endif
  12412. void Parser::AddNestedCapturedNames(ParseNodeFnc* pnodeChildFnc)
  12413. {
  12414. if (m_currentNodeFunc && this->IsCreatingStateCache() && pnodeChildFnc->HasAnyCapturedNames())
  12415. {
  12416. IdentPtrSet* parentCapturedNames = GetCurrentFunctionNode()->EnsureCapturedNames(&m_nodeAllocator);
  12417. IdentPtrSet* childCaptureNames = pnodeChildFnc->GetCapturedNames();
  12418. auto iter = childCaptureNames->GetIterator();
  12419. while (iter.IsValid())
  12420. {
  12421. parentCapturedNames->AddNew(iter.CurrentValue());
  12422. iter.MoveNext();
  12423. }
  12424. }
  12425. }
  12426. void Parser::ProcessCapturedNames(ParseNodeFnc* pnodeFnc)
  12427. {
  12428. if (this->IsCreatingStateCache() && pnodeFnc->HasAnyCapturedNames())
  12429. {
  12430. IdentPtrSet* capturedNames = pnodeFnc->GetCapturedNames();
  12431. auto iter = capturedNames->GetIteratorWithRemovalSupport();
  12432. while (iter.IsValid())
  12433. {
  12434. const IdentPtr& pid = iter.CurrentValueReference();
  12435. PidRefStack* ref = pid->GetTopRef();
  12436. // If the pid has no refs left in our function's scope after binding, we didn't capture it.
  12437. if (!ref || ref->GetFuncScopeId() < pnodeFnc->functionId)
  12438. {
  12439. iter.RemoveCurrent();
  12440. }
  12441. iter.MoveNext();
  12442. }
  12443. #if DBG_DUMP
  12444. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::CreateParserStatePhase))
  12445. {
  12446. DumpCapturedNames(pnodeFnc, capturedNames, &this->m_nodeAllocator);
  12447. fflush(stdout);
  12448. }
  12449. #endif
  12450. }
  12451. }
  12452. void Parser::ReleaseTemporaryGuestArena()
  12453. {
  12454. // In case of modules the Parser lives longer than the temporary Guest Arena. We may have already released the arena explicitly.
  12455. if (!m_tempGuestArenaReleased)
  12456. {
  12457. // The regex patterns list has references to the temporary Guest Arena. Reset it first.
  12458. m_registeredRegexPatterns.Reset();
  12459. if (this->m_scriptContext != nullptr)
  12460. {
  12461. this->m_scriptContext->ReleaseTemporaryGuestAllocator(m_tempGuestArena);
  12462. m_tempGuestArena.Unroot();
  12463. }
  12464. m_tempGuestArenaReleased = true;
  12465. }
  12466. }
  12467. bool Parser::IsCreatingStateCache()
  12468. {
  12469. return (((this->m_grfscr & fscrCreateParserState) == fscrCreateParserState)
  12470. && this->m_functionBody == nullptr
  12471. && CONFIG_FLAG(ParserStateCache));
  12472. }
  12473. void Parser::ShiftCurrDeferredStubToChildFunction(ParseNodeFnc* pnodeFnc, ParseNodeFnc* pnodeFncParent)
  12474. {
  12475. // Goal here is to shift the current deferred stub to point to the stubs for pnodeFnc
  12476. // so we may continue parsing pnodeFnc using the correct set of stubs instead of the
  12477. // stubs for pnodeFncParent.
  12478. // This function assumes we are in the middle of parsing pnodeFnc which is a child
  12479. // nested in pnodeFncParent.
  12480. if (pnodeFnc->IsNested() && pnodeFncParent != nullptr && m_currDeferredStub != nullptr && pnodeFncParent->ichMin != pnodeFnc->ichMin)
  12481. {
  12482. AssertOrFailFast(pnodeFncParent->nestedCount > 0);
  12483. DeferredFunctionStub* childStub = m_currDeferredStub + (pnodeFncParent->nestedCount - 1);
  12484. m_currDeferredStubCount = childStub->nestedCount;
  12485. m_currDeferredStub = childStub->deferredStubs;
  12486. }
  12487. }
  12488. uint Parser::BuildDeferredStubTreeHelper(ParseNodeBlock* pnodeBlock, DeferredFunctionStub* deferredStubs, uint currentStubIndex, uint deferredStubCount, Recycler *recycler)
  12489. {
  12490. Assert(pnodeBlock != nullptr
  12491. && (pnodeBlock->blockType == PnodeBlockType::Function
  12492. || pnodeBlock->blockType == PnodeBlockType::Parameter));
  12493. ParseNodePtr pnodeChild = pnodeBlock->pnodeScopes;
  12494. while (pnodeChild != nullptr)
  12495. {
  12496. if (pnodeChild->nop != knopFncDecl)
  12497. {
  12498. // We only expect to find a function body block in a parameter scope block.
  12499. Assert(pnodeChild->nop == knopBlock
  12500. && (pnodeBlock->blockType == PnodeBlockType::Parameter
  12501. || pnodeChild->AsParseNodeBlock()->blockType == PnodeBlockType::Function));
  12502. pnodeChild = pnodeChild->AsParseNodeBlock()->pnodeNext;
  12503. continue;
  12504. }
  12505. ParseNodeFnc* pnodeFncChild = pnodeChild->AsParseNodeFnc();
  12506. AnalysisAssertOrFailFast(currentStubIndex < deferredStubCount);
  12507. Assert(pnodeFncChild->pnodeBody == nullptr);
  12508. if (pnodeFncChild->IsGeneratedDefault())
  12509. {
  12510. ++currentStubIndex;
  12511. pnodeChild = pnodeFncChild->pnodeNext;
  12512. continue;
  12513. }
  12514. deferredStubs[currentStubIndex].fncFlags = pnodeFncChild->fncFlags;
  12515. deferredStubs[currentStubIndex].nestedCount = pnodeFncChild->nestedCount;
  12516. deferredStubs[currentStubIndex].restorePoint = *pnodeFncChild->pRestorePoint;
  12517. deferredStubs[currentStubIndex].deferredStubs = BuildDeferredStubTree(pnodeFncChild, recycler);
  12518. deferredStubs[currentStubIndex].ichMin = pnodeChild->ichMin;
  12519. // Save the set of captured names onto the deferred stub.
  12520. // Since this set is allocated in the Parser arena, we'll have to convert these
  12521. // into indices in a string table which will survive when the parser goes away.
  12522. deferredStubs[currentStubIndex].capturedNamePointers = pnodeFncChild->GetCapturedNames();
  12523. ++currentStubIndex;
  12524. pnodeChild = pnodeFncChild->pnodeNext;
  12525. }
  12526. return currentStubIndex;
  12527. }
  12528. DeferredFunctionStub * Parser::BuildDeferredStubTree(ParseNodeFnc *pnodeFnc, Recycler *recycler)
  12529. {
  12530. Assert(CONFIG_FLAG(ParserStateCache));
  12531. uint nestedCount = pnodeFnc->nestedCount;
  12532. if (nestedCount == 0)
  12533. {
  12534. return nullptr;
  12535. }
  12536. if (pnodeFnc->deferredStub)
  12537. {
  12538. return pnodeFnc->deferredStub;
  12539. }
  12540. DeferredFunctionStub* deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);
  12541. uint currentStubIndex = BuildDeferredStubTreeHelper(pnodeFnc->pnodeScopes, deferredStubs, 0, nestedCount, recycler);
  12542. currentStubIndex = BuildDeferredStubTreeHelper(pnodeFnc->pnodeBodyScope, deferredStubs, currentStubIndex, nestedCount, recycler);
  12543. Assert(currentStubIndex == nestedCount);
  12544. pnodeFnc->deferredStub = deferredStubs;
  12545. return deferredStubs;
  12546. }