Parse.cpp 484 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051
  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 StmtNest
  29. {
  30. union
  31. {
  32. struct
  33. {
  34. ParseNodeStmt * pnodeStmt; // This statement node.
  35. };
  36. struct
  37. {
  38. bool isDeferred : 1;
  39. OpCode op; // This statement operation.
  40. };
  41. };
  42. LabelId* pLabelId; // Labels for this statement.
  43. StmtNest *pstmtOuter; // Enclosing statement.
  44. OpCode GetNop() const
  45. {
  46. AnalysisAssert(isDeferred || pnodeStmt != nullptr);
  47. return isDeferred ? op : pnodeStmt->nop;
  48. }
  49. };
  50. struct BlockInfoStack
  51. {
  52. StmtNest pstmt;
  53. ParseNodeBlock *pnodeBlock;
  54. ParseNodePtr *m_ppnodeLex; // lexical variable list tail
  55. BlockInfoStack *pBlockInfoOuter; // containing block's BlockInfoStack
  56. BlockInfoStack *pBlockInfoFunction; // nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)
  57. };
  58. #if DEBUG
  59. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)
  60. #else
  61. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)
  62. #endif
  63. : m_nodeAllocator(_u("Parser"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),
  64. m_cactIdentToNodeLookup(0),
  65. m_grfscr(fscrNil),
  66. m_length(0),
  67. m_originalLength(0),
  68. m_nextFunctionId(nullptr),
  69. m_sourceContextInfo(nullptr),
  70. #if ENABLE_BACKGROUND_PARSING
  71. m_isInBackground(isBackground),
  72. m_hasParallelJob(false),
  73. m_doingFastScan(false),
  74. #endif
  75. m_nextBlockId(0),
  76. m_tempGuestArenaReleased(false),
  77. m_tempGuestArena(scriptContext->GetTemporaryGuestAllocator(_u("ParserRegex")), scriptContext->GetRecycler()),
  78. // use the GuestArena directly for keeping the RegexPattern* alive during byte code generation
  79. m_registeredRegexPatterns(m_tempGuestArena->GetAllocator()),
  80. m_scriptContext(scriptContext),
  81. m_token(), // should initialize to 0/nullptrs
  82. m_scan(this, &m_token, scriptContext),
  83. m_currentNodeNonLambdaFunc(nullptr),
  84. m_currentNodeNonLambdaDeferredFunc(nullptr),
  85. m_currentNodeFunc(nullptr),
  86. m_currentNodeDeferredFunc(nullptr),
  87. m_currentNodeProg(nullptr),
  88. m_currDeferredStub(nullptr),
  89. m_currDeferredStubCount(0),
  90. m_pCurrentAstSize(nullptr),
  91. m_ppnodeScope(nullptr),
  92. m_ppnodeExprScope(nullptr),
  93. m_ppnodeVar(nullptr),
  94. m_inDeferredNestedFunc(false),
  95. m_reparsingLambdaParams(false),
  96. m_disallowImportExportStmt(false),
  97. m_isInParsingArgList(false),
  98. m_hasDestructuringPattern(false),
  99. m_hasDeferredShorthandInitError(false),
  100. m_pnestedCount(nullptr),
  101. wellKnownPropertyPids(), // should initialize to nullptrs
  102. m_sourceLim(0),
  103. m_functionBody(nullptr),
  104. m_parseType(ParseType_Upfront),
  105. m_arrayDepth(0),
  106. m_funcInArrayDepth(0),
  107. m_funcInArray(0),
  108. m_scopeCountNoAst(0),
  109. m_parsingSuperRestrictionState(ParsingSuperRestrictionState_SuperDisallowed),
  110. m_funcParenExprDepth(0),
  111. m_deferEllipsisError(false),
  112. m_deferEllipsisErrorLoc(), // calls default initializer
  113. m_tryCatchOrFinallyDepth(0),
  114. m_pstmtCur(nullptr),
  115. m_currentBlockInfo(nullptr),
  116. m_currentScope(nullptr),
  117. currBackgroundParseItem(nullptr),
  118. backgroundParseItems(nullptr),
  119. fastScannedRegExpNodes(nullptr),
  120. m_currentDynamicBlock(nullptr),
  121. m_UsesArgumentsAtGlobal(false),
  122. m_fUseStrictMode(strictMode),
  123. m_InAsmMode(false),
  124. m_deferAsmJs(true),
  125. m_fExpectExternalSource(FALSE),
  126. m_deferringAST(FALSE),
  127. m_stoppedDeferredParse(FALSE)
  128. {
  129. AssertMsg(size == sizeof(Parser), "verify conditionals affecting the size of Parser agree");
  130. Assert(scriptContext != nullptr);
  131. // init PID members
  132. InitPids();
  133. }
  134. Parser::~Parser(void)
  135. {
  136. this->ReleaseTemporaryGuestArena();
  137. #if ENABLE_BACKGROUND_PARSING
  138. if (this->m_hasParallelJob)
  139. {
  140. // Let the background threads know that they can decommit their arena pages.
  141. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  142. Assert(bgp);
  143. if (bgp->Processor()->ProcessesInBackground())
  144. {
  145. JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());
  146. bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {
  147. threadData->canDecommit = true;
  148. return false;
  149. });
  150. Assert(result);
  151. }
  152. }
  153. #endif
  154. }
  155. void Parser::OutOfMemory()
  156. {
  157. throw ParseExceptionObject(ERRnoMemory);
  158. }
  159. void Parser::Error(HRESULT hr)
  160. {
  161. throw ParseExceptionObject(hr);
  162. }
  163. void Parser::Error(HRESULT hr, ParseNodePtr pnode)
  164. {
  165. if (pnode && pnode->ichLim)
  166. {
  167. Error(hr, pnode->ichMin, pnode->ichLim);
  168. }
  169. else
  170. {
  171. Error(hr);
  172. }
  173. }
  174. void Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim)
  175. {
  176. this->GetScanner()->SetErrorPosition(ichMin, ichLim);
  177. Error(hr);
  178. }
  179. void Parser::IdentifierExpectedError(const Token& token)
  180. {
  181. Assert(token.tk != tkID);
  182. HRESULT hr;
  183. if (token.IsReservedWord())
  184. {
  185. if (token.IsKeyword())
  186. {
  187. hr = ERRKeywordNotId;
  188. }
  189. else
  190. {
  191. Assert(token.IsFutureReservedWord(true));
  192. if (token.IsFutureReservedWord(false))
  193. {
  194. // Future reserved word in strict and non-strict modes
  195. hr = ERRFutureReservedWordNotId;
  196. }
  197. else
  198. {
  199. // Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not
  200. // in strict mode.
  201. Assert(IsStrictMode());
  202. hr = ERRFutureReservedWordInStrictModeNotId;
  203. }
  204. }
  205. }
  206. else
  207. {
  208. hr = ERRnoIdent;
  209. }
  210. Error(hr);
  211. }
  212. HRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())
  213. {
  214. Assert(pszSrc);
  215. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  216. HRESULT hr;
  217. SmartFPUControl smartFpuControl;
  218. BOOL fDeferSave = m_deferringAST;
  219. try
  220. {
  221. hr = NOERROR;
  222. m_length = encodedCharCount;
  223. m_originalLength = encodedCharCount;
  224. // make sure deferred parsing is turned off
  225. ULONG grfscr = fscrNil;
  226. // Give the scanner the source and get the first token
  227. this->GetScanner()->SetText(pszSrc, 0, encodedCharCount, 0, false, grfscr);
  228. this->GetScanner()->SetYieldIsKeywordRegion(isGenerator);
  229. this->GetScanner()->SetAwaitIsKeywordRegion(isAsync);
  230. this->GetScanner()->Scan();
  231. uint nestedCount = 0;
  232. m_pnestedCount = &nestedCount;
  233. ParseNodePtr pnodeScope = nullptr;
  234. m_ppnodeScope = &pnodeScope;
  235. m_ppnodeExprScope = nullptr;
  236. uint nextFunctionId = 0;
  237. m_nextFunctionId = &nextFunctionId;
  238. m_inDeferredNestedFunc = false;
  239. m_deferringAST = true;
  240. m_nextBlockId = 0;
  241. ParseNodeFnc *pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  242. pnodeFnc->SetIsGenerator(isGenerator);
  243. pnodeFnc->SetIsAsync(isAsync);
  244. m_ppnodeVar = &pnodeFnc->pnodeVars;
  245. m_currentNodeFunc = pnodeFnc;
  246. m_currentNodeDeferredFunc = NULL;
  247. m_sourceContextInfo = nullptr;
  248. AssertMsg(m_pstmtCur == NULL, "Statement stack should be empty when we start parse function body");
  249. ParseNodeBlock * block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);
  250. (this->*validateFunction)();
  251. FinishParseBlock(block);
  252. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  253. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  254. pnodeFnc->pnodeVars = nullptr;
  255. // there should be nothing after successful parsing for a given construct
  256. if (m_token.tk != tkEOF)
  257. Error(ERRsyntax);
  258. m_deferringAST = fDeferSave;
  259. }
  260. catch (ParseExceptionObject& e)
  261. {
  262. m_deferringAST = fDeferSave;
  263. hr = e.GetError();
  264. }
  265. if (nullptr != pse && FAILED(hr))
  266. {
  267. hr = pse->ProcessError(this->GetScanner(), hr, /* pnodeBase */ NULL);
  268. }
  269. return hr;
  270. }
  271. HRESULT Parser::ParseSourceInternal(
  272. __out ParseNodeProg ** parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,
  273. bool isUtf8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)
  274. {
  275. Assert(parseTree);
  276. Assert(pszSrc);
  277. if (this->IsBackgroundParser())
  278. {
  279. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  280. }
  281. else
  282. {
  283. PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);
  284. }
  285. #ifdef PROFILE_EXEC
  286. m_scriptContext->ProfileBegin(Js::ParsePhase);
  287. #endif
  288. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_START(m_scriptContext, 0));
  289. *parseTree = NULL;
  290. m_sourceLim = 0;
  291. m_grfscr = grfscr;
  292. m_sourceContextInfo = sourceContextInfo;
  293. ParseNodeProg * pnodeBase = NULL;
  294. HRESULT hr;
  295. SmartFPUControl smartFpuControl;
  296. try
  297. {
  298. if ((grfscr & fscrEvalCode) != 0)
  299. {
  300. this->m_parsingSuperRestrictionState = Parser::ParsingSuperRestrictionState_SuperPropertyAllowed;
  301. }
  302. if ((grfscr & fscrIsModuleCode) != 0)
  303. {
  304. // Module source flag should not be enabled unless module is enabled
  305. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  306. // Module code is always strict mode code.
  307. this->m_fUseStrictMode = TRUE;
  308. }
  309. // parse the source
  310. pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, isUtf8, grfscr, lineNumber, nextFunctionId, pse);
  311. Assert(pnodeBase);
  312. // Record the actual number of words parsed.
  313. m_sourceLim = pnodeBase->ichLim - offsetInChars;
  314. // TODO: The assert can be false positive in some scenarios and chuckj to fix it later
  315. // Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, isUtf8 ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);
  316. #if DBG_DUMP
  317. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))
  318. {
  319. PrintPnodeWIndent(pnodeBase, 4);
  320. fflush(stdout);
  321. }
  322. #endif
  323. *parseTree = pnodeBase;
  324. hr = NOERROR;
  325. }
  326. catch (ParseExceptionObject& e)
  327. {
  328. hr = e.GetError();
  329. }
  330. catch (Js::AsmJsParseException&)
  331. {
  332. hr = JSERR_AsmJsCompileError;
  333. }
  334. if (FAILED(hr))
  335. {
  336. hr = pse->ProcessError(this->GetScanner(), hr, pnodeBase);
  337. }
  338. #if ENABLE_BACKGROUND_PARSING
  339. if (this->m_hasParallelJob)
  340. {
  341. ///// Wait here for remaining jobs to finish. Then look for errors, do final const bindings.
  342. // pleath TODO: If there are remaining jobs, let the main thread help finish them.
  343. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  344. Assert(bgp);
  345. CompileScriptException se;
  346. this->WaitForBackgroundJobs(bgp, &se);
  347. BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();
  348. if (failedItem)
  349. {
  350. CompileScriptException *bgPse = failedItem->GetPSE();
  351. Assert(bgPse);
  352. *pse = *bgPse;
  353. hr = failedItem->GetHR();
  354. bgp->SetFailedBackgroundParseItem(nullptr);
  355. }
  356. if (this->fastScannedRegExpNodes != nullptr)
  357. {
  358. this->FinishBackgroundRegExpNodes();
  359. }
  360. for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())
  361. {
  362. Parser *parser = item->GetParser();
  363. parser->FinishBackgroundPidRefs(item, this != parser);
  364. }
  365. }
  366. #endif
  367. // done with the scanner
  368. this->GetScanner()->Clear();
  369. #ifdef PROFILE_EXEC
  370. m_scriptContext->ProfileEnd(Js::ParsePhase);
  371. #endif
  372. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));
  373. return hr;
  374. }
  375. #if ENABLE_BACKGROUND_PARSING
  376. void Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)
  377. {
  378. // The scan of the script is done, but there may be unfinished background jobs in the queue.
  379. // Enlist the main thread to help with those.
  380. BackgroundParseItem *item;
  381. if (!*bgp->GetPendingBackgroundItemsPtr())
  382. {
  383. // We're done.
  384. return;
  385. }
  386. // Save parser state, since we'll need to restore it in order to bind references correctly later.
  387. this->m_isInBackground = true;
  388. this->SetCurrBackgroundParseItem(nullptr);
  389. uint blockIdSave = this->m_nextBlockId;
  390. uint functionIdSave = *this->m_nextFunctionId;
  391. StmtNest *pstmtSave = this->m_pstmtCur;
  392. if (!bgp->Processor()->ProcessesInBackground())
  393. {
  394. // No background thread. Just walk the jobs with no locking and process them.
  395. for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())
  396. {
  397. bgp->Processor()->RemoveJob(item);
  398. bool succeeded = bgp->Process(item, this, pse);
  399. bgp->JobProcessed(item, succeeded);
  400. }
  401. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  402. }
  403. else
  404. {
  405. // Background threads. We need to have the critical section in order to:
  406. // - Check for unprocessed jobs;
  407. // - Remove jobs from the processor queue;
  408. // - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).
  409. CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();
  410. pcs->Enter();
  411. for (;;)
  412. {
  413. // Grab a job (in lock)
  414. item = bgp->GetNextUnprocessedItem();
  415. if (item == nullptr)
  416. {
  417. break;
  418. }
  419. bgp->Processor()->RemoveJob(item);
  420. pcs->Leave();
  421. // Process job (if there is one) (outside lock)
  422. bool succeeded = bgp->Process(item, this, pse);
  423. pcs->Enter();
  424. bgp->JobProcessed(item, succeeded);
  425. }
  426. pcs->Leave();
  427. // Wait for the background threads to finish jobs they're already processing (if any).
  428. // TODO: Replace with a proper semaphore.
  429. while (*bgp->GetPendingBackgroundItemsPtr());
  430. }
  431. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  432. // Restore parser state.
  433. this->m_pstmtCur = pstmtSave;
  434. this->m_isInBackground = false;
  435. this->m_nextBlockId = blockIdSave;
  436. *this->m_nextFunctionId = functionIdSave;
  437. }
  438. void Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)
  439. {
  440. for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)
  441. {
  442. if (isOtherParser)
  443. {
  444. this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());
  445. }
  446. else
  447. {
  448. this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());
  449. }
  450. }
  451. }
  452. void Parser::FinishBackgroundRegExpNodes()
  453. {
  454. // We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,
  455. // and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.
  456. // We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the
  457. // background nodes.
  458. // There may be UI thread nodes for which there are no background thread equivalents, because the UI thread
  459. // has to assume that the background thread won't defer anything.
  460. // Note that because these lists (and the list of background jobs) are SList's built by prepending, they are
  461. // all in reverse lexical order.
  462. Assert(!this->IsBackgroundParser());
  463. Assert(this->fastScannedRegExpNodes);
  464. Assert(this->backgroundParseItems != nullptr);
  465. BackgroundParseItem *currBackgroundItem;
  466. #if DBG
  467. for (currBackgroundItem = this->backgroundParseItems;
  468. currBackgroundItem;
  469. currBackgroundItem = currBackgroundItem->GetNext())
  470. {
  471. if (currBackgroundItem->RegExpNodeList())
  472. {
  473. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  474. {
  475. Assert(pnode->AsParseNodeRegExp()->regexPattern == nullptr);
  476. }
  477. NEXT_DLIST_ENTRY;
  478. }
  479. }
  480. #endif
  481. // Hook up the patterns allocated on the main thread to the nodes created on the background thread.
  482. // Walk the list of foreground nodes, advancing through the work items and looking up each item.
  483. // Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground
  484. // node will have a matching background node. Doesn't matter for correctness.
  485. // (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's
  486. // list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how
  487. // to start the inner loop from a known internal node within the list if that turns out to be important.)
  488. currBackgroundItem = this->backgroundParseItems;
  489. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)
  490. {
  491. Assert(pnodeFgnd->nop == knopRegExp);
  492. Assert(pnodeFgnd->AsParseNodeRegExp()->regexPattern != nullptr);
  493. bool quit = false;
  494. while (!quit)
  495. {
  496. // Find the next work item with a RegEx in it.
  497. while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)
  498. {
  499. currBackgroundItem = currBackgroundItem->GetNext();
  500. }
  501. if (!currBackgroundItem)
  502. {
  503. break;
  504. }
  505. // Walk the RegExps in the work item.
  506. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())
  507. {
  508. Assert(pnodeBgnd->nop == knopRegExp);
  509. if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)
  510. {
  511. // Either we found a match, or the next background node is past the foreground node.
  512. // In any case, we can stop searching.
  513. if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)
  514. {
  515. Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);
  516. pnodeBgnd->AsParseNodeRegExp()->regexPattern = pnodeFgnd->AsParseNodeRegExp()->regexPattern;
  517. }
  518. quit = true;
  519. break;
  520. }
  521. }
  522. NEXT_DLIST_ENTRY;
  523. if (!quit)
  524. {
  525. // Need to advance to the next work item.
  526. currBackgroundItem = currBackgroundItem->GetNext();
  527. }
  528. }
  529. }
  530. NEXT_DLIST_ENTRY;
  531. #if DBG
  532. for (currBackgroundItem = this->backgroundParseItems;
  533. currBackgroundItem;
  534. currBackgroundItem = currBackgroundItem->GetNext())
  535. {
  536. if (currBackgroundItem->RegExpNodeList())
  537. {
  538. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  539. {
  540. Assert(pnode->AsParseNodeRegExp()->regexPattern != nullptr);
  541. }
  542. NEXT_DLIST_ENTRY;
  543. }
  544. }
  545. #endif
  546. }
  547. #endif
  548. LabelId* Parser::CreateLabelId(IdentPtr pid)
  549. {
  550. LabelId* pLabelId;
  551. pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));
  552. if (NULL == pLabelId)
  553. Error(ERRnoMemory);
  554. pLabelId->pid = pid;
  555. pLabelId->next = NULL;
  556. return pLabelId;
  557. }
  558. /*****************************************************************************
  559. The following set of routines allocate parse tree nodes of various kinds.
  560. They catch an exception on out of memory.
  561. *****************************************************************************/
  562. void
  563. Parser::AddAstSize(int size)
  564. {
  565. Assert(!this->m_deferringAST);
  566. Assert(m_pCurrentAstSize != NULL);
  567. *m_pCurrentAstSize += size;
  568. }
  569. void
  570. Parser::AddAstSizeAllowDefer(int size)
  571. {
  572. if (!this->m_deferringAST)
  573. {
  574. AddAstSize(size);
  575. }
  576. }
  577. // StaticCreate
  578. ParseNodeVar * Parser::StaticCreateTempNode(ParseNode* initExpr, ArenaAllocator * alloc)
  579. {
  580. ParseNodeVar * pnode = Anew(alloc, ParseNodeVar, knopTemp, 0, 0, nullptr);
  581. pnode->pnodeInit = initExpr;
  582. return pnode;
  583. }
  584. ParseNodeUni * Parser::StaticCreateTempRef(ParseNode* tempNode, ArenaAllocator * alloc)
  585. {
  586. return Anew(alloc, ParseNodeUni, knopTempRef, 0, 0, tempNode);
  587. }
  588. // Create Node with limit
  589. template <OpCode nop>
  590. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  591. {
  592. Assert(!this->m_deferringAST);
  593. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  594. AddAstSize(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  595. return pnode;
  596. }
  597. template <OpCode nop>
  598. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateAllowDeferNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  599. {
  600. CompileAssert(OpCodeTrait<nop>::AllowDefer);
  601. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  602. AddAstSizeAllowDefer(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  603. return pnode;
  604. }
  605. #if DBG
  606. static const int g_mpnopcbNode[] =
  607. {
  608. #define PTNODE(nop,sn,pc,nk,ok,json) sizeof(ParseNode##nk),
  609. #include "ptlist.h"
  610. };
  611. void VerifyNodeSize(OpCode nop, int size)
  612. {
  613. Assert(nop >= 0 && nop < knopLim);
  614. __analysis_assume(nop < knopLim);
  615. Assert(g_mpnopcbNode[nop] == size);
  616. }
  617. #endif
  618. // Create ParseNodeUni
  619. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)
  620. {
  621. charcount_t ichMin;
  622. charcount_t ichLim;
  623. if (nullptr == pnode1)
  624. {
  625. // no ops
  626. ichMin = this->GetScanner()->IchMinTok();
  627. ichLim = this->GetScanner()->IchLimTok();
  628. }
  629. else
  630. {
  631. // 1 op
  632. ichMin = pnode1->ichMin;
  633. ichLim = pnode1->ichLim;
  634. this->CheckArguments(pnode1);
  635. }
  636. return CreateUniNode(nop, pnode1, ichMin, ichLim);
  637. }
  638. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin, charcount_t ichLim)
  639. {
  640. Assert(!this->m_deferringAST);
  641. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeUni)));
  642. ParseNodeUni * pnode = Anew(&m_nodeAllocator, ParseNodeUni, nop, ichMin, ichLim, pnode1);
  643. AddAstSize(sizeof(ParseNodeUni));
  644. return pnode;
  645. }
  646. // Create ParseNodeBin
  647. ParseNodeBin * Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim)
  648. {
  649. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeBin)));
  650. return Anew(alloc, ParseNodeBin, nop, ichMin, ichLim, pnode1, pnode2);
  651. }
  652. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  653. {
  654. Assert(!this->m_deferringAST);
  655. charcount_t ichMin;
  656. charcount_t ichLim;
  657. if (nullptr == pnode1)
  658. {
  659. // no ops
  660. Assert(nullptr == pnode2);
  661. ichMin = this->GetScanner()->IchMinTok();
  662. ichLim = this->GetScanner()->IchLimTok();
  663. }
  664. else
  665. {
  666. if (nullptr == pnode2)
  667. {
  668. // 1 op
  669. ichMin = pnode1->ichMin;
  670. ichLim = pnode1->ichLim;
  671. }
  672. else
  673. {
  674. // 2 ops
  675. ichMin = pnode1->ichMin;
  676. ichLim = pnode2->ichLim;
  677. if (nop != knopDot && nop != knopIndex)
  678. {
  679. this->CheckArguments(pnode2);
  680. }
  681. }
  682. if (nop != knopDot && nop != knopIndex)
  683. {
  684. this->CheckArguments(pnode1);
  685. }
  686. }
  687. return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
  688. }
  689. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
  690. ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  691. {
  692. Assert(!this->m_deferringAST);
  693. ParseNodeBin * pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator, ichMin, ichLim);
  694. AddAstSize(sizeof(ParseNodeBin));
  695. return pnode;
  696. }
  697. // Create ParseNodeTri
  698. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  699. ParseNodePtr pnode2, ParseNodePtr pnode3)
  700. {
  701. charcount_t ichMin;
  702. charcount_t ichLim;
  703. if (nullptr == pnode1)
  704. {
  705. // no ops
  706. Assert(nullptr == pnode2);
  707. Assert(nullptr == pnode3);
  708. ichMin = this->GetScanner()->IchMinTok();
  709. ichLim = this->GetScanner()->IchLimTok();
  710. }
  711. else if (nullptr == pnode2)
  712. {
  713. // 1 op
  714. Assert(nullptr == pnode3);
  715. ichMin = pnode1->ichMin;
  716. ichLim = pnode1->ichLim;
  717. }
  718. else if (nullptr == pnode3)
  719. {
  720. // 2 op
  721. ichMin = pnode1->ichMin;
  722. ichLim = pnode2->ichLim;
  723. }
  724. else
  725. {
  726. // 3 ops
  727. ichMin = pnode1->ichMin;
  728. ichLim = pnode3->ichLim;
  729. }
  730. return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);
  731. }
  732. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  733. ParseNodePtr pnode2, ParseNodePtr pnode3,
  734. charcount_t ichMin, charcount_t ichLim)
  735. {
  736. Assert(!this->m_deferringAST);
  737. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeTri)));
  738. ParseNodeTri * pnode = Anew(&m_nodeAllocator, ParseNodeTri, nop, ichMin, ichLim);
  739. AddAstSize(sizeof(ParseNodeTri));
  740. pnode->pnode1 = pnode1;
  741. pnode->pnode2 = pnode2;
  742. pnode->pnode3 = pnode3;
  743. return pnode;
  744. }
  745. // Create ParseNodeBlock
  746. ParseNodeBlock *
  747. Parser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim, int blockId, PnodeBlockType blockType)
  748. {
  749. return Anew(alloc, ParseNodeBlock, ichMin, ichLim, blockId, blockType);
  750. }
  751. ParseNodeBlock * Parser::CreateBlockNode(PnodeBlockType blockType)
  752. {
  753. return CreateBlockNode(this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), blockType);
  754. }
  755. ParseNodeBlock * Parser::CreateBlockNode(charcount_t ichMin, charcount_t ichLim, PnodeBlockType blockType)
  756. {
  757. Assert(OpCodeTrait<knopBlock>::AllowDefer);
  758. ParseNodeBlock * pnode = StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);
  759. AddAstSizeAllowDefer(sizeof(ParseNodeBlock));
  760. return pnode;
  761. }
  762. // Create ParseNodeVar
  763. ParseNodeVar * Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  764. {
  765. Assert(nop == knopVarDecl || nop == knopLetDecl || nop == knopConstDecl);
  766. ParseNodeVar * pnode = Anew(&m_nodeAllocator, ParseNodeVar, nop, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  767. if (symbolType != STUnknown)
  768. {
  769. pnode->sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);
  770. }
  771. return pnode;
  772. }
  773. ParseNodeInt * Parser::CreateIntNode(int32 lw)
  774. {
  775. Assert(!this->m_deferringAST);
  776. ParseNodeInt * pnode = Anew(&m_nodeAllocator, ParseNodeInt, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), lw);
  777. AddAstSize(sizeof(ParseNodeInt));
  778. return pnode;
  779. }
  780. ParseNodeStr * Parser::CreateStrNode(IdentPtr pid)
  781. {
  782. Assert(!this->m_deferringAST);
  783. ParseNodeStr * pnode = Anew(&m_nodeAllocator, ParseNodeStr, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  784. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  785. AddAstSize(sizeof(ParseNodeStr));
  786. return pnode;
  787. }
  788. ParseNodeName * Parser::CreateNameNode(IdentPtr pid)
  789. {
  790. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  791. AddAstSizeAllowDefer(sizeof(ParseNodeName));
  792. return pnode;
  793. }
  794. ParseNodeName * Parser::CreateNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  795. {
  796. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, ichMin, ichLim, pid);
  797. pnode->SetSymRef(ref);
  798. AddAstSize(sizeof(ParseNodeName));
  799. return pnode;
  800. }
  801. ParseNodeSpecialName * Parser::CreateSpecialNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  802. {
  803. Assert(!this->m_deferringAST);
  804. ParseNodeSpecialName * pnode = Anew(&m_nodeAllocator, ParseNodeSpecialName, ichMin, ichLim, pid);
  805. pnode->SetSymRef(ref);
  806. if (pid == wellKnownPropertyPids._this)
  807. {
  808. pnode->isThis = true;
  809. }
  810. else if (pid == wellKnownPropertyPids._super || pid == wellKnownPropertyPids._superConstructor)
  811. {
  812. pnode->isSuper = true;
  813. }
  814. AddAstSize(sizeof(ParseNodeSpecialName));
  815. return pnode;
  816. }
  817. ParseNodeSuperReference * Parser::CreateSuperReferenceNode(OpCode nop, ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  818. {
  819. Assert(!this->m_deferringAST);
  820. Assert(pnode1 && pnode1->isSuper);
  821. Assert(pnode2 != nullptr);
  822. Assert(nop == knopDot || nop == knopIndex);
  823. ParseNodeSuperReference * pnode = Anew(&m_nodeAllocator, ParseNodeSuperReference, nop, pnode1->ichMin, pnode2->ichLim, pnode1, pnode2);
  824. AddAstSize(sizeof(ParseNodeSuperReference));
  825. return pnode;
  826. }
  827. ParseNodeProg * Parser::CreateProgNode(bool isModuleSource, ULONG lineNumber)
  828. {
  829. ParseNodeProg * pnodeProg;
  830. if (isModuleSource)
  831. {
  832. pnodeProg = CreateNodeForOpT<knopModule>();
  833. // knopModule is not actually handled anywhere since we would need to handle it everywhere we could
  834. // have knopProg and it would be treated exactly the same except for import/export statements.
  835. // We are only using it as a way to get the correct size for PnModule.
  836. // Consider: Should we add a flag to PnProg which is false but set to true in PnModule?
  837. // If we do, it can't be a virtual method since the parse nodes are all in a union.
  838. pnodeProg->nop = knopProg;
  839. }
  840. else
  841. {
  842. pnodeProg = CreateNodeForOpT<knopProg>();
  843. }
  844. pnodeProg->cbMin = this->GetScanner()->IecpMinTok();
  845. pnodeProg->lineNumber = lineNumber;
  846. pnodeProg->homeObjLocation = Js::Constants::NoRegister;
  847. return pnodeProg;
  848. }
  849. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  850. {
  851. charcount_t ichMin;
  852. charcount_t ichLim;
  853. if (nullptr == pnode1)
  854. {
  855. Assert(nullptr == pnode2);
  856. ichMin = this->GetScanner()->IchMinTok();
  857. ichLim = this->GetScanner()->IchLimTok();
  858. }
  859. else
  860. {
  861. ichMin = pnode1->ichMin;
  862. ichLim = pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim;
  863. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  864. {
  865. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  866. }
  867. }
  868. return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);
  869. }
  870. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  871. {
  872. Assert(!this->m_deferringAST);
  873. // Classes, derived from ParseNodeCall, can be created here as well,
  874. // as long as their size matches kcbPnCall (that is, they don't add
  875. // any data members of their own).
  876. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeCall)));
  877. ParseNodeCall* pnode = Anew(&m_nodeAllocator, ParseNodeCall, nop, ichMin, ichLim, pnode1, pnode2);
  878. AddAstSize(sizeof(ParseNodeCall));
  879. return pnode;
  880. }
  881. ParseNodeSuperCall * Parser::CreateSuperCallNode(ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  882. {
  883. Assert(!this->m_deferringAST);
  884. Assert(pnode1 && pnode1->isSuper);
  885. ParseNodeSuperCall* pnode = Anew(&m_nodeAllocator, ParseNodeSuperCall, knopCall, pnode1->ichMin, pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim, pnode1, pnode2);
  886. AddAstSize(sizeof(ParseNodeSuperCall));
  887. return pnode;
  888. }
  889. ParseNodeParamPattern * Parser::CreateParamPatternNode(ParseNode * pnode1)
  890. {
  891. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(pnode1->ichMin, pnode1->ichLim);
  892. paramPatternNode->pnode1 = pnode1;
  893. paramPatternNode->pnodeNext = nullptr;
  894. paramPatternNode->location = Js::Constants::NoRegister;
  895. return paramPatternNode;
  896. }
  897. ParseNodeParamPattern * Parser::CreateDummyParamPatternNode(charcount_t ichMin)
  898. {
  899. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(ichMin);
  900. paramPatternNode->pnode1 = nullptr;
  901. paramPatternNode->pnodeNext = nullptr;
  902. paramPatternNode->location = Js::Constants::NoRegister;
  903. return paramPatternNode;
  904. }
  905. Symbol* Parser::AddDeclForPid(ParseNodeVar * pnodeVar, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  906. {
  907. Assert(pnodeVar->IsVarLetOrConst());
  908. PidRefStack *refForUse = nullptr, *refForDecl = nullptr;
  909. BlockInfoStack *blockInfo;
  910. bool fBlockScope = false;
  911. if (pnodeVar->nop != knopVarDecl || symbolType == STFunction)
  912. {
  913. Assert(m_pstmtCur);
  914. if (m_pstmtCur->GetNop() != knopBlock)
  915. {
  916. // Let/const declared in a bare statement context.
  917. Error(ERRDeclOutOfStmt);
  918. }
  919. if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->GetNop() == knopSwitch)
  920. {
  921. // Let/const declared inside a switch block (requiring conservative use-before-decl check).
  922. pnodeVar->isSwitchStmtDecl = true;
  923. }
  924. fBlockScope = pnodeVar->nop != knopVarDecl ||
  925. (
  926. !GetCurrentBlockInfo()->pnodeBlock->scope ||
  927. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock
  928. );
  929. }
  930. if (fBlockScope)
  931. {
  932. blockInfo = GetCurrentBlockInfo();
  933. }
  934. else
  935. {
  936. blockInfo = GetCurrentFunctionBlockInfo();
  937. }
  938. refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->blockId, GetCurrentFunctionNode()->functionId);
  939. if (refForDecl == nullptr)
  940. {
  941. Error(ERRnoMemory);
  942. }
  943. if (refForDecl->funcId != GetCurrentFunctionNode()->functionId)
  944. {
  945. // Fix up the function id, which is incorrect if we're reparsing lambda parameters
  946. Assert(this->m_reparsingLambdaParams);
  947. refForDecl->funcId = GetCurrentFunctionNode()->functionId;
  948. }
  949. if (blockInfo == GetCurrentBlockInfo())
  950. {
  951. refForUse = refForDecl;
  952. }
  953. else
  954. {
  955. refForUse = this->PushPidRef(pid);
  956. }
  957. pnodeVar->symRef = refForUse->GetSymRef();
  958. Symbol *sym = refForDecl->GetSym();
  959. if (sym != nullptr)
  960. {
  961. // Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.
  962. switch (pnodeVar->nop)
  963. {
  964. case knopLetDecl:
  965. case knopConstDecl:
  966. if (!sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar && !sym->IsArguments())
  967. {
  968. // If the built-in arguments is shadowed then don't throw
  969. Assert(errorOnRedecl);
  970. // Redeclaration error.
  971. Error(ERRRedeclaration);
  972. }
  973. else
  974. {
  975. // (New) let/const hides the (old) var
  976. sym->SetSymbolType(symbolType);
  977. sym->SetDecl(pnodeVar);
  978. }
  979. break;
  980. case knopVarDecl:
  981. if (m_currentScope->GetScopeType() == ScopeType_Parameter && !sym->IsArguments())
  982. {
  983. // If this is a parameter list, mark the scope to indicate that it has duplicate definition unless it is shadowing the default arguments symbol.
  984. // 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.
  985. m_currentScope->SetHasDuplicateFormals();
  986. }
  987. if (sym->GetDecl() == nullptr)
  988. {
  989. sym->SetDecl(pnodeVar);
  990. break;
  991. }
  992. switch (sym->GetDecl()->nop)
  993. {
  994. case knopLetDecl:
  995. case knopConstDecl:
  996. // Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.
  997. if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))
  998. {
  999. Error(ERRRedeclaration);
  1000. }
  1001. // If !errorOnRedecl, (old) let/const hides the (new) var, so do nothing.
  1002. break;
  1003. case knopVarDecl:
  1004. // Legal redeclaration. Who wins?
  1005. if (errorOnRedecl || sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsArguments())
  1006. {
  1007. if (symbolType == STFormal ||
  1008. (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||
  1009. sym->GetSymbolType() == STVariable)
  1010. {
  1011. // New decl wins.
  1012. sym->SetSymbolType(symbolType);
  1013. sym->SetDecl(pnodeVar);
  1014. }
  1015. }
  1016. break;
  1017. }
  1018. break;
  1019. }
  1020. }
  1021. else
  1022. {
  1023. Scope *scope = blockInfo->pnodeBlock->scope;
  1024. if (scope == nullptr)
  1025. {
  1026. Assert(blockInfo->pnodeBlock->blockType == PnodeBlockType::Regular);
  1027. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);
  1028. if (this->IsCurBlockInLoop())
  1029. {
  1030. scope->SetIsBlockInLoop();
  1031. }
  1032. blockInfo->pnodeBlock->scope = scope;
  1033. PushScope(scope);
  1034. }
  1035. ParseNodeFnc * pnodeFnc = GetCurrentFunctionNode();
  1036. if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)
  1037. {
  1038. Assert(fBlockScope);
  1039. Assert(scope->GetEnclosingScope() == m_currentNodeProg->scope);
  1040. // Check for same-named decl in Global scope.
  1041. CheckRedeclarationErrorForBlockId(pid, 0);
  1042. }
  1043. else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&
  1044. !(m_functionBody && m_functionBody->GetScopeInfo()))
  1045. {
  1046. // Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary
  1047. // if we're compiling a deferred nested function and the global scope was restored from cached info,
  1048. // because in that case we don't need a GlobalEvalScope.
  1049. Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);
  1050. CheckRedeclarationErrorForBlockId(pid, 1);
  1051. }
  1052. else if (!pnodeFnc->IsBodyAndParamScopeMerged()
  1053. && scope->GetScopeType() == ScopeType_FunctionBody
  1054. && (pnodeVar->nop == knopLetDecl || pnodeVar->nop == knopConstDecl))
  1055. {
  1056. // In case of split scope function when we add a new let or const declaration to the body
  1057. // we have to check whether the param scope already has the same symbol defined.
  1058. CheckRedeclarationErrorForBlockId(pid, pnodeFnc->pnodeScopes->blockId);
  1059. }
  1060. if (!sym)
  1061. {
  1062. const char16 *name = reinterpret_cast<const char16*>(pid->Psz());
  1063. int nameLength = pid->Cch();
  1064. SymbolName const symName(name, nameLength);
  1065. Assert(!scope->FindLocalSymbol(symName));
  1066. sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeVar, symbolType);
  1067. scope->AddNewSymbol(sym);
  1068. sym->SetPid(pid);
  1069. }
  1070. refForDecl->SetSym(sym);
  1071. }
  1072. return sym;
  1073. }
  1074. void Parser::CheckRedeclarationErrorForBlockId(IdentPtr pid, int blockId)
  1075. {
  1076. // If the ref stack entry for the blockId contains a sym then throw redeclaration error
  1077. PidRefStack *pidRefOld = pid->GetPidRefForScopeId(blockId);
  1078. if (pidRefOld && pidRefOld->GetSym() && !pidRefOld->GetSym()->IsArguments())
  1079. {
  1080. Error(ERRRedeclaration);
  1081. }
  1082. }
  1083. bool Parser::IsCurBlockInLoop() const
  1084. {
  1085. for (StmtNest *stmt = this->m_pstmtCur; stmt != nullptr; stmt = stmt->pstmtOuter)
  1086. {
  1087. OpCode nop = stmt->GetNop();
  1088. if (ParseNode::Grfnop(nop) & fnopContinue)
  1089. {
  1090. return true;
  1091. }
  1092. if (nop == knopFncDecl)
  1093. {
  1094. return false;
  1095. }
  1096. }
  1097. return false;
  1098. }
  1099. void Parser::RestorePidRefForSym(Symbol *sym)
  1100. {
  1101. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());
  1102. Assert(pid);
  1103. sym->SetPid(pid);
  1104. PidRefStack *ref = this->PushPidRef(pid);
  1105. ref->SetSym(sym);
  1106. }
  1107. void Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)
  1108. {
  1109. if (IsStrictMode())
  1110. {
  1111. // in strict mode, variable named 'eval' cannot be created
  1112. if (pid == wellKnownPropertyPids.eval)
  1113. {
  1114. Error(ERREvalUsage);
  1115. }
  1116. else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)
  1117. {
  1118. Error(ERRArgsUsage);
  1119. }
  1120. }
  1121. }
  1122. // CreateVarDecl needs m_ppnodeVar to be pointing to the right function.
  1123. // Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.
  1124. // This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.
  1125. // This prevents accidentally adding var declarations to the last parsed function.
  1126. ParseNodeVar * Parser::AddVarDeclNode(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1127. {
  1128. AnalysisAssert(pnodeFnc);
  1129. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  1130. m_ppnodeVar = &pnodeFnc->pnodeVars;
  1131. while (*m_ppnodeVar != nullptr)
  1132. {
  1133. m_ppnodeVar = &(*m_ppnodeVar)->AsParseNodeVar()->pnodeNext;
  1134. }
  1135. ParseNodeVar * pnode = CreateVarDeclNode(pid, STUnknown, false, 0, /* checkReDecl = */ false);
  1136. m_ppnodeVar = ppnodeVarSave;
  1137. return pnode;
  1138. }
  1139. ParseNodeVar * Parser::CreateModuleImportDeclNode(IdentPtr localName)
  1140. {
  1141. ParseNodeVar * declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);
  1142. Symbol* sym = declNode->sym;
  1143. sym->SetIsModuleExportStorage(true);
  1144. sym->SetIsModuleImport(true);
  1145. return declNode;
  1146. }
  1147. ParseNodeVar * Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)
  1148. {
  1149. ParseNodeVar * pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);
  1150. // Append the variable to the end of the current variable list.
  1151. Assert(m_ppnodeVar);
  1152. pnode->pnodeNext = *m_ppnodeVar;
  1153. *m_ppnodeVar = pnode;
  1154. if (nullptr != pid)
  1155. {
  1156. // this is not a temp - make sure temps go after this node
  1157. Assert(pid);
  1158. m_ppnodeVar = &pnode->pnodeNext;
  1159. CheckPidIsValid(pid, autoArgumentsObject);
  1160. }
  1161. return pnode;
  1162. }
  1163. ParseNodeVar * Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)
  1164. {
  1165. Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);
  1166. ParseNodeVar * pnode = CreateDeclNode(nodeType, pid, STVariable, true);
  1167. if (nullptr != pid)
  1168. {
  1169. Assert(pid);
  1170. AddVarDeclToBlock(pnode);
  1171. CheckPidIsValid(pid);
  1172. }
  1173. return pnode;
  1174. }
  1175. void Parser::AddVarDeclToBlock(ParseNodeVar *pnode)
  1176. {
  1177. Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);
  1178. // Maintain a combined list of let and const declarations to keep
  1179. // track of declaration order.
  1180. Assert(m_currentBlockInfo->m_ppnodeLex);
  1181. *m_currentBlockInfo->m_ppnodeLex = pnode;
  1182. m_currentBlockInfo->m_ppnodeLex = &pnode->pnodeNext;
  1183. pnode->pnodeNext = nullptr;
  1184. }
  1185. void Parser::SetCurrentStatement(StmtNest *stmt)
  1186. {
  1187. m_pstmtCur = stmt;
  1188. }
  1189. template<bool buildAST>
  1190. ParseNodeBlock * Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)
  1191. {
  1192. Scope *scope = nullptr;
  1193. // Block scopes are not created lazily in the case where we're repopulating a persisted scope.
  1194. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);
  1195. PushScope(scope);
  1196. return StartParseBlockHelper<buildAST>(blockType, scope, nullptr);
  1197. }
  1198. template<bool buildAST>
  1199. ParseNodeBlock * Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, LabelId* pLabelId)
  1200. {
  1201. Scope *scope = nullptr;
  1202. // Block scopes are created lazily when we discover block-scoped content.
  1203. if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)
  1204. {
  1205. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);
  1206. PushScope(scope);
  1207. }
  1208. return StartParseBlockHelper<buildAST>(blockType, scope, pLabelId);
  1209. }
  1210. template<bool buildAST>
  1211. ParseNodeBlock * Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, LabelId* pLabelId)
  1212. {
  1213. ParseNodeBlock * pnodeBlock = CreateBlockNode(blockType);
  1214. pnodeBlock->scope = scope;
  1215. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);
  1216. PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pLabelId);
  1217. return pnodeBlock;
  1218. }
  1219. void Parser::PushScope(Scope *scope)
  1220. {
  1221. Assert(scope);
  1222. scope->SetEnclosingScope(m_currentScope);
  1223. m_currentScope = scope;
  1224. }
  1225. void Parser::PopScope(Scope *scope)
  1226. {
  1227. Assert(scope == m_currentScope);
  1228. m_currentScope = scope->GetEnclosingScope();
  1229. scope->SetEnclosingScope(nullptr);
  1230. }
  1231. void Parser::PushFuncBlockScope(ParseNodeBlock * pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)
  1232. {
  1233. // Maintain the scope tree.
  1234. pnodeBlock->pnodeScopes = nullptr;
  1235. pnodeBlock->pnodeNext = nullptr;
  1236. // Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).
  1237. // Save the current block's "next" pointer as the new endpoint of that list.
  1238. if (m_ppnodeExprScope)
  1239. {
  1240. *ppnodeScopeSave = m_ppnodeScope;
  1241. Assert(*m_ppnodeExprScope == nullptr);
  1242. *m_ppnodeExprScope = pnodeBlock;
  1243. *ppnodeExprScopeSave = &pnodeBlock->pnodeNext;
  1244. }
  1245. else
  1246. {
  1247. Assert(m_ppnodeScope);
  1248. Assert(*m_ppnodeScope == nullptr);
  1249. *m_ppnodeScope = pnodeBlock;
  1250. *ppnodeScopeSave = &pnodeBlock->pnodeNext;
  1251. *ppnodeExprScopeSave = m_ppnodeExprScope;
  1252. }
  1253. // Advance the global scope list pointer to the new block's child list.
  1254. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  1255. // Set m_ppnodeExprScope to NULL to make that list inactive.
  1256. m_ppnodeExprScope = nullptr;
  1257. }
  1258. void Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)
  1259. {
  1260. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  1261. m_ppnodeExprScope = ppnodeExprScopeSave;
  1262. Assert(m_ppnodeScope);
  1263. Assert(nullptr == *m_ppnodeScope);
  1264. m_ppnodeScope = ppnodeScopeSave;
  1265. }
  1266. template<bool buildAST>
  1267. ParseNodeBlock * Parser::ParseBlock(LabelId* pLabelId)
  1268. {
  1269. ParseNodeBlock * pnodeBlock = nullptr;
  1270. ParseNodePtr *ppnodeScopeSave = nullptr;
  1271. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  1272. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pLabelId);
  1273. BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1274. if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr
  1275. && outerBlockInfo->pnodeBlock->scope != nullptr
  1276. && outerBlockInfo->pnodeBlock->scope->GetScopeType() == ScopeType_CatchParamPattern)
  1277. {
  1278. // If we are parsing the catch block then destructured params can have let declarations. Let's add them to the new block.
  1279. for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1280. {
  1281. PidRefStack* ref = PushPidRef(pnode->AsParseNodeVar()->sym->GetPid());
  1282. ref->SetSym(pnode->AsParseNodeVar()->sym);
  1283. }
  1284. }
  1285. ChkCurTok(tkLCurly, ERRnoLcurly);
  1286. ParseNodePtr * ppnodeList = nullptr;
  1287. if (buildAST)
  1288. {
  1289. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  1290. ppnodeList = &pnodeBlock->pnodeStmt;
  1291. }
  1292. ParseStmtList<buildAST>(ppnodeList);
  1293. if (buildAST)
  1294. {
  1295. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  1296. }
  1297. FinishParseBlock(pnodeBlock);
  1298. ChkCurTok(tkRCurly, ERRnoRcurly);
  1299. return pnodeBlock;
  1300. }
  1301. bool Parser::IsSpecialName(IdentPtr pid)
  1302. {
  1303. return pid == wellKnownPropertyPids._this ||
  1304. pid == wellKnownPropertyPids._super ||
  1305. pid == wellKnownPropertyPids._superConstructor ||
  1306. pid == wellKnownPropertyPids._newTarget;
  1307. }
  1308. ParseNodeSpecialName * Parser::ReferenceSpecialName(IdentPtr pid, charcount_t ichMin, charcount_t ichLim, bool createNode)
  1309. {
  1310. PidRefStack* ref = this->PushPidRef(pid);
  1311. if (!createNode)
  1312. {
  1313. return nullptr;
  1314. }
  1315. return CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  1316. }
  1317. ParseNodeVar * Parser::CreateSpecialVarDeclIfNeeded(ParseNodeFnc * pnodeFnc, IdentPtr pid, bool forceCreate)
  1318. {
  1319. Assert(pid != nullptr);
  1320. PidRefStack* ref = pid->GetTopRef();
  1321. // If the function has a reference to pid or we set forceCreate, make a special var decl
  1322. if (forceCreate || (ref && ref->GetScopeId() >= m_currentBlockInfo->pnodeBlock->blockId))
  1323. {
  1324. return this->CreateSpecialVarDeclNode(pnodeFnc, pid);
  1325. }
  1326. return nullptr;
  1327. }
  1328. void Parser::CreateSpecialSymbolDeclarations(ParseNodeFnc * pnodeFnc)
  1329. {
  1330. // Lambda function cannot have any special bindings.
  1331. if (pnodeFnc->IsLambda())
  1332. {
  1333. return;
  1334. }
  1335. bool isTopLevelEventHandler = (this->m_grfscr & fscrImplicitThis) && !pnodeFnc->IsNested();
  1336. // Create a 'this' symbol for non-lambda functions with references to 'this', and all class constructors and top level event hanlders.
  1337. ParseNodePtr varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._this, pnodeFnc->IsClassConstructor() || isTopLevelEventHandler);
  1338. if (varDeclNode)
  1339. {
  1340. varDeclNode->AsParseNodeVar()->sym->SetIsThis(true);
  1341. if (pnodeFnc->IsDerivedClassConstructor())
  1342. {
  1343. varDeclNode->AsParseNodeVar()->sym->SetNeedDeclaration(true);
  1344. }
  1345. }
  1346. // Create a 'new.target' symbol for any ordinary function with a reference and all class constructors.
  1347. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._newTarget, pnodeFnc->IsClassConstructor());
  1348. if (varDeclNode)
  1349. {
  1350. varDeclNode->AsParseNodeVar()->sym->SetIsNewTarget(true);
  1351. }
  1352. // Create a 'super' (as a reference) symbol.
  1353. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._super);
  1354. if (varDeclNode)
  1355. {
  1356. varDeclNode->AsParseNodeVar()->sym->SetIsSuper(true);
  1357. }
  1358. // Create a 'super' (as the call target for super()) symbol only for derived class constructors.
  1359. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._superConstructor);
  1360. if (varDeclNode)
  1361. {
  1362. varDeclNode->AsParseNodeVar()->sym->SetIsSuperConstructor(true);
  1363. }
  1364. }
  1365. void Parser::FinishParseBlock(ParseNodeBlock *pnodeBlock, bool needScanRCurly)
  1366. {
  1367. Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);
  1368. if (needScanRCurly)
  1369. {
  1370. // Only update the ichLim if we were expecting an RCurly. If there is an
  1371. // expression body without a necessary RCurly, the correct ichLim will
  1372. // have been set already.
  1373. pnodeBlock->ichLim = this->GetScanner()->IchLimTok();
  1374. }
  1375. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  1376. PopStmt(&m_currentBlockInfo->pstmt);
  1377. PopBlockInfo();
  1378. Scope *scope = pnodeBlock->scope;
  1379. if (scope)
  1380. {
  1381. PopScope(scope);
  1382. }
  1383. }
  1384. void Parser::FinishParseFncExprScope(ParseNodeFnc * pnodeFnc, ParseNodeBlock * pnodeFncExprScope)
  1385. {
  1386. int fncExprScopeId = pnodeFncExprScope->blockId;
  1387. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  1388. if (pnodeName)
  1389. {
  1390. Assert(pnodeName->nop == knopVarDecl);
  1391. BindPidRefsInScope(pnodeName->AsParseNodeVar()->pid, pnodeName->AsParseNodeVar()->sym, fncExprScopeId, m_nextBlockId - 1);
  1392. }
  1393. FinishParseBlock(pnodeFncExprScope);
  1394. }
  1395. template <const bool backgroundPidRef>
  1396. void Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)
  1397. {
  1398. // We need to bind all assignments in order to emit assignment to 'const' error
  1399. int blockId = blockInfo->pnodeBlock->blockId;
  1400. Scope *scope = blockInfo->pnodeBlock->scope;
  1401. if (scope)
  1402. {
  1403. auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)
  1404. {
  1405. ParseNodePtr pnode = sym->GetDecl();
  1406. IdentPtr pid;
  1407. #if PROFILE_DICTIONARY
  1408. int depth = 0;
  1409. #endif
  1410. Assert(pnode);
  1411. switch (pnode->nop)
  1412. {
  1413. case knopVarDecl:
  1414. case knopLetDecl:
  1415. case knopConstDecl:
  1416. pid = pnode->AsParseNodeVar()->pid;
  1417. if (backgroundPidRef)
  1418. {
  1419. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1420. #if PROFILE_DICTIONARY
  1421. , depth
  1422. #endif
  1423. );
  1424. if (pid == nullptr)
  1425. {
  1426. break;
  1427. }
  1428. }
  1429. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1430. break;
  1431. case knopName:
  1432. pid = pnode->AsParseNodeName()->pid;
  1433. if (backgroundPidRef)
  1434. {
  1435. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1436. #if PROFILE_DICTIONARY
  1437. , depth
  1438. #endif
  1439. );
  1440. if (pid == nullptr)
  1441. {
  1442. break;
  1443. }
  1444. }
  1445. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1446. break;
  1447. default:
  1448. Assert(0);
  1449. break;
  1450. }
  1451. };
  1452. scope->ForEachSymbol(bindPidRefs);
  1453. }
  1454. }
  1455. void Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)
  1456. {
  1457. PidRefStack *ref, *nextRef, *lastRef = nullptr;
  1458. Js::LocalFunctionId funcId = GetCurrentFunctionNode()->functionId;
  1459. Assert(sym);
  1460. if (pid->GetIsModuleExport() && IsTopLevelModuleFunc())
  1461. {
  1462. sym->SetIsModuleExportStorage(true);
  1463. }
  1464. bool hasFuncAssignment = sym->GetHasFuncAssignment();
  1465. bool doesEscape = false;
  1466. for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)
  1467. {
  1468. // Fix up sym* on PID ref.
  1469. Assert(!ref->GetSym() || ref->GetSym() == sym);
  1470. nextRef = ref->prev;
  1471. Assert(ref->GetScopeId() >= 0);
  1472. if ((uint)ref->GetScopeId() > maxBlockId)
  1473. {
  1474. lastRef = ref;
  1475. continue;
  1476. }
  1477. ref->SetSym(sym);
  1478. this->RemovePrevPidRef(pid, lastRef);
  1479. if (ref->IsUsedInLdElem())
  1480. {
  1481. sym->SetIsUsedInLdElem(true);
  1482. }
  1483. if (ref->IsAssignment())
  1484. {
  1485. sym->PromoteAssignmentState();
  1486. if (sym->GetIsFormal())
  1487. {
  1488. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  1489. }
  1490. }
  1491. if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1492. {
  1493. Assert(ref->GetFuncScopeId() > funcId);
  1494. sym->SetHasNonLocalReference();
  1495. if (ref->IsDynamicBinding())
  1496. {
  1497. sym->SetNeedsScopeObject();
  1498. }
  1499. }
  1500. if (ref->IsFuncAssignment())
  1501. {
  1502. hasFuncAssignment = true;
  1503. }
  1504. if (ref->IsEscape())
  1505. {
  1506. doesEscape = true;
  1507. }
  1508. if (m_currentNodeFunc && doesEscape && hasFuncAssignment)
  1509. {
  1510. if (m_sourceContextInfo ?
  1511. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1512. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1513. {
  1514. m_currentNodeFunc->SetNestedFuncEscapes();
  1515. }
  1516. }
  1517. if (ref->GetScopeId() == blockId)
  1518. {
  1519. break;
  1520. }
  1521. }
  1522. }
  1523. void Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)
  1524. {
  1525. if (m_currentNodeFunc == nullptr)
  1526. {
  1527. return;
  1528. }
  1529. if (pnode && pnode->nop == knopFncDecl)
  1530. {
  1531. this->SetNestedFuncEscapes();
  1532. }
  1533. else if (pToken->pid)
  1534. {
  1535. PidRefStack *pidRef = pToken->pid->GetTopRef();
  1536. if (pidRef->sym)
  1537. {
  1538. if (pidRef->sym->GetSymbolType() == STFunction)
  1539. {
  1540. this->SetNestedFuncEscapes();
  1541. }
  1542. }
  1543. else
  1544. {
  1545. pidRef->isEscape = true;
  1546. }
  1547. }
  1548. }
  1549. void Parser::SetNestedFuncEscapes() const
  1550. {
  1551. if (m_sourceContextInfo ?
  1552. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1553. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1554. {
  1555. m_currentNodeFunc->SetNestedFuncEscapes();
  1556. }
  1557. }
  1558. void Parser::PopStmt(StmtNest *pStmt)
  1559. {
  1560. Assert(pStmt == m_pstmtCur);
  1561. SetCurrentStatement(m_pstmtCur->pstmtOuter);
  1562. }
  1563. BlockInfoStack *Parser::PushBlockInfo(ParseNodeBlock * pnodeBlock)
  1564. {
  1565. BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));
  1566. Assert(nullptr != newBlockInfo);
  1567. newBlockInfo->pnodeBlock = pnodeBlock;
  1568. newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;
  1569. newBlockInfo->m_ppnodeLex = &pnodeBlock->pnodeLexVars;
  1570. if (pnodeBlock->blockType != PnodeBlockType::Regular)
  1571. {
  1572. newBlockInfo->pBlockInfoFunction = newBlockInfo;
  1573. }
  1574. else
  1575. {
  1576. Assert(m_currentBlockInfo);
  1577. newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;
  1578. }
  1579. m_currentBlockInfo = newBlockInfo;
  1580. return newBlockInfo;
  1581. }
  1582. void Parser::PopBlockInfo()
  1583. {
  1584. Assert(m_currentBlockInfo);
  1585. PopDynamicBlock();
  1586. m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1587. }
  1588. void Parser::PushDynamicBlock()
  1589. {
  1590. Assert(GetCurrentBlock());
  1591. int blockId = GetCurrentBlock()->blockId;
  1592. if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)
  1593. {
  1594. return;
  1595. }
  1596. BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));
  1597. if (nullptr == info)
  1598. {
  1599. Error(ERRnoMemory);
  1600. }
  1601. info->id = blockId;
  1602. info->prev = m_currentDynamicBlock;
  1603. m_currentDynamicBlock = info;
  1604. }
  1605. void Parser::PopDynamicBlock()
  1606. {
  1607. int blockId = GetCurrentDynamicBlockId();
  1608. if (GetCurrentBlock()->blockId != blockId || blockId == -1)
  1609. {
  1610. return;
  1611. }
  1612. Assert(m_currentDynamicBlock);
  1613. this->GetHashTbl()->VisitPids([&](IdentPtr pid) {
  1614. for (PidRefStack *ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = ref->prev)
  1615. {
  1616. ref->SetDynamicBinding();
  1617. }
  1618. });
  1619. m_currentDynamicBlock = m_currentDynamicBlock->prev;
  1620. }
  1621. int Parser::GetCurrentDynamicBlockId() const
  1622. {
  1623. return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;
  1624. }
  1625. ParseNodeFnc *Parser::GetCurrentFunctionNode()
  1626. {
  1627. if (m_currentNodeDeferredFunc != nullptr)
  1628. {
  1629. return m_currentNodeDeferredFunc;
  1630. }
  1631. else if (m_currentNodeFunc != nullptr)
  1632. {
  1633. return m_currentNodeFunc;
  1634. }
  1635. else
  1636. {
  1637. AssertMsg(GetFunctionBlock()->blockType == PnodeBlockType::Global,
  1638. "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'");
  1639. return m_currentNodeProg;
  1640. }
  1641. }
  1642. ParseNodeFnc *Parser::GetCurrentNonLambdaFunctionNode()
  1643. {
  1644. if (m_currentNodeNonLambdaDeferredFunc != nullptr)
  1645. {
  1646. return m_currentNodeNonLambdaDeferredFunc;
  1647. }
  1648. return m_currentNodeNonLambdaFunc;
  1649. }
  1650. void Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)
  1651. {
  1652. Assert(regexPattern);
  1653. // ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator
  1654. if (!m_registeredRegexPatterns.PrependNoThrow(m_tempGuestArena->GetAllocator(), regexPattern))
  1655. {
  1656. Parser::Error(ERRnoMemory);
  1657. }
  1658. }
  1659. void Parser::CaptureState(ParserState *state)
  1660. {
  1661. Assert(state != nullptr);
  1662. state->m_funcInArraySave = m_funcInArray;
  1663. state->m_funcInArrayDepthSave = m_funcInArrayDepth;
  1664. state->m_nestedCountSave = *m_pnestedCount;
  1665. state->m_ppnodeScopeSave = m_ppnodeScope;
  1666. state->m_ppnodeExprScopeSave = m_ppnodeExprScope;
  1667. state->m_pCurrentAstSizeSave = m_pCurrentAstSize;
  1668. state->m_nextBlockId = m_nextBlockId;
  1669. Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);
  1670. Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);
  1671. #if DEBUG
  1672. state->m_currentBlockInfo = m_currentBlockInfo;
  1673. #endif
  1674. }
  1675. void Parser::RestoreStateFrom(ParserState *state)
  1676. {
  1677. Assert(state != nullptr);
  1678. Assert(state->m_currentBlockInfo == m_currentBlockInfo);
  1679. m_funcInArray = state->m_funcInArraySave;
  1680. m_funcInArrayDepth = state->m_funcInArrayDepthSave;
  1681. *m_pnestedCount = state->m_nestedCountSave;
  1682. m_pCurrentAstSize = state->m_pCurrentAstSizeSave;
  1683. m_nextBlockId = state->m_nextBlockId;
  1684. if (state->m_ppnodeScopeSave != nullptr)
  1685. {
  1686. *state->m_ppnodeScopeSave = nullptr;
  1687. }
  1688. if (state->m_ppnodeExprScopeSave != nullptr)
  1689. {
  1690. *state->m_ppnodeExprScopeSave = nullptr;
  1691. }
  1692. m_ppnodeScope = state->m_ppnodeScopeSave;
  1693. m_ppnodeExprScope = state->m_ppnodeExprScopeSave;
  1694. }
  1695. void Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1696. ParseNode * pnodeAdd)
  1697. {
  1698. AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);
  1699. pnodeAdd->SetIsInList();
  1700. }
  1701. void Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1702. ParseNode * pnodeAdd)
  1703. {
  1704. Assert(!this->m_deferringAST);
  1705. if (nullptr == *pppnodeLast)
  1706. {
  1707. // should be an empty list
  1708. Assert(nullptr == *ppnodeList);
  1709. *ppnodeList = pnodeAdd;
  1710. *pppnodeLast = ppnodeList;
  1711. }
  1712. else
  1713. {
  1714. //
  1715. Assert(*ppnodeList);
  1716. Assert(**pppnodeLast);
  1717. ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);
  1718. **pppnodeLast = pnodeT;
  1719. *pppnodeLast = &pnodeT->AsParseNodeBin()->pnode2;
  1720. }
  1721. }
  1722. // Check reference to "arguments" that indicates the object may escape.
  1723. void Parser::CheckArguments(ParseNodePtr pnode)
  1724. {
  1725. if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))
  1726. {
  1727. m_currentNodeFunc->SetHasHeapArguments();
  1728. }
  1729. }
  1730. // Check use of "arguments" that requires instantiation of the object.
  1731. void Parser::CheckArgumentsUse(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1732. {
  1733. if (pid == wellKnownPropertyPids.arguments)
  1734. {
  1735. if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)
  1736. {
  1737. pnodeFnc->SetUsesArguments(TRUE);
  1738. }
  1739. else
  1740. {
  1741. m_UsesArgumentsAtGlobal = true;
  1742. }
  1743. }
  1744. }
  1745. void Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)
  1746. {
  1747. if (pid != nullptr)
  1748. {
  1749. // In strict mode, 'eval' / 'arguments' cannot be assigned to.
  1750. if (pid == wellKnownPropertyPids.eval)
  1751. {
  1752. Error(ERREvalUsage, pnode);
  1753. }
  1754. if (pid == wellKnownPropertyPids.arguments)
  1755. {
  1756. Error(ERRArgsUsage, pnode);
  1757. }
  1758. }
  1759. }
  1760. void Parser::ReduceDeferredScriptLength(size_t chars)
  1761. {
  1762. // If we're in deferred mode, subtract the given char count from the total length,
  1763. // and see if this puts us under the deferral threshold.
  1764. if (((m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse)) == (fscrCanDeferFncParse | fscrWillDeferFncParse)) &&
  1765. (
  1766. PHASE_OFF1(Js::DeferEventHandlersPhase) ||
  1767. (m_grfscr & fscrGlobalCode)
  1768. )
  1769. )
  1770. {
  1771. if (m_length > chars)
  1772. {
  1773. m_length -= chars;
  1774. }
  1775. else
  1776. {
  1777. m_length = 0;
  1778. }
  1779. if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))
  1780. {
  1781. // Stop deferring.
  1782. m_grfscr &= ~fscrWillDeferFncParse;
  1783. m_stoppedDeferredParse = TRUE;
  1784. }
  1785. }
  1786. }
  1787. void Parser::EnsureStackAvailable()
  1788. {
  1789. bool isInterrupt = false;
  1790. if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile, &isInterrupt))
  1791. {
  1792. Error(isInterrupt ? E_ABORT : VBSERR_OutOfStack);
  1793. }
  1794. }
  1795. void Parser::ThrowNewTargetSyntaxErrForGlobalScope()
  1796. {
  1797. // If we are parsing a previously deferred function, we can skip throwing the SyntaxError for `new.target` at global scope.
  1798. // If we are at global scope, we would have thrown a SyntaxError when we did the Upfront parse pass and we would not have
  1799. // deferred the function in order to come back now and reparse it.
  1800. if (m_parseType == ParseType_Deferred)
  1801. {
  1802. return;
  1803. }
  1804. if (GetCurrentNonLambdaFunctionNode() != nullptr)
  1805. {
  1806. return;
  1807. }
  1808. if ((this->m_grfscr & fscrEval) != 0)
  1809. {
  1810. Js::JavascriptFunction * caller = nullptr;
  1811. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  1812. {
  1813. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  1814. Assert(callerBody);
  1815. if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))
  1816. {
  1817. return;
  1818. }
  1819. }
  1820. }
  1821. Error(ERRInvalidNewTarget);
  1822. }
  1823. template<bool buildAST>
  1824. IdentPtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)
  1825. {
  1826. AssertMsg(metaParentKeyword == tkNEW, "Only supported for tkNEW parent keywords");
  1827. AssertMsg(this->m_token.tk == tkDot, "We must be currently sitting on the dot after the parent keyword");
  1828. this->GetScanner()->Scan();
  1829. if (this->m_token.tk == tkID && this->m_token.GetIdentifier(this->GetHashTbl()) == this->GetTargetPid())
  1830. {
  1831. ThrowNewTargetSyntaxErrForGlobalScope();
  1832. if (pfCanAssign)
  1833. {
  1834. *pfCanAssign = FALSE;
  1835. }
  1836. return wellKnownPropertyPids._newTarget;
  1837. }
  1838. else
  1839. {
  1840. Error(ERRsyntax);
  1841. }
  1842. }
  1843. template<bool buildAST>
  1844. void Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)
  1845. {
  1846. Assert(m_token.tk == tkLCurly);
  1847. Assert(importOrExportEntryList != nullptr);
  1848. this->GetScanner()->Scan();
  1849. while (m_token.tk != tkRCurly && m_token.tk != tkEOF)
  1850. {
  1851. tokens firstToken = m_token.tk;
  1852. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1853. {
  1854. Error(ERRsyntax);
  1855. }
  1856. IdentPtr identifierName = m_token.GetIdentifier(this->GetHashTbl());
  1857. IdentPtr identifierAs = identifierName;
  1858. this->GetScanner()->Scan();
  1859. if (m_token.tk == tkID)
  1860. {
  1861. // We have the pattern "IdentifierName as"
  1862. if (wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  1863. {
  1864. Error(ERRsyntax);
  1865. }
  1866. this->GetScanner()->Scan();
  1867. // If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.
  1868. if (!isExportClause)
  1869. {
  1870. ChkCurTokNoScan(tkID, ERRsyntax);
  1871. }
  1872. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1873. {
  1874. Error(ERRsyntax);
  1875. }
  1876. identifierAs = m_token.GetIdentifier(this->GetHashTbl());
  1877. // Scan to the next token.
  1878. this->GetScanner()->Scan();
  1879. }
  1880. else if (!isExportClause && firstToken != tkID)
  1881. {
  1882. // If we are parsing an import statement and this ImportSpecifier clause did not have
  1883. // 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.
  1884. Error(ERRsyntax);
  1885. }
  1886. if (m_token.tk == tkComma)
  1887. {
  1888. // Consume a trailing comma
  1889. this->GetScanner()->Scan();
  1890. }
  1891. if (buildAST)
  1892. {
  1893. // The name we will use 'as' this import/export is a binding identifier in import statements.
  1894. if (!isExportClause)
  1895. {
  1896. CreateModuleImportDeclNode(identifierAs);
  1897. AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);
  1898. }
  1899. else
  1900. {
  1901. identifierName->SetIsModuleExport();
  1902. AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr);
  1903. }
  1904. }
  1905. }
  1906. // Final token in a named import or export clause must be a '}'
  1907. ChkCurTokNoScan(tkRCurly, ERRsyntax);
  1908. }
  1909. IdentPtrList* Parser::GetRequestedModulesList()
  1910. {
  1911. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1912. }
  1913. ModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()
  1914. {
  1915. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  1916. }
  1917. ModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()
  1918. {
  1919. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  1920. }
  1921. ModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()
  1922. {
  1923. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  1924. }
  1925. ModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()
  1926. {
  1927. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  1928. }
  1929. IdentPtrList* Parser::EnsureRequestedModulesList()
  1930. {
  1931. if (m_currentNodeProg->AsParseNodeModule()->requestedModules == nullptr)
  1932. {
  1933. m_currentNodeProg->AsParseNodeModule()->requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);
  1934. }
  1935. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1936. }
  1937. ModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()
  1938. {
  1939. if (m_currentNodeProg->AsParseNodeModule()->importEntries == nullptr)
  1940. {
  1941. m_currentNodeProg->AsParseNodeModule()->importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1942. }
  1943. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  1944. }
  1945. ModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()
  1946. {
  1947. if (m_currentNodeProg->AsParseNodeModule()->localExportEntries == nullptr)
  1948. {
  1949. m_currentNodeProg->AsParseNodeModule()->localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1950. }
  1951. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  1952. }
  1953. ModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()
  1954. {
  1955. if (m_currentNodeProg->AsParseNodeModule()->indirectExportEntries == nullptr)
  1956. {
  1957. m_currentNodeProg->AsParseNodeModule()->indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1958. }
  1959. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  1960. }
  1961. ModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()
  1962. {
  1963. if (m_currentNodeProg->AsParseNodeModule()->starExportEntries == nullptr)
  1964. {
  1965. m_currentNodeProg->AsParseNodeModule()->starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1966. }
  1967. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  1968. }
  1969. void Parser::AddModuleSpecifier(IdentPtr moduleRequest)
  1970. {
  1971. IdentPtrList* requestedModulesList = EnsureRequestedModulesList();
  1972. if (!requestedModulesList->Has(moduleRequest))
  1973. {
  1974. requestedModulesList->Prepend(moduleRequest);
  1975. }
  1976. }
  1977. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)
  1978. {
  1979. if (importOrExportEntry->exportName != nullptr)
  1980. {
  1981. CheckForDuplicateExportEntry(importOrExportEntryList, importOrExportEntry->exportName);
  1982. }
  1983. importOrExportEntryList->Prepend(*importOrExportEntry);
  1984. return importOrExportEntry;
  1985. }
  1986. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest)
  1987. {
  1988. ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);
  1989. importOrExportEntry->importName = importName;
  1990. importOrExportEntry->localName = localName;
  1991. importOrExportEntry->exportName = exportName;
  1992. importOrExportEntry->moduleRequest = moduleRequest;
  1993. return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);
  1994. }
  1995. void Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)
  1996. {
  1997. AssertOrFailFast(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);
  1998. IdentPtr localName = varDeclNode->AsParseNodeVar()->pid;
  1999. varDeclNode->AsParseNodeVar()->sym->SetIsModuleExportStorage(true);
  2000. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2001. }
  2002. void Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)
  2003. {
  2004. ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)
  2005. {
  2006. if (exportName == exportEntry.exportName)
  2007. {
  2008. return true;
  2009. }
  2010. return false;
  2011. });
  2012. if (findResult != nullptr)
  2013. {
  2014. Error(ERRsyntax);
  2015. }
  2016. }
  2017. template<bool buildAST>
  2018. void Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)
  2019. {
  2020. bool parsedNamespaceOrNamedImport = false;
  2021. switch (m_token.tk)
  2022. {
  2023. case tkID:
  2024. // This is the default binding identifier.
  2025. // If we already saw a comma in the import clause, this is a syntax error.
  2026. if (parsingAfterComma)
  2027. {
  2028. Error(ERRsyntax);
  2029. }
  2030. if (buildAST)
  2031. {
  2032. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2033. IdentPtr importName = wellKnownPropertyPids._default;
  2034. CreateModuleImportDeclNode(localName);
  2035. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2036. }
  2037. break;
  2038. case tkLCurly:
  2039. // This begins a list of named imports.
  2040. ParseNamedImportOrExportClause<buildAST>(importEntryList, false);
  2041. parsedNamespaceOrNamedImport = true;
  2042. break;
  2043. case tkStar:
  2044. // This begins a namespace import clause.
  2045. // "* as ImportedBinding"
  2046. // Token following * must be the identifier 'as'
  2047. this->GetScanner()->Scan();
  2048. if (m_token.tk != tkID || wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  2049. {
  2050. Error(ERRsyntax);
  2051. }
  2052. // Token following 'as' must be a binding identifier.
  2053. this->GetScanner()->Scan();
  2054. ChkCurTokNoScan(tkID, ERRsyntax);
  2055. if (buildAST)
  2056. {
  2057. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2058. IdentPtr importName = wellKnownPropertyPids._star;
  2059. CreateModuleImportDeclNode(localName);
  2060. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2061. }
  2062. parsedNamespaceOrNamedImport = true;
  2063. break;
  2064. default:
  2065. Error(ERRsyntax);
  2066. }
  2067. this->GetScanner()->Scan();
  2068. if (m_token.tk == tkComma)
  2069. {
  2070. // There cannot be more than one comma in a module import clause.
  2071. // There cannot be a namespace import or named imports list on the left of the comma in a module import clause.
  2072. if (parsingAfterComma || parsedNamespaceOrNamedImport)
  2073. {
  2074. Error(ERRsyntax);
  2075. }
  2076. this->GetScanner()->Scan();
  2077. ParseImportClause<buildAST>(importEntryList, true);
  2078. }
  2079. }
  2080. bool Parser::IsImportOrExportStatementValidHere()
  2081. {
  2082. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2083. // Import must be located in the top scope of the module body.
  2084. return curFunc->nop == knopFncDecl
  2085. && curFunc->IsModule()
  2086. && this->m_currentBlockInfo->pnodeBlock == curFunc->pnodeBodyScope
  2087. && (this->m_grfscr & fscrEvalCode) != fscrEvalCode
  2088. && this->m_tryCatchOrFinallyDepth == 0
  2089. && !this->m_disallowImportExportStmt;
  2090. }
  2091. bool Parser::IsTopLevelModuleFunc()
  2092. {
  2093. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2094. return curFunc->nop == knopFncDecl && curFunc->IsModule();
  2095. }
  2096. template<bool buildAST> ParseNodePtr Parser::ParseImportCall()
  2097. {
  2098. this->GetScanner()->Scan();
  2099. ParseNodePtr specifier = ParseExpr<buildAST>(koplCma, nullptr, /* fAllowIn */FALSE, /* fAllowEllipsis */FALSE);
  2100. if (m_token.tk != tkRParen)
  2101. {
  2102. Error(ERRnoRparen);
  2103. }
  2104. this->GetScanner()->Scan();
  2105. return buildAST ? CreateCallNode(knopCall, CreateNodeForOpT<knopImport>(), specifier) : nullptr;
  2106. }
  2107. template<bool buildAST>
  2108. ParseNodePtr Parser::ParseImport()
  2109. {
  2110. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2111. Assert(m_token.tk == tkIMPORT);
  2112. RestorePoint parsedImport;
  2113. this->GetScanner()->Capture(&parsedImport);
  2114. this->GetScanner()->Scan();
  2115. // import()
  2116. if (m_token.tk == tkLParen)
  2117. {
  2118. if (!m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2119. {
  2120. Error(ERRsyntax);
  2121. }
  2122. ParseNodePtr pnode = ParseImportCall<buildAST>();
  2123. BOOL fCanAssign;
  2124. IdentToken token;
  2125. return ParsePostfixOperators<buildAST>(pnode, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  2126. }
  2127. this->GetScanner()->SeekTo(parsedImport);
  2128. if (!IsImportOrExportStatementValidHere())
  2129. {
  2130. Error(ERRInvalidModuleImportOrExport);
  2131. }
  2132. // We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.
  2133. this->GetScanner()->Scan();
  2134. if (m_token.tk == tkStrCon)
  2135. {
  2136. // This import declaration has no import clause.
  2137. // "import ModuleSpecifier;"
  2138. if (buildAST)
  2139. {
  2140. AddModuleSpecifier(m_token.GetStr());
  2141. }
  2142. // Scan past the module identifier.
  2143. this->GetScanner()->Scan();
  2144. }
  2145. else
  2146. {
  2147. ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);
  2148. // Parse the import clause (default binding can only exist before the comma).
  2149. ParseImportClause<buildAST>(&importEntryList);
  2150. // Token following import clause must be the identifier 'from'
  2151. IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);
  2152. if (buildAST)
  2153. {
  2154. Assert(moduleSpecifier != nullptr);
  2155. AddModuleSpecifier(moduleSpecifier);
  2156. importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {
  2157. importEntry.moduleRequest = moduleSpecifier;
  2158. AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);
  2159. });
  2160. }
  2161. importEntryList.Clear();
  2162. }
  2163. // Import statement is actually a nop, we hoist all the imported bindings to the top of the module.
  2164. return nullptr;
  2165. }
  2166. template<bool buildAST>
  2167. IdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)
  2168. {
  2169. IdentPtr moduleSpecifier = nullptr;
  2170. if (m_token.tk == tkID && wellKnownPropertyPids.from == m_token.GetIdentifier(this->GetHashTbl()))
  2171. {
  2172. this->GetScanner()->Scan();
  2173. // Token following the 'from' token must be a string constant - the module specifier.
  2174. ChkCurTokNoScan(tkStrCon, ERRsyntax);
  2175. if (buildAST)
  2176. {
  2177. moduleSpecifier = m_token.GetStr();
  2178. }
  2179. this->GetScanner()->Scan();
  2180. }
  2181. else if (throwIfNotFound)
  2182. {
  2183. Error(ERRsyntax);
  2184. }
  2185. return moduleSpecifier;
  2186. }
  2187. template<bool buildAST>
  2188. ParseNodePtr Parser::ParseDefaultExportClause()
  2189. {
  2190. Assert(m_token.tk == tkDEFAULT);
  2191. this->GetScanner()->Scan();
  2192. ParseNodePtr pnode = nullptr;
  2193. ushort flags = fFncNoFlgs;
  2194. switch (m_token.tk)
  2195. {
  2196. case tkCLASS:
  2197. {
  2198. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2199. {
  2200. goto LDefault;
  2201. }
  2202. // Before we parse the class itself we need to know if the class has an identifier name.
  2203. // If it does, we'll treat this class as an ordinary class declaration which will bind
  2204. // it to that name. Otherwise the class should parse as a nameless class expression and
  2205. // bind only to the export binding.
  2206. BOOL classHasName = false;
  2207. RestorePoint parsedClass;
  2208. this->GetScanner()->Capture(&parsedClass);
  2209. this->GetScanner()->Scan();
  2210. if (m_token.tk == tkID)
  2211. {
  2212. classHasName = true;
  2213. }
  2214. this->GetScanner()->SeekTo(parsedClass);
  2215. ParseNodeClass * pnodeClass;
  2216. pnode = pnodeClass = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);
  2217. if (buildAST)
  2218. {
  2219. AnalysisAssert(pnode != nullptr);
  2220. Assert(pnode->nop == knopClassDecl);
  2221. pnodeClass->SetIsDefaultModuleExport(true);
  2222. }
  2223. break;
  2224. }
  2225. case tkID:
  2226. // If we parsed an async token, it could either modify the next token (if it is a
  2227. // function token) or it could be an identifier (let async = 0; export default async;).
  2228. // To handle both cases, when we parse an async token we need to keep the parser state
  2229. // and rewind if the next token is not function.
  2230. if (wellKnownPropertyPids.async == m_token.GetIdentifier(this->GetHashTbl()))
  2231. {
  2232. RestorePoint parsedAsync;
  2233. this->GetScanner()->Capture(&parsedAsync);
  2234. this->GetScanner()->Scan();
  2235. if (m_token.tk == tkFUNCTION)
  2236. {
  2237. // Token after async is function, consume the async token and continue to parse the
  2238. // function as an async function.
  2239. flags |= fFncAsync;
  2240. goto LFunction;
  2241. }
  2242. // Token after async is not function, no idea what the async token is supposed to mean
  2243. // so rewind and let the default case handle it.
  2244. this->GetScanner()->SeekTo(parsedAsync);
  2245. }
  2246. goto LDefault;
  2247. break;
  2248. case tkFUNCTION:
  2249. {
  2250. LFunction:
  2251. // We just parsed a function token but we need to figure out if the function
  2252. // has an identifier name or not before we call the helper.
  2253. RestorePoint parsedFunction;
  2254. this->GetScanner()->Capture(&parsedFunction);
  2255. this->GetScanner()->Scan();
  2256. if (m_token.tk == tkStar)
  2257. {
  2258. // If we saw 'function*' that indicates we are going to parse a generator,
  2259. // but doesn't tell us if the generator has an identifier or not.
  2260. // Skip the '*' token for now as it doesn't matter yet.
  2261. this->GetScanner()->Scan();
  2262. }
  2263. // We say that if the function has an identifier name, it is a 'normal' declaration
  2264. // and should create a binding to that identifier as well as one for our default export.
  2265. if (m_token.tk == tkID)
  2266. {
  2267. flags |= fFncDeclaration;
  2268. }
  2269. else
  2270. {
  2271. flags |= fFncNoName;
  2272. }
  2273. // Rewind back to the function token and let the helper handle the parsing.
  2274. this->GetScanner()->SeekTo(parsedFunction);
  2275. pnode = ParseFncDeclCheckScope<buildAST>(flags);
  2276. if (buildAST)
  2277. {
  2278. AnalysisAssert(pnode != nullptr);
  2279. Assert(pnode->nop == knopFncDecl);
  2280. pnode->AsParseNodeFnc()->SetIsDefaultModuleExport(true);
  2281. }
  2282. break;
  2283. }
  2284. default:
  2285. LDefault:
  2286. {
  2287. ParseNodePtr pnodeExpression = ParseExpr<buildAST>();
  2288. // Consider: Can we detect this syntax error earlier?
  2289. if (pnodeExpression && pnodeExpression->nop == knopComma)
  2290. {
  2291. Error(ERRsyntax);
  2292. }
  2293. if (buildAST)
  2294. {
  2295. AnalysisAssert(pnodeExpression != nullptr);
  2296. // Mark this node as the default module export. We need to make sure it is put into the correct
  2297. // module export slot when we emit the node.
  2298. ParseNodeExportDefault * pnodeExportDefault;
  2299. pnode = pnodeExportDefault = CreateNodeForOpT<knopExportDefault>();
  2300. pnode->AsParseNodeExportDefault()->pnodeExpr = pnodeExpression;
  2301. }
  2302. break;
  2303. }
  2304. }
  2305. IdentPtr exportName = wellKnownPropertyPids._default;
  2306. IdentPtr localName = wellKnownPropertyPids._starDefaultStar;
  2307. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, exportName, nullptr);
  2308. return pnode;
  2309. }
  2310. template<bool buildAST>
  2311. ParseNodePtr Parser::ParseExportDeclaration(bool *needTerminator)
  2312. {
  2313. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2314. Assert(m_token.tk == tkEXPORT);
  2315. if (!IsImportOrExportStatementValidHere())
  2316. {
  2317. Error(ERRInvalidModuleImportOrExport);
  2318. }
  2319. ParseNodePtr pnode = nullptr;
  2320. IdentPtr moduleIdentifier = nullptr;
  2321. tokens declarationType;
  2322. if (needTerminator != nullptr)
  2323. {
  2324. *needTerminator = false;
  2325. }
  2326. // We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.
  2327. this->GetScanner()->Scan();
  2328. switch (m_token.tk)
  2329. {
  2330. case tkStar:
  2331. this->GetScanner()->Scan();
  2332. // A star token in an export declaration must be followed by a from clause which begins with a token 'from'.
  2333. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);
  2334. if (buildAST)
  2335. {
  2336. Assert(moduleIdentifier != nullptr);
  2337. AddModuleSpecifier(moduleIdentifier);
  2338. IdentPtr importName = wellKnownPropertyPids._star;
  2339. AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), importName, nullptr, nullptr, moduleIdentifier);
  2340. }
  2341. if (needTerminator != nullptr)
  2342. {
  2343. *needTerminator = true;
  2344. }
  2345. break;
  2346. case tkLCurly:
  2347. {
  2348. ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);
  2349. ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);
  2350. this->GetScanner()->Scan();
  2351. // Export clause may be followed by a from clause.
  2352. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);
  2353. if (buildAST)
  2354. {
  2355. if (moduleIdentifier != nullptr)
  2356. {
  2357. AddModuleSpecifier(moduleIdentifier);
  2358. }
  2359. exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {
  2360. if (moduleIdentifier != nullptr)
  2361. {
  2362. exportEntry.moduleRequest = moduleIdentifier;
  2363. // We need to swap localname and importname when this is a re-export.
  2364. exportEntry.importName = exportEntry.localName;
  2365. exportEntry.localName = nullptr;
  2366. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);
  2367. }
  2368. else
  2369. {
  2370. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);
  2371. }
  2372. });
  2373. exportEntryList.Clear();
  2374. }
  2375. }
  2376. if (needTerminator != nullptr)
  2377. {
  2378. *needTerminator = true;
  2379. }
  2380. break;
  2381. case tkID:
  2382. {
  2383. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  2384. if (wellKnownPropertyPids.let == pid)
  2385. {
  2386. declarationType = tkLET;
  2387. goto ParseVarDecl;
  2388. }
  2389. if (wellKnownPropertyPids.async == pid && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2390. {
  2391. // In module export statements, async token is only valid if it's followed by function.
  2392. // We need to check here because ParseStatement would think 'async = 20' is a var decl.
  2393. RestorePoint parsedAsync;
  2394. this->GetScanner()->Capture(&parsedAsync);
  2395. this->GetScanner()->Scan();
  2396. if (m_token.tk == tkFUNCTION)
  2397. {
  2398. // Token after async is function, rewind to the async token and let ParseStatement handle it.
  2399. this->GetScanner()->SeekTo(parsedAsync);
  2400. goto ParseFunctionDecl;
  2401. }
  2402. // Token after async is not function, it's a syntax error.
  2403. }
  2404. goto ErrorToken;
  2405. }
  2406. case tkVAR:
  2407. case tkLET:
  2408. case tkCONST:
  2409. {
  2410. declarationType = m_token.tk;
  2411. ParseVarDecl:
  2412. this->GetScanner()->Scan();
  2413. pnode = ParseVariableDeclaration<buildAST>(declarationType, this->GetScanner()->IchMinTok());
  2414. if (buildAST)
  2415. {
  2416. ForEachItemInList(pnode, [&](ParseNodePtr item) {
  2417. if (item->nop == knopAsg)
  2418. {
  2419. Parser::MapBindIdentifier(item, [&](ParseNodePtr subItem)
  2420. {
  2421. AddModuleLocalExportEntry(subItem);
  2422. });
  2423. }
  2424. else
  2425. {
  2426. AddModuleLocalExportEntry(item);
  2427. }
  2428. });
  2429. }
  2430. }
  2431. break;
  2432. case tkFUNCTION:
  2433. case tkCLASS:
  2434. {
  2435. ParseFunctionDecl:
  2436. pnode = ParseStatement<buildAST>();
  2437. if (buildAST)
  2438. {
  2439. IdentPtr localName;
  2440. if (pnode->nop == knopClassDecl)
  2441. {
  2442. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  2443. pnodeClass->pnodeDeclName->sym->SetIsModuleExportStorage(true);
  2444. localName = pnodeClass->pnodeName->pid;
  2445. }
  2446. else
  2447. {
  2448. Assert(pnode->nop == knopFncDecl);
  2449. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  2450. pnodeFnc->GetFuncSymbol()->SetIsModuleExportStorage(true);
  2451. localName = pnodeFnc->pid;
  2452. }
  2453. Assert(localName != nullptr);
  2454. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2455. }
  2456. }
  2457. break;
  2458. case tkDEFAULT:
  2459. {
  2460. pnode = ParseDefaultExportClause<buildAST>();
  2461. }
  2462. break;
  2463. default:
  2464. {
  2465. ErrorToken:
  2466. Error(ERRsyntax);
  2467. }
  2468. }
  2469. return pnode;
  2470. }
  2471. /***************************************************************************
  2472. Parse an expression term.
  2473. ***************************************************************************/
  2474. template<bool buildAST>
  2475. ParseNodePtr Parser::ParseTerm(BOOL fAllowCall,
  2476. LPCOLESTR pNameHint,
  2477. uint32 *pHintLength,
  2478. uint32 *pShortNameOffset,
  2479. _Inout_opt_ IdentToken* pToken /*= nullptr*/,
  2480. bool fUnaryOrParen /*= false*/,
  2481. BOOL fCanAssignToCall /*= TRUE*/,
  2482. _Out_opt_ BOOL* pfCanAssign /*= nullptr*/,
  2483. _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/,
  2484. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/,
  2485. _Inout_opt_ charcount_t *plastRParen /*= nullptr*/)
  2486. {
  2487. ParseNodePtr pnode = nullptr;
  2488. PidRefStack *savedTopAsyncRef = nullptr;
  2489. charcount_t ichMin = 0;
  2490. charcount_t ichLim = 0;
  2491. size_t iecpMin = 0;
  2492. size_t iecpLim = 0;
  2493. size_t iuMin;
  2494. IdentToken term;
  2495. BOOL fInNew = FALSE;
  2496. BOOL fCanAssign = TRUE;
  2497. bool isAsyncExpr = false;
  2498. bool isLambdaExpr = false;
  2499. bool isSpecialName = false;
  2500. IdentPtr pid = nullptr;
  2501. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  2502. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);
  2503. switch (m_token.tk)
  2504. {
  2505. case tkID:
  2506. {
  2507. pid = m_token.GetIdentifier(this->GetHashTbl());
  2508. ichMin = this->GetScanner()->IchMinTok();
  2509. iecpMin = this->GetScanner()->IecpMinTok();
  2510. ichLim = this->GetScanner()->IchLimTok();
  2511. iecpLim = this->GetScanner()->IecpLimTok();
  2512. if (pid == wellKnownPropertyPids.async &&
  2513. m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2514. {
  2515. isAsyncExpr = true;
  2516. }
  2517. // Put this into a block to avoid previousAwaitIsKeyword being not initialized after jump to LIdentifier
  2518. {
  2519. bool previousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(isAsyncExpr);
  2520. this->GetScanner()->Scan();
  2521. this->GetScanner()->SetAwaitIsKeywordRegion(previousAwaitIsKeyword);
  2522. }
  2523. // We search for an Async expression (a function declaration or an async lambda expression)
  2524. if (isAsyncExpr && !this->GetScanner()->FHadNewLine())
  2525. {
  2526. if (m_token.tk == tkFUNCTION)
  2527. {
  2528. goto LFunction;
  2529. }
  2530. else if (m_token.tk == tkID || m_token.tk == tkAWAIT)
  2531. {
  2532. isLambdaExpr = true;
  2533. goto LFunction;
  2534. }
  2535. else if (m_token.tk == tkLParen)
  2536. {
  2537. // This is potentially an async arrow function. Save the state of the async references
  2538. // in case it needs to be restored. (Note that the case of a single parameter with no ()'s
  2539. // is detected upstream and need not be handled here.)
  2540. savedTopAsyncRef = pid->GetTopRef();
  2541. }
  2542. }
  2543. CheckArgumentsUse(pid, GetCurrentFunctionNode());
  2544. // Assume this pid is not special - overwrite when we parse a special name
  2545. isSpecialName = false;
  2546. LIdentifier:
  2547. PidRefStack * ref = nullptr;
  2548. // Don't push a reference if this is a single lambda parameter, because we'll reparse with
  2549. // a correct function ID.
  2550. if (m_token.tk != tkDArrow)
  2551. {
  2552. ref = this->PushPidRef(pid);
  2553. }
  2554. if (buildAST)
  2555. {
  2556. if (isSpecialName)
  2557. {
  2558. pnode = CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  2559. }
  2560. else
  2561. {
  2562. pnode = CreateNameNode(pid, ref, ichMin, ichLim);
  2563. }
  2564. }
  2565. else
  2566. {
  2567. // Remember the identifier start and end in case it turns out to be a statement label.
  2568. term.tk = tkID;
  2569. term.pid = pid; // Record the identifier for detection of eval
  2570. term.ichMin = static_cast<charcount_t>(iecpMin);
  2571. term.ichLim = static_cast<charcount_t>(iecpLim);
  2572. }
  2573. break;
  2574. }
  2575. case tkSUPER:
  2576. ichMin = this->GetScanner()->IchMinTok();
  2577. iecpMin = this->GetScanner()->IecpMinTok();
  2578. ichLim = this->GetScanner()->IchLimTok();
  2579. iecpLim = this->GetScanner()->IecpLimTok();
  2580. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2581. {
  2582. goto LUnknown;
  2583. }
  2584. this->GetScanner()->Scan();
  2585. pid = ParseSuper<buildAST>(!!fAllowCall);
  2586. isSpecialName = true;
  2587. // Super reference and super call need to push a pid ref to 'this' even when not building an AST
  2588. ReferenceSpecialName(wellKnownPropertyPids._this, ichMin, ichLim);
  2589. // Super call needs to reference 'new.target'
  2590. if (pid == wellKnownPropertyPids._superConstructor)
  2591. {
  2592. ReferenceSpecialName(wellKnownPropertyPids._newTarget, ichMin, ichLim);
  2593. }
  2594. goto LIdentifier;
  2595. case tkTHIS:
  2596. ichMin = this->GetScanner()->IchMinTok();
  2597. iecpMin = this->GetScanner()->IecpMinTok();
  2598. ichLim = this->GetScanner()->IchLimTok();
  2599. iecpLim = this->GetScanner()->IecpLimTok();
  2600. pid = wellKnownPropertyPids._this;
  2601. this->GetScanner()->Scan();
  2602. isSpecialName = true;
  2603. goto LIdentifier;
  2604. case tkLParen:
  2605. {
  2606. ichMin = this->GetScanner()->IchMinTok();
  2607. iuMin = this->GetScanner()->IecpMinTok();
  2608. // If we are undeferring a function which has deferred stubs, we can check to see if the next deferred stub
  2609. // is a lambda at the current character. If it is, we know this LParen is the beginning of a lambda nested
  2610. // function and we can avoid parsing the next series of tokens as a parenthetical expression and reparsing
  2611. // after finding the => token.
  2612. if (buildAST && m_currDeferredStub != nullptr && GetCurrentFunctionNode() != nullptr && GetCurrentFunctionNode()->nestedCount < m_currDeferredStubCount)
  2613. {
  2614. DeferredFunctionStub* stub = m_currDeferredStub + GetCurrentFunctionNode()->nestedCount;
  2615. if (stub->ichMin == ichMin)
  2616. {
  2617. Assert((stub->fncFlags & kFunctionIsLambda) == kFunctionIsLambda);
  2618. pnode = ParseFncDeclCheckScope<true>(fFncLambda, /* resetParsingSuperRestrictionState*/ false);
  2619. break;
  2620. }
  2621. }
  2622. this->GetScanner()->Scan();
  2623. if (m_token.tk == tkRParen)
  2624. {
  2625. // Empty parens can only be legal as an empty parameter list to a lambda declaration.
  2626. // We're in a lambda if the next token is =>.
  2627. fAllowCall = FALSE;
  2628. this->GetScanner()->Scan();
  2629. // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error
  2630. if (!IsDoingFastScan() && (m_token.tk != tkDArrow || this->GetScanner()->FHadNewLine()))
  2631. {
  2632. Error(ERRsyntax);
  2633. }
  2634. if (buildAST)
  2635. {
  2636. pnode = CreateNodeForOpT<knopEmpty>();
  2637. }
  2638. break;
  2639. }
  2640. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  2641. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  2642. // up function ID's.
  2643. uint saveNextBlockId = m_nextBlockId;
  2644. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  2645. GetCurrentBlock()->blockId = m_nextBlockId++;
  2646. // Push the deferred error state for ellipsis errors. It is possible that another syntax error will occur before we undefer this one.
  2647. bool deferEllipsisErrorSave = m_deferEllipsisError;
  2648. RestorePoint ellipsisErrorLocSave = m_deferEllipsisErrorLoc;
  2649. this->m_funcParenExprDepth++;
  2650. pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen);
  2651. this->m_funcParenExprDepth--;
  2652. if (buildAST && plastRParen)
  2653. {
  2654. *plastRParen = this->GetScanner()->IchLimTok();
  2655. }
  2656. ChkCurTok(tkRParen, ERRnoRparen);
  2657. GetCurrentBlock()->blockId = saveCurrBlockId;
  2658. if (m_token.tk == tkDArrow)
  2659. {
  2660. // We're going to rewind and reinterpret the expression as a parameter list.
  2661. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  2662. m_nextBlockId = saveNextBlockId;
  2663. }
  2664. // Emit a deferred ... error if one was parsed.
  2665. if (m_deferEllipsisError && m_token.tk != tkDArrow)
  2666. {
  2667. this->GetScanner()->SeekTo(m_deferEllipsisErrorLoc);
  2668. Error(ERRInvalidSpreadUse);
  2669. }
  2670. else
  2671. {
  2672. m_deferEllipsisError = false;
  2673. }
  2674. // We didn't error out, so restore the deferred error state.
  2675. m_deferEllipsisError = deferEllipsisErrorSave;
  2676. m_deferEllipsisErrorLoc = ellipsisErrorLocSave;
  2677. break;
  2678. }
  2679. case tkIntCon:
  2680. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2681. {
  2682. Error(ERRES5NoOctal);
  2683. }
  2684. if (buildAST)
  2685. {
  2686. pnode = CreateIntNode(m_token.GetLong());
  2687. }
  2688. fCanAssign = FALSE;
  2689. this->GetScanner()->Scan();
  2690. break;
  2691. case tkFltCon:
  2692. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2693. {
  2694. Error(ERRES5NoOctal);
  2695. }
  2696. if (buildAST)
  2697. {
  2698. ParseNodeFloat * pnodeFloat;
  2699. pnode = pnodeFloat = CreateNodeForOpT<knopFlt>();
  2700. pnodeFloat->dbl = m_token.GetDouble();
  2701. pnodeFloat->maybeInt = m_token.GetDoubleMayBeInt();
  2702. }
  2703. fCanAssign = FALSE;
  2704. this->GetScanner()->Scan();
  2705. break;
  2706. case tkStrCon:
  2707. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2708. {
  2709. Error(ERRES5NoOctal);
  2710. }
  2711. if (buildAST)
  2712. {
  2713. pnode = CreateStrNode(m_token.GetStr());
  2714. }
  2715. else
  2716. {
  2717. // Subtract the string literal length from the total char count for the purpose
  2718. // of deciding whether to defer parsing and byte code generation.
  2719. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok());
  2720. }
  2721. fCanAssign = FALSE;
  2722. this->GetScanner()->Scan();
  2723. break;
  2724. case tkTRUE:
  2725. if (buildAST)
  2726. {
  2727. pnode = CreateNodeForOpT<knopTrue>();
  2728. }
  2729. fCanAssign = FALSE;
  2730. this->GetScanner()->Scan();
  2731. break;
  2732. case tkFALSE:
  2733. if (buildAST)
  2734. {
  2735. pnode = CreateNodeForOpT<knopFalse>();
  2736. }
  2737. fCanAssign = FALSE;
  2738. this->GetScanner()->Scan();
  2739. break;
  2740. case tkNULL:
  2741. if (buildAST)
  2742. {
  2743. pnode = CreateNodeForOpT<knopNull>();
  2744. }
  2745. fCanAssign = FALSE;
  2746. this->GetScanner()->Scan();
  2747. break;
  2748. case tkDiv:
  2749. case tkAsgDiv:
  2750. pnode = ParseRegExp<buildAST>();
  2751. fCanAssign = FALSE;
  2752. this->GetScanner()->Scan();
  2753. break;
  2754. case tkNEW:
  2755. {
  2756. ichMin = this->GetScanner()->IchMinTok();
  2757. iecpMin = this->GetScanner()->IecpMinTok();
  2758. this->GetScanner()->Scan();
  2759. if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2760. {
  2761. pid = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);
  2762. ichLim = this->GetScanner()->IchLimTok();
  2763. iecpLim = this->GetScanner()->IecpLimTok();
  2764. this->GetScanner()->Scan();
  2765. isSpecialName = true;
  2766. goto LIdentifier;
  2767. }
  2768. else
  2769. {
  2770. ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset, nullptr, false, TRUE, nullptr, nullptr, nullptr, plastRParen);
  2771. if (buildAST)
  2772. {
  2773. pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);
  2774. pnode->ichMin = ichMin;
  2775. }
  2776. fInNew = TRUE;
  2777. fCanAssign = FALSE;
  2778. }
  2779. break;
  2780. }
  2781. case tkLBrack:
  2782. {
  2783. ichMin = this->GetScanner()->IchMinTok();
  2784. this->GetScanner()->Scan();
  2785. pnode = ParseArrayLiteral<buildAST>();
  2786. if (buildAST)
  2787. {
  2788. pnode->ichMin = ichMin;
  2789. pnode->ichLim = this->GetScanner()->IchLimTok();
  2790. }
  2791. if (this->m_arrayDepth == 0)
  2792. {
  2793. Assert(this->GetScanner()->IchLimTok() - ichMin > m_funcInArray);
  2794. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - ichMin - this->m_funcInArray);
  2795. this->m_funcInArray = 0;
  2796. this->m_funcInArrayDepth = 0;
  2797. }
  2798. ChkCurTok(tkRBrack, ERRnoRbrack);
  2799. if (!IsES6DestructuringEnabled())
  2800. {
  2801. fCanAssign = FALSE;
  2802. }
  2803. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2804. {
  2805. *pfLikelyPattern = TRUE;
  2806. }
  2807. break;
  2808. }
  2809. case tkLCurly:
  2810. {
  2811. ichMin = this->GetScanner()->IchMinTok();
  2812. this->GetScanner()->ScanForcingPid();
  2813. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);
  2814. if (buildAST)
  2815. {
  2816. pnode = CreateUniNode(knopObject, pnodeMemberList);
  2817. pnode->ichMin = ichMin;
  2818. pnode->ichLim = this->GetScanner()->IchLimTok();
  2819. }
  2820. ChkCurTok(tkRCurly, ERRnoRcurly);
  2821. if (!IsES6DestructuringEnabled())
  2822. {
  2823. fCanAssign = FALSE;
  2824. }
  2825. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2826. {
  2827. *pfLikelyPattern = TRUE;
  2828. }
  2829. break;
  2830. }
  2831. case tkFUNCTION:
  2832. {
  2833. LFunction:
  2834. if (m_grfscr & fscrDeferredFncExpression)
  2835. {
  2836. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  2837. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  2838. // first time we see it.
  2839. //
  2840. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  2841. // token of the source code of the function may not a 'function' token though, so we still need to reset this flag
  2842. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  2843. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  2844. m_grfscr &= ~fscrDeferredFncExpression;
  2845. }
  2846. ushort flags = fFncNoFlgs;
  2847. if (isLambdaExpr)
  2848. {
  2849. flags |= fFncLambda;
  2850. }
  2851. if (isAsyncExpr)
  2852. {
  2853. flags |= fFncAsync;
  2854. }
  2855. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, pNameHint, false, true, fUnaryOrParen);
  2856. if (isAsyncExpr)
  2857. {
  2858. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  2859. pnode->ichMin = ichMin;
  2860. }
  2861. fCanAssign = FALSE;
  2862. break;
  2863. }
  2864. case tkCLASS:
  2865. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2866. {
  2867. pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);
  2868. }
  2869. else
  2870. {
  2871. goto LUnknown;
  2872. }
  2873. fCanAssign = FALSE;
  2874. break;
  2875. case tkStrTmplBasic:
  2876. case tkStrTmplBegin:
  2877. pnode = ParseStringTemplateDecl<buildAST>(nullptr);
  2878. fCanAssign = FALSE;
  2879. break;
  2880. case tkIMPORT:
  2881. if (m_scriptContext->GetConfig()->IsES6ModuleEnabled() && m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2882. {
  2883. this->GetScanner()->Scan();
  2884. ChkCurTokNoScan(tkLParen, ERRnoLparen);
  2885. pnode = ParseImportCall<buildAST>();
  2886. }
  2887. else
  2888. {
  2889. goto LUnknown;
  2890. }
  2891. break;
  2892. #if ENABLE_BACKGROUND_PARSING
  2893. case tkCASE:
  2894. {
  2895. if (!m_doingFastScan)
  2896. {
  2897. goto LUnknown;
  2898. }
  2899. ParseNodePtr pnodeUnused;
  2900. pnode = ParseCase<buildAST>(&pnodeUnused);
  2901. break;
  2902. }
  2903. case tkELSE:
  2904. if (!m_doingFastScan)
  2905. {
  2906. goto LUnknown;
  2907. }
  2908. this->GetScanner()->Scan();
  2909. ParseStatement<buildAST>();
  2910. break;
  2911. #endif
  2912. default:
  2913. LUnknown:
  2914. Error(ERRsyntax);
  2915. break;
  2916. }
  2917. pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, fCanAssignToCall, &fCanAssign, &term, pfIsDotOrIndex);
  2918. if (savedTopAsyncRef != nullptr &&
  2919. this->m_token.tk == tkDArrow)
  2920. {
  2921. // This is an async arrow function; we're going to back up and reparse it.
  2922. // Make sure we don't leave behind a bogus reference to the 'async' identifier.
  2923. for (pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;)
  2924. {
  2925. Assert(pid->GetTopRef() != nullptr);
  2926. pid->RemovePrevPidRef(nullptr);
  2927. }
  2928. }
  2929. // Pass back identifier if requested
  2930. if (pToken && term.tk == tkID)
  2931. {
  2932. *pToken = term;
  2933. }
  2934. if (pfCanAssign)
  2935. {
  2936. *pfCanAssign = fCanAssign;
  2937. }
  2938. return pnode;
  2939. }
  2940. template <bool buildAST>
  2941. ParseNodeRegExp * Parser::ParseRegExp()
  2942. {
  2943. ParseNodeRegExp * pnode = nullptr;
  2944. if (buildAST || IsDoingFastScan())
  2945. {
  2946. this->GetScanner()->RescanRegExp();
  2947. #if ENABLE_BACKGROUND_PARSING
  2948. BOOL saveDeferringAST = this->m_deferringAST;
  2949. if (m_doingFastScan)
  2950. {
  2951. this->m_deferringAST = false;
  2952. }
  2953. #endif
  2954. pnode = CreateNodeForOpT<knopRegExp>();
  2955. pnode->regexPattern = m_token.GetRegex();
  2956. #if ENABLE_BACKGROUND_PARSING
  2957. if (m_doingFastScan)
  2958. {
  2959. this->m_deferringAST = saveDeferringAST;
  2960. this->AddFastScannedRegExpNode(pnode);
  2961. if (!buildAST)
  2962. {
  2963. pnode = nullptr;
  2964. }
  2965. }
  2966. else if (this->IsBackgroundParser())
  2967. {
  2968. Assert(pnode->regexPattern == nullptr);
  2969. this->AddBackgroundRegExpNode(pnode);
  2970. }
  2971. #endif
  2972. }
  2973. else
  2974. {
  2975. this->GetScanner()->RescanRegExpNoAST();
  2976. }
  2977. Assert(m_token.tk == tkRegExp);
  2978. return pnode;
  2979. }
  2980. BOOL Parser::NodeIsEvalName(ParseNodePtr pnode)
  2981. {
  2982. //WOOB 1107758 Special case of indirect eval binds to local scope in standards mode
  2983. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids.eval);
  2984. }
  2985. BOOL Parser::NodeIsSuperName(ParseNodePtr pnode)
  2986. {
  2987. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids._superConstructor);
  2988. }
  2989. BOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)
  2990. {
  2991. return pnode->nop == knopName &&
  2992. pnode->AsParseNodeName()->pid->Cch() == cch &&
  2993. !wmemcmp(pnode->AsParseNodeName()->pid->Psz(), sz, cch);
  2994. }
  2995. BOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)
  2996. {
  2997. for (;;)
  2998. {
  2999. switch (pnode->nop)
  3000. {
  3001. case knopName:
  3002. return (pnode->AsParseNodeName()->pid == pid);
  3003. case knopComma:
  3004. pnode = pnode->AsParseNodeBin()->pnode2;
  3005. break;
  3006. default:
  3007. return FALSE;
  3008. }
  3009. }
  3010. }
  3011. template<bool buildAST>
  3012. ParseNodePtr Parser::ParsePostfixOperators(
  3013. ParseNodePtr pnode,
  3014. BOOL fAllowCall,
  3015. BOOL fInNew,
  3016. BOOL isAsyncExpr,
  3017. BOOL fCanAssignToCallResult,
  3018. BOOL *pfCanAssign,
  3019. _Inout_ IdentToken* pToken,
  3020. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr */)
  3021. {
  3022. uint16 count = 0;
  3023. bool callOfConstants = false;
  3024. if (pfIsDotOrIndex)
  3025. {
  3026. *pfIsDotOrIndex = false;
  3027. }
  3028. for (;;)
  3029. {
  3030. uint16 spreadArgCount = 0;
  3031. switch (m_token.tk)
  3032. {
  3033. case tkLParen:
  3034. {
  3035. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3036. if (fInNew)
  3037. {
  3038. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3039. if (buildAST)
  3040. {
  3041. Assert(pnode->nop == knopNew);
  3042. Assert(pnode->AsParseNodeCall()->pnodeArgs == nullptr);
  3043. pnode->AsParseNodeCall()->pnodeArgs = pnodeArgs;
  3044. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3045. pnode->AsParseNodeCall()->isApplyCall = false;
  3046. pnode->AsParseNodeCall()->isEvalCall = false;
  3047. pnode->AsParseNodeCall()->isSuperCall = false;
  3048. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3049. Assert(!m_hasDestructuringPattern || count > 0);
  3050. pnode->AsParseNodeCall()->argCount = count;
  3051. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3052. pnode->ichLim = this->GetScanner()->IchLimTok();
  3053. }
  3054. else
  3055. {
  3056. pnode = nullptr;
  3057. pToken->tk = tkNone; // This is no longer an identifier
  3058. }
  3059. fInNew = FALSE;
  3060. ChkCurTok(tkRParen, ERRnoRparen);
  3061. }
  3062. else
  3063. {
  3064. if (!fAllowCall)
  3065. {
  3066. return pnode;
  3067. }
  3068. uint saveNextBlockId = m_nextBlockId;
  3069. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  3070. if (isAsyncExpr)
  3071. {
  3072. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  3073. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  3074. // up function ID's.
  3075. GetCurrentBlock()->blockId = m_nextBlockId++;
  3076. }
  3077. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3078. // We used to un-defer a deferred function body here if it was called as part of the expression that declared it.
  3079. // We now detect this case up front in ParseFncDecl, which is cheaper and simpler.
  3080. if (buildAST)
  3081. {
  3082. bool fCallIsEval = false;
  3083. // Detect super()
  3084. if (this->NodeIsSuperName(pnode))
  3085. {
  3086. pnode = CreateSuperCallNode(pnode->AsParseNodeSpecialName(), pnodeArgs);
  3087. Assert(pnode);
  3088. pnode->AsParseNodeSuperCall()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3089. pnode->AsParseNodeSuperCall()->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3090. }
  3091. else
  3092. {
  3093. pnode = CreateCallNode(knopCall, pnode, pnodeArgs);
  3094. Assert(pnode);
  3095. }
  3096. // Detect call to "eval" and record it on the function.
  3097. // Note: we used to leave it up to the byte code generator to detect eval calls
  3098. // at global scope, but now it relies on the flag the parser sets, so set it here.
  3099. if (count > 0 && this->NodeIsEvalName(pnode->AsParseNodeCall()->pnodeTarget))
  3100. {
  3101. this->MarkEvalCaller();
  3102. fCallIsEval = true;
  3103. // Eval may reference any of the special symbols so we need to push refs to them here.
  3104. ReferenceSpecialName(wellKnownPropertyPids._this);
  3105. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3106. ReferenceSpecialName(wellKnownPropertyPids._super);
  3107. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3108. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3109. }
  3110. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3111. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3112. pnode->AsParseNodeCall()->isApplyCall = false;
  3113. pnode->AsParseNodeCall()->isEvalCall = fCallIsEval;
  3114. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3115. Assert(!m_hasDestructuringPattern || count > 0);
  3116. pnode->AsParseNodeCall()->argCount = count;
  3117. pnode->ichLim = this->GetScanner()->IchLimTok();
  3118. }
  3119. else
  3120. {
  3121. pnode = nullptr;
  3122. if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) // Detect eval
  3123. {
  3124. this->MarkEvalCaller();
  3125. ReferenceSpecialName(wellKnownPropertyPids._this);
  3126. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3127. ReferenceSpecialName(wellKnownPropertyPids._super);
  3128. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3129. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3130. }
  3131. pToken->tk = tkNone; // This is no longer an identifier
  3132. }
  3133. ChkCurTok(tkRParen, ERRnoRparen);
  3134. if (isAsyncExpr)
  3135. {
  3136. GetCurrentBlock()->blockId = saveCurrBlockId;
  3137. if (m_token.tk == tkDArrow)
  3138. {
  3139. // We're going to rewind and reinterpret the expression as a parameter list.
  3140. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  3141. m_nextBlockId = saveNextBlockId;
  3142. }
  3143. }
  3144. }
  3145. if (pfCanAssign)
  3146. {
  3147. *pfCanAssign = fCanAssignToCallResult &&
  3148. (m_sourceContextInfo ?
  3149. !PHASE_ON_RAW(Js::EarlyErrorOnAssignToCallPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId) :
  3150. !PHASE_ON1(Js::EarlyErrorOnAssignToCallPhase));
  3151. }
  3152. if (pfIsDotOrIndex)
  3153. {
  3154. *pfIsDotOrIndex = false;
  3155. }
  3156. break;
  3157. }
  3158. case tkLBrack:
  3159. {
  3160. this->GetScanner()->Scan();
  3161. IdentToken tok;
  3162. ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
  3163. if (buildAST)
  3164. {
  3165. AnalysisAssert(pnodeExpr);
  3166. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3167. {
  3168. pnode = CreateSuperReferenceNode(knopIndex, pnode->AsParseNodeSpecialName(), pnodeExpr);
  3169. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3170. }
  3171. else
  3172. {
  3173. pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
  3174. }
  3175. AnalysisAssert(pnode);
  3176. pnode->ichLim = this->GetScanner()->IchLimTok();
  3177. }
  3178. else
  3179. {
  3180. pnode = nullptr;
  3181. pToken->tk = tkNone; // This is no longer an identifier
  3182. }
  3183. ChkCurTok(tkRBrack, ERRnoRbrack);
  3184. if (pfCanAssign)
  3185. {
  3186. *pfCanAssign = TRUE;
  3187. }
  3188. if (pfIsDotOrIndex)
  3189. {
  3190. *pfIsDotOrIndex = true;
  3191. }
  3192. PidRefStack * topPidRef = nullptr;
  3193. if (buildAST)
  3194. {
  3195. if (pnodeExpr && pnodeExpr->nop == knopName)
  3196. {
  3197. topPidRef = pnodeExpr->AsParseNodeName()->pid->GetTopRef();
  3198. }
  3199. }
  3200. else if (tok.tk == tkID)
  3201. {
  3202. topPidRef = tok.pid->GetTopRef();
  3203. }
  3204. if (topPidRef)
  3205. {
  3206. topPidRef->SetIsUsedInLdElem(true);
  3207. }
  3208. if (!buildAST)
  3209. {
  3210. break;
  3211. }
  3212. bool shouldConvertToDot = false;
  3213. if (pnode->AsParseNodeBin()->pnode2->nop == knopStr)
  3214. {
  3215. // if the string is empty or contains escape character, we will not convert them to dot node
  3216. shouldConvertToDot = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch() > 0 && !this->GetScanner()->IsEscapeOnLastTkStrCon();
  3217. }
  3218. if (shouldConvertToDot)
  3219. {
  3220. LPCOLESTR str = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Psz();
  3221. // See if we can convert o["p"] into o.p and o["0"] into o[0] since they're equivalent and the latter forms
  3222. // are faster
  3223. uint32 uintValue;
  3224. if (Js::JavascriptOperators::TryConvertToUInt32(
  3225. str,
  3226. pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch(),
  3227. &uintValue) &&
  3228. !Js::TaggedInt::IsOverflow(uintValue)) // the optimization is not very useful if the number can't be represented as a TaggedInt
  3229. {
  3230. // No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes
  3231. auto intNode = CreateIntNode(uintValue); // implicit conversion from uint32 to int32
  3232. pnode->AsParseNodeBin()->pnode2 = intNode;
  3233. }
  3234. // Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,
  3235. // and since NaN/Infinity is a number it won't kill o.NaN/o.Infinity which would cause a problem
  3236. // if we decide to hoist o.NaN/o.Infinity.
  3237. // We need to keep o["NaN"] and o["+/-Infinity"] as array element access (we don't hoist that but we may hoist field access),
  3238. // so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.
  3239. // We need to follow same logic for strings that convert to a floating point number.
  3240. else
  3241. {
  3242. bool doConvertToProperty = false; // Convert a["x"] -> a.x.
  3243. if (!Parser::IsNaNOrInfinityLiteral<true>(str))
  3244. {
  3245. const OLECHAR* terminalChar;
  3246. double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);
  3247. bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);
  3248. doConvertToProperty = !convertsToFloat;
  3249. }
  3250. if (doConvertToProperty)
  3251. {
  3252. ParseNodeName * pnodeNewExpr = CreateNameNode(pnodeExpr->AsParseNodeStr()->pid);
  3253. pnodeNewExpr->ichMin = pnodeExpr->ichMin;
  3254. pnodeNewExpr->ichLim = pnodeExpr->ichLim;
  3255. pnode->AsParseNodeBin()->pnode2 = pnodeNewExpr;
  3256. pnode->nop = knopDot;
  3257. pnode->grfpn |= PNodeFlags::fpnIndexOperator;
  3258. }
  3259. }
  3260. }
  3261. }
  3262. break;
  3263. case tkDot:
  3264. {
  3265. ParseNodePtr name = nullptr;
  3266. OpCode opCode = knopDot;
  3267. this->GetScanner()->Scan();
  3268. if (!m_token.IsIdentifier())
  3269. {
  3270. //allow reserved words in ES5 mode
  3271. if (!(m_token.IsReservedWord()))
  3272. {
  3273. IdentifierExpectedError(m_token);
  3274. }
  3275. }
  3276. // Note: see comment above about field optimization WRT NaN/Infinity/-Infinity.
  3277. // Convert a.Nan, a.Infinity into a["NaN"], a["Infinity"].
  3278. // We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.
  3279. // Both NaN and Infinity are identifiers.
  3280. else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(this->GetHashTbl())->Psz()))
  3281. {
  3282. opCode = knopIndex;
  3283. }
  3284. if (buildAST)
  3285. {
  3286. if (opCode == knopDot)
  3287. {
  3288. name = CreateNameNode(m_token.GetIdentifier(this->GetHashTbl()));
  3289. }
  3290. else
  3291. {
  3292. Assert(opCode == knopIndex);
  3293. name = CreateStrNode(m_token.GetIdentifier(this->GetHashTbl()));
  3294. }
  3295. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3296. {
  3297. pnode = CreateSuperReferenceNode(opCode, pnode->AsParseNodeSpecialName(), name);
  3298. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3299. }
  3300. else
  3301. {
  3302. pnode = CreateBinNode(opCode, pnode, name);
  3303. }
  3304. }
  3305. else
  3306. {
  3307. pnode = nullptr;
  3308. pToken->tk = tkNone;
  3309. }
  3310. if (pfCanAssign)
  3311. {
  3312. *pfCanAssign = TRUE;
  3313. }
  3314. if (pfIsDotOrIndex)
  3315. {
  3316. *pfIsDotOrIndex = true;
  3317. }
  3318. this->GetScanner()->Scan();
  3319. break;
  3320. }
  3321. case tkStrTmplBasic:
  3322. case tkStrTmplBegin:
  3323. {
  3324. ParseNode* templateNode = nullptr;
  3325. if (pnode != nullptr)
  3326. {
  3327. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3328. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3329. }
  3330. else
  3331. {
  3332. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3333. }
  3334. if (!buildAST)
  3335. {
  3336. pToken->tk = tkNone; // This is no longer an identifier
  3337. }
  3338. pnode = templateNode;
  3339. if (pfCanAssign)
  3340. {
  3341. *pfCanAssign = FALSE;
  3342. }
  3343. if (pfIsDotOrIndex)
  3344. {
  3345. *pfIsDotOrIndex = false;
  3346. }
  3347. break;
  3348. }
  3349. default:
  3350. return pnode;
  3351. }
  3352. }
  3353. }
  3354. /***************************************************************************
  3355. Look for an existing label with the given name.
  3356. ***************************************************************************/
  3357. bool Parser::LabelExists(IdentPtr pid, LabelId* pLabelIdList)
  3358. {
  3359. StmtNest dummy;
  3360. dummy.pLabelId = pLabelIdList;
  3361. dummy.pstmtOuter = m_pstmtCur;
  3362. // Look through each label list for the current stack of statements
  3363. for (StmtNest* pStmt = &dummy; pStmt != nullptr; pStmt = pStmt->pstmtOuter)
  3364. {
  3365. for (LabelId* pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)
  3366. {
  3367. if (pLabelId->pid == pid)
  3368. return true;
  3369. }
  3370. }
  3371. return false;
  3372. }
  3373. // Currently only ints and floats are treated as constants in function call
  3374. // TODO: Check if we need for other constants as well
  3375. BOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)
  3376. {
  3377. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3378. {
  3379. return TRUE;
  3380. }
  3381. if (pnode->nop == knopFlt)
  3382. {
  3383. return TRUE;
  3384. }
  3385. return FALSE;
  3386. }
  3387. /***************************************************************************
  3388. Parse a list of arguments.
  3389. ***************************************************************************/
  3390. template<bool buildAST>
  3391. ParseNodePtr Parser::ParseArgList(bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)
  3392. {
  3393. ParseNodePtr pnodeArg;
  3394. ParseNodePtr pnodeList = nullptr;
  3395. ParseNodePtr *lastNodeRef = nullptr;
  3396. // Check for an empty list
  3397. Assert(m_token.tk == tkLParen);
  3398. if (this->GetScanner()->Scan() == tkRParen)
  3399. {
  3400. return nullptr;
  3401. }
  3402. *pCallOfConstants = true;
  3403. *pSpreadArgCount = 0;
  3404. int count = 0;
  3405. while (true)
  3406. {
  3407. if (count >= Js::Constants::MaxAllowedArgs)
  3408. {
  3409. Error(ERRTooManyArgs);
  3410. }
  3411. // Allow spread in argument lists.
  3412. IdentToken token;
  3413. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */TRUE, NULL, nullptr, nullptr, &token);
  3414. ++count;
  3415. this->MarkEscapingRef(pnodeArg, &token);
  3416. if (buildAST)
  3417. {
  3418. this->CheckArguments(pnodeArg);
  3419. if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))
  3420. {
  3421. *pCallOfConstants = false;
  3422. }
  3423. if (pnodeArg->nop == knopEllipsis)
  3424. {
  3425. (*pSpreadArgCount)++;
  3426. }
  3427. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3428. }
  3429. if (m_token.tk != tkComma)
  3430. {
  3431. break;
  3432. }
  3433. this->GetScanner()->Scan();
  3434. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  3435. {
  3436. break;
  3437. }
  3438. }
  3439. if (pSpreadArgCount != nullptr && (*pSpreadArgCount) > 0) {
  3440. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3441. }
  3442. *pCount = static_cast<uint16>(count);
  3443. if (buildAST)
  3444. {
  3445. Assert(lastNodeRef);
  3446. Assert(*lastNodeRef);
  3447. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3448. }
  3449. return pnodeList;
  3450. }
  3451. // Currently only ints are treated as constants in ArrayLiterals
  3452. BOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)
  3453. {
  3454. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3455. {
  3456. return TRUE;
  3457. }
  3458. return FALSE;
  3459. }
  3460. template<bool buildAST>
  3461. ParseNodeArrLit * Parser::ParseArrayLiteral()
  3462. {
  3463. ParseNodeArrLit * pnode = nullptr;
  3464. bool arrayOfTaggedInts = false;
  3465. bool arrayOfInts = false;
  3466. bool arrayOfNumbers = false;
  3467. bool hasMissingValues = false;
  3468. uint count = 0;
  3469. uint spreadCount = 0;
  3470. ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);
  3471. if (buildAST)
  3472. {
  3473. pnode = CreateNodeForOpT<knopArray>();
  3474. pnode->pnode1 = pnode1;
  3475. pnode->arrayOfTaggedInts = arrayOfTaggedInts;
  3476. pnode->arrayOfInts = arrayOfInts;
  3477. pnode->arrayOfNumbers = arrayOfNumbers;
  3478. pnode->hasMissingValues = hasMissingValues;
  3479. pnode->count = count;
  3480. pnode->spreadCount = spreadCount;
  3481. if (pnode->pnode1)
  3482. {
  3483. this->CheckArguments(pnode->pnode1);
  3484. }
  3485. }
  3486. return pnode;
  3487. }
  3488. /***************************************************************************
  3489. Create an ArrayLiteral node
  3490. Parse a list of array elements. [ a, b, , c, ]
  3491. ***************************************************************************/
  3492. template<bool buildAST>
  3493. ParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)
  3494. {
  3495. ParseNodePtr pnodeArg = nullptr;
  3496. ParseNodePtr pnodeList = nullptr;
  3497. ParseNodePtr *lastNodeRef = nullptr;
  3498. *count = 0;
  3499. // Check for an empty list
  3500. if (tkRBrack == m_token.tk)
  3501. {
  3502. return nullptr;
  3503. }
  3504. this->m_arrayDepth++;
  3505. bool arrayOfTaggedInts = buildAST;
  3506. bool arrayOfInts = buildAST;
  3507. bool arrayOfNumbers = buildAST;
  3508. bool arrayOfVarInts = false;
  3509. bool hasMissingValues = false;
  3510. for (;;)
  3511. {
  3512. (*count)++;
  3513. if (tkComma == m_token.tk || tkRBrack == m_token.tk)
  3514. {
  3515. hasMissingValues = true;
  3516. arrayOfTaggedInts = false;
  3517. arrayOfInts = false;
  3518. arrayOfNumbers = false;
  3519. if (buildAST)
  3520. {
  3521. pnodeArg = CreateNodeForOpT<knopEmpty>();
  3522. }
  3523. }
  3524. else
  3525. {
  3526. // Allow Spread in array literals.
  3527. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  3528. if (buildAST)
  3529. {
  3530. if (pnodeArg->nop == knopEllipsis)
  3531. {
  3532. (*spreadCount)++;
  3533. }
  3534. this->CheckArguments(pnodeArg);
  3535. }
  3536. }
  3537. #if DEBUG
  3538. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))
  3539. {
  3540. Error(ERRsyntax);
  3541. }
  3542. #endif
  3543. if (buildAST)
  3544. {
  3545. if (arrayOfNumbers)
  3546. {
  3547. if (pnodeArg->nop != knopInt)
  3548. {
  3549. arrayOfTaggedInts = false;
  3550. if (pnodeArg->nop != knopFlt)
  3551. {
  3552. // Not an array of constants.
  3553. arrayOfInts = false;
  3554. arrayOfNumbers = false;
  3555. }
  3556. else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->AsParseNodeFloat()->dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->AsParseNodeFloat()->dbl) || pnodeArg->AsParseNodeFloat()->dbl == -2147483648.0))
  3557. {
  3558. // We've seen nothing but ints, and this is a uint32 but not an int32.
  3559. // Unless we see an actual float at some point, we want an array of vars
  3560. // so we can work with tagged ints.
  3561. arrayOfVarInts = true;
  3562. }
  3563. else
  3564. {
  3565. // Not an int array, but it may still be a float array.
  3566. arrayOfInts = false;
  3567. }
  3568. }
  3569. else
  3570. {
  3571. if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->AsParseNodeInt()->lw))
  3572. {
  3573. arrayOfInts = false;
  3574. }
  3575. if (Js::TaggedInt::IsOverflow(pnodeArg->AsParseNodeInt()->lw))
  3576. {
  3577. arrayOfTaggedInts = false;
  3578. }
  3579. }
  3580. }
  3581. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3582. }
  3583. if (tkComma != m_token.tk)
  3584. {
  3585. break;
  3586. }
  3587. this->GetScanner()->Scan();
  3588. if (tkRBrack == m_token.tk)
  3589. {
  3590. break;
  3591. }
  3592. }
  3593. if (spreadCount != nullptr && *spreadCount > 0) {
  3594. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3595. }
  3596. if (buildAST)
  3597. {
  3598. Assert(lastNodeRef);
  3599. Assert(*lastNodeRef);
  3600. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3601. if (arrayOfVarInts && arrayOfInts)
  3602. {
  3603. arrayOfInts = false;
  3604. arrayOfNumbers = false;
  3605. }
  3606. *pArrayOfTaggedInts = arrayOfTaggedInts;
  3607. *pArrayOfInts = arrayOfInts;
  3608. *pArrayOfNumbers = arrayOfNumbers;
  3609. *pHasMissingValues = hasMissingValues;
  3610. }
  3611. this->m_arrayDepth--;
  3612. return pnodeList;
  3613. }
  3614. Parser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)
  3615. {
  3616. Assert(pAllocator);
  3617. return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);
  3618. }
  3619. template<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)
  3620. {
  3621. this->GetScanner()->Scan();
  3622. ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);
  3623. if (buildAST)
  3624. {
  3625. *ppnodeName = CreateUniNode(knopComputedName, pnodeNameExpr, pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);
  3626. }
  3627. if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))
  3628. {
  3629. *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);
  3630. }
  3631. ChkCurTokNoScan(tkRBrack, ERRnoRbrack);
  3632. }
  3633. /***************************************************************************
  3634. Parse a list of object set/get members, e.g.:
  3635. { get foo(){ ... }, set bar(arg) { ... } }
  3636. ***************************************************************************/
  3637. template<bool buildAST>
  3638. ParseNodeBin * Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint)
  3639. {
  3640. ParseNodePtr pnodeName = nullptr;
  3641. Assert(nop == knopGetMember || nop == knopSetMember);
  3642. Assert(ppNameHint);
  3643. IdentPtr pid = nullptr;
  3644. bool isComputedName = false;
  3645. *ppNameHint = nullptr;
  3646. switch (m_token.tk)
  3647. {
  3648. default:
  3649. if (!m_token.IsReservedWord())
  3650. {
  3651. Error(ERRnoMemberIdent);
  3652. }
  3653. // fall through
  3654. case tkID:
  3655. pid = m_token.GetIdentifier(this->GetHashTbl());
  3656. *ppNameHint = pid->Psz();
  3657. if (buildAST)
  3658. {
  3659. pnodeName = CreateStrNode(pid);
  3660. }
  3661. break;
  3662. case tkStrCon:
  3663. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3664. {
  3665. Error(ERRES5NoOctal);
  3666. }
  3667. pid = m_token.GetStr();
  3668. *ppNameHint = pid->Psz();
  3669. if (buildAST)
  3670. {
  3671. pnodeName = CreateStrNode(pid);
  3672. }
  3673. break;
  3674. case tkIntCon:
  3675. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3676. {
  3677. Error(ERRES5NoOctal);
  3678. }
  3679. pid = this->GetScanner()->PidFromLong(m_token.GetLong());
  3680. if (buildAST)
  3681. {
  3682. pnodeName = CreateStrNode(pid);
  3683. }
  3684. break;
  3685. case tkFltCon:
  3686. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3687. {
  3688. Error(ERRES5NoOctal);
  3689. }
  3690. pid = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  3691. if (buildAST)
  3692. {
  3693. pnodeName = CreateStrNode(pid);
  3694. }
  3695. break;
  3696. case tkLBrack:
  3697. // Computed property name: get|set [expr] () { }
  3698. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3699. {
  3700. Error(ERRnoMemberIdent);
  3701. }
  3702. LPCOLESTR emptyHint = nullptr;
  3703. uint32 offset = 0;
  3704. ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);
  3705. isComputedName = true;
  3706. break;
  3707. }
  3708. MemberType memberType;
  3709. ushort flags = fFncMethod | fFncNoName;
  3710. if (nop == knopGetMember)
  3711. {
  3712. memberType = MemberTypeGetter;
  3713. flags |= fFncNoArg;
  3714. }
  3715. else
  3716. {
  3717. Assert(nop == knopSetMember);
  3718. memberType = MemberTypeSetter;
  3719. flags |= fFncOneArg;
  3720. }
  3721. AutoParsingSuperRestrictionStateRestorer restorer(this);
  3722. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  3723. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(flags, *ppNameHint,
  3724. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  3725. if (isComputedName)
  3726. {
  3727. pnodeFnc->SetHasComputedName();
  3728. }
  3729. pnodeFnc->SetHasHomeObj();
  3730. if (buildAST)
  3731. {
  3732. pnodeFnc->SetIsAccessor();
  3733. return CreateBinNode(nop, pnodeName, pnodeFnc);
  3734. }
  3735. else
  3736. {
  3737. return nullptr;
  3738. }
  3739. }
  3740. /***************************************************************************
  3741. Parse a list of object members. e.g. { x:foo, 'y me':bar }
  3742. ***************************************************************************/
  3743. template<bool buildAST>
  3744. ParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)
  3745. {
  3746. ParseNodeBin * pnodeArg = nullptr;
  3747. ParseNodePtr pnodeSpread = nullptr;
  3748. ParseNodePtr pnodeName = nullptr;
  3749. ParseNodePtr pnodeList = nullptr;
  3750. ParseNodePtr *lastNodeRef = nullptr;
  3751. LPCOLESTR pFullNameHint = nullptr; // A calculated full name
  3752. uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;
  3753. uint32 shortNameOffset = 0;
  3754. bool isProtoDeclared = false;
  3755. // we get declaration tkLCurly - when the possible object pattern found under the expression.
  3756. bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();
  3757. // Check for an empty list
  3758. if (tkRCurly == m_token.tk)
  3759. {
  3760. return nullptr;
  3761. }
  3762. ArenaAllocator tempAllocator(_u("MemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  3763. bool hasDeferredInitError = false;
  3764. for (;;)
  3765. {
  3766. bool isComputedName = false;
  3767. #if DEBUG
  3768. if ((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(this->GetScanner()->IsDoubleQuoteOnLastTkStrCon())))
  3769. {
  3770. Error(ERRsyntax);
  3771. }
  3772. #endif
  3773. bool isAsyncMethod = false;
  3774. charcount_t ichMin = 0;
  3775. size_t iecpMin = 0;
  3776. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  3777. {
  3778. RestorePoint parsedAsync;
  3779. this->GetScanner()->Capture(&parsedAsync);
  3780. ichMin = this->GetScanner()->IchMinTok();
  3781. iecpMin = this->GetScanner()->IecpMinTok();
  3782. this->GetScanner()->ScanForcingPid();
  3783. if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || this->GetScanner()->FHadNewLine() || m_token.tk == tkComma)
  3784. {
  3785. this->GetScanner()->SeekTo(parsedAsync);
  3786. }
  3787. else
  3788. {
  3789. isAsyncMethod = true;
  3790. }
  3791. }
  3792. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  3793. m_token.tk == tkStar;
  3794. ushort fncDeclFlags = fFncNoName | fFncMethod;
  3795. if (isGenerator)
  3796. {
  3797. if (isAsyncMethod)
  3798. {
  3799. Error(ERRsyntax);
  3800. }
  3801. // Include star character in the function extents
  3802. ichMin = this->GetScanner()->IchMinTok();
  3803. iecpMin = this->GetScanner()->IecpMinTok();
  3804. this->GetScanner()->ScanForcingPid();
  3805. fncDeclFlags |= fFncGenerator;
  3806. }
  3807. IdentPtr pidHint = nullptr; // A name scoped to current expression
  3808. Token tkHint = m_token;
  3809. charcount_t idHintIchMin = static_cast<charcount_t>(this->GetScanner()->IecpMinTok());
  3810. charcount_t idHintIchLim = static_cast<charcount_t>(this->GetScanner()->IecpLimTok());
  3811. bool wrapInBrackets = false;
  3812. bool useSpread = false;
  3813. switch (m_token.tk)
  3814. {
  3815. default:
  3816. if (!m_token.IsReservedWord())
  3817. {
  3818. Error(ERRnoMemberIdent);
  3819. }
  3820. // allow reserved words
  3821. wrapInBrackets = true;
  3822. // fall-through
  3823. case tkID:
  3824. pidHint = m_token.GetIdentifier(this->GetHashTbl());
  3825. if (buildAST)
  3826. {
  3827. pnodeName = CreateStrNode(pidHint);
  3828. }
  3829. break;
  3830. case tkStrCon:
  3831. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3832. {
  3833. Error(ERRES5NoOctal);
  3834. }
  3835. wrapInBrackets = true;
  3836. pidHint = m_token.GetStr();
  3837. if (buildAST)
  3838. {
  3839. pnodeName = CreateStrNode(pidHint);
  3840. }
  3841. break;
  3842. case tkIntCon:
  3843. // Object initializers with numeric labels allowed in JS6
  3844. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3845. {
  3846. Error(ERRES5NoOctal);
  3847. }
  3848. pidHint = this->GetScanner()->PidFromLong(m_token.GetLong());
  3849. if (buildAST)
  3850. {
  3851. pnodeName = CreateStrNode(pidHint);
  3852. }
  3853. break;
  3854. case tkFltCon:
  3855. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3856. {
  3857. Error(ERRES5NoOctal);
  3858. }
  3859. pidHint = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  3860. if (buildAST)
  3861. {
  3862. pnodeName = CreateStrNode(pidHint);
  3863. }
  3864. wrapInBrackets = true;
  3865. break;
  3866. case tkLBrack:
  3867. // Computed property name: [expr] : value
  3868. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3869. {
  3870. Error(ERRnoMemberIdent);
  3871. }
  3872. ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3873. isComputedName = true;
  3874. break;
  3875. case tkEllipsis:
  3876. if (CONFIG_FLAG(ES2018ObjectSpread))
  3877. {
  3878. useSpread = true;
  3879. }
  3880. else
  3881. {
  3882. Error(ERRnoMemberIdent);
  3883. }
  3884. break;
  3885. }
  3886. if (pFullNameHint == nullptr)
  3887. {
  3888. if (CONFIG_FLAG(UseFullName))
  3889. {
  3890. pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);
  3891. }
  3892. else
  3893. {
  3894. pFullNameHint = pidHint ? pidHint->Psz() : nullptr;
  3895. fullNameHintLength = pidHint ? pidHint->Cch() : 0;
  3896. shortNameOffset = 0;
  3897. }
  3898. }
  3899. RestorePoint atPid;
  3900. // Only move to next token if spread op was not seen
  3901. if (!useSpread)
  3902. {
  3903. this->GetScanner()->Capture(&atPid);
  3904. this->GetScanner()->ScanForcingPid();
  3905. }
  3906. if (isGenerator && m_token.tk != tkLParen)
  3907. {
  3908. Error(ERRnoLparen);
  3909. }
  3910. if (tkColon == m_token.tk)
  3911. {
  3912. // It is a syntax error if the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.
  3913. // Note that previous scan is important because only after that we can determine we have a variable.
  3914. if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)
  3915. {
  3916. if (isProtoDeclared)
  3917. {
  3918. Error(ERRsyntax);
  3919. }
  3920. else
  3921. {
  3922. isProtoDeclared = true;
  3923. }
  3924. }
  3925. this->GetScanner()->Scan();
  3926. ParseNodePtr pnodeExpr = nullptr;
  3927. if (isObjectPattern)
  3928. {
  3929. if (m_token.tk == tkEllipsis)
  3930. {
  3931. Error(ERRUnexpectedEllipsis);
  3932. }
  3933. RestorePoint atExpression;
  3934. if (!buildAST && declarationType == tkLCurly && IsPossiblePatternStart())
  3935. {
  3936. this->GetScanner()->Capture(&atExpression);
  3937. int saveNextBlockId = m_nextBlockId;
  3938. // It is possible that we might encounter the shorthand init error. Lets find that out.
  3939. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  3940. m_hasDeferredShorthandInitError = false;
  3941. IdentToken token;
  3942. BOOL fLikelyPattern = false;
  3943. // First identify that the current expression is indeed the object/array literal. Otherwise we will just use the ParsrExpr to parse that.
  3944. ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false /*fUnaryOrParen*/,
  3945. TRUE, nullptr /*pfCanAssign*/, &fLikelyPattern);
  3946. m_nextBlockId = saveNextBlockId;
  3947. this->GetScanner()->SeekTo(atExpression);
  3948. if (fLikelyPattern)
  3949. {
  3950. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3951. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3952. {
  3953. if (m_token.IsOperator())
  3954. {
  3955. Error(ERRDestructNoOper);
  3956. }
  3957. Error(ERRsyntax);
  3958. }
  3959. }
  3960. else
  3961. {
  3962. if (m_hasDeferredShorthandInitError)
  3963. {
  3964. Error(ERRnoColon);
  3965. }
  3966. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3967. }
  3968. m_hasDeferredShorthandInitError = savedDeferredInitError;
  3969. }
  3970. else
  3971. {
  3972. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3973. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3974. {
  3975. if (m_token.IsOperator())
  3976. {
  3977. Error(ERRDestructNoOper);
  3978. }
  3979. Error(ERRsyntax);
  3980. }
  3981. }
  3982. }
  3983. else
  3984. {
  3985. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3986. if (pnodeExpr && pnodeExpr->nop == knopFncDecl)
  3987. {
  3988. ParseNodeFnc* funcNode = pnodeExpr->AsParseNodeFnc();
  3989. if (isComputedName)
  3990. {
  3991. funcNode->SetHasComputedName();
  3992. }
  3993. funcNode->SetHasHomeObj();
  3994. }
  3995. }
  3996. #if DEBUG
  3997. if ((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))
  3998. {
  3999. Error(ERRsyntax);
  4000. }
  4001. #endif
  4002. if (buildAST)
  4003. {
  4004. pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);
  4005. if (pnodeArg->pnode1->nop == knopStr)
  4006. {
  4007. pnodeArg->pnode1->AsParseNodeStr()->pid->PromoteAssignmentState();
  4008. }
  4009. }
  4010. }
  4011. else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4012. {
  4013. if (isObjectPattern)
  4014. {
  4015. Error(ERRInvalidAssignmentTarget);
  4016. }
  4017. // Shorthand syntax: foo() {} -> foo: function() {}
  4018. // Rewind to the PID and parse a function expression.
  4019. this->GetScanner()->SeekTo(atPid);
  4020. AutoParsingSuperRestrictionStateRestorer restorer(this);
  4021. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  4022. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), pFullNameHint,
  4023. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  4024. if (isAsyncMethod || isGenerator)
  4025. {
  4026. pnodeFnc->cbMin = iecpMin;
  4027. pnodeFnc->ichMin = ichMin;
  4028. }
  4029. if (isComputedName)
  4030. {
  4031. pnodeFnc->SetHasComputedName();
  4032. }
  4033. pnodeFnc->SetHasHomeObj();
  4034. if (buildAST)
  4035. {
  4036. pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFnc);
  4037. }
  4038. }
  4039. else if (useSpread)
  4040. {
  4041. pnodeSpread = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  4042. if (buildAST)
  4043. {
  4044. this->CheckArguments(pnodeSpread);
  4045. }
  4046. }
  4047. else if (nullptr != pidHint) //It's either tkID/tkStrCon/tkFloatCon/tkIntCon
  4048. {
  4049. Assert(pidHint->Psz() != nullptr);
  4050. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&
  4051. // get/set are only pseudo keywords when they are identifiers (i.e. not strings)
  4052. tkHint.tk == tkID && NextTokenIsPropertyNameStart())
  4053. {
  4054. if (isObjectPattern)
  4055. {
  4056. Error(ERRInvalidAssignmentTarget);
  4057. }
  4058. LPCOLESTR pNameGetOrSet = nullptr;
  4059. OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;
  4060. pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet);
  4061. if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->pnode2->nop == knopFncDecl)
  4062. {
  4063. // displays as "get object.funcname" or "set object.funcname"
  4064. uint32 getOrSetOffset = 0;
  4065. LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);
  4066. pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);
  4067. shortNameOffset += getOrSetOffset;
  4068. }
  4069. }
  4070. else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4071. {
  4072. // Shorthand {foo} -> {foo:foo} syntax.
  4073. // {foo = <initializer>} supported only when on object pattern rules are being applied
  4074. if (tkHint.tk != tkID)
  4075. {
  4076. Assert(tkHint.IsReservedWord()
  4077. || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);
  4078. // All keywords are banned in non-strict mode.
  4079. // Future reserved words are banned in strict mode.
  4080. if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))
  4081. {
  4082. IdentifierExpectedError(tkHint);
  4083. }
  4084. }
  4085. if (buildAST)
  4086. {
  4087. CheckArgumentsUse(pidHint, GetCurrentFunctionNode());
  4088. }
  4089. bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;
  4090. // Saving the current state as we may change the isObjectPattern down below.
  4091. bool oldState = isObjectPattern;
  4092. if (couldBeObjectPattern)
  4093. {
  4094. declarationType = tkLCurly;
  4095. isObjectPattern = true;
  4096. // This may be an error but we are deferring for favouring destructuring.
  4097. hasDeferredInitError = true;
  4098. }
  4099. ParseNodePtr pnodeIdent = nullptr;
  4100. if (isObjectPattern)
  4101. {
  4102. this->GetScanner()->SeekTo(atPid);
  4103. pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  4104. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4105. {
  4106. if (m_token.IsOperator())
  4107. {
  4108. Error(ERRDestructNoOper);
  4109. }
  4110. Error(ERRsyntax);
  4111. }
  4112. }
  4113. else
  4114. {
  4115. // Add a reference to the hinted name so we can bind it properly.
  4116. PidRefStack *ref = PushPidRef(pidHint);
  4117. if (buildAST)
  4118. {
  4119. pnodeIdent = CreateNameNode(pidHint, ref, idHintIchMin, idHintIchLim);
  4120. }
  4121. }
  4122. if (buildAST)
  4123. {
  4124. pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);
  4125. }
  4126. isObjectPattern = oldState;
  4127. }
  4128. else
  4129. {
  4130. Error(ERRnoColon);
  4131. }
  4132. }
  4133. else
  4134. {
  4135. Error(ERRnoColon);
  4136. }
  4137. if (buildAST)
  4138. {
  4139. if (useSpread)
  4140. {
  4141. Assert(pnodeSpread != nullptr);
  4142. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeSpread);
  4143. }
  4144. else
  4145. {
  4146. Assert(pnodeArg->pnode2 != nullptr);
  4147. if (pnodeArg->pnode2->nop == knopFncDecl)
  4148. {
  4149. Assert(fullNameHintLength >= shortNameOffset);
  4150. ParseNodeFnc * pnodeFunc = pnodeArg->pnode2->AsParseNodeFnc();
  4151. pnodeFunc->hint = pFullNameHint;
  4152. pnodeFunc->hintLength = fullNameHintLength;
  4153. pnodeFunc->hintOffset = shortNameOffset;
  4154. }
  4155. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  4156. }
  4157. }
  4158. pidHint = nullptr;
  4159. pFullNameHint = nullptr;
  4160. if (tkComma != m_token.tk)
  4161. {
  4162. break;
  4163. }
  4164. this->GetScanner()->ScanForcingPid();
  4165. if (tkRCurly == m_token.tk)
  4166. {
  4167. break;
  4168. }
  4169. }
  4170. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;
  4171. if (buildAST)
  4172. {
  4173. Assert(lastNodeRef);
  4174. Assert(*lastNodeRef);
  4175. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  4176. }
  4177. return pnodeList;
  4178. }
  4179. BOOL Parser::WillDeferParse(Js::LocalFunctionId functionId)
  4180. {
  4181. if ((m_grfscr & fscrWillDeferFncParse) != 0)
  4182. {
  4183. if (m_stoppedDeferredParse)
  4184. {
  4185. return false;
  4186. }
  4187. if (!PHASE_ENABLED_RAW(DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))
  4188. {
  4189. return false;
  4190. }
  4191. if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId)
  4192. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4193. || Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag)
  4194. #endif
  4195. )
  4196. {
  4197. return true;
  4198. }
  4199. #if ENABLE_PROFILE_INFO
  4200. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4201. if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)
  4202. {
  4203. Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);
  4204. return flags != Js::ExecutionFlags_Executed;
  4205. }
  4206. #endif
  4207. #endif
  4208. return true;
  4209. }
  4210. return false;
  4211. }
  4212. //
  4213. // Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred
  4214. // function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.
  4215. //
  4216. BOOL Parser::IsDeferredFnc()
  4217. {
  4218. if (m_grfscr & fscrDeferredFnc)
  4219. {
  4220. m_grfscr &= ~fscrDeferredFnc;
  4221. return true;
  4222. }
  4223. return false;
  4224. }
  4225. template<bool buildAST>
  4226. ParseNode * Parser::ParseFncDeclCheckScope(ushort flags, bool resetParsingSuperRestrictionState, bool fAllowIn)
  4227. {
  4228. ParseNodeBlock * pnodeFncBlockScope = nullptr;
  4229. ParseNodePtr *ppnodeScopeSave = nullptr;
  4230. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4231. bool fDeclaration = flags & fFncDeclaration;
  4232. bool noStmtContext = false;
  4233. if (fDeclaration)
  4234. {
  4235. noStmtContext = m_pstmtCur->GetNop() != knopBlock;
  4236. if (noStmtContext)
  4237. {
  4238. // We have a function declaration like "if (a) function f() {}". We didn't see
  4239. // a block scope on the way in, so we need to pretend we did. Note that this is a syntax error
  4240. // in strict mode.
  4241. if (!this->FncDeclAllowedWithoutContext(flags))
  4242. {
  4243. Error(ERRsyntax);
  4244. }
  4245. pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  4246. if (buildAST)
  4247. {
  4248. PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);
  4249. }
  4250. }
  4251. }
  4252. ParseNodeFnc * pnodeFnc = ParseFncDeclInternal<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan */ false, resetParsingSuperRestrictionState, /* fUnaryOrParen */ false, noStmtContext, fAllowIn);
  4253. if (pnodeFncBlockScope)
  4254. {
  4255. Assert(pnodeFncBlockScope->pnodeStmt == nullptr);
  4256. pnodeFncBlockScope->pnodeStmt = pnodeFnc;
  4257. if (buildAST)
  4258. {
  4259. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  4260. }
  4261. FinishParseBlock(pnodeFncBlockScope);
  4262. return pnodeFncBlockScope;
  4263. }
  4264. return pnodeFnc;
  4265. }
  4266. template<bool buildAST>
  4267. ParseNodeFnc * Parser::ParseFncDeclNoCheckScope(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool resetParsingSuperRestrictionState, bool fUnaryOrParen, bool fAllowIn)
  4268. {
  4269. Assert((flags & fFncDeclaration) == 0);
  4270. return ParseFncDeclInternal<buildAST>(flags, pNameHint, needsPIDOnRCurlyScan, resetParsingSuperRestrictionState, fUnaryOrParen, /* noStmtContext */ false, fAllowIn);
  4271. }
  4272. template<bool buildAST>
  4273. ParseNodeFnc * Parser::ParseFncDeclInternal(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool resetParsingSuperRestrictionState, bool fUnaryOrParen, bool noStmtContext, bool fAllowIn)
  4274. {
  4275. AutoParsingSuperRestrictionStateRestorer restorer(this);
  4276. if (resetParsingSuperRestrictionState)
  4277. {
  4278. // ParseFncDecl will always reset m_parsingSuperRestrictionState to super disallowed unless explicitly disabled
  4279. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperDisallowed;
  4280. }
  4281. ParseNodeFnc * pnodeFnc = nullptr;
  4282. ParseNodePtr *ppnodeVarSave = nullptr;
  4283. bool fDeclaration = flags & fFncDeclaration;
  4284. bool fModule = (flags & fFncModule) != 0;
  4285. bool fLambda = (flags & fFncLambda) != 0;
  4286. charcount_t ichMin = this->GetScanner()->IchMinTok();
  4287. bool wasInDeferredNestedFunc = false;
  4288. uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;
  4289. this->m_tryCatchOrFinallyDepth = 0;
  4290. if (this->m_arrayDepth)
  4291. {
  4292. this->m_funcInArrayDepth++; // Count function depth within array literal
  4293. }
  4294. // Update the count of functions nested in the current parent.
  4295. Assert(m_pnestedCount || !buildAST);
  4296. uint *pnestedCountSave = m_pnestedCount;
  4297. if (buildAST || m_pnestedCount)
  4298. {
  4299. (*m_pnestedCount)++;
  4300. }
  4301. uint scopeCountNoAstSave = m_scopeCountNoAst;
  4302. m_scopeCountNoAst = 0;
  4303. // Create the node.
  4304. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  4305. pnodeFnc->SetDeclaration(fDeclaration);
  4306. pnodeFnc->nestedFuncEscapes = false;
  4307. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  4308. pnodeFnc->functionId = (*m_nextFunctionId)++;
  4309. // Push new parser state with this new function node
  4310. AppendFunctionToScopeList(fDeclaration, pnodeFnc);
  4311. // Start the argument list.
  4312. ppnodeVarSave = m_ppnodeVar;
  4313. if (buildAST)
  4314. {
  4315. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  4316. pnodeFnc->columnNumber = CalculateFunctionColumnNumber();
  4317. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  4318. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  4319. m_pCurrentAstSize = &pnodeFnc->astSize;
  4320. }
  4321. else // if !buildAST
  4322. {
  4323. wasInDeferredNestedFunc = m_inDeferredNestedFunc;
  4324. m_inDeferredNestedFunc = true;
  4325. }
  4326. m_pnestedCount = &pnodeFnc->nestedCount;
  4327. AnalysisAssert(pnodeFnc);
  4328. pnodeFnc->SetIsAsync((flags & fFncAsync) != 0);
  4329. pnodeFnc->SetIsLambda(fLambda);
  4330. pnodeFnc->SetIsMethod((flags & fFncMethod) != 0);
  4331. pnodeFnc->SetIsClassMember((flags & fFncClassMember) != 0);
  4332. pnodeFnc->SetIsModule(fModule);
  4333. pnodeFnc->SetIsClassConstructor((flags & fFncClassConstructor) != 0);
  4334. pnodeFnc->SetIsBaseClassConstructor((flags & fFncBaseClassConstructor) != 0);
  4335. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  4336. IdentPtr pFncNamePid = nullptr;
  4337. bool needScanRCurly = true;
  4338. ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule, &pFncNamePid, fAllowIn);
  4339. AddNestedCapturedNames(pnodeFnc);
  4340. AnalysisAssert(pnodeFnc);
  4341. *m_ppnodeVar = nullptr;
  4342. m_ppnodeVar = ppnodeVarSave;
  4343. if (m_currentNodeFunc && (pnodeFnc->CallsEval() || pnodeFnc->ChildCallsEval()))
  4344. {
  4345. GetCurrentFunctionNode()->SetChildCallsEval(true);
  4346. }
  4347. // Lambdas do not have "arguments" and instead capture their parent's
  4348. // binding of "arguments. To ensure the arguments object of the enclosing
  4349. // non-lambda function is loaded propagate the UsesArguments flag up to
  4350. // the parent function
  4351. if (fLambda && (pnodeFnc->UsesArguments() || pnodeFnc->CallsEval()))
  4352. {
  4353. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4354. if (pnodeFncParent != nullptr)
  4355. {
  4356. pnodeFncParent->SetUsesArguments();
  4357. }
  4358. else
  4359. {
  4360. m_UsesArgumentsAtGlobal = true;
  4361. }
  4362. }
  4363. if (needScanRCurly && !fModule)
  4364. {
  4365. // Consume the next token now that we're back in the enclosing function (whose strictness may be
  4366. // different from the function we just finished).
  4367. #if DBG
  4368. bool expectedTokenValid = m_token.tk == tkRCurly;
  4369. AssertMsg(expectedTokenValid, "Invalid token expected for RCurly match");
  4370. #endif
  4371. // The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.
  4372. if (needsPIDOnRCurlyScan)
  4373. {
  4374. this->GetScanner()->ScanForcingPid();
  4375. }
  4376. else
  4377. {
  4378. this->GetScanner()->Scan();
  4379. }
  4380. }
  4381. m_pnestedCount = pnestedCountSave;
  4382. Assert(!buildAST || !wasInDeferredNestedFunc);
  4383. m_inDeferredNestedFunc = wasInDeferredNestedFunc;
  4384. if (this->m_arrayDepth)
  4385. {
  4386. this->m_funcInArrayDepth--;
  4387. if (this->m_funcInArrayDepth == 0)
  4388. {
  4389. // We disable deferred parsing if array literals dominate.
  4390. // But don't do this if the array literal is dominated by function bodies.
  4391. if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)
  4392. {
  4393. // Class member methods have optional separators. We need to check whether we are
  4394. // getting the IchLim of the correct token.
  4395. Assert(this->GetScanner()->m_tkPrevious == tkRCurly && needScanRCurly);
  4396. this->m_funcInArray += this->GetScanner()->IchMinTok() - /*tkRCurly*/ 1 - ichMin;
  4397. }
  4398. else
  4399. {
  4400. this->m_funcInArray += this->GetScanner()->IchLimTok() - ichMin;
  4401. }
  4402. }
  4403. }
  4404. m_scopeCountNoAst = scopeCountNoAstSave;
  4405. if (fDeclaration && !IsStrictMode())
  4406. {
  4407. if (pFncNamePid != nullptr &&
  4408. GetCurrentBlock() &&
  4409. GetCurrentBlock()->blockType == PnodeBlockType::Regular)
  4410. {
  4411. // Add a function-scoped VarDecl with the same name as the function for
  4412. // back compat with pre-ES6 code that declares functions in blocks. The
  4413. // idea is that the last executed declaration wins at the function scope
  4414. // level and we accomplish this by having each block scoped function
  4415. // declaration assign to both the block scoped "let" binding, as well
  4416. // as the function scoped "var" binding.
  4417. ParseNodeVar * vardecl = CreateVarDeclNode(pFncNamePid, STVariable, false, nullptr, false);
  4418. vardecl->isBlockScopeFncDeclVar = true;
  4419. if (GetCurrentFunctionNode() && vardecl->sym->GetIsFormal())
  4420. {
  4421. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4422. }
  4423. }
  4424. }
  4425. if (buildAST && fDeclaration)
  4426. {
  4427. Symbol* funcSym = pnodeFnc->GetFuncSymbol();
  4428. if (funcSym->GetIsFormal())
  4429. {
  4430. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4431. }
  4432. } this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;
  4433. return pnodeFnc;
  4434. }
  4435. bool Parser::FncDeclAllowedWithoutContext(ushort flags)
  4436. {
  4437. // Statement context required for strict mode, async functions, and generators.
  4438. // Note that generators aren't detected yet when this method is called; they're checked elsewhere.
  4439. return !IsStrictMode() && !(flags & fFncAsync);
  4440. }
  4441. uint Parser::CalculateFunctionColumnNumber()
  4442. {
  4443. uint columnNumber;
  4444. charcount_t ichMinTok = this->GetScanner()->IchMinTok();
  4445. charcount_t ichMinLine = this->GetScanner()->IchMinLine();
  4446. if (ichMinTok >= ichMinLine)
  4447. {
  4448. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  4449. columnNumber = ichMinTok - ichMinLine;
  4450. if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == this->GetScanner()->LineCur())
  4451. {
  4452. // Adjust the column if it falls on the first line, where the re-parse is happening.
  4453. columnNumber += m_functionBody->GetRelativeColumnNumber();
  4454. }
  4455. }
  4456. else if (m_currentNodeFunc)
  4457. {
  4458. // For the first line after defer parse, compute the column relative to the column number
  4459. // of the lexically parent function.
  4460. ULONG offsetFromCurrentFunction = ichMinTok - m_currentNodeFunc->ichMin;
  4461. columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  4462. }
  4463. else
  4464. {
  4465. // if there is no current function, lets give a default of 0.
  4466. columnNumber = 0;
  4467. }
  4468. return columnNumber;
  4469. }
  4470. void Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodeFnc * pnodeFnc)
  4471. {
  4472. if (!fDeclaration && m_ppnodeExprScope)
  4473. {
  4474. // We're tracking function expressions separately from declarations in this scope
  4475. // (e.g., inside a catch scope in standards mode).
  4476. Assert(*m_ppnodeExprScope == nullptr);
  4477. *m_ppnodeExprScope = pnodeFnc;
  4478. m_ppnodeExprScope = &pnodeFnc->pnodeNext;
  4479. }
  4480. else
  4481. {
  4482. Assert(*m_ppnodeScope == nullptr);
  4483. *m_ppnodeScope = pnodeFnc;
  4484. m_ppnodeScope = &pnodeFnc->pnodeNext;
  4485. }
  4486. }
  4487. /***************************************************************************
  4488. Parse a function definition.
  4489. ***************************************************************************/
  4490. template<bool buildAST>
  4491. void Parser::ParseFncDeclHelper(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals, IdentPtr* pFncNamePid, bool fAllowIn)
  4492. {
  4493. Assert(pnodeFnc);
  4494. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4495. // is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred
  4496. ParseNodeFnc * pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4497. ParseNodeFnc * pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;
  4498. int32* pAstSizeSave = m_pCurrentAstSize;
  4499. bool fDeclaration = (flags & fFncDeclaration) != 0;
  4500. bool fLambda = (flags & fFncLambda) != 0;
  4501. bool fAsync = (flags & fFncAsync) != 0;
  4502. bool fModule = (flags & fFncModule) != 0;
  4503. bool fDeferred = false;
  4504. StmtNest *pstmtSave;
  4505. bool fFunctionInBlock = false;
  4506. if (buildAST)
  4507. {
  4508. fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&
  4509. (GetCurrentBlockInfo()->pnodeBlock->scope == nullptr ||
  4510. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock);
  4511. }
  4512. // Save the position of the scanner in case we need to inspect the name hint later
  4513. RestorePoint beginNameHint;
  4514. this->GetScanner()->Capture(&beginNameHint);
  4515. ParseNodeBlock * pnodeFncExprScope = nullptr;
  4516. Scope *fncExprScope = nullptr;
  4517. if (!fDeclaration)
  4518. {
  4519. if (!fLambda)
  4520. {
  4521. pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);
  4522. fncExprScope = pnodeFncExprScope->scope;
  4523. }
  4524. // Function expression: push the new function onto the stack now so that the name (if any) will be
  4525. // local to the new function.
  4526. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4527. }
  4528. if (!fLambda && !fModule)
  4529. {
  4530. this->ParseFncName<buildAST>(pnodeFnc, flags, pFncNamePid);
  4531. }
  4532. if (fDeclaration)
  4533. {
  4534. // Declaration statement: push the new function now, after parsing the name, so the name is local to the
  4535. // enclosing function.
  4536. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4537. }
  4538. if (noStmtContext && pnodeFnc->IsGenerator())
  4539. {
  4540. // Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to
  4541. // detect generator.)
  4542. Error(ERRsyntax, pnodeFnc);
  4543. }
  4544. // switch scanner to treat 'yield' as keyword in generator functions
  4545. // or as an identifier in non-generator functions
  4546. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc->IsGenerator());
  4547. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync);
  4548. if (pnodeFnc->IsGenerator())
  4549. {
  4550. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Generator, m_scriptContext);
  4551. }
  4552. if (fncExprScope && pnodeFnc->pnodeName == nullptr)
  4553. {
  4554. FinishParseBlock(pnodeFncExprScope);
  4555. m_nextBlockId--;
  4556. Adelete(&m_nodeAllocator, fncExprScope);
  4557. fncExprScope = nullptr;
  4558. pnodeFncExprScope = nullptr;
  4559. }
  4560. pnodeFnc->scope = fncExprScope;
  4561. // Start a new statement stack.
  4562. bool topLevelStmt =
  4563. buildAST &&
  4564. !fFunctionInBlock &&
  4565. (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);
  4566. pstmtSave = m_pstmtCur;
  4567. SetCurrentStatement(nullptr);
  4568. RestorePoint beginFormals;
  4569. this->GetScanner()->Capture(&beginFormals);
  4570. BOOL fWasAlreadyStrictMode = IsStrictMode();
  4571. BOOL oldStrictMode = this->m_fUseStrictMode;
  4572. if (fLambda)
  4573. {
  4574. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Lambda, m_scriptContext);
  4575. }
  4576. uint uCanDeferSave = m_grfscr & fscrCanDeferFncParse;
  4577. uint uDeferSave = m_grfscr & fscrWillDeferFncParse;
  4578. if (flags & fFncClassMember)
  4579. {
  4580. // Disable deferral on class members or other construct with unusual text bounds
  4581. // as these are usually trivial, and re-parsing is problematic.
  4582. // NOTE: It is probably worth supporting these cases for memory and load-time purposes,
  4583. // especially as they become more and more common.
  4584. m_grfscr &= ~(fscrCanDeferFncParse | fscrWillDeferFncParse);
  4585. }
  4586. bool isTopLevelDeferredFunc = false;
  4587. #if ENABLE_BACKGROUND_PARSING
  4588. struct AutoFastScanFlag {
  4589. bool savedDoingFastScan;
  4590. AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }
  4591. ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }
  4592. Parser *m_parser;
  4593. } flag(this);
  4594. #endif
  4595. bool doParallel = false;
  4596. #if ENABLE_BACKGROUND_PARSING
  4597. bool parallelJobStarted = false;
  4598. #endif
  4599. if (buildAST)
  4600. {
  4601. bool isLikelyIIFE = !fDeclaration && fUnaryOrParen;
  4602. BOOL isDeferredFnc = IsDeferredFnc();
  4603. // These are the conditions that prohibit upfront deferral *and* redeferral.
  4604. isTopLevelDeferredFunc =
  4605. (m_grfscr & fscrCanDeferFncParse)
  4606. && !m_InAsmMode
  4607. // Don't defer a module function wrapper because we need to do export resolution at parse time
  4608. && !fModule;
  4609. pnodeFnc->SetCanBeDeferred(isTopLevelDeferredFunc && ParseNodeFnc::CanBeRedeferred(pnodeFnc->fncFlags));
  4610. // These are heuristic conditions that prohibit upfront deferral but not redeferral.
  4611. isTopLevelDeferredFunc = isTopLevelDeferredFunc && !isDeferredFnc && WillDeferParse(pnodeFnc->functionId) &&
  4612. (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId));
  4613. #if ENABLE_BACKGROUND_PARSING
  4614. if (!fLambda &&
  4615. !isDeferredFnc &&
  4616. !isLikelyIIFE &&
  4617. !this->IsBackgroundParser() &&
  4618. !this->m_doingFastScan &&
  4619. !(pnodeFncSave && m_currDeferredStub) &&
  4620. !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))
  4621. {
  4622. doParallel = DoParallelParse(pnodeFnc);
  4623. if (doParallel)
  4624. {
  4625. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  4626. Assert(bgp);
  4627. if (bgp->HasFailedBackgroundParseItem())
  4628. {
  4629. Error(ERRsyntax);
  4630. }
  4631. doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);
  4632. if (doParallel)
  4633. {
  4634. parallelJobStarted = true;
  4635. this->m_hasParallelJob = true;
  4636. this->m_doingFastScan = true;
  4637. doParallel = FastScanFormalsAndBody();
  4638. if (doParallel)
  4639. {
  4640. // Let the foreground thread take care of marking the limit on the function node,
  4641. // because in some cases this function's caller will want to change that limit,
  4642. // so we don't want the background thread to try and touch it.
  4643. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  4644. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  4645. }
  4646. }
  4647. }
  4648. }
  4649. #endif
  4650. }
  4651. if (!doParallel)
  4652. {
  4653. #if ENABLE_BACKGROUND_PARSING
  4654. // We don't want to, or couldn't, let the main thread scan past this function body, so parse
  4655. // it for real.
  4656. ParseNodeFnc * pnodeRealFnc = pnodeFnc;
  4657. if (parallelJobStarted)
  4658. {
  4659. // We have to deal with a failure to fast-scan the function (due to syntax error? "/"?) when
  4660. // a background thread may already have begun to work on the job. Both threads can't be allowed to
  4661. // operate on the same node.
  4662. pnodeFnc = CreateDummyFuncNode(fDeclaration);
  4663. }
  4664. #endif
  4665. AnalysisAssert(pnodeFnc);
  4666. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  4667. AnalysisAssert(pnodeBlock != nullptr);
  4668. pnodeFnc->pnodeScopes = pnodeBlock;
  4669. m_ppnodeVar = &pnodeFnc->pnodeParams;
  4670. pnodeFnc->pnodeVars = nullptr;
  4671. ParseNodePtr* varNodesList = &pnodeFnc->pnodeVars;
  4672. ParseNodeVar * argNode = nullptr;
  4673. if (!fModule && !fLambda)
  4674. {
  4675. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  4676. m_ppnodeVar = &pnodeFnc->pnodeVars;
  4677. // Create the built-in arguments symbol
  4678. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  4679. // Save the updated var list
  4680. varNodesList = m_ppnodeVar;
  4681. m_ppnodeVar = ppnodeVarSave;
  4682. }
  4683. ParseNodePtr *ppnodeScopeSave = nullptr;
  4684. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4685. ppnodeScopeSave = m_ppnodeScope;
  4686. if (pnodeBlock)
  4687. {
  4688. // This synthetic block scope will contain all the nested scopes.
  4689. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  4690. pnodeBlock->pnodeStmt = pnodeFnc;
  4691. }
  4692. // Keep nested function declarations and expressions in the same list at function scope.
  4693. // (Indicate this by nulling out the current function expressions list.)
  4694. ppnodeExprScopeSave = m_ppnodeExprScope;
  4695. m_ppnodeExprScope = nullptr;
  4696. uint parenExprDepthSave = m_funcParenExprDepth;
  4697. m_funcParenExprDepth = 0;
  4698. if (!skipFormals)
  4699. {
  4700. bool fLambdaParamsSave = m_reparsingLambdaParams;
  4701. if (fLambda)
  4702. {
  4703. m_reparsingLambdaParams = true;
  4704. }
  4705. DeferredFunctionStub* savedDeferredStub = m_currDeferredStub;
  4706. m_currDeferredStub = nullptr;
  4707. this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags, isTopLevelDeferredFunc);
  4708. m_currDeferredStub = savedDeferredStub;
  4709. m_reparsingLambdaParams = fLambdaParamsSave;
  4710. }
  4711. // Create function body scope
  4712. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  4713. // Set the parameter block's child to the function body block.
  4714. // The pnodeFnc->pnodeScopes list is constructed in such a way that it includes all the scopes in this list.
  4715. // For example if the param scope has one function and body scope has one function then the list will look like below,
  4716. // param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.
  4717. *m_ppnodeScope = pnodeInnerBlock;
  4718. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  4719. // This synthetic block scope will contain all the nested scopes.
  4720. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  4721. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  4722. // DEFER: Begin deferral here (after names are parsed and name nodes created).
  4723. // Create no more AST nodes until we're done.
  4724. // Try to defer this func if all these are true:
  4725. // 0. We are not already in deferred parsing (i.e. buildAST is true)
  4726. // 1. We are not re-parsing a deferred func which is being invoked.
  4727. // 2. Dynamic profile suggests this func can be deferred (and deferred parse is on).
  4728. // 3. This func is top level or defer nested func is on.
  4729. // 4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,
  4730. // or the function is sufficiently long. (I.e., don't defer little nested functions unless we're
  4731. // confident they'll never be executed, because un-deferring nested functions is more expensive.)
  4732. // NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,
  4733. // and we don't want to create function bodies aggressively for little functions.
  4734. // We will also temporarily defer all asm.js functions, except for the asm.js
  4735. // module itself, which we will never defer
  4736. bool strictModeTurnedOn = false;
  4737. if (isTopLevelDeferredFunc &&
  4738. !(this->m_grfscr & fscrEvalCode) &&
  4739. pnodeFnc->IsNested() &&
  4740. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4741. m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&
  4742. #endif
  4743. PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) &&
  4744. (
  4745. !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) ||
  4746. PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId)
  4747. ))
  4748. {
  4749. // Try to scan ahead to the end of the function. If we get there before we've scanned a minimum
  4750. // number of tokens, don't bother deferring, because it's too small.
  4751. if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))
  4752. {
  4753. isTopLevelDeferredFunc = false;
  4754. }
  4755. }
  4756. Scope* paramScope = pnodeFnc->pnodeScopes ? pnodeFnc->pnodeScopes->scope : nullptr;
  4757. if (paramScope != nullptr)
  4758. {
  4759. if (CONFIG_FLAG(ForceSplitScope))
  4760. {
  4761. pnodeFnc->ResetBodyAndParamScopeMerged();
  4762. }
  4763. else if (pnodeFnc->HasNonSimpleParameterList() && pnodeFnc->IsBodyAndParamScopeMerged())
  4764. {
  4765. paramScope->ForEachSymbolUntil([this, paramScope, pnodeFnc](Symbol* sym) {
  4766. if (sym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  4767. {
  4768. // One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.
  4769. pnodeFnc->ResetBodyAndParamScopeMerged();
  4770. return true;
  4771. }
  4772. return false;
  4773. });
  4774. if (pnodeFnc->IsBodyAndParamScopeMerged() && !fDeclaration && pnodeFnc->pnodeName != nullptr)
  4775. {
  4776. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  4777. Symbol* funcSym = pnodeFnc->pnodeName->sym;
  4778. if (funcSym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  4779. {
  4780. // This is a function expression with name captured in the param scope. In non-eval, non-split cases the function
  4781. // name symbol is added to the body scope to make it accessible in the body. But if there is a function or var
  4782. // declaration with the same name in the body then adding to the body will fail. So in this case we have to add
  4783. // the name symbol to the param scope by splitting it.
  4784. pnodeFnc->ResetBodyAndParamScopeMerged();
  4785. }
  4786. }
  4787. }
  4788. }
  4789. // If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.
  4790. // So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice
  4791. // in the same pid ref stack.
  4792. if (paramScope != nullptr && pnodeFnc->IsBodyAndParamScopeMerged())
  4793. {
  4794. paramScope->ForEachSymbol([this](Symbol* paramSym)
  4795. {
  4796. PidRefStack* ref = PushPidRef(paramSym->GetPid());
  4797. ref->SetSym(paramSym);
  4798. });
  4799. }
  4800. AssertMsg(m_funcParenExprDepth == 0, "Paren exprs should have been resolved by the time we finish function formals");
  4801. if (fLambda)
  4802. {
  4803. #ifdef ASMJS_PLAT
  4804. if (m_InAsmMode && (isTopLevelDeferredFunc && m_deferAsmJs))
  4805. {
  4806. // asm.js doesn't support lambda functions
  4807. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Lambda functions are not supported."));
  4808. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Asm.js compilation failed."));
  4809. throw Js::AsmJsParseException();
  4810. }
  4811. #endif
  4812. }
  4813. if (m_token.tk == tkRParen)
  4814. {
  4815. this->GetScanner()->Scan();
  4816. }
  4817. if (fLambda)
  4818. {
  4819. BOOL hadNewLine = this->GetScanner()->FHadNewLine();
  4820. // it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side
  4821. // of the fat arrow, but that expression does not parse as a parameter list. E.g.
  4822. // a.x => { }
  4823. // Therefore check for it and error if not found.
  4824. ChkCurTok(tkDArrow, ERRnoDArrow);
  4825. // Newline character between arrow parameters and fat arrow is a syntax error but we want to check for
  4826. // this after verifying there was a => token. Otherwise we would throw the wrong error.
  4827. if (hadNewLine)
  4828. {
  4829. Error(ERRsyntax);
  4830. }
  4831. }
  4832. if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))
  4833. {
  4834. fDeferred = true;
  4835. this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint, fLambda, pNeedScanRCurly, fAllowIn);
  4836. }
  4837. else
  4838. {
  4839. AnalysisAssert(pnodeFnc);
  4840. // Shouldn't be any temps in the arg list.
  4841. Assert(*m_ppnodeVar == nullptr);
  4842. // Start the var list.
  4843. m_ppnodeVar = varNodesList;
  4844. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  4845. {
  4846. 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"));
  4847. }
  4848. // Keep nested function declarations and expressions in the same list at function scope.
  4849. // (Indicate this by nulling out the current function expressions list.)
  4850. m_ppnodeExprScope = nullptr;
  4851. if (buildAST)
  4852. {
  4853. if (m_token.tk != tkLCurly && fLambda)
  4854. {
  4855. *pNeedScanRCurly = false;
  4856. }
  4857. uint savedStubCount = m_currDeferredStubCount;
  4858. DeferredFunctionStub* savedStub = m_currDeferredStub;
  4859. if (pnodeFnc->IsNested() && pnodeFncSave != nullptr && m_currDeferredStub != nullptr && pnodeFncSave->ichMin != pnodeFnc->ichMin)
  4860. {
  4861. DeferredFunctionStub* childStub = m_currDeferredStub + (pnodeFncSave->nestedCount - 1);
  4862. m_currDeferredStubCount = childStub->nestedCount;
  4863. m_currDeferredStub = childStub->deferredStubs;
  4864. }
  4865. this->FinishFncDecl(pnodeFnc, pNameHint, fLambda, skipFormals, fAllowIn);
  4866. m_currDeferredStub = savedStub;
  4867. m_currDeferredStubCount = savedStubCount;
  4868. }
  4869. else
  4870. {
  4871. this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn, fAllowIn);
  4872. }
  4873. }
  4874. // Restore the paren count for any outer spread/rest error checking.
  4875. m_funcParenExprDepth = parenExprDepthSave;
  4876. if (pnodeInnerBlock)
  4877. {
  4878. FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);
  4879. }
  4880. if (!fModule && (m_token.tk == tkLCurly || !fLambda))
  4881. {
  4882. UpdateArgumentsNode(pnodeFnc, argNode);
  4883. }
  4884. CreateSpecialSymbolDeclarations(pnodeFnc);
  4885. // Restore the lists of scopes that contain function expressions.
  4886. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  4887. m_ppnodeExprScope = ppnodeExprScopeSave;
  4888. Assert(m_ppnodeScope);
  4889. Assert(nullptr == *m_ppnodeScope);
  4890. m_ppnodeScope = ppnodeScopeSave;
  4891. if (pnodeBlock)
  4892. {
  4893. FinishParseBlock(pnodeBlock, *pNeedScanRCurly);
  4894. }
  4895. if (IsStrictMode() || strictModeTurnedOn)
  4896. {
  4897. this->m_fUseStrictMode = TRUE; // Now we know this function is in strict mode
  4898. if (!fWasAlreadyStrictMode)
  4899. {
  4900. // If this function turned on strict mode then we didn't check the formal
  4901. // parameters or function name hint for future reserved word usage. So do that now.
  4902. RestorePoint afterFnc;
  4903. this->GetScanner()->Capture(&afterFnc);
  4904. if (pnodeFnc->pnodeName != nullptr)
  4905. {
  4906. // Rewind to the function name hint and check if the token is a reserved word.
  4907. this->GetScanner()->SeekTo(beginNameHint);
  4908. this->GetScanner()->Scan();
  4909. if (pnodeFnc->IsGenerator())
  4910. {
  4911. Assert(m_token.tk == tkStar);
  4912. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  4913. Assert(!(flags & fFncClassMember));
  4914. this->GetScanner()->Scan();
  4915. }
  4916. if (m_token.IsReservedWord())
  4917. {
  4918. IdentifierExpectedError(m_token);
  4919. }
  4920. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  4921. }
  4922. // Fast forward to formal parameter list, check for future reserved words,
  4923. // then restore scanner as it was.
  4924. this->GetScanner()->SeekToForcingPid(beginFormals);
  4925. CheckStrictFormalParameters();
  4926. this->GetScanner()->SeekTo(afterFnc);
  4927. }
  4928. if (buildAST)
  4929. {
  4930. if (pnodeFnc->pnodeName != nullptr)
  4931. {
  4932. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  4933. CheckStrictModeEvalArgumentsUsage(pnodeFnc->pnodeName->pid, pnodeFnc->pnodeName);
  4934. }
  4935. }
  4936. this->m_fUseStrictMode = oldStrictMode;
  4937. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StrictModeFunction, m_scriptContext);
  4938. }
  4939. ProcessCapturedNames(pnodeFnc);
  4940. if (fDeferred)
  4941. {
  4942. AnalysisAssert(pnodeFnc);
  4943. pnodeFnc->pnodeVars = nullptr;
  4944. }
  4945. #if ENABLE_BACKGROUND_PARSING
  4946. if (parallelJobStarted)
  4947. {
  4948. pnodeFnc = pnodeRealFnc;
  4949. m_currentNodeFunc = pnodeRealFnc;
  4950. // Let the foreground thread take care of marking the limit on the function node,
  4951. // because in some cases this function's caller will want to change that limit,
  4952. // so we don't want the background thread to try and touch it.
  4953. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  4954. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  4955. }
  4956. #endif
  4957. }
  4958. // after parsing asm.js module, we want to reset asm.js state before continuing
  4959. AnalysisAssert(pnodeFnc);
  4960. if (pnodeFnc->GetAsmjsMode())
  4961. {
  4962. m_InAsmMode = false;
  4963. }
  4964. // Restore the statement stack.
  4965. Assert(nullptr == m_pstmtCur);
  4966. SetCurrentStatement(pstmtSave);
  4967. if (pnodeFncExprScope)
  4968. {
  4969. FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);
  4970. }
  4971. m_grfscr |= uCanDeferSave;
  4972. if (!m_stoppedDeferredParse)
  4973. {
  4974. m_grfscr |= uDeferSave;
  4975. }
  4976. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  4977. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  4978. // Restore the current function.
  4979. if (buildAST)
  4980. {
  4981. Assert(pnodeFnc == m_currentNodeFunc);
  4982. m_currentNodeFunc = pnodeFncSave;
  4983. m_pCurrentAstSize = pAstSizeSave;
  4984. if (!fLambda)
  4985. {
  4986. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  4987. m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;
  4988. }
  4989. }
  4990. else
  4991. {
  4992. Assert(pnodeFnc == m_currentNodeDeferredFunc);
  4993. if (!fLambda)
  4994. {
  4995. Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);
  4996. m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;
  4997. }
  4998. m_currentNodeDeferredFunc = pnodeFncSave;
  4999. }
  5000. if (m_currentNodeFunc && pnodeFnc->HasWithStmt())
  5001. {
  5002. GetCurrentFunctionNode()->SetHasWithStmt(true);
  5003. }
  5004. }
  5005. template<bool buildAST>
  5006. void Parser::UpdateCurrentNodeFunc(ParseNodeFnc * pnodeFnc, bool fLambda)
  5007. {
  5008. if (buildAST)
  5009. {
  5010. // Make this the current function and start its sub-function list.
  5011. m_currentNodeFunc = pnodeFnc;
  5012. Assert(m_currentNodeDeferredFunc == nullptr);
  5013. if (!fLambda)
  5014. {
  5015. m_currentNodeNonLambdaFunc = pnodeFnc;
  5016. }
  5017. }
  5018. else // if !buildAST
  5019. {
  5020. AnalysisAssert(pnodeFnc);
  5021. if (!fLambda)
  5022. {
  5023. m_currentNodeNonLambdaDeferredFunc = pnodeFnc;
  5024. }
  5025. m_currentNodeDeferredFunc = pnodeFnc;
  5026. }
  5027. }
  5028. void Parser::ParseTopLevelDeferredFunc(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeFncParent, LPCOLESTR pNameHint, bool fLambda, bool *pNeedScanRCurly, bool fAllowIn)
  5029. {
  5030. // Parse a function body that is a transition point from building AST to doing fast syntax check.
  5031. pnodeFnc->pnodeVars = nullptr;
  5032. pnodeFnc->pnodeBody = nullptr;
  5033. this->m_deferringAST = TRUE;
  5034. // Put the scanner into "no hashing" mode.
  5035. BYTE deferFlags = this->GetScanner()->SetDeferredParse(TRUE);
  5036. if (!fLambda)
  5037. {
  5038. ChkCurTok(tkLCurly, ERRnoLcurly);
  5039. }
  5040. else
  5041. {
  5042. // Lambda may consist of a single expression instead of a block
  5043. if (this->GetScanner()->m_ptoken->tk == tkLCurly)
  5044. {
  5045. this->GetScanner()->Scan();
  5046. }
  5047. else
  5048. {
  5049. *pNeedScanRCurly = false;
  5050. }
  5051. }
  5052. ParseNodePtr *ppnodeVarSave = m_ppnodeVar;
  5053. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5054. // Don't try and skip scanning nested deferred lambdas which have only a single expression in the body.
  5055. // Their more-complicated text extents won't match the deferred-stub and the single expression should be fast to scan, anyway.
  5056. if (fLambda && !*pNeedScanRCurly)
  5057. {
  5058. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5059. }
  5060. else if (pnodeFncParent != nullptr && m_currDeferredStub != nullptr && !pnodeFncParent->HasDefaultArguments())
  5061. {
  5062. // We've already parsed this function body for syntax errors on the initial parse of the script.
  5063. // We have information that allows us to skip it, so do so.
  5064. Assert(pnodeFncParent->nestedCount != 0);
  5065. DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->nestedCount - 1);
  5066. Assert(pnodeFnc->ichMin == stub->ichMin
  5067. || (stub->fncFlags & kFunctionIsAsync) == kFunctionIsAsync
  5068. || ((stub->fncFlags & kFunctionIsGenerator) == kFunctionIsGenerator && (stub->fncFlags & kFunctionIsMethod) == kFunctionIsMethod));
  5069. if (stub->fncFlags & kFunctionCallsEval)
  5070. {
  5071. this->MarkEvalCaller();
  5072. }
  5073. PHASE_PRINT_TRACE1(
  5074. Js::SkipNestedDeferredPhase,
  5075. _u("Skipping nested deferred function %d. %s: %d...%d\n"),
  5076. pnodeFnc->functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);
  5077. this->GetScanner()->SeekTo(stub->restorePoint, m_nextFunctionId);
  5078. for (uint i = 0; i < stub->capturedNameCount; i++)
  5079. {
  5080. int stringId = stub->capturedNameSerializedIds[i];
  5081. uint32 stringLength = 0;
  5082. LPCWSTR stringVal = Js::ByteCodeSerializer::DeserializeString(stub, stringId, stringLength);
  5083. OUTPUT_TRACE_DEBUGONLY(Js::SkipNestedDeferredPhase, _u("\tPushing a reference to '%s'\n"), stringVal);
  5084. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(stringVal, stringLength);
  5085. PushPidRef(pid);
  5086. }
  5087. pnodeFnc->nestedCount = stub->nestedCount;
  5088. pnodeFnc->deferredStub = stub->deferredStubs;
  5089. pnodeFnc->fncFlags = (FncFlags)(pnodeFnc->fncFlags | stub->fncFlags);
  5090. }
  5091. else
  5092. {
  5093. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */);
  5094. }
  5095. if (!fLambda || *pNeedScanRCurly)
  5096. {
  5097. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5098. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5099. }
  5100. m_ppnodeVar = ppnodeVarSave;
  5101. // Restore the scanner's default hashing mode.
  5102. // Do this before we consume the next token.
  5103. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  5104. if (*pNeedScanRCurly)
  5105. {
  5106. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5107. }
  5108. #if DBG
  5109. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  5110. #endif
  5111. this->m_deferringAST = FALSE;
  5112. }
  5113. bool Parser::DoParallelParse(ParseNodeFnc * pnodeFnc) const
  5114. {
  5115. #if ENABLE_BACKGROUND_PARSING
  5116. if (!PHASE_ENABLED_RAW(ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId))
  5117. {
  5118. return false;
  5119. }
  5120. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  5121. return bgp != nullptr;
  5122. #else
  5123. return false;
  5124. #endif
  5125. }
  5126. bool Parser::ScanAheadToFunctionEnd(uint count)
  5127. {
  5128. bool found = false;
  5129. uint curlyDepth = 0;
  5130. RestorePoint funcStart;
  5131. this->GetScanner()->Capture(&funcStart);
  5132. for (uint i = 0; i < count; i++)
  5133. {
  5134. switch (m_token.tk)
  5135. {
  5136. case tkStrTmplBegin:
  5137. case tkStrTmplMid:
  5138. case tkStrTmplEnd:
  5139. case tkDiv:
  5140. case tkAsgDiv:
  5141. case tkScanError:
  5142. case tkEOF:
  5143. goto LEnd;
  5144. case tkLCurly:
  5145. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5146. break;
  5147. case tkRCurly:
  5148. if (curlyDepth == 1)
  5149. {
  5150. found = true;
  5151. goto LEnd;
  5152. }
  5153. if (curlyDepth == 0)
  5154. {
  5155. goto LEnd;
  5156. }
  5157. curlyDepth--;
  5158. break;
  5159. }
  5160. this->GetScanner()->ScanAhead();
  5161. }
  5162. LEnd:
  5163. this->GetScanner()->SeekTo(funcStart);
  5164. return found;
  5165. }
  5166. #if ENABLE_BACKGROUND_PARSING
  5167. bool Parser::FastScanFormalsAndBody()
  5168. {
  5169. // The scanner is currently pointing just past the name of a function.
  5170. // The idea here is to find the end of the function body as quickly as possible,
  5171. // by tokenizing and tracking {}'s if possible.
  5172. // String templates require some extra logic but can be handled.
  5173. // The real wrinkle is "/" and "/=", which may indicate either a RegExp literal or a division, depending
  5174. // on the context.
  5175. // To handle this with minimal work, keep track of the last ";" seen at each {} depth. If we see one of the
  5176. // difficult tokens, rewind to the last ";" at the current {} depth and parse statements until we pass the
  5177. // point where we had to rewind. This will process the "/" as required.
  5178. RestorePoint funcStart;
  5179. this->GetScanner()->Capture(&funcStart);
  5180. const int maxRestorePointDepth = 16;
  5181. struct FastScanRestorePoint
  5182. {
  5183. RestorePoint restorePoint;
  5184. uint parenDepth;
  5185. Js::LocalFunctionId functionId;
  5186. int blockId;
  5187. FastScanRestorePoint() : restorePoint(), parenDepth(0) {};
  5188. };
  5189. FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];
  5190. charcount_t ichStart = this->GetScanner()->IchMinTok();
  5191. uint blockIdSave = m_nextBlockId;
  5192. uint functionIdSave = *m_nextFunctionId;
  5193. uint curlyDepth = 0;
  5194. uint strTmplDepth = 0;
  5195. for (;;)
  5196. {
  5197. switch (m_token.tk)
  5198. {
  5199. case tkStrTmplBegin:
  5200. UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);
  5201. // Fall through
  5202. case tkStrTmplMid:
  5203. case tkLCurly:
  5204. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5205. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5206. break;
  5207. case tkStrTmplEnd:
  5208. // We can assert here, because the scanner will only return this token if we've told it we're
  5209. // in a string template.
  5210. Assert(strTmplDepth > 0);
  5211. strTmplDepth--;
  5212. break;
  5213. case tkRCurly:
  5214. if (curlyDepth == 1)
  5215. {
  5216. Assert(strTmplDepth == 0);
  5217. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5218. {
  5219. Output::Print(_u("Finished fast seek: %d. %s -- %d...%d\n"),
  5220. m_currentNodeFunc->functionId,
  5221. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5222. ichStart, this->GetScanner()->IchLimTok());
  5223. }
  5224. return true;
  5225. }
  5226. if (curlyDepth < maxRestorePointDepth)
  5227. {
  5228. lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;
  5229. }
  5230. curlyDepth--;
  5231. if (strTmplDepth > 0)
  5232. {
  5233. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  5234. }
  5235. break;
  5236. case tkSColon:
  5237. // Track the location of the ";" (if it's outside parens, as we don't, for instance, want
  5238. // to track the ";"'s in a for-loop header. If we find it's important to rewind within a paren
  5239. // expression, we can do something more sophisticated.)
  5240. if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)
  5241. {
  5242. this->GetScanner()->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);
  5243. lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;
  5244. lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;
  5245. }
  5246. break;
  5247. case tkLParen:
  5248. if (curlyDepth < maxRestorePointDepth)
  5249. {
  5250. UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);
  5251. }
  5252. break;
  5253. case tkRParen:
  5254. if (curlyDepth < maxRestorePointDepth)
  5255. {
  5256. Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);
  5257. lastSColonAtCurlyDepth[curlyDepth].parenDepth--;
  5258. }
  5259. break;
  5260. case tkID:
  5261. {
  5262. charcount_t tokLength = this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok();
  5263. // Detect the function and class keywords so we can track function ID's.
  5264. // (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token
  5265. // to a PID.)
  5266. // Detect try/catch/for to increment block count for them.
  5267. switch (tokLength)
  5268. {
  5269. case 3:
  5270. if (!memcmp(this->GetScanner()->PchMinTok(), "try", 3) || !memcmp(this->GetScanner()->PchMinTok(), "for", 3))
  5271. {
  5272. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5273. }
  5274. break;
  5275. case 5:
  5276. if (!memcmp(this->GetScanner()->PchMinTok(), "catch", 5))
  5277. {
  5278. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5279. }
  5280. else if (!memcmp(this->GetScanner()->PchMinTok(), "class", 5))
  5281. {
  5282. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5283. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5284. }
  5285. break;
  5286. case 8:
  5287. if (!memcmp(this->GetScanner()->PchMinTok(), "function", 8))
  5288. {
  5289. // Account for the possible func expr scope or dummy block for missing {}'s around a declaration
  5290. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5291. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5292. }
  5293. break;
  5294. }
  5295. break;
  5296. }
  5297. case tkDArrow:
  5298. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5299. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5300. break;
  5301. case tkDiv:
  5302. case tkAsgDiv:
  5303. {
  5304. int opl;
  5305. OpCode nop;
  5306. tokens tkPrev = this->GetScanner()->m_tkPrevious;
  5307. if ((this->GetHashTbl()->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||
  5308. (this->GetHashTbl()->TokIsUnop(tkPrev, &opl, &nop) &&
  5309. nop != knopNone &&
  5310. tkPrev != tkInc &&
  5311. tkPrev != tkDec) ||
  5312. tkPrev == tkColon ||
  5313. tkPrev == tkLParen ||
  5314. tkPrev == tkLBrack ||
  5315. tkPrev == tkRETURN)
  5316. {
  5317. // Previous token indicates that we're starting an expression here and can't have a
  5318. // binary operator now.
  5319. // Assume this is a RegExp.
  5320. ParseRegExp<false>();
  5321. break;
  5322. }
  5323. uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;
  5324. for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)
  5325. {
  5326. // We don't know whether we've got a RegExp or a divide. Rewind to the last safe ";"
  5327. // if we can and parse statements until we pass this point.
  5328. if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)
  5329. {
  5330. break;
  5331. }
  5332. }
  5333. if (tempCurlyDepth != (uint)-1)
  5334. {
  5335. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5336. int32 *pastSizeSave = m_pCurrentAstSize;
  5337. uint *pnestedCountSave = m_pnestedCount;
  5338. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  5339. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  5340. ParseNodeFnc * pnodeFnc = CreateDummyFuncNode(true);
  5341. charcount_t ichStop = this->GetScanner()->IchLimTok();
  5342. curlyDepth = tempCurlyDepth;
  5343. this->GetScanner()->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);
  5344. m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;
  5345. *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;
  5346. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5347. pnodeFnc->pnodeScopes = pnodeBlock;
  5348. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  5349. m_ppnodeExprScope = nullptr;
  5350. this->GetScanner()->Scan();
  5351. do
  5352. {
  5353. ParseStatement<false>();
  5354. } while (this->GetScanner()->IchMinTok() < ichStop);
  5355. FinishParseBlock(pnodeBlock);
  5356. m_currentNodeFunc = pnodeFncSave;
  5357. m_pCurrentAstSize = pastSizeSave;
  5358. m_pnestedCount = pnestedCountSave;
  5359. m_ppnodeScope = ppnodeScopeSave;
  5360. m_ppnodeExprScope = ppnodeExprScopeSave;
  5361. // We've already consumed the first token of the next statement, so just continue
  5362. // without a further scan.
  5363. continue;
  5364. }
  5365. }
  5366. // fall through to rewind to function start
  5367. case tkScanError:
  5368. case tkEOF:
  5369. // Unexpected token.
  5370. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5371. {
  5372. Output::Print(_u("Failed fast seek: %d. %s -- %d...%d\n"),
  5373. m_currentNodeFunc->functionId,
  5374. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5375. ichStart, this->GetScanner()->IchLimTok());
  5376. }
  5377. m_nextBlockId = blockIdSave;
  5378. *m_nextFunctionId = functionIdSave;
  5379. this->GetScanner()->SeekTo(funcStart);
  5380. return false;
  5381. }
  5382. this->GetScanner()->ScanNoKeywords();
  5383. }
  5384. }
  5385. #endif
  5386. ParseNodeFnc * Parser::CreateDummyFuncNode(bool fDeclaration)
  5387. {
  5388. // Create a dummy node and make it look like the current function declaration.
  5389. // Do this in situations where we want to parse statements without impacting
  5390. // the state of the "real" AST.
  5391. ParseNodeFnc * pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5392. pnodeFnc->SetDeclaration(fDeclaration);
  5393. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  5394. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  5395. m_pCurrentAstSize = &pnodeFnc->astSize;
  5396. m_currentNodeFunc = pnodeFnc;
  5397. m_pnestedCount = &pnodeFnc->nestedCount;
  5398. return pnodeFnc;
  5399. }
  5400. void Parser::ParseNestedDeferredFunc(ParseNodeFnc * pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn, bool fAllowIn)
  5401. {
  5402. // Parse a function nested inside another deferred function.
  5403. size_t lengthBeforeBody = this->GetSourceLength();
  5404. if (m_token.tk != tkLCurly && fLambda)
  5405. {
  5406. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5407. *pNeedScanRCurly = false;
  5408. }
  5409. else
  5410. {
  5411. ChkCurTok(tkLCurly, ERRnoLcurly);
  5412. bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;
  5413. m_ppnodeVar = &m_currentNodeDeferredFunc->pnodeVars;
  5414. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */, detectStrictModeOn);
  5415. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5416. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5417. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5418. }
  5419. if (*pStrictModeTurnedOn)
  5420. {
  5421. pnodeFnc->SetStrictMode(true);
  5422. }
  5423. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  5424. {
  5425. // Record the end of the function and the function ID increment that happens inside the function.
  5426. // Byte code gen will use this to build stub information to allow us to skip this function when the
  5427. // enclosing function is fully parsed.
  5428. RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);
  5429. this->GetScanner()->Capture(restorePoint,
  5430. *m_nextFunctionId - pnodeFnc->functionId - 1,
  5431. lengthBeforeBody - this->GetSourceLength());
  5432. pnodeFnc->pRestorePoint = restorePoint;
  5433. }
  5434. }
  5435. template<bool buildAST>
  5436. void Parser::ParseFncName(ParseNodeFnc * pnodeFnc, ushort flags, IdentPtr* pFncNamePid)
  5437. {
  5438. Assert(pnodeFnc);
  5439. BOOL fDeclaration = flags & fFncDeclaration;
  5440. BOOL fIsAsync = flags & fFncAsync;
  5441. this->GetScanner()->Scan();
  5442. // If generators are enabled then we are in a recent enough version
  5443. // that deferred parsing will create a parse node for pnodeFnc and
  5444. // it is safe to assume it is not null.
  5445. if (flags & fFncGenerator)
  5446. {
  5447. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5448. pnodeFnc->SetIsGenerator();
  5449. }
  5450. else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  5451. m_token.tk == tkStar &&
  5452. !(flags & fFncClassMember))
  5453. {
  5454. if (!fDeclaration)
  5455. {
  5456. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(!fDeclaration);
  5457. this->GetScanner()->Scan();
  5458. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5459. }
  5460. else
  5461. {
  5462. this->GetScanner()->Scan();
  5463. }
  5464. pnodeFnc->SetIsGenerator();
  5465. }
  5466. if (fIsAsync)
  5467. {
  5468. if (pnodeFnc->IsGenerator())
  5469. {
  5470. Error(ERRsyntax);
  5471. }
  5472. pnodeFnc->SetIsAsync();
  5473. }
  5474. pnodeFnc->pnodeName = nullptr;
  5475. if ((m_token.tk != tkID || flags & fFncNoName)
  5476. && (IsStrictMode() || fDeclaration
  5477. || pnodeFnc->IsGenerator() || pnodeFnc->IsAsync()
  5478. || (m_token.tk != tkYIELD && m_token.tk != tkAWAIT))) // Function expressions can have the name yield/await even inside generator/async functions
  5479. {
  5480. if (fDeclaration ||
  5481. m_token.IsReservedWord()) // For example: var x = (function break(){});
  5482. {
  5483. IdentifierExpectedError(m_token);
  5484. }
  5485. return;
  5486. }
  5487. Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration) || (m_token.tk == tkAWAIT && !fDeclaration));
  5488. if (IsStrictMode())
  5489. {
  5490. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  5491. }
  5492. IdentPtr pidBase = m_token.GetIdentifier(this->GetHashTbl());
  5493. pnodeFnc->pnodeName = CreateDeclNode(knopVarDecl, pidBase, STFunction);
  5494. pnodeFnc->pid = pnodeFnc->pnodeName->pid;
  5495. if (pFncNamePid != nullptr)
  5496. {
  5497. *pFncNamePid = pidBase;
  5498. }
  5499. this->GetScanner()->Scan();
  5500. }
  5501. void Parser::ValidateFormals()
  5502. {
  5503. ParseFncFormals<false>(this->GetCurrentFunctionNode(), nullptr, fFncNoFlgs);
  5504. // Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.
  5505. this->GetScanner()->Scan();
  5506. }
  5507. void Parser::ValidateSourceElementList()
  5508. {
  5509. ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);
  5510. }
  5511. void Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)
  5512. {
  5513. bool isStrictMode = IsStrictMode();
  5514. if (isStrictMode)
  5515. {
  5516. CheckStrictModeEvalArgumentsUsage(pid);
  5517. }
  5518. if (formals->Has(pid))
  5519. {
  5520. if (isStrictMode)
  5521. {
  5522. Error(ERRES5ArgSame);
  5523. }
  5524. else
  5525. {
  5526. Error(ERRFormalSame);
  5527. }
  5528. }
  5529. else
  5530. {
  5531. formals->Prepend(pid);
  5532. }
  5533. }
  5534. template<bool buildAST>
  5535. void Parser::ParseFncFormals(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeParentFnc, ushort flags, bool isTopLevelDeferredFunc)
  5536. {
  5537. bool fLambda = (flags & fFncLambda) != 0;
  5538. bool fMethod = (flags & fFncMethod) != 0;
  5539. bool fNoArg = (flags & fFncNoArg) != 0;
  5540. bool fOneArg = (flags & fFncOneArg) != 0;
  5541. bool fAsync = (flags & fFncAsync) != 0;
  5542. bool fPreviousYieldIsKeyword = false;
  5543. bool fPreviousAwaitIsKeyword = false;
  5544. if (fLambda)
  5545. {
  5546. fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeParentFnc != nullptr && pnodeParentFnc->IsGenerator());
  5547. fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->IsAsync()));
  5548. }
  5549. Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.
  5550. // strictFormals corresponds to the StrictFormalParameters grammar production
  5551. // in the ES spec which just means duplicate names are not allowed
  5552. bool fStrictFormals = IsStrictMode() || fLambda || fMethod;
  5553. // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
  5554. bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
  5555. AutoTempForcePid autoForcePid(this->GetScanner(), forcePid);
  5556. // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
  5557. if (fLambda && m_token.tk == tkID)
  5558. {
  5559. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5560. CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5561. CheckPidIsValid(pid);
  5562. this->GetScanner()->Scan();
  5563. if (m_token.tk != tkDArrow)
  5564. {
  5565. Error(ERRsyntax, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  5566. }
  5567. if (fLambda)
  5568. {
  5569. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5570. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5571. }
  5572. return;
  5573. }
  5574. else if (fLambda && m_token.tk == tkAWAIT)
  5575. {
  5576. // async await => {}
  5577. IdentifierExpectedError(m_token);
  5578. }
  5579. // Otherwise, must have a parameter list within parens.
  5580. ChkCurTok(tkLParen, ERRnoLparen);
  5581. // Now parse the list of arguments, if present
  5582. if (m_token.tk == tkRParen)
  5583. {
  5584. if (fOneArg)
  5585. {
  5586. Error(ERRSetterMustHaveOneParameter);
  5587. }
  5588. }
  5589. else
  5590. {
  5591. if (fNoArg)
  5592. {
  5593. Error(ERRGetterMustHaveNoParameters);
  5594. }
  5595. SList<IdentPtr> formals(&m_nodeAllocator);
  5596. ParseNodeVar * pnodeT = nullptr;
  5597. bool seenRestParameter = false;
  5598. bool isNonSimpleParameterList = false;
  5599. for (Js::ArgSlot argPos = 0; ; ++argPos)
  5600. {
  5601. bool isBindingPattern = false;
  5602. if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
  5603. {
  5604. // Possible rest parameter
  5605. this->GetScanner()->Scan();
  5606. seenRestParameter = true;
  5607. }
  5608. if (m_token.tk != tkID)
  5609. {
  5610. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  5611. {
  5612. // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
  5613. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5614. this->GetCurrentFunctionNode()->SetHasDestructuredParams();
  5615. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5616. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5617. ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
  5618. Assert(ppNodeLex != nullptr);
  5619. ParseNodeParamPattern * paramPattern = nullptr;
  5620. ParseNode * pnodePattern = nullptr;
  5621. if (isTopLevelDeferredFunc)
  5622. {
  5623. pnodePattern = ParseDestructuredLiteral<false>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5624. }
  5625. else
  5626. {
  5627. pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5628. }
  5629. // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
  5630. for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->AsParseNodeVar()->pnodeNext)
  5631. {
  5632. Assert(lexNode->IsVarLetOrConst());
  5633. UpdateOrCheckForDuplicateInFormals(lexNode->AsParseNodeVar()->pid, &formals);
  5634. lexNode->AsParseNodeVar()->sym->SetSymbolType(STFormal);
  5635. if (lexNode->AsParseNodeVar()->pid == wellKnownPropertyPids.arguments)
  5636. {
  5637. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5638. }
  5639. }
  5640. m_ppnodeVar = ppnodeVarSave;
  5641. if (buildAST)
  5642. {
  5643. if (isTopLevelDeferredFunc)
  5644. {
  5645. Assert(pnodePattern == nullptr);
  5646. // Create a dummy pattern node as we need the node to be considered for the param count
  5647. paramPattern = CreateDummyParamPatternNode(this->GetScanner()->IchMinTok());
  5648. }
  5649. else
  5650. {
  5651. Assert(pnodePattern);
  5652. paramPattern = CreateParamPatternNode(pnodePattern);
  5653. }
  5654. // Linking the current formal parameter (which is pattern parameter) with other formals.
  5655. *m_ppnodeVar = paramPattern;
  5656. paramPattern->pnodeNext = nullptr;
  5657. m_ppnodeVar = &paramPattern->pnodeNext;
  5658. }
  5659. isBindingPattern = true;
  5660. isNonSimpleParameterList = true;
  5661. }
  5662. else
  5663. {
  5664. IdentifierExpectedError(m_token);
  5665. }
  5666. }
  5667. if (!isBindingPattern)
  5668. {
  5669. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5670. LPCOLESTR pNameHint = pid->Psz();
  5671. uint32 nameHintLength = pid->Cch();
  5672. uint32 nameHintOffset = 0;
  5673. if (seenRestParameter)
  5674. {
  5675. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5676. if (flags & fFncOneArg)
  5677. {
  5678. // The parameter of a setter cannot be a rest parameter.
  5679. Error(ERRUnexpectedEllipsis);
  5680. }
  5681. pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
  5682. pnodeT->sym->SetIsNonSimpleParameter(true);
  5683. if (buildAST)
  5684. {
  5685. // When only validating formals, we won't have a function node.
  5686. pnodeFnc->pnodeRest = pnodeT;
  5687. if (!isNonSimpleParameterList)
  5688. {
  5689. // This is the first non-simple parameter we've seen. We need to go back
  5690. // and set the Symbols of all previous parameters.
  5691. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5692. }
  5693. }
  5694. isNonSimpleParameterList = true;
  5695. }
  5696. else
  5697. {
  5698. pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5699. if (isNonSimpleParameterList)
  5700. {
  5701. pnodeT->sym->SetIsNonSimpleParameter(true);
  5702. }
  5703. }
  5704. if (buildAST && pid == wellKnownPropertyPids.arguments)
  5705. {
  5706. // This formal parameter overrides the built-in 'arguments' object
  5707. m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5708. }
  5709. if (fStrictFormals)
  5710. {
  5711. UpdateOrCheckForDuplicateInFormals(pid, &formals);
  5712. }
  5713. this->GetScanner()->Scan();
  5714. if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)
  5715. {
  5716. Error(ERRRestLastArg);
  5717. }
  5718. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5719. {
  5720. if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
  5721. {
  5722. Error(ERRRestWithDefault);
  5723. }
  5724. // In defer parse mode we have to flag the function node to indicate that it has default arguments
  5725. // so that it will be considered for any syntax error scenario.
  5726. // Also mark it before parsing the expression as it may contain functions.
  5727. ParseNodeFnc * currentFncNode = GetCurrentFunctionNode();
  5728. if (!currentFncNode->HasDefaultArguments())
  5729. {
  5730. currentFncNode->SetHasDefaultArguments();
  5731. currentFncNode->SetHasNonSimpleParameterList();
  5732. currentFncNode->firstDefaultArg = argPos;
  5733. }
  5734. this->GetScanner()->Scan();
  5735. ParseNodePtr pnodeInit;
  5736. if (isTopLevelDeferredFunc)
  5737. {
  5738. // Defer default expressions if the function will be deferred, since we know they can't be evaluated
  5739. // until the function is fully compiled, and generating code for a function nested inside a deferred function
  5740. // creates inconsistencies.
  5741. pnodeInit = ParseExpr<false>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5742. }
  5743. else
  5744. {
  5745. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5746. }
  5747. if (buildAST && pnodeInit && pnodeInit->nop == knopFncDecl)
  5748. {
  5749. Assert(nameHintLength >= nameHintOffset);
  5750. ParseNodeFnc * pnodeFncInit = pnodeInit->AsParseNodeFnc();
  5751. pnodeFncInit->hint = pNameHint;
  5752. pnodeFncInit->hintLength = nameHintLength;
  5753. pnodeFncInit->hintOffset = nameHintOffset;
  5754. }
  5755. AnalysisAssert(pnodeT);
  5756. pnodeT->sym->SetIsNonSimpleParameter(true);
  5757. if (!isNonSimpleParameterList)
  5758. {
  5759. if (buildAST)
  5760. {
  5761. // This is the first non-simple parameter we've seen. We need to go back
  5762. // and set the Symbols of all previous parameters.
  5763. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5764. }
  5765. // There may be previous parameters that need to be checked for duplicates.
  5766. isNonSimpleParameterList = true;
  5767. }
  5768. if (buildAST)
  5769. {
  5770. if (!m_currentNodeFunc->HasDefaultArguments())
  5771. {
  5772. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, DefaultArgFunction, m_scriptContext);
  5773. }
  5774. pnodeT->pnodeInit = pnodeInit;
  5775. pnodeT->ichLim = this->GetScanner()->IchLimTok();
  5776. }
  5777. }
  5778. }
  5779. if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
  5780. {
  5781. Error(ERRFormalSame);
  5782. }
  5783. if (flags & fFncOneArg)
  5784. {
  5785. if (m_token.tk != tkRParen)
  5786. {
  5787. Error(ERRSetterMustHaveOneParameter);
  5788. }
  5789. break; //enforce only one arg
  5790. }
  5791. if (m_token.tk != tkComma)
  5792. {
  5793. break;
  5794. }
  5795. this->GetScanner()->Scan();
  5796. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5797. {
  5798. break;
  5799. }
  5800. }
  5801. if (seenRestParameter)
  5802. {
  5803. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Rest, m_scriptContext);
  5804. }
  5805. if (m_token.tk != tkRParen)
  5806. {
  5807. Error(ERRnoRparen);
  5808. }
  5809. if (this->GetCurrentFunctionNode()->CallsEval() || this->GetCurrentFunctionNode()->ChildCallsEval())
  5810. {
  5811. Assert(pnodeFnc->HasNonSimpleParameterList());
  5812. pnodeFnc->ResetBodyAndParamScopeMerged();
  5813. }
  5814. }
  5815. Assert(m_token.tk == tkRParen);
  5816. if (fLambda)
  5817. {
  5818. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5819. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5820. }
  5821. }
  5822. template<bool buildAST>
  5823. ParseNodePtr Parser::GenerateModuleFunctionWrapper()
  5824. {
  5825. ParseNodePtr pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fFncModule, nullptr, false, true, true);
  5826. ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);
  5827. return callNode;
  5828. }
  5829. template<bool buildAST>
  5830. ParseNodeFnc * Parser::GenerateEmptyConstructor(bool extends)
  5831. {
  5832. ParseNodeFnc * pnodeFnc;
  5833. // Create the node.
  5834. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5835. pnodeFnc->SetNested(NULL != m_currentNodeFunc);
  5836. pnodeFnc->SetStrictMode();
  5837. pnodeFnc->SetDeclaration(TRUE);
  5838. pnodeFnc->SetIsMethod(TRUE);
  5839. pnodeFnc->SetIsClassMember(TRUE);
  5840. pnodeFnc->SetIsClassConstructor(TRUE);
  5841. pnodeFnc->SetIsBaseClassConstructor(!extends);
  5842. pnodeFnc->SetHasNonThisStmt();
  5843. pnodeFnc->SetIsGeneratedDefault(TRUE);
  5844. pnodeFnc->SetHasComputedName();
  5845. pnodeFnc->SetHasHomeObj();
  5846. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  5847. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5848. pnodeFnc->ichMin = this->GetScanner()->IchMinTok();
  5849. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5850. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  5851. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  5852. pnodeFnc->functionId = (*m_nextFunctionId);
  5853. // In order to (re-)defer the default constructor, we need to, for instance, track
  5854. // deferred class expression the way we track function expression, since we lose the part of the source
  5855. // that tells us which we have.
  5856. Assert(!pnodeFnc->canBeDeferred);
  5857. #ifdef DBG
  5858. pnodeFnc->deferredParseNextFunctionId = *(this->m_nextFunctionId);
  5859. #endif
  5860. AppendFunctionToScopeList(true, pnodeFnc);
  5861. if (m_nextFunctionId)
  5862. {
  5863. (*m_nextFunctionId)++;
  5864. }
  5865. // Update the count of functions nested in the current parent.
  5866. if (m_pnestedCount)
  5867. {
  5868. (*m_pnestedCount)++;
  5869. }
  5870. if (this->GetScanner()->IchMinTok() >= this->GetScanner()->IchMinLine())
  5871. {
  5872. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  5873. pnodeFnc->columnNumber = this->GetScanner()->IchMinTok() - this->GetScanner()->IchMinLine();
  5874. }
  5875. else if (m_currentNodeFunc)
  5876. {
  5877. // For the first line after defer parse, compute the column relative to the column number
  5878. // of the lexically parent function.
  5879. ULONG offsetFromCurrentFunction = this->GetScanner()->IchMinTok() - m_currentNodeFunc->ichMin;
  5880. pnodeFnc->columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  5881. }
  5882. else
  5883. {
  5884. // if there is no current function, lets give a default of 0.
  5885. pnodeFnc->columnNumber = 0;
  5886. }
  5887. int32 * pAstSizeSave = m_pCurrentAstSize;
  5888. m_pCurrentAstSize = &(pnodeFnc->astSize);
  5889. // Make this the current function.
  5890. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5891. m_currentNodeFunc = pnodeFnc;
  5892. ParseNodeName * argsId = nullptr;
  5893. ParseNodePtr *lastNodeRef = nullptr;
  5894. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  5895. if (buildAST && extends)
  5896. {
  5897. // constructor(...args) { super(...args); }
  5898. // ^^^^^^^
  5899. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5900. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5901. IdentPtr pidargs = this->GetHashTbl()->PidHashNameLen(_u("args"), sizeof("args") - 1);
  5902. ParseNodeVar * pnodeT = CreateVarDeclNode(pidargs, STFormal);
  5903. pnodeT->sym->SetIsNonSimpleParameter(true);
  5904. pnodeFnc->pnodeRest = pnodeT;
  5905. PidRefStack *ref = this->PushPidRef(pidargs);
  5906. argsId = CreateNameNode(pidargs, ref, pnodeFnc->ichMin, pnodeFnc->ichLim);
  5907. m_ppnodeVar = ppnodeVarSave;
  5908. }
  5909. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5910. pnodeBlock->pnodeScopes = pnodeInnerBlock;
  5911. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  5912. pnodeFnc->pnodeScopes = pnodeBlock;
  5913. if (buildAST)
  5914. {
  5915. if (extends)
  5916. {
  5917. // constructor(...args) { super(...args); }
  5918. // ^^^^^^^^^^^^^^^
  5919. Assert(argsId);
  5920. ParseNodeUni * spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);
  5921. ParseNodeSpecialName * superRef = ReferenceSpecialName(wellKnownPropertyPids._superConstructor, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5922. pnodeFnc->SetHasSuperReference(TRUE);
  5923. ParseNodeSuperCall * callNode = CreateSuperCallNode(superRef, spreadArg);
  5924. callNode->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5925. callNode->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5926. callNode->spreadArgCount = 1;
  5927. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, callNode);
  5928. }
  5929. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  5930. }
  5931. FinishParseBlock(pnodeInnerBlock);
  5932. CreateSpecialSymbolDeclarations(pnodeFnc);
  5933. FinishParseBlock(pnodeBlock);
  5934. m_currentNodeFunc = pnodeFncSave;
  5935. m_pCurrentAstSize = pAstSizeSave;
  5936. return pnodeFnc;
  5937. }
  5938. template<bool buildAST>
  5939. void Parser::ParseExpressionLambdaBody(ParseNodeFnc * pnodeLambda, bool fAllowIn)
  5940. {
  5941. ParseNodePtr *lastNodeRef = nullptr;
  5942. // The lambda body is a single expression, the result of which is the return value.
  5943. ParseNodeReturn * pnodeRet = nullptr;
  5944. if (buildAST)
  5945. {
  5946. pnodeRet = CreateNodeForOpT<knopReturn>();
  5947. pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;
  5948. pnodeLambda->pnodeScopes->pnodeStmt = pnodeRet;
  5949. }
  5950. IdentToken token;
  5951. charcount_t lastRParen = 0;
  5952. // We need to disable deferred parse mode in the scanner because the lambda body doesn't end with a right paren.
  5953. // The scanner needs to create a pid in the case of a string constant token immediately following the lambda body expression.
  5954. // Otherwise, we'll save null for the string constant pid which will AV during ByteCode generation.
  5955. BYTE fScanDeferredFlagsSave = this->GetScanner()->SetDeferredParse(FALSE);
  5956. ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, fAllowIn, FALSE, nullptr, nullptr, nullptr, &token, false, nullptr, &lastRParen);
  5957. this->GetScanner()->SetDeferredParseFlags(fScanDeferredFlagsSave);
  5958. this->MarkEscapingRef(result, &token);
  5959. if (buildAST)
  5960. {
  5961. pnodeRet->pnodeExpr = result;
  5962. pnodeRet->ichMin = pnodeRet->pnodeExpr->ichMin;
  5963. pnodeRet->ichLim = pnodeRet->pnodeExpr->ichLim;
  5964. // Pushing a statement node with PushStmt<>() normally does this initialization
  5965. // but do it here manually since we know there is no outer statement node.
  5966. pnodeRet->grfnop = 0;
  5967. pnodeRet->pnodeOuter = nullptr;
  5968. pnodeLambda->ichLim = max(pnodeRet->ichLim, lastRParen);
  5969. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  5970. pnodeLambda->pnodeScopes->ichLim = pnodeRet->ichLim;
  5971. pnodeLambda->pnodeBody = nullptr;
  5972. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, pnodeRet);
  5973. // Append an EndCode node.
  5974. ParseNodePtr end = CreateNodeForOpT<knopEndCode>(pnodeRet->ichLim);
  5975. end->ichLim = end->ichMin; // make end code zero width at the immediate end of lambda body
  5976. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, end);
  5977. // Lambda's do not have arguments binding
  5978. pnodeLambda->SetHasReferenceableBuiltInArguments(false);
  5979. }
  5980. else
  5981. {
  5982. pnodeLambda->ichLim = max(this->GetScanner()->IchLimTokPrevious(), lastRParen);
  5983. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  5984. }
  5985. }
  5986. void Parser::CheckStrictFormalParameters()
  5987. {
  5988. if (m_token.tk == tkID)
  5989. {
  5990. // single parameter arrow function case
  5991. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5992. CheckStrictModeEvalArgumentsUsage(pid);
  5993. return;
  5994. }
  5995. Assert(m_token.tk == tkLParen);
  5996. this->GetScanner()->ScanForcingPid();
  5997. if (m_token.tk != tkRParen)
  5998. {
  5999. SList<IdentPtr> formals(&m_nodeAllocator);
  6000. for (;;)
  6001. {
  6002. if (m_token.tk != tkID)
  6003. {
  6004. IdentifierExpectedError(m_token);
  6005. }
  6006. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  6007. CheckStrictModeEvalArgumentsUsage(pid);
  6008. if (formals.Has(pid))
  6009. {
  6010. Error(ERRES5ArgSame, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  6011. }
  6012. else
  6013. {
  6014. formals.Prepend(pid);
  6015. }
  6016. this->GetScanner()->Scan();
  6017. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  6018. {
  6019. this->GetScanner()->Scan();
  6020. // We can avoid building the AST since we are just checking the default expression.
  6021. ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);
  6022. Assert(pnodeInit == nullptr);
  6023. }
  6024. if (m_token.tk != tkComma)
  6025. {
  6026. break;
  6027. }
  6028. this->GetScanner()->ScanForcingPid();
  6029. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6030. {
  6031. break;
  6032. }
  6033. }
  6034. }
  6035. Assert(m_token.tk == tkRParen);
  6036. }
  6037. void Parser::FinishFncNode(ParseNodeFnc * pnodeFnc, bool fAllowIn)
  6038. {
  6039. AnalysisAssert(pnodeFnc);
  6040. // Finish the AST for a function that was deferred earlier, but which we decided
  6041. // to finish after the fact.
  6042. // We assume that the name(s) and arg(s) have already got parse nodes, so
  6043. // we just have to do the function body.
  6044. // Save the current next function Id, and resume from the old one.
  6045. Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;
  6046. Js::LocalFunctionId tempNextFunctionId = pnodeFnc->functionId + 1;
  6047. this->m_nextFunctionId = &tempNextFunctionId;
  6048. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  6049. uint *pnestedCountSave = m_pnestedCount;
  6050. int32* pAstSizeSave = m_pCurrentAstSize;
  6051. m_currentNodeFunc = pnodeFnc;
  6052. m_pCurrentAstSize = &(pnodeFnc->astSize);
  6053. pnodeFnc->nestedCount = 0;
  6054. m_pnestedCount = &pnodeFnc->nestedCount;
  6055. bool fLambda = pnodeFnc->IsLambda();
  6056. bool fMethod = pnodeFnc->IsMethod();
  6057. // Cue up the parser to the start of the function body.
  6058. if (pnodeFnc->pnodeName)
  6059. {
  6060. // Skip the name(s).
  6061. this->GetScanner()->SetCurrentCharacter(pnodeFnc->pnodeName->ichLim, pnodeFnc->lineNumber);
  6062. }
  6063. else
  6064. {
  6065. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->lineNumber);
  6066. if (fMethod)
  6067. {
  6068. // Method. Skip identifier name, computed property name, "async", "get", "set", and '*' or '(' characters.
  6069. for (;;)
  6070. {
  6071. this->GetScanner()->Scan();
  6072. // '[' character indicates a computed property name for this method. We should consume it.
  6073. if (m_token.tk == tkLBrack)
  6074. {
  6075. // We don't care what the name expr is.
  6076. this->GetScanner()->Scan();
  6077. ParseExpr<false>();
  6078. Assert(m_token.tk == tkRBrack);
  6079. continue;
  6080. }
  6081. // Quit scanning ahead when we reach a '(' character which opens the arg list.
  6082. if (m_token.tk == tkLParen)
  6083. {
  6084. break;
  6085. }
  6086. }
  6087. }
  6088. else if (pnodeFnc->IsAccessor())
  6089. {
  6090. // Getter/setter. The node text starts with the name, so eat that.
  6091. this->GetScanner()->ScanNoKeywords();
  6092. }
  6093. else if (!fLambda)
  6094. {
  6095. // Anonymous function. Skip "async", "function", and '(' or '*' characters.
  6096. for (;;)
  6097. {
  6098. this->GetScanner()->Scan();
  6099. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6100. {
  6101. Assert(pnodeFnc->IsAsync());
  6102. continue;
  6103. }
  6104. // Quit scanning ahead when we reach a 'function' keyword which precedes the arg list.
  6105. if (m_token.tk == tkFUNCTION)
  6106. {
  6107. break;
  6108. }
  6109. Assert(m_token.tk == tkLParen || m_token.tk == tkStar);
  6110. }
  6111. }
  6112. }
  6113. // switch scanner to treat 'yield' as keyword in generator functions
  6114. // or as an identifier in non-generator functions
  6115. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->IsGenerator());
  6116. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(pnodeFnc && pnodeFnc->IsAsync());
  6117. // Skip the arg list.
  6118. if (!fMethod)
  6119. {
  6120. // If this is a method, we've already advanced to the '(' token.
  6121. this->GetScanner()->Scan();
  6122. }
  6123. if (m_token.tk == tkStar)
  6124. {
  6125. Assert(pnodeFnc->IsGenerator());
  6126. this->GetScanner()->ScanNoKeywords();
  6127. }
  6128. if (fLambda && m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6129. {
  6130. Assert(pnodeFnc->IsAsync());
  6131. this->GetScanner()->ScanNoKeywords();
  6132. }
  6133. Assert(m_token.tk == tkLParen || (fLambda && m_token.tk == tkID));
  6134. this->GetScanner()->ScanNoKeywords();
  6135. if (m_token.tk != tkRParen && m_token.tk != tkDArrow)
  6136. {
  6137. for (;;)
  6138. {
  6139. if (m_token.tk == tkEllipsis)
  6140. {
  6141. this->GetScanner()->ScanNoKeywords();
  6142. }
  6143. if (m_token.tk == tkID)
  6144. {
  6145. this->GetScanner()->ScanNoKeywords();
  6146. if (m_token.tk == tkAsg)
  6147. {
  6148. // Eat the default expression
  6149. this->GetScanner()->Scan();
  6150. ParseExpr<false>(koplCma);
  6151. }
  6152. }
  6153. else if (IsPossiblePatternStart())
  6154. {
  6155. ParseDestructuredLiteralWithScopeSave(tkLET, false/*isDecl*/, false /*topLevel*/);
  6156. }
  6157. else
  6158. {
  6159. AssertMsg(false, "Unexpected identifier prefix while fast-scanning formals");
  6160. }
  6161. if (m_token.tk != tkComma)
  6162. {
  6163. break;
  6164. }
  6165. this->GetScanner()->ScanNoKeywords();
  6166. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6167. {
  6168. break;
  6169. }
  6170. }
  6171. }
  6172. if (m_token.tk == tkRParen)
  6173. {
  6174. this->GetScanner()->Scan();
  6175. }
  6176. if (fLambda && m_token.tk == tkDArrow)
  6177. {
  6178. this->GetScanner()->Scan();
  6179. }
  6180. // Finish the function body.
  6181. {
  6182. // Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. "( function x(){} )".
  6183. // We lose that context here since we start from middle of function body. So save and restore source range info.
  6184. const charcount_t ichLim = pnodeFnc->ichLim;
  6185. const size_t cbLim = pnodeFnc->cbLim;
  6186. this->FinishFncDecl(pnodeFnc, NULL, fLambda, /* skipCurlyBraces */ false, fAllowIn);
  6187. #if DBG
  6188. // The pnode extent may not match the original extent.
  6189. // We expect this to happen only when there are trailing ")"'s.
  6190. // Consume them and make sure that's all we've got.
  6191. if (pnodeFnc->ichLim != ichLim)
  6192. {
  6193. Assert(pnodeFnc->ichLim < ichLim);
  6194. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichLim);
  6195. while (this->GetScanner()->IchLimTok() != ichLim)
  6196. {
  6197. this->GetScanner()->ScanNoKeywords();
  6198. Assert(m_token.tk == tkRParen);
  6199. }
  6200. }
  6201. #endif
  6202. pnodeFnc->ichLim = ichLim;
  6203. pnodeFnc->cbLim = cbLim;
  6204. }
  6205. m_currentNodeFunc = pnodeFncSave;
  6206. m_pCurrentAstSize = pAstSizeSave;
  6207. m_pnestedCount = pnestedCountSave;
  6208. Assert(m_pnestedCount);
  6209. Assert(tempNextFunctionId == pnodeFnc->deferredParseNextFunctionId);
  6210. this->m_nextFunctionId = nextFunctionIdSave;
  6211. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6212. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6213. }
  6214. void Parser::FinishFncDecl(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, bool fLambda, bool skipCurlyBraces, bool fAllowIn)
  6215. {
  6216. LPCOLESTR name = NULL;
  6217. JS_ETW(int32 startAstSize = *m_pCurrentAstSize);
  6218. if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))
  6219. {
  6220. name = GetFunctionName(pnodeFnc, pNameHint);
  6221. m_functionBody = NULL; // for nested functions we do not want to get the name of the top deferred function return name;
  6222. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, 0, m_parseType, name));
  6223. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), name, pnodeFnc->functionId);
  6224. }
  6225. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->functionId, /*Undefer*/FALSE));
  6226. // Do the work of creating an AST for a function body.
  6227. // This is common to the un-deferred case and the case in which we un-defer late in the game.
  6228. Assert(pnodeFnc->nop == knopFncDecl);
  6229. if (fLambda && m_token.tk != tkLCurly)
  6230. {
  6231. ParseExpressionLambdaBody<true>(pnodeFnc, fAllowIn);
  6232. }
  6233. else
  6234. {
  6235. if (!skipCurlyBraces)
  6236. {
  6237. ChkCurTok(tkLCurly, ERRnoLcurly);
  6238. }
  6239. ParseNodePtr * lastNodeRef = nullptr;
  6240. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true /* isSourceElementList */);
  6241. // Append an EndCode node.
  6242. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  6243. if (!skipCurlyBraces)
  6244. {
  6245. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6246. }
  6247. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  6248. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  6249. }
  6250. #ifdef ENABLE_JS_ETW
  6251. int32 astSize = *m_pCurrentAstSize - startAstSize;
  6252. EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, astSize, m_parseType, name);
  6253. #endif
  6254. }
  6255. ParseNodeVar * Parser::CreateSpecialVarDeclNode(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6256. {
  6257. ParseNodeVar * pnode = InsertVarAtBeginning(pnodeFnc, pid);
  6258. pnode->grfpn |= fpnSpecialSymbol;
  6259. // special symbol must not be global
  6260. pnode->sym->SetIsGlobal(false);
  6261. return pnode;
  6262. }
  6263. ParseNodeVar * Parser::InsertVarAtBeginning(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6264. {
  6265. ParseNodeVar * pnode = nullptr;
  6266. if (m_ppnodeVar == &pnodeFnc->pnodeVars)
  6267. {
  6268. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6269. }
  6270. else
  6271. {
  6272. ParseNodePtr * const ppnodeVarSave = m_ppnodeVar;
  6273. m_ppnodeVar = &pnodeFnc->pnodeVars;
  6274. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6275. m_ppnodeVar = ppnodeVarSave;
  6276. }
  6277. Assert(pnode);
  6278. return pnode;
  6279. }
  6280. ParseNodeVar * Parser::AddArgumentsNodeToVars(ParseNodeFnc * pnodeFnc)
  6281. {
  6282. Assert(!GetCurrentFunctionNode()->IsLambda());
  6283. ParseNodeVar * argNode = InsertVarAtBeginning(pnodeFnc, wellKnownPropertyPids.arguments);
  6284. argNode->grfpn |= PNodeFlags::fpnArguments; // Flag this as the built-in arguments node
  6285. return argNode;
  6286. }
  6287. void Parser::UpdateArgumentsNode(ParseNodeFnc * pnodeFnc, ParseNodeVar * argNode)
  6288. {
  6289. if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam) || pnodeFnc->IsLambda())
  6290. {
  6291. // There is a parameter named arguments. So we don't have to create the built-in arguments.
  6292. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6293. }
  6294. else if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) && pnodeFnc->IsBodyAndParamScopeMerged())
  6295. {
  6296. // In non-split scope case there is a var or function definition named arguments in the body
  6297. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6298. }
  6299. else
  6300. {
  6301. pnodeFnc->SetHasReferenceableBuiltInArguments(true);
  6302. Assert(argNode);
  6303. }
  6304. if (argNode != nullptr && !argNode->sym->IsArguments())
  6305. {
  6306. // A duplicate definition has updated the declaration node. Need to reset it back.
  6307. argNode->grfpn |= PNodeFlags::fpnArguments;
  6308. argNode->sym->SetDecl(argNode);
  6309. }
  6310. }
  6311. LPCOLESTR Parser::GetFunctionName(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint)
  6312. {
  6313. LPCOLESTR name = nullptr;
  6314. if (pnodeFnc->pnodeName != nullptr)
  6315. {
  6316. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  6317. name = pnodeFnc->pnodeName->pid->Psz();
  6318. }
  6319. if (name == nullptr && pNameHint != nullptr)
  6320. {
  6321. name = pNameHint;
  6322. }
  6323. if (name == nullptr && (pnodeFnc->IsLambda() ||
  6324. (!pnodeFnc->IsDeclaration() && !pnodeFnc->IsMethod())))
  6325. {
  6326. name = Js::Constants::AnonymousFunction;
  6327. }
  6328. if (name == nullptr && m_functionBody != nullptr)
  6329. {
  6330. name = m_functionBody->GetExternalDisplayName();
  6331. }
  6332. else if (name == nullptr)
  6333. {
  6334. name = Js::Constants::AnonymousFunction;
  6335. }
  6336. return name;
  6337. }
  6338. IdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)
  6339. {
  6340. if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())
  6341. {
  6342. IdentPtr pid;
  6343. if (m_token.tk == tkStrCon)
  6344. {
  6345. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6346. {
  6347. Error(ERRES5NoOctal);
  6348. }
  6349. pid = m_token.GetStr();
  6350. }
  6351. else
  6352. {
  6353. pid = m_token.GetIdentifier(this->GetHashTbl());
  6354. }
  6355. *pidHint = pid;
  6356. return pid;
  6357. }
  6358. else if (m_token.tk == tkIntCon)
  6359. {
  6360. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6361. {
  6362. Error(ERRES5NoOctal);
  6363. }
  6364. return this->GetScanner()->PidFromLong(m_token.GetLong());
  6365. }
  6366. else if (m_token.tk == tkFltCon)
  6367. {
  6368. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6369. {
  6370. Error(ERRES5NoOctal);
  6371. }
  6372. return this->GetScanner()->PidFromDbl(m_token.GetDouble());
  6373. }
  6374. Error(ERRnoMemberIdent);
  6375. }
  6376. LPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)
  6377. {
  6378. if ((pMemberName == nullptr && !isComputedName) ||
  6379. (pMemberNameHint == nullptr && isComputedName) ||
  6380. !CONFIG_FLAG(UseFullName))
  6381. {
  6382. return nullptr;
  6383. }
  6384. LPCOLESTR pFinalName = isComputedName ? pMemberNameHint : pMemberName->Psz();
  6385. uint32 fullNameHintLength = (uint32)wcslen(pFinalName);
  6386. uint32 shortNameOffset = 0;
  6387. if (!isStatic)
  6388. {
  6389. // Add prototype.
  6390. pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);
  6391. }
  6392. if (pClassName)
  6393. {
  6394. uint32 classNameOffset = 0;
  6395. pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);
  6396. shortNameOffset += classNameOffset;
  6397. }
  6398. if (pGetSet)
  6399. {
  6400. // displays as get/set prototype.funcname
  6401. uint32 getSetOffset = 0;
  6402. pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);
  6403. shortNameOffset += getSetOffset;
  6404. }
  6405. *nameLength = fullNameHintLength;
  6406. *pShortNameOffset = shortNameOffset;
  6407. return pFinalName;
  6408. }
  6409. class AutoParsingSuperRestrictionStateRestorer
  6410. {
  6411. public:
  6412. AutoParsingSuperRestrictionStateRestorer(Parser* parser) : m_parser(parser)
  6413. {
  6414. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6415. this->m_originalParsingSuperRestrictionState = this->m_parser->m_parsingSuperRestrictionState;
  6416. }
  6417. ~AutoParsingSuperRestrictionStateRestorer()
  6418. {
  6419. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6420. this->m_parser->m_parsingSuperRestrictionState = m_originalParsingSuperRestrictionState;
  6421. }
  6422. private:
  6423. Parser * m_parser;
  6424. int m_originalParsingSuperRestrictionState;
  6425. };
  6426. template<bool buildAST>
  6427. ParseNodeClass * Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)
  6428. {
  6429. bool hasConstructor = false;
  6430. bool hasExtends = false;
  6431. IdentPtr name = nullptr;
  6432. ParseNodeVar * pnodeName = nullptr;
  6433. ParseNodeFnc * pnodeConstructor = nullptr;
  6434. ParseNodePtr pnodeExtends = nullptr;
  6435. ParseNodePtr pnodeMembers = nullptr;
  6436. ParseNodePtr *lastMemberNodeRef = nullptr;
  6437. ParseNodePtr pnodeStaticMembers = nullptr;
  6438. ParseNodePtr *lastStaticMemberNodeRef = nullptr;
  6439. uint32 nameHintLength = pHintLength ? *pHintLength : 0;
  6440. uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;
  6441. ArenaAllocator tempAllocator(_u("ClassMemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  6442. size_t cbMinConstructor = 0;
  6443. ParseNodeClass * pnodeClass = nullptr;
  6444. if (buildAST)
  6445. {
  6446. pnodeClass = CreateNodeForOpT<knopClassDecl>();
  6447. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Class, m_scriptContext);
  6448. cbMinConstructor = this->GetScanner()->IecpMinTok();
  6449. }
  6450. this->GetScanner()->Scan();
  6451. if (m_token.tk == tkID)
  6452. {
  6453. name = m_token.GetIdentifier(this->GetHashTbl());
  6454. this->GetScanner()->Scan();
  6455. }
  6456. else if (isDeclaration)
  6457. {
  6458. IdentifierExpectedError(m_token);
  6459. }
  6460. if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  6461. {
  6462. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  6463. }
  6464. BOOL strictSave = m_fUseStrictMode;
  6465. m_fUseStrictMode = TRUE;
  6466. ParseNodeVar * pnodeDeclName = nullptr;
  6467. if (isDeclaration)
  6468. {
  6469. pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);
  6470. }
  6471. ParseNodePtr *ppnodeScopeSave = nullptr;
  6472. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  6473. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  6474. if (buildAST)
  6475. {
  6476. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  6477. pnodeClass->pnodeBlock = pnodeBlock;
  6478. }
  6479. if (name)
  6480. {
  6481. pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);
  6482. }
  6483. if (m_token.tk == tkEXTENDS)
  6484. {
  6485. this->GetScanner()->Scan();
  6486. pnodeExtends = ParseTerm<buildAST>();
  6487. hasExtends = true;
  6488. }
  6489. if (m_token.tk != tkLCurly)
  6490. {
  6491. Error(ERRnoLcurly);
  6492. }
  6493. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Parsing class (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6494. RestorePoint beginClass;
  6495. this->GetScanner()->Capture(&beginClass);
  6496. this->GetScanner()->ScanForcingPid();
  6497. IdentPtr pClassNamePid = pnodeName ? pnodeName->pid : nullptr;
  6498. for (;;)
  6499. {
  6500. if (m_token.tk == tkSColon)
  6501. {
  6502. this->GetScanner()->ScanForcingPid();
  6503. continue;
  6504. }
  6505. if (m_token.tk == tkRCurly)
  6506. {
  6507. break;
  6508. }
  6509. bool isStatic = false;
  6510. if (m_token.tk == tkSTATIC)
  6511. {
  6512. // 'static' can be used as an IdentifierName here, even in strict mode code. We need to see the next token before we know
  6513. // if this is being used as a keyword. This is similar to the way we treat 'let' in some cases.
  6514. // See https://tc39.github.io/ecma262/#sec-keywords for more info.
  6515. RestorePoint beginStatic;
  6516. this->GetScanner()->Capture(&beginStatic);
  6517. this->GetScanner()->ScanForcingPid();
  6518. if (m_token.tk == tkLParen)
  6519. {
  6520. this->GetScanner()->SeekTo(beginStatic);
  6521. }
  6522. else
  6523. {
  6524. isStatic = true;
  6525. }
  6526. }
  6527. ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;
  6528. charcount_t ichMin = 0;
  6529. size_t iecpMin = 0;
  6530. ParseNodePtr pnodeMemberName = nullptr;
  6531. IdentPtr pidHint = nullptr;
  6532. IdentPtr memberPid = nullptr;
  6533. LPCOLESTR pMemberNameHint = nullptr;
  6534. uint32 memberNameHintLength = 0;
  6535. uint32 memberNameOffset = 0;
  6536. bool isComputedName = false;
  6537. bool isAsyncMethod = false;
  6538. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  6539. {
  6540. RestorePoint parsedAsync;
  6541. this->GetScanner()->Capture(&parsedAsync);
  6542. ichMin = this->GetScanner()->IchMinTok();
  6543. iecpMin = this->GetScanner()->IecpMinTok();
  6544. this->GetScanner()->Scan();
  6545. if (m_token.tk == tkLParen || this->GetScanner()->FHadNewLine())
  6546. {
  6547. this->GetScanner()->SeekTo(parsedAsync);
  6548. }
  6549. else
  6550. {
  6551. isAsyncMethod = true;
  6552. }
  6553. }
  6554. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  6555. m_token.tk == tkStar;
  6556. if (isGenerator)
  6557. {
  6558. fncDeclFlags |= fFncGenerator;
  6559. this->GetScanner()->ScanForcingPid();
  6560. }
  6561. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6562. {
  6563. // Computed member name: [expr] () { }
  6564. LPCOLESTR emptyHint = nullptr;
  6565. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6566. isComputedName = true;
  6567. }
  6568. else // not computed name
  6569. {
  6570. memberPid = this->ParseClassPropertyName(&pidHint);
  6571. if (pidHint)
  6572. {
  6573. pMemberNameHint = pidHint->Psz();
  6574. memberNameHintLength = pidHint->Cch();
  6575. }
  6576. }
  6577. if (buildAST && memberPid)
  6578. {
  6579. pnodeMemberName = CreateStrNode(memberPid);
  6580. }
  6581. if (!isStatic && memberPid == wellKnownPropertyPids.constructor)
  6582. {
  6583. if (hasConstructor || isAsyncMethod)
  6584. {
  6585. Error(ERRsyntax);
  6586. }
  6587. hasConstructor = true;
  6588. LPCOLESTR pConstructorName = nullptr;
  6589. uint32 constructorNameLength = 0;
  6590. uint32 constructorShortNameHintOffset = 0;
  6591. if (pnodeName && pnodeName->pid)
  6592. {
  6593. pConstructorName = pnodeName->pid->Psz();
  6594. constructorNameLength = pnodeName->pid->Cch();
  6595. }
  6596. else
  6597. {
  6598. pConstructorName = pNameHint;
  6599. constructorNameLength = nameHintLength;
  6600. constructorShortNameHintOffset = nameHintOffset;
  6601. }
  6602. {
  6603. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6604. this->m_parsingSuperRestrictionState = hasExtends ? ParsingSuperRestrictionState_SuperCallAndPropertyAllowed : ParsingSuperRestrictionState_SuperPropertyAllowed;
  6605. // Add the class constructor flag and base class constructor flag if pnodeExtends is nullptr
  6606. fncDeclFlags |= fFncClassConstructor | (hasExtends ? kFunctionNone : fFncBaseClassConstructor);
  6607. pnodeConstructor = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, pConstructorName, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState = */false);
  6608. }
  6609. if (pnodeConstructor->IsGenerator())
  6610. {
  6611. Error(ERRConstructorCannotBeGenerator);
  6612. }
  6613. Assert(constructorNameLength >= constructorShortNameHintOffset);
  6614. // The constructor function will get the same name as class.
  6615. pnodeConstructor->hint = pConstructorName;
  6616. pnodeConstructor->hintLength = constructorNameLength;
  6617. pnodeConstructor->hintOffset = constructorShortNameHintOffset;
  6618. pnodeConstructor->pid = pnodeName && pnodeName->pid ? pnodeName->pid : wellKnownPropertyPids.constructor;
  6619. pnodeConstructor->SetHasNonThisStmt();
  6620. pnodeConstructor->SetHasComputedName();
  6621. pnodeConstructor->SetHasHomeObj();
  6622. }
  6623. else
  6624. {
  6625. ParseNodePtr pnodeMember = nullptr;
  6626. bool isMemberNamedGetOrSet = false;
  6627. RestorePoint beginMethodName;
  6628. this->GetScanner()->Capture(&beginMethodName);
  6629. if (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set)
  6630. {
  6631. this->GetScanner()->ScanForcingPid();
  6632. }
  6633. if (m_token.tk == tkLParen)
  6634. {
  6635. this->GetScanner()->SeekTo(beginMethodName);
  6636. isMemberNamedGetOrSet = true;
  6637. }
  6638. if ((memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set) && !isMemberNamedGetOrSet)
  6639. {
  6640. bool isGetter = (memberPid == wellKnownPropertyPids.get);
  6641. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6642. {
  6643. // Computed get/set member name: get|set [expr] () { }
  6644. LPCOLESTR emptyHint = nullptr;
  6645. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6646. isComputedName = true;
  6647. }
  6648. else // not computed name
  6649. {
  6650. memberPid = this->ParseClassPropertyName(&pidHint);
  6651. }
  6652. if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)
  6653. {
  6654. Error(ERRsyntax);
  6655. }
  6656. if (buildAST && memberPid && !isComputedName)
  6657. {
  6658. pnodeMemberName = CreateStrNode(memberPid);
  6659. }
  6660. ParseNodeFnc * pnodeFnc = nullptr;
  6661. {
  6662. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6663. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6664. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),
  6665. pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true,
  6666. /* resetParsingSuperRestrictionState */false);
  6667. }
  6668. pnodeFnc->SetIsStaticMember(isStatic);
  6669. if (isComputedName)
  6670. {
  6671. pnodeFnc->SetHasComputedName();
  6672. }
  6673. pnodeFnc->SetHasHomeObj();
  6674. if (buildAST)
  6675. {
  6676. pnodeFnc->SetIsAccessor();
  6677. pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);
  6678. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,
  6679. isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,
  6680. &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6681. }
  6682. }
  6683. else
  6684. {
  6685. if (isStatic && (memberPid == wellKnownPropertyPids.prototype))
  6686. {
  6687. Error(ERRsyntax);
  6688. }
  6689. ParseNodeFnc * pnodeFnc = nullptr;
  6690. {
  6691. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6692. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6693. if (isAsyncMethod)
  6694. {
  6695. fncDeclFlags |= fFncAsync;
  6696. }
  6697. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState */false);
  6698. if (isAsyncMethod)
  6699. {
  6700. pnodeFnc->cbMin = iecpMin;
  6701. pnodeFnc->ichMin = ichMin;
  6702. }
  6703. }
  6704. pnodeFnc->SetIsStaticMember(isStatic);
  6705. if (isComputedName)
  6706. {
  6707. pnodeFnc->SetHasComputedName();
  6708. }
  6709. pnodeFnc->SetHasHomeObj();
  6710. if (buildAST)
  6711. {
  6712. pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);
  6713. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr /*pgetset*/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6714. }
  6715. }
  6716. if (buildAST)
  6717. {
  6718. Assert(memberNameHintLength >= memberNameOffset);
  6719. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pMemberNameHint; // Fully qualified name
  6720. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = memberNameHintLength;
  6721. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = memberNameOffset;
  6722. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->pid = memberPid; // Short name
  6723. AddToNodeList(isStatic ? &pnodeStaticMembers : &pnodeMembers, isStatic ? &lastStaticMemberNodeRef : &lastMemberNodeRef, pnodeMember);
  6724. }
  6725. }
  6726. }
  6727. size_t cbLimConstructor = 0;
  6728. if (buildAST)
  6729. {
  6730. pnodeClass->ichLim = this->GetScanner()->IchLimTok();
  6731. cbLimConstructor = this->GetScanner()->IecpLimTok();
  6732. }
  6733. if (!hasConstructor)
  6734. {
  6735. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Generating constructor (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6736. RestorePoint endClass;
  6737. this->GetScanner()->Capture(&endClass);
  6738. this->GetScanner()->SeekTo(beginClass);
  6739. pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);
  6740. if (buildAST)
  6741. {
  6742. if (pClassNamePid)
  6743. {
  6744. pnodeConstructor->hint = pClassNamePid->Psz();
  6745. pnodeConstructor->hintLength = pClassNamePid->Cch();
  6746. pnodeConstructor->hintOffset = 0;
  6747. }
  6748. else
  6749. {
  6750. Assert(nameHintLength >= nameHintOffset);
  6751. pnodeConstructor->hint = pNameHint;
  6752. pnodeConstructor->hintLength = nameHintLength;
  6753. pnodeConstructor->hintOffset = nameHintOffset;
  6754. }
  6755. pnodeConstructor->pid = pClassNamePid;
  6756. }
  6757. this->GetScanner()->SeekTo(endClass);
  6758. }
  6759. if (buildAST)
  6760. {
  6761. pnodeConstructor->cbMin = cbMinConstructor;
  6762. pnodeConstructor->cbLim = cbLimConstructor;
  6763. pnodeConstructor->ichMin = pnodeClass->ichMin;
  6764. pnodeConstructor->ichLim = pnodeClass->ichLim;
  6765. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  6766. pnodeClass->pnodeDeclName = pnodeDeclName;
  6767. pnodeClass->pnodeName = pnodeName;
  6768. pnodeClass->pnodeConstructor = pnodeConstructor;
  6769. pnodeClass->pnodeExtends = pnodeExtends;
  6770. pnodeClass->pnodeMembers = pnodeMembers;
  6771. pnodeClass->pnodeStaticMembers = pnodeStaticMembers;
  6772. pnodeClass->isDefaultModuleExport = false;
  6773. }
  6774. FinishParseBlock(pnodeBlock);
  6775. m_fUseStrictMode = strictSave;
  6776. this->GetScanner()->Scan();
  6777. return pnodeClass;
  6778. }
  6779. template<bool buildAST>
  6780. ParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)
  6781. {
  6782. ParseNodePtr pnodeStringLiterals = nullptr;
  6783. ParseNodePtr* lastStringLiteralNodeRef = nullptr;
  6784. ParseNodePtr pnodeRawStringLiterals = nullptr;
  6785. ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;
  6786. ParseNodePtr pnodeSubstitutionExpressions = nullptr;
  6787. ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;
  6788. ParseNodePtr pnodeTagFncArgs = nullptr;
  6789. ParseNodePtr* lastTagFncArgNodeRef = nullptr;
  6790. ParseNodeStr * stringLiteral = nullptr;
  6791. ParseNodeStr * stringLiteralRaw = nullptr;
  6792. ParseNodeStrTemplate * pnodeStringTemplate = nullptr;
  6793. ParseNode * pnodeReturn = nullptr;
  6794. bool templateClosed = false;
  6795. const bool isTagged = pnodeTagFnc != nullptr;
  6796. uint16 stringConstantCount = 0;
  6797. charcount_t ichMin = 0;
  6798. Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);
  6799. if (buildAST)
  6800. {
  6801. pnodeReturn = pnodeStringTemplate = CreateNodeForOpT<knopStrTemplate>();
  6802. pnodeStringTemplate->countStringLiterals = 0;
  6803. pnodeStringTemplate->isTaggedTemplate = isTagged ? TRUE : FALSE;
  6804. // If this is a tagged string template, we need to start building the arg list for the call
  6805. if (isTagged)
  6806. {
  6807. ichMin = pnodeTagFnc->ichMin;
  6808. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);
  6809. }
  6810. }
  6811. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StringTemplates, m_scriptContext);
  6812. OUTPUT_TRACE_DEBUGONLY(
  6813. Js::StringTemplateParsePhase,
  6814. _u("Starting to parse a string template (%s)...\n\tis tagged = %s\n"),
  6815. GetParseType(),
  6816. isTagged ? _u("true") : _u("false (Raw and cooked strings will not differ!)"));
  6817. // String template grammar
  6818. // `...` Simple string template
  6819. // `...${ String template beginning
  6820. // }...${ String template middle
  6821. // }...` String template end
  6822. while (!templateClosed)
  6823. {
  6824. // First, extract the string constant part - we always have one
  6825. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6826. {
  6827. Error(ERRES5NoOctal);
  6828. }
  6829. // We are not able to pass more than a ushort worth of arguments to the tag
  6830. // so use that as a logical limit on the number of string constant pieces.
  6831. if (stringConstantCount >= Js::Constants::MaxAllowedArgs)
  6832. {
  6833. Error(ERRTooManyArgs);
  6834. }
  6835. // Keep track of the string literal count (must be the same for raw strings)
  6836. // We use this in code gen so we don't need to count the string literals list
  6837. stringConstantCount++;
  6838. // If we are not creating parse nodes, there is no need to create strings
  6839. if (buildAST)
  6840. {
  6841. stringLiteral = CreateStrNode(m_token.GetStr());
  6842. AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);
  6843. // We only need to collect a raw string when we are going to pass the string template to a tag
  6844. if (isTagged)
  6845. {
  6846. // Make the scanner create a PID for the raw string constant for the preceding scan
  6847. IdentPtr pid = this->GetScanner()->GetSecondaryBufferAsPid();
  6848. stringLiteralRaw = CreateStrNode(pid);
  6849. // Should have gotten a raw string literal above
  6850. AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);
  6851. }
  6852. else
  6853. {
  6854. #if DBG
  6855. // Assign the raw string for debug tracing below
  6856. stringLiteralRaw = stringLiteral;
  6857. #endif
  6858. }
  6859. OUTPUT_TRACE_DEBUGONLY(
  6860. Js::StringTemplateParsePhase,
  6861. _u("Parsed string constant: \n\tcooked = \"%s\" \n\traw = \"%s\" \n\tdiffer = %d\n"),
  6862. stringLiteral->pid->Psz(),
  6863. stringLiteralRaw->pid->Psz(),
  6864. stringLiteral->pid->Psz() == stringLiteralRaw->pid->Psz() ? 0 : 1);
  6865. }
  6866. switch (m_token.tk)
  6867. {
  6868. case tkStrTmplEnd:
  6869. case tkStrTmplBasic:
  6870. // We do not need to parse an expression for either the end or basic string template tokens
  6871. templateClosed = true;
  6872. break;
  6873. case tkStrTmplBegin:
  6874. case tkStrTmplMid:
  6875. {
  6876. // In the middle or begin string template token case, we need to parse an expression next
  6877. this->GetScanner()->Scan();
  6878. // Parse the contents of the curly braces as an expression
  6879. ParseNodePtr expression = ParseExpr<buildAST>(0);
  6880. // After parsing expression, scan should leave us with an RCurly token.
  6881. // Use the NoScan version so we do not automatically perform a scan - we need to
  6882. // set the scan state before next scan but we don't want to set that state if
  6883. // the token is not as expected since we'll error in that case.
  6884. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6885. // Notify the scanner that it should scan for a middle or end string template token
  6886. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  6887. this->GetScanner()->Scan();
  6888. if (buildAST)
  6889. {
  6890. // If we are going to call the tag function, add this expression into the list of args
  6891. if (isTagged)
  6892. {
  6893. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);
  6894. }
  6895. else
  6896. {
  6897. // Otherwise add it to the substitution expression list
  6898. // TODO: Store the arguments and substitution expressions in a single list?
  6899. AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);
  6900. }
  6901. }
  6902. if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))
  6903. {
  6904. // Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return
  6905. // tkStrTmpMid/End unless it is EOF or tkScanError
  6906. Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);
  6907. Error(ERRsyntax);
  6908. }
  6909. OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u("Parsed expression\n"));
  6910. }
  6911. break;
  6912. default:
  6913. Assert(false);
  6914. break;
  6915. }
  6916. }
  6917. if (buildAST)
  6918. {
  6919. pnodeStringTemplate->pnodeStringLiterals = pnodeStringLiterals;
  6920. pnodeStringTemplate->pnodeStringRawLiterals = pnodeRawStringLiterals;
  6921. pnodeStringTemplate->pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;
  6922. pnodeStringTemplate->countStringLiterals = stringConstantCount;
  6923. // We should still have the last string literal.
  6924. // Use the char offset of the end of that constant as the end of the string template.
  6925. pnodeStringTemplate->ichLim = stringLiteral->ichLim;
  6926. // If this is a tagged template, we now have the argument list and can construct a call node
  6927. if (isTagged)
  6928. {
  6929. // Return the call node here and let the byte code generator Emit the string template automagically
  6930. ParseNodeCall * pnodeCall;
  6931. pnodeReturn = pnodeCall = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);
  6932. // We need to set the arg count explicitly
  6933. pnodeCall->argCount = stringConstantCount;
  6934. pnodeCall->hasDestructuring = m_hasDestructuringPattern;
  6935. }
  6936. }
  6937. this->GetScanner()->Scan();
  6938. return pnodeReturn;
  6939. }
  6940. LPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)
  6941. {
  6942. // propertyString could be null, such as 'this.foo' =
  6943. // propertyString could be empty, found in pattern as in (-1)[""][(x = z)]
  6944. OpCode op = pNode->nop;
  6945. LPCOLESTR rightNode = nullptr;
  6946. if (propertyString == nullptr)
  6947. {
  6948. propertyString = _u("");
  6949. }
  6950. if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)
  6951. {
  6952. rightNode = _u("");
  6953. }
  6954. else if (op == knopStr)
  6955. {
  6956. return AppendNameHints(propertyString, pNode->AsParseNodeStr()->pid, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  6957. }
  6958. else if (op == knopFlt)
  6959. {
  6960. rightNode = this->GetScanner()->StringFromDbl(pNode->AsParseNodeFloat()->dbl);
  6961. }
  6962. else
  6963. {
  6964. rightNode = op == knopInt ? this->GetScanner()->StringFromLong(pNode->AsParseNodeInt()->lw)
  6965. : pNode->AsParseNodeName()->pid->Psz();
  6966. }
  6967. return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  6968. }
  6969. LPCOLESTR Parser::ConstructNameHint(ParseNodeBin * pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)
  6970. {
  6971. Assert(pNode != nullptr);
  6972. Assert(pNode->nop == knopDot || pNode->nop == knopIndex);
  6973. // This method recursively visits nodes in the AST and could cause an SOE crash for long knopDot chains.
  6974. // Although this method could be made non-recursive, Emit (ByteCodeEmitter.cpp) hits a stack probe
  6975. // for shorter chains than which cause SOE here, so add a stack probe to throw SOE rather than crash on SOE.
  6976. // Because of that correspondence, use Js::Constants::MinStackByteCodeVisitor (which is used in Emit)
  6977. // for the stack probe here. See OS#14711878.
  6978. PROBE_STACK_NO_DISPOSE(this->m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  6979. LPCOLESTR leftNode = nullptr;
  6980. if (pNode->pnode1->nop == knopDot || pNode->pnode1->nop == knopIndex)
  6981. {
  6982. leftNode = ConstructNameHint(pNode->pnode1->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  6983. }
  6984. else if (pNode->pnode1->nop == knopName && !pNode->pnode1->AsParseNodeName()->IsSpecialName())
  6985. {
  6986. // We need to skip special names like 'this' because those shouldn't be appended to the
  6987. // name hint in the debugger stack trace.
  6988. // function ctor() {
  6989. // this.func = function() {
  6990. // // If we break here, the stack should say we are in 'func' and not 'this.func'
  6991. // }
  6992. // }
  6993. IdentPtr pid = pNode->pnode1->AsParseNodeName()->pid;
  6994. leftNode = pid->Psz();
  6995. *fullNameHintLength = pid->Cch();
  6996. *pShortNameOffset = 0;
  6997. }
  6998. if (pNode->nop == knopIndex)
  6999. {
  7000. return FormatPropertyString(
  7001. leftNode ? leftNode : Js::Constants::AnonymousFunction, // e.g. f()[0] = function () {}
  7002. pNode->pnode2, fullNameHintLength, pShortNameOffset);
  7003. }
  7004. Assert(pNode->pnode2->nop == knopDot || pNode->pnode2->nop == knopName);
  7005. LPCOLESTR rightNode = nullptr;
  7006. bool wrapWithBrackets = false;
  7007. if (pNode->pnode2->nop == knopDot)
  7008. {
  7009. rightNode = ConstructNameHint(pNode->pnode2->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  7010. }
  7011. else
  7012. {
  7013. rightNode = pNode->pnode2->AsParseNodeName()->pid->Psz();
  7014. wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);
  7015. }
  7016. Assert(rightNode != nullptr);
  7017. return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);
  7018. }
  7019. LPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7020. {
  7021. Assert(rightStr != nullptr);
  7022. Assert(leftLen != 0 || wrapInBrackets);
  7023. Assert(rightLen != 0 || wrapInBrackets);
  7024. 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
  7025. uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); // 1 (for dot or [) + 1 (for null termination)
  7026. if (wrapInBrackets)
  7027. {
  7028. totalLength++; //1 for ']';
  7029. }
  7030. WCHAR * finalName = AllocateStringOfLength(totalLength);
  7031. if (leftStr != nullptr && leftLen != 0)
  7032. {
  7033. wcscpy_s(finalName, leftLen + 1, leftStr);
  7034. }
  7035. if (ignoreAddDotWithSpace)
  7036. {
  7037. finalName[leftLen++] = (OLECHAR)_u(' ');
  7038. }
  7039. // mutually exclusive from ignoreAddDotWithSpace which is used for getters/setters
  7040. else if (wrapInBrackets)
  7041. {
  7042. finalName[leftLen++] = (OLECHAR)_u('[');
  7043. finalName[totalLength - 2] = (OLECHAR)_u(']');
  7044. }
  7045. else if (!ignoreDot)
  7046. {
  7047. finalName[leftLen++] = (OLECHAR)_u('.');
  7048. }
  7049. //ignore case falls through
  7050. js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);
  7051. finalName[totalLength - 1] = (OLECHAR)_u('\0');
  7052. if (pNameLength != nullptr)
  7053. {
  7054. *pNameLength = totalLength - 1;
  7055. }
  7056. if (pShortNameOffset != nullptr)
  7057. {
  7058. *pShortNameOffset = leftLen;
  7059. }
  7060. return finalName;
  7061. }
  7062. WCHAR * Parser::AllocateStringOfLength(ULONG length)
  7063. {
  7064. Assert(length > 0);
  7065. ULONG totalBytes;
  7066. if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)
  7067. {
  7068. Error(ERRnoMemory);
  7069. }
  7070. WCHAR* finalName = (WCHAR*)this->GetHashTbl()->GetAllocator()->Alloc(totalBytes);
  7071. if (finalName == nullptr)
  7072. {
  7073. Error(ERRnoMemory);
  7074. }
  7075. return finalName;
  7076. }
  7077. LPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7078. {
  7079. if (pShortNameOffset != nullptr)
  7080. {
  7081. *pShortNameOffset = 0;
  7082. }
  7083. if (left == nullptr && !wrapInBrackets)
  7084. {
  7085. if (right)
  7086. {
  7087. *pNameLength = right->Cch();
  7088. return right->Psz();
  7089. }
  7090. return nullptr;
  7091. }
  7092. uint32 leftLen = 0;
  7093. LPCOLESTR leftStr = _u("");
  7094. if (left != nullptr) // if wrapInBrackets is true
  7095. {
  7096. leftStr = left->Psz();
  7097. leftLen = left->Cch();
  7098. }
  7099. if (right == nullptr)
  7100. {
  7101. *pNameLength = leftLen;
  7102. return left->Psz();
  7103. }
  7104. uint32 rightLen = right->Cch();
  7105. return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7106. }
  7107. LPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7108. {
  7109. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7110. if (pShortNameOffset != nullptr)
  7111. {
  7112. *pShortNameOffset = 0;
  7113. }
  7114. Assert(rightLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7115. if (left == nullptr && !wrapInBrackets)
  7116. {
  7117. *pNameLength = rightLen;
  7118. return right;
  7119. }
  7120. LPCOLESTR leftStr = _u("");
  7121. uint32 leftLen = 0;
  7122. if (left != nullptr) // if wrapInBrackets is true
  7123. {
  7124. leftStr = left->Psz();
  7125. leftLen = left->Cch();
  7126. }
  7127. if (rightLen == 0 && !wrapInBrackets)
  7128. {
  7129. *pNameLength = leftLen;
  7130. return left->Psz();
  7131. }
  7132. return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7133. }
  7134. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7135. {
  7136. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7137. if (pShortNameOffset != nullptr)
  7138. {
  7139. *pShortNameOffset = 0;
  7140. }
  7141. Assert(leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7142. if (left == nullptr || (leftLen == 0 && !wrapInBrackets))
  7143. {
  7144. if (right != nullptr)
  7145. {
  7146. *pNameLength = right->Cch();
  7147. return right->Psz();
  7148. }
  7149. return nullptr;
  7150. }
  7151. if (right == nullptr)
  7152. {
  7153. *pNameLength = leftLen;
  7154. return left;
  7155. }
  7156. uint32 rightLen = right->Cch();
  7157. return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7158. }
  7159. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7160. {
  7161. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7162. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7163. if (pShortNameOffset != nullptr)
  7164. {
  7165. *pShortNameOffset = 0;
  7166. }
  7167. Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7168. if (leftLen == 0 && !wrapInBrackets)
  7169. {
  7170. *pNameLength = right ? rightLen : 0;
  7171. return right;
  7172. }
  7173. if (rightLen == 0 && !wrapInBrackets)
  7174. {
  7175. *pNameLength = leftLen;
  7176. return left;
  7177. }
  7178. return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7179. }
  7180. /**
  7181. * Emits a spread error if there is no ambiguity, or marks defers the error for
  7182. * when we can determine if it is a rest error or a spread error.
  7183. *
  7184. * The ambiguity arises when we are parsing a lambda parameter list but we have
  7185. * not seen the => token. At this point, we are either in a parenthesized
  7186. * expression or a parameter list, and cannot issue an error until the matching
  7187. * RParen has been scanned.
  7188. *
  7189. * The actual emission of the error happens in ParseExpr, when we first know if
  7190. * the expression is a lambda parameter list or not.
  7191. *
  7192. */
  7193. void Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)
  7194. {
  7195. if (m_funcParenExprDepth > 0)
  7196. {
  7197. if (m_token.tk == tkRParen)
  7198. {
  7199. if (!m_deferEllipsisError)
  7200. {
  7201. // Capture only the first error instance. Because a lambda will cause a reparse in a formals context, we can assume
  7202. // that this will be a spread error. Nested paren exprs will have their own error instance.
  7203. this->GetScanner()->Capture(&m_deferEllipsisErrorLoc);
  7204. m_deferEllipsisError = true;
  7205. }
  7206. }
  7207. else
  7208. {
  7209. Error(ERRUnexpectedEllipsis);
  7210. }
  7211. }
  7212. else
  7213. {
  7214. Error(ERRInvalidSpreadUse);
  7215. }
  7216. }
  7217. bool Parser::IsTerminateToken()
  7218. {
  7219. return (m_token.tk == tkRCurly ||
  7220. m_token.tk == tkRBrack ||
  7221. m_token.tk == tkRParen ||
  7222. m_token.tk == tkSColon ||
  7223. m_token.tk == tkColon ||
  7224. m_token.tk == tkComma ||
  7225. m_token.tk == tkLimKwd ||
  7226. this->GetScanner()->FHadNewLine());
  7227. }
  7228. /***************************************************************************
  7229. Parse an optional sub expression returning null if there was no expression.
  7230. Checks for no expression by looking for a token that can follow an
  7231. Expression grammar production.
  7232. ***************************************************************************/
  7233. template<bool buildAST>
  7234. bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
  7235. {
  7236. *pnode = nullptr;
  7237. if (IsTerminateToken())
  7238. {
  7239. return false;
  7240. }
  7241. IdentToken token;
  7242. ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
  7243. // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
  7244. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7245. // is not detected at byte code gen time because of deferred parsing.
  7246. this->MarkEscapingRef(pnodeT, &token);
  7247. if (pToken)
  7248. {
  7249. *pToken = token;
  7250. }
  7251. *pnode = pnodeT;
  7252. return true;
  7253. }
  7254. /***************************************************************************
  7255. Parse a sub expression.
  7256. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7257. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7258. ***************************************************************************/
  7259. template<bool buildAST>
  7260. ParseNodePtr Parser::ParseExpr(int oplMin,
  7261. BOOL *pfCanAssign,
  7262. BOOL fAllowIn,
  7263. BOOL fAllowEllipsis,
  7264. LPCOLESTR pNameHint,
  7265. uint32 *pHintLength,
  7266. uint32 *pShortNameOffset,
  7267. _Inout_opt_ IdentToken* pToken,
  7268. bool fUnaryOrParen,
  7269. _Inout_opt_ bool* pfLikelyPattern,
  7270. _Inout_opt_ charcount_t *plastRParen)
  7271. {
  7272. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  7273. int opl;
  7274. OpCode nop;
  7275. charcount_t ichMin;
  7276. ParseNodePtr pnode = nullptr;
  7277. ParseNodePtr pnodeT = nullptr;
  7278. BOOL fCanAssign = TRUE;
  7279. bool assignmentStmt = false;
  7280. bool fIsDotOrIndex = false;
  7281. IdentToken term;
  7282. RestorePoint termStart;
  7283. uint32 hintLength = 0;
  7284. uint32 hintOffset = 0;
  7285. BOOL fLikelyPattern = FALSE;
  7286. ParserState parserState;
  7287. if (pHintLength != nullptr)
  7288. {
  7289. hintLength = *pHintLength;
  7290. }
  7291. if (pShortNameOffset != nullptr)
  7292. {
  7293. hintOffset = *pShortNameOffset;
  7294. }
  7295. EnsureStackAvailable();
  7296. // Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.
  7297. CaptureState(&parserState);
  7298. this->GetScanner()->Capture(&termStart);
  7299. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  7300. m_hasDeferredShorthandInitError = false;
  7301. // Is the current token a unary operator?
  7302. if (this->GetHashTbl()->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)
  7303. {
  7304. IdentToken operandToken;
  7305. ichMin = this->GetScanner()->IchMinTok();
  7306. if (nop == knopYield)
  7307. {
  7308. if (!this->GetScanner()->YieldIsKeywordRegion() || oplMin > opl)
  7309. {
  7310. // The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner
  7311. // is not treating yield as a keyword (!this->GetScanner()->YieldIsKeywordRegion()) occurs
  7312. // in strict mode non-generator function contexts.
  7313. //
  7314. // That is, 'yield' is a keyword because of strict mode, but YieldExpression
  7315. // is not a grammar production outside of generator functions.
  7316. //
  7317. // Otherwise it is an error for a yield to appear in the context of a higher level
  7318. // binding operator, be it unary or binary.
  7319. Error(ERRsyntax);
  7320. }
  7321. if (m_currentScope->GetScopeType() == ScopeType_Parameter
  7322. || (m_currentScope->GetScopeType() == ScopeType_Block && m_currentScope->GetEnclosingScope()->GetScopeType() == ScopeType_Parameter)) // Check whether this is a class definition inside param scope
  7323. {
  7324. Error(ERRsyntax);
  7325. }
  7326. }
  7327. else if (nop == knopAwait)
  7328. {
  7329. if (!this->GetScanner()->AwaitIsKeywordRegion() ||
  7330. m_currentScope->GetScopeType() == ScopeType_Parameter ||
  7331. (m_currentScope->GetScopeType() == ScopeType_Block && m_currentScope->GetEnclosingScope()->GetScopeType() == ScopeType_Parameter)) // Check whether this is a class definition inside param scope
  7332. {
  7333. // As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)
  7334. // but the scanner is not treating await as a keyword (!this->GetScanner()->AwaitIsKeyword())
  7335. // occurs in strict mode non-async function contexts.
  7336. //
  7337. // That is, 'await' is a keyword because of strict mode, but AwaitExpression
  7338. // is not a grammar production outside of async functions.
  7339. //
  7340. // Further, await expressions are disallowed within parameter scopes.
  7341. Error(ERRBadAwait);
  7342. }
  7343. }
  7344. this->GetScanner()->Scan();
  7345. if (m_token.tk == tkEllipsis) {
  7346. // ... cannot have a unary prefix.
  7347. Error(ERRUnexpectedEllipsis);
  7348. }
  7349. if (nop == knopYield && !this->GetScanner()->FHadNewLine() && m_token.tk == tkStar)
  7350. {
  7351. this->GetScanner()->Scan();
  7352. nop = knopYieldStar;
  7353. }
  7354. if (nop == knopYield)
  7355. {
  7356. if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, TRUE, fAllowEllipsis))
  7357. {
  7358. nop = knopYieldLeaf;
  7359. if (buildAST)
  7360. {
  7361. pnode = CreateNodeForOpT<knopYieldLeaf>(ichMin, this->GetScanner()->IchLimTok());
  7362. }
  7363. }
  7364. }
  7365. else
  7366. {
  7367. // Disallow spread after a unary operator.
  7368. pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr /*hint*/, nullptr /*hintLength*/, nullptr /*hintOffset*/, &operandToken, true, nullptr, plastRParen);
  7369. }
  7370. if (nop != knopYieldLeaf)
  7371. {
  7372. if ((nop == knopIncPre || nop == knopDecPre) && (m_token.tk != tkDArrow))
  7373. {
  7374. if (!fCanAssign &&
  7375. (m_sourceContextInfo
  7376. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7377. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7378. {
  7379. Error(JSERR_CantAssignTo);
  7380. }
  7381. TrackAssignment<buildAST>(pnodeT, &operandToken);
  7382. if (buildAST)
  7383. {
  7384. if (IsStrictMode() && pnodeT->nop == knopName)
  7385. {
  7386. CheckStrictModeEvalArgumentsUsage(pnodeT->AsParseNodeName()->pid);
  7387. }
  7388. }
  7389. else
  7390. {
  7391. if (IsStrictMode() && operandToken.tk == tkID)
  7392. {
  7393. CheckStrictModeEvalArgumentsUsage(operandToken.pid);
  7394. }
  7395. }
  7396. }
  7397. else if (nop == knopEllipsis)
  7398. {
  7399. if (!fAllowEllipsis)
  7400. {
  7401. DeferOrEmitPotentialSpreadError(pnodeT);
  7402. }
  7403. }
  7404. else if (m_token.tk == tkExpo)
  7405. {
  7406. //Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...
  7407. Error(ERRInvalidUseofExponentiationOperator);
  7408. }
  7409. if (buildAST)
  7410. {
  7411. //Do not do the folding for Asm in case of KnopPos as we need this to determine the type
  7412. if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)
  7413. {
  7414. // Fold away a unary '+' on a number.
  7415. pnode = pnodeT;
  7416. }
  7417. else if (nop == knopNeg &&
  7418. ((pnodeT->nop == knopInt && pnodeT->AsParseNodeInt()->lw != 0) ||
  7419. (pnodeT->nop == knopFlt && (pnodeT->AsParseNodeFloat()->dbl != 0 || this->m_InAsmMode))))
  7420. {
  7421. // Fold a unary '-' on a number into the value of the number itself.
  7422. pnode = pnodeT;
  7423. if (pnode->nop == knopInt)
  7424. {
  7425. pnode->AsParseNodeInt()->lw = -pnode->AsParseNodeInt()->lw;
  7426. }
  7427. else
  7428. {
  7429. pnode->AsParseNodeFloat()->dbl = -pnode->AsParseNodeFloat()->dbl;
  7430. }
  7431. }
  7432. else
  7433. {
  7434. pnode = CreateUniNode(nop, pnodeT);
  7435. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  7436. }
  7437. pnode->ichMin = ichMin;
  7438. }
  7439. if (nop == knopDelete)
  7440. {
  7441. if (IsStrictMode())
  7442. {
  7443. if ((buildAST && pnode->AsParseNodeUni()->pnode1->IsUserIdentifier()) ||
  7444. (!buildAST && operandToken.tk == tkID && !this->IsSpecialName(operandToken.pid)))
  7445. {
  7446. Error(ERRInvalidDelete);
  7447. }
  7448. }
  7449. if (buildAST)
  7450. {
  7451. ParseNodePtr pnode1 = pnode->AsParseNodeUni()->pnode1;
  7452. if (m_currentNodeFunc)
  7453. {
  7454. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  7455. {
  7456. // If we delete an arguments property, use the conservative,
  7457. // heap-allocated arguments object.
  7458. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  7459. }
  7460. }
  7461. }
  7462. }
  7463. }
  7464. fCanAssign = FALSE;
  7465. }
  7466. else
  7467. {
  7468. ichMin = this->GetScanner()->IchMinTok();
  7469. pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, TRUE, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex, plastRParen);
  7470. if (pfLikelyPattern != nullptr)
  7471. {
  7472. *pfLikelyPattern = !!fLikelyPattern;
  7473. }
  7474. if (m_token.tk == tkDArrow
  7475. // If we have introduced shorthand error above in the ParseExpr, we need to reset if next token is the assignment.
  7476. || (m_token.tk == tkAsg && oplMin <= koplAsg))
  7477. {
  7478. m_hasDeferredShorthandInitError = false;
  7479. }
  7480. if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)
  7481. {
  7482. this->GetScanner()->SeekTo(termStart);
  7483. // 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
  7484. // on the pidref stack match.
  7485. int saveNextBlockId = m_nextBlockId;
  7486. m_nextBlockId = parserState.m_nextBlockId;
  7487. ParseDestructuredLiteralWithScopeSave(tkLCurly, false/*isDecl*/, false /*topLevel*/, DIC_ShouldNotParseInitializer);
  7488. // 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
  7489. // because we don't parse initializers during reparse and there may be additional blocks (e.g. a class declaration)
  7490. // in the initializers that will cause the next Block ID at the end of the reparsing to be different.
  7491. m_nextBlockId = saveNextBlockId;
  7492. if (buildAST)
  7493. {
  7494. this->SetHasDestructuringPattern(true);
  7495. pnode = ConvertToPattern(pnode);
  7496. }
  7497. }
  7498. if (buildAST)
  7499. {
  7500. pNameHint = NULL;
  7501. if (pnode->nop == knopName)
  7502. {
  7503. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7504. pNameHint = pid->Psz();
  7505. hintLength = pid->Cch();
  7506. hintOffset = 0;
  7507. }
  7508. else if (pnode->nop == knopDot || pnode->nop == knopIndex)
  7509. {
  7510. if (CONFIG_FLAG(UseFullName))
  7511. {
  7512. pNameHint = ConstructNameHint(pnode->AsParseNodeBin(), &hintLength, &hintOffset);
  7513. }
  7514. else
  7515. {
  7516. ParseNodePtr pnodeName = pnode;
  7517. while (pnodeName->nop == knopDot)
  7518. {
  7519. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  7520. }
  7521. if (pnodeName->nop == knopName)
  7522. {
  7523. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7524. pNameHint = pid->Psz();
  7525. hintLength = pid->Cch();
  7526. hintOffset = 0;
  7527. }
  7528. }
  7529. }
  7530. }
  7531. // Check for postfix unary operators.
  7532. if (!this->GetScanner()->FHadNewLine() &&
  7533. (tkInc == m_token.tk || tkDec == m_token.tk))
  7534. {
  7535. if (!fCanAssign &&
  7536. (m_sourceContextInfo
  7537. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7538. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7539. {
  7540. Error(JSERR_CantAssignTo);
  7541. }
  7542. TrackAssignment<buildAST>(pnode, &term);
  7543. fCanAssign = FALSE;
  7544. if (buildAST)
  7545. {
  7546. if (IsStrictMode() && pnode->nop == knopName)
  7547. {
  7548. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7549. }
  7550. this->CheckArguments(pnode);
  7551. pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);
  7552. pnode->ichLim = this->GetScanner()->IchLimTok();
  7553. }
  7554. else
  7555. {
  7556. if (IsStrictMode() && term.tk == tkID)
  7557. {
  7558. CheckStrictModeEvalArgumentsUsage(term.pid);
  7559. }
  7560. // This expression is not an identifier
  7561. term.tk = tkNone;
  7562. }
  7563. this->GetScanner()->Scan();
  7564. }
  7565. }
  7566. // Process a sequence of operators and operands.
  7567. for (;;)
  7568. {
  7569. if (!this->GetHashTbl()->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)
  7570. {
  7571. break;
  7572. }
  7573. if (!fAllowIn && nop == knopIn)
  7574. {
  7575. break;
  7576. }
  7577. Assert(opl != koplNo);
  7578. if (opl == koplAsg)
  7579. {
  7580. if (m_token.tk != tkDArrow)
  7581. {
  7582. // Assignment operator. These are the only right associative
  7583. // binary operators. We also need to special case the left
  7584. // operand - it should only be a LeftHandSideExpression.
  7585. Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);
  7586. TrackAssignment<buildAST>(pnode, &term);
  7587. if (buildAST)
  7588. {
  7589. if (IsStrictMode() && pnode->nop == knopName)
  7590. {
  7591. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7592. }
  7593. // Assignment stmt of the form "this.<id> = <expr>"
  7594. if (nop == knopAsg
  7595. && pnode->nop == knopDot
  7596. && pnode->AsParseNodeBin()->pnode1->nop == knopName
  7597. && pnode->AsParseNodeBin()->pnode1->AsParseNodeName()->pid == wellKnownPropertyPids._this
  7598. && pnode->AsParseNodeBin()->pnode2->nop == knopName)
  7599. {
  7600. if (pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->pid != wellKnownPropertyPids.__proto__)
  7601. {
  7602. assignmentStmt = true;
  7603. }
  7604. }
  7605. }
  7606. else
  7607. {
  7608. if (IsStrictMode() && term.tk == tkID)
  7609. {
  7610. CheckStrictModeEvalArgumentsUsage(term.pid);
  7611. }
  7612. }
  7613. }
  7614. if (opl < oplMin)
  7615. {
  7616. break;
  7617. }
  7618. if (m_token.tk != tkDArrow && !fCanAssign &&
  7619. (m_sourceContextInfo
  7620. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7621. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7622. {
  7623. Error(JSERR_CantAssignTo);
  7624. // No recovery necessary since this is a semantic, not structural, error.
  7625. }
  7626. }
  7627. else if (opl == koplExpo)
  7628. {
  7629. // ** operator is right associative
  7630. if (opl < oplMin)
  7631. {
  7632. break;
  7633. }
  7634. }
  7635. else if (opl <= oplMin)
  7636. {
  7637. break;
  7638. }
  7639. // This expression is not an identifier
  7640. term.tk = tkNone;
  7641. // Precedence is high enough. Consume the operator token.
  7642. this->GetScanner()->Scan();
  7643. fCanAssign = !!fLikelyPattern;
  7644. // Special case the "?:" operator
  7645. if (nop == knopQmark)
  7646. {
  7647. pnodeT = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);
  7648. ChkCurTok(tkColon, ERRnoColon);
  7649. ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, plastRParen);
  7650. if (buildAST)
  7651. {
  7652. pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);
  7653. this->CheckArguments(pnode->AsParseNodeTri()->pnode2);
  7654. this->CheckArguments(pnode->AsParseNodeTri()->pnode3);
  7655. }
  7656. }
  7657. else if (nop == knopFncDecl)
  7658. {
  7659. ushort flags = fFncLambda;
  7660. size_t iecpMin = 0;
  7661. bool isAsyncMethod = false;
  7662. RestoreStateFrom(&parserState);
  7663. this->GetScanner()->SeekTo(termStart);
  7664. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  7665. {
  7666. ichMin = this->GetScanner()->IchMinTok();
  7667. iecpMin = this->GetScanner()->IecpMinTok();
  7668. this->GetScanner()->Scan();
  7669. if ((m_token.tk == tkID || m_token.tk == tkLParen) && !this->GetScanner()->FHadNewLine())
  7670. {
  7671. flags |= fFncAsync;
  7672. isAsyncMethod = true;
  7673. }
  7674. else
  7675. {
  7676. this->GetScanner()->SeekTo(termStart);
  7677. }
  7678. }
  7679. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan = */false, /* resetParsingSuperRestrictionState = */false, /* fUnaryOrParen = */ false, fAllowIn);
  7680. if (isAsyncMethod)
  7681. {
  7682. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  7683. pnode->ichMin = ichMin;
  7684. }
  7685. // ArrowFunction/AsyncArrowFunction is part of AssignmentExpression, which should terminate the expression unless followed by a comma
  7686. if (m_token.tk != tkComma && m_token.tk != tkIN)
  7687. {
  7688. if (!(IsTerminateToken()))
  7689. {
  7690. Error(ERRnoSemic);
  7691. }
  7692. break;
  7693. }
  7694. }
  7695. else // a binary operator
  7696. {
  7697. ParseNode* pnode1 = pnode;
  7698. // Parse the operand, make a new node, and look for more
  7699. IdentToken token;
  7700. ParseNode* pnode2 = ParseExpr<buildAST>(
  7701. opl, nullptr, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token, false, nullptr, plastRParen);
  7702. // Detect nested function escapes of the pattern "o.f = function(){...}" or "o[s] = function(){...}".
  7703. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7704. // is not detected at byte code gen time because of deferred parsing.
  7705. if (fIsDotOrIndex && nop == knopAsg)
  7706. {
  7707. this->MarkEscapingRef(pnodeT, &token);
  7708. }
  7709. if (buildAST)
  7710. {
  7711. Assert(pnode2 != nullptr);
  7712. if (pnode2->nop == knopFncDecl)
  7713. {
  7714. Assert(hintLength >= hintOffset);
  7715. pnode2->AsParseNodeFnc()->hint = pNameHint;
  7716. pnode2->AsParseNodeFnc()->hintLength = hintLength;
  7717. pnode2->AsParseNodeFnc()->hintOffset = hintOffset;
  7718. if (pnode1->nop == knopDot)
  7719. {
  7720. pnode2->AsParseNodeFnc()->isNameIdentifierRef = false;
  7721. }
  7722. else if (pnode1->nop == knopName)
  7723. {
  7724. PidRefStack *pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7725. pidRef->isFuncAssignment = true;
  7726. }
  7727. }
  7728. else if (pnode2->nop == knopClassDecl && pnode1->nop == knopDot)
  7729. {
  7730. Assert(pnode2->AsParseNodeClass()->pnodeConstructor);
  7731. if (!pnode2->AsParseNodeClass()->pnodeConstructor->pid)
  7732. {
  7733. pnode2->AsParseNodeClass()->pnodeConstructor->isNameIdentifierRef = false;
  7734. }
  7735. }
  7736. else if (pnode1->nop == knopName && nop == knopIn)
  7737. {
  7738. PidRefStack* pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7739. pidRef->SetIsUsedInLdElem(true);
  7740. }
  7741. pnode = CreateBinNode(nop, pnode1, pnode2);
  7742. }
  7743. pNameHint = nullptr;
  7744. }
  7745. }
  7746. if (buildAST)
  7747. {
  7748. if (!assignmentStmt)
  7749. {
  7750. // Don't set the flag for following nodes
  7751. switch (pnode->nop)
  7752. {
  7753. case knopName:
  7754. case knopInt:
  7755. case knopFlt:
  7756. case knopStr:
  7757. case knopRegExp:
  7758. case knopNull:
  7759. case knopFalse:
  7760. case knopTrue:
  7761. break;
  7762. default:
  7763. if (m_currentNodeFunc)
  7764. {
  7765. m_currentNodeFunc->SetHasNonThisStmt();
  7766. }
  7767. else if (m_currentNodeProg)
  7768. {
  7769. m_currentNodeProg->SetHasNonThisStmt();
  7770. }
  7771. }
  7772. }
  7773. }
  7774. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;
  7775. if (NULL != pfCanAssign)
  7776. {
  7777. *pfCanAssign = fCanAssign;
  7778. }
  7779. // Pass back identifier if requested
  7780. if (pToken && term.tk == tkID)
  7781. {
  7782. *pToken = term;
  7783. }
  7784. //Track "obj.a" assignment patterns here - Promote the Assignment state for the property's PID.
  7785. // This includes =, += etc.
  7786. if (pnode != NULL)
  7787. {
  7788. uint nodeType = ParseNode::Grfnop(pnode->nop);
  7789. if (nodeType & fnopAsg)
  7790. {
  7791. if (nodeType & fnopBin)
  7792. {
  7793. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  7794. Assert(lhs);
  7795. if (lhs->nop == knopDot)
  7796. {
  7797. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7798. if (propertyNode->nop == knopName)
  7799. {
  7800. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  7801. }
  7802. }
  7803. }
  7804. else if (nodeType & fnopUni)
  7805. {
  7806. // cases like obj.a++, ++obj.a
  7807. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  7808. if (lhs->nop == knopDot)
  7809. {
  7810. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7811. if (propertyNode->nop == knopName)
  7812. {
  7813. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  7814. }
  7815. }
  7816. }
  7817. }
  7818. }
  7819. return pnode;
  7820. }
  7821. template<bool buildAST>
  7822. void Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)
  7823. {
  7824. if (buildAST)
  7825. {
  7826. Assert(pnodeT != nullptr);
  7827. if (pnodeT->nop == knopName)
  7828. {
  7829. PidRefStack *ref = pnodeT->AsParseNodeName()->pid->GetTopRef();
  7830. Assert(ref);
  7831. ref->isAsg = true;
  7832. }
  7833. }
  7834. else
  7835. {
  7836. Assert(pToken != nullptr);
  7837. if (pToken->tk == tkID)
  7838. {
  7839. PidRefStack *ref = pToken->pid->GetTopRef();
  7840. Assert(ref);
  7841. ref->isAsg = true;
  7842. }
  7843. }
  7844. }
  7845. PidRefStack* Parser::PushPidRef(IdentPtr pid)
  7846. {
  7847. ParseNodeFnc* currentFnc = GetCurrentFunctionNode();
  7848. if (this->IsCreatingStateCache())
  7849. {
  7850. IdentPtrSet* capturedNames = currentFnc->EnsureCapturedNames(&m_nodeAllocator);
  7851. capturedNames->AddNew(pid);
  7852. }
  7853. if (PHASE_ON1(Js::ParallelParsePhase))
  7854. {
  7855. // NOTE: the phase check is here to protect perf. See OSG 1020424.
  7856. // In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather
  7857. // than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.
  7858. return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->blockId, currentFnc->functionId);
  7859. }
  7860. Assert(GetCurrentBlock() != nullptr);
  7861. AssertMsg(pid != nullptr, "PID should be created");
  7862. PidRefStack *ref = pid->GetTopRef(m_nextBlockId - 1);
  7863. int blockId = GetCurrentBlock()->blockId;
  7864. int funcId = currentFnc->functionId;
  7865. if (!ref || (ref->GetScopeId() < blockId))
  7866. {
  7867. ref = Anew(&m_nodeAllocator, PidRefStack);
  7868. if (ref == nullptr)
  7869. {
  7870. Error(ERRnoMemory);
  7871. }
  7872. pid->PushPidRef(blockId, funcId, ref);
  7873. }
  7874. else if (m_reparsingLambdaParams)
  7875. {
  7876. // If we're reparsing params, then we may have pid refs left behind from the first pass. Make sure we're
  7877. // working with the right ref at this point.
  7878. ref = this->FindOrAddPidRef(pid, blockId, funcId);
  7879. // Fix up the function ID if we're reparsing lambda parameters.
  7880. ref->funcId = funcId;
  7881. }
  7882. return ref;
  7883. }
  7884. PidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)
  7885. {
  7886. PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);
  7887. if (ref == NULL)
  7888. {
  7889. Error(ERRnoMemory);
  7890. }
  7891. return ref;
  7892. }
  7893. void Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)
  7894. {
  7895. PidRefStack *prevRef = pid->RemovePrevPidRef(ref);
  7896. Assert(prevRef);
  7897. if (prevRef->GetSym() == nullptr)
  7898. {
  7899. AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);
  7900. }
  7901. }
  7902. void Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)
  7903. {
  7904. PidRefStack *ref = pid->GetTopRef();
  7905. while (ref && ref->GetScopeId() >= blockId)
  7906. {
  7907. ref->SetDynamicBinding();
  7908. ref = ref->prev;
  7909. }
  7910. }
  7911. ParseNodeBlock* Parser::GetFunctionBlock()
  7912. {
  7913. Assert(m_currentBlockInfo != nullptr);
  7914. return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;
  7915. }
  7916. ParseNodeBlock* Parser::GetCurrentBlock()
  7917. {
  7918. return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;
  7919. }
  7920. BlockInfoStack* Parser::GetCurrentBlockInfo()
  7921. {
  7922. return m_currentBlockInfo;
  7923. }
  7924. BlockInfoStack* Parser::GetCurrentFunctionBlockInfo()
  7925. {
  7926. return m_currentBlockInfo->pBlockInfoFunction;
  7927. }
  7928. /***************************************************************************
  7929. Parse a variable declaration.
  7930. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7931. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7932. ***************************************************************************/
  7933. template<bool buildAST>
  7934. ParseNodePtr Parser::ParseVariableDeclaration(
  7935. tokens declarationType, charcount_t ichMin,
  7936. BOOL fAllowIn/* = TRUE*/,
  7937. BOOL* pfForInOk/* = nullptr*/,
  7938. BOOL singleDefOnly/* = FALSE*/,
  7939. BOOL allowInit/* = TRUE*/,
  7940. BOOL isTopVarParse/* = TRUE*/,
  7941. BOOL isFor/* = FALSE*/,
  7942. BOOL* nativeForOk /*= nullptr*/)
  7943. {
  7944. ParseNodePtr pnodeThis = nullptr;
  7945. ParseNodePtr pnodeInit;
  7946. ParseNodePtr pnodeList = nullptr;
  7947. ParseNodePtr *lastNodeRef = nullptr;
  7948. LPCOLESTR pNameHint = nullptr;
  7949. uint32 nameHintLength = 0;
  7950. uint32 nameHintOffset = 0;
  7951. Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);
  7952. for (;;)
  7953. {
  7954. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  7955. {
  7956. pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);
  7957. if (pnodeThis != nullptr)
  7958. {
  7959. pnodeThis->ichMin = ichMin;
  7960. pnodeThis->SetIsPatternDeclaration();
  7961. }
  7962. }
  7963. else
  7964. {
  7965. if (m_token.tk != tkID)
  7966. {
  7967. IdentifierExpectedError(m_token);
  7968. }
  7969. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  7970. Assert(pid);
  7971. pNameHint = pid->Psz();
  7972. nameHintLength = pid->Cch();
  7973. nameHintOffset = 0;
  7974. if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))
  7975. {
  7976. Error(ERRLetIDInLexicalDecl, pnodeThis);
  7977. }
  7978. if (declarationType == tkVAR)
  7979. {
  7980. pnodeThis = CreateVarDeclNode(pid, STVariable);
  7981. }
  7982. else if (declarationType == tkCONST)
  7983. {
  7984. pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);
  7985. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Const, m_scriptContext);
  7986. }
  7987. else
  7988. {
  7989. pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);
  7990. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Let, m_scriptContext);
  7991. }
  7992. if (pid == wellKnownPropertyPids.arguments)
  7993. {
  7994. // This var declaration may change the way an 'arguments' identifier in the function is resolved
  7995. if (declarationType == tkVAR)
  7996. {
  7997. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_varDeclaration;
  7998. }
  7999. else
  8000. {
  8001. if (GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  8002. {
  8003. // Only override arguments if we are at the function block level.
  8004. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  8005. }
  8006. }
  8007. }
  8008. if (pnodeThis)
  8009. {
  8010. pnodeThis->ichMin = ichMin;
  8011. }
  8012. this->GetScanner()->Scan();
  8013. if (m_token.tk == tkAsg)
  8014. {
  8015. if (!allowInit)
  8016. {
  8017. Error(ERRUnexpectedDefault);
  8018. }
  8019. if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))
  8020. {
  8021. *pfForInOk = FALSE;
  8022. }
  8023. this->GetScanner()->Scan();
  8024. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  8025. if (buildAST)
  8026. {
  8027. AnalysisAssert(pnodeThis);
  8028. pnodeThis->AsParseNodeVar()->pnodeInit = pnodeInit;
  8029. pnodeThis->ichLim = pnodeInit->ichLim;
  8030. if (pnodeInit->nop == knopFncDecl)
  8031. {
  8032. Assert(nameHintLength >= nameHintOffset);
  8033. pnodeInit->AsParseNodeFnc()->hint = pNameHint;
  8034. pnodeInit->AsParseNodeFnc()->hintLength = nameHintLength;
  8035. pnodeInit->AsParseNodeFnc()->hintOffset = nameHintOffset;
  8036. pnodeThis->AsParseNodeVar()->pid->GetTopRef()->isFuncAssignment = true;
  8037. }
  8038. else
  8039. {
  8040. this->CheckArguments(pnodeInit);
  8041. }
  8042. pNameHint = nullptr;
  8043. }
  8044. //Track var a =, let a= , const a =
  8045. // This is for FixedFields Constant Heuristics
  8046. if (pnodeThis && pnodeThis->AsParseNodeVar()->pnodeInit != nullptr)
  8047. {
  8048. pnodeThis->AsParseNodeVar()->sym->PromoteAssignmentState();
  8049. }
  8050. }
  8051. else if (declarationType == tkCONST /*pnodeThis->nop == knopConstDecl*/
  8052. && !singleDefOnly
  8053. && !(isFor && TokIsForInOrForOf()))
  8054. {
  8055. Error(ERRUninitializedConst);
  8056. }
  8057. if (m_currentNodeFunc && pnodeThis && pnodeThis->AsParseNodeVar()->sym->GetIsFormal())
  8058. {
  8059. m_currentNodeFunc->SetHasAnyWriteToFormals(true);
  8060. }
  8061. }
  8062. if (singleDefOnly)
  8063. {
  8064. return pnodeThis;
  8065. }
  8066. if (buildAST)
  8067. {
  8068. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);
  8069. }
  8070. if (m_token.tk != tkComma)
  8071. {
  8072. return pnodeList;
  8073. }
  8074. if (pfForInOk)
  8075. {
  8076. // don't allow "for (var a, b in c)"
  8077. *pfForInOk = FALSE;
  8078. }
  8079. this->GetScanner()->Scan();
  8080. ichMin = this->GetScanner()->IchMinTok();
  8081. }
  8082. }
  8083. /***************************************************************************
  8084. Parse try-catch-finally statement
  8085. ***************************************************************************/
  8086. // The try-catch-finally tree nests the try-catch within a try-finally.
  8087. // This matches the new runtime implementation.
  8088. template<bool buildAST>
  8089. ParseNodeStmt * Parser::ParseTryCatchFinally()
  8090. {
  8091. this->m_tryCatchOrFinallyDepth++;
  8092. ParseNodeTry * pnodeT = ParseTry<buildAST>();
  8093. ParseNodeTryCatch * pnodeTC = nullptr;
  8094. StmtNest stmt;
  8095. bool hasCatch = false;
  8096. if (tkCATCH == m_token.tk)
  8097. {
  8098. hasCatch = true;
  8099. if (buildAST)
  8100. {
  8101. pnodeTC = CreateNodeForOpT<knopTryCatch>();
  8102. pnodeT->pnodeOuter = pnodeTC;
  8103. pnodeTC->pnodeTry = pnodeT;
  8104. }
  8105. PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr);
  8106. ParseNodeCatch * pnodeCatch = ParseCatch<buildAST>();
  8107. if (buildAST)
  8108. {
  8109. pnodeTC->pnodeCatch = pnodeCatch;
  8110. }
  8111. PopStmt(&stmt);
  8112. }
  8113. if (tkFINALLY != m_token.tk)
  8114. {
  8115. if (!hasCatch)
  8116. {
  8117. Error(ERRnoCatch);
  8118. }
  8119. Assert(!buildAST || pnodeTC);
  8120. this->m_tryCatchOrFinallyDepth--;
  8121. return pnodeTC;
  8122. }
  8123. ParseNodeTryFinally * pnodeTF = nullptr;
  8124. if (buildAST)
  8125. {
  8126. pnodeTF = CreateNodeForOpT<knopTryFinally>();
  8127. }
  8128. PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr);
  8129. ParseNodeFinally * pnodeFinally = ParseFinally<buildAST>();
  8130. if (buildAST)
  8131. {
  8132. if (!hasCatch)
  8133. {
  8134. pnodeTF->pnodeTry = pnodeT;
  8135. pnodeT->pnodeOuter = pnodeTF;
  8136. }
  8137. else
  8138. {
  8139. pnodeTF->pnodeTry = CreateNodeForOpT<knopTry>();
  8140. pnodeTF->pnodeTry->pnodeOuter = pnodeTF;
  8141. pnodeTF->pnodeTry->pnodeBody = pnodeTC;
  8142. pnodeTC->pnodeOuter = pnodeTF->pnodeTry;
  8143. }
  8144. pnodeTF->pnodeFinally = pnodeFinally;
  8145. }
  8146. PopStmt(&stmt);
  8147. this->m_tryCatchOrFinallyDepth--;
  8148. return pnodeTF;
  8149. }
  8150. template<bool buildAST>
  8151. ParseNodeTry * Parser::ParseTry()
  8152. {
  8153. ParseNodeTry * pnode = nullptr;
  8154. StmtNest stmt;
  8155. Assert(tkTRY == m_token.tk);
  8156. if (buildAST)
  8157. {
  8158. pnode = CreateNodeForOpT<knopTry>();
  8159. }
  8160. this->GetScanner()->Scan();
  8161. if (tkLCurly != m_token.tk)
  8162. {
  8163. Error(ERRnoLcurly);
  8164. }
  8165. PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr);
  8166. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8167. if (buildAST)
  8168. {
  8169. pnode->pnodeBody = pnodeBody;
  8170. if (pnode->pnodeBody)
  8171. pnode->ichLim = pnode->pnodeBody->ichLim;
  8172. }
  8173. PopStmt(&stmt);
  8174. return pnode;
  8175. }
  8176. template<bool buildAST>
  8177. ParseNodeFinally * Parser::ParseFinally()
  8178. {
  8179. ParseNodeFinally * pnode = nullptr;
  8180. StmtNest stmt;
  8181. Assert(tkFINALLY == m_token.tk);
  8182. if (buildAST)
  8183. {
  8184. pnode = CreateNodeForOpT<knopFinally>();
  8185. }
  8186. this->GetScanner()->Scan();
  8187. if (tkLCurly != m_token.tk)
  8188. {
  8189. Error(ERRnoLcurly);
  8190. }
  8191. PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr);
  8192. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8193. if (buildAST)
  8194. {
  8195. pnode->pnodeBody = pnodeBody;
  8196. if (!pnode->pnodeBody)
  8197. // Will only occur due to error correction.
  8198. pnode->pnodeBody = CreateNodeForOpT<knopEmpty>();
  8199. else
  8200. pnode->ichLim = pnode->pnodeBody->ichLim;
  8201. }
  8202. PopStmt(&stmt);
  8203. return pnode;
  8204. }
  8205. template<bool buildAST>
  8206. ParseNodeCatch * Parser::ParseCatch()
  8207. {
  8208. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8209. ParseNodeCatch * pnode = nullptr;
  8210. ParseNodeBlock * pnodeCatchScope = nullptr;
  8211. StmtNest stmt;
  8212. IdentPtr pidCatch = nullptr;
  8213. if (tkCATCH == m_token.tk)
  8214. {
  8215. charcount_t ichMin;
  8216. if (buildAST)
  8217. {
  8218. ichMin = this->GetScanner()->IchMinTok();
  8219. }
  8220. this->GetScanner()->Scan(); //catch
  8221. ChkCurTok(tkLParen, ERRnoLparen); //catch(
  8222. bool isPattern = false;
  8223. if (tkID != m_token.tk)
  8224. {
  8225. isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();
  8226. if (!isPattern)
  8227. {
  8228. IdentifierExpectedError(m_token);
  8229. }
  8230. }
  8231. if (buildAST)
  8232. {
  8233. pnode = CreateNodeForOpT<knopCatch>(ichMin);
  8234. pnode->pnodeNext = nullptr;
  8235. PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr);
  8236. }
  8237. pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);
  8238. if (buildAST)
  8239. {
  8240. // Add this catch to the current scope list.
  8241. if (m_ppnodeExprScope)
  8242. {
  8243. Assert(*m_ppnodeExprScope == nullptr);
  8244. *m_ppnodeExprScope = pnode;
  8245. m_ppnodeExprScope = &pnode->pnodeNext;
  8246. }
  8247. else
  8248. {
  8249. Assert(m_ppnodeScope);
  8250. Assert(*m_ppnodeScope == nullptr);
  8251. *m_ppnodeScope = pnode;
  8252. m_ppnodeScope = &pnode->pnodeNext;
  8253. }
  8254. // Keep a list of function expressions (not declarations) at this scope.
  8255. ppnodeExprScopeSave = m_ppnodeExprScope;
  8256. m_ppnodeExprScope = &pnode->pnodeScopes;
  8257. pnode->pnodeScopes = nullptr;
  8258. }
  8259. if (isPattern)
  8260. {
  8261. ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, true /*topLevel*/, DIC_ForceErrorOnInitializer);
  8262. if (buildAST)
  8263. {
  8264. pnode->SetParam(CreateParamPatternNode(pnodePattern));
  8265. Scope *scope = pnodeCatchScope->scope;
  8266. pnode->scope = scope;
  8267. }
  8268. }
  8269. else
  8270. {
  8271. if (IsStrictMode())
  8272. {
  8273. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  8274. if (pid == wellKnownPropertyPids.eval)
  8275. {
  8276. Error(ERREvalUsage);
  8277. }
  8278. else if (pid == wellKnownPropertyPids.arguments)
  8279. {
  8280. Error(ERRArgsUsage);
  8281. }
  8282. }
  8283. pidCatch = m_token.GetIdentifier(this->GetHashTbl());
  8284. PidRefStack *ref = this->FindOrAddPidRef(pidCatch, GetCurrentBlock()->blockId, GetCurrentFunctionNode()->functionId);
  8285. ParseNodeName * pnodeParam = CreateNameNode(pidCatch);
  8286. pnodeParam->SetSymRef(ref);
  8287. const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());
  8288. int nameLength = pidCatch->Cch();
  8289. SymbolName const symName(name, nameLength);
  8290. Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);
  8291. if (sym == nullptr)
  8292. {
  8293. Error(ERRnoMemory);
  8294. }
  8295. sym->SetPid(pidCatch);
  8296. Assert(ref->GetSym() == nullptr);
  8297. ref->SetSym(sym);
  8298. Scope *scope = pnodeCatchScope->scope;
  8299. scope->AddNewSymbol(sym);
  8300. if (buildAST)
  8301. {
  8302. pnode->SetParam(pnodeParam);
  8303. pnode->scope = scope;
  8304. }
  8305. this->GetScanner()->Scan();
  8306. }
  8307. charcount_t ichLim;
  8308. if (buildAST)
  8309. {
  8310. ichLim = this->GetScanner()->IchLimTok();
  8311. }
  8312. ChkCurTok(tkRParen, ERRnoRparen); //catch(id[:expr])
  8313. if (tkLCurly != m_token.tk)
  8314. {
  8315. Error(ERRnoLcurly);
  8316. }
  8317. ParseNodePtr pnodeBody = ParseStatement<buildAST>(); //catch(id[:expr]) {block}
  8318. if (buildAST)
  8319. {
  8320. pnode->pnodeBody = pnodeBody;
  8321. pnode->ichLim = ichLim;
  8322. }
  8323. if (pnodeCatchScope != nullptr)
  8324. {
  8325. FinishParseBlock(pnodeCatchScope);
  8326. }
  8327. if (pnodeCatchScope->GetCallsEval() || pnodeCatchScope->GetChildCallsEval())
  8328. {
  8329. GetCurrentBlock()->SetChildCallsEval(true);
  8330. }
  8331. if (buildAST)
  8332. {
  8333. PopStmt(&stmt);
  8334. // Restore the lists of function expression scopes.
  8335. Assert(m_ppnodeExprScope);
  8336. Assert(*m_ppnodeExprScope == nullptr);
  8337. m_ppnodeExprScope = ppnodeExprScopeSave;
  8338. }
  8339. }
  8340. return pnode;
  8341. }
  8342. template<bool buildAST>
  8343. ParseNodeCase * Parser::ParseCase(ParseNodePtr *ppnodeBody)
  8344. {
  8345. ParseNodeCase * pnodeT = nullptr;
  8346. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8347. this->GetScanner()->Scan();
  8348. ParseNodePtr pnodeExpr = ParseExpr<buildAST>();
  8349. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8350. ChkCurTok(tkColon, ERRnoColon);
  8351. if (buildAST)
  8352. {
  8353. pnodeT = CreateNodeForOpT<knopCase>(ichMinT);
  8354. pnodeT->pnodeExpr = pnodeExpr;
  8355. pnodeT->ichLim = ichLim;
  8356. }
  8357. ParseStmtList<buildAST>(ppnodeBody);
  8358. return pnodeT;
  8359. }
  8360. /***************************************************************************
  8361. Parse a single statement. Digest a trailing semicolon.
  8362. ***************************************************************************/
  8363. template<bool buildAST>
  8364. ParseNodePtr Parser::ParseStatement()
  8365. {
  8366. ParseNodePtr pnode = nullptr;
  8367. LabelId* pLabelIdList = nullptr;
  8368. charcount_t ichMin = 0;
  8369. size_t iecpMin = 0;
  8370. StmtNest stmt;
  8371. StmtNest *pstmt;
  8372. BOOL fForInOrOfOkay;
  8373. BOOL fCanAssign;
  8374. IdentPtr pid;
  8375. uint fnop;
  8376. bool expressionStmt = false;
  8377. bool isAsyncMethod = false;
  8378. tokens tok;
  8379. #if EXCEPTION_RECOVERY
  8380. ParseNodeTryCatch * pParentTryCatch = nullptr;
  8381. ParseNodeBlock * pTryBlock = nullptr;
  8382. ParseNodeTry * pTry = nullptr;
  8383. ParseNodeBlock * pParentTryCatchBlock = nullptr;
  8384. StmtNest stmtTryCatchBlock;
  8385. StmtNest stmtTryCatch;
  8386. StmtNest stmtTry;
  8387. StmtNest stmtTryBlock;
  8388. #endif
  8389. if (buildAST)
  8390. {
  8391. #if EXCEPTION_RECOVERY
  8392. if (Js::Configuration::Global.flags.SwallowExceptions)
  8393. {
  8394. // If we're swallowing exceptions, surround this statement with a try/catch block:
  8395. //
  8396. // Before: x.y = 3;
  8397. // After: try { x.y = 3; } catch(__ehobj) { }
  8398. //
  8399. // This is done to force the runtime to recover from exceptions at the most granular
  8400. // possible point. Recovering from EH dramatically improves coverage of testing via
  8401. // fault injection.
  8402. // create and push the try-catch node
  8403. pParentTryCatchBlock = CreateBlockNode();
  8404. PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr);
  8405. pParentTryCatch = CreateNodeForOpT<knopTryCatch>();
  8406. PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr);
  8407. // create and push a try node
  8408. pTry = CreateNodeForOpT<knopTry>();
  8409. PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr);
  8410. pTryBlock = CreateBlockNode();
  8411. PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr);
  8412. // these nodes will be closed after the statement is parsed.
  8413. }
  8414. #endif // EXCEPTION_RECOVERY
  8415. }
  8416. EnsureStackAvailable();
  8417. LRestart:
  8418. tok = m_token.tk;
  8419. switch (tok)
  8420. {
  8421. case tkEOF:
  8422. if (buildAST)
  8423. {
  8424. pnode = nullptr;
  8425. }
  8426. break;
  8427. case tkFUNCTION:
  8428. {
  8429. LFunctionStatement:
  8430. if (m_grfscr & fscrDeferredFncExpression)
  8431. {
  8432. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  8433. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  8434. // first time we see it.
  8435. m_grfscr &= ~fscrDeferredFncExpression;
  8436. pnode = ParseFncDeclNoCheckScope<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs);
  8437. }
  8438. else
  8439. {
  8440. pnode = ParseFncDeclCheckScope<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs));
  8441. }
  8442. if (isAsyncMethod)
  8443. {
  8444. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  8445. pnode->ichMin = ichMin;
  8446. }
  8447. break;
  8448. }
  8449. case tkCLASS:
  8450. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  8451. {
  8452. pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);
  8453. }
  8454. else
  8455. {
  8456. goto LDefaultToken;
  8457. }
  8458. break;
  8459. case tkID:
  8460. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.let)
  8461. {
  8462. // We see "let" at the start of a statement. This could either be a declaration or an identifier
  8463. // reference. The next token determines which.
  8464. RestorePoint parsedLet;
  8465. this->GetScanner()->Capture(&parsedLet);
  8466. ichMin = this->GetScanner()->IchMinTok();
  8467. this->GetScanner()->Scan();
  8468. if (this->NextTokenConfirmsLetDecl())
  8469. {
  8470. pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);
  8471. goto LNeedTerminator;
  8472. }
  8473. this->GetScanner()->SeekTo(parsedLet);
  8474. }
  8475. else if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8476. {
  8477. RestorePoint parsedAsync;
  8478. this->GetScanner()->Capture(&parsedAsync);
  8479. ichMin = this->GetScanner()->IchMinTok();
  8480. iecpMin = this->GetScanner()->IecpMinTok();
  8481. this->GetScanner()->Scan();
  8482. if (m_token.tk == tkFUNCTION && !this->GetScanner()->FHadNewLine())
  8483. {
  8484. isAsyncMethod = true;
  8485. goto LFunctionStatement;
  8486. }
  8487. this->GetScanner()->SeekTo(parsedAsync);
  8488. }
  8489. goto LDefaultToken;
  8490. case tkCONST:
  8491. case tkLET:
  8492. ichMin = this->GetScanner()->IchMinTok();
  8493. this->GetScanner()->Scan();
  8494. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8495. goto LNeedTerminator;
  8496. case tkVAR:
  8497. ichMin = this->GetScanner()->IchMinTok();
  8498. this->GetScanner()->Scan();
  8499. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8500. goto LNeedTerminator;
  8501. case tkFOR:
  8502. {
  8503. ParseNodeBlock * pnodeBlock = nullptr;
  8504. ParseNodePtr *ppnodeScopeSave = nullptr;
  8505. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8506. ichMin = this->GetScanner()->IchMinTok();
  8507. ChkNxtTok(tkLParen, ERRnoLparen);
  8508. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8509. if (buildAST)
  8510. {
  8511. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8512. }
  8513. RestorePoint startExprOrIdentifier;
  8514. fForInOrOfOkay = TRUE;
  8515. fCanAssign = TRUE;
  8516. tok = m_token.tk;
  8517. BOOL nativeForOkay = TRUE;
  8518. ParseNodePtr pnodeT;
  8519. switch (tok)
  8520. {
  8521. case tkID:
  8522. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.let)
  8523. {
  8524. // We see "let" in the init part of a for loop. This could either be a declaration or an identifier
  8525. // reference. The next token determines which.
  8526. RestorePoint parsedLet;
  8527. this->GetScanner()->Capture(&parsedLet);
  8528. auto ichMinInner = this->GetScanner()->IchMinTok();
  8529. this->GetScanner()->Scan();
  8530. if (IsPossiblePatternStart())
  8531. {
  8532. this->GetScanner()->Capture(&startExprOrIdentifier);
  8533. }
  8534. if (this->NextTokenConfirmsLetDecl() && m_token.tk != tkIN)
  8535. {
  8536. pnodeT = ParseVariableDeclaration<buildAST>(tkLET, ichMinInner
  8537. , /*fAllowIn = */FALSE
  8538. , /*pfForInOk = */&fForInOrOfOkay
  8539. , /*singleDefOnly*/FALSE
  8540. , /*allowInit*/TRUE
  8541. , /*isTopVarParse*/TRUE
  8542. , /*isFor*/TRUE
  8543. , &nativeForOkay);
  8544. break;
  8545. }
  8546. this->GetScanner()->SeekTo(parsedLet);
  8547. }
  8548. goto LDefaultTokenFor;
  8549. case tkLET:
  8550. case tkCONST:
  8551. case tkVAR:
  8552. {
  8553. auto ichMinInner = this->GetScanner()->IchMinTok();
  8554. this->GetScanner()->Scan();
  8555. if (IsPossiblePatternStart())
  8556. {
  8557. this->GetScanner()->Capture(&startExprOrIdentifier);
  8558. }
  8559. pnodeT = ParseVariableDeclaration<buildAST>(tok, ichMinInner
  8560. , /*fAllowIn = */FALSE
  8561. , /*pfForInOk = */&fForInOrOfOkay
  8562. , /*singleDefOnly*/FALSE
  8563. , /*allowInit*/TRUE
  8564. , /*isTopVarParse*/TRUE
  8565. , /*isFor*/TRUE
  8566. , &nativeForOkay);
  8567. }
  8568. break;
  8569. case tkSColon:
  8570. pnodeT = nullptr;
  8571. fForInOrOfOkay = FALSE;
  8572. break;
  8573. default:
  8574. {
  8575. LDefaultTokenFor:
  8576. RestorePoint exprStart;
  8577. tokens beforeToken = tok;
  8578. this->GetScanner()->Capture(&exprStart);
  8579. if (IsPossiblePatternStart())
  8580. {
  8581. this->GetScanner()->Capture(&startExprOrIdentifier);
  8582. }
  8583. bool fLikelyPattern = false;
  8584. if (IsES6DestructuringEnabled() && (beforeToken == tkLBrack || beforeToken == tkLCurly))
  8585. {
  8586. pnodeT = ParseExpr<buildAST>(koplNo,
  8587. &fCanAssign,
  8588. /*fAllowIn = */FALSE,
  8589. /*fAllowEllipsis*/FALSE,
  8590. /*pHint*/nullptr,
  8591. /*pHintLength*/nullptr,
  8592. /*pShortNameOffset*/nullptr,
  8593. /*pToken*/nullptr,
  8594. /**fUnaryOrParen*/false,
  8595. &fLikelyPattern);
  8596. }
  8597. else
  8598. {
  8599. pnodeT = ParseExpr<buildAST>(koplNo, &fCanAssign, /*fAllowIn = */FALSE);
  8600. }
  8601. // 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
  8602. // has already converted them appropriately.
  8603. if (fLikelyPattern && TokIsForInOrForOf())
  8604. {
  8605. this->GetScanner()->SeekTo(exprStart);
  8606. ParseDestructuredLiteralWithScopeSave(tkNone, false/*isDecl*/, false /*topLevel*/, DIC_None, false /*allowIn*/);
  8607. if (buildAST)
  8608. {
  8609. pnodeT = ConvertToPattern(pnodeT);
  8610. }
  8611. }
  8612. if (buildAST)
  8613. {
  8614. Assert(pnodeT);
  8615. pnodeT->isUsed = false;
  8616. }
  8617. }
  8618. break;
  8619. }
  8620. if (TokIsForInOrForOf())
  8621. {
  8622. bool isForOf = (m_token.tk != tkIN);
  8623. Assert(!isForOf || (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.of));
  8624. if ((buildAST && nullptr == pnodeT) || !fForInOrOfOkay)
  8625. {
  8626. if (isForOf)
  8627. {
  8628. Error(ERRForOfNoInitAllowed);
  8629. }
  8630. else
  8631. {
  8632. Error(ERRForInNoInitAllowed);
  8633. }
  8634. }
  8635. if (!fCanAssign &&
  8636. (m_sourceContextInfo
  8637. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  8638. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  8639. {
  8640. Error(ERRInvalidLHSInFor);
  8641. }
  8642. this->GetScanner()->Scan();
  8643. ParseNodePtr pnodeObj = ParseExpr<buildAST>(isForOf ? koplCma : koplNo);
  8644. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8645. ChkCurTok(tkRParen, ERRnoRparen);
  8646. ParseNodeForInOrForOf * pnodeForInOrForOf = nullptr;
  8647. if (buildAST)
  8648. {
  8649. if (isForOf)
  8650. {
  8651. pnodeForInOrForOf = CreateNodeForOpT<knopForOf>(ichMin);
  8652. }
  8653. else
  8654. {
  8655. pnodeForInOrForOf = CreateNodeForOpT<knopForIn>(ichMin);
  8656. }
  8657. pnodeForInOrForOf->pnodeBlock = pnodeBlock;
  8658. pnodeForInOrForOf->pnodeLval = pnodeT;
  8659. pnodeForInOrForOf->pnodeObj = pnodeObj;
  8660. pnodeForInOrForOf->ichLim = ichLim;
  8661. TrackAssignment<true>(pnodeT, nullptr);
  8662. }
  8663. PushStmt<buildAST>(&stmt, pnodeForInOrForOf, isForOf ? knopForOf : knopForIn, pLabelIdList);
  8664. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8665. if (buildAST)
  8666. {
  8667. pnodeForInOrForOf->pnodeBody = pnodeBody;
  8668. pnode = pnodeForInOrForOf;
  8669. }
  8670. PopStmt(&stmt);
  8671. }
  8672. else
  8673. {
  8674. if (!nativeForOkay)
  8675. {
  8676. Error(ERRDestructInit);
  8677. }
  8678. ChkCurTok(tkSColon, ERRnoSemic);
  8679. ParseNodePtr pnodeCond = nullptr;
  8680. if (m_token.tk != tkSColon)
  8681. {
  8682. pnodeCond = ParseExpr<buildAST>();
  8683. if (m_token.tk != tkSColon)
  8684. {
  8685. Error(ERRnoSemic);
  8686. }
  8687. }
  8688. tokens tk;
  8689. tk = this->GetScanner()->Scan();
  8690. ParseNodePtr pnodeIncr = nullptr;
  8691. if (tk != tkRParen)
  8692. {
  8693. pnodeIncr = ParseExpr<buildAST>();
  8694. if (pnodeIncr)
  8695. {
  8696. pnodeIncr->isUsed = false;
  8697. }
  8698. }
  8699. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8700. ChkCurTok(tkRParen, ERRnoRparen);
  8701. ParseNodeFor * pnodeFor = nullptr;
  8702. if (buildAST)
  8703. {
  8704. pnodeFor = CreateNodeForOpT<knopFor>(ichMin);
  8705. pnodeFor->pnodeBlock = pnodeBlock;
  8706. pnodeFor->pnodeInverted = nullptr;
  8707. pnodeFor->pnodeInit = pnodeT;
  8708. pnodeFor->pnodeCond = pnodeCond;
  8709. pnodeFor->pnodeIncr = pnodeIncr;
  8710. pnodeFor->ichLim = ichLim;
  8711. }
  8712. PushStmt<buildAST>(&stmt, pnodeFor, knopFor, pLabelIdList);
  8713. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8714. if (buildAST)
  8715. {
  8716. pnodeFor->pnodeBody = pnodeBody;
  8717. pnode = pnodeFor;
  8718. }
  8719. PopStmt(&stmt);
  8720. }
  8721. if (buildAST)
  8722. {
  8723. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8724. }
  8725. FinishParseBlock(pnodeBlock);
  8726. break;
  8727. }
  8728. case tkSWITCH:
  8729. {
  8730. BOOL fSeenDefault = FALSE;
  8731. ParseNodeBlock * pnodeBlock = nullptr;
  8732. ParseNodePtr *ppnodeScopeSave = nullptr;
  8733. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8734. ichMin = this->GetScanner()->IchMinTok();
  8735. ChkNxtTok(tkLParen, ERRnoLparen);
  8736. ParseNodePtr pnodeVal = ParseExpr<buildAST>();
  8737. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8738. ChkCurTok(tkRParen, ERRnoRparen);
  8739. ChkCurTok(tkLCurly, ERRnoLcurly);
  8740. ParseNodeSwitch * pnodeSwitch = nullptr;
  8741. if (buildAST)
  8742. {
  8743. pnodeSwitch = CreateNodeForOpT<knopSwitch>(ichMin);
  8744. }
  8745. PushStmt<buildAST>(&stmt, pnodeSwitch, knopSwitch, pLabelIdList);
  8746. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8747. ParseNodeCase ** ppnodeCase = nullptr;
  8748. if (buildAST)
  8749. {
  8750. pnodeSwitch->pnodeVal = pnodeVal;
  8751. pnodeSwitch->pnodeBlock = pnodeBlock;
  8752. pnodeSwitch->ichLim = ichLim;
  8753. PushFuncBlockScope(pnodeSwitch->pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8754. pnodeSwitch->pnodeDefault = nullptr;
  8755. ppnodeCase = &pnodeSwitch->pnodeCases;
  8756. pnode = pnodeSwitch;
  8757. }
  8758. for (;;)
  8759. {
  8760. ParseNodeCase * pnodeCase;
  8761. ParseNodePtr pnodeBody = nullptr;
  8762. switch (m_token.tk)
  8763. {
  8764. default:
  8765. goto LEndSwitch;
  8766. case tkCASE:
  8767. {
  8768. pnodeCase = this->ParseCase<buildAST>(&pnodeBody);
  8769. break;
  8770. }
  8771. case tkDEFAULT:
  8772. if (fSeenDefault)
  8773. {
  8774. Error(ERRdupDefault);
  8775. // No recovery necessary since this is a semantic, not structural, error
  8776. }
  8777. fSeenDefault = TRUE;
  8778. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8779. this->GetScanner()->Scan();
  8780. charcount_t ichMinInner = this->GetScanner()->IchLimTok();
  8781. ChkCurTok(tkColon, ERRnoColon);
  8782. if (buildAST)
  8783. {
  8784. pnodeCase = CreateNodeForOpT<knopCase>(ichMinT);
  8785. pnodeSwitch->pnodeDefault = pnodeCase;
  8786. pnodeCase->ichLim = ichMinInner;
  8787. pnodeCase->pnodeExpr = nullptr;
  8788. }
  8789. ParseStmtList<buildAST>(&pnodeBody);
  8790. break;
  8791. }
  8792. // Create a block node to contain the statement list for this case.
  8793. // This helps us insert byte code to return the right value from
  8794. // global/eval code.
  8795. ParseNodeBlock * pnodeFakeBlock = CreateBlockNode();
  8796. if (buildAST)
  8797. {
  8798. if (pnodeBody)
  8799. {
  8800. pnodeFakeBlock->ichMin = pnodeCase->ichMin;
  8801. pnodeFakeBlock->ichLim = pnodeCase->ichLim;
  8802. pnodeCase->pnodeBody = pnodeFakeBlock;
  8803. pnodeCase->pnodeBody->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  8804. pnodeCase->pnodeBody->pnodeStmt = pnodeBody;
  8805. }
  8806. else
  8807. {
  8808. pnodeCase->pnodeBody = nullptr;
  8809. }
  8810. *ppnodeCase = pnodeCase;
  8811. ppnodeCase = &pnodeCase->pnodeNext;
  8812. }
  8813. }
  8814. LEndSwitch:
  8815. ChkCurTok(tkRCurly, ERRnoRcurly);
  8816. if (buildAST)
  8817. {
  8818. *ppnodeCase = nullptr;
  8819. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8820. FinishParseBlock(pnode->AsParseNodeSwitch()->pnodeBlock);
  8821. }
  8822. else
  8823. {
  8824. FinishParseBlock(pnodeBlock);
  8825. }
  8826. PopStmt(&stmt);
  8827. break;
  8828. }
  8829. case tkWHILE:
  8830. {
  8831. ichMin = this->GetScanner()->IchMinTok();
  8832. ChkNxtTok(tkLParen, ERRnoLparen);
  8833. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8834. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8835. ChkCurTok(tkRParen, ERRnoRparen);
  8836. ParseNodeWhile * pnodeWhile = nullptr;
  8837. if (buildAST)
  8838. {
  8839. pnodeWhile = CreateNodeForOpT<knopWhile>(ichMin);
  8840. pnodeWhile->pnodeCond = pnodeCond;
  8841. pnodeWhile->ichLim = ichLim;
  8842. }
  8843. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8844. m_disallowImportExportStmt = true;
  8845. PushStmt<buildAST>(&stmt, pnodeWhile, knopWhile, pLabelIdList);
  8846. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8847. PopStmt(&stmt);
  8848. if (buildAST)
  8849. {
  8850. pnodeWhile->pnodeBody = pnodeBody;
  8851. pnode = pnodeWhile;
  8852. }
  8853. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8854. break;
  8855. }
  8856. case tkDO:
  8857. {
  8858. ParseNodeWhile * pnodeWhile = nullptr;
  8859. if (buildAST)
  8860. {
  8861. pnodeWhile = CreateNodeForOpT<knopDoWhile>();
  8862. }
  8863. PushStmt<buildAST>(&stmt, pnodeWhile, knopDoWhile, pLabelIdList);
  8864. this->GetScanner()->Scan();
  8865. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8866. m_disallowImportExportStmt = true;
  8867. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8868. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8869. PopStmt(&stmt);
  8870. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8871. ChkCurTok(tkWHILE, ERRnoWhile);
  8872. ChkCurTok(tkLParen, ERRnoLparen);
  8873. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8874. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8875. ChkCurTok(tkRParen, ERRnoRparen);
  8876. if (buildAST)
  8877. {
  8878. pnodeWhile->pnodeBody = pnodeBody;
  8879. pnodeWhile->pnodeCond = pnodeCond;
  8880. pnodeWhile->ichLim = ichLim;
  8881. pnodeWhile->ichMin = ichMinT;
  8882. pnode = pnodeWhile;
  8883. }
  8884. // REVIEW: Allow do...while statements to be embedded in other compound statements like if..else, or do..while?
  8885. // goto LNeedTerminator;
  8886. // For now just eat the trailing semicolon if present.
  8887. if (m_token.tk == tkSColon)
  8888. {
  8889. if (pnode)
  8890. {
  8891. pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  8892. }
  8893. this->GetScanner()->Scan();
  8894. }
  8895. else if (pnode)
  8896. {
  8897. pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  8898. }
  8899. break;
  8900. }
  8901. case tkIF:
  8902. {
  8903. ichMin = this->GetScanner()->IchMinTok();
  8904. ChkNxtTok(tkLParen, ERRnoLparen);
  8905. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8906. ParseNodeIf * pnodeIf = nullptr;
  8907. if (buildAST)
  8908. {
  8909. pnodeIf = CreateNodeForOpT<knopIf>(ichMin);
  8910. pnodeIf->ichLim = this->GetScanner()->IchLimTok();
  8911. pnodeIf->pnodeCond = pnodeCond;
  8912. }
  8913. ChkCurTok(tkRParen, ERRnoRparen);
  8914. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8915. m_disallowImportExportStmt = true;
  8916. PushStmt<buildAST>(&stmt, pnodeIf, knopIf, pLabelIdList);
  8917. ParseNodePtr pnodeTrue = ParseStatement<buildAST>();
  8918. ParseNodePtr pnodeFalse = nullptr;
  8919. if (m_token.tk == tkELSE)
  8920. {
  8921. this->GetScanner()->Scan();
  8922. pnodeFalse = ParseStatement<buildAST>();
  8923. }
  8924. if (buildAST)
  8925. {
  8926. pnodeIf->pnodeTrue = pnodeTrue;
  8927. pnodeIf->pnodeFalse = pnodeFalse;
  8928. pnode = pnodeIf;
  8929. }
  8930. PopStmt(&stmt);
  8931. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8932. break;
  8933. }
  8934. case tkTRY:
  8935. {
  8936. ParseNodeBlock * pnodeBlock = CreateBlockNode();
  8937. pnodeBlock->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  8938. PushStmt<buildAST>(&stmt, pnodeBlock, knopBlock, pLabelIdList);
  8939. ParseNodePtr pnodeStmt = ParseTryCatchFinally<buildAST>();
  8940. if (buildAST)
  8941. {
  8942. pnodeBlock->pnodeStmt = pnodeStmt;
  8943. }
  8944. PopStmt(&stmt);
  8945. pnode = pnodeBlock;
  8946. break;
  8947. }
  8948. case tkWITH:
  8949. {
  8950. if (IsStrictMode())
  8951. {
  8952. Error(ERRES5NoWith);
  8953. }
  8954. if (m_currentNodeFunc)
  8955. {
  8956. GetCurrentFunctionNode()->SetHasWithStmt(); // Used by DeferNested
  8957. }
  8958. ichMin = this->GetScanner()->IchMinTok();
  8959. ChkNxtTok(tkLParen, ERRnoLparen);
  8960. ParseNodePtr pnodeObj = ParseExpr<buildAST>();
  8961. if (!buildAST)
  8962. {
  8963. m_scopeCountNoAst++;
  8964. }
  8965. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8966. ChkCurTok(tkRParen, ERRnoRparen);
  8967. ParseNodeWith * pnodeWith = nullptr;
  8968. if (buildAST)
  8969. {
  8970. pnodeWith = CreateNodeForOpT<knopWith>(ichMin);
  8971. }
  8972. PushStmt<buildAST>(&stmt, pnodeWith, knopWith, pLabelIdList);
  8973. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8974. if (buildAST)
  8975. {
  8976. pnodeWith->pnodeObj = pnodeObj;
  8977. this->CheckArguments(pnodeWith->pnodeObj);
  8978. if (m_ppnodeExprScope)
  8979. {
  8980. Assert(*m_ppnodeExprScope == nullptr);
  8981. *m_ppnodeExprScope = pnodeWith;
  8982. m_ppnodeExprScope = &pnodeWith->pnodeNext;
  8983. }
  8984. else
  8985. {
  8986. Assert(m_ppnodeScope);
  8987. Assert(*m_ppnodeScope == nullptr);
  8988. *m_ppnodeScope = pnodeWith;
  8989. m_ppnodeScope = &pnodeWith->pnodeNext;
  8990. }
  8991. pnodeWith->pnodeNext = nullptr;
  8992. pnodeWith->scope = nullptr;
  8993. ppnodeExprScopeSave = m_ppnodeExprScope;
  8994. m_ppnodeExprScope = &pnodeWith->pnodeScopes;
  8995. pnodeWith->pnodeScopes = nullptr;
  8996. pnodeWith->ichLim = ichLim;
  8997. pnode = pnodeWith;
  8998. }
  8999. PushBlockInfo(CreateBlockNode());
  9000. PushDynamicBlock();
  9001. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9002. if (buildAST)
  9003. {
  9004. pnode->AsParseNodeWith()->pnodeBody = pnodeBody;
  9005. m_ppnodeExprScope = ppnodeExprScopeSave;
  9006. }
  9007. else
  9008. {
  9009. m_scopeCountNoAst--;
  9010. }
  9011. // The dynamic block is not stored in the actual parse tree and so will not
  9012. // be visited by the byte code generator. Grab the callsEval flag off it and
  9013. // pass on to outer block in case of:
  9014. // with (...) eval(...); // i.e. blockless form of with
  9015. bool callsEval = GetCurrentBlock()->GetCallsEval();
  9016. PopBlockInfo();
  9017. if (callsEval)
  9018. {
  9019. // be careful not to overwrite an existing true with false
  9020. GetCurrentBlock()->SetCallsEval(true);
  9021. }
  9022. PopStmt(&stmt);
  9023. break;
  9024. }
  9025. case tkLCurly:
  9026. pnode = ParseBlock<buildAST>(pLabelIdList);
  9027. break;
  9028. case tkSColon:
  9029. pnode = nullptr;
  9030. this->GetScanner()->Scan();
  9031. break;
  9032. case tkBREAK:
  9033. if (buildAST)
  9034. {
  9035. pnode = CreateNodeForOpT<knopBreak>();
  9036. }
  9037. fnop = fnopBreak;
  9038. goto LGetJumpStatement;
  9039. case tkCONTINUE:
  9040. if (buildAST)
  9041. {
  9042. pnode = CreateNodeForOpT<knopContinue>();
  9043. }
  9044. fnop = fnopContinue;
  9045. LGetJumpStatement:
  9046. this->GetScanner()->ScanForcingPid();
  9047. if (tkID == m_token.tk && !this->GetScanner()->FHadNewLine())
  9048. {
  9049. // Labeled break or continue.
  9050. pid = m_token.GetIdentifier(this->GetHashTbl());
  9051. if (buildAST)
  9052. {
  9053. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9054. pnodeJump->hasExplicitTarget = true;
  9055. pnodeJump->ichLim = this->GetScanner()->IchLimTok();
  9056. this->GetScanner()->Scan();
  9057. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9058. Assert(pnodeJump->grfnop == 0);
  9059. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9060. {
  9061. for (LabelId* label = pstmt->pLabelId; label != nullptr; label = label->next)
  9062. {
  9063. if (pid == label->pid)
  9064. {
  9065. // Found the label. Make sure we can use it. We can
  9066. // break out of any statement, but we can only
  9067. // continue loops.
  9068. if (fnop == fnopContinue &&
  9069. !(pstmt->pnodeStmt->Grfnop() & fnop))
  9070. {
  9071. Error(ERRbadContinue);
  9072. }
  9073. else
  9074. {
  9075. pstmt->pnodeStmt->grfnop |= fnop;
  9076. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9077. }
  9078. PopStmt(&stmt);
  9079. goto LNeedTerminator;
  9080. }
  9081. }
  9082. pnodeJump->grfnop |=
  9083. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9084. }
  9085. }
  9086. else
  9087. {
  9088. this->GetScanner()->Scan();
  9089. for (pstmt = m_pstmtCur; pstmt; pstmt = pstmt->pstmtOuter)
  9090. {
  9091. LabelId* pLabelId;
  9092. for (pLabelId = pstmt->pLabelId; pLabelId; pLabelId = pLabelId->next)
  9093. {
  9094. if (pid == pLabelId->pid)
  9095. {
  9096. // Found the label. Make sure we can use it. We can
  9097. // break out of any statement, but we can only
  9098. // continue loops.
  9099. if (fnop == fnopContinue &&
  9100. !(ParseNode::Grfnop(pstmt->op) & fnop))
  9101. {
  9102. Error(ERRbadContinue);
  9103. }
  9104. goto LNeedTerminator;
  9105. }
  9106. }
  9107. }
  9108. }
  9109. Error(ERRnoLabel);
  9110. }
  9111. else
  9112. {
  9113. // If we're doing a fast scan, we're not tracking labels, so we can't accurately do this analysis.
  9114. // Let the thread that's doing the full parse detect the error, if there is one.
  9115. if (!this->IsDoingFastScan())
  9116. {
  9117. // Unlabeled break or continue.
  9118. ParseNodeJump * pnodeJump = nullptr;
  9119. if (buildAST)
  9120. {
  9121. pnodeJump = pnode->AsParseNodeJump();
  9122. pnodeJump->hasExplicitTarget = false;
  9123. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9124. Assert(pnodeJump->grfnop == 0);
  9125. }
  9126. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9127. {
  9128. if (buildAST)
  9129. {
  9130. AnalysisAssert(pstmt->pnodeStmt);
  9131. if (pstmt->pnodeStmt->Grfnop() & fnop)
  9132. {
  9133. pstmt->pnodeStmt->grfnop |= fnop;
  9134. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9135. PopStmt(&stmt);
  9136. goto LNeedTerminator;
  9137. }
  9138. pnodeJump->grfnop |=
  9139. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9140. }
  9141. else
  9142. {
  9143. if (ParseNode::Grfnop(pstmt->GetNop()) & fnop)
  9144. {
  9145. if (!pstmt->isDeferred)
  9146. {
  9147. AnalysisAssert(pstmt->pnodeStmt);
  9148. pstmt->pnodeStmt->grfnop |= fnop;
  9149. }
  9150. goto LNeedTerminator;
  9151. }
  9152. }
  9153. }
  9154. Error(fnop == fnopBreak ? ERRbadBreak : ERRbadContinue);
  9155. }
  9156. goto LNeedTerminator;
  9157. }
  9158. case tkRETURN:
  9159. {
  9160. ParseNodeReturn * pnodeReturn;
  9161. if (buildAST)
  9162. {
  9163. if (nullptr == m_currentNodeFunc || IsTopLevelModuleFunc())
  9164. {
  9165. Error(ERRbadReturn);
  9166. }
  9167. pnodeReturn = CreateNodeForOpT<knopReturn>();
  9168. }
  9169. this->GetScanner()->Scan();
  9170. ParseNodePtr pnodeExpr = nullptr;
  9171. ParseOptionalExpr<buildAST>(&pnodeExpr, true);
  9172. // Class constructors have special semantics regarding return statements.
  9173. // This might require a reference to 'this'
  9174. if (GetCurrentFunctionNode()->IsClassConstructor())
  9175. {
  9176. ReferenceSpecialName(wellKnownPropertyPids._this);
  9177. }
  9178. if (buildAST)
  9179. {
  9180. pnodeReturn->pnodeExpr = pnodeExpr;
  9181. if (pnodeExpr)
  9182. {
  9183. this->CheckArguments(pnodeReturn->pnodeExpr);
  9184. pnodeReturn->ichLim = pnodeReturn->pnodeExpr->ichLim;
  9185. }
  9186. // See if return should call finally
  9187. PushStmt<buildAST>(&stmt, pnodeReturn, knopReturn, pLabelIdList);
  9188. Assert(pnodeReturn->grfnop == 0);
  9189. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9190. {
  9191. if (pstmt->pnodeStmt->Grfnop() & fnopCleanup)
  9192. {
  9193. pnodeReturn->grfnop |= fnopCleanup;
  9194. break;
  9195. }
  9196. }
  9197. PopStmt(&stmt);
  9198. pnode = pnodeReturn;
  9199. }
  9200. goto LNeedTerminator;
  9201. }
  9202. case tkTHROW:
  9203. {
  9204. if (buildAST)
  9205. {
  9206. pnode = CreateUniNode(knopThrow, nullptr);
  9207. }
  9208. this->GetScanner()->Scan();
  9209. ParseNodePtr pnode1 = nullptr;
  9210. if (m_token.tk != tkSColon &&
  9211. m_token.tk != tkRCurly &&
  9212. !this->GetScanner()->FHadNewLine())
  9213. {
  9214. pnode1 = ParseExpr<buildAST>();
  9215. }
  9216. else
  9217. {
  9218. Error(ERRdanglingThrow);
  9219. }
  9220. if (buildAST)
  9221. {
  9222. pnode->AsParseNodeUni()->pnode1 = pnode1;
  9223. if (pnode1)
  9224. {
  9225. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  9226. pnode->ichLim = pnode->AsParseNodeUni()->pnode1->ichLim;
  9227. }
  9228. }
  9229. goto LNeedTerminator;
  9230. }
  9231. case tkDEBUGGER:
  9232. if (buildAST)
  9233. {
  9234. pnode = CreateNodeForOpT<knopDebugger>();
  9235. }
  9236. this->GetScanner()->Scan();
  9237. goto LNeedTerminator;
  9238. case tkIMPORT:
  9239. pnode = ParseImport<buildAST>();
  9240. goto LNeedTerminator;
  9241. case tkEXPORT:
  9242. {
  9243. if (!(m_grfscr & fscrIsModuleCode))
  9244. {
  9245. goto LDefaultToken;
  9246. }
  9247. bool needTerminator = false;
  9248. pnode = ParseExportDeclaration<buildAST>(&needTerminator);
  9249. if (needTerminator)
  9250. {
  9251. goto LNeedTerminator;
  9252. }
  9253. else
  9254. {
  9255. break;
  9256. }
  9257. }
  9258. LDefaultToken:
  9259. default:
  9260. {
  9261. // First check for a label via lookahead. If not found,
  9262. // rewind and reparse as expression statement.
  9263. if (m_token.tk == tkID)
  9264. {
  9265. RestorePoint idStart;
  9266. this->GetScanner()->Capture(&idStart);
  9267. IdentPtr pidInner = m_token.GetIdentifier(this->GetHashTbl());
  9268. this->GetScanner()->Scan();
  9269. if (m_token.tk == tkColon)
  9270. {
  9271. // We have a label.
  9272. if (LabelExists(pidInner, pLabelIdList))
  9273. {
  9274. Error(ERRbadLabel);
  9275. }
  9276. LabelId* pLabelId = CreateLabelId(pidInner);
  9277. pLabelId->next = pLabelIdList;
  9278. pLabelIdList = pLabelId;
  9279. this->GetScanner()->Scan();
  9280. goto LRestart;
  9281. }
  9282. // No label, rewind back to the tkID and parse an expression
  9283. this->GetScanner()->SeekTo(idStart);
  9284. }
  9285. // Must be an expression statement.
  9286. pnode = ParseExpr<buildAST>();
  9287. if (m_hasDeferredShorthandInitError)
  9288. {
  9289. Error(ERRnoColon);
  9290. }
  9291. if (buildAST)
  9292. {
  9293. expressionStmt = true;
  9294. AnalysisAssert(pnode);
  9295. pnode->isUsed = false;
  9296. }
  9297. }
  9298. LNeedTerminator:
  9299. // Need a semicolon, new-line, } or end-of-file.
  9300. // We digest a semicolon if it's there.
  9301. switch (m_token.tk)
  9302. {
  9303. case tkSColon:
  9304. this->GetScanner()->Scan();
  9305. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9306. break;
  9307. case tkEOF:
  9308. case tkRCurly:
  9309. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9310. break;
  9311. default:
  9312. if (!this->GetScanner()->FHadNewLine())
  9313. {
  9314. Error(ERRnoSemic);
  9315. }
  9316. else
  9317. {
  9318. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9319. }
  9320. break;
  9321. }
  9322. break;
  9323. }
  9324. if (m_hasDeferredShorthandInitError)
  9325. {
  9326. Error(ERRnoColon);
  9327. }
  9328. if (buildAST)
  9329. {
  9330. // All non expression statements excluded from the "this.x" optimization
  9331. // Another check while parsing expressions
  9332. if (!expressionStmt)
  9333. {
  9334. if (m_currentNodeFunc)
  9335. {
  9336. m_currentNodeFunc->SetHasNonThisStmt();
  9337. }
  9338. else if (m_currentNodeProg)
  9339. {
  9340. m_currentNodeProg->SetHasNonThisStmt();
  9341. }
  9342. }
  9343. #if EXCEPTION_RECOVERY
  9344. // close the try/catch block
  9345. if (Js::Configuration::Global.flags.SwallowExceptions)
  9346. {
  9347. // pop the try block and fill in the body
  9348. PopStmt(&stmtTryBlock);
  9349. pTryBlock->pnodeStmt = pnode;
  9350. PopStmt(&stmtTry);
  9351. if (pnode != nullptr)
  9352. {
  9353. pTry->ichLim = pnode->ichLim;
  9354. }
  9355. pTry->pnodeBody = pTryBlock;
  9356. // create a catch block with an empty body
  9357. StmtNest stmtCatch;
  9358. ParseNodeCatch * pCatch;
  9359. pCatch = CreateNodeForOpT<knopCatch>();
  9360. PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr);
  9361. pCatch->pnodeBody = nullptr;
  9362. if (pnode != nullptr)
  9363. {
  9364. pCatch->ichLim = pnode->ichLim;
  9365. }
  9366. pCatch->grfnop = 0;
  9367. pCatch->pnodeNext = nullptr;
  9368. // create a fake name for the catch var.
  9369. const WCHAR *uniqueNameStr = _u("__ehobj");
  9370. IdentPtr uniqueName = this->GetHashTbl()->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));
  9371. pCatch->SetParam(CreateNameNode(uniqueName));
  9372. // Add this catch to the current list. We don't bother adjusting the catch and function expression
  9373. // lists here because the catch is just an empty statement.
  9374. if (m_ppnodeExprScope)
  9375. {
  9376. Assert(*m_ppnodeExprScope == nullptr);
  9377. *m_ppnodeExprScope = pCatch;
  9378. m_ppnodeExprScope = &pCatch->pnodeNext;
  9379. }
  9380. else
  9381. {
  9382. Assert(m_ppnodeScope);
  9383. Assert(*m_ppnodeScope == nullptr);
  9384. *m_ppnodeScope = pCatch;
  9385. m_ppnodeScope = &pCatch->pnodeNext;
  9386. }
  9387. pCatch->pnodeScopes = nullptr;
  9388. PopStmt(&stmtCatch);
  9389. // fill in and pop the try-catch
  9390. pParentTryCatch->pnodeTry = pTry;
  9391. pParentTryCatch->pnodeCatch = pCatch;
  9392. PopStmt(&stmtTryCatch);
  9393. PopStmt(&stmtTryCatchBlock);
  9394. // replace the node that's being returned
  9395. pParentTryCatchBlock->pnodeStmt = pParentTryCatch;
  9396. pnode = pParentTryCatchBlock;
  9397. }
  9398. #endif // EXCEPTION_RECOVERY
  9399. }
  9400. return pnode;
  9401. }
  9402. BOOL
  9403. Parser::TokIsForInOrForOf()
  9404. {
  9405. return m_token.tk == tkIN ||
  9406. (m_token.tk == tkID &&
  9407. m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.of);
  9408. }
  9409. /***************************************************************************
  9410. Parse a sequence of statements.
  9411. ***************************************************************************/
  9412. template<bool buildAST>
  9413. void Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)
  9414. {
  9415. BOOL doneDirectives = !isSourceElementList; // directives may only exist in a SourceElementList, not a StatementList
  9416. BOOL seenDirectiveContainingOctal = false; // Have we seen an octal directive before a use strict directive?
  9417. BOOL old_UseStrictMode = m_fUseStrictMode;
  9418. ParseNodePtr pnodeStmt;
  9419. ParseNodePtr *lastNodeRef = nullptr;
  9420. if (buildAST)
  9421. {
  9422. Assert(ppnodeList);
  9423. *ppnodeList = nullptr;
  9424. }
  9425. if (CONFIG_FLAG(ForceStrictMode))
  9426. {
  9427. m_fUseStrictMode = TRUE;
  9428. }
  9429. for (;;)
  9430. {
  9431. switch (m_token.tk)
  9432. {
  9433. case tkCASE:
  9434. case tkDEFAULT:
  9435. case tkRCurly:
  9436. case tkEOF:
  9437. if (buildAST && nullptr != pppnodeLast)
  9438. {
  9439. *pppnodeLast = lastNodeRef;
  9440. }
  9441. if (!buildAST)
  9442. {
  9443. m_fUseStrictMode = old_UseStrictMode;
  9444. }
  9445. return;
  9446. }
  9447. if (doneDirectives == FALSE)
  9448. {
  9449. bool isOctalInString = false;
  9450. bool isUseStrictDirective = false;
  9451. bool isUseAsmDirective = false;
  9452. if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))
  9453. {
  9454. // Ignore "use asm" statement when not building the AST
  9455. isUseAsmDirective &= buildAST;
  9456. if (isUseStrictDirective)
  9457. {
  9458. // Functions with non-simple parameter list cannot be made strict mode
  9459. if (GetCurrentFunctionNode()->HasNonSimpleParameterList())
  9460. {
  9461. Error(ERRNonSimpleParamListInStrictMode);
  9462. }
  9463. if (seenDirectiveContainingOctal)
  9464. {
  9465. // Directives seen before a "use strict" cannot contain an octal.
  9466. Error(ERRES5NoOctal);
  9467. }
  9468. if (!buildAST)
  9469. {
  9470. // Turning on strict mode in deferred code.
  9471. m_fUseStrictMode = TRUE;
  9472. if (!m_inDeferredNestedFunc)
  9473. {
  9474. // Top-level deferred function, so there's a parse node
  9475. Assert(m_currentNodeFunc != nullptr);
  9476. m_currentNodeFunc->SetStrictMode();
  9477. }
  9478. else if (strictModeOn)
  9479. {
  9480. // This turns on strict mode in a deferred function, we need to go back
  9481. // and re-check duplicated formals.
  9482. *strictModeOn = true;
  9483. }
  9484. }
  9485. else
  9486. {
  9487. if (smEnvironment == SM_OnGlobalCode)
  9488. {
  9489. // Turning on strict mode at the top level
  9490. m_fUseStrictMode = TRUE;
  9491. }
  9492. else
  9493. {
  9494. // i.e. smEnvironment == SM_OnFunctionCode
  9495. Assert(m_currentNodeFunc != nullptr);
  9496. m_currentNodeFunc->SetStrictMode();
  9497. }
  9498. }
  9499. }
  9500. else if (isUseAsmDirective)
  9501. {
  9502. if (smEnvironment != SM_OnGlobalCode) //Top level use asm doesn't mean anything.
  9503. {
  9504. // i.e. smEnvironment == SM_OnFunctionCode
  9505. Assert(m_currentNodeFunc != nullptr);
  9506. m_currentNodeFunc->SetAsmjsMode();
  9507. m_currentNodeFunc->SetCanBeDeferred(false);
  9508. m_InAsmMode = true;
  9509. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, AsmJSFunction, m_scriptContext);
  9510. }
  9511. }
  9512. else if (isOctalInString)
  9513. {
  9514. seenDirectiveContainingOctal = TRUE;
  9515. }
  9516. }
  9517. else
  9518. {
  9519. // The first time we see anything other than a directive we can have no more directives.
  9520. doneDirectives = TRUE;
  9521. }
  9522. }
  9523. if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))
  9524. {
  9525. if (buildAST)
  9526. {
  9527. AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);
  9528. }
  9529. }
  9530. }
  9531. }
  9532. template <class Fn>
  9533. void Parser::FinishFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)
  9534. {
  9535. Scope * scope;
  9536. Scope * origCurrentScope = this->m_currentScope;
  9537. ParseNodePtr pnodeScope;
  9538. ParseNodeBlock * pnodeBlock;
  9539. for (pnodeScope = pnodeScopeList; pnodeScope;)
  9540. {
  9541. switch (pnodeScope->nop)
  9542. {
  9543. case knopBlock:
  9544. {
  9545. ParseNodeBlock * pnodeBlockScope = pnodeScope->AsParseNodeBlock();
  9546. m_nextBlockId = pnodeBlockScope->blockId + 1;
  9547. PushBlockInfo(pnodeBlockScope);
  9548. scope = pnodeBlockScope->scope;
  9549. if (scope && scope != origCurrentScope)
  9550. {
  9551. PushScope(scope);
  9552. }
  9553. FinishFunctionsInScope(pnodeBlockScope->pnodeScopes, fn);
  9554. if (scope && scope != origCurrentScope)
  9555. {
  9556. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9557. PopScope(scope);
  9558. }
  9559. PopBlockInfo();
  9560. pnodeScope = pnodeBlockScope->pnodeNext;
  9561. break;
  9562. }
  9563. case knopFncDecl:
  9564. fn(pnodeScope->AsParseNodeFnc());
  9565. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  9566. break;
  9567. case knopCatch:
  9568. scope = pnodeScope->AsParseNodeCatch()->scope;
  9569. if (scope)
  9570. {
  9571. PushScope(scope);
  9572. }
  9573. pnodeBlock = CreateBlockNode(PnodeBlockType::Regular);
  9574. pnodeBlock->scope = scope;
  9575. PushBlockInfo(pnodeBlock);
  9576. FinishFunctionsInScope(pnodeScope->AsParseNodeCatch()->pnodeScopes, fn);
  9577. if (scope)
  9578. {
  9579. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9580. PopScope(scope);
  9581. }
  9582. PopBlockInfo();
  9583. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  9584. break;
  9585. case knopWith:
  9586. PushBlockInfo(CreateBlockNode());
  9587. PushDynamicBlock();
  9588. FinishFunctionsInScope(pnodeScope->AsParseNodeWith()->pnodeScopes, fn);
  9589. PopBlockInfo();
  9590. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  9591. break;
  9592. default:
  9593. AssertMsg(false, "Unexpected node with scope list");
  9594. return;
  9595. }
  9596. }
  9597. }
  9598. // Scripts above this size (minus string literals and comments) will have parsing of
  9599. // function bodies deferred.
  9600. ULONG Parser::GetDeferralThreshold(bool isProfileLoaded)
  9601. {
  9602. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9603. if (CONFIG_FLAG(ForceDeferParse) ||
  9604. PHASE_FORCE1(Js::DeferParsePhase) ||
  9605. Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  9606. {
  9607. return 0;
  9608. }
  9609. else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))
  9610. {
  9611. return Js::Configuration::Global.flags.DeferParse;
  9612. }
  9613. else
  9614. #endif
  9615. {
  9616. if (isProfileLoaded)
  9617. {
  9618. return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;
  9619. }
  9620. return DEFAULT_CONFIG_DeferParseThreshold;
  9621. }
  9622. }
  9623. void Parser::FinishDeferredFunction(ParseNodeBlock * pnodeScopeList)
  9624. {
  9625. uint saveNextBlockId = m_nextBlockId;
  9626. m_nextBlockId = pnodeScopeList->blockId + 1;
  9627. FinishFunctionsInScope(pnodeScopeList,
  9628. [this](ParseNodeFnc * pnodeFnc)
  9629. {
  9630. Assert(pnodeFnc->nop == knopFncDecl);
  9631. // Non-simple params (such as default) require a good amount of logic to put vars on appropriate scopes. ParseFncDecl handles it
  9632. // properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param
  9633. // will remain deferred until they are called.
  9634. if (pnodeFnc->pnodeBody == nullptr && !pnodeFnc->HasNonSimpleParameterList())
  9635. {
  9636. // Go back and generate an AST for this function.
  9637. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->functionId, /*Undefer*/TRUE));
  9638. ParseNodeFnc * pnodeFncSave = this->m_currentNodeFunc;
  9639. this->m_currentNodeFunc = pnodeFnc;
  9640. ParseNodeBlock * pnodeFncExprBlock = nullptr;
  9641. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  9642. if (pnodeName)
  9643. {
  9644. Assert(pnodeName->nop == knopVarDecl);
  9645. ParseNodeVar * pnodeVarName = pnodeName->AsParseNodeVar();
  9646. Assert(pnodeVarName->pnodeNext == nullptr);
  9647. if (!pnodeFnc->IsDeclaration())
  9648. {
  9649. // Set up the named function expression symbol so references inside the function can be bound.
  9650. pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);
  9651. PidRefStack *ref = this->PushPidRef(pnodeVarName->pid);
  9652. pnodeVarName->symRef = ref->GetSymRef();
  9653. ref->SetSym(pnodeVarName->sym);
  9654. Scope *fncExprScope = pnodeFncExprBlock->scope;
  9655. fncExprScope->AddNewSymbol(pnodeVarName->sym);
  9656. pnodeFnc->scope = fncExprScope;
  9657. }
  9658. }
  9659. ParseNodeBlock * pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);
  9660. pnodeFnc->pnodeScopes = pnodeBlock;
  9661. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  9662. pnodeBlock->pnodeStmt = pnodeFnc;
  9663. ParseNodePtr * varNodesList = &pnodeFnc->pnodeVars;
  9664. ParseNodeVar * argNode = nullptr;
  9665. if (!pnodeFnc->IsModule() && !pnodeFnc->IsLambda() && !(pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam))
  9666. {
  9667. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  9668. m_ppnodeVar = &pnodeFnc->pnodeVars;
  9669. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  9670. varNodesList = m_ppnodeVar;
  9671. m_ppnodeVar = ppnodeVarSave;
  9672. }
  9673. // Add the args to the scope, since we won't re-parse those.
  9674. Scope *scope = pnodeBlock->scope;
  9675. uint blockId = GetCurrentBlock()->blockId;
  9676. uint funcId = GetCurrentFunctionNode()->functionId;
  9677. auto addArgsToScope = [&](ParseNodePtr pnodeArg) {
  9678. if (pnodeArg->IsVarLetOrConst())
  9679. {
  9680. ParseNodeVar * pnodeVarArg = pnodeArg->AsParseNodeVar();
  9681. PidRefStack *ref = this->FindOrAddPidRef(pnodeVarArg->pid, blockId, funcId);
  9682. pnodeVarArg->symRef = ref->GetSymRef();
  9683. if (ref->GetSym() != nullptr)
  9684. {
  9685. // Duplicate parameter in a configuration that allows them.
  9686. // The symbol is already in the scope, just point it to the right declaration.
  9687. Assert(ref->GetSym() == pnodeVarArg->sym);
  9688. ref->GetSym()->SetDecl(pnodeVarArg);
  9689. }
  9690. else
  9691. {
  9692. ref->SetSym(pnodeArg->AsParseNodeVar()->sym);
  9693. scope->AddNewSymbol(pnodeVarArg->sym);
  9694. }
  9695. }
  9696. };
  9697. MapFormals(pnodeFnc, addArgsToScope);
  9698. MapFormalsFromPattern(pnodeFnc, addArgsToScope);
  9699. ParseNodeBlock * pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  9700. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  9701. // Set the parameter block's child to the function body block.
  9702. *m_ppnodeScope = pnodeInnerBlock;
  9703. ParseNodePtr *ppnodeScopeSave = nullptr;
  9704. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9705. ppnodeScopeSave = m_ppnodeScope;
  9706. // This synthetic block scope will contain all the nested scopes.
  9707. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  9708. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  9709. // Keep nested function declarations and expressions in the same list at function scope.
  9710. // (Indicate this by nulling out the current function expressions list.)
  9711. ppnodeExprScopeSave = m_ppnodeExprScope;
  9712. m_ppnodeExprScope = nullptr;
  9713. // Shouldn't be any temps in the arg list.
  9714. Assert(*m_ppnodeVar == nullptr);
  9715. // Start the var list.
  9716. m_ppnodeVar = varNodesList;
  9717. if (scope != nullptr)
  9718. {
  9719. Assert(pnodeFnc->IsBodyAndParamScopeMerged());
  9720. blockId = GetCurrentBlock()->blockId;
  9721. funcId = GetCurrentFunctionNode()->functionId;
  9722. scope->ForEachSymbol([this, blockId, funcId](Symbol* paramSym)
  9723. {
  9724. PidRefStack* ref = this->FindOrAddPidRef(paramSym->GetPid(), blockId, funcId);
  9725. ref->SetSym(paramSym);
  9726. });
  9727. }
  9728. Assert(m_currentNodeNonLambdaFunc == nullptr);
  9729. m_currentNodeNonLambdaFunc = pnodeFnc;
  9730. this->FinishFncNode(pnodeFnc);
  9731. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  9732. m_currentNodeNonLambdaFunc = nullptr;
  9733. m_ppnodeExprScope = ppnodeExprScopeSave;
  9734. Assert(m_ppnodeScope);
  9735. Assert(nullptr == *m_ppnodeScope);
  9736. m_ppnodeScope = ppnodeScopeSave;
  9737. this->FinishParseBlock(pnodeInnerBlock);
  9738. if (!pnodeFnc->IsModule() && (m_token.tk == tkLCurly || !pnodeFnc->IsLambda()))
  9739. {
  9740. UpdateArgumentsNode(pnodeFnc, argNode);
  9741. }
  9742. CreateSpecialSymbolDeclarations(pnodeFnc);
  9743. this->FinishParseBlock(pnodeBlock);
  9744. if (pnodeFncExprBlock)
  9745. {
  9746. this->FinishParseBlock(pnodeFncExprBlock);
  9747. }
  9748. this->m_currentNodeFunc = pnodeFncSave;
  9749. }
  9750. });
  9751. m_nextBlockId = saveNextBlockId;
  9752. }
  9753. void Parser::InitPids()
  9754. {
  9755. wellKnownPropertyPids.arguments = this->GetHashTbl()->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);
  9756. wellKnownPropertyPids.async = this->GetHashTbl()->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);
  9757. wellKnownPropertyPids.eval = this->GetHashTbl()->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);
  9758. wellKnownPropertyPids.get = this->GetHashTbl()->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);
  9759. wellKnownPropertyPids.set = this->GetHashTbl()->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);
  9760. wellKnownPropertyPids.let = this->GetHashTbl()->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);
  9761. wellKnownPropertyPids.constructor = this->GetHashTbl()->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);
  9762. wellKnownPropertyPids.prototype = this->GetHashTbl()->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);
  9763. wellKnownPropertyPids.__proto__ = this->GetHashTbl()->PidHashNameLen(_u("__proto__"), sizeof("__proto__") - 1);
  9764. wellKnownPropertyPids.of = this->GetHashTbl()->PidHashNameLen(_u("of"), sizeof("of") - 1);
  9765. wellKnownPropertyPids.target = this->GetHashTbl()->PidHashNameLen(_u("target"), sizeof("target") - 1);
  9766. wellKnownPropertyPids.as = this->GetHashTbl()->PidHashNameLen(_u("as"), sizeof("as") - 1);
  9767. wellKnownPropertyPids.from = this->GetHashTbl()->PidHashNameLen(_u("from"), sizeof("from") - 1);
  9768. wellKnownPropertyPids._default = this->GetHashTbl()->PidHashNameLen(_u("default"), sizeof("default") - 1);
  9769. wellKnownPropertyPids._starDefaultStar = this->GetHashTbl()->PidHashNameLen(_u("*default*"), sizeof("*default*") - 1);
  9770. wellKnownPropertyPids._star = this->GetHashTbl()->PidHashNameLen(_u("*"), sizeof("*") - 1);
  9771. wellKnownPropertyPids._this = this->GetHashTbl()->PidHashNameLen(_u("*this*"), sizeof("*this*") - 1);
  9772. wellKnownPropertyPids._newTarget = this->GetHashTbl()->PidHashNameLen(_u("*new.target*"), sizeof("*new.target*") - 1);
  9773. wellKnownPropertyPids._super = this->GetHashTbl()->PidHashNameLen(_u("*super*"), sizeof("*super*") - 1);
  9774. wellKnownPropertyPids._superConstructor = this->GetHashTbl()->PidHashNameLen(_u("*superconstructor*"), sizeof("*superconstructor*") - 1);
  9775. }
  9776. void Parser::RestoreScopeInfo(Js::ScopeInfo * scopeInfo)
  9777. {
  9778. if (!scopeInfo)
  9779. {
  9780. return;
  9781. }
  9782. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9783. RestoreScopeInfo(scopeInfo->GetParentScopeInfo()); // Recursively restore outer func scope info
  9784. scopeInfo->SetScopeId(m_nextBlockId);
  9785. ParseNodeBlock * pnodeScope = nullptr;
  9786. ScopeType scopeType = scopeInfo->GetScopeType();
  9787. PnodeBlockType blockType;
  9788. switch (scopeType)
  9789. {
  9790. case ScopeType_With:
  9791. PushDynamicBlock();
  9792. // fall through
  9793. case ScopeType_Block:
  9794. case ScopeType_Catch:
  9795. case ScopeType_CatchParamPattern:
  9796. case ScopeType_GlobalEvalBlock:
  9797. blockType = PnodeBlockType::Regular;
  9798. break;
  9799. case ScopeType_FunctionBody:
  9800. case ScopeType_FuncExpr:
  9801. blockType = PnodeBlockType::Function;
  9802. break;
  9803. case ScopeType_Parameter:
  9804. blockType = PnodeBlockType::Parameter;
  9805. break;
  9806. default:
  9807. Assert(0);
  9808. return;
  9809. }
  9810. pnodeScope = StartParseBlockWithCapacity<true>(blockType, scopeType, scopeInfo->GetSymbolCount());
  9811. Scope *scope = pnodeScope->scope;
  9812. scope->SetScopeInfo(scopeInfo);
  9813. scopeInfo->ExtractScopeInfo(this, /*nullptr, nullptr,*/ scope);
  9814. }
  9815. void Parser::FinishScopeInfo(Js::ScopeInfo * scopeInfo)
  9816. {
  9817. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9818. for (; scopeInfo != nullptr; scopeInfo = scopeInfo->GetParentScopeInfo())
  9819. {
  9820. int scopeId = scopeInfo->GetScopeId();
  9821. scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)
  9822. {
  9823. this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);
  9824. });
  9825. PopScope(scopeInfo->GetScope());
  9826. PopStmt(&m_currentBlockInfo->pstmt);
  9827. PopBlockInfo();
  9828. }
  9829. }
  9830. /***************************************************************************
  9831. Parse the code.
  9832. ***************************************************************************/
  9833. 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)
  9834. {
  9835. ParseNodeProg * pnodeProg;
  9836. ParseNodePtr *lastNodeRef = nullptr;
  9837. m_nextBlockId = 0;
  9838. bool isDeferred = (grfscr & fscrDeferredFnc) != 0;
  9839. bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;
  9840. bool isGlobalCode = (grfscr & fscrGlobalCode) != 0;
  9841. if (this->m_scriptContext->IsScriptContextInDebugMode()
  9842. #ifdef ENABLE_PREJIT
  9843. || Js::Configuration::Global.flags.Prejit
  9844. #endif
  9845. || ((grfscr & fscrNoDeferParse) != 0)
  9846. )
  9847. {
  9848. // Don't do deferred parsing if debugger is attached or feature is disabled
  9849. // by command-line switch.
  9850. grfscr &= ~fscrWillDeferFncParse;
  9851. }
  9852. else if (!isGlobalCode &&
  9853. (
  9854. PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||
  9855. this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  9856. )
  9857. )
  9858. {
  9859. // Don't defer event handlers in debug/rundown mode, because we need to register the document,
  9860. // so we need to create a full FunctionBody for the script body.
  9861. grfscr &= ~fscrWillDeferFncParse;
  9862. }
  9863. m_grfscr = grfscr;
  9864. m_length = length;
  9865. m_originalLength = length;
  9866. m_nextFunctionId = nextFunctionId;
  9867. if (m_parseType != ParseType_Deferred)
  9868. {
  9869. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));
  9870. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);
  9871. }
  9872. // Give the scanner the source and get the first token
  9873. this->GetScanner()->SetText(pszSrc, offset, length, charOffset, isUtf8, grfscr, lineNumber);
  9874. this->GetScanner()->Scan();
  9875. // Make the main 'knopProg' node
  9876. int32 initSize = 0;
  9877. m_pCurrentAstSize = &initSize;
  9878. pnodeProg = CreateProgNode(isModuleSource, lineNumber);
  9879. if (!isDeferred || (isDeferred && isGlobalCode))
  9880. {
  9881. // In the deferred case, if the global function is deferred parse (which is in no-refresh case),
  9882. // we will re-use the same function body, so start with the correct functionId.
  9883. pnodeProg->functionId = (*m_nextFunctionId)++;
  9884. }
  9885. if (isModuleSource)
  9886. {
  9887. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  9888. pnodeProg->AsParseNodeModule()->localExportEntries = nullptr;
  9889. pnodeProg->AsParseNodeModule()->indirectExportEntries = nullptr;
  9890. pnodeProg->AsParseNodeModule()->starExportEntries = nullptr;
  9891. pnodeProg->AsParseNodeModule()->importEntries = nullptr;
  9892. pnodeProg->AsParseNodeModule()->requestedModules = nullptr;
  9893. }
  9894. m_pCurrentAstSize = &(pnodeProg->astSize);
  9895. // initialize parsing variables
  9896. m_currentNodeFunc = nullptr;
  9897. m_currentNodeDeferredFunc = nullptr;
  9898. m_currentNodeProg = pnodeProg;
  9899. m_cactIdentToNodeLookup = 1;
  9900. m_pnestedCount = &pnodeProg->nestedCount;
  9901. m_inDeferredNestedFunc = false;
  9902. m_ppnodeVar = &pnodeProg->pnodeVars;
  9903. SetCurrentStatement(nullptr);
  9904. AssertMsg(m_pstmtCur == nullptr, "Statement stack should be empty when we start parse global code");
  9905. // Create block for const's and let's
  9906. ParseNodeBlock * pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);
  9907. pnodeProg->scope = pnodeGlobalBlock->scope;
  9908. ParseNodeBlock * pnodeGlobalEvalBlock = nullptr;
  9909. // Don't track function expressions separately from declarations at global scope.
  9910. m_ppnodeExprScope = nullptr;
  9911. // This synthetic block scope will contain all the nested scopes.
  9912. pnodeProg->pnodeScopes = pnodeGlobalBlock;
  9913. m_ppnodeScope = &pnodeGlobalBlock->pnodeScopes;
  9914. if ((this->m_grfscr & fscrEvalCode) &&
  9915. !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))
  9916. {
  9917. pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);
  9918. pnodeProg->pnodeScopes = pnodeGlobalEvalBlock;
  9919. m_ppnodeScope = &pnodeGlobalEvalBlock->pnodeScopes;
  9920. }
  9921. Js::ScopeInfo *scopeInfo = nullptr;
  9922. if (m_parseType == ParseType_Deferred && m_functionBody)
  9923. {
  9924. // this->m_functionBody can be cleared during parsing, but we need access to the scope info later.
  9925. scopeInfo = m_functionBody->GetScopeInfo();
  9926. if (scopeInfo)
  9927. {
  9928. // Create an enclosing function context.
  9929. m_currentNodeFunc = CreateNodeForOpT<knopFncDecl>();
  9930. m_currentNodeFunc->functionId = m_functionBody->GetLocalFunctionId();
  9931. m_currentNodeFunc->nestedCount = m_functionBody->GetNestedCount();
  9932. m_currentNodeFunc->SetStrictMode(!!this->m_fUseStrictMode);
  9933. this->RestoreScopeInfo(scopeInfo);
  9934. m_currentNodeFunc->SetIsGenerator(scopeInfo->IsGeneratorFunctionBody());
  9935. m_currentNodeFunc->SetIsAsync(scopeInfo->IsAsyncFunctionBody());
  9936. }
  9937. }
  9938. // It's possible for the module global to be defer-parsed in debug scenarios.
  9939. if (isModuleSource && (!isDeferred || (isDeferred && isGlobalCode)))
  9940. {
  9941. ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();
  9942. pnodeProg->pnodeBody = nullptr;
  9943. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, moduleFunction);
  9944. }
  9945. else
  9946. {
  9947. if (isDeferred && !isGlobalCode)
  9948. {
  9949. // Defer parse for a single function should just parse that one function - there are no other statements.
  9950. ushort flags = fFncNoFlgs;
  9951. size_t iecpMin = 0;
  9952. charcount_t ichMin = 0;
  9953. bool isAsync = false;
  9954. bool isGenerator = false;
  9955. bool isMethod = false;
  9956. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  9957. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  9958. // first time we see it.
  9959. //
  9960. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  9961. // token of the source code of the function may not be a 'function' token though, so we still need to reset this flag
  9962. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  9963. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  9964. if (m_grfscr & fscrDeferredFncExpression)
  9965. {
  9966. m_grfscr &= ~fscrDeferredFncExpression;
  9967. }
  9968. else
  9969. {
  9970. flags |= fFncDeclaration;
  9971. }
  9972. if (m_grfscr & fscrDeferredFncIsMethod)
  9973. {
  9974. m_grfscr &= ~fscrDeferredFncIsMethod;
  9975. isMethod = true;
  9976. flags |= fFncNoName | fFncMethod;
  9977. }
  9978. // These are the cases which can confirm async function:
  9979. // async function() {} -> async function
  9980. // async () => {} -> async lambda with parens around the formal parameter
  9981. // async arg => {} -> async lambda with single identifier parameter
  9982. // async name() {} -> async method
  9983. // async [computed_name]() {} -> async method with a computed name
  9984. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  9985. {
  9986. ichMin = this->GetScanner()->IchMinTok();
  9987. iecpMin = this->GetScanner()->IecpMinTok();
  9988. // Keep state so we can rewind if it turns out that this isn't an async function:
  9989. // async() {} -> method named async
  9990. // async => {} -> lambda with single parameter named async
  9991. RestorePoint termStart;
  9992. this->GetScanner()->Capture(&termStart);
  9993. this->GetScanner()->Scan();
  9994. if (m_token.tk == tkDArrow || (m_token.tk == tkLParen && isMethod) || this->GetScanner()->FHadNewLine())
  9995. {
  9996. this->GetScanner()->SeekTo(termStart);
  9997. }
  9998. else
  9999. {
  10000. flags |= fFncAsync;
  10001. isAsync = true;
  10002. }
  10003. }
  10004. if (m_token.tk == tkStar && m_scriptContext->GetConfig()->IsES6GeneratorsEnabled())
  10005. {
  10006. ichMin = this->GetScanner()->IchMinTok();
  10007. iecpMin = this->GetScanner()->IecpMinTok();
  10008. flags |= fFncGenerator;
  10009. isGenerator = true;
  10010. this->GetScanner()->Scan();
  10011. }
  10012. // Eat the computed name expression
  10013. if (m_token.tk == tkLBrack && isMethod)
  10014. {
  10015. this->GetScanner()->Scan();
  10016. ParseExpr<false>();
  10017. }
  10018. if (!isMethod && (m_token.tk == tkID || m_token.tk == tkLParen))
  10019. {
  10020. // If first token of the function is tkID or tkLParen, this is a lambda.
  10021. flags |= fFncLambda;
  10022. }
  10023. ParseNode * pnodeFnc = ParseFncDeclCheckScope<true>(flags, /* resetParsingSuperRestrictionState*/ false);
  10024. pnodeProg->pnodeBody = nullptr;
  10025. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, pnodeFnc);
  10026. // Include the async keyword or star character in the function extents
  10027. if (isAsync || isGenerator)
  10028. {
  10029. pnodeFnc->AsParseNodeFnc()->cbMin = iecpMin;
  10030. pnodeFnc->ichMin = ichMin;
  10031. }
  10032. }
  10033. else
  10034. {
  10035. // Process a sequence of statements/declarations
  10036. ParseStmtList<true>(
  10037. &pnodeProg->pnodeBody,
  10038. &lastNodeRef,
  10039. SM_OnGlobalCode,
  10040. !(m_grfscr & fscrDeferredFncExpression) /* isSourceElementList */);
  10041. }
  10042. }
  10043. if (m_parseType == ParseType_Deferred)
  10044. {
  10045. if (scopeInfo)
  10046. {
  10047. this->FinishScopeInfo(scopeInfo);
  10048. }
  10049. }
  10050. pnodeProg->m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;
  10051. if (IsStrictMode())
  10052. {
  10053. pnodeProg->SetStrictMode();
  10054. }
  10055. #if DEBUG
  10056. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->pnodeBody))
  10057. {
  10058. Error(ERRsyntax);
  10059. }
  10060. #endif
  10061. if (tkEOF != m_token.tk)
  10062. Error(ERRsyntax);
  10063. // Append an EndCode node.
  10064. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef,
  10065. CreateNodeForOpT<knopEndCode>());
  10066. Assert(lastNodeRef);
  10067. Assert(*lastNodeRef);
  10068. Assert((*lastNodeRef)->nop == knopEndCode);
  10069. (*lastNodeRef)->ichMin = 0;
  10070. (*lastNodeRef)->ichLim = 0;
  10071. // Get the extent of the code.
  10072. pnodeProg->ichLim = this->GetScanner()->IchLimTok();
  10073. pnodeProg->cbLim = this->GetScanner()->IecpLimTok();
  10074. // Terminate the local list
  10075. *m_ppnodeVar = nullptr;
  10076. Assert(nullptr == *m_ppnodeScope);
  10077. Assert(nullptr == pnodeProg->pnodeNext);
  10078. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10079. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10080. {
  10081. m_stoppedDeferredParse = true;
  10082. }
  10083. #endif
  10084. if (m_stoppedDeferredParse)
  10085. {
  10086. #if ENABLE_BACKGROUND_PARSING
  10087. if (this->m_hasParallelJob)
  10088. {
  10089. BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());
  10090. Assert(bgp);
  10091. this->WaitForBackgroundJobs(bgp, pse);
  10092. }
  10093. #endif
  10094. // Do any remaining bindings of globals referenced in non-deferred functions.
  10095. if (pnodeGlobalEvalBlock)
  10096. {
  10097. FinishParseBlock(pnodeGlobalEvalBlock);
  10098. }
  10099. FinishParseBlock(pnodeGlobalBlock);
  10100. // Clear out references to undeclared identifiers.
  10101. this->GetHashTbl()->VisitPids([&](IdentPtr pid) { pid->SetTopRef(nullptr); });
  10102. // Restore global scope and blockinfo stacks preparatory to reparsing deferred functions.
  10103. PushScope(pnodeGlobalBlock->scope);
  10104. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeGlobalBlock);
  10105. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalBlock, knopBlock, nullptr);
  10106. if (pnodeGlobalEvalBlock)
  10107. {
  10108. PushScope(pnodeGlobalEvalBlock->scope);
  10109. newBlockInfo = PushBlockInfo(pnodeGlobalEvalBlock);
  10110. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalEvalBlock, knopBlock, nullptr);
  10111. }
  10112. // Finally, see if there are any function bodies we now want to generate because we
  10113. // decided to stop deferring.
  10114. FinishDeferredFunction(pnodeProg->pnodeScopes);
  10115. }
  10116. if (pnodeGlobalEvalBlock)
  10117. {
  10118. FinishParseBlock(pnodeGlobalEvalBlock);
  10119. }
  10120. // Append block as body of pnodeProg
  10121. FinishParseBlock(pnodeGlobalBlock);
  10122. m_scriptContext->AddSourceSize(m_length);
  10123. if (m_parseType != ParseType_Deferred)
  10124. {
  10125. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));
  10126. }
  10127. return pnodeProg;
  10128. }
  10129. bool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)
  10130. {
  10131. // A directive is a string constant followed by a statement terminating token
  10132. if (m_token.tk != tkStrCon)
  10133. return false;
  10134. // Careful, need to check for octal before calling this->GetScanner()->Scan()
  10135. // because Scan() clears the "had octal" flag on the scanner and
  10136. // this->GetScanner()->Restore() does not restore this flag.
  10137. if (pIsOctalInString != nullptr)
  10138. {
  10139. *pIsOctalInString = this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber();
  10140. }
  10141. Ident* pidDirective = m_token.GetStr();
  10142. RestorePoint start;
  10143. this->GetScanner()->Capture(&start);
  10144. this->GetScanner()->Scan();
  10145. bool isDirective = true;
  10146. switch (m_token.tk)
  10147. {
  10148. case tkSColon:
  10149. case tkEOF:
  10150. case tkLCurly:
  10151. case tkRCurly:
  10152. break;
  10153. default:
  10154. if (!this->GetScanner()->FHadNewLine())
  10155. {
  10156. isDirective = false;
  10157. }
  10158. break;
  10159. }
  10160. if (isDirective)
  10161. {
  10162. if (pIsUseStrict != nullptr)
  10163. {
  10164. *pIsUseStrict = CheckStrictModeStrPid(pidDirective);
  10165. }
  10166. if (pIsUseAsm != nullptr)
  10167. {
  10168. *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);
  10169. }
  10170. }
  10171. this->GetScanner()->SeekTo(start);
  10172. return isDirective;
  10173. }
  10174. bool Parser::CheckStrictModeStrPid(IdentPtr pid)
  10175. {
  10176. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10177. if (Js::Configuration::Global.flags.NoStrictMode)
  10178. return false;
  10179. #endif
  10180. return pid != nullptr &&
  10181. pid->Cch() == 10 &&
  10182. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10183. wcsncmp(pid->Psz(), _u("use strict"), 10) == 0;
  10184. }
  10185. bool Parser::CheckAsmjsModeStrPid(IdentPtr pid)
  10186. {
  10187. #ifdef ASMJS_PLAT
  10188. if (!CONFIG_FLAG(AsmJs))
  10189. {
  10190. return false;
  10191. }
  10192. bool isAsmCandidate = (pid != nullptr &&
  10193. AutoSystemInfo::Data.SSE2Available() &&
  10194. pid->Cch() == 7 &&
  10195. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10196. wcsncmp(pid->Psz(), _u("use asm"), 10) == 0);
  10197. #ifdef ENABLE_SCRIPT_DEBUGGING
  10198. if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())
  10199. {
  10200. // We would like to report this to debugger - they may choose to disable debugging.
  10201. // TODO : localization of the string?
  10202. 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);
  10203. return false;
  10204. }
  10205. #endif
  10206. return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);
  10207. #else
  10208. return false;
  10209. #endif
  10210. }
  10211. HRESULT Parser::ParseUtf8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10212. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10213. {
  10214. m_functionBody = nullptr;
  10215. m_parseType = ParseType_Upfront;
  10216. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10217. }
  10218. HRESULT Parser::ParseCesu8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10219. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10220. {
  10221. m_functionBody = nullptr;
  10222. m_parseType = ParseType_Upfront;
  10223. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10224. }
  10225. #if ENABLE_BACKGROUND_PARSING
  10226. void Parser::PrepareForBackgroundParse()
  10227. {
  10228. this->GetScanner()->PrepareForBackgroundParse(m_scriptContext);
  10229. }
  10230. void Parser::AddBackgroundParseItem(BackgroundParseItem *const item)
  10231. {
  10232. if (currBackgroundParseItem == nullptr)
  10233. {
  10234. backgroundParseItems = item;
  10235. }
  10236. else
  10237. {
  10238. currBackgroundParseItem->SetNext(item);
  10239. }
  10240. currBackgroundParseItem = item;
  10241. }
  10242. void Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)
  10243. {
  10244. Assert(!IsBackgroundParser());
  10245. Assert(m_doingFastScan);
  10246. if (fastScannedRegExpNodes == nullptr)
  10247. {
  10248. fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);
  10249. }
  10250. fastScannedRegExpNodes->Append(pnode);
  10251. }
  10252. void Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)
  10253. {
  10254. Assert(IsBackgroundParser());
  10255. Assert(currBackgroundParseItem != nullptr);
  10256. currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);
  10257. }
  10258. HRESULT Parser::ParseFunctionInBackground(ParseNodeFnc * pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)
  10259. {
  10260. m_functionBody = nullptr;
  10261. m_parseType = ParseType_Upfront;
  10262. HRESULT hr = S_OK;
  10263. SmartFPUControl smartFpuControl;
  10264. uint nextFunctionId = pnodeFnc->functionId + 1;
  10265. this->RestoreContext(parseContext);
  10266. m_nextFunctionId = &nextFunctionId;
  10267. m_deferringAST = topLevelDeferred;
  10268. m_inDeferredNestedFunc = false;
  10269. m_scopeCountNoAst = 0;
  10270. SetCurrentStatement(nullptr);
  10271. pnodeFnc->pnodeVars = nullptr;
  10272. pnodeFnc->pnodeParams = nullptr;
  10273. pnodeFnc->pnodeBody = nullptr;
  10274. pnodeFnc->nestedCount = 0;
  10275. ParseNodeFnc * pnodeParentFnc = GetCurrentFunctionNode();
  10276. m_currentNodeFunc = pnodeFnc;
  10277. m_currentNodeDeferredFunc = nullptr;
  10278. m_ppnodeScope = nullptr;
  10279. m_ppnodeExprScope = nullptr;
  10280. m_pnestedCount = &pnodeFnc->nestedCount;
  10281. m_pCurrentAstSize = &pnodeFnc->astSize;
  10282. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10283. pnodeFnc->pnodeScopes = pnodeBlock;
  10284. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  10285. uint uDeferSave = m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse);
  10286. try
  10287. {
  10288. this->GetScanner()->Scan();
  10289. m_ppnodeVar = &pnodeFnc->pnodeParams;
  10290. this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);
  10291. if (m_token.tk == tkRParen)
  10292. {
  10293. this->GetScanner()->Scan();
  10294. }
  10295. ChkCurTok(tkLCurly, ERRnoLcurly);
  10296. m_ppnodeVar = &pnodeFnc->pnodeVars;
  10297. // Put the scanner into "no hashing" mode.
  10298. BYTE deferFlags = this->GetScanner()->SetDeferredParse(topLevelDeferred);
  10299. // Process a sequence of statements/declarations
  10300. if (topLevelDeferred)
  10301. {
  10302. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);
  10303. }
  10304. else
  10305. {
  10306. ParseNodePtr *lastNodeRef = nullptr;
  10307. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);
  10308. AddArgumentsNodeToVars(pnodeFnc);
  10309. // Append an EndCode node.
  10310. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  10311. }
  10312. // Restore the scanner's default hashing mode.
  10313. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  10314. #if DBG
  10315. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  10316. #endif
  10317. this->m_deferringAST = FALSE;
  10318. // Append block as body of pnodeProg
  10319. FinishParseBlock(pnodeBlock);
  10320. }
  10321. catch (ParseExceptionObject& e)
  10322. {
  10323. hr = e.GetError();
  10324. }
  10325. if (FAILED(hr))
  10326. {
  10327. hr = pse->ProcessError(this->GetScanner(), hr, nullptr);
  10328. }
  10329. if (IsStrictMode())
  10330. {
  10331. pnodeFnc->SetStrictMode();
  10332. }
  10333. if (topLevelDeferred)
  10334. {
  10335. pnodeFnc->pnodeVars = nullptr;
  10336. }
  10337. m_grfscr |= uDeferSave;
  10338. Assert(nullptr == *m_ppnodeScope);
  10339. return hr;
  10340. }
  10341. #endif
  10342. HRESULT Parser::ParseSourceWithOffset(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,
  10343. bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,
  10344. Js::ParseableFunctionInfo* functionInfo)
  10345. {
  10346. m_functionBody = functionInfo;
  10347. if (m_functionBody)
  10348. {
  10349. m_currDeferredStub = m_functionBody->GetDeferredStubs();
  10350. m_currDeferredStubCount = m_currDeferredStub != nullptr ? m_functionBody->GetNestedCount() : 0;
  10351. m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();
  10352. }
  10353. m_deferAsmJs = !m_InAsmMode;
  10354. m_parseType = ParseType_Deferred;
  10355. return ParseSourceInternal(parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);
  10356. }
  10357. bool Parser::IsStrictMode() const
  10358. {
  10359. return (m_fUseStrictMode ||
  10360. (m_currentNodeFunc != nullptr && m_currentNodeFunc->GetStrictMode()));
  10361. }
  10362. BOOL Parser::ExpectingExternalSource()
  10363. {
  10364. return m_fExpectExternalSource;
  10365. }
  10366. Symbol *ParseNodeFnc::GetFuncSymbol()
  10367. {
  10368. if (pnodeName)
  10369. {
  10370. Assert(pnodeName->nop == knopVarDecl);
  10371. return pnodeName->sym;
  10372. }
  10373. return nullptr;
  10374. }
  10375. void ParseNodeFnc::SetFuncSymbol(Symbol *sym)
  10376. {
  10377. Assert(pnodeName);
  10378. Assert(pnodeName->nop == knopVarDecl);
  10379. pnodeName->sym = sym;
  10380. }
  10381. ParseNodePtr ParseNodeFnc::GetParamScope() const
  10382. {
  10383. if (this->pnodeScopes == nullptr)
  10384. {
  10385. return nullptr;
  10386. }
  10387. Assert(this->pnodeScopes->nop == knopBlock &&
  10388. this->pnodeScopes->pnodeNext == nullptr);
  10389. return this->pnodeScopes->pnodeScopes;
  10390. }
  10391. ParseNodePtr ParseNodeFnc::GetBodyScope() const
  10392. {
  10393. if (this->pnodeBodyScope == nullptr)
  10394. {
  10395. return nullptr;
  10396. }
  10397. Assert(this->pnodeBodyScope->nop == knopBlock &&
  10398. this->pnodeBodyScope->pnodeNext == nullptr);
  10399. return this->pnodeBodyScope->pnodeScopes;
  10400. }
  10401. bool ParseNodeBlock::HasBlockScopedContent() const
  10402. {
  10403. // A block has its own content if a let, const, or function is declared there.
  10404. if (this->pnodeLexVars != nullptr || this->blockType == Parameter)
  10405. {
  10406. return true;
  10407. }
  10408. // The enclosing scopes can contain functions and other things, so walk the list
  10409. // looking specifically for functions.
  10410. for (ParseNodePtr pnode = this->pnodeScopes; pnode;)
  10411. {
  10412. switch (pnode->nop) {
  10413. case knopFncDecl:
  10414. return true;
  10415. case knopBlock:
  10416. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  10417. break;
  10418. case knopCatch:
  10419. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  10420. break;
  10421. case knopWith:
  10422. pnode = pnode->AsParseNodeWith()->pnodeNext;
  10423. break;
  10424. default:
  10425. Assert(UNREACHED);
  10426. return true;
  10427. }
  10428. }
  10429. return false;
  10430. }
  10431. class ByteCodeGenerator;
  10432. // Copy AST; this works mostly on expressions for now
  10433. ParseNode* Parser::CopyPnode(ParseNode *pnode) {
  10434. if (pnode == NULL)
  10435. return NULL;
  10436. switch (pnode->nop) {
  10437. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  10438. case knopName: {
  10439. ParseNodeName * nameNode = CreateNameNode(pnode->AsParseNodeName()->pid);
  10440. nameNode->ichMin = pnode->ichMin;
  10441. nameNode->ichLim = pnode->ichLim;
  10442. nameNode->sym = pnode->AsParseNodeName()->sym;
  10443. return nameNode;
  10444. }
  10445. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  10446. case knopInt:
  10447. return pnode;
  10448. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  10449. case knopFlt:
  10450. return pnode;
  10451. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  10452. case knopStr:
  10453. return pnode;
  10454. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  10455. case knopRegExp:
  10456. return pnode;
  10457. break;
  10458. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  10459. case knopNull:
  10460. return pnode;
  10461. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  10462. case knopFalse:
  10463. {
  10464. ParseNode* ret = CreateNodeForOpT<knopFalse>(pnode->ichMin, pnode->ichLim);
  10465. ret->location = pnode->location;
  10466. return ret;
  10467. }
  10468. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  10469. case knopTrue:
  10470. {
  10471. ParseNode* ret = CreateNodeForOpT<knopTrue>(pnode->ichMin, pnode->ichLim);
  10472. ret->location = pnode->location;
  10473. return ret;
  10474. }
  10475. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  10476. case knopEmpty:
  10477. return CreateNodeForOpT<knopEmpty>(pnode->ichMin, pnode->ichLim);
  10478. // Unary operators.
  10479. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  10480. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  10481. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  10482. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  10483. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  10484. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  10485. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  10486. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  10487. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  10488. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  10489. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  10490. case knopNot:
  10491. case knopNeg:
  10492. case knopPos:
  10493. case knopLogNot:
  10494. case knopEllipsis:
  10495. case knopIncPost:
  10496. case knopDecPost:
  10497. case knopIncPre:
  10498. case knopDecPre:
  10499. case knopTypeof:
  10500. case knopVoid:
  10501. case knopDelete:
  10502. return CreateUniNode(pnode->nop, CopyPnode(pnode->AsParseNodeUni()->pnode1), pnode->ichMin, pnode->ichLim);
  10503. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  10504. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  10505. case knopArray:
  10506. case knopObject:
  10507. // TODO: need to copy arr
  10508. Assert(false);
  10509. break;
  10510. // Binary operators
  10511. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  10512. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  10513. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  10514. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  10515. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  10516. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  10517. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  10518. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  10519. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  10520. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  10521. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  10522. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  10523. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  10524. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  10525. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  10526. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  10527. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  10528. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  10529. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  10530. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  10531. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10532. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10533. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  10534. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  10535. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  10536. case knopAdd:
  10537. case knopSub:
  10538. case knopMul:
  10539. case knopExpo:
  10540. case knopDiv:
  10541. case knopMod:
  10542. case knopOr:
  10543. case knopXor:
  10544. case knopAnd:
  10545. case knopEq:
  10546. case knopNe:
  10547. case knopLt:
  10548. case knopLe:
  10549. case knopGe:
  10550. case knopGt:
  10551. case knopEqv:
  10552. case knopIn:
  10553. case knopInstOf:
  10554. case knopNEqv:
  10555. case knopComma:
  10556. case knopLogOr:
  10557. case knopLogAnd:
  10558. case knopLsh:
  10559. case knopRsh:
  10560. case knopRs2:
  10561. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10562. case knopAsg:
  10563. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  10564. case knopDot:
  10565. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  10566. case knopAsgAdd:
  10567. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  10568. case knopAsgSub:
  10569. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  10570. case knopAsgMul:
  10571. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  10572. case knopAsgExpo:
  10573. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  10574. case knopAsgDiv:
  10575. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  10576. case knopAsgMod:
  10577. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  10578. case knopAsgAnd:
  10579. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  10580. case knopAsgXor:
  10581. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  10582. case knopAsgOr:
  10583. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  10584. case knopAsgLsh:
  10585. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  10586. case knopAsgRsh:
  10587. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  10588. case knopAsgRs2:
  10589. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  10590. case knopMember:
  10591. case knopMemberShort:
  10592. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  10593. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  10594. case knopIndex:
  10595. case knopList:
  10596. return CreateBinNode(pnode->nop, CopyPnode(pnode->AsParseNodeBin()->pnode1),
  10597. CopyPnode(pnode->AsParseNodeBin()->pnode2), pnode->ichMin, pnode->ichLim);
  10598. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  10599. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  10600. case knopNew:
  10601. case knopCall:
  10602. return CreateCallNode(pnode->nop, CopyPnode(pnode->AsParseNodeCall()->pnodeTarget),
  10603. CopyPnode(pnode->AsParseNodeCall()->pnodeArgs), pnode->ichMin, pnode->ichLim);
  10604. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10605. case knopQmark:
  10606. return CreateTriNode(pnode->nop, CopyPnode(pnode->AsParseNodeTri()->pnode1),
  10607. CopyPnode(pnode->AsParseNodeTri()->pnode2), CopyPnode(pnode->AsParseNodeTri()->pnode3),
  10608. pnode->ichMin, pnode->ichLim);
  10609. // General nodes.
  10610. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10611. case knopVarDecl: {
  10612. ParseNodeVar* copyNode = Anew(&m_nodeAllocator, ParseNodeVar, knopVarDecl, pnode->ichMin, pnode->ichLim, nullptr);
  10613. copyNode->pnodeInit = CopyPnode(pnode->AsParseNodeVar()->pnodeInit);
  10614. copyNode->sym = pnode->AsParseNodeVar()->sym;
  10615. // TODO: mult-decl
  10616. Assert(pnode->AsParseNodeVar()->pnodeNext == NULL);
  10617. copyNode->pnodeNext = NULL;
  10618. return copyNode;
  10619. }
  10620. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10621. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  10622. case knopFncDecl:
  10623. case knopProg:
  10624. Assert(false);
  10625. break;
  10626. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  10627. case knopEndCode:
  10628. break;
  10629. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10630. case knopDebugger:
  10631. break;
  10632. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10633. case knopFor: {
  10634. ParseNode* copyNode = CreateNodeForOpT<knopFor>(pnode->ichMin, pnode->ichLim);
  10635. copyNode->AsParseNodeFor()->pnodeInverted = NULL;
  10636. copyNode->AsParseNodeFor()->pnodeInit = CopyPnode(pnode->AsParseNodeFor()->pnodeInit);
  10637. copyNode->AsParseNodeFor()->pnodeCond = CopyPnode(pnode->AsParseNodeFor()->pnodeCond);
  10638. copyNode->AsParseNodeFor()->pnodeIncr = CopyPnode(pnode->AsParseNodeFor()->pnodeIncr);
  10639. copyNode->AsParseNodeFor()->pnodeBody = CopyPnode(pnode->AsParseNodeFor()->pnodeBody);
  10640. return copyNode;
  10641. }
  10642. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10643. case knopIf:
  10644. Assert(false);
  10645. break;
  10646. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  10647. case knopWhile:
  10648. Assert(false);
  10649. break;
  10650. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10651. case knopDoWhile:
  10652. Assert(false);
  10653. break;
  10654. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10655. case knopForIn:
  10656. Assert(false);
  10657. break;
  10658. case knopForOf:
  10659. Assert(false);
  10660. break;
  10661. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10662. case knopReturn: {
  10663. ParseNode* copyNode = CreateNodeForOpT<knopReturn>(pnode->ichMin, pnode->ichLim);
  10664. copyNode->AsParseNodeReturn()->pnodeExpr = CopyPnode(pnode->AsParseNodeReturn()->pnodeExpr);
  10665. return copyNode;
  10666. }
  10667. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10668. case knopBlock: {
  10669. ParseNodeBlock* copyNode = CreateBlockNode(pnode->ichMin, pnode->ichLim, pnode->AsParseNodeBlock()->blockType);
  10670. if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {
  10671. // fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which
  10672. // CreateBlockNode() will not automatically set for us, so set it here if it's
  10673. // specified on the source node.
  10674. copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;
  10675. }
  10676. copyNode->pnodeStmt = CopyPnode(pnode->AsParseNodeBlock()->pnodeStmt);
  10677. return copyNode;
  10678. }
  10679. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10680. case knopWith:
  10681. Assert(false);
  10682. break;
  10683. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10684. case knopBreak:
  10685. Assert(false);
  10686. break;
  10687. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10688. case knopContinue:
  10689. Assert(false);
  10690. break;
  10691. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  10692. case knopSwitch:
  10693. Assert(false);
  10694. break;
  10695. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  10696. case knopCase:
  10697. Assert(false);
  10698. break;
  10699. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  10700. case knopTryFinally:
  10701. Assert(false);
  10702. break;
  10703. case knopFinally:
  10704. Assert(false);
  10705. break;
  10706. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  10707. case knopCatch:
  10708. Assert(false);
  10709. break;
  10710. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  10711. case knopTryCatch:
  10712. Assert(false);
  10713. break;
  10714. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  10715. case knopTry:
  10716. Assert(false);
  10717. break;
  10718. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  10719. case knopThrow:
  10720. Assert(false);
  10721. break;
  10722. default:
  10723. Assert(false);
  10724. break;
  10725. }
  10726. return NULL;
  10727. }
  10728. // Returns true when str is string for Nan, Infinity or -Infinity.
  10729. // Does not check for double number value being in NaN/Infinity range.
  10730. // static
  10731. template<bool CheckForNegativeInfinity>
  10732. inline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)
  10733. {
  10734. // Note: wcscmp crashes when one of the parameters is NULL.
  10735. return str &&
  10736. (wcscmp(_u("NaN"), str) == 0 ||
  10737. wcscmp(_u("Infinity"), str) == 0 ||
  10738. (CheckForNegativeInfinity && wcscmp(_u("-Infinity"), str) == 0));
  10739. }
  10740. template <bool buildAST>
  10741. IdentPtr Parser::ParseSuper(bool fAllowCall)
  10742. {
  10743. ParseNodeFnc * currentNodeFunc = GetCurrentFunctionNode();
  10744. IdentPtr superPid = nullptr;
  10745. switch (m_token.tk)
  10746. {
  10747. case tkDot: // super.prop
  10748. case tkLBrack: // super[foo]
  10749. superPid = wellKnownPropertyPids._super;
  10750. break;
  10751. case tkLParen: // super(args)
  10752. superPid = wellKnownPropertyPids._superConstructor;
  10753. break;
  10754. default:
  10755. Error(ERRInvalidSuper);
  10756. break;
  10757. }
  10758. currentNodeFunc->SetHasSuperReference(TRUE);
  10759. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Super, m_scriptContext);
  10760. // If we are defer parsing, we can skip verifying that the super reference is valid.
  10761. // If it wasn't the parser would have thrown during upfront parsing and we wouldn't be defer parsing the function.
  10762. if (m_parseType == ParseType_Deferred)
  10763. {
  10764. return superPid;
  10765. }
  10766. if (!fAllowCall && (m_token.tk == tkLParen))
  10767. {
  10768. Error(ERRInvalidSuper); // new super() is not allowed
  10769. }
  10770. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperCallAndPropertyAllowed)
  10771. {
  10772. // Any super access is good within a class constructor
  10773. }
  10774. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperPropertyAllowed)
  10775. {
  10776. if (m_token.tk == tkLParen)
  10777. {
  10778. if ((this->m_grfscr & fscrEval) == fscrNil)
  10779. {
  10780. // Cannot call super within a class member
  10781. Error(ERRInvalidSuper);
  10782. }
  10783. else
  10784. {
  10785. Js::JavascriptFunction * caller = nullptr;
  10786. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  10787. {
  10788. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  10789. Assert(callerBody);
  10790. if (!callerBody->GetFunctionInfo()->GetAllowDirectSuper())
  10791. {
  10792. Error(ERRInvalidSuper);
  10793. }
  10794. }
  10795. }
  10796. }
  10797. }
  10798. else
  10799. {
  10800. // Anything else is an error
  10801. Error(ERRInvalidSuper);
  10802. }
  10803. return superPid;
  10804. }
  10805. void Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)
  10806. {
  10807. Assert(nodeToAppend);
  10808. ParseNodePtr* lastPtr = node;
  10809. while ((*lastPtr) && (*lastPtr)->nop == knopList)
  10810. {
  10811. lastPtr = &(*lastPtr)->AsParseNodeBin()->pnode2;
  10812. }
  10813. auto last = (*lastPtr);
  10814. if (last)
  10815. {
  10816. *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);
  10817. }
  10818. else
  10819. {
  10820. *lastPtr = nodeToAppend;
  10821. }
  10822. }
  10823. ParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)
  10824. {
  10825. Assert(pnode->nop == knopArray);
  10826. pnode->nop = knopArrayPattern;
  10827. ForEachItemRefInList(&pnode->AsParseNodeArrLit()->pnode1, [&](ParseNodePtr *itemRef) {
  10828. ParseNodePtr item = *itemRef;
  10829. if (item->nop == knopEllipsis)
  10830. {
  10831. itemRef = &item->AsParseNodeUni()->pnode1;
  10832. item = *itemRef;
  10833. if (!(item->nop == knopName
  10834. || item->nop == knopDot
  10835. || item->nop == knopIndex
  10836. || item->nop == knopArray
  10837. || item->nop == knopObject))
  10838. {
  10839. Error(ERRInvalidAssignmentTarget);
  10840. }
  10841. }
  10842. else if (item->nop == knopAsg)
  10843. {
  10844. itemRef = &item->AsParseNodeBin()->pnode1;
  10845. item = *itemRef;
  10846. }
  10847. if (item->nop == knopArray)
  10848. {
  10849. ConvertArrayToArrayPattern(item);
  10850. }
  10851. else if (item->nop == knopObject)
  10852. {
  10853. *itemRef = ConvertObjectToObjectPattern(item);
  10854. }
  10855. else if (item->nop == knopName)
  10856. {
  10857. TrackAssignment<true>(item, nullptr);
  10858. }
  10859. });
  10860. return pnode;
  10861. }
  10862. ParseNodeUni * Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)
  10863. {
  10864. charcount_t ichMin = this->GetScanner()->IchMinTok();
  10865. charcount_t ichLim = this->GetScanner()->IchLimTok();
  10866. ParseNodePtr pnodeMemberNodeList = nullptr;
  10867. if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)
  10868. {
  10869. ichMin = pnodeMemberList->ichMin;
  10870. ichLim = pnodeMemberList->ichLim;
  10871. pnodeMemberList = pnodeMemberList->AsParseNodeUni()->pnode1;
  10872. }
  10873. ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {
  10874. ParseNodePtr memberNode = ConvertMemberToMemberPattern(item);
  10875. AppendToList(&pnodeMemberNodeList, memberNode);
  10876. });
  10877. return CreateUniNode(knopObjectPattern, pnodeMemberNodeList, ichMin, ichLim);
  10878. }
  10879. ParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)
  10880. {
  10881. Assert(pnode != nullptr);
  10882. ParseNodePtr rightNode = nullptr;
  10883. OpCode op = pnode->nop;
  10884. if (op == knopObject)
  10885. {
  10886. rightNode = ConvertObjectToObjectPattern(pnode);
  10887. }
  10888. else if (op == knopArray)
  10889. {
  10890. rightNode = ConvertArrayToArrayPattern(pnode);
  10891. }
  10892. else
  10893. {
  10894. rightNode = pnode;
  10895. if (op == knopName)
  10896. {
  10897. TrackAssignment<true>(pnode, nullptr);
  10898. }
  10899. else if (op == knopAsg)
  10900. {
  10901. TrackAssignment<true>(pnode->AsParseNodeBin()->pnode1, nullptr);
  10902. }
  10903. }
  10904. return rightNode;
  10905. }
  10906. ParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)
  10907. {
  10908. if (pnodeMember->nop == knopObjectPatternMember)
  10909. {
  10910. return pnodeMember;
  10911. }
  10912. Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);
  10913. ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->AsParseNodeBin()->pnode2);
  10914. ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->AsParseNodeBin()->pnode1, rightNode);
  10915. resultNode->ichMin = pnodeMember->ichMin;
  10916. resultNode->ichLim = pnodeMember->ichLim;
  10917. return resultNode;
  10918. }
  10919. ParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)
  10920. {
  10921. if (pnode != nullptr)
  10922. {
  10923. if (pnode->nop == knopArray)
  10924. {
  10925. ConvertArrayToArrayPattern(pnode);
  10926. }
  10927. else if (pnode->nop == knopObject)
  10928. {
  10929. pnode = ConvertObjectToObjectPattern(pnode);
  10930. }
  10931. }
  10932. return pnode;
  10933. }
  10934. // This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.
  10935. void Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,
  10936. bool isDecl,
  10937. bool topLevel,
  10938. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  10939. bool allowIn /*= true*/)
  10940. {
  10941. // We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and
  10942. // AST related information before the validation parsing and later they will be restored.
  10943. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  10944. ParseNodeFnc * pnodeDeferredFncSave = m_currentNodeDeferredFunc;
  10945. if (m_currentNodeDeferredFunc == nullptr)
  10946. {
  10947. m_currentNodeDeferredFunc = m_currentNodeFunc;
  10948. }
  10949. int32 *pAstSizeSave = m_pCurrentAstSize;
  10950. uint *pNestedCountSave = m_pnestedCount;
  10951. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  10952. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  10953. ParseNodePtr newTempScope = nullptr;
  10954. m_ppnodeScope = &newTempScope;
  10955. int32 newTempAstSize = 0;
  10956. m_pCurrentAstSize = &newTempAstSize;
  10957. uint newTempNestedCount = 0;
  10958. m_pnestedCount = &newTempNestedCount;
  10959. m_ppnodeExprScope = nullptr;
  10960. charcount_t funcInArraySave = m_funcInArray;
  10961. uint funcInArrayDepthSave = m_funcInArrayDepth;
  10962. // we need to reset this as we are going to parse the grammar again.
  10963. m_hasDeferredShorthandInitError = false;
  10964. ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);
  10965. m_currentNodeFunc = pnodeFncSave;
  10966. m_currentNodeDeferredFunc = pnodeDeferredFncSave;
  10967. m_pCurrentAstSize = pAstSizeSave;
  10968. m_pnestedCount = pNestedCountSave;
  10969. m_ppnodeScope = ppnodeScopeSave;
  10970. m_ppnodeExprScope = ppnodeExprScopeSave;
  10971. m_funcInArray = funcInArraySave;
  10972. m_funcInArrayDepth = funcInArrayDepthSave;
  10973. }
  10974. template <bool buildAST>
  10975. ParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,
  10976. bool isDecl,
  10977. bool topLevel/* = true*/,
  10978. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  10979. bool allowIn/* = true*/,
  10980. BOOL *forInOfOkay/* = nullptr*/,
  10981. BOOL *nativeForOkay/* = nullptr*/)
  10982. {
  10983. ParseNodeUni * pnode = nullptr;
  10984. Assert(IsPossiblePatternStart());
  10985. if (m_token.tk == tkLCurly)
  10986. {
  10987. pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);
  10988. }
  10989. else
  10990. {
  10991. pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);
  10992. }
  10993. return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);
  10994. }
  10995. template <bool buildAST>
  10996. ParseNodePtr Parser::ParseDestructuredInitializer(ParseNodeUni * lhsNode,
  10997. bool isDecl,
  10998. bool topLevel,
  10999. DestructuringInitializerContext initializerContext,
  11000. bool allowIn,
  11001. BOOL *forInOfOkay,
  11002. BOOL *nativeForOkay)
  11003. {
  11004. this->GetScanner()->Scan();
  11005. if (topLevel && nativeForOkay == nullptr)
  11006. {
  11007. if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)
  11008. {
  11009. // e.g. var {x};
  11010. Error(ERRDestructInit);
  11011. }
  11012. else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)
  11013. {
  11014. // e.g. catch([x] = [0])
  11015. Error(ERRDestructNotInit);
  11016. }
  11017. }
  11018. if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)
  11019. {
  11020. if (topLevel && nativeForOkay != nullptr)
  11021. {
  11022. // Native loop should have destructuring initializer
  11023. *nativeForOkay = FALSE;
  11024. }
  11025. return lhsNode;
  11026. }
  11027. if (forInOfOkay)
  11028. {
  11029. *forInOfOkay = FALSE;
  11030. }
  11031. this->GetScanner()->Scan();
  11032. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11033. ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);
  11034. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11035. {
  11036. Error(ERRnoColon);
  11037. }
  11038. ParseNodeBin * pnodeDestructAsg = nullptr;
  11039. if (buildAST)
  11040. {
  11041. Assert(lhsNode != nullptr);
  11042. pnodeDestructAsg = CreateBinNode(knopAsg, lhsNode, pnodeDefault, lhsNode->ichMin, pnodeDefault->ichLim);
  11043. }
  11044. return pnodeDestructAsg;
  11045. }
  11046. template <bool buildAST>
  11047. ParseNodeUni * Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel/* = true*/)
  11048. {
  11049. Assert(m_token.tk == tkLCurly);
  11050. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11051. this->GetScanner()->Scan();
  11052. if (!isDecl)
  11053. {
  11054. declarationType = tkLCurly;
  11055. }
  11056. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr/*pNameHint*/, nullptr/*pHintLength*/, declarationType);
  11057. Assert(m_token.tk == tkRCurly);
  11058. ParseNodeUni * objectPatternNode = nullptr;
  11059. if (buildAST)
  11060. {
  11061. charcount_t ichLim = this->GetScanner()->IchLimTok();
  11062. objectPatternNode = CreateUniNode(knopObjectPattern, pnodeMemberList, ichMin, ichLim);
  11063. }
  11064. return objectPatternNode;
  11065. }
  11066. template <bool buildAST>
  11067. ParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel/* = true*/, bool allowEmptyExpression/* = true*/)
  11068. {
  11069. ParseNodePtr pnodeElem = nullptr;
  11070. int parenCount = 0;
  11071. bool seenRest = false;
  11072. // Save the Block ID prior to the increments, so we can restore it back.
  11073. int originalCurrentBlockId = GetCurrentBlock()->blockId;
  11074. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11075. if (!isDecl)
  11076. {
  11077. while (m_token.tk == tkLParen)
  11078. {
  11079. this->GetScanner()->Scan();
  11080. ++parenCount;
  11081. // Match the block increment we do upon entering parenthetical expressions
  11082. // so that the block ID's will match on reparsing of parameters.
  11083. GetCurrentBlock()->blockId = m_nextBlockId++;
  11084. }
  11085. }
  11086. if (m_token.tk == tkEllipsis)
  11087. {
  11088. // As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed
  11089. // But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.
  11090. seenRest = true;
  11091. this->GetScanner()->Scan();
  11092. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11093. if (!isDecl)
  11094. {
  11095. while (m_token.tk == tkLParen)
  11096. {
  11097. this->GetScanner()->Scan();
  11098. ++parenCount;
  11099. // Match the block increment we do upon entering parenthetical expressions
  11100. // so that the block ID's will match on reparsing of parameters.
  11101. GetCurrentBlock()->blockId = m_nextBlockId++;
  11102. }
  11103. }
  11104. if (m_token.tk != tkID && m_token.tk != tkTHIS && m_token.tk != tkSUPER && m_token.tk != tkLCurly && m_token.tk != tkLBrack)
  11105. {
  11106. if (isDecl)
  11107. {
  11108. Error(ERRnoIdent);
  11109. }
  11110. else
  11111. {
  11112. Error(ERRInvalidAssignmentTarget);
  11113. }
  11114. }
  11115. }
  11116. if (IsPossiblePatternStart())
  11117. {
  11118. // For the possible pattern start we do not allow the parens before
  11119. if (parenCount != 0)
  11120. {
  11121. Error(ERRDestructIDRef);
  11122. }
  11123. // Go recursively
  11124. pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false /*topLevel*/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);
  11125. if (!isDecl)
  11126. {
  11127. BOOL fCanAssign;
  11128. IdentToken token;
  11129. // Look for postfix operator
  11130. pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  11131. }
  11132. }
  11133. else if (m_token.tk == tkSUPER || m_token.tk == tkID || m_token.tk == tkTHIS)
  11134. {
  11135. if (isDecl)
  11136. {
  11137. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11138. pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin
  11139. ,/* fAllowIn */false, /* pfForInOk */nullptr, /* singleDefOnly */true, /* allowInit */!seenRest, false /*topLevelParse*/);
  11140. }
  11141. else
  11142. {
  11143. BOOL fCanAssign;
  11144. IdentToken token;
  11145. // We aren't declaring anything, so scan the ID reference manually.
  11146. pnodeElem = ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false,
  11147. FALSE, &fCanAssign);
  11148. // In this destructuring case we can force error here as we cannot assign.
  11149. if (!fCanAssign)
  11150. {
  11151. Error(ERRInvalidAssignmentTarget);
  11152. }
  11153. if (buildAST)
  11154. {
  11155. if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)
  11156. {
  11157. CheckStrictModeEvalArgumentsUsage(pnodeElem->AsParseNodeName()->pid);
  11158. }
  11159. }
  11160. else
  11161. {
  11162. if (IsStrictMode() && token.tk == tkID)
  11163. {
  11164. CheckStrictModeEvalArgumentsUsage(token.pid);
  11165. }
  11166. token.tk = tkNone;
  11167. }
  11168. }
  11169. }
  11170. else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))
  11171. {
  11172. if (m_token.IsOperator())
  11173. {
  11174. Error(ERRDestructNoOper);
  11175. }
  11176. Error(ERRDestructIDRef);
  11177. }
  11178. // Swallow RParens before a default expression, if any.
  11179. // 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.
  11180. if (!isDecl)
  11181. {
  11182. while (m_token.tk == tkRParen)
  11183. {
  11184. this->GetScanner()->Scan();
  11185. --parenCount;
  11186. }
  11187. // Restore the Block ID of the current block after the parsing of destructured variable declarations and initializers.
  11188. GetCurrentBlock()->blockId = originalCurrentBlockId;
  11189. }
  11190. if (parenCount != 0)
  11191. {
  11192. Error(ERRnoRparen);
  11193. }
  11194. if (hasSeenRest != nullptr)
  11195. {
  11196. *hasSeenRest = seenRest;
  11197. }
  11198. if (m_token.tk == tkAsg)
  11199. {
  11200. // Parse the initializer.
  11201. if (seenRest)
  11202. {
  11203. Error(ERRRestWithDefault);
  11204. }
  11205. this->GetScanner()->Scan();
  11206. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11207. ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);
  11208. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11209. {
  11210. Error(ERRnoColon);
  11211. }
  11212. if (buildAST)
  11213. {
  11214. pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);
  11215. }
  11216. }
  11217. if (buildAST && seenRest)
  11218. {
  11219. ParseNodePtr pnodeRest = CreateUniNode(knopEllipsis, pnodeElem);
  11220. pnodeElem = pnodeRest;
  11221. }
  11222. if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))
  11223. {
  11224. if (m_token.IsOperator())
  11225. {
  11226. Error(ERRDestructNoOper);
  11227. }
  11228. Error(ERRsyntax);
  11229. }
  11230. return pnodeElem;
  11231. }
  11232. template <bool buildAST>
  11233. ParseNodeUni * Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)
  11234. {
  11235. Assert(m_token.tk == tkLBrack);
  11236. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11237. this->GetScanner()->Scan();
  11238. ParseNodeArrLit * pnodeDestructArr = nullptr;
  11239. ParseNodePtr pnodeList = nullptr;
  11240. ParseNodePtr *lastNodeRef = nullptr;
  11241. uint count = 0;
  11242. bool hasMissingValues = false;
  11243. bool seenRest = false;
  11244. if (m_token.tk != tkRBrack)
  11245. {
  11246. while (true)
  11247. {
  11248. ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);
  11249. if (buildAST)
  11250. {
  11251. if (pnodeElem == nullptr && buildAST)
  11252. {
  11253. pnodeElem = CreateNodeForOpT<knopEmpty>();
  11254. hasMissingValues = true;
  11255. }
  11256. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);
  11257. }
  11258. count++;
  11259. if (m_token.tk == tkRBrack)
  11260. {
  11261. break;
  11262. }
  11263. if (m_token.tk != tkComma)
  11264. {
  11265. Error(ERRDestructNoOper);
  11266. }
  11267. if (seenRest) // Rest must be in the last position.
  11268. {
  11269. Error(ERRDestructRestLast);
  11270. }
  11271. this->GetScanner()->Scan();
  11272. // break if we have the trailing comma as well, eg. [a,]
  11273. if (m_token.tk == tkRBrack)
  11274. {
  11275. break;
  11276. }
  11277. }
  11278. }
  11279. if (buildAST)
  11280. {
  11281. pnodeDestructArr = CreateNodeForOpT<knopArrayPattern>(ichMin);
  11282. pnodeDestructArr->pnode1 = pnodeList;
  11283. pnodeDestructArr->arrayOfTaggedInts = false;
  11284. pnodeDestructArr->arrayOfInts = false;
  11285. pnodeDestructArr->arrayOfNumbers = false;
  11286. pnodeDestructArr->hasMissingValues = hasMissingValues;
  11287. pnodeDestructArr->count = count;
  11288. pnodeDestructArr->spreadCount = seenRest ? 1 : 0;
  11289. if (pnodeDestructArr->pnode1)
  11290. {
  11291. this->CheckArguments(pnodeDestructArr->pnode1);
  11292. }
  11293. }
  11294. return pnodeDestructArr;
  11295. }
  11296. void Parser::CaptureContext(ParseContext *parseContext) const
  11297. {
  11298. parseContext->pszSrc = this->GetScanner()->PchBase();
  11299. parseContext->length = this->m_originalLength;
  11300. parseContext->characterOffset = this->GetScanner()->IchMinTok();
  11301. parseContext->offset = parseContext->characterOffset + this->GetScanner()->m_cMultiUnits;
  11302. parseContext->grfscr = this->m_grfscr;
  11303. parseContext->lineNumber = this->GetScanner()->LineCur();
  11304. parseContext->pnodeProg = this->m_currentNodeProg;
  11305. parseContext->isUtf8 = this->GetScanner()->IsUtf8();
  11306. parseContext->strictMode = this->IsStrictMode();
  11307. parseContext->sourceContextInfo = this->m_sourceContextInfo;
  11308. parseContext->currentBlockInfo = this->m_currentBlockInfo;
  11309. parseContext->nextBlockId = this->m_nextBlockId;
  11310. }
  11311. void Parser::RestoreContext(ParseContext *const parseContext)
  11312. {
  11313. m_sourceContextInfo = parseContext->sourceContextInfo;
  11314. m_currentBlockInfo = parseContext->currentBlockInfo;
  11315. m_nextBlockId = parseContext->nextBlockId;
  11316. m_grfscr = parseContext->grfscr;
  11317. m_length = parseContext->length;
  11318. this->GetScanner()->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->isUtf8, parseContext->grfscr, parseContext->lineNumber);
  11319. m_currentNodeProg = parseContext->pnodeProg;
  11320. m_fUseStrictMode = parseContext->strictMode;
  11321. }
  11322. class ByteCodeGenerator;
  11323. #if DBG_DUMP
  11324. #define INDENT_SIZE 2
  11325. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt);
  11326. void PrintFormalsWIndent(ParseNode *pnode, int indentAmt);
  11327. void Indent(int indentAmt) {
  11328. for (int i = 0; i < indentAmt; i++) {
  11329. Output::Print(_u(" "));
  11330. }
  11331. }
  11332. void PrintBlockType(PnodeBlockType type)
  11333. {
  11334. switch (type)
  11335. {
  11336. case Global:
  11337. Output::Print(_u("(Global)"));
  11338. break;
  11339. case Function:
  11340. Output::Print(_u("(Function)"));
  11341. break;
  11342. case Regular:
  11343. Output::Print(_u("(Regular)"));
  11344. break;
  11345. case Parameter:
  11346. Output::Print(_u("(Parameter)"));
  11347. break;
  11348. default:
  11349. Output::Print(_u("(unknown blocktype)"));
  11350. break;
  11351. }
  11352. }
  11353. void PrintScopesWIndent(ParseNode *pnode, int indentAmt) {
  11354. ParseNode *scope = nullptr;
  11355. bool firstOnly = false;
  11356. switch (pnode->nop)
  11357. {
  11358. case knopProg:
  11359. case knopFncDecl: scope = pnode->AsParseNodeFnc()->pnodeScopes; break;
  11360. case knopBlock: scope = pnode->AsParseNodeBlock()->pnodeScopes; break;
  11361. case knopCatch: scope = pnode->AsParseNodeCatch()->pnodeScopes; break;
  11362. case knopWith: scope = pnode->AsParseNodeWith()->pnodeScopes; break;
  11363. case knopSwitch: scope = pnode->AsParseNodeSwitch()->pnodeBlock; firstOnly = true; break;
  11364. case knopFor: scope = pnode->AsParseNodeFor()->pnodeBlock; firstOnly = true; break;
  11365. case knopForIn: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11366. case knopForOf: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11367. }
  11368. if (scope) {
  11369. Output::Print(_u("[%4d, %4d): "), scope->ichMin, scope->ichLim);
  11370. Indent(indentAmt);
  11371. Output::Print(_u("Scopes: "));
  11372. ParseNode *next = nullptr;
  11373. ParseNode *syntheticBlock = nullptr;
  11374. while (scope) {
  11375. switch (scope->nop) {
  11376. case knopFncDecl: Output::Print(_u("knopFncDecl")); next = scope->AsParseNodeFnc()->pnodeNext; break;
  11377. case knopBlock: Output::Print(_u("knopBlock")); PrintBlockType(scope->AsParseNodeBlock()->blockType); next = scope->AsParseNodeBlock()->pnodeNext; break;
  11378. case knopCatch: Output::Print(_u("knopCatch")); next = scope->AsParseNodeCatch()->pnodeNext; break;
  11379. case knopWith: Output::Print(_u("knopWith")); next = scope->AsParseNodeWith()->pnodeNext; break;
  11380. default: Output::Print(_u("unknown")); break;
  11381. }
  11382. if (firstOnly) {
  11383. next = nullptr;
  11384. syntheticBlock = scope;
  11385. }
  11386. if (scope->grfpn & fpnSyntheticNode) {
  11387. Output::Print(_u(" synthetic"));
  11388. if (scope->nop == knopBlock)
  11389. syntheticBlock = scope;
  11390. }
  11391. Output::Print(_u(" (%d-%d)"), scope->ichMin, scope->ichLim);
  11392. if (next) Output::Print(_u(", "));
  11393. scope = next;
  11394. }
  11395. Output::Print(_u("\n"));
  11396. if (syntheticBlock || firstOnly) {
  11397. PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);
  11398. }
  11399. }
  11400. }
  11401. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt) {
  11402. if (pnode == NULL)
  11403. return;
  11404. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11405. switch (pnode->nop) {
  11406. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  11407. case knopName:
  11408. Indent(indentAmt);
  11409. if (pnode->AsParseNodeName()->pid != NULL) {
  11410. Output::Print(_u("id: %s\n"), pnode->AsParseNodeName()->pid->Psz());
  11411. }
  11412. else {
  11413. Output::Print(_u("name node\n"));
  11414. }
  11415. break;
  11416. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11417. case knopInt:
  11418. Indent(indentAmt);
  11419. Output::Print(_u("%d\n"), pnode->AsParseNodeInt()->lw);
  11420. break;
  11421. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  11422. case knopFlt:
  11423. Indent(indentAmt);
  11424. Output::Print(_u("%lf\n"), pnode->AsParseNodeFloat()->dbl);
  11425. break;
  11426. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  11427. case knopStr:
  11428. Indent(indentAmt);
  11429. Output::Print(_u("\"%s\"\n"), pnode->AsParseNodeStr()->pid->Psz());
  11430. break;
  11431. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  11432. case knopRegExp:
  11433. Indent(indentAmt);
  11434. Output::Print(_u("/%x/\n"), pnode->AsParseNodeRegExp()->regexPattern);
  11435. break;
  11436. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  11437. case knopNull:
  11438. Indent(indentAmt);
  11439. Output::Print(_u("null\n"));
  11440. break;
  11441. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  11442. case knopFalse:
  11443. Indent(indentAmt);
  11444. Output::Print(_u("false\n"));
  11445. break;
  11446. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  11447. case knopTrue:
  11448. Indent(indentAmt);
  11449. Output::Print(_u("true\n"));
  11450. break;
  11451. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  11452. case knopEmpty:
  11453. Indent(indentAmt);
  11454. Output::Print(_u("empty\n"));
  11455. break;
  11456. // Unary operators.
  11457. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  11458. case knopNot:
  11459. Indent(indentAmt);
  11460. Output::Print(_u("~\n"));
  11461. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11462. break;
  11463. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  11464. case knopNeg:
  11465. Indent(indentAmt);
  11466. Output::Print(_u("U-\n"));
  11467. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11468. break;
  11469. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  11470. case knopPos:
  11471. Indent(indentAmt);
  11472. Output::Print(_u("U+\n"));
  11473. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11474. break;
  11475. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  11476. case knopLogNot:
  11477. Indent(indentAmt);
  11478. Output::Print(_u("!\n"));
  11479. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11480. break;
  11481. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  11482. case knopEllipsis:
  11483. Indent(indentAmt);
  11484. Output::Print(_u("...<expr>\n"));
  11485. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11486. break;
  11487. //PTNODE(knopIncPost , "++ post" ,Inc ,Uni ,fnopUni|fnopAsg)
  11488. case knopIncPost:
  11489. Indent(indentAmt);
  11490. Output::Print(_u("<expr>++\n"));
  11491. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11492. break;
  11493. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  11494. case knopDecPost:
  11495. Indent(indentAmt);
  11496. Output::Print(_u("<expr>--\n"));
  11497. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11498. break;
  11499. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  11500. case knopIncPre:
  11501. Indent(indentAmt);
  11502. Output::Print(_u("++<expr>\n"));
  11503. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11504. break;
  11505. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  11506. case knopDecPre:
  11507. Indent(indentAmt);
  11508. Output::Print(_u("--<expr>\n"));
  11509. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11510. break;
  11511. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  11512. case knopTypeof:
  11513. Indent(indentAmt);
  11514. Output::Print(_u("typeof\n"));
  11515. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11516. break;
  11517. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  11518. case knopVoid:
  11519. Indent(indentAmt);
  11520. Output::Print(_u("void\n"));
  11521. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11522. break;
  11523. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  11524. case knopDelete:
  11525. Indent(indentAmt);
  11526. Output::Print(_u("delete\n"));
  11527. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11528. break;
  11529. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  11530. case knopArrayPattern:
  11531. Indent(indentAmt);
  11532. Output::Print(_u("Array Pattern\n"));
  11533. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11534. break;
  11535. case knopObjectPattern:
  11536. Indent(indentAmt);
  11537. Output::Print(_u("Object Pattern\n"));
  11538. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11539. break;
  11540. case knopArray:
  11541. Indent(indentAmt);
  11542. Output::Print(_u("Array Literal\n"));
  11543. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11544. break;
  11545. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  11546. case knopObject:
  11547. Indent(indentAmt);
  11548. Output::Print(_u("Object Literal\n"));
  11549. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11550. break;
  11551. // Binary and Ternary Operators
  11552. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  11553. case knopAdd:
  11554. Indent(indentAmt);
  11555. Output::Print(_u("+\n"));
  11556. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11557. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11558. break;
  11559. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  11560. case knopSub:
  11561. Indent(indentAmt);
  11562. Output::Print(_u("-\n"));
  11563. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11564. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11565. break;
  11566. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  11567. case knopMul:
  11568. Indent(indentAmt);
  11569. Output::Print(_u("*\n"));
  11570. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11571. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11572. break;
  11573. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  11574. case knopExpo:
  11575. Indent(indentAmt);
  11576. Output::Print(_u("**\n"));
  11577. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11578. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11579. break;
  11580. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  11581. case knopDiv:
  11582. Indent(indentAmt);
  11583. Output::Print(_u("/\n"));
  11584. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11585. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11586. break;
  11587. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  11588. case knopMod:
  11589. Indent(indentAmt);
  11590. Output::Print(_u("%%\n"));
  11591. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11592. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11593. break;
  11594. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  11595. case knopOr:
  11596. Indent(indentAmt);
  11597. Output::Print(_u("|\n"));
  11598. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11599. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11600. break;
  11601. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  11602. case knopXor:
  11603. Indent(indentAmt);
  11604. Output::Print(_u("^\n"));
  11605. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11606. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11607. break;
  11608. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  11609. case knopAnd:
  11610. Indent(indentAmt);
  11611. Output::Print(_u("&\n"));
  11612. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11613. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11614. break;
  11615. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  11616. case knopEq:
  11617. Indent(indentAmt);
  11618. Output::Print(_u("==\n"));
  11619. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11620. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11621. break;
  11622. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  11623. case knopNe:
  11624. Indent(indentAmt);
  11625. Output::Print(_u("!=\n"));
  11626. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11627. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11628. break;
  11629. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  11630. case knopLt:
  11631. Indent(indentAmt);
  11632. Output::Print(_u("<\n"));
  11633. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11634. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11635. break;
  11636. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  11637. case knopLe:
  11638. Indent(indentAmt);
  11639. Output::Print(_u("<=\n"));
  11640. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11641. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11642. break;
  11643. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  11644. case knopGe:
  11645. Indent(indentAmt);
  11646. Output::Print(_u(">=\n"));
  11647. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11648. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11649. break;
  11650. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  11651. case knopGt:
  11652. Indent(indentAmt);
  11653. Output::Print(_u(">\n"));
  11654. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11655. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11656. break;
  11657. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  11658. case knopCall:
  11659. Indent(indentAmt);
  11660. Output::Print(_u("Call\n"));
  11661. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11662. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11663. break;
  11664. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  11665. case knopDot:
  11666. Indent(indentAmt);
  11667. Output::Print(_u(".\n"));
  11668. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11669. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11670. break;
  11671. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  11672. case knopAsg:
  11673. Indent(indentAmt);
  11674. Output::Print(_u("=\n"));
  11675. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11676. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11677. break;
  11678. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  11679. case knopInstOf:
  11680. Indent(indentAmt);
  11681. Output::Print(_u("instanceof\n"));
  11682. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11683. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11684. break;
  11685. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  11686. case knopIn:
  11687. Indent(indentAmt);
  11688. Output::Print(_u("in\n"));
  11689. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11690. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11691. break;
  11692. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  11693. case knopEqv:
  11694. Indent(indentAmt);
  11695. Output::Print(_u("===\n"));
  11696. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11697. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11698. break;
  11699. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  11700. case knopNEqv:
  11701. Indent(indentAmt);
  11702. Output::Print(_u("!==\n"));
  11703. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11704. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11705. break;
  11706. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  11707. case knopComma:
  11708. Indent(indentAmt);
  11709. Output::Print(_u(",\n"));
  11710. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11711. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11712. break;
  11713. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  11714. case knopLogOr:
  11715. Indent(indentAmt);
  11716. Output::Print(_u("||\n"));
  11717. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11718. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11719. break;
  11720. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  11721. case knopLogAnd:
  11722. Indent(indentAmt);
  11723. Output::Print(_u("&&\n"));
  11724. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11725. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11726. break;
  11727. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  11728. case knopLsh:
  11729. Indent(indentAmt);
  11730. Output::Print(_u("<<\n"));
  11731. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11732. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11733. break;
  11734. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  11735. case knopRsh:
  11736. Indent(indentAmt);
  11737. Output::Print(_u(">>\n"));
  11738. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11739. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11740. break;
  11741. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  11742. case knopRs2:
  11743. Indent(indentAmt);
  11744. Output::Print(_u(">>>\n"));
  11745. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11746. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11747. break;
  11748. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  11749. case knopNew:
  11750. Indent(indentAmt);
  11751. Output::Print(_u("new\n"));
  11752. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11753. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11754. break;
  11755. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  11756. case knopIndex:
  11757. Indent(indentAmt);
  11758. Output::Print(_u("[]\n"));
  11759. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11760. PrintPnodeListWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11761. break;
  11762. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  11763. case knopQmark:
  11764. Indent(indentAmt);
  11765. Output::Print(_u("?:\n"));
  11766. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode1, indentAmt + INDENT_SIZE);
  11767. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode2, indentAmt + INDENT_SIZE);
  11768. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode3, indentAmt + INDENT_SIZE);
  11769. break;
  11770. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  11771. case knopAsgAdd:
  11772. Indent(indentAmt);
  11773. Output::Print(_u("+=\n"));
  11774. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11775. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11776. break;
  11777. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  11778. case knopAsgSub:
  11779. Indent(indentAmt);
  11780. Output::Print(_u("-=\n"));
  11781. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11782. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11783. break;
  11784. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  11785. case knopAsgMul:
  11786. Indent(indentAmt);
  11787. Output::Print(_u("*=\n"));
  11788. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11789. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11790. break;
  11791. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  11792. case knopAsgExpo:
  11793. Indent(indentAmt);
  11794. Output::Print(_u("**=\n"));
  11795. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11796. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11797. break;
  11798. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  11799. case knopAsgDiv:
  11800. Indent(indentAmt);
  11801. Output::Print(_u("/=\n"));
  11802. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11803. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11804. break;
  11805. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  11806. case knopAsgMod:
  11807. Indent(indentAmt);
  11808. Output::Print(_u("%=\n"));
  11809. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11810. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11811. break;
  11812. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  11813. case knopAsgAnd:
  11814. Indent(indentAmt);
  11815. Output::Print(_u("&=\n"));
  11816. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11817. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11818. break;
  11819. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  11820. case knopAsgXor:
  11821. Indent(indentAmt);
  11822. Output::Print(_u("^=\n"));
  11823. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11824. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11825. break;
  11826. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  11827. case knopAsgOr:
  11828. Indent(indentAmt);
  11829. Output::Print(_u("|=\n"));
  11830. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11831. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11832. break;
  11833. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  11834. case knopAsgLsh:
  11835. Indent(indentAmt);
  11836. Output::Print(_u("<<=\n"));
  11837. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11838. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11839. break;
  11840. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  11841. case knopAsgRsh:
  11842. Indent(indentAmt);
  11843. Output::Print(_u(">>=\n"));
  11844. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11845. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11846. break;
  11847. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  11848. case knopAsgRs2:
  11849. Indent(indentAmt);
  11850. Output::Print(_u(">>>=\n"));
  11851. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11852. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11853. break;
  11854. case knopComputedName:
  11855. Indent(indentAmt);
  11856. Output::Print(_u("ComputedProperty\n"));
  11857. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11858. break;
  11859. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  11860. case knopMember:
  11861. case knopMemberShort:
  11862. case knopObjectPatternMember:
  11863. Indent(indentAmt);
  11864. Output::Print(_u(":\n"));
  11865. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11866. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11867. break;
  11868. // General nodes.
  11869. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  11870. case knopList:
  11871. Indent(indentAmt);
  11872. Output::Print(_u("List\n"));
  11873. PrintPnodeListWIndent(pnode, indentAmt + INDENT_SIZE);
  11874. break;
  11875. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  11876. case knopVarDecl:
  11877. Indent(indentAmt);
  11878. Output::Print(_u("var %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11879. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11880. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11881. break;
  11882. case knopConstDecl:
  11883. Indent(indentAmt);
  11884. Output::Print(_u("const %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11885. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11886. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11887. break;
  11888. case knopLetDecl:
  11889. Indent(indentAmt);
  11890. Output::Print(_u("let %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11891. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11892. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11893. break;
  11894. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  11895. case knopFncDecl:
  11896. Indent(indentAmt);
  11897. if (pnode->AsParseNodeFnc()->pid != NULL)
  11898. {
  11899. Output::Print(_u("fn decl %d nested %d name %s (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(),
  11900. pnode->AsParseNodeFnc()->pid->Psz(), pnode->ichMin, pnode->ichLim);
  11901. }
  11902. else
  11903. {
  11904. Output::Print(_u("fn decl %d nested %d anonymous (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(), pnode->ichMin, pnode->ichLim);
  11905. }
  11906. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11907. PrintFormalsWIndent(pnode->AsParseNodeFnc()->pnodeParams, indentAmt + INDENT_SIZE);
  11908. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeRest, indentAmt + INDENT_SIZE);
  11909. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  11910. if (pnode->AsParseNodeFnc()->pnodeBody == nullptr)
  11911. {
  11912. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11913. Indent(indentAmt + INDENT_SIZE);
  11914. Output::Print(_u("<parse deferred body>\n"));
  11915. }
  11916. break;
  11917. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  11918. case knopProg:
  11919. Indent(indentAmt);
  11920. Output::Print(_u("program\n"));
  11921. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11922. PrintPnodeListWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  11923. break;
  11924. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  11925. case knopEndCode:
  11926. Indent(indentAmt);
  11927. Output::Print(_u("<endcode>\n"));
  11928. break;
  11929. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  11930. case knopDebugger:
  11931. Indent(indentAmt);
  11932. Output::Print(_u("<debugger>\n"));
  11933. break;
  11934. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  11935. case knopFor:
  11936. Indent(indentAmt);
  11937. Output::Print(_u("for\n"));
  11938. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11939. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeInit, indentAmt + INDENT_SIZE);
  11940. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeCond, indentAmt + INDENT_SIZE);
  11941. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeIncr, indentAmt + INDENT_SIZE);
  11942. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeBody, indentAmt + INDENT_SIZE);
  11943. break;
  11944. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  11945. case knopIf:
  11946. Indent(indentAmt);
  11947. Output::Print(_u("if\n"));
  11948. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeCond, indentAmt + INDENT_SIZE);
  11949. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeTrue, indentAmt + INDENT_SIZE);
  11950. if (pnode->AsParseNodeIf()->pnodeFalse != NULL)
  11951. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeFalse, indentAmt + INDENT_SIZE);
  11952. break;
  11953. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  11954. case knopWhile:
  11955. Indent(indentAmt);
  11956. Output::Print(_u("while\n"));
  11957. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  11958. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  11959. break;
  11960. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  11961. case knopDoWhile:
  11962. Indent(indentAmt);
  11963. Output::Print(_u("do\n"));
  11964. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  11965. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  11966. break;
  11967. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  11968. case knopForIn:
  11969. Indent(indentAmt);
  11970. Output::Print(_u("forIn\n"));
  11971. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11972. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  11973. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  11974. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  11975. break;
  11976. case knopForOf:
  11977. Indent(indentAmt);
  11978. Output::Print(_u("forOf\n"));
  11979. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11980. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  11981. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  11982. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  11983. break;
  11984. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  11985. case knopReturn:
  11986. Indent(indentAmt);
  11987. Output::Print(_u("return\n"));
  11988. if (pnode->AsParseNodeReturn()->pnodeExpr != NULL)
  11989. PrintPnodeWIndent(pnode->AsParseNodeReturn()->pnodeExpr, indentAmt + INDENT_SIZE);
  11990. break;
  11991. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  11992. case knopBlock:
  11993. Indent(indentAmt);
  11994. Output::Print(_u("block "));
  11995. if (pnode->grfpn & fpnSyntheticNode)
  11996. Output::Print(_u("synthetic "));
  11997. PrintBlockType(pnode->AsParseNodeBlock()->blockType);
  11998. Output::Print(_u("(%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  11999. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12000. if (pnode->AsParseNodeBlock()->pnodeStmt != NULL)
  12001. PrintPnodeWIndent(pnode->AsParseNodeBlock()->pnodeStmt, indentAmt + INDENT_SIZE);
  12002. break;
  12003. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  12004. case knopWith:
  12005. Indent(indentAmt);
  12006. Output::Print(_u("with (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12007. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12008. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeObj, indentAmt + INDENT_SIZE);
  12009. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeBody, indentAmt + INDENT_SIZE);
  12010. break;
  12011. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  12012. case knopBreak:
  12013. Indent(indentAmt);
  12014. Output::Print(_u("break\n"));
  12015. // TODO: some representation of target
  12016. break;
  12017. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  12018. case knopContinue:
  12019. Indent(indentAmt);
  12020. Output::Print(_u("continue\n"));
  12021. // TODO: some representation of target
  12022. break;
  12023. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  12024. case knopSwitch:
  12025. Indent(indentAmt);
  12026. Output::Print(_u("switch\n"));
  12027. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12028. for (ParseNodeCase *pnodeT = pnode->AsParseNodeSwitch()->pnodeCases; NULL != pnodeT; pnodeT = pnodeT->pnodeNext) {
  12029. PrintPnodeWIndent(pnodeT, indentAmt + 2);
  12030. }
  12031. break;
  12032. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  12033. case knopCase:
  12034. Indent(indentAmt);
  12035. Output::Print(_u("case\n"));
  12036. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeExpr, indentAmt + INDENT_SIZE);
  12037. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeBody, indentAmt + INDENT_SIZE);
  12038. break;
  12039. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  12040. case knopTryFinally:
  12041. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeTry, indentAmt);
  12042. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeFinally, indentAmt);
  12043. break;
  12044. case knopFinally:
  12045. Indent(indentAmt);
  12046. Output::Print(_u("finally\n"));
  12047. PrintPnodeWIndent(pnode->AsParseNodeFinally()->pnodeBody, indentAmt + INDENT_SIZE);
  12048. break;
  12049. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  12050. case knopCatch:
  12051. Indent(indentAmt);
  12052. Output::Print(_u("catch (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12053. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12054. PrintPnodeWIndent(pnode->AsParseNodeCatch()->GetParam(), indentAmt + INDENT_SIZE);
  12055. // if (pnode->AsParseNodeCatch()->pnodeGuard!=NULL)
  12056. // PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeGuard,indentAmt+INDENT_SIZE);
  12057. PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeBody, indentAmt + INDENT_SIZE);
  12058. break;
  12059. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  12060. case knopTryCatch:
  12061. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeTry, indentAmt);
  12062. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeCatch, indentAmt);
  12063. break;
  12064. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  12065. case knopTry:
  12066. Indent(indentAmt);
  12067. Output::Print(_u("try\n"));
  12068. PrintPnodeWIndent(pnode->AsParseNodeTry()->pnodeBody, indentAmt + INDENT_SIZE);
  12069. break;
  12070. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  12071. case knopThrow:
  12072. Indent(indentAmt);
  12073. Output::Print(_u("throw\n"));
  12074. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12075. break;
  12076. //PTNODE(knopClassDecl, "classDecl", None , Class, fnopLeaf)
  12077. case knopClassDecl:
  12078. Indent(indentAmt);
  12079. Output::Print(_u("class %s"), pnode->AsParseNodeClass()->pnodeName->pid->Psz());
  12080. if (pnode->AsParseNodeClass()->pnodeExtends != nullptr)
  12081. {
  12082. Output::Print(_u(" extends "));
  12083. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeExtends, 0);
  12084. }
  12085. else {
  12086. Output::Print(_u("\n"));
  12087. }
  12088. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeConstructor, indentAmt + INDENT_SIZE);
  12089. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeMembers, indentAmt + INDENT_SIZE);
  12090. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeStaticMembers, indentAmt + INDENT_SIZE);
  12091. break;
  12092. case knopStrTemplate:
  12093. Indent(indentAmt);
  12094. Output::Print(_u("string template\n"));
  12095. PrintPnodeListWIndent(pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);
  12096. break;
  12097. case knopYieldStar:
  12098. Indent(indentAmt);
  12099. Output::Print(_u("yield*\n"));
  12100. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12101. break;
  12102. case knopYield:
  12103. case knopYieldLeaf:
  12104. Indent(indentAmt);
  12105. Output::Print(_u("yield\n"));
  12106. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12107. break;
  12108. case knopAwait:
  12109. Indent(indentAmt);
  12110. Output::Print(_u("await\n"));
  12111. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12112. break;
  12113. case knopExportDefault:
  12114. Indent(indentAmt);
  12115. Output::Print(_u("export default\n"));
  12116. PrintPnodeListWIndent(pnode->AsParseNodeExportDefault()->pnodeExpr, indentAmt + INDENT_SIZE);
  12117. break;
  12118. default:
  12119. Output::Print(_u("unhandled pnode op %d\n"), pnode->nop);
  12120. break;
  12121. }
  12122. }
  12123. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt) {
  12124. if (pnode != NULL) {
  12125. while (pnode->nop == knopList) {
  12126. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt);
  12127. pnode = pnode->AsParseNodeBin()->pnode2;
  12128. }
  12129. PrintPnodeWIndent(pnode, indentAmt);
  12130. }
  12131. }
  12132. void PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)
  12133. {
  12134. for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())
  12135. {
  12136. PrintPnodeWIndent(pnode->nop == knopParamPattern ? pnode->AsParseNodeParamPattern()->pnode1 : pnode, indentAmt);
  12137. }
  12138. }
  12139. void PrintPnode(ParseNode *pnode) {
  12140. PrintPnodeWIndent(pnode, 0);
  12141. }
  12142. void ParseNode::Dump()
  12143. {
  12144. switch (nop)
  12145. {
  12146. case knopFncDecl:
  12147. case knopProg:
  12148. LPCOLESTR name = Js::Constants::AnonymousFunction;
  12149. if (this->AsParseNodeFnc()->pnodeName)
  12150. {
  12151. Assert(this->AsParseNodeFnc()->pnodeName->nop == knopVarDecl);
  12152. name = this->AsParseNodeFnc()->pnodeName->pid->Psz();
  12153. }
  12154. Output::Print(_u("%s (%d) [%d, %d]:\n"), name, this->AsParseNodeFnc()->functionId, this->AsParseNodeFnc()->lineNumber, this->AsParseNodeFnc()->columnNumber);
  12155. Output::Print(_u("hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasOnlyThis:%s \n"),
  12156. IsTrueOrFalse(this->AsParseNodeFnc()->HasHeapArguments()),
  12157. IsTrueOrFalse(this->AsParseNodeFnc()->CallsEval()),
  12158. IsTrueOrFalse(this->AsParseNodeFnc()->ChildCallsEval()),
  12159. IsTrueOrFalse(this->AsParseNodeFnc()->HasReferenceableBuiltInArguments()),
  12160. IsTrueOrFalse(this->AsParseNodeFnc()->GetArgumentsObjectEscapes()),
  12161. IsTrueOrFalse(this->AsParseNodeFnc()->HasWithStmt()),
  12162. IsTrueOrFalse(this->AsParseNodeFnc()->HasOnlyThisStmts()));
  12163. if (this->AsParseNodeFnc()->funcInfo)
  12164. {
  12165. this->AsParseNodeFnc()->funcInfo->Dump();
  12166. }
  12167. break;
  12168. }
  12169. }
  12170. void DumpCapturedNames(ParseNodeFnc* pnodeFnc, IdentPtrSet* capturedNames, ArenaAllocator* alloc)
  12171. {
  12172. auto sortedNames = JsUtil::List<IdentPtr, ArenaAllocator>::New(alloc);
  12173. capturedNames->Map([=](const IdentPtr& pid) -> void {
  12174. sortedNames->Add(pid);
  12175. });
  12176. sortedNames->Sort([](void* context, const void* left, const void* right) -> int {
  12177. const IdentPtr leftIdentPtr = *(const IdentPtr*)(left);
  12178. const IdentPtr rightIdentPtr = *(const IdentPtr*)(right);
  12179. return ::wcscmp(leftIdentPtr->Psz(), rightIdentPtr->Psz());
  12180. }, nullptr);
  12181. sortedNames->Map([=](int index, const IdentPtr pid) -> void {
  12182. OUTPUT_TRACE_DEBUGONLY(Js::CreateParserStatePhase, _u(" Function %u captured name \"%s\"\n"), pnodeFnc->functionId, pid->Psz());
  12183. });
  12184. }
  12185. #endif
  12186. void Parser::AddNestedCapturedNames(ParseNodeFnc* pnodeChildFnc)
  12187. {
  12188. if (m_currentNodeFunc && this->IsCreatingStateCache() && pnodeChildFnc->HasAnyCapturedNames())
  12189. {
  12190. IdentPtrSet* parentCapturedNames = GetCurrentFunctionNode()->EnsureCapturedNames(&m_nodeAllocator);
  12191. IdentPtrSet* childCaptureNames = pnodeChildFnc->GetCapturedNames();
  12192. auto iter = childCaptureNames->GetIterator();
  12193. while (iter.IsValid())
  12194. {
  12195. parentCapturedNames->AddNew(iter.CurrentValue());
  12196. iter.MoveNext();
  12197. }
  12198. }
  12199. }
  12200. void Parser::ProcessCapturedNames(ParseNodeFnc* pnodeFnc)
  12201. {
  12202. if (this->IsCreatingStateCache() && pnodeFnc->HasAnyCapturedNames())
  12203. {
  12204. IdentPtrSet* capturedNames = pnodeFnc->GetCapturedNames();
  12205. auto iter = capturedNames->GetIteratorWithRemovalSupport();
  12206. while (iter.IsValid())
  12207. {
  12208. const IdentPtr& pid = iter.CurrentValueReference();
  12209. PidRefStack* ref = pid->GetTopRef();
  12210. // If the pid has no refs left in our function's scope after binding, we didn't capture it.
  12211. if (!ref || ref->GetFuncScopeId() < pnodeFnc->functionId)
  12212. {
  12213. iter.RemoveCurrent();
  12214. }
  12215. iter.MoveNext();
  12216. }
  12217. #if DBG_DUMP
  12218. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::CreateParserStatePhase))
  12219. {
  12220. DumpCapturedNames(pnodeFnc, capturedNames, &this->m_nodeAllocator);
  12221. fflush(stdout);
  12222. }
  12223. #endif
  12224. }
  12225. }
  12226. void Parser::ReleaseTemporaryGuestArena()
  12227. {
  12228. // In case of modules the Parser lives longer than the temporary Guest Arena. We may have already released the arena explicitly.
  12229. if (!m_tempGuestArenaReleased)
  12230. {
  12231. // The regex patterns list has references to the temporary Guest Arena. Reset it first.
  12232. m_registeredRegexPatterns.Reset();
  12233. if (this->m_scriptContext != nullptr)
  12234. {
  12235. this->m_scriptContext->ReleaseTemporaryGuestAllocator(m_tempGuestArena);
  12236. }
  12237. m_tempGuestArenaReleased = true;
  12238. }
  12239. }
  12240. bool Parser::IsCreatingStateCache()
  12241. {
  12242. return (((this->m_grfscr & fscrCreateParserState) == fscrCreateParserState)
  12243. && this->m_functionBody == nullptr
  12244. && CONFIG_FLAG(ParserStateCache));
  12245. }
  12246. DeferredFunctionStub * Parser::BuildDeferredStubTree(ParseNodeFnc *pnodeFnc, Recycler *recycler)
  12247. {
  12248. Assert(CONFIG_FLAG(ParserStateCache));
  12249. uint nestedCount = pnodeFnc->nestedCount;
  12250. if (nestedCount == 0)
  12251. {
  12252. return nullptr;
  12253. }
  12254. if (pnodeFnc->deferredStub)
  12255. {
  12256. return pnodeFnc->deferredStub;
  12257. }
  12258. DeferredFunctionStub* deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);
  12259. uint i = 0;
  12260. ParseNodeBlock* pnodeBlock = pnodeFnc->pnodeBodyScope;
  12261. ParseNodePtr pnodeChild = nullptr;
  12262. if (pnodeFnc->nop == knopProg)
  12263. {
  12264. Assert(pnodeFnc->pnodeBodyScope == nullptr
  12265. && pnodeFnc->pnodeScopes != nullptr
  12266. && pnodeFnc->pnodeScopes->blockType == PnodeBlockType::Global);
  12267. pnodeBlock = pnodeFnc->pnodeScopes;
  12268. pnodeChild = pnodeFnc->pnodeScopes->pnodeScopes;
  12269. }
  12270. else
  12271. {
  12272. Assert(pnodeBlock != nullptr
  12273. && (pnodeBlock->blockType == PnodeBlockType::Function
  12274. || pnodeBlock->blockType == PnodeBlockType::Parameter));
  12275. pnodeChild = pnodeBlock->pnodeScopes;
  12276. }
  12277. while (pnodeChild != nullptr)
  12278. {
  12279. if (pnodeChild->nop != knopFncDecl)
  12280. {
  12281. // We only expect to find a function body block in a parameter scope block.
  12282. Assert(pnodeChild->nop == knopBlock
  12283. && (pnodeBlock->blockType == PnodeBlockType::Parameter
  12284. || pnodeChild->AsParseNodeBlock()->blockType == PnodeBlockType::Function));
  12285. pnodeChild = pnodeChild->AsParseNodeBlock()->pnodeNext;
  12286. continue;
  12287. }
  12288. ParseNodeFnc* pnodeFncChild = pnodeChild->AsParseNodeFnc();
  12289. AnalysisAssertOrFailFast(i < nestedCount);
  12290. if (pnodeFncChild->pnodeBody != nullptr)
  12291. {
  12292. // Anomalous case of a non-deferred function nested within a deferred one.
  12293. // Work around by discarding the stub tree.
  12294. return nullptr;
  12295. }
  12296. if (pnodeFncChild->IsGeneratedDefault())
  12297. {
  12298. ++i;
  12299. pnodeChild = pnodeFncChild->pnodeNext;
  12300. continue;
  12301. }
  12302. deferredStubs[i].fncFlags = pnodeFncChild->fncFlags;
  12303. deferredStubs[i].nestedCount = pnodeFncChild->nestedCount;
  12304. deferredStubs[i].restorePoint = *pnodeFncChild->pRestorePoint;
  12305. deferredStubs[i].deferredStubs = BuildDeferredStubTree(pnodeFncChild, recycler);
  12306. deferredStubs[i].ichMin = pnodeChild->ichMin;
  12307. // Save the set of captured names onto the deferred stub.
  12308. // Since this set is allocated in the Parser arena, we'll have to convert these
  12309. // into indices in a string table which will survive when the parser goes away.
  12310. deferredStubs[i].capturedNamePointers = pnodeFncChild->GetCapturedNames();
  12311. ++i;
  12312. pnodeChild = pnodeFncChild->pnodeNext;
  12313. }
  12314. pnodeFnc->deferredStub = deferredStubs;
  12315. return deferredStubs;
  12316. }