Parse.cpp 482 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "ParserPch.h"
  6. #include "FormalsUtil.h"
  7. #include "../Runtime/Language/SourceDynamicProfileManager.h"
  8. #include "ByteCode/ByteCodeSerializer.h"
  9. #if DBG_DUMP
  10. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt);
  11. #endif
  12. const char* const nopNames[knopLim] = {
  13. #define PTNODE(nop,sn,pc,nk,grfnop,json) sn,
  14. #include "ptlist.h"
  15. };
  16. void printNop(int nop) {
  17. Output::Print(_u("%S\n"), nopNames[nop]);
  18. }
  19. const uint ParseNode::mpnopgrfnop[knopLim] =
  20. {
  21. #define PTNODE(nop,sn,pc,nk,grfnop,json) grfnop,
  22. #include "ptlist.h"
  23. };
  24. bool Parser::IsES6DestructuringEnabled() const
  25. {
  26. return m_scriptContext->GetConfig()->IsES6DestructuringEnabled();
  27. }
  28. struct BlockInfoStack
  29. {
  30. StmtNest pstmt;
  31. ParseNodeBlock *pnodeBlock;
  32. ParseNodePtr *m_ppnodeLex; // lexical variable list tail
  33. BlockInfoStack *pBlockInfoOuter; // containing block's BlockInfoStack
  34. BlockInfoStack *pBlockInfoFunction; // nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)
  35. };
  36. #if DEBUG
  37. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)
  38. #else
  39. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)
  40. #endif
  41. : m_nodeAllocator(_u("Parser"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),
  42. m_cactIdentToNodeLookup(0),
  43. m_grfscr(fscrNil),
  44. m_length(0),
  45. m_originalLength(0),
  46. m_nextFunctionId(nullptr),
  47. m_sourceContextInfo(nullptr),
  48. #if ENABLE_BACKGROUND_PARSING
  49. m_isInBackground(isBackground),
  50. m_hasParallelJob(false),
  51. m_doingFastScan(false),
  52. #endif
  53. m_nextBlockId(0),
  54. m_tempGuestArenaReleased(false),
  55. m_tempGuestArena(scriptContext->GetTemporaryGuestAllocator(_u("ParserRegex")), scriptContext->GetRecycler()),
  56. // use the GuestArena directly for keeping the RegexPattern* alive during byte code generation
  57. m_registeredRegexPatterns(m_tempGuestArena->GetAllocator()),
  58. m_scriptContext(scriptContext),
  59. m_token(), // should initialize to 0/nullptrs
  60. m_scan(this, &m_token, scriptContext),
  61. m_currentNodeNonLambdaFunc(nullptr),
  62. m_currentNodeNonLambdaDeferredFunc(nullptr),
  63. m_currentNodeFunc(nullptr),
  64. m_currentNodeDeferredFunc(nullptr),
  65. m_currentNodeProg(nullptr),
  66. m_currDeferredStub(nullptr),
  67. m_currDeferredStubCount(0),
  68. m_pCurrentAstSize(nullptr),
  69. m_ppnodeScope(nullptr),
  70. m_ppnodeExprScope(nullptr),
  71. m_ppnodeVar(nullptr),
  72. m_inDeferredNestedFunc(false),
  73. m_reparsingLambdaParams(false),
  74. m_disallowImportExportStmt(false),
  75. m_isInParsingArgList(false),
  76. m_hasDestructuringPattern(false),
  77. m_hasDeferredShorthandInitError(false),
  78. m_deferCommaError(false),
  79. m_pnestedCount(nullptr),
  80. wellKnownPropertyPids(), // should initialize to nullptrs
  81. m_sourceLim(0),
  82. m_functionBody(nullptr),
  83. m_parseType(ParseType_Upfront),
  84. m_arrayDepth(0),
  85. m_funcInArrayDepth(0),
  86. m_funcInArray(0),
  87. m_scopeCountNoAst(0),
  88. m_funcParenExprDepth(0),
  89. m_deferEllipsisError(false),
  90. m_deferEllipsisErrorLoc(), // calls default initializer
  91. m_deferCommaErrorLoc(),
  92. m_tryCatchOrFinallyDepth(0),
  93. m_pstmtCur(nullptr),
  94. m_currentBlockInfo(nullptr),
  95. m_currentScope(nullptr),
  96. currBackgroundParseItem(nullptr),
  97. backgroundParseItems(nullptr),
  98. fastScannedRegExpNodes(nullptr),
  99. m_currentDynamicBlock(nullptr),
  100. m_UsesArgumentsAtGlobal(false),
  101. m_fUseStrictMode(strictMode),
  102. m_InAsmMode(false),
  103. m_deferAsmJs(true),
  104. m_fExpectExternalSource(FALSE),
  105. m_deferringAST(FALSE),
  106. m_stoppedDeferredParse(FALSE)
  107. {
  108. AssertMsg(size == sizeof(Parser), "verify conditionals affecting the size of Parser agree");
  109. Assert(scriptContext != nullptr);
  110. // init PID members
  111. InitPids();
  112. }
  113. Parser::~Parser(void)
  114. {
  115. this->ReleaseTemporaryGuestArena();
  116. #if ENABLE_BACKGROUND_PARSING
  117. if (this->m_hasParallelJob)
  118. {
  119. // Let the background threads know that they can decommit their arena pages.
  120. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  121. Assert(bgp);
  122. if (bgp->Processor()->ProcessesInBackground())
  123. {
  124. JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());
  125. bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {
  126. threadData->canDecommit = true;
  127. return false;
  128. });
  129. Assert(result);
  130. }
  131. }
  132. #endif
  133. }
  134. void Parser::OutOfMemory()
  135. {
  136. throw ParseExceptionObject(ERRnoMemory);
  137. }
  138. void Parser::Error(HRESULT hr)
  139. {
  140. throw ParseExceptionObject(hr);
  141. }
  142. void Parser::Error(HRESULT hr, ParseNodePtr pnode)
  143. {
  144. if (pnode && pnode->ichLim)
  145. {
  146. Error(hr, pnode->ichMin, pnode->ichLim);
  147. }
  148. else
  149. {
  150. Error(hr);
  151. }
  152. }
  153. void Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim)
  154. {
  155. this->GetScanner()->SetErrorPosition(ichMin, ichLim);
  156. Error(hr);
  157. }
  158. void Parser::IdentifierExpectedError(const Token& token)
  159. {
  160. Assert(token.tk != tkID);
  161. HRESULT hr;
  162. if (token.IsReservedWord())
  163. {
  164. if (token.IsKeyword())
  165. {
  166. hr = ERRKeywordNotId;
  167. }
  168. else
  169. {
  170. Assert(token.IsFutureReservedWord(true));
  171. if (token.IsFutureReservedWord(false))
  172. {
  173. // Future reserved word in strict and non-strict modes
  174. hr = ERRFutureReservedWordNotId;
  175. }
  176. else
  177. {
  178. // Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not
  179. // in strict mode.
  180. Assert(IsStrictMode());
  181. hr = ERRFutureReservedWordInStrictModeNotId;
  182. }
  183. }
  184. }
  185. else
  186. {
  187. hr = ERRnoIdent;
  188. }
  189. Error(hr);
  190. }
  191. HRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())
  192. {
  193. Assert(pszSrc);
  194. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  195. HRESULT hr;
  196. SmartFPUControl smartFpuControl;
  197. BOOL fDeferSave = m_deferringAST;
  198. try
  199. {
  200. hr = NOERROR;
  201. m_length = encodedCharCount;
  202. m_originalLength = encodedCharCount;
  203. // make sure deferred parsing is turned off
  204. ULONG grfscr = fscrNil;
  205. // Give the scanner the source and get the first token
  206. this->GetScanner()->SetText(pszSrc, 0, encodedCharCount, 0, false, grfscr);
  207. this->GetScanner()->SetYieldIsKeywordRegion(isGenerator);
  208. this->GetScanner()->SetAwaitIsKeywordRegion(isAsync);
  209. this->GetScanner()->Scan();
  210. uint nestedCount = 0;
  211. m_pnestedCount = &nestedCount;
  212. ParseNodePtr pnodeScope = nullptr;
  213. m_ppnodeScope = &pnodeScope;
  214. m_ppnodeExprScope = nullptr;
  215. uint nextFunctionId = 0;
  216. m_nextFunctionId = &nextFunctionId;
  217. m_inDeferredNestedFunc = false;
  218. m_deferringAST = true;
  219. m_nextBlockId = 0;
  220. ParseNodeFnc *pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  221. pnodeFnc->SetIsGenerator(isGenerator);
  222. pnodeFnc->SetIsAsync(isAsync);
  223. m_ppnodeVar = &pnodeFnc->pnodeVars;
  224. m_currentNodeFunc = pnodeFnc;
  225. m_currentNodeDeferredFunc = NULL;
  226. m_sourceContextInfo = nullptr;
  227. AssertMsg(m_pstmtCur == NULL, "Statement stack should be empty when we start parse function body");
  228. ParseNodeBlock * block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);
  229. (this->*validateFunction)();
  230. FinishParseBlock(block);
  231. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  232. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  233. pnodeFnc->pnodeVars = nullptr;
  234. // there should be nothing after successful parsing for a given construct
  235. if (m_token.tk != tkEOF)
  236. Error(ERRsyntax);
  237. m_deferringAST = fDeferSave;
  238. }
  239. catch (ParseExceptionObject& e)
  240. {
  241. m_deferringAST = fDeferSave;
  242. hr = e.GetError();
  243. }
  244. if (nullptr != pse && FAILED(hr))
  245. {
  246. hr = pse->ProcessError(this->GetScanner(), hr, /* pnodeBase */ NULL);
  247. }
  248. return hr;
  249. }
  250. HRESULT Parser::ParseSourceInternal(
  251. __out ParseNodeProg ** parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,
  252. bool isUtf8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)
  253. {
  254. Assert(parseTree);
  255. Assert(pszSrc);
  256. if (this->IsBackgroundParser())
  257. {
  258. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  259. }
  260. else
  261. {
  262. PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);
  263. }
  264. #ifdef PROFILE_EXEC
  265. m_scriptContext->ProfileBegin(Js::ParsePhase);
  266. #endif
  267. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_START(m_scriptContext, 0));
  268. *parseTree = NULL;
  269. m_sourceLim = 0;
  270. m_grfscr = grfscr;
  271. m_sourceContextInfo = sourceContextInfo;
  272. ParseNodeProg * pnodeBase = NULL;
  273. HRESULT hr;
  274. SmartFPUControl smartFpuControl;
  275. try
  276. {
  277. if ((grfscr & fscrIsModuleCode) != 0)
  278. {
  279. // Module source flag should not be enabled unless module is enabled
  280. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  281. // Module code is always strict mode code.
  282. this->m_fUseStrictMode = TRUE;
  283. }
  284. // parse the source
  285. pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, isUtf8, grfscr, lineNumber, nextFunctionId, pse);
  286. Assert(pnodeBase);
  287. // Record the actual number of words parsed.
  288. m_sourceLim = pnodeBase->ichLim - offsetInChars;
  289. // TODO: The assert can be false positive in some scenarios and chuckj to fix it later
  290. // Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, isUtf8 ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);
  291. #if DBG_DUMP
  292. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))
  293. {
  294. PrintPnodeWIndent(pnodeBase, 4);
  295. fflush(stdout);
  296. }
  297. #endif
  298. *parseTree = pnodeBase;
  299. hr = NOERROR;
  300. }
  301. catch (ParseExceptionObject& e)
  302. {
  303. hr = e.GetError();
  304. }
  305. catch (Js::AsmJsParseException&)
  306. {
  307. hr = JSERR_AsmJsCompileError;
  308. }
  309. if (FAILED(hr))
  310. {
  311. hr = pse->ProcessError(this->GetScanner(), hr, pnodeBase);
  312. }
  313. #if ENABLE_BACKGROUND_PARSING
  314. if (this->m_hasParallelJob)
  315. {
  316. ///// Wait here for remaining jobs to finish. Then look for errors, do final const bindings.
  317. // pleath TODO: If there are remaining jobs, let the main thread help finish them.
  318. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  319. Assert(bgp);
  320. CompileScriptException se;
  321. this->WaitForBackgroundJobs(bgp, &se);
  322. BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();
  323. if (failedItem)
  324. {
  325. CompileScriptException *bgPse = failedItem->GetPSE();
  326. Assert(bgPse);
  327. *pse = *bgPse;
  328. hr = failedItem->GetHR();
  329. bgp->SetFailedBackgroundParseItem(nullptr);
  330. }
  331. if (this->fastScannedRegExpNodes != nullptr)
  332. {
  333. this->FinishBackgroundRegExpNodes();
  334. }
  335. for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())
  336. {
  337. Parser *parser = item->GetParser();
  338. parser->FinishBackgroundPidRefs(item, this != parser);
  339. }
  340. }
  341. #endif
  342. // done with the scanner
  343. this->GetScanner()->Clear();
  344. #ifdef PROFILE_EXEC
  345. m_scriptContext->ProfileEnd(Js::ParsePhase);
  346. #endif
  347. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));
  348. return hr;
  349. }
  350. #if ENABLE_BACKGROUND_PARSING
  351. void Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)
  352. {
  353. // The scan of the script is done, but there may be unfinished background jobs in the queue.
  354. // Enlist the main thread to help with those.
  355. BackgroundParseItem *item;
  356. if (!*bgp->GetPendingBackgroundItemsPtr())
  357. {
  358. // We're done.
  359. return;
  360. }
  361. // Save parser state, since we'll need to restore it in order to bind references correctly later.
  362. this->m_isInBackground = true;
  363. this->SetCurrBackgroundParseItem(nullptr);
  364. uint blockIdSave = this->m_nextBlockId;
  365. uint functionIdSave = *this->m_nextFunctionId;
  366. StmtNest *pstmtSave = this->m_pstmtCur;
  367. if (!bgp->Processor()->ProcessesInBackground())
  368. {
  369. // No background thread. Just walk the jobs with no locking and process them.
  370. for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())
  371. {
  372. bgp->Processor()->RemoveJob(item);
  373. bool succeeded = bgp->Process(item, this, pse);
  374. bgp->JobProcessed(item, succeeded);
  375. }
  376. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  377. }
  378. else
  379. {
  380. // Background threads. We need to have the critical section in order to:
  381. // - Check for unprocessed jobs;
  382. // - Remove jobs from the processor queue;
  383. // - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).
  384. CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();
  385. pcs->Enter();
  386. for (;;)
  387. {
  388. // Grab a job (in lock)
  389. item = bgp->GetNextUnprocessedItem();
  390. if (item == nullptr)
  391. {
  392. break;
  393. }
  394. bgp->Processor()->RemoveJob(item);
  395. pcs->Leave();
  396. // Process job (if there is one) (outside lock)
  397. bool succeeded = bgp->Process(item, this, pse);
  398. pcs->Enter();
  399. bgp->JobProcessed(item, succeeded);
  400. }
  401. pcs->Leave();
  402. // Wait for the background threads to finish jobs they're already processing (if any).
  403. // TODO: Replace with a proper semaphore.
  404. while (*bgp->GetPendingBackgroundItemsPtr());
  405. }
  406. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  407. // Restore parser state.
  408. this->m_pstmtCur = pstmtSave;
  409. this->m_isInBackground = false;
  410. this->m_nextBlockId = blockIdSave;
  411. *this->m_nextFunctionId = functionIdSave;
  412. }
  413. void Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)
  414. {
  415. for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)
  416. {
  417. if (isOtherParser)
  418. {
  419. this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());
  420. }
  421. else
  422. {
  423. this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());
  424. }
  425. }
  426. }
  427. void Parser::FinishBackgroundRegExpNodes()
  428. {
  429. // We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,
  430. // and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.
  431. // We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the
  432. // background nodes.
  433. // There may be UI thread nodes for which there are no background thread equivalents, because the UI thread
  434. // has to assume that the background thread won't defer anything.
  435. // Note that because these lists (and the list of background jobs) are SList's built by prepending, they are
  436. // all in reverse lexical order.
  437. Assert(!this->IsBackgroundParser());
  438. Assert(this->fastScannedRegExpNodes);
  439. Assert(this->backgroundParseItems != nullptr);
  440. BackgroundParseItem *currBackgroundItem;
  441. #if DBG
  442. for (currBackgroundItem = this->backgroundParseItems;
  443. currBackgroundItem;
  444. currBackgroundItem = currBackgroundItem->GetNext())
  445. {
  446. if (currBackgroundItem->RegExpNodeList())
  447. {
  448. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  449. {
  450. Assert(pnode->AsParseNodeRegExp()->regexPattern == nullptr);
  451. }
  452. NEXT_DLIST_ENTRY;
  453. }
  454. }
  455. #endif
  456. // Hook up the patterns allocated on the main thread to the nodes created on the background thread.
  457. // Walk the list of foreground nodes, advancing through the work items and looking up each item.
  458. // Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground
  459. // node will have a matching background node. Doesn't matter for correctness.
  460. // (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's
  461. // list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how
  462. // to start the inner loop from a known internal node within the list if that turns out to be important.)
  463. currBackgroundItem = this->backgroundParseItems;
  464. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)
  465. {
  466. Assert(pnodeFgnd->nop == knopRegExp);
  467. Assert(pnodeFgnd->AsParseNodeRegExp()->regexPattern != nullptr);
  468. bool quit = false;
  469. while (!quit)
  470. {
  471. // Find the next work item with a RegEx in it.
  472. while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)
  473. {
  474. currBackgroundItem = currBackgroundItem->GetNext();
  475. }
  476. if (!currBackgroundItem)
  477. {
  478. break;
  479. }
  480. // Walk the RegExps in the work item.
  481. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())
  482. {
  483. Assert(pnodeBgnd->nop == knopRegExp);
  484. if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)
  485. {
  486. // Either we found a match, or the next background node is past the foreground node.
  487. // In any case, we can stop searching.
  488. if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)
  489. {
  490. Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);
  491. pnodeBgnd->AsParseNodeRegExp()->regexPattern = pnodeFgnd->AsParseNodeRegExp()->regexPattern;
  492. }
  493. quit = true;
  494. break;
  495. }
  496. }
  497. NEXT_DLIST_ENTRY;
  498. if (!quit)
  499. {
  500. // Need to advance to the next work item.
  501. currBackgroundItem = currBackgroundItem->GetNext();
  502. }
  503. }
  504. }
  505. NEXT_DLIST_ENTRY;
  506. #if DBG
  507. for (currBackgroundItem = this->backgroundParseItems;
  508. currBackgroundItem;
  509. currBackgroundItem = currBackgroundItem->GetNext())
  510. {
  511. if (currBackgroundItem->RegExpNodeList())
  512. {
  513. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  514. {
  515. Assert(pnode->AsParseNodeRegExp()->regexPattern != nullptr);
  516. }
  517. NEXT_DLIST_ENTRY;
  518. }
  519. }
  520. #endif
  521. }
  522. #endif
  523. LabelId* Parser::CreateLabelId(IdentPtr pid)
  524. {
  525. LabelId* pLabelId;
  526. pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));
  527. if (NULL == pLabelId)
  528. Error(ERRnoMemory);
  529. pLabelId->pid = pid;
  530. pLabelId->next = NULL;
  531. return pLabelId;
  532. }
  533. /*****************************************************************************
  534. The following set of routines allocate parse tree nodes of various kinds.
  535. They catch an exception on out of memory.
  536. *****************************************************************************/
  537. void
  538. Parser::AddAstSize(int size)
  539. {
  540. Assert(!this->m_deferringAST);
  541. Assert(m_pCurrentAstSize != NULL);
  542. *m_pCurrentAstSize += size;
  543. }
  544. void
  545. Parser::AddAstSizeAllowDefer(int size)
  546. {
  547. if (!this->m_deferringAST)
  548. {
  549. AddAstSize(size);
  550. }
  551. }
  552. // StaticCreate
  553. ParseNodeVar * Parser::StaticCreateTempNode(ParseNode* initExpr, ArenaAllocator * alloc)
  554. {
  555. ParseNodeVar * pnode = Anew(alloc, ParseNodeVar, knopTemp, 0, 0, nullptr);
  556. pnode->pnodeInit = initExpr;
  557. return pnode;
  558. }
  559. ParseNodeUni * Parser::StaticCreateTempRef(ParseNode* tempNode, ArenaAllocator * alloc)
  560. {
  561. return Anew(alloc, ParseNodeUni, knopTempRef, 0, 0, tempNode);
  562. }
  563. // Create Node with limit
  564. template <OpCode nop>
  565. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  566. {
  567. Assert(!this->m_deferringAST);
  568. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  569. AddAstSize(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  570. return pnode;
  571. }
  572. template <OpCode nop>
  573. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateAllowDeferNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  574. {
  575. CompileAssert(OpCodeTrait<nop>::AllowDefer);
  576. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  577. AddAstSizeAllowDefer(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  578. return pnode;
  579. }
  580. #if DBG
  581. static const int g_mpnopcbNode[] =
  582. {
  583. #define PTNODE(nop,sn,pc,nk,ok,json) sizeof(ParseNode##nk),
  584. #include "ptlist.h"
  585. };
  586. void VerifyNodeSize(OpCode nop, int size)
  587. {
  588. Assert(nop >= 0 && nop < knopLim);
  589. __analysis_assume(nop < knopLim);
  590. Assert(g_mpnopcbNode[nop] == size);
  591. }
  592. #endif
  593. // Create ParseNodeUni
  594. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)
  595. {
  596. charcount_t ichMin;
  597. charcount_t ichLim;
  598. if (nullptr == pnode1)
  599. {
  600. // no ops
  601. ichMin = this->GetScanner()->IchMinTok();
  602. ichLim = this->GetScanner()->IchLimTok();
  603. }
  604. else
  605. {
  606. // 1 op
  607. ichMin = pnode1->ichMin;
  608. ichLim = pnode1->ichLim;
  609. this->CheckArguments(pnode1);
  610. }
  611. return CreateUniNode(nop, pnode1, ichMin, ichLim);
  612. }
  613. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin, charcount_t ichLim)
  614. {
  615. Assert(!this->m_deferringAST);
  616. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeUni)));
  617. ParseNodeUni * pnode = Anew(&m_nodeAllocator, ParseNodeUni, nop, ichMin, ichLim, pnode1);
  618. AddAstSize(sizeof(ParseNodeUni));
  619. return pnode;
  620. }
  621. // Create ParseNodeBin
  622. ParseNodeBin * Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim)
  623. {
  624. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeBin)));
  625. return Anew(alloc, ParseNodeBin, nop, ichMin, ichLim, pnode1, pnode2);
  626. }
  627. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  628. {
  629. Assert(!this->m_deferringAST);
  630. charcount_t ichMin;
  631. charcount_t ichLim;
  632. if (nullptr == pnode1)
  633. {
  634. // no ops
  635. Assert(nullptr == pnode2);
  636. ichMin = this->GetScanner()->IchMinTok();
  637. ichLim = this->GetScanner()->IchLimTok();
  638. }
  639. else
  640. {
  641. if (nullptr == pnode2)
  642. {
  643. // 1 op
  644. ichMin = pnode1->ichMin;
  645. ichLim = pnode1->ichLim;
  646. }
  647. else
  648. {
  649. // 2 ops
  650. ichMin = pnode1->ichMin;
  651. ichLim = pnode2->ichLim;
  652. if (nop != knopDot && nop != knopIndex)
  653. {
  654. this->CheckArguments(pnode2);
  655. }
  656. }
  657. if (nop != knopDot && nop != knopIndex)
  658. {
  659. this->CheckArguments(pnode1);
  660. }
  661. }
  662. return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
  663. }
  664. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
  665. ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  666. {
  667. Assert(!this->m_deferringAST);
  668. ParseNodeBin * pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator, ichMin, ichLim);
  669. AddAstSize(sizeof(ParseNodeBin));
  670. return pnode;
  671. }
  672. // Create ParseNodeTri
  673. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  674. ParseNodePtr pnode2, ParseNodePtr pnode3)
  675. {
  676. charcount_t ichMin;
  677. charcount_t ichLim;
  678. if (nullptr == pnode1)
  679. {
  680. // no ops
  681. Assert(nullptr == pnode2);
  682. Assert(nullptr == pnode3);
  683. ichMin = this->GetScanner()->IchMinTok();
  684. ichLim = this->GetScanner()->IchLimTok();
  685. }
  686. else if (nullptr == pnode2)
  687. {
  688. // 1 op
  689. Assert(nullptr == pnode3);
  690. ichMin = pnode1->ichMin;
  691. ichLim = pnode1->ichLim;
  692. }
  693. else if (nullptr == pnode3)
  694. {
  695. // 2 op
  696. ichMin = pnode1->ichMin;
  697. ichLim = pnode2->ichLim;
  698. }
  699. else
  700. {
  701. // 3 ops
  702. ichMin = pnode1->ichMin;
  703. ichLim = pnode3->ichLim;
  704. }
  705. return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);
  706. }
  707. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  708. ParseNodePtr pnode2, ParseNodePtr pnode3,
  709. charcount_t ichMin, charcount_t ichLim)
  710. {
  711. Assert(!this->m_deferringAST);
  712. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeTri)));
  713. ParseNodeTri * pnode = Anew(&m_nodeAllocator, ParseNodeTri, nop, ichMin, ichLim);
  714. AddAstSize(sizeof(ParseNodeTri));
  715. pnode->pnode1 = pnode1;
  716. pnode->pnode2 = pnode2;
  717. pnode->pnode3 = pnode3;
  718. return pnode;
  719. }
  720. // Create ParseNodeBlock
  721. ParseNodeBlock *
  722. Parser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim, int blockId, PnodeBlockType blockType)
  723. {
  724. return Anew(alloc, ParseNodeBlock, ichMin, ichLim, blockId, blockType);
  725. }
  726. ParseNodeBlock * Parser::CreateBlockNode(PnodeBlockType blockType)
  727. {
  728. return CreateBlockNode(this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), blockType);
  729. }
  730. ParseNodeBlock * Parser::CreateBlockNode(charcount_t ichMin, charcount_t ichLim, PnodeBlockType blockType)
  731. {
  732. Assert(OpCodeTrait<knopBlock>::AllowDefer);
  733. ParseNodeBlock * pnode = StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);
  734. AddAstSizeAllowDefer(sizeof(ParseNodeBlock));
  735. return pnode;
  736. }
  737. // Create ParseNodeVar
  738. ParseNodeVar * Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  739. {
  740. Assert(nop == knopVarDecl || nop == knopLetDecl || nop == knopConstDecl);
  741. ParseNodeVar * pnode = Anew(&m_nodeAllocator, ParseNodeVar, nop, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  742. if (symbolType != STUnknown)
  743. {
  744. pnode->sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);
  745. }
  746. return pnode;
  747. }
  748. ParseNodeInt * Parser::CreateIntNode(int32 lw)
  749. {
  750. Assert(!this->m_deferringAST);
  751. ParseNodeInt * pnode = Anew(&m_nodeAllocator, ParseNodeInt, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), lw);
  752. AddAstSize(sizeof(ParseNodeInt));
  753. return pnode;
  754. }
  755. ParseNodeStr * Parser::CreateStrNode(IdentPtr pid)
  756. {
  757. Assert(!this->m_deferringAST);
  758. ParseNodeStr * pnode = Anew(&m_nodeAllocator, ParseNodeStr, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  759. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  760. AddAstSize(sizeof(ParseNodeStr));
  761. return pnode;
  762. }
  763. ParseNodeName * Parser::CreateNameNode(IdentPtr pid)
  764. {
  765. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  766. AddAstSizeAllowDefer(sizeof(ParseNodeName));
  767. return pnode;
  768. }
  769. ParseNodeName * Parser::CreateNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  770. {
  771. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, ichMin, ichLim, pid);
  772. pnode->SetSymRef(ref);
  773. AddAstSize(sizeof(ParseNodeName));
  774. return pnode;
  775. }
  776. ParseNodeSpecialName * Parser::CreateSpecialNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  777. {
  778. Assert(!this->m_deferringAST);
  779. ParseNodeSpecialName * pnode = Anew(&m_nodeAllocator, ParseNodeSpecialName, ichMin, ichLim, pid);
  780. pnode->SetSymRef(ref);
  781. if (pid == wellKnownPropertyPids._this)
  782. {
  783. pnode->isThis = true;
  784. }
  785. else if (pid == wellKnownPropertyPids._super || pid == wellKnownPropertyPids._superConstructor)
  786. {
  787. pnode->isSuper = true;
  788. }
  789. AddAstSize(sizeof(ParseNodeSpecialName));
  790. return pnode;
  791. }
  792. ParseNodeSuperReference * Parser::CreateSuperReferenceNode(OpCode nop, ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  793. {
  794. Assert(!this->m_deferringAST);
  795. Assert(pnode1 && pnode1->isSuper);
  796. Assert(pnode2 != nullptr);
  797. Assert(nop == knopDot || nop == knopIndex);
  798. ParseNodeSuperReference * pnode = Anew(&m_nodeAllocator, ParseNodeSuperReference, nop, pnode1->ichMin, pnode2->ichLim, pnode1, pnode2);
  799. AddAstSize(sizeof(ParseNodeSuperReference));
  800. return pnode;
  801. }
  802. ParseNodeProg * Parser::CreateProgNode(bool isModuleSource, ULONG lineNumber)
  803. {
  804. ParseNodeProg * pnodeProg;
  805. if (isModuleSource)
  806. {
  807. pnodeProg = CreateNodeForOpT<knopModule>();
  808. // knopModule is not actually handled anywhere since we would need to handle it everywhere we could
  809. // have knopProg and it would be treated exactly the same except for import/export statements.
  810. // We are only using it as a way to get the correct size for PnModule.
  811. // Consider: Should we add a flag to PnProg which is false but set to true in PnModule?
  812. // If we do, it can't be a virtual method since the parse nodes are all in a union.
  813. pnodeProg->nop = knopProg;
  814. }
  815. else
  816. {
  817. pnodeProg = CreateNodeForOpT<knopProg>();
  818. }
  819. pnodeProg->cbMin = this->GetScanner()->IecpMinTok();
  820. pnodeProg->lineNumber = lineNumber;
  821. pnodeProg->homeObjLocation = Js::Constants::NoRegister;
  822. pnodeProg->superRestrictionState = SuperRestrictionState::Disallowed;
  823. return pnodeProg;
  824. }
  825. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  826. {
  827. charcount_t ichMin;
  828. charcount_t ichLim;
  829. if (nullptr == pnode1)
  830. {
  831. Assert(nullptr == pnode2);
  832. ichMin = this->GetScanner()->IchMinTok();
  833. ichLim = this->GetScanner()->IchLimTok();
  834. }
  835. else
  836. {
  837. ichMin = pnode1->ichMin;
  838. ichLim = pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim;
  839. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  840. {
  841. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  842. }
  843. }
  844. return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);
  845. }
  846. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  847. {
  848. Assert(!this->m_deferringAST);
  849. // Classes, derived from ParseNodeCall, can be created here as well,
  850. // as long as their size matches kcbPnCall (that is, they don't add
  851. // any data members of their own).
  852. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeCall)));
  853. ParseNodeCall* pnode = Anew(&m_nodeAllocator, ParseNodeCall, nop, ichMin, ichLim, pnode1, pnode2);
  854. AddAstSize(sizeof(ParseNodeCall));
  855. return pnode;
  856. }
  857. ParseNodeSuperCall * Parser::CreateSuperCallNode(ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  858. {
  859. Assert(!this->m_deferringAST);
  860. Assert(pnode1 && pnode1->isSuper);
  861. ParseNodeSuperCall* pnode = Anew(&m_nodeAllocator, ParseNodeSuperCall, knopCall, pnode1->ichMin, pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim, pnode1, pnode2);
  862. AddAstSize(sizeof(ParseNodeSuperCall));
  863. return pnode;
  864. }
  865. ParseNodeParamPattern * Parser::CreateParamPatternNode(ParseNode * pnode1)
  866. {
  867. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(pnode1->ichMin, pnode1->ichLim);
  868. paramPatternNode->pnode1 = pnode1;
  869. paramPatternNode->pnodeNext = nullptr;
  870. paramPatternNode->location = Js::Constants::NoRegister;
  871. return paramPatternNode;
  872. }
  873. ParseNodeParamPattern * Parser::CreateDummyParamPatternNode(charcount_t ichMin)
  874. {
  875. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(ichMin);
  876. paramPatternNode->pnode1 = nullptr;
  877. paramPatternNode->pnodeNext = nullptr;
  878. paramPatternNode->location = Js::Constants::NoRegister;
  879. return paramPatternNode;
  880. }
  881. Symbol* Parser::AddDeclForPid(ParseNodeVar * pnodeVar, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  882. {
  883. Assert(pnodeVar->IsVarLetOrConst());
  884. PidRefStack *refForUse = nullptr, *refForDecl = nullptr;
  885. BlockInfoStack *blockInfo;
  886. bool fBlockScope = false;
  887. if (pnodeVar->nop != knopVarDecl || symbolType == STFunction)
  888. {
  889. Assert(m_pstmtCur);
  890. if (m_pstmtCur->GetNop() != knopBlock)
  891. {
  892. // Let/const declared in a bare statement context.
  893. Error(ERRDeclOutOfStmt);
  894. }
  895. if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->GetNop() == knopSwitch)
  896. {
  897. // Let/const declared inside a switch block (requiring conservative use-before-decl check).
  898. pnodeVar->isSwitchStmtDecl = true;
  899. }
  900. fBlockScope = pnodeVar->nop != knopVarDecl ||
  901. (
  902. !GetCurrentBlockInfo()->pnodeBlock->scope ||
  903. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock
  904. );
  905. }
  906. if (fBlockScope)
  907. {
  908. blockInfo = GetCurrentBlockInfo();
  909. }
  910. else
  911. {
  912. blockInfo = GetCurrentFunctionBlockInfo();
  913. }
  914. refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->blockId, GetCurrentFunctionNode()->functionId);
  915. if (refForDecl == nullptr)
  916. {
  917. Error(ERRnoMemory);
  918. }
  919. if (refForDecl->funcId != GetCurrentFunctionNode()->functionId)
  920. {
  921. // Fix up the function id, which is incorrect if we're reparsing lambda parameters
  922. Assert(this->m_reparsingLambdaParams);
  923. refForDecl->funcId = GetCurrentFunctionNode()->functionId;
  924. }
  925. if (blockInfo == GetCurrentBlockInfo())
  926. {
  927. refForUse = refForDecl;
  928. }
  929. else
  930. {
  931. refForUse = this->PushPidRef(pid);
  932. }
  933. pnodeVar->symRef = refForUse->GetSymRef();
  934. Symbol *sym = refForDecl->GetSym();
  935. if (sym != nullptr)
  936. {
  937. // Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.
  938. switch (pnodeVar->nop)
  939. {
  940. case knopLetDecl:
  941. case knopConstDecl:
  942. if (!sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar && !sym->IsArguments())
  943. {
  944. // If the built-in arguments is shadowed then don't throw
  945. Assert(errorOnRedecl);
  946. // Redeclaration error.
  947. Error(ERRRedeclaration);
  948. }
  949. else
  950. {
  951. // (New) let/const hides the (old) var
  952. sym->SetSymbolType(symbolType);
  953. sym->SetDecl(pnodeVar);
  954. }
  955. break;
  956. case knopVarDecl:
  957. if (m_currentScope->GetScopeType() == ScopeType_Parameter && !sym->IsArguments())
  958. {
  959. // If this is a parameter list, mark the scope to indicate that it has duplicate definition unless it is shadowing the default arguments symbol.
  960. // 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.
  961. m_currentScope->SetHasDuplicateFormals();
  962. }
  963. if (sym->GetDecl() == nullptr)
  964. {
  965. sym->SetDecl(pnodeVar);
  966. break;
  967. }
  968. switch (sym->GetDecl()->nop)
  969. {
  970. case knopLetDecl:
  971. case knopConstDecl:
  972. // Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.
  973. if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))
  974. {
  975. Error(ERRRedeclaration);
  976. }
  977. // If !errorOnRedecl, (old) let/const hides the (new) var, so do nothing.
  978. break;
  979. case knopVarDecl:
  980. // Legal redeclaration. Who wins?
  981. if (errorOnRedecl || sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsArguments())
  982. {
  983. if (symbolType == STFormal ||
  984. (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||
  985. sym->GetSymbolType() == STVariable)
  986. {
  987. // New decl wins.
  988. sym->SetSymbolType(symbolType);
  989. sym->SetDecl(pnodeVar);
  990. }
  991. }
  992. break;
  993. }
  994. break;
  995. }
  996. }
  997. else
  998. {
  999. Scope *scope = blockInfo->pnodeBlock->scope;
  1000. if (scope == nullptr)
  1001. {
  1002. Assert(blockInfo->pnodeBlock->blockType == PnodeBlockType::Regular);
  1003. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);
  1004. if (this->IsCurBlockInLoop())
  1005. {
  1006. scope->SetIsBlockInLoop();
  1007. }
  1008. blockInfo->pnodeBlock->scope = scope;
  1009. PushScope(scope);
  1010. }
  1011. ParseNodeFnc * pnodeFnc = GetCurrentFunctionNode();
  1012. if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)
  1013. {
  1014. Assert(fBlockScope);
  1015. Assert(scope->GetEnclosingScope() == m_currentNodeProg->scope);
  1016. // Check for same-named decl in Global scope.
  1017. CheckRedeclarationErrorForBlockId(pid, 0);
  1018. }
  1019. else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&
  1020. !(m_functionBody && m_functionBody->GetScopeInfo()))
  1021. {
  1022. // Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary
  1023. // if we're compiling a deferred nested function and the global scope was restored from cached info,
  1024. // because in that case we don't need a GlobalEvalScope.
  1025. Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);
  1026. CheckRedeclarationErrorForBlockId(pid, 1);
  1027. }
  1028. else if (!pnodeFnc->IsBodyAndParamScopeMerged()
  1029. && scope->GetScopeType() == ScopeType_FunctionBody
  1030. && (pnodeVar->nop == knopLetDecl || pnodeVar->nop == knopConstDecl))
  1031. {
  1032. // In case of split scope function when we add a new let or const declaration to the body
  1033. // we have to check whether the param scope already has the same symbol defined.
  1034. CheckRedeclarationErrorForBlockId(pid, pnodeFnc->pnodeScopes->blockId);
  1035. }
  1036. if (!sym)
  1037. {
  1038. const char16 *name = reinterpret_cast<const char16*>(pid->Psz());
  1039. int nameLength = pid->Cch();
  1040. SymbolName const symName(name, nameLength);
  1041. Assert(!scope->FindLocalSymbol(symName));
  1042. sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeVar, symbolType);
  1043. scope->AddNewSymbol(sym);
  1044. sym->SetPid(pid);
  1045. }
  1046. refForDecl->SetSym(sym);
  1047. }
  1048. return sym;
  1049. }
  1050. void Parser::CheckRedeclarationErrorForBlockId(IdentPtr pid, int blockId)
  1051. {
  1052. // If the ref stack entry for the blockId contains a sym then throw redeclaration error
  1053. PidRefStack *pidRefOld = pid->GetPidRefForScopeId(blockId);
  1054. if (pidRefOld && pidRefOld->GetSym() && !pidRefOld->GetSym()->IsArguments())
  1055. {
  1056. Error(ERRRedeclaration);
  1057. }
  1058. }
  1059. bool Parser::IsCurBlockInLoop() const
  1060. {
  1061. for (StmtNest *stmt = this->m_pstmtCur; stmt != nullptr; stmt = stmt->pstmtOuter)
  1062. {
  1063. OpCode nop = stmt->GetNop();
  1064. if (ParseNode::Grfnop(nop) & fnopContinue)
  1065. {
  1066. return true;
  1067. }
  1068. if (nop == knopFncDecl)
  1069. {
  1070. return false;
  1071. }
  1072. }
  1073. return false;
  1074. }
  1075. void Parser::RestorePidRefForSym(Symbol *sym)
  1076. {
  1077. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());
  1078. Assert(pid);
  1079. sym->SetPid(pid);
  1080. PidRefStack *ref = this->PushPidRef(pid);
  1081. ref->SetSym(sym);
  1082. }
  1083. void Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)
  1084. {
  1085. if (IsStrictMode())
  1086. {
  1087. // in strict mode, variable named 'eval' cannot be created
  1088. if (pid == wellKnownPropertyPids.eval)
  1089. {
  1090. Error(ERREvalUsage);
  1091. }
  1092. else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)
  1093. {
  1094. Error(ERRArgsUsage);
  1095. }
  1096. }
  1097. }
  1098. // CreateVarDecl needs m_ppnodeVar to be pointing to the right function.
  1099. // Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.
  1100. // This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.
  1101. // This prevents accidentally adding var declarations to the last parsed function.
  1102. ParseNodeVar * Parser::AddVarDeclNode(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1103. {
  1104. AnalysisAssert(pnodeFnc);
  1105. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  1106. m_ppnodeVar = &pnodeFnc->pnodeVars;
  1107. while (*m_ppnodeVar != nullptr)
  1108. {
  1109. m_ppnodeVar = &(*m_ppnodeVar)->AsParseNodeVar()->pnodeNext;
  1110. }
  1111. ParseNodeVar * pnode = CreateVarDeclNode(pid, STUnknown, false, 0, /* checkReDecl = */ false);
  1112. m_ppnodeVar = ppnodeVarSave;
  1113. return pnode;
  1114. }
  1115. ParseNodeVar * Parser::CreateModuleImportDeclNode(IdentPtr localName)
  1116. {
  1117. ParseNodeVar * declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);
  1118. Symbol* sym = declNode->sym;
  1119. sym->SetIsModuleExportStorage(true);
  1120. sym->SetIsModuleImport(true);
  1121. return declNode;
  1122. }
  1123. ParseNodeVar * Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)
  1124. {
  1125. ParseNodeVar * pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);
  1126. // Append the variable to the end of the current variable list.
  1127. Assert(m_ppnodeVar);
  1128. pnode->pnodeNext = *m_ppnodeVar;
  1129. *m_ppnodeVar = pnode;
  1130. if (nullptr != pid)
  1131. {
  1132. // this is not a temp - make sure temps go after this node
  1133. Assert(pid);
  1134. m_ppnodeVar = &pnode->pnodeNext;
  1135. CheckPidIsValid(pid, autoArgumentsObject);
  1136. }
  1137. return pnode;
  1138. }
  1139. ParseNodeVar * Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)
  1140. {
  1141. Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);
  1142. ParseNodeVar * pnode = CreateDeclNode(nodeType, pid, STVariable, true);
  1143. if (nullptr != pid)
  1144. {
  1145. Assert(pid);
  1146. AddVarDeclToBlock(pnode);
  1147. CheckPidIsValid(pid);
  1148. }
  1149. return pnode;
  1150. }
  1151. void Parser::AddVarDeclToBlock(ParseNodeVar *pnode)
  1152. {
  1153. Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);
  1154. // Maintain a combined list of let and const declarations to keep
  1155. // track of declaration order.
  1156. Assert(m_currentBlockInfo->m_ppnodeLex);
  1157. *m_currentBlockInfo->m_ppnodeLex = pnode;
  1158. m_currentBlockInfo->m_ppnodeLex = &pnode->pnodeNext;
  1159. pnode->pnodeNext = nullptr;
  1160. }
  1161. void Parser::SetCurrentStatement(StmtNest *stmt)
  1162. {
  1163. m_pstmtCur = stmt;
  1164. }
  1165. template<bool buildAST>
  1166. ParseNodeBlock * Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)
  1167. {
  1168. Scope *scope = nullptr;
  1169. // Block scopes are not created lazily in the case where we're repopulating a persisted scope.
  1170. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);
  1171. PushScope(scope);
  1172. return StartParseBlockHelper<buildAST>(blockType, scope, nullptr);
  1173. }
  1174. template<bool buildAST>
  1175. ParseNodeBlock * Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, LabelId* pLabelId)
  1176. {
  1177. Scope *scope = nullptr;
  1178. // Block scopes are created lazily when we discover block-scoped content.
  1179. if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)
  1180. {
  1181. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);
  1182. PushScope(scope);
  1183. }
  1184. return StartParseBlockHelper<buildAST>(blockType, scope, pLabelId);
  1185. }
  1186. template<bool buildAST>
  1187. ParseNodeBlock * Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, LabelId* pLabelId)
  1188. {
  1189. ParseNodeBlock * pnodeBlock = CreateBlockNode(blockType);
  1190. pnodeBlock->scope = scope;
  1191. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);
  1192. PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pLabelId);
  1193. return pnodeBlock;
  1194. }
  1195. void Parser::PushScope(Scope *scope)
  1196. {
  1197. Assert(scope);
  1198. scope->SetEnclosingScope(m_currentScope);
  1199. m_currentScope = scope;
  1200. }
  1201. void Parser::PopScope(Scope *scope)
  1202. {
  1203. Assert(scope == m_currentScope);
  1204. m_currentScope = scope->GetEnclosingScope();
  1205. scope->SetEnclosingScope(nullptr);
  1206. }
  1207. void Parser::PushFuncBlockScope(ParseNodeBlock * pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)
  1208. {
  1209. // Maintain the scope tree.
  1210. pnodeBlock->pnodeScopes = nullptr;
  1211. pnodeBlock->pnodeNext = nullptr;
  1212. // Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).
  1213. // Save the current block's "next" pointer as the new endpoint of that list.
  1214. if (m_ppnodeExprScope)
  1215. {
  1216. *ppnodeScopeSave = m_ppnodeScope;
  1217. Assert(*m_ppnodeExprScope == nullptr);
  1218. *m_ppnodeExprScope = pnodeBlock;
  1219. *ppnodeExprScopeSave = &pnodeBlock->pnodeNext;
  1220. }
  1221. else
  1222. {
  1223. Assert(m_ppnodeScope);
  1224. Assert(*m_ppnodeScope == nullptr);
  1225. *m_ppnodeScope = pnodeBlock;
  1226. *ppnodeScopeSave = &pnodeBlock->pnodeNext;
  1227. *ppnodeExprScopeSave = m_ppnodeExprScope;
  1228. }
  1229. // Advance the global scope list pointer to the new block's child list.
  1230. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  1231. // Set m_ppnodeExprScope to NULL to make that list inactive.
  1232. m_ppnodeExprScope = nullptr;
  1233. }
  1234. void Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)
  1235. {
  1236. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  1237. m_ppnodeExprScope = ppnodeExprScopeSave;
  1238. Assert(m_ppnodeScope);
  1239. Assert(nullptr == *m_ppnodeScope);
  1240. m_ppnodeScope = ppnodeScopeSave;
  1241. }
  1242. template<bool buildAST>
  1243. ParseNodeBlock * Parser::ParseBlock(LabelId* pLabelId)
  1244. {
  1245. ParseNodeBlock * pnodeBlock = nullptr;
  1246. ParseNodePtr *ppnodeScopeSave = nullptr;
  1247. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  1248. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pLabelId);
  1249. BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1250. if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr
  1251. && outerBlockInfo->pnodeBlock->scope != nullptr
  1252. && outerBlockInfo->pnodeBlock->scope->GetScopeType() == ScopeType_CatchParamPattern)
  1253. {
  1254. // If we are parsing the catch block then destructured params can have let declarations. Let's add them to the new block.
  1255. for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1256. {
  1257. PidRefStack* ref = PushPidRef(pnode->AsParseNodeVar()->sym->GetPid());
  1258. ref->SetSym(pnode->AsParseNodeVar()->sym);
  1259. }
  1260. }
  1261. ChkCurTok(tkLCurly, ERRnoLcurly);
  1262. ParseNodePtr * ppnodeList = nullptr;
  1263. if (buildAST)
  1264. {
  1265. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  1266. ppnodeList = &pnodeBlock->pnodeStmt;
  1267. }
  1268. ParseStmtList<buildAST>(ppnodeList);
  1269. if (buildAST)
  1270. {
  1271. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  1272. }
  1273. FinishParseBlock(pnodeBlock);
  1274. ChkCurTok(tkRCurly, ERRnoRcurly);
  1275. return pnodeBlock;
  1276. }
  1277. bool Parser::IsSpecialName(IdentPtr pid)
  1278. {
  1279. return pid == wellKnownPropertyPids._this ||
  1280. pid == wellKnownPropertyPids._super ||
  1281. pid == wellKnownPropertyPids._superConstructor ||
  1282. pid == wellKnownPropertyPids._newTarget;
  1283. }
  1284. ParseNodeSpecialName * Parser::ReferenceSpecialName(IdentPtr pid, charcount_t ichMin, charcount_t ichLim, bool createNode)
  1285. {
  1286. PidRefStack* ref = this->PushPidRef(pid);
  1287. if (!createNode)
  1288. {
  1289. return nullptr;
  1290. }
  1291. return CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  1292. }
  1293. ParseNodeVar * Parser::CreateSpecialVarDeclIfNeeded(ParseNodeFnc * pnodeFnc, IdentPtr pid, bool forceCreate)
  1294. {
  1295. Assert(pid != nullptr);
  1296. PidRefStack* ref = pid->GetTopRef();
  1297. // If the function has a reference to pid or we set forceCreate, make a special var decl
  1298. if (forceCreate || (ref && ref->GetScopeId() >= m_currentBlockInfo->pnodeBlock->blockId))
  1299. {
  1300. return this->CreateSpecialVarDeclNode(pnodeFnc, pid);
  1301. }
  1302. return nullptr;
  1303. }
  1304. void Parser::CreateSpecialSymbolDeclarations(ParseNodeFnc * pnodeFnc)
  1305. {
  1306. // Lambda function cannot have any special bindings.
  1307. if (pnodeFnc->IsLambda())
  1308. {
  1309. return;
  1310. }
  1311. bool isTopLevelEventHandler = (this->m_grfscr & fscrImplicitThis) && !pnodeFnc->IsNested();
  1312. // Create a 'this' symbol for non-lambda functions with references to 'this', and all class constructors and top level event hanlders.
  1313. ParseNodePtr varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._this, pnodeFnc->IsClassConstructor() || isTopLevelEventHandler);
  1314. if (varDeclNode)
  1315. {
  1316. varDeclNode->AsParseNodeVar()->sym->SetIsThis(true);
  1317. if (pnodeFnc->IsDerivedClassConstructor())
  1318. {
  1319. varDeclNode->AsParseNodeVar()->sym->SetNeedDeclaration(true);
  1320. }
  1321. }
  1322. // Create a 'new.target' symbol for any ordinary function with a reference and all class constructors.
  1323. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._newTarget, pnodeFnc->IsClassConstructor());
  1324. if (varDeclNode)
  1325. {
  1326. varDeclNode->AsParseNodeVar()->sym->SetIsNewTarget(true);
  1327. }
  1328. // Create a 'super' (as a reference) symbol.
  1329. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._super);
  1330. if (varDeclNode)
  1331. {
  1332. varDeclNode->AsParseNodeVar()->sym->SetIsSuper(true);
  1333. }
  1334. // Create a 'super' (as the call target for super()) symbol only for derived class constructors.
  1335. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._superConstructor);
  1336. if (varDeclNode)
  1337. {
  1338. varDeclNode->AsParseNodeVar()->sym->SetIsSuperConstructor(true);
  1339. }
  1340. }
  1341. void Parser::FinishParseBlock(ParseNodeBlock *pnodeBlock, bool needScanRCurly)
  1342. {
  1343. Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);
  1344. if (needScanRCurly)
  1345. {
  1346. // Only update the ichLim if we were expecting an RCurly. If there is an
  1347. // expression body without a necessary RCurly, the correct ichLim will
  1348. // have been set already.
  1349. pnodeBlock->ichLim = this->GetScanner()->IchLimTok();
  1350. }
  1351. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  1352. PopStmt(&m_currentBlockInfo->pstmt);
  1353. PopBlockInfo();
  1354. Scope *scope = pnodeBlock->scope;
  1355. if (scope)
  1356. {
  1357. PopScope(scope);
  1358. }
  1359. }
  1360. void Parser::FinishParseFncExprScope(ParseNodeFnc * pnodeFnc, ParseNodeBlock * pnodeFncExprScope)
  1361. {
  1362. int fncExprScopeId = pnodeFncExprScope->blockId;
  1363. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  1364. if (pnodeName)
  1365. {
  1366. Assert(pnodeName->nop == knopVarDecl);
  1367. BindPidRefsInScope(pnodeName->AsParseNodeVar()->pid, pnodeName->AsParseNodeVar()->sym, fncExprScopeId, m_nextBlockId - 1);
  1368. }
  1369. FinishParseBlock(pnodeFncExprScope);
  1370. }
  1371. template <const bool backgroundPidRef>
  1372. void Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)
  1373. {
  1374. // We need to bind all assignments in order to emit assignment to 'const' error
  1375. int blockId = blockInfo->pnodeBlock->blockId;
  1376. Scope *scope = blockInfo->pnodeBlock->scope;
  1377. if (scope)
  1378. {
  1379. auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)
  1380. {
  1381. ParseNodePtr pnode = sym->GetDecl();
  1382. IdentPtr pid;
  1383. #if PROFILE_DICTIONARY
  1384. int depth = 0;
  1385. #endif
  1386. Assert(pnode);
  1387. switch (pnode->nop)
  1388. {
  1389. case knopVarDecl:
  1390. case knopLetDecl:
  1391. case knopConstDecl:
  1392. pid = pnode->AsParseNodeVar()->pid;
  1393. if (backgroundPidRef)
  1394. {
  1395. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1396. #if PROFILE_DICTIONARY
  1397. , depth
  1398. #endif
  1399. );
  1400. if (pid == nullptr)
  1401. {
  1402. break;
  1403. }
  1404. }
  1405. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1406. break;
  1407. case knopName:
  1408. pid = pnode->AsParseNodeName()->pid;
  1409. if (backgroundPidRef)
  1410. {
  1411. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1412. #if PROFILE_DICTIONARY
  1413. , depth
  1414. #endif
  1415. );
  1416. if (pid == nullptr)
  1417. {
  1418. break;
  1419. }
  1420. }
  1421. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1422. break;
  1423. default:
  1424. Assert(0);
  1425. break;
  1426. }
  1427. };
  1428. scope->ForEachSymbol(bindPidRefs);
  1429. }
  1430. }
  1431. void Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)
  1432. {
  1433. PidRefStack *ref, *nextRef, *lastRef = nullptr;
  1434. Js::LocalFunctionId funcId = GetCurrentFunctionNode()->functionId;
  1435. Assert(sym);
  1436. if (pid->GetIsModuleExport() && IsTopLevelModuleFunc())
  1437. {
  1438. sym->SetIsModuleExportStorage(true);
  1439. }
  1440. bool hasFuncAssignment = sym->GetHasFuncAssignment();
  1441. bool doesEscape = false;
  1442. for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)
  1443. {
  1444. // Fix up sym* on PID ref.
  1445. Assert(!ref->GetSym() || ref->GetSym() == sym);
  1446. nextRef = ref->prev;
  1447. Assert(ref->GetScopeId() >= 0);
  1448. if ((uint)ref->GetScopeId() > maxBlockId)
  1449. {
  1450. lastRef = ref;
  1451. continue;
  1452. }
  1453. ref->SetSym(sym);
  1454. this->RemovePrevPidRef(pid, lastRef);
  1455. if (ref->IsUsedInLdElem())
  1456. {
  1457. sym->SetIsUsedInLdElem(true);
  1458. }
  1459. if (ref->IsAssignment())
  1460. {
  1461. sym->PromoteAssignmentState();
  1462. if (sym->GetIsFormal())
  1463. {
  1464. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  1465. }
  1466. }
  1467. if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1468. {
  1469. Assert(ref->GetFuncScopeId() > funcId);
  1470. sym->SetHasNonLocalReference();
  1471. if (ref->IsDynamicBinding())
  1472. {
  1473. sym->SetNeedsScopeObject();
  1474. }
  1475. }
  1476. if (ref->IsFuncAssignment())
  1477. {
  1478. hasFuncAssignment = true;
  1479. }
  1480. if (ref->IsEscape())
  1481. {
  1482. doesEscape = true;
  1483. }
  1484. if (m_currentNodeFunc && doesEscape && hasFuncAssignment)
  1485. {
  1486. if (m_sourceContextInfo ?
  1487. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1488. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1489. {
  1490. m_currentNodeFunc->SetNestedFuncEscapes();
  1491. }
  1492. }
  1493. if (m_currentNodeFunc && m_currentNodeFunc->pnodeName && pid == m_currentNodeFunc->pnodeName->pid && !m_currentNodeFunc->IsDeclaration() && m_currentNodeFunc->IsBodyAndParamScopeMerged())
  1494. {
  1495. Scope* funcExprScope = m_currentNodeFunc->scope;
  1496. Assert(funcExprScope->GetScopeType() == ScopeType_FuncExpr);
  1497. ParseNodeBlock* bodyScope = m_currentNodeFunc->pnodeBodyScope;
  1498. Assert(bodyScope == nullptr || bodyScope->blockType == PnodeBlockType::Function);
  1499. if (bodyScope && ref->GetScopeId() < bodyScope->blockId && ref->GetScopeId() > blockId)
  1500. {
  1501. funcExprScope->SetIsObject();
  1502. }
  1503. }
  1504. if (ref->GetScopeId() == blockId)
  1505. {
  1506. break;
  1507. }
  1508. }
  1509. }
  1510. void Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)
  1511. {
  1512. if (m_currentNodeFunc == nullptr)
  1513. {
  1514. return;
  1515. }
  1516. if (pnode && pnode->nop == knopFncDecl)
  1517. {
  1518. this->SetNestedFuncEscapes();
  1519. }
  1520. else if (pToken->pid)
  1521. {
  1522. PidRefStack *pidRef = pToken->pid->GetTopRef();
  1523. if (pidRef->sym)
  1524. {
  1525. if (pidRef->sym->GetSymbolType() == STFunction)
  1526. {
  1527. this->SetNestedFuncEscapes();
  1528. }
  1529. }
  1530. else
  1531. {
  1532. pidRef->isEscape = true;
  1533. }
  1534. }
  1535. }
  1536. void Parser::SetNestedFuncEscapes() const
  1537. {
  1538. if (m_sourceContextInfo ?
  1539. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1540. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1541. {
  1542. m_currentNodeFunc->SetNestedFuncEscapes();
  1543. }
  1544. }
  1545. void Parser::PopStmt(StmtNest *pStmt)
  1546. {
  1547. Assert(pStmt == m_pstmtCur);
  1548. SetCurrentStatement(m_pstmtCur->pstmtOuter);
  1549. }
  1550. BlockInfoStack *Parser::PushBlockInfo(ParseNodeBlock * pnodeBlock)
  1551. {
  1552. BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));
  1553. Assert(nullptr != newBlockInfo);
  1554. newBlockInfo->pnodeBlock = pnodeBlock;
  1555. newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;
  1556. newBlockInfo->m_ppnodeLex = &pnodeBlock->pnodeLexVars;
  1557. if (pnodeBlock->blockType != PnodeBlockType::Regular)
  1558. {
  1559. newBlockInfo->pBlockInfoFunction = newBlockInfo;
  1560. }
  1561. else
  1562. {
  1563. Assert(m_currentBlockInfo);
  1564. newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;
  1565. }
  1566. m_currentBlockInfo = newBlockInfo;
  1567. return newBlockInfo;
  1568. }
  1569. void Parser::PopBlockInfo()
  1570. {
  1571. Assert(m_currentBlockInfo);
  1572. PopDynamicBlock();
  1573. m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1574. }
  1575. void Parser::PushDynamicBlock()
  1576. {
  1577. Assert(GetCurrentBlock());
  1578. int blockId = GetCurrentBlock()->blockId;
  1579. if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)
  1580. {
  1581. return;
  1582. }
  1583. BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));
  1584. if (nullptr == info)
  1585. {
  1586. Error(ERRnoMemory);
  1587. }
  1588. info->id = blockId;
  1589. info->prev = m_currentDynamicBlock;
  1590. m_currentDynamicBlock = info;
  1591. }
  1592. void Parser::PopDynamicBlock()
  1593. {
  1594. int blockId = GetCurrentDynamicBlockId();
  1595. if (GetCurrentBlock()->blockId != blockId || blockId == -1)
  1596. {
  1597. return;
  1598. }
  1599. Assert(m_currentDynamicBlock);
  1600. this->GetHashTbl()->VisitPids([&](IdentPtr pid) {
  1601. for (PidRefStack *ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = ref->prev)
  1602. {
  1603. ref->SetDynamicBinding();
  1604. }
  1605. });
  1606. m_currentDynamicBlock = m_currentDynamicBlock->prev;
  1607. }
  1608. int Parser::GetCurrentDynamicBlockId() const
  1609. {
  1610. return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;
  1611. }
  1612. ParseNodeFnc *Parser::GetCurrentFunctionNode()
  1613. {
  1614. if (m_currentNodeDeferredFunc != nullptr)
  1615. {
  1616. return m_currentNodeDeferredFunc;
  1617. }
  1618. else if (m_currentNodeFunc != nullptr)
  1619. {
  1620. return m_currentNodeFunc;
  1621. }
  1622. else
  1623. {
  1624. AssertMsg(GetFunctionBlock()->blockType == PnodeBlockType::Global,
  1625. "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'");
  1626. return m_currentNodeProg;
  1627. }
  1628. }
  1629. ParseNodeFnc *Parser::GetCurrentNonLambdaFunctionNode()
  1630. {
  1631. if (m_currentNodeNonLambdaDeferredFunc != nullptr)
  1632. {
  1633. return m_currentNodeNonLambdaDeferredFunc;
  1634. }
  1635. return m_currentNodeNonLambdaFunc;
  1636. }
  1637. void Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)
  1638. {
  1639. Assert(regexPattern);
  1640. // ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator
  1641. if (!m_registeredRegexPatterns.PrependNoThrow(m_tempGuestArena->GetAllocator(), regexPattern))
  1642. {
  1643. Parser::Error(ERRnoMemory);
  1644. }
  1645. }
  1646. void Parser::CaptureState(ParserState *state)
  1647. {
  1648. Assert(state != nullptr);
  1649. state->m_funcInArraySave = m_funcInArray;
  1650. state->m_funcInArrayDepthSave = m_funcInArrayDepth;
  1651. state->m_nestedCountSave = *m_pnestedCount;
  1652. state->m_ppnodeScopeSave = m_ppnodeScope;
  1653. state->m_ppnodeExprScopeSave = m_ppnodeExprScope;
  1654. state->m_pCurrentAstSizeSave = m_pCurrentAstSize;
  1655. state->m_nextBlockId = m_nextBlockId;
  1656. Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);
  1657. Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);
  1658. #if DEBUG
  1659. state->m_currentBlockInfo = m_currentBlockInfo;
  1660. #endif
  1661. }
  1662. void Parser::RestoreStateFrom(ParserState *state)
  1663. {
  1664. Assert(state != nullptr);
  1665. Assert(state->m_currentBlockInfo == m_currentBlockInfo);
  1666. m_funcInArray = state->m_funcInArraySave;
  1667. m_funcInArrayDepth = state->m_funcInArrayDepthSave;
  1668. *m_pnestedCount = state->m_nestedCountSave;
  1669. m_pCurrentAstSize = state->m_pCurrentAstSizeSave;
  1670. m_nextBlockId = state->m_nextBlockId;
  1671. if (state->m_ppnodeScopeSave != nullptr)
  1672. {
  1673. *state->m_ppnodeScopeSave = nullptr;
  1674. }
  1675. if (state->m_ppnodeExprScopeSave != nullptr)
  1676. {
  1677. *state->m_ppnodeExprScopeSave = nullptr;
  1678. }
  1679. m_ppnodeScope = state->m_ppnodeScopeSave;
  1680. m_ppnodeExprScope = state->m_ppnodeExprScopeSave;
  1681. }
  1682. void Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1683. ParseNode * pnodeAdd)
  1684. {
  1685. AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);
  1686. pnodeAdd->SetIsInList();
  1687. }
  1688. void Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1689. ParseNode * pnodeAdd)
  1690. {
  1691. Assert(!this->m_deferringAST);
  1692. if (nullptr == *pppnodeLast)
  1693. {
  1694. // should be an empty list
  1695. Assert(nullptr == *ppnodeList);
  1696. *ppnodeList = pnodeAdd;
  1697. *pppnodeLast = ppnodeList;
  1698. }
  1699. else
  1700. {
  1701. //
  1702. Assert(*ppnodeList);
  1703. Assert(**pppnodeLast);
  1704. ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);
  1705. **pppnodeLast = pnodeT;
  1706. *pppnodeLast = &pnodeT->AsParseNodeBin()->pnode2;
  1707. }
  1708. }
  1709. // Check reference to "arguments" that indicates the object may escape.
  1710. void Parser::CheckArguments(ParseNodePtr pnode)
  1711. {
  1712. if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))
  1713. {
  1714. m_currentNodeFunc->SetHasHeapArguments();
  1715. }
  1716. }
  1717. // Check use of "arguments" that requires instantiation of the object.
  1718. void Parser::CheckArgumentsUse(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1719. {
  1720. if (pid == wellKnownPropertyPids.arguments)
  1721. {
  1722. if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)
  1723. {
  1724. pnodeFnc->SetUsesArguments(TRUE);
  1725. }
  1726. else
  1727. {
  1728. m_UsesArgumentsAtGlobal = true;
  1729. }
  1730. }
  1731. }
  1732. void Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)
  1733. {
  1734. if (pid != nullptr)
  1735. {
  1736. // In strict mode, 'eval' / 'arguments' cannot be assigned to.
  1737. if (pid == wellKnownPropertyPids.eval)
  1738. {
  1739. Error(ERREvalUsage, pnode);
  1740. }
  1741. if (pid == wellKnownPropertyPids.arguments)
  1742. {
  1743. Error(ERRArgsUsage, pnode);
  1744. }
  1745. }
  1746. }
  1747. void Parser::ReduceDeferredScriptLength(size_t chars)
  1748. {
  1749. // If we're in deferred mode, subtract the given char count from the total length,
  1750. // and see if this puts us under the deferral threshold.
  1751. if (((m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse)) == (fscrCanDeferFncParse | fscrWillDeferFncParse)) &&
  1752. (
  1753. PHASE_OFF1(Js::DeferEventHandlersPhase) ||
  1754. (m_grfscr & fscrGlobalCode)
  1755. )
  1756. )
  1757. {
  1758. if (m_length > chars)
  1759. {
  1760. m_length -= chars;
  1761. }
  1762. else
  1763. {
  1764. m_length = 0;
  1765. }
  1766. if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))
  1767. {
  1768. // Stop deferring.
  1769. m_grfscr &= ~fscrWillDeferFncParse;
  1770. m_stoppedDeferredParse = TRUE;
  1771. }
  1772. }
  1773. }
  1774. void Parser::EnsureStackAvailable()
  1775. {
  1776. bool isInterrupt = false;
  1777. if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile, &isInterrupt))
  1778. {
  1779. Error(isInterrupt ? E_ABORT : VBSERR_OutOfStack);
  1780. }
  1781. }
  1782. void Parser::ThrowNewTargetSyntaxErrForGlobalScope()
  1783. {
  1784. // If we are parsing a previously deferred function, we can skip throwing the SyntaxError for `new.target` at global scope.
  1785. // If we are at global scope, we would have thrown a SyntaxError when we did the Upfront parse pass and we would not have
  1786. // deferred the function in order to come back now and reparse it.
  1787. if (m_parseType == ParseType_Deferred)
  1788. {
  1789. return;
  1790. }
  1791. if (GetCurrentNonLambdaFunctionNode() != nullptr)
  1792. {
  1793. return;
  1794. }
  1795. if ((this->m_grfscr & fscrEval) != 0)
  1796. {
  1797. Js::JavascriptFunction * caller = nullptr;
  1798. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  1799. {
  1800. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  1801. Assert(callerBody);
  1802. if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))
  1803. {
  1804. return;
  1805. }
  1806. }
  1807. }
  1808. Error(ERRInvalidNewTarget);
  1809. }
  1810. template<bool buildAST>
  1811. IdentPtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)
  1812. {
  1813. AssertMsg(metaParentKeyword == tkNEW, "Only supported for tkNEW parent keywords");
  1814. AssertMsg(this->m_token.tk == tkDot, "We must be currently sitting on the dot after the parent keyword");
  1815. this->GetScanner()->Scan();
  1816. if (this->m_token.tk == tkID && this->m_token.GetIdentifier(this->GetHashTbl()) == this->GetTargetPid())
  1817. {
  1818. ThrowNewTargetSyntaxErrForGlobalScope();
  1819. if (pfCanAssign)
  1820. {
  1821. *pfCanAssign = FALSE;
  1822. }
  1823. return wellKnownPropertyPids._newTarget;
  1824. }
  1825. else
  1826. {
  1827. Error(ERRsyntax);
  1828. }
  1829. }
  1830. template<bool buildAST>
  1831. void Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)
  1832. {
  1833. Assert(m_token.tk == tkLCurly);
  1834. Assert(importOrExportEntryList != nullptr);
  1835. this->GetScanner()->Scan();
  1836. while (m_token.tk != tkRCurly && m_token.tk != tkEOF)
  1837. {
  1838. tokens firstToken = m_token.tk;
  1839. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1840. {
  1841. Error(ERRsyntax);
  1842. }
  1843. IdentPtr identifierName = m_token.GetIdentifier(this->GetHashTbl());
  1844. IdentPtr identifierAs = identifierName;
  1845. this->GetScanner()->Scan();
  1846. if (m_token.tk == tkID)
  1847. {
  1848. // We have the pattern "IdentifierName as"
  1849. if (wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  1850. {
  1851. Error(ERRsyntax);
  1852. }
  1853. this->GetScanner()->Scan();
  1854. // If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.
  1855. if (!isExportClause)
  1856. {
  1857. ChkCurTokNoScan(tkID, ERRsyntax);
  1858. }
  1859. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1860. {
  1861. Error(ERRsyntax);
  1862. }
  1863. identifierAs = m_token.GetIdentifier(this->GetHashTbl());
  1864. // Scan to the next token.
  1865. this->GetScanner()->Scan();
  1866. }
  1867. else if (!isExportClause && firstToken != tkID)
  1868. {
  1869. // If we are parsing an import statement and this ImportSpecifier clause did not have
  1870. // 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.
  1871. Error(ERRsyntax);
  1872. }
  1873. if (m_token.tk == tkComma)
  1874. {
  1875. // Consume a trailing comma
  1876. this->GetScanner()->Scan();
  1877. }
  1878. if (buildAST)
  1879. {
  1880. // The name we will use 'as' this import/export is a binding identifier in import statements.
  1881. if (!isExportClause)
  1882. {
  1883. CreateModuleImportDeclNode(identifierAs);
  1884. AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);
  1885. }
  1886. else
  1887. {
  1888. identifierName->SetIsModuleExport();
  1889. AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr);
  1890. }
  1891. }
  1892. }
  1893. // Final token in a named import or export clause must be a '}'
  1894. ChkCurTokNoScan(tkRCurly, ERRsyntax);
  1895. }
  1896. IdentPtrList* Parser::GetRequestedModulesList()
  1897. {
  1898. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1899. }
  1900. ModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()
  1901. {
  1902. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  1903. }
  1904. ModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()
  1905. {
  1906. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  1907. }
  1908. ModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()
  1909. {
  1910. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  1911. }
  1912. ModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()
  1913. {
  1914. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  1915. }
  1916. IdentPtrList* Parser::EnsureRequestedModulesList()
  1917. {
  1918. if (m_currentNodeProg->AsParseNodeModule()->requestedModules == nullptr)
  1919. {
  1920. m_currentNodeProg->AsParseNodeModule()->requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);
  1921. }
  1922. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1923. }
  1924. ModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()
  1925. {
  1926. if (m_currentNodeProg->AsParseNodeModule()->importEntries == nullptr)
  1927. {
  1928. m_currentNodeProg->AsParseNodeModule()->importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1929. }
  1930. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  1931. }
  1932. ModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()
  1933. {
  1934. if (m_currentNodeProg->AsParseNodeModule()->localExportEntries == nullptr)
  1935. {
  1936. m_currentNodeProg->AsParseNodeModule()->localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1937. }
  1938. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  1939. }
  1940. ModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()
  1941. {
  1942. if (m_currentNodeProg->AsParseNodeModule()->indirectExportEntries == nullptr)
  1943. {
  1944. m_currentNodeProg->AsParseNodeModule()->indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1945. }
  1946. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  1947. }
  1948. ModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()
  1949. {
  1950. if (m_currentNodeProg->AsParseNodeModule()->starExportEntries == nullptr)
  1951. {
  1952. m_currentNodeProg->AsParseNodeModule()->starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1953. }
  1954. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  1955. }
  1956. void Parser::AddModuleSpecifier(IdentPtr moduleRequest)
  1957. {
  1958. IdentPtrList* requestedModulesList = EnsureRequestedModulesList();
  1959. if (!requestedModulesList->Has(moduleRequest))
  1960. {
  1961. requestedModulesList->Prepend(moduleRequest);
  1962. }
  1963. }
  1964. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)
  1965. {
  1966. if (importOrExportEntry->exportName != nullptr)
  1967. {
  1968. CheckForDuplicateExportEntry(importOrExportEntryList, importOrExportEntry->exportName);
  1969. }
  1970. importOrExportEntryList->Prepend(*importOrExportEntry);
  1971. return importOrExportEntry;
  1972. }
  1973. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest)
  1974. {
  1975. ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);
  1976. importOrExportEntry->importName = importName;
  1977. importOrExportEntry->localName = localName;
  1978. importOrExportEntry->exportName = exportName;
  1979. importOrExportEntry->moduleRequest = moduleRequest;
  1980. return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);
  1981. }
  1982. void Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)
  1983. {
  1984. AssertOrFailFast(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);
  1985. IdentPtr localName = varDeclNode->AsParseNodeVar()->pid;
  1986. varDeclNode->AsParseNodeVar()->sym->SetIsModuleExportStorage(true);
  1987. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  1988. }
  1989. void Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)
  1990. {
  1991. ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)
  1992. {
  1993. if (exportName == exportEntry.exportName)
  1994. {
  1995. return true;
  1996. }
  1997. return false;
  1998. });
  1999. if (findResult != nullptr)
  2000. {
  2001. Error(ERRsyntax);
  2002. }
  2003. }
  2004. template<bool buildAST>
  2005. void Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)
  2006. {
  2007. bool parsedNamespaceOrNamedImport = false;
  2008. switch (m_token.tk)
  2009. {
  2010. case tkID:
  2011. // This is the default binding identifier.
  2012. // If we already saw a comma in the import clause, this is a syntax error.
  2013. if (parsingAfterComma)
  2014. {
  2015. Error(ERRsyntax);
  2016. }
  2017. if (buildAST)
  2018. {
  2019. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2020. IdentPtr importName = wellKnownPropertyPids._default;
  2021. CreateModuleImportDeclNode(localName);
  2022. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2023. }
  2024. break;
  2025. case tkLCurly:
  2026. // This begins a list of named imports.
  2027. ParseNamedImportOrExportClause<buildAST>(importEntryList, false);
  2028. parsedNamespaceOrNamedImport = true;
  2029. break;
  2030. case tkStar:
  2031. // This begins a namespace import clause.
  2032. // "* as ImportedBinding"
  2033. // Token following * must be the identifier 'as'
  2034. this->GetScanner()->Scan();
  2035. if (m_token.tk != tkID || wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  2036. {
  2037. Error(ERRsyntax);
  2038. }
  2039. // Token following 'as' must be a binding identifier.
  2040. this->GetScanner()->Scan();
  2041. ChkCurTokNoScan(tkID, ERRsyntax);
  2042. if (buildAST)
  2043. {
  2044. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2045. IdentPtr importName = wellKnownPropertyPids._star;
  2046. CreateModuleImportDeclNode(localName);
  2047. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2048. }
  2049. parsedNamespaceOrNamedImport = true;
  2050. break;
  2051. default:
  2052. Error(ERRsyntax);
  2053. }
  2054. this->GetScanner()->Scan();
  2055. if (m_token.tk == tkComma)
  2056. {
  2057. // There cannot be more than one comma in a module import clause.
  2058. // There cannot be a namespace import or named imports list on the left of the comma in a module import clause.
  2059. if (parsingAfterComma || parsedNamespaceOrNamedImport)
  2060. {
  2061. Error(ERRsyntax);
  2062. }
  2063. this->GetScanner()->Scan();
  2064. ParseImportClause<buildAST>(importEntryList, true);
  2065. }
  2066. }
  2067. bool Parser::IsImportOrExportStatementValidHere()
  2068. {
  2069. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2070. // Import must be located in the top scope of the module body.
  2071. return curFunc->nop == knopFncDecl
  2072. && curFunc->IsModule()
  2073. && this->m_currentBlockInfo->pnodeBlock == curFunc->pnodeBodyScope
  2074. && (this->m_grfscr & fscrEvalCode) != fscrEvalCode
  2075. && this->m_tryCatchOrFinallyDepth == 0
  2076. && !this->m_disallowImportExportStmt;
  2077. }
  2078. bool Parser::IsTopLevelModuleFunc()
  2079. {
  2080. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2081. return curFunc->nop == knopFncDecl && curFunc->IsModule();
  2082. }
  2083. template<bool buildAST> ParseNodePtr Parser::ParseImportCall()
  2084. {
  2085. this->GetScanner()->Scan();
  2086. ParseNodePtr specifier = ParseExpr<buildAST>(koplCma, nullptr, /* fAllowIn */FALSE, /* fAllowEllipsis */FALSE);
  2087. if (m_token.tk != tkRParen)
  2088. {
  2089. Error(ERRnoRparen);
  2090. }
  2091. this->GetScanner()->Scan();
  2092. return buildAST ? CreateCallNode(knopCall, CreateNodeForOpT<knopImport>(), specifier) : nullptr;
  2093. }
  2094. template<bool buildAST>
  2095. ParseNodePtr Parser::ParseImport()
  2096. {
  2097. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2098. Assert(m_token.tk == tkIMPORT);
  2099. RestorePoint parsedImport;
  2100. this->GetScanner()->Capture(&parsedImport);
  2101. this->GetScanner()->Scan();
  2102. // import()
  2103. if (m_token.tk == tkLParen)
  2104. {
  2105. if (!m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2106. {
  2107. Error(ERRsyntax);
  2108. }
  2109. ParseNodePtr pnode = ParseImportCall<buildAST>();
  2110. BOOL fCanAssign;
  2111. IdentToken token;
  2112. return ParsePostfixOperators<buildAST>(pnode, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  2113. }
  2114. this->GetScanner()->SeekTo(parsedImport);
  2115. if (!IsImportOrExportStatementValidHere())
  2116. {
  2117. Error(ERRInvalidModuleImportOrExport);
  2118. }
  2119. // We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.
  2120. this->GetScanner()->Scan();
  2121. if (m_token.tk == tkStrCon)
  2122. {
  2123. // This import declaration has no import clause.
  2124. // "import ModuleSpecifier;"
  2125. if (buildAST)
  2126. {
  2127. AddModuleSpecifier(m_token.GetStr());
  2128. }
  2129. // Scan past the module identifier.
  2130. this->GetScanner()->Scan();
  2131. }
  2132. else
  2133. {
  2134. ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);
  2135. // Parse the import clause (default binding can only exist before the comma).
  2136. ParseImportClause<buildAST>(&importEntryList);
  2137. // Token following import clause must be the identifier 'from'
  2138. IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);
  2139. if (buildAST)
  2140. {
  2141. Assert(moduleSpecifier != nullptr);
  2142. AddModuleSpecifier(moduleSpecifier);
  2143. importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {
  2144. importEntry.moduleRequest = moduleSpecifier;
  2145. AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);
  2146. });
  2147. }
  2148. importEntryList.Clear();
  2149. }
  2150. // Import statement is actually a nop, we hoist all the imported bindings to the top of the module.
  2151. return nullptr;
  2152. }
  2153. template<bool buildAST>
  2154. IdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)
  2155. {
  2156. IdentPtr moduleSpecifier = nullptr;
  2157. if (m_token.tk == tkID && wellKnownPropertyPids.from == m_token.GetIdentifier(this->GetHashTbl()))
  2158. {
  2159. this->GetScanner()->Scan();
  2160. // Token following the 'from' token must be a string constant - the module specifier.
  2161. ChkCurTokNoScan(tkStrCon, ERRsyntax);
  2162. if (buildAST)
  2163. {
  2164. moduleSpecifier = m_token.GetStr();
  2165. }
  2166. this->GetScanner()->Scan();
  2167. }
  2168. else if (throwIfNotFound)
  2169. {
  2170. Error(ERRsyntax);
  2171. }
  2172. return moduleSpecifier;
  2173. }
  2174. template<bool buildAST>
  2175. ParseNodePtr Parser::ParseDefaultExportClause()
  2176. {
  2177. Assert(m_token.tk == tkDEFAULT);
  2178. this->GetScanner()->Scan();
  2179. ParseNodePtr pnode = nullptr;
  2180. ushort flags = fFncNoFlgs;
  2181. switch (m_token.tk)
  2182. {
  2183. case tkCLASS:
  2184. {
  2185. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2186. {
  2187. goto LDefault;
  2188. }
  2189. // Before we parse the class itself we need to know if the class has an identifier name.
  2190. // If it does, we'll treat this class as an ordinary class declaration which will bind
  2191. // it to that name. Otherwise the class should parse as a nameless class expression and
  2192. // bind only to the export binding.
  2193. BOOL classHasName = false;
  2194. RestorePoint parsedClass;
  2195. this->GetScanner()->Capture(&parsedClass);
  2196. this->GetScanner()->Scan();
  2197. if (m_token.tk == tkID)
  2198. {
  2199. classHasName = true;
  2200. }
  2201. this->GetScanner()->SeekTo(parsedClass);
  2202. ParseNodeClass * pnodeClass;
  2203. pnode = pnodeClass = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);
  2204. if (buildAST)
  2205. {
  2206. AnalysisAssert(pnode != nullptr);
  2207. Assert(pnode->nop == knopClassDecl);
  2208. pnodeClass->SetIsDefaultModuleExport(true);
  2209. }
  2210. break;
  2211. }
  2212. case tkID:
  2213. // If we parsed an async token, it could either modify the next token (if it is a
  2214. // function token) or it could be an identifier (let async = 0; export default async;).
  2215. // To handle both cases, when we parse an async token we need to keep the parser state
  2216. // and rewind if the next token is not function.
  2217. if (wellKnownPropertyPids.async == m_token.GetIdentifier(this->GetHashTbl()))
  2218. {
  2219. RestorePoint parsedAsync;
  2220. this->GetScanner()->Capture(&parsedAsync);
  2221. this->GetScanner()->Scan();
  2222. if (m_token.tk == tkFUNCTION)
  2223. {
  2224. // Token after async is function, consume the async token and continue to parse the
  2225. // function as an async function.
  2226. flags |= fFncAsync;
  2227. goto LFunction;
  2228. }
  2229. // Token after async is not function, no idea what the async token is supposed to mean
  2230. // so rewind and let the default case handle it.
  2231. this->GetScanner()->SeekTo(parsedAsync);
  2232. }
  2233. goto LDefault;
  2234. break;
  2235. case tkFUNCTION:
  2236. {
  2237. LFunction:
  2238. // We just parsed a function token but we need to figure out if the function
  2239. // has an identifier name or not before we call the helper.
  2240. RestorePoint parsedFunction;
  2241. this->GetScanner()->Capture(&parsedFunction);
  2242. this->GetScanner()->Scan();
  2243. if (m_token.tk == tkStar)
  2244. {
  2245. // If we saw 'function*' that indicates we are going to parse a generator,
  2246. // but doesn't tell us if the generator has an identifier or not.
  2247. // Skip the '*' token for now as it doesn't matter yet.
  2248. this->GetScanner()->Scan();
  2249. }
  2250. // We say that if the function has an identifier name, it is a 'normal' declaration
  2251. // and should create a binding to that identifier as well as one for our default export.
  2252. if (m_token.tk == tkID)
  2253. {
  2254. flags |= fFncDeclaration;
  2255. }
  2256. else
  2257. {
  2258. flags |= fFncNoName;
  2259. }
  2260. // Rewind back to the function token and let the helper handle the parsing.
  2261. this->GetScanner()->SeekTo(parsedFunction);
  2262. pnode = ParseFncDeclNoCheckScope<buildAST>(flags);
  2263. if (buildAST)
  2264. {
  2265. AnalysisAssert(pnode != nullptr);
  2266. Assert(pnode->nop == knopFncDecl);
  2267. pnode->AsParseNodeFnc()->SetIsDefaultModuleExport(true);
  2268. }
  2269. break;
  2270. }
  2271. default:
  2272. LDefault:
  2273. {
  2274. ParseNodePtr pnodeExpression = ParseExpr<buildAST>();
  2275. // Consider: Can we detect this syntax error earlier?
  2276. if (pnodeExpression && pnodeExpression->nop == knopComma)
  2277. {
  2278. Error(ERRsyntax);
  2279. }
  2280. if (buildAST)
  2281. {
  2282. AnalysisAssert(pnodeExpression != nullptr);
  2283. // Mark this node as the default module export. We need to make sure it is put into the correct
  2284. // module export slot when we emit the node.
  2285. ParseNodeExportDefault * pnodeExportDefault;
  2286. pnode = pnodeExportDefault = CreateNodeForOpT<knopExportDefault>();
  2287. pnode->AsParseNodeExportDefault()->pnodeExpr = pnodeExpression;
  2288. }
  2289. break;
  2290. }
  2291. }
  2292. IdentPtr exportName = wellKnownPropertyPids._default;
  2293. IdentPtr localName = wellKnownPropertyPids._starDefaultStar;
  2294. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, exportName, nullptr);
  2295. return pnode;
  2296. }
  2297. template<bool buildAST>
  2298. ParseNodePtr Parser::ParseExportDeclaration(bool *needTerminator)
  2299. {
  2300. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2301. Assert(m_token.tk == tkEXPORT);
  2302. if (!IsImportOrExportStatementValidHere())
  2303. {
  2304. Error(ERRInvalidModuleImportOrExport);
  2305. }
  2306. ParseNodePtr pnode = nullptr;
  2307. IdentPtr moduleIdentifier = nullptr;
  2308. tokens declarationType;
  2309. if (needTerminator != nullptr)
  2310. {
  2311. *needTerminator = false;
  2312. }
  2313. // We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.
  2314. this->GetScanner()->Scan();
  2315. switch (m_token.tk)
  2316. {
  2317. case tkStar:
  2318. this->GetScanner()->Scan();
  2319. // A star token in an export declaration must be followed by a from clause which begins with a token 'from'.
  2320. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);
  2321. if (buildAST)
  2322. {
  2323. Assert(moduleIdentifier != nullptr);
  2324. AddModuleSpecifier(moduleIdentifier);
  2325. IdentPtr importName = wellKnownPropertyPids._star;
  2326. AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), importName, nullptr, nullptr, moduleIdentifier);
  2327. }
  2328. if (needTerminator != nullptr)
  2329. {
  2330. *needTerminator = true;
  2331. }
  2332. break;
  2333. case tkLCurly:
  2334. {
  2335. ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);
  2336. ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);
  2337. this->GetScanner()->Scan();
  2338. // Export clause may be followed by a from clause.
  2339. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);
  2340. if (buildAST)
  2341. {
  2342. if (moduleIdentifier != nullptr)
  2343. {
  2344. AddModuleSpecifier(moduleIdentifier);
  2345. }
  2346. exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {
  2347. if (moduleIdentifier != nullptr)
  2348. {
  2349. exportEntry.moduleRequest = moduleIdentifier;
  2350. // We need to swap localname and importname when this is a re-export.
  2351. exportEntry.importName = exportEntry.localName;
  2352. exportEntry.localName = nullptr;
  2353. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);
  2354. }
  2355. else
  2356. {
  2357. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);
  2358. }
  2359. });
  2360. exportEntryList.Clear();
  2361. }
  2362. }
  2363. if (needTerminator != nullptr)
  2364. {
  2365. *needTerminator = true;
  2366. }
  2367. break;
  2368. case tkID:
  2369. {
  2370. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  2371. if (wellKnownPropertyPids.let == pid)
  2372. {
  2373. declarationType = tkLET;
  2374. goto ParseVarDecl;
  2375. }
  2376. if (wellKnownPropertyPids.async == pid && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2377. {
  2378. // In module export statements, async token is only valid if it's followed by function.
  2379. // We need to check here because ParseStatement would think 'async = 20' is a var decl.
  2380. RestorePoint parsedAsync;
  2381. this->GetScanner()->Capture(&parsedAsync);
  2382. this->GetScanner()->Scan();
  2383. if (m_token.tk == tkFUNCTION)
  2384. {
  2385. // Token after async is function, rewind to the async token and let ParseStatement handle it.
  2386. this->GetScanner()->SeekTo(parsedAsync);
  2387. goto ParseFunctionDecl;
  2388. }
  2389. // Token after async is not function, it's a syntax error.
  2390. }
  2391. goto ErrorToken;
  2392. }
  2393. case tkVAR:
  2394. case tkLET:
  2395. case tkCONST:
  2396. {
  2397. declarationType = m_token.tk;
  2398. ParseVarDecl:
  2399. this->GetScanner()->Scan();
  2400. pnode = ParseVariableDeclaration<buildAST>(declarationType, this->GetScanner()->IchMinTok());
  2401. if (buildAST)
  2402. {
  2403. ForEachItemInList(pnode, [&](ParseNodePtr item) {
  2404. if (item->nop == knopAsg)
  2405. {
  2406. Parser::MapBindIdentifier(item, [&](ParseNodePtr subItem)
  2407. {
  2408. AddModuleLocalExportEntry(subItem);
  2409. });
  2410. }
  2411. else
  2412. {
  2413. AddModuleLocalExportEntry(item);
  2414. }
  2415. });
  2416. }
  2417. }
  2418. break;
  2419. case tkFUNCTION:
  2420. case tkCLASS:
  2421. {
  2422. ParseFunctionDecl:
  2423. pnode = ParseStatement<buildAST>();
  2424. if (buildAST)
  2425. {
  2426. IdentPtr localName;
  2427. if (pnode->nop == knopClassDecl)
  2428. {
  2429. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  2430. pnodeClass->pnodeDeclName->sym->SetIsModuleExportStorage(true);
  2431. localName = pnodeClass->pnodeName->pid;
  2432. }
  2433. else
  2434. {
  2435. Assert(pnode->nop == knopFncDecl);
  2436. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  2437. pnodeFnc->GetFuncSymbol()->SetIsModuleExportStorage(true);
  2438. localName = pnodeFnc->pid;
  2439. }
  2440. Assert(localName != nullptr);
  2441. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2442. }
  2443. }
  2444. break;
  2445. case tkDEFAULT:
  2446. {
  2447. pnode = ParseDefaultExportClause<buildAST>();
  2448. }
  2449. break;
  2450. default:
  2451. {
  2452. ErrorToken:
  2453. Error(ERRsyntax);
  2454. }
  2455. }
  2456. return pnode;
  2457. }
  2458. /***************************************************************************
  2459. Parse an expression term.
  2460. ***************************************************************************/
  2461. template<bool buildAST>
  2462. ParseNodePtr Parser::ParseTerm(BOOL fAllowCall,
  2463. LPCOLESTR pNameHint,
  2464. uint32 *pHintLength,
  2465. uint32 *pShortNameOffset,
  2466. _Inout_opt_ IdentToken* pToken /*= nullptr*/,
  2467. bool fUnaryOrParen /*= false*/,
  2468. BOOL fCanAssignToCall /*= TRUE*/,
  2469. _Out_opt_ BOOL* pfCanAssign /*= nullptr*/,
  2470. _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/,
  2471. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/,
  2472. _Inout_opt_ charcount_t *plastRParen /*= nullptr*/)
  2473. {
  2474. ParseNodePtr pnode = nullptr;
  2475. PidRefStack *savedTopAsyncRef = nullptr;
  2476. charcount_t ichMin = 0;
  2477. charcount_t ichLim = 0;
  2478. size_t iecpMin = 0;
  2479. size_t iecpLim = 0;
  2480. size_t iuMin;
  2481. IdentToken term;
  2482. BOOL fInNew = FALSE;
  2483. BOOL fCanAssign = TRUE;
  2484. bool isAsyncExpr = false;
  2485. bool isLambdaExpr = false;
  2486. bool isSpecialName = false;
  2487. IdentPtr pid = nullptr;
  2488. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  2489. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);
  2490. switch (m_token.tk)
  2491. {
  2492. case tkID:
  2493. {
  2494. pid = m_token.GetIdentifier(this->GetHashTbl());
  2495. ichMin = this->GetScanner()->IchMinTok();
  2496. iecpMin = this->GetScanner()->IecpMinTok();
  2497. ichLim = this->GetScanner()->IchLimTok();
  2498. iecpLim = this->GetScanner()->IecpLimTok();
  2499. if (pid == wellKnownPropertyPids.async &&
  2500. m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2501. {
  2502. isAsyncExpr = true;
  2503. }
  2504. // Put this into a block to avoid previousAwaitIsKeyword being not initialized after jump to LIdentifier
  2505. {
  2506. bool previousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(isAsyncExpr);
  2507. this->GetScanner()->Scan();
  2508. this->GetScanner()->SetAwaitIsKeywordRegion(previousAwaitIsKeyword);
  2509. }
  2510. // We search for an Async expression (a function declaration or an async lambda expression)
  2511. if (isAsyncExpr && !this->GetScanner()->FHadNewLine())
  2512. {
  2513. if (m_token.tk == tkFUNCTION)
  2514. {
  2515. goto LFunction;
  2516. }
  2517. else if (m_token.tk == tkID || m_token.tk == tkAWAIT)
  2518. {
  2519. isLambdaExpr = true;
  2520. goto LFunction;
  2521. }
  2522. else if (m_token.tk == tkLParen)
  2523. {
  2524. // This is potentially an async arrow function. Save the state of the async references
  2525. // in case it needs to be restored. (Note that the case of a single parameter with no ()'s
  2526. // is detected upstream and need not be handled here.)
  2527. savedTopAsyncRef = pid->GetTopRef();
  2528. }
  2529. }
  2530. CheckArgumentsUse(pid, GetCurrentFunctionNode());
  2531. // Assume this pid is not special - overwrite when we parse a special name
  2532. isSpecialName = false;
  2533. LIdentifier:
  2534. PidRefStack * ref = nullptr;
  2535. // Don't push a reference if this is a single lambda parameter, because we'll reparse with
  2536. // a correct function ID.
  2537. if (m_token.tk != tkDArrow)
  2538. {
  2539. ref = this->PushPidRef(pid);
  2540. }
  2541. if (buildAST)
  2542. {
  2543. if (isSpecialName)
  2544. {
  2545. pnode = CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  2546. }
  2547. else
  2548. {
  2549. pnode = CreateNameNode(pid, ref, ichMin, ichLim);
  2550. }
  2551. }
  2552. else
  2553. {
  2554. // Remember the identifier start and end in case it turns out to be a statement label.
  2555. term.tk = tkID;
  2556. term.pid = pid; // Record the identifier for detection of eval
  2557. term.ichMin = static_cast<charcount_t>(iecpMin);
  2558. term.ichLim = static_cast<charcount_t>(iecpLim);
  2559. }
  2560. break;
  2561. }
  2562. case tkSUPER:
  2563. ichMin = this->GetScanner()->IchMinTok();
  2564. iecpMin = this->GetScanner()->IecpMinTok();
  2565. ichLim = this->GetScanner()->IchLimTok();
  2566. iecpLim = this->GetScanner()->IecpLimTok();
  2567. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2568. {
  2569. goto LUnknown;
  2570. }
  2571. this->GetScanner()->Scan();
  2572. pid = ParseSuper<buildAST>(!!fAllowCall);
  2573. isSpecialName = true;
  2574. // Super reference and super call need to push a pid ref to 'this' even when not building an AST
  2575. ReferenceSpecialName(wellKnownPropertyPids._this, ichMin, ichLim);
  2576. // Super call needs to reference 'new.target'
  2577. if (pid == wellKnownPropertyPids._superConstructor)
  2578. {
  2579. ReferenceSpecialName(wellKnownPropertyPids._newTarget, ichMin, ichLim);
  2580. }
  2581. goto LIdentifier;
  2582. case tkTHIS:
  2583. ichMin = this->GetScanner()->IchMinTok();
  2584. iecpMin = this->GetScanner()->IecpMinTok();
  2585. ichLim = this->GetScanner()->IchLimTok();
  2586. iecpLim = this->GetScanner()->IecpLimTok();
  2587. pid = wellKnownPropertyPids._this;
  2588. this->GetScanner()->Scan();
  2589. isSpecialName = true;
  2590. goto LIdentifier;
  2591. case tkLParen:
  2592. {
  2593. ichMin = this->GetScanner()->IchMinTok();
  2594. iuMin = this->GetScanner()->IecpMinTok();
  2595. // If we are undeferring a function which has deferred stubs, we can check to see if the next deferred stub
  2596. // is a lambda at the current character. If it is, we know this LParen is the beginning of a lambda nested
  2597. // function and we can avoid parsing the next series of tokens as a parenthetical expression and reparsing
  2598. // after finding the => token.
  2599. if (buildAST && m_currDeferredStub != nullptr && GetCurrentFunctionNode() != nullptr && GetCurrentFunctionNode()->nestedCount < m_currDeferredStubCount)
  2600. {
  2601. DeferredFunctionStub* stub = m_currDeferredStub + GetCurrentFunctionNode()->nestedCount;
  2602. if (stub->ichMin == ichMin)
  2603. {
  2604. Assert((stub->fncFlags & kFunctionIsLambda) == kFunctionIsLambda);
  2605. pnode = ParseFncDeclNoCheckScope<true>(fFncLambda);
  2606. break;
  2607. }
  2608. }
  2609. this->GetScanner()->Scan();
  2610. if (m_token.tk == tkRParen)
  2611. {
  2612. // Empty parens can only be legal as an empty parameter list to a lambda declaration.
  2613. // We're in a lambda if the next token is =>.
  2614. fAllowCall = FALSE;
  2615. this->GetScanner()->Scan();
  2616. // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error
  2617. if (!IsDoingFastScan() && (m_token.tk != tkDArrow || this->GetScanner()->FHadNewLine()))
  2618. {
  2619. Error(ERRsyntax);
  2620. }
  2621. if (buildAST)
  2622. {
  2623. pnode = CreateNodeForOpT<knopEmpty>();
  2624. }
  2625. break;
  2626. }
  2627. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  2628. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  2629. // up function ID's.
  2630. uint saveNextBlockId = m_nextBlockId;
  2631. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  2632. GetCurrentBlock()->blockId = m_nextBlockId++;
  2633. AutoDeferErrorsRestore deferErrorRestore(this);
  2634. this->m_funcParenExprDepth++;
  2635. pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen);
  2636. this->m_funcParenExprDepth--;
  2637. if (buildAST && plastRParen)
  2638. {
  2639. *plastRParen = this->GetScanner()->IchLimTok();
  2640. }
  2641. ChkCurTok(tkRParen, ERRnoRparen);
  2642. GetCurrentBlock()->blockId = saveCurrBlockId;
  2643. if (m_token.tk == tkDArrow)
  2644. {
  2645. // We're going to rewind and reinterpret the expression as a parameter list.
  2646. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  2647. m_nextBlockId = saveNextBlockId;
  2648. }
  2649. else
  2650. {
  2651. // Emit a deferred ... error if one was parsed.
  2652. if (m_deferEllipsisError)
  2653. {
  2654. this->GetScanner()->SeekTo(m_deferEllipsisErrorLoc);
  2655. Error(ERRInvalidSpreadUse);
  2656. }
  2657. else if (m_deferCommaError)
  2658. {
  2659. // Emit a comma error if that was deferred.
  2660. this->GetScanner()->SeekTo(m_deferCommaErrorLoc);
  2661. Error(ERRsyntax);
  2662. }
  2663. }
  2664. break;
  2665. }
  2666. case tkIntCon:
  2667. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2668. {
  2669. Error(ERRES5NoOctal);
  2670. }
  2671. if (buildAST)
  2672. {
  2673. pnode = CreateIntNode(m_token.GetLong());
  2674. }
  2675. fCanAssign = FALSE;
  2676. this->GetScanner()->Scan();
  2677. break;
  2678. case tkFltCon:
  2679. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2680. {
  2681. Error(ERRES5NoOctal);
  2682. }
  2683. if (buildAST)
  2684. {
  2685. ParseNodeFloat * pnodeFloat;
  2686. pnode = pnodeFloat = CreateNodeForOpT<knopFlt>();
  2687. pnodeFloat->dbl = m_token.GetDouble();
  2688. pnodeFloat->maybeInt = m_token.GetDoubleMayBeInt();
  2689. }
  2690. fCanAssign = FALSE;
  2691. this->GetScanner()->Scan();
  2692. break;
  2693. case tkStrCon:
  2694. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2695. {
  2696. Error(ERRES5NoOctal);
  2697. }
  2698. if (buildAST)
  2699. {
  2700. pnode = CreateStrNode(m_token.GetStr());
  2701. }
  2702. else
  2703. {
  2704. // Subtract the string literal length from the total char count for the purpose
  2705. // of deciding whether to defer parsing and byte code generation.
  2706. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok());
  2707. }
  2708. fCanAssign = FALSE;
  2709. this->GetScanner()->Scan();
  2710. break;
  2711. case tkTRUE:
  2712. if (buildAST)
  2713. {
  2714. pnode = CreateNodeForOpT<knopTrue>();
  2715. }
  2716. fCanAssign = FALSE;
  2717. this->GetScanner()->Scan();
  2718. break;
  2719. case tkFALSE:
  2720. if (buildAST)
  2721. {
  2722. pnode = CreateNodeForOpT<knopFalse>();
  2723. }
  2724. fCanAssign = FALSE;
  2725. this->GetScanner()->Scan();
  2726. break;
  2727. case tkNULL:
  2728. if (buildAST)
  2729. {
  2730. pnode = CreateNodeForOpT<knopNull>();
  2731. }
  2732. fCanAssign = FALSE;
  2733. this->GetScanner()->Scan();
  2734. break;
  2735. case tkDiv:
  2736. case tkAsgDiv:
  2737. pnode = ParseRegExp<buildAST>();
  2738. fCanAssign = FALSE;
  2739. this->GetScanner()->Scan();
  2740. break;
  2741. case tkNEW:
  2742. {
  2743. ichMin = this->GetScanner()->IchMinTok();
  2744. iecpMin = this->GetScanner()->IecpMinTok();
  2745. this->GetScanner()->Scan();
  2746. if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2747. {
  2748. pid = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);
  2749. ichLim = this->GetScanner()->IchLimTok();
  2750. iecpLim = this->GetScanner()->IecpLimTok();
  2751. this->GetScanner()->Scan();
  2752. isSpecialName = true;
  2753. goto LIdentifier;
  2754. }
  2755. else
  2756. {
  2757. ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset, nullptr, false, TRUE, nullptr, nullptr, nullptr, plastRParen);
  2758. if (buildAST)
  2759. {
  2760. pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);
  2761. pnode->ichMin = ichMin;
  2762. }
  2763. fInNew = TRUE;
  2764. fCanAssign = FALSE;
  2765. }
  2766. break;
  2767. }
  2768. case tkLBrack:
  2769. {
  2770. ichMin = this->GetScanner()->IchMinTok();
  2771. this->GetScanner()->Scan();
  2772. pnode = ParseArrayLiteral<buildAST>();
  2773. if (buildAST)
  2774. {
  2775. pnode->ichMin = ichMin;
  2776. pnode->ichLim = this->GetScanner()->IchLimTok();
  2777. }
  2778. if (this->m_arrayDepth == 0)
  2779. {
  2780. Assert(this->GetScanner()->IchLimTok() - ichMin > m_funcInArray);
  2781. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - ichMin - this->m_funcInArray);
  2782. this->m_funcInArray = 0;
  2783. this->m_funcInArrayDepth = 0;
  2784. }
  2785. ChkCurTok(tkRBrack, ERRnoRbrack);
  2786. if (!IsES6DestructuringEnabled())
  2787. {
  2788. fCanAssign = FALSE;
  2789. }
  2790. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2791. {
  2792. *pfLikelyPattern = TRUE;
  2793. }
  2794. break;
  2795. }
  2796. case tkLCurly:
  2797. {
  2798. ichMin = this->GetScanner()->IchMinTok();
  2799. this->GetScanner()->ScanForcingPid();
  2800. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);
  2801. if (buildAST)
  2802. {
  2803. pnode = CreateUniNode(knopObject, pnodeMemberList);
  2804. pnode->ichMin = ichMin;
  2805. pnode->ichLim = this->GetScanner()->IchLimTok();
  2806. }
  2807. ChkCurTok(tkRCurly, ERRnoRcurly);
  2808. if (!IsES6DestructuringEnabled())
  2809. {
  2810. fCanAssign = FALSE;
  2811. }
  2812. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2813. {
  2814. *pfLikelyPattern = TRUE;
  2815. }
  2816. break;
  2817. }
  2818. case tkFUNCTION:
  2819. {
  2820. LFunction:
  2821. if (m_grfscr & fscrDeferredFncExpression)
  2822. {
  2823. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  2824. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  2825. // first time we see it.
  2826. //
  2827. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  2828. // token of the source code of the function may not a 'function' token though, so we still need to reset this flag
  2829. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  2830. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  2831. m_grfscr &= ~fscrDeferredFncExpression;
  2832. }
  2833. ushort flags = fFncNoFlgs;
  2834. if (isLambdaExpr)
  2835. {
  2836. flags |= fFncLambda;
  2837. }
  2838. if (isAsyncExpr)
  2839. {
  2840. flags |= fFncAsync;
  2841. }
  2842. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::Disallowed, pNameHint, /* needsPIDOnRCurlyScan */ false, fUnaryOrParen);
  2843. if (isAsyncExpr)
  2844. {
  2845. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  2846. pnode->ichMin = ichMin;
  2847. }
  2848. fCanAssign = FALSE;
  2849. break;
  2850. }
  2851. case tkCLASS:
  2852. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2853. {
  2854. pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);
  2855. }
  2856. else
  2857. {
  2858. goto LUnknown;
  2859. }
  2860. fCanAssign = FALSE;
  2861. break;
  2862. case tkStrTmplBasic:
  2863. case tkStrTmplBegin:
  2864. pnode = ParseStringTemplateDecl<buildAST>(nullptr);
  2865. fCanAssign = FALSE;
  2866. break;
  2867. case tkIMPORT:
  2868. if (m_scriptContext->GetConfig()->IsES6ModuleEnabled() && m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2869. {
  2870. this->GetScanner()->Scan();
  2871. ChkCurTokNoScan(tkLParen, ERRnoLparen);
  2872. pnode = ParseImportCall<buildAST>();
  2873. }
  2874. else
  2875. {
  2876. goto LUnknown;
  2877. }
  2878. break;
  2879. #if ENABLE_BACKGROUND_PARSING
  2880. case tkCASE:
  2881. {
  2882. if (!m_doingFastScan)
  2883. {
  2884. goto LUnknown;
  2885. }
  2886. ParseNodePtr pnodeUnused;
  2887. pnode = ParseCase<buildAST>(&pnodeUnused);
  2888. break;
  2889. }
  2890. case tkELSE:
  2891. if (!m_doingFastScan)
  2892. {
  2893. goto LUnknown;
  2894. }
  2895. this->GetScanner()->Scan();
  2896. ParseStatement<buildAST>();
  2897. break;
  2898. #endif
  2899. default:
  2900. LUnknown:
  2901. Error(ERRsyntax);
  2902. break;
  2903. }
  2904. pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, fCanAssignToCall, &fCanAssign, &term, pfIsDotOrIndex);
  2905. if (savedTopAsyncRef != nullptr &&
  2906. this->m_token.tk == tkDArrow)
  2907. {
  2908. // This is an async arrow function; we're going to back up and reparse it.
  2909. // Make sure we don't leave behind a bogus reference to the 'async' identifier.
  2910. for (pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;)
  2911. {
  2912. Assert(pid->GetTopRef() != nullptr);
  2913. pid->RemovePrevPidRef(nullptr);
  2914. }
  2915. }
  2916. // Pass back identifier if requested
  2917. if (pToken && term.tk == tkID)
  2918. {
  2919. *pToken = term;
  2920. }
  2921. if (pfCanAssign)
  2922. {
  2923. *pfCanAssign = fCanAssign;
  2924. }
  2925. return pnode;
  2926. }
  2927. template <bool buildAST>
  2928. ParseNodeRegExp * Parser::ParseRegExp()
  2929. {
  2930. ParseNodeRegExp * pnode = nullptr;
  2931. if (buildAST || IsDoingFastScan())
  2932. {
  2933. this->GetScanner()->RescanRegExp();
  2934. #if ENABLE_BACKGROUND_PARSING
  2935. BOOL saveDeferringAST = this->m_deferringAST;
  2936. if (m_doingFastScan)
  2937. {
  2938. this->m_deferringAST = false;
  2939. }
  2940. #endif
  2941. pnode = CreateNodeForOpT<knopRegExp>();
  2942. pnode->regexPattern = m_token.GetRegex();
  2943. #if ENABLE_BACKGROUND_PARSING
  2944. if (m_doingFastScan)
  2945. {
  2946. this->m_deferringAST = saveDeferringAST;
  2947. this->AddFastScannedRegExpNode(pnode);
  2948. if (!buildAST)
  2949. {
  2950. pnode = nullptr;
  2951. }
  2952. }
  2953. else if (this->IsBackgroundParser())
  2954. {
  2955. Assert(pnode->regexPattern == nullptr);
  2956. this->AddBackgroundRegExpNode(pnode);
  2957. }
  2958. #endif
  2959. }
  2960. else
  2961. {
  2962. this->GetScanner()->RescanRegExpNoAST();
  2963. }
  2964. Assert(m_token.tk == tkRegExp);
  2965. return pnode;
  2966. }
  2967. BOOL Parser::NodeIsEvalName(ParseNodePtr pnode)
  2968. {
  2969. //WOOB 1107758 Special case of indirect eval binds to local scope in standards mode
  2970. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids.eval);
  2971. }
  2972. BOOL Parser::NodeIsSuperName(ParseNodePtr pnode)
  2973. {
  2974. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids._superConstructor);
  2975. }
  2976. BOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)
  2977. {
  2978. return pnode->nop == knopName &&
  2979. pnode->AsParseNodeName()->pid->Cch() == cch &&
  2980. !wmemcmp(pnode->AsParseNodeName()->pid->Psz(), sz, cch);
  2981. }
  2982. BOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)
  2983. {
  2984. for (;;)
  2985. {
  2986. switch (pnode->nop)
  2987. {
  2988. case knopName:
  2989. return (pnode->AsParseNodeName()->pid == pid);
  2990. case knopComma:
  2991. pnode = pnode->AsParseNodeBin()->pnode2;
  2992. break;
  2993. default:
  2994. return FALSE;
  2995. }
  2996. }
  2997. }
  2998. template<bool buildAST>
  2999. ParseNodePtr Parser::ParsePostfixOperators(
  3000. ParseNodePtr pnode,
  3001. BOOL fAllowCall,
  3002. BOOL fInNew,
  3003. BOOL isAsyncExpr,
  3004. BOOL fCanAssignToCallResult,
  3005. BOOL *pfCanAssign,
  3006. _Inout_ IdentToken* pToken,
  3007. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr */)
  3008. {
  3009. uint16 count = 0;
  3010. bool callOfConstants = false;
  3011. if (pfIsDotOrIndex)
  3012. {
  3013. *pfIsDotOrIndex = false;
  3014. }
  3015. for (;;)
  3016. {
  3017. uint16 spreadArgCount = 0;
  3018. switch (m_token.tk)
  3019. {
  3020. case tkLParen:
  3021. {
  3022. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3023. if (fInNew)
  3024. {
  3025. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3026. if (buildAST)
  3027. {
  3028. Assert(pnode->nop == knopNew);
  3029. Assert(pnode->AsParseNodeCall()->pnodeArgs == nullptr);
  3030. pnode->AsParseNodeCall()->pnodeArgs = pnodeArgs;
  3031. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3032. pnode->AsParseNodeCall()->isApplyCall = false;
  3033. pnode->AsParseNodeCall()->isEvalCall = false;
  3034. pnode->AsParseNodeCall()->isSuperCall = false;
  3035. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3036. Assert(!m_hasDestructuringPattern || count > 0);
  3037. pnode->AsParseNodeCall()->argCount = count;
  3038. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3039. pnode->ichLim = this->GetScanner()->IchLimTok();
  3040. }
  3041. else
  3042. {
  3043. pnode = nullptr;
  3044. pToken->tk = tkNone; // This is no longer an identifier
  3045. }
  3046. fInNew = FALSE;
  3047. ChkCurTok(tkRParen, ERRnoRparen);
  3048. }
  3049. else
  3050. {
  3051. if (!fAllowCall)
  3052. {
  3053. return pnode;
  3054. }
  3055. uint saveNextBlockId = m_nextBlockId;
  3056. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  3057. if (isAsyncExpr)
  3058. {
  3059. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  3060. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  3061. // up function ID's.
  3062. GetCurrentBlock()->blockId = m_nextBlockId++;
  3063. }
  3064. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3065. // We used to un-defer a deferred function body here if it was called as part of the expression that declared it.
  3066. // We now detect this case up front in ParseFncDecl, which is cheaper and simpler.
  3067. if (buildAST)
  3068. {
  3069. bool fCallIsEval = false;
  3070. // Detect super()
  3071. if (this->NodeIsSuperName(pnode))
  3072. {
  3073. pnode = CreateSuperCallNode(pnode->AsParseNodeSpecialName(), pnodeArgs);
  3074. Assert(pnode);
  3075. pnode->AsParseNodeSuperCall()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3076. pnode->AsParseNodeSuperCall()->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3077. }
  3078. else
  3079. {
  3080. pnode = CreateCallNode(knopCall, pnode, pnodeArgs);
  3081. Assert(pnode);
  3082. }
  3083. // Detect call to "eval" and record it on the function.
  3084. // Note: we used to leave it up to the byte code generator to detect eval calls
  3085. // at global scope, but now it relies on the flag the parser sets, so set it here.
  3086. if (count > 0 && this->NodeIsEvalName(pnode->AsParseNodeCall()->pnodeTarget))
  3087. {
  3088. this->MarkEvalCaller();
  3089. fCallIsEval = true;
  3090. // Eval may reference any of the special symbols so we need to push refs to them here.
  3091. ReferenceSpecialName(wellKnownPropertyPids._this);
  3092. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3093. ReferenceSpecialName(wellKnownPropertyPids._super);
  3094. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3095. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3096. }
  3097. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3098. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3099. pnode->AsParseNodeCall()->isApplyCall = false;
  3100. pnode->AsParseNodeCall()->isEvalCall = fCallIsEval;
  3101. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3102. Assert(!m_hasDestructuringPattern || count > 0);
  3103. pnode->AsParseNodeCall()->argCount = count;
  3104. pnode->ichLim = this->GetScanner()->IchLimTok();
  3105. }
  3106. else
  3107. {
  3108. pnode = nullptr;
  3109. if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) // Detect eval
  3110. {
  3111. this->MarkEvalCaller();
  3112. ReferenceSpecialName(wellKnownPropertyPids._this);
  3113. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3114. ReferenceSpecialName(wellKnownPropertyPids._super);
  3115. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3116. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3117. }
  3118. pToken->tk = tkNone; // This is no longer an identifier
  3119. }
  3120. ChkCurTok(tkRParen, ERRnoRparen);
  3121. if (isAsyncExpr)
  3122. {
  3123. GetCurrentBlock()->blockId = saveCurrBlockId;
  3124. if (m_token.tk == tkDArrow)
  3125. {
  3126. // We're going to rewind and reinterpret the expression as a parameter list.
  3127. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  3128. m_nextBlockId = saveNextBlockId;
  3129. }
  3130. }
  3131. }
  3132. if (pfCanAssign)
  3133. {
  3134. *pfCanAssign = fCanAssignToCallResult &&
  3135. (m_sourceContextInfo ?
  3136. !PHASE_ON_RAW(Js::EarlyErrorOnAssignToCallPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId) :
  3137. !PHASE_ON1(Js::EarlyErrorOnAssignToCallPhase));
  3138. }
  3139. if (pfIsDotOrIndex)
  3140. {
  3141. *pfIsDotOrIndex = false;
  3142. }
  3143. break;
  3144. }
  3145. case tkLBrack:
  3146. {
  3147. this->GetScanner()->Scan();
  3148. IdentToken tok;
  3149. ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
  3150. if (buildAST)
  3151. {
  3152. AnalysisAssert(pnodeExpr);
  3153. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3154. {
  3155. pnode = CreateSuperReferenceNode(knopIndex, pnode->AsParseNodeSpecialName(), pnodeExpr);
  3156. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3157. }
  3158. else
  3159. {
  3160. pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
  3161. }
  3162. AnalysisAssert(pnode);
  3163. pnode->ichLim = this->GetScanner()->IchLimTok();
  3164. }
  3165. else
  3166. {
  3167. pnode = nullptr;
  3168. pToken->tk = tkNone; // This is no longer an identifier
  3169. }
  3170. ChkCurTok(tkRBrack, ERRnoRbrack);
  3171. if (pfCanAssign)
  3172. {
  3173. *pfCanAssign = TRUE;
  3174. }
  3175. if (pfIsDotOrIndex)
  3176. {
  3177. *pfIsDotOrIndex = true;
  3178. }
  3179. PidRefStack * topPidRef = nullptr;
  3180. if (buildAST)
  3181. {
  3182. if (pnodeExpr && pnodeExpr->nop == knopName)
  3183. {
  3184. topPidRef = pnodeExpr->AsParseNodeName()->pid->GetTopRef();
  3185. }
  3186. }
  3187. else if (tok.tk == tkID)
  3188. {
  3189. topPidRef = tok.pid->GetTopRef();
  3190. }
  3191. if (topPidRef)
  3192. {
  3193. topPidRef->SetIsUsedInLdElem(true);
  3194. }
  3195. if (!buildAST)
  3196. {
  3197. break;
  3198. }
  3199. bool shouldConvertToDot = false;
  3200. if (pnode->AsParseNodeBin()->pnode2->nop == knopStr)
  3201. {
  3202. // if the string is empty or contains escape character, we will not convert them to dot node
  3203. shouldConvertToDot = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch() > 0 && !this->GetScanner()->IsEscapeOnLastTkStrCon();
  3204. }
  3205. if (shouldConvertToDot)
  3206. {
  3207. LPCOLESTR str = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Psz();
  3208. // See if we can convert o["p"] into o.p and o["0"] into o[0] since they're equivalent and the latter forms
  3209. // are faster
  3210. uint32 uintValue;
  3211. if (Js::JavascriptOperators::TryConvertToUInt32(
  3212. str,
  3213. pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch(),
  3214. &uintValue) &&
  3215. !Js::TaggedInt::IsOverflow(uintValue)) // the optimization is not very useful if the number can't be represented as a TaggedInt
  3216. {
  3217. // No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes
  3218. auto intNode = CreateIntNode(uintValue); // implicit conversion from uint32 to int32
  3219. pnode->AsParseNodeBin()->pnode2 = intNode;
  3220. }
  3221. // Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,
  3222. // and since NaN/Infinity is a number it won't kill o.NaN/o.Infinity which would cause a problem
  3223. // if we decide to hoist o.NaN/o.Infinity.
  3224. // We need to keep o["NaN"] and o["+/-Infinity"] as array element access (we don't hoist that but we may hoist field access),
  3225. // so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.
  3226. // We need to follow same logic for strings that convert to a floating point number.
  3227. else
  3228. {
  3229. bool doConvertToProperty = false; // Convert a["x"] -> a.x.
  3230. if (!Parser::IsNaNOrInfinityLiteral<true>(str))
  3231. {
  3232. const OLECHAR* terminalChar;
  3233. double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);
  3234. bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);
  3235. doConvertToProperty = !convertsToFloat;
  3236. }
  3237. if (doConvertToProperty)
  3238. {
  3239. ParseNodeName * pnodeNewExpr = CreateNameNode(pnodeExpr->AsParseNodeStr()->pid);
  3240. pnodeNewExpr->ichMin = pnodeExpr->ichMin;
  3241. pnodeNewExpr->ichLim = pnodeExpr->ichLim;
  3242. pnode->AsParseNodeBin()->pnode2 = pnodeNewExpr;
  3243. pnode->nop = knopDot;
  3244. pnode->grfpn |= PNodeFlags::fpnIndexOperator;
  3245. }
  3246. }
  3247. }
  3248. }
  3249. break;
  3250. case tkDot:
  3251. {
  3252. ParseNodePtr name = nullptr;
  3253. OpCode opCode = knopDot;
  3254. this->GetScanner()->Scan();
  3255. if (!m_token.IsIdentifier())
  3256. {
  3257. //allow reserved words in ES5 mode
  3258. if (!(m_token.IsReservedWord()))
  3259. {
  3260. IdentifierExpectedError(m_token);
  3261. }
  3262. }
  3263. // Note: see comment above about field optimization WRT NaN/Infinity/-Infinity.
  3264. // Convert a.Nan, a.Infinity into a["NaN"], a["Infinity"].
  3265. // We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.
  3266. // Both NaN and Infinity are identifiers.
  3267. else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(this->GetHashTbl())->Psz()))
  3268. {
  3269. opCode = knopIndex;
  3270. }
  3271. if (buildAST)
  3272. {
  3273. if (opCode == knopDot)
  3274. {
  3275. name = CreateNameNode(m_token.GetIdentifier(this->GetHashTbl()));
  3276. }
  3277. else
  3278. {
  3279. Assert(opCode == knopIndex);
  3280. name = CreateStrNode(m_token.GetIdentifier(this->GetHashTbl()));
  3281. }
  3282. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3283. {
  3284. pnode = CreateSuperReferenceNode(opCode, pnode->AsParseNodeSpecialName(), name);
  3285. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3286. }
  3287. else
  3288. {
  3289. pnode = CreateBinNode(opCode, pnode, name);
  3290. }
  3291. }
  3292. else
  3293. {
  3294. pnode = nullptr;
  3295. pToken->tk = tkNone;
  3296. }
  3297. if (pfCanAssign)
  3298. {
  3299. *pfCanAssign = TRUE;
  3300. }
  3301. if (pfIsDotOrIndex)
  3302. {
  3303. *pfIsDotOrIndex = true;
  3304. }
  3305. this->GetScanner()->Scan();
  3306. break;
  3307. }
  3308. case tkStrTmplBasic:
  3309. case tkStrTmplBegin:
  3310. {
  3311. ParseNode* templateNode = nullptr;
  3312. if (pnode != nullptr)
  3313. {
  3314. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3315. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3316. }
  3317. else
  3318. {
  3319. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3320. }
  3321. if (!buildAST)
  3322. {
  3323. pToken->tk = tkNone; // This is no longer an identifier
  3324. }
  3325. pnode = templateNode;
  3326. if (pfCanAssign)
  3327. {
  3328. *pfCanAssign = FALSE;
  3329. }
  3330. if (pfIsDotOrIndex)
  3331. {
  3332. *pfIsDotOrIndex = false;
  3333. }
  3334. break;
  3335. }
  3336. default:
  3337. return pnode;
  3338. }
  3339. }
  3340. }
  3341. /***************************************************************************
  3342. Look for an existing label with the given name.
  3343. ***************************************************************************/
  3344. bool Parser::LabelExists(IdentPtr pid, LabelId* pLabelIdList)
  3345. {
  3346. StmtNest dummy;
  3347. dummy.pLabelId = pLabelIdList;
  3348. dummy.pstmtOuter = m_pstmtCur;
  3349. // Look through each label list for the current stack of statements
  3350. for (StmtNest* pStmt = &dummy; pStmt != nullptr; pStmt = pStmt->pstmtOuter)
  3351. {
  3352. for (LabelId* pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)
  3353. {
  3354. if (pLabelId->pid == pid)
  3355. return true;
  3356. }
  3357. }
  3358. return false;
  3359. }
  3360. // Currently only ints and floats are treated as constants in function call
  3361. // TODO: Check if we need for other constants as well
  3362. BOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)
  3363. {
  3364. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3365. {
  3366. return TRUE;
  3367. }
  3368. if (pnode->nop == knopFlt)
  3369. {
  3370. return TRUE;
  3371. }
  3372. return FALSE;
  3373. }
  3374. /***************************************************************************
  3375. Parse a list of arguments.
  3376. ***************************************************************************/
  3377. template<bool buildAST>
  3378. ParseNodePtr Parser::ParseArgList(bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)
  3379. {
  3380. ParseNodePtr pnodeArg;
  3381. ParseNodePtr pnodeList = nullptr;
  3382. ParseNodePtr *lastNodeRef = nullptr;
  3383. // Check for an empty list
  3384. Assert(m_token.tk == tkLParen);
  3385. if (this->GetScanner()->Scan() == tkRParen)
  3386. {
  3387. return nullptr;
  3388. }
  3389. *pCallOfConstants = true;
  3390. *pSpreadArgCount = 0;
  3391. int count = 0;
  3392. while (true)
  3393. {
  3394. if (count >= Js::Constants::MaxAllowedArgs)
  3395. {
  3396. Error(ERRTooManyArgs);
  3397. }
  3398. // Allow spread in argument lists.
  3399. IdentToken token;
  3400. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */TRUE, NULL, nullptr, nullptr, &token);
  3401. ++count;
  3402. this->MarkEscapingRef(pnodeArg, &token);
  3403. if (buildAST)
  3404. {
  3405. this->CheckArguments(pnodeArg);
  3406. if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))
  3407. {
  3408. *pCallOfConstants = false;
  3409. }
  3410. if (pnodeArg->nop == knopEllipsis)
  3411. {
  3412. (*pSpreadArgCount)++;
  3413. }
  3414. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3415. }
  3416. if (m_token.tk != tkComma)
  3417. {
  3418. break;
  3419. }
  3420. this->GetScanner()->Scan();
  3421. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  3422. {
  3423. break;
  3424. }
  3425. }
  3426. if (pSpreadArgCount != nullptr && (*pSpreadArgCount) > 0) {
  3427. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3428. }
  3429. *pCount = static_cast<uint16>(count);
  3430. if (buildAST)
  3431. {
  3432. Assert(lastNodeRef);
  3433. Assert(*lastNodeRef);
  3434. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3435. }
  3436. return pnodeList;
  3437. }
  3438. // Currently only ints are treated as constants in ArrayLiterals
  3439. BOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)
  3440. {
  3441. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3442. {
  3443. return TRUE;
  3444. }
  3445. return FALSE;
  3446. }
  3447. template<bool buildAST>
  3448. ParseNodeArrLit * Parser::ParseArrayLiteral()
  3449. {
  3450. ParseNodeArrLit * pnode = nullptr;
  3451. bool arrayOfTaggedInts = false;
  3452. bool arrayOfInts = false;
  3453. bool arrayOfNumbers = false;
  3454. bool hasMissingValues = false;
  3455. uint count = 0;
  3456. uint spreadCount = 0;
  3457. ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);
  3458. if (buildAST)
  3459. {
  3460. pnode = CreateNodeForOpT<knopArray>();
  3461. pnode->pnode1 = pnode1;
  3462. pnode->arrayOfTaggedInts = arrayOfTaggedInts;
  3463. pnode->arrayOfInts = arrayOfInts;
  3464. pnode->arrayOfNumbers = arrayOfNumbers;
  3465. pnode->hasMissingValues = hasMissingValues;
  3466. pnode->count = count;
  3467. pnode->spreadCount = spreadCount;
  3468. if (pnode->pnode1)
  3469. {
  3470. this->CheckArguments(pnode->pnode1);
  3471. }
  3472. }
  3473. return pnode;
  3474. }
  3475. /***************************************************************************
  3476. Create an ArrayLiteral node
  3477. Parse a list of array elements. [ a, b, , c, ]
  3478. ***************************************************************************/
  3479. template<bool buildAST>
  3480. ParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)
  3481. {
  3482. ParseNodePtr pnodeArg = nullptr;
  3483. ParseNodePtr pnodeList = nullptr;
  3484. ParseNodePtr *lastNodeRef = nullptr;
  3485. *count = 0;
  3486. // Check for an empty list
  3487. if (tkRBrack == m_token.tk)
  3488. {
  3489. return nullptr;
  3490. }
  3491. this->m_arrayDepth++;
  3492. bool arrayOfTaggedInts = buildAST;
  3493. bool arrayOfInts = buildAST;
  3494. bool arrayOfNumbers = buildAST;
  3495. bool arrayOfVarInts = false;
  3496. bool hasMissingValues = false;
  3497. for (;;)
  3498. {
  3499. (*count)++;
  3500. if (tkComma == m_token.tk || tkRBrack == m_token.tk)
  3501. {
  3502. hasMissingValues = true;
  3503. arrayOfTaggedInts = false;
  3504. arrayOfInts = false;
  3505. arrayOfNumbers = false;
  3506. if (buildAST)
  3507. {
  3508. pnodeArg = CreateNodeForOpT<knopEmpty>();
  3509. }
  3510. }
  3511. else
  3512. {
  3513. // Allow Spread in array literals.
  3514. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  3515. if (buildAST)
  3516. {
  3517. if (pnodeArg->nop == knopEllipsis)
  3518. {
  3519. (*spreadCount)++;
  3520. }
  3521. this->CheckArguments(pnodeArg);
  3522. }
  3523. }
  3524. #if DEBUG
  3525. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))
  3526. {
  3527. Error(ERRsyntax);
  3528. }
  3529. #endif
  3530. if (buildAST)
  3531. {
  3532. if (arrayOfNumbers)
  3533. {
  3534. if (pnodeArg->nop != knopInt)
  3535. {
  3536. arrayOfTaggedInts = false;
  3537. if (pnodeArg->nop != knopFlt)
  3538. {
  3539. // Not an array of constants.
  3540. arrayOfInts = false;
  3541. arrayOfNumbers = false;
  3542. }
  3543. else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->AsParseNodeFloat()->dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->AsParseNodeFloat()->dbl) || pnodeArg->AsParseNodeFloat()->dbl == -2147483648.0))
  3544. {
  3545. // We've seen nothing but ints, and this is a uint32 but not an int32.
  3546. // Unless we see an actual float at some point, we want an array of vars
  3547. // so we can work with tagged ints.
  3548. arrayOfVarInts = true;
  3549. }
  3550. else
  3551. {
  3552. // Not an int array, but it may still be a float array.
  3553. arrayOfInts = false;
  3554. }
  3555. }
  3556. else
  3557. {
  3558. if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->AsParseNodeInt()->lw))
  3559. {
  3560. arrayOfInts = false;
  3561. }
  3562. if (Js::TaggedInt::IsOverflow(pnodeArg->AsParseNodeInt()->lw))
  3563. {
  3564. arrayOfTaggedInts = false;
  3565. }
  3566. }
  3567. }
  3568. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3569. }
  3570. if (tkComma != m_token.tk)
  3571. {
  3572. break;
  3573. }
  3574. this->GetScanner()->Scan();
  3575. if (tkRBrack == m_token.tk)
  3576. {
  3577. break;
  3578. }
  3579. }
  3580. if (spreadCount != nullptr && *spreadCount > 0) {
  3581. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3582. }
  3583. if (buildAST)
  3584. {
  3585. Assert(lastNodeRef);
  3586. Assert(*lastNodeRef);
  3587. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3588. if (arrayOfVarInts && arrayOfInts)
  3589. {
  3590. arrayOfInts = false;
  3591. arrayOfNumbers = false;
  3592. }
  3593. *pArrayOfTaggedInts = arrayOfTaggedInts;
  3594. *pArrayOfInts = arrayOfInts;
  3595. *pArrayOfNumbers = arrayOfNumbers;
  3596. *pHasMissingValues = hasMissingValues;
  3597. }
  3598. this->m_arrayDepth--;
  3599. return pnodeList;
  3600. }
  3601. Parser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)
  3602. {
  3603. Assert(pAllocator);
  3604. return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);
  3605. }
  3606. template<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)
  3607. {
  3608. this->GetScanner()->Scan();
  3609. ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);
  3610. if (buildAST)
  3611. {
  3612. *ppnodeName = CreateUniNode(knopComputedName, pnodeNameExpr, pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);
  3613. }
  3614. if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))
  3615. {
  3616. *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);
  3617. }
  3618. ChkCurTokNoScan(tkRBrack, ERRnoRbrack);
  3619. }
  3620. /***************************************************************************
  3621. Parse a list of object set/get members, e.g.:
  3622. { get foo(){ ... }, set bar(arg) { ... } }
  3623. ***************************************************************************/
  3624. template<bool buildAST>
  3625. ParseNodeBin * Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint)
  3626. {
  3627. ParseNodePtr pnodeName = nullptr;
  3628. Assert(nop == knopGetMember || nop == knopSetMember);
  3629. Assert(ppNameHint);
  3630. IdentPtr pid = nullptr;
  3631. bool isComputedName = false;
  3632. *ppNameHint = nullptr;
  3633. switch (m_token.tk)
  3634. {
  3635. default:
  3636. if (!m_token.IsReservedWord())
  3637. {
  3638. Error(ERRnoMemberIdent);
  3639. }
  3640. // fall through
  3641. case tkID:
  3642. pid = m_token.GetIdentifier(this->GetHashTbl());
  3643. *ppNameHint = pid->Psz();
  3644. if (buildAST)
  3645. {
  3646. pnodeName = CreateStrNode(pid);
  3647. }
  3648. break;
  3649. case tkStrCon:
  3650. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3651. {
  3652. Error(ERRES5NoOctal);
  3653. }
  3654. pid = m_token.GetStr();
  3655. *ppNameHint = pid->Psz();
  3656. if (buildAST)
  3657. {
  3658. pnodeName = CreateStrNode(pid);
  3659. }
  3660. break;
  3661. case tkIntCon:
  3662. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3663. {
  3664. Error(ERRES5NoOctal);
  3665. }
  3666. pid = this->GetScanner()->PidFromLong(m_token.GetLong());
  3667. if (buildAST)
  3668. {
  3669. pnodeName = CreateStrNode(pid);
  3670. }
  3671. break;
  3672. case tkFltCon:
  3673. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3674. {
  3675. Error(ERRES5NoOctal);
  3676. }
  3677. pid = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  3678. if (buildAST)
  3679. {
  3680. pnodeName = CreateStrNode(pid);
  3681. }
  3682. break;
  3683. case tkLBrack:
  3684. // Computed property name: get|set [expr] () { }
  3685. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3686. {
  3687. Error(ERRnoMemberIdent);
  3688. }
  3689. LPCOLESTR emptyHint = nullptr;
  3690. uint32 offset = 0;
  3691. ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);
  3692. isComputedName = true;
  3693. break;
  3694. }
  3695. MemberType memberType;
  3696. ushort flags = fFncMethod | fFncNoName;
  3697. if (nop == knopGetMember)
  3698. {
  3699. memberType = MemberTypeGetter;
  3700. flags |= fFncNoArg;
  3701. }
  3702. else
  3703. {
  3704. Assert(nop == knopSetMember);
  3705. memberType = MemberTypeSetter;
  3706. flags |= fFncOneArg;
  3707. }
  3708. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::PropertyAllowed, *ppNameHint,
  3709. /*needsPIDOnRCurlyScan*/ false);
  3710. if (isComputedName)
  3711. {
  3712. pnodeFnc->SetHasComputedName();
  3713. }
  3714. pnodeFnc->SetHasHomeObj();
  3715. if (buildAST)
  3716. {
  3717. pnodeFnc->SetIsAccessor();
  3718. return CreateBinNode(nop, pnodeName, pnodeFnc);
  3719. }
  3720. else
  3721. {
  3722. return nullptr;
  3723. }
  3724. }
  3725. /***************************************************************************
  3726. Parse a list of object members. e.g. { x:foo, 'y me':bar }
  3727. ***************************************************************************/
  3728. template<bool buildAST>
  3729. ParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)
  3730. {
  3731. ParseNodeBin * pnodeArg = nullptr;
  3732. ParseNodePtr pnodeName = nullptr;
  3733. ParseNodePtr pnodeList = nullptr;
  3734. ParseNodePtr *lastNodeRef = nullptr;
  3735. LPCOLESTR pFullNameHint = nullptr; // A calculated full name
  3736. uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;
  3737. uint32 shortNameOffset = 0;
  3738. bool isProtoDeclared = false;
  3739. // we get declaration tkLCurly - when the possible object pattern found under the expression.
  3740. bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();
  3741. // Check for an empty list
  3742. if (tkRCurly == m_token.tk)
  3743. {
  3744. return nullptr;
  3745. }
  3746. ArenaAllocator tempAllocator(_u("MemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  3747. bool hasDeferredInitError = false;
  3748. for (;;)
  3749. {
  3750. bool isComputedName = false;
  3751. #if DEBUG
  3752. if ((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(this->GetScanner()->IsDoubleQuoteOnLastTkStrCon())))
  3753. {
  3754. Error(ERRsyntax);
  3755. }
  3756. #endif
  3757. bool isAsyncMethod = false;
  3758. charcount_t ichMin = 0;
  3759. size_t iecpMin = 0;
  3760. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  3761. {
  3762. RestorePoint parsedAsync;
  3763. this->GetScanner()->Capture(&parsedAsync);
  3764. ichMin = this->GetScanner()->IchMinTok();
  3765. iecpMin = this->GetScanner()->IecpMinTok();
  3766. this->GetScanner()->ScanForcingPid();
  3767. if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || this->GetScanner()->FHadNewLine() || m_token.tk == tkComma)
  3768. {
  3769. this->GetScanner()->SeekTo(parsedAsync);
  3770. }
  3771. else
  3772. {
  3773. isAsyncMethod = true;
  3774. }
  3775. }
  3776. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  3777. m_token.tk == tkStar;
  3778. ushort fncDeclFlags = fFncNoName | fFncMethod;
  3779. if (isGenerator)
  3780. {
  3781. if (isAsyncMethod)
  3782. {
  3783. Error(ERRsyntax);
  3784. }
  3785. // Include star character in the function extents
  3786. ichMin = this->GetScanner()->IchMinTok();
  3787. iecpMin = this->GetScanner()->IecpMinTok();
  3788. this->GetScanner()->ScanForcingPid();
  3789. fncDeclFlags |= fFncGenerator;
  3790. }
  3791. IdentPtr pidHint = nullptr; // A name scoped to current expression
  3792. Token tkHint = m_token;
  3793. charcount_t idHintIchMin = static_cast<charcount_t>(this->GetScanner()->IecpMinTok());
  3794. charcount_t idHintIchLim = static_cast<charcount_t>(this->GetScanner()->IecpLimTok());
  3795. bool wrapInBrackets = false;
  3796. switch (m_token.tk)
  3797. {
  3798. default:
  3799. if (!m_token.IsReservedWord())
  3800. {
  3801. Error(ERRnoMemberIdent);
  3802. }
  3803. // allow reserved words
  3804. wrapInBrackets = true;
  3805. // fall-through
  3806. case tkID:
  3807. pidHint = m_token.GetIdentifier(this->GetHashTbl());
  3808. if (buildAST)
  3809. {
  3810. pnodeName = CreateStrNode(pidHint);
  3811. }
  3812. break;
  3813. case tkStrCon:
  3814. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3815. {
  3816. Error(ERRES5NoOctal);
  3817. }
  3818. wrapInBrackets = true;
  3819. pidHint = m_token.GetStr();
  3820. if (buildAST)
  3821. {
  3822. pnodeName = CreateStrNode(pidHint);
  3823. }
  3824. break;
  3825. case tkIntCon:
  3826. // Object initializers with numeric labels allowed in JS6
  3827. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3828. {
  3829. Error(ERRES5NoOctal);
  3830. }
  3831. pidHint = this->GetScanner()->PidFromLong(m_token.GetLong());
  3832. if (buildAST)
  3833. {
  3834. pnodeName = CreateStrNode(pidHint);
  3835. }
  3836. break;
  3837. case tkFltCon:
  3838. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3839. {
  3840. Error(ERRES5NoOctal);
  3841. }
  3842. pidHint = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  3843. if (buildAST)
  3844. {
  3845. pnodeName = CreateStrNode(pidHint);
  3846. }
  3847. wrapInBrackets = true;
  3848. break;
  3849. case tkLBrack:
  3850. // Computed property name: [expr] : value
  3851. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3852. {
  3853. Error(ERRnoMemberIdent);
  3854. }
  3855. ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3856. isComputedName = true;
  3857. break;
  3858. }
  3859. if (pFullNameHint == nullptr)
  3860. {
  3861. if (CONFIG_FLAG(UseFullName))
  3862. {
  3863. pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);
  3864. }
  3865. else
  3866. {
  3867. pFullNameHint = pidHint ? pidHint->Psz() : nullptr;
  3868. fullNameHintLength = pidHint ? pidHint->Cch() : 0;
  3869. shortNameOffset = 0;
  3870. }
  3871. }
  3872. RestorePoint atPid;
  3873. this->GetScanner()->Capture(&atPid);
  3874. this->GetScanner()->ScanForcingPid();
  3875. if (isGenerator && m_token.tk != tkLParen)
  3876. {
  3877. Error(ERRnoLparen);
  3878. }
  3879. if (tkColon == m_token.tk)
  3880. {
  3881. // It is a syntax error is the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.
  3882. // Note that previous scan is important because only after that we can determine we have a variable.
  3883. if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)
  3884. {
  3885. if (isProtoDeclared)
  3886. {
  3887. Error(ERRsyntax);
  3888. }
  3889. else
  3890. {
  3891. isProtoDeclared = true;
  3892. }
  3893. }
  3894. this->GetScanner()->Scan();
  3895. ParseNodePtr pnodeExpr = nullptr;
  3896. if (isObjectPattern)
  3897. {
  3898. if (m_token.tk == tkEllipsis)
  3899. {
  3900. Error(ERRUnexpectedEllipsis);
  3901. }
  3902. RestorePoint atExpression;
  3903. if (!buildAST && declarationType == tkLCurly && IsPossiblePatternStart())
  3904. {
  3905. this->GetScanner()->Capture(&atExpression);
  3906. int saveNextBlockId = m_nextBlockId;
  3907. // It is possible that we might encounter the shorthand init error. Lets find that out.
  3908. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  3909. m_hasDeferredShorthandInitError = false;
  3910. IdentToken token;
  3911. BOOL fLikelyPattern = false;
  3912. // First identify that the current expression is indeed the object/array literal. Otherwise we will just use the ParsrExpr to parse that.
  3913. ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false /*fUnaryOrParen*/,
  3914. TRUE, nullptr /*pfCanAssign*/, &fLikelyPattern);
  3915. m_nextBlockId = saveNextBlockId;
  3916. this->GetScanner()->SeekTo(atExpression);
  3917. if (fLikelyPattern)
  3918. {
  3919. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3920. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3921. {
  3922. if (m_token.IsOperator())
  3923. {
  3924. Error(ERRDestructNoOper);
  3925. }
  3926. Error(ERRsyntax);
  3927. }
  3928. }
  3929. else
  3930. {
  3931. if (m_hasDeferredShorthandInitError)
  3932. {
  3933. Error(ERRnoColon);
  3934. }
  3935. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3936. }
  3937. m_hasDeferredShorthandInitError = savedDeferredInitError;
  3938. }
  3939. else
  3940. {
  3941. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3942. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3943. {
  3944. if (m_token.IsOperator())
  3945. {
  3946. Error(ERRDestructNoOper);
  3947. }
  3948. Error(ERRsyntax);
  3949. }
  3950. }
  3951. }
  3952. else
  3953. {
  3954. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3955. if (pnodeExpr && pnodeExpr->nop == knopFncDecl)
  3956. {
  3957. ParseNodeFnc* funcNode = pnodeExpr->AsParseNodeFnc();
  3958. if (isComputedName)
  3959. {
  3960. funcNode->SetHasComputedName();
  3961. }
  3962. funcNode->SetHasHomeObj();
  3963. }
  3964. }
  3965. #if DEBUG
  3966. if ((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))
  3967. {
  3968. Error(ERRsyntax);
  3969. }
  3970. #endif
  3971. if (buildAST)
  3972. {
  3973. pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);
  3974. if (pnodeArg->pnode1->nop == knopStr)
  3975. {
  3976. pnodeArg->pnode1->AsParseNodeStr()->pid->PromoteAssignmentState();
  3977. }
  3978. }
  3979. }
  3980. else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3981. {
  3982. if (isObjectPattern)
  3983. {
  3984. Error(ERRInvalidAssignmentTarget);
  3985. }
  3986. // Shorthand syntax: foo() {} -> foo: function() {}
  3987. // Rewind to the PID and parse a function expression.
  3988. this->GetScanner()->SeekTo(atPid);
  3989. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), SuperRestrictionState::PropertyAllowed, pFullNameHint,
  3990. /*needsPIDOnRCurlyScan*/ false);
  3991. if (isAsyncMethod || isGenerator)
  3992. {
  3993. pnodeFnc->cbMin = iecpMin;
  3994. pnodeFnc->ichMin = ichMin;
  3995. }
  3996. if (isComputedName)
  3997. {
  3998. pnodeFnc->SetHasComputedName();
  3999. }
  4000. pnodeFnc->SetHasHomeObj();
  4001. if (buildAST)
  4002. {
  4003. pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFnc);
  4004. }
  4005. }
  4006. else if (nullptr != pidHint) //Its either tkID/tkStrCon/tkFloatCon/tkIntCon
  4007. {
  4008. Assert(pidHint->Psz() != nullptr);
  4009. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&
  4010. // get/set are only pseudo keywords when they are identifiers (i.e. not strings)
  4011. tkHint.tk == tkID && NextTokenIsPropertyNameStart())
  4012. {
  4013. if (isObjectPattern)
  4014. {
  4015. Error(ERRInvalidAssignmentTarget);
  4016. }
  4017. LPCOLESTR pNameGetOrSet = nullptr;
  4018. OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;
  4019. pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet);
  4020. if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->pnode2->nop == knopFncDecl)
  4021. {
  4022. // displays as "get object.funcname" or "set object.funcname"
  4023. uint32 getOrSetOffset = 0;
  4024. LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);
  4025. pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);
  4026. shortNameOffset += getOrSetOffset;
  4027. }
  4028. }
  4029. else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4030. {
  4031. // Shorthand {foo} -> {foo:foo} syntax.
  4032. // {foo = <initializer>} supported only when on object pattern rules are being applied
  4033. if (tkHint.tk != tkID)
  4034. {
  4035. Assert(tkHint.IsReservedWord()
  4036. || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);
  4037. // All keywords are banned in non-strict mode.
  4038. // Future reserved words are banned in strict mode.
  4039. if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))
  4040. {
  4041. IdentifierExpectedError(tkHint);
  4042. }
  4043. }
  4044. CheckArgumentsUse(pidHint, GetCurrentFunctionNode());
  4045. bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;
  4046. // Saving the current state as we may change the isObjectPattern down below.
  4047. bool oldState = isObjectPattern;
  4048. if (couldBeObjectPattern)
  4049. {
  4050. declarationType = tkLCurly;
  4051. isObjectPattern = true;
  4052. // This may be an error but we are deferring for favouring destructuring.
  4053. hasDeferredInitError = true;
  4054. }
  4055. ParseNodePtr pnodeIdent = nullptr;
  4056. if (isObjectPattern)
  4057. {
  4058. this->GetScanner()->SeekTo(atPid);
  4059. pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  4060. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4061. {
  4062. if (m_token.IsOperator())
  4063. {
  4064. Error(ERRDestructNoOper);
  4065. }
  4066. Error(ERRsyntax);
  4067. }
  4068. }
  4069. else
  4070. {
  4071. // Add a reference to the hinted name so we can bind it properly.
  4072. PidRefStack *ref = PushPidRef(pidHint);
  4073. if (buildAST)
  4074. {
  4075. pnodeIdent = CreateNameNode(pidHint, ref, idHintIchMin, idHintIchLim);
  4076. }
  4077. }
  4078. if (buildAST)
  4079. {
  4080. pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);
  4081. }
  4082. isObjectPattern = oldState;
  4083. }
  4084. else
  4085. {
  4086. Error(ERRnoColon);
  4087. }
  4088. }
  4089. else
  4090. {
  4091. Error(ERRnoColon);
  4092. }
  4093. if (buildAST)
  4094. {
  4095. Assert(pnodeArg->pnode2 != nullptr);
  4096. if (pnodeArg->pnode2->nop == knopFncDecl)
  4097. {
  4098. Assert(fullNameHintLength >= shortNameOffset);
  4099. ParseNodeFnc * pnodeFunc = pnodeArg->pnode2->AsParseNodeFnc();
  4100. pnodeFunc->hint = pFullNameHint;
  4101. pnodeFunc->hintLength = fullNameHintLength;
  4102. pnodeFunc->hintOffset = shortNameOffset;
  4103. }
  4104. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  4105. }
  4106. pidHint = nullptr;
  4107. pFullNameHint = nullptr;
  4108. if (tkComma != m_token.tk)
  4109. {
  4110. break;
  4111. }
  4112. this->GetScanner()->ScanForcingPid();
  4113. if (tkRCurly == m_token.tk)
  4114. {
  4115. break;
  4116. }
  4117. }
  4118. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;
  4119. if (buildAST)
  4120. {
  4121. Assert(lastNodeRef);
  4122. Assert(*lastNodeRef);
  4123. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  4124. }
  4125. return pnodeList;
  4126. }
  4127. BOOL Parser::WillDeferParse(Js::LocalFunctionId functionId)
  4128. {
  4129. if ((m_grfscr & fscrWillDeferFncParse) != 0)
  4130. {
  4131. if (m_stoppedDeferredParse)
  4132. {
  4133. return false;
  4134. }
  4135. if (!PHASE_ENABLED_RAW(DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))
  4136. {
  4137. return false;
  4138. }
  4139. if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId)
  4140. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4141. || Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag)
  4142. #endif
  4143. )
  4144. {
  4145. return true;
  4146. }
  4147. #if ENABLE_PROFILE_INFO
  4148. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4149. if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)
  4150. {
  4151. Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);
  4152. return flags != Js::ExecutionFlags_Executed;
  4153. }
  4154. #endif
  4155. #endif
  4156. return true;
  4157. }
  4158. return false;
  4159. }
  4160. //
  4161. // Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred
  4162. // function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.
  4163. //
  4164. BOOL Parser::IsDeferredFnc()
  4165. {
  4166. if (m_grfscr & fscrDeferredFnc)
  4167. {
  4168. m_grfscr &= ~fscrDeferredFnc;
  4169. return true;
  4170. }
  4171. return false;
  4172. }
  4173. template<bool buildAST>
  4174. ParseNode * Parser::ParseFncDeclCheckScope(ushort flags, bool fAllowIn)
  4175. {
  4176. ParseNodeBlock * pnodeFncBlockScope = nullptr;
  4177. ParseNodePtr *ppnodeScopeSave = nullptr;
  4178. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4179. bool fDeclaration = flags & fFncDeclaration;
  4180. bool noStmtContext = false;
  4181. if (fDeclaration)
  4182. {
  4183. noStmtContext = m_pstmtCur->GetNop() != knopBlock;
  4184. if (noStmtContext)
  4185. {
  4186. // We have a function declaration like "if (a) function f() {}". We didn't see
  4187. // a block scope on the way in, so we need to pretend we did. Note that this is a syntax error
  4188. // in strict mode.
  4189. if (!this->FncDeclAllowedWithoutContext(flags))
  4190. {
  4191. Error(ERRsyntax);
  4192. }
  4193. pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  4194. if (buildAST)
  4195. {
  4196. PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);
  4197. }
  4198. }
  4199. }
  4200. ParseNodeFnc * pnodeFnc = ParseFncDeclInternal<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan */ false, /* fUnaryOrParen */ false, noStmtContext, SuperRestrictionState::Disallowed, fAllowIn);
  4201. if (pnodeFncBlockScope)
  4202. {
  4203. Assert(pnodeFncBlockScope->pnodeStmt == nullptr);
  4204. pnodeFncBlockScope->pnodeStmt = pnodeFnc;
  4205. if (buildAST)
  4206. {
  4207. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  4208. }
  4209. FinishParseBlock(pnodeFncBlockScope);
  4210. return pnodeFncBlockScope;
  4211. }
  4212. return pnodeFnc;
  4213. }
  4214. template<bool buildAST>
  4215. ParseNodeFnc * Parser::ParseFncDeclNoCheckScope(ushort flags, SuperRestrictionState::State superRestrictionState, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool fUnaryOrParen, bool fAllowIn)
  4216. {
  4217. Assert((flags & fFncDeclaration) == 0 || m_pstmtCur->GetNop() == knopBlock);
  4218. return ParseFncDeclInternal<buildAST>(flags, pNameHint, needsPIDOnRCurlyScan, fUnaryOrParen, /* noStmtContext */ false, superRestrictionState, fAllowIn);
  4219. }
  4220. template<bool buildAST>
  4221. ParseNodeFnc * Parser::ParseFncDeclInternal(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool fUnaryOrParen, bool noStmtContext, SuperRestrictionState::State superRestrictionState, bool fAllowIn)
  4222. {
  4223. ParseNodeFnc * pnodeFnc = nullptr;
  4224. ParseNodePtr *ppnodeVarSave = nullptr;
  4225. bool fDeclaration = flags & fFncDeclaration;
  4226. bool fModule = (flags & fFncModule) != 0;
  4227. bool fLambda = (flags & fFncLambda) != 0;
  4228. charcount_t ichMin = this->GetScanner()->IchMinTok();
  4229. bool wasInDeferredNestedFunc = false;
  4230. uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;
  4231. this->m_tryCatchOrFinallyDepth = 0;
  4232. if (this->m_arrayDepth)
  4233. {
  4234. this->m_funcInArrayDepth++; // Count function depth within array literal
  4235. }
  4236. // Update the count of functions nested in the current parent.
  4237. Assert(m_pnestedCount || !buildAST);
  4238. uint *pnestedCountSave = m_pnestedCount;
  4239. if (buildAST || m_pnestedCount)
  4240. {
  4241. (*m_pnestedCount)++;
  4242. }
  4243. uint scopeCountNoAstSave = m_scopeCountNoAst;
  4244. m_scopeCountNoAst = 0;
  4245. // Create the node.
  4246. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  4247. pnodeFnc->SetDeclaration(fDeclaration);
  4248. pnodeFnc->nestedFuncEscapes = false;
  4249. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  4250. pnodeFnc->functionId = (*m_nextFunctionId)++;
  4251. pnodeFnc->superRestrictionState = superRestrictionState;
  4252. // Push new parser state with this new function node
  4253. AppendFunctionToScopeList(fDeclaration, pnodeFnc);
  4254. // Start the argument list.
  4255. ppnodeVarSave = m_ppnodeVar;
  4256. if (buildAST)
  4257. {
  4258. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  4259. pnodeFnc->columnNumber = CalculateFunctionColumnNumber();
  4260. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  4261. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  4262. m_pCurrentAstSize = &pnodeFnc->astSize;
  4263. }
  4264. else // if !buildAST
  4265. {
  4266. wasInDeferredNestedFunc = m_inDeferredNestedFunc;
  4267. m_inDeferredNestedFunc = true;
  4268. }
  4269. m_pnestedCount = &pnodeFnc->nestedCount;
  4270. AnalysisAssert(pnodeFnc);
  4271. pnodeFnc->SetIsAsync((flags & fFncAsync) != 0);
  4272. pnodeFnc->SetIsLambda(fLambda);
  4273. pnodeFnc->SetIsMethod((flags & fFncMethod) != 0);
  4274. pnodeFnc->SetIsClassMember((flags & fFncClassMember) != 0);
  4275. pnodeFnc->SetIsModule(fModule);
  4276. pnodeFnc->SetIsClassConstructor((flags & fFncClassConstructor) != 0);
  4277. pnodeFnc->SetIsBaseClassConstructor((flags & fFncBaseClassConstructor) != 0);
  4278. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  4279. if (this->m_currentScope && this->m_currentScope->GetScopeType() == ScopeType_Parameter)
  4280. {
  4281. pnodeFnc->SetIsDeclaredInParamScope();
  4282. this->m_currentScope->SetHasNestedParamFunc();
  4283. }
  4284. IdentPtr pFncNamePid = nullptr;
  4285. bool needScanRCurly = true;
  4286. ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule, &pFncNamePid, fAllowIn);
  4287. AddNestedCapturedNames(pnodeFnc);
  4288. AnalysisAssert(pnodeFnc);
  4289. *m_ppnodeVar = nullptr;
  4290. m_ppnodeVar = ppnodeVarSave;
  4291. if (m_currentNodeFunc && (pnodeFnc->CallsEval() || pnodeFnc->ChildCallsEval()))
  4292. {
  4293. GetCurrentFunctionNode()->SetChildCallsEval(true);
  4294. }
  4295. // Lambdas do not have "arguments" and instead capture their parent's
  4296. // binding of "arguments. To ensure the arguments object of the enclosing
  4297. // non-lambda function is loaded propagate the UsesArguments flag up to
  4298. // the parent function
  4299. if (fLambda && (pnodeFnc->UsesArguments() || pnodeFnc->CallsEval()))
  4300. {
  4301. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4302. if (pnodeFncParent != nullptr)
  4303. {
  4304. pnodeFncParent->SetUsesArguments();
  4305. }
  4306. else
  4307. {
  4308. m_UsesArgumentsAtGlobal = true;
  4309. }
  4310. }
  4311. if (needScanRCurly && !fModule)
  4312. {
  4313. // Consume the next token now that we're back in the enclosing function (whose strictness may be
  4314. // different from the function we just finished).
  4315. #if DBG
  4316. bool expectedTokenValid = m_token.tk == tkRCurly;
  4317. AssertMsg(expectedTokenValid, "Invalid token expected for RCurly match");
  4318. #endif
  4319. // The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.
  4320. if (needsPIDOnRCurlyScan)
  4321. {
  4322. this->GetScanner()->ScanForcingPid();
  4323. }
  4324. else
  4325. {
  4326. this->GetScanner()->Scan();
  4327. }
  4328. }
  4329. m_pnestedCount = pnestedCountSave;
  4330. Assert(!buildAST || !wasInDeferredNestedFunc);
  4331. m_inDeferredNestedFunc = wasInDeferredNestedFunc;
  4332. if (this->m_arrayDepth)
  4333. {
  4334. this->m_funcInArrayDepth--;
  4335. if (this->m_funcInArrayDepth == 0)
  4336. {
  4337. // We disable deferred parsing if array literals dominate.
  4338. // But don't do this if the array literal is dominated by function bodies.
  4339. if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)
  4340. {
  4341. // Class member methods have optional separators. We need to check whether we are
  4342. // getting the IchLim of the correct token.
  4343. Assert(this->GetScanner()->m_tkPrevious == tkRCurly && needScanRCurly);
  4344. this->m_funcInArray += this->GetScanner()->IchMinTok() - /*tkRCurly*/ 1 - ichMin;
  4345. }
  4346. else
  4347. {
  4348. this->m_funcInArray += this->GetScanner()->IchLimTok() - ichMin;
  4349. }
  4350. }
  4351. }
  4352. m_scopeCountNoAst = scopeCountNoAstSave;
  4353. if (fDeclaration && !IsStrictMode())
  4354. {
  4355. if (pFncNamePid != nullptr &&
  4356. GetCurrentBlock() &&
  4357. GetCurrentBlock()->blockType == PnodeBlockType::Regular)
  4358. {
  4359. // Add a function-scoped VarDecl with the same name as the function for
  4360. // back compat with pre-ES6 code that declares functions in blocks. The
  4361. // idea is that the last executed declaration wins at the function scope
  4362. // level and we accomplish this by having each block scoped function
  4363. // declaration assign to both the block scoped "let" binding, as well
  4364. // as the function scoped "var" binding.
  4365. ParseNodeVar * vardecl = CreateVarDeclNode(pFncNamePid, STVariable, false, nullptr, false);
  4366. vardecl->isBlockScopeFncDeclVar = true;
  4367. if (GetCurrentFunctionNode() && vardecl->sym->GetIsFormal())
  4368. {
  4369. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4370. }
  4371. }
  4372. }
  4373. if (buildAST && fDeclaration)
  4374. {
  4375. Symbol* funcSym = pnodeFnc->GetFuncSymbol();
  4376. if (funcSym->GetIsFormal())
  4377. {
  4378. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4379. }
  4380. } this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;
  4381. return pnodeFnc;
  4382. }
  4383. bool Parser::FncDeclAllowedWithoutContext(ushort flags)
  4384. {
  4385. // Statement context required for strict mode, async functions, and generators.
  4386. // Note that generators aren't detected yet when this method is called; they're checked elsewhere.
  4387. return !IsStrictMode() && !(flags & fFncAsync);
  4388. }
  4389. uint Parser::CalculateFunctionColumnNumber()
  4390. {
  4391. uint columnNumber;
  4392. charcount_t ichMinTok = this->GetScanner()->IchMinTok();
  4393. charcount_t ichMinLine = this->GetScanner()->IchMinLine();
  4394. if (ichMinTok >= ichMinLine)
  4395. {
  4396. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  4397. columnNumber = ichMinTok - ichMinLine;
  4398. if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == this->GetScanner()->LineCur())
  4399. {
  4400. // Adjust the column if it falls on the first line, where the re-parse is happening.
  4401. columnNumber += m_functionBody->GetRelativeColumnNumber();
  4402. }
  4403. }
  4404. else if (m_currentNodeFunc)
  4405. {
  4406. // For the first line after defer parse, compute the column relative to the column number
  4407. // of the lexically parent function.
  4408. ULONG offsetFromCurrentFunction = ichMinTok - m_currentNodeFunc->ichMin;
  4409. columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  4410. }
  4411. else
  4412. {
  4413. // if there is no current function, lets give a default of 0.
  4414. columnNumber = 0;
  4415. }
  4416. return columnNumber;
  4417. }
  4418. void Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodeFnc * pnodeFnc)
  4419. {
  4420. if (!fDeclaration && m_ppnodeExprScope)
  4421. {
  4422. // We're tracking function expressions separately from declarations in this scope
  4423. // (e.g., inside a catch scope in standards mode).
  4424. Assert(*m_ppnodeExprScope == nullptr);
  4425. *m_ppnodeExprScope = pnodeFnc;
  4426. m_ppnodeExprScope = &pnodeFnc->pnodeNext;
  4427. }
  4428. else
  4429. {
  4430. Assert(*m_ppnodeScope == nullptr);
  4431. *m_ppnodeScope = pnodeFnc;
  4432. m_ppnodeScope = &pnodeFnc->pnodeNext;
  4433. }
  4434. }
  4435. /***************************************************************************
  4436. Parse a function definition.
  4437. ***************************************************************************/
  4438. template<bool buildAST>
  4439. void Parser::ParseFncDeclHelper(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals, IdentPtr* pFncNamePid, bool fAllowIn)
  4440. {
  4441. Assert(pnodeFnc);
  4442. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4443. // is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred
  4444. ParseNodeFnc * pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4445. ParseNodeFnc * pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;
  4446. int32* pAstSizeSave = m_pCurrentAstSize;
  4447. bool fDeclaration = (flags & fFncDeclaration) != 0;
  4448. bool fLambda = (flags & fFncLambda) != 0;
  4449. bool fAsync = (flags & fFncAsync) != 0;
  4450. bool fModule = (flags & fFncModule) != 0;
  4451. bool fDeferred = false;
  4452. StmtNest *pstmtSave;
  4453. bool fFunctionInBlock = false;
  4454. if (buildAST)
  4455. {
  4456. fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&
  4457. (GetCurrentBlockInfo()->pnodeBlock->scope == nullptr ||
  4458. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock);
  4459. }
  4460. // Save the position of the scanner in case we need to inspect the name hint later
  4461. RestorePoint beginNameHint;
  4462. this->GetScanner()->Capture(&beginNameHint);
  4463. ParseNodeBlock * pnodeFncExprScope = nullptr;
  4464. Scope *fncExprScope = nullptr;
  4465. if (!fDeclaration)
  4466. {
  4467. if (!fLambda)
  4468. {
  4469. pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);
  4470. fncExprScope = pnodeFncExprScope->scope;
  4471. }
  4472. // Function expression: push the new function onto the stack now so that the name (if any) will be
  4473. // local to the new function.
  4474. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4475. }
  4476. if (!fLambda && !fModule)
  4477. {
  4478. this->ParseFncName<buildAST>(pnodeFnc, flags, pFncNamePid);
  4479. }
  4480. if (fDeclaration)
  4481. {
  4482. // Declaration statement: push the new function now, after parsing the name, so the name is local to the
  4483. // enclosing function.
  4484. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4485. }
  4486. if (noStmtContext && pnodeFnc->IsGenerator())
  4487. {
  4488. // Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to
  4489. // detect generator.)
  4490. Error(ERRsyntax, pnodeFnc);
  4491. }
  4492. // switch scanner to treat 'yield' as keyword in generator functions
  4493. // or as an identifier in non-generator functions
  4494. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc->IsGenerator());
  4495. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync);
  4496. if (pnodeFnc->IsGenerator())
  4497. {
  4498. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Generator, m_scriptContext);
  4499. }
  4500. if (fncExprScope && pnodeFnc->pnodeName == nullptr)
  4501. {
  4502. FinishParseBlock(pnodeFncExprScope);
  4503. m_nextBlockId--;
  4504. Adelete(&m_nodeAllocator, fncExprScope);
  4505. fncExprScope = nullptr;
  4506. pnodeFncExprScope = nullptr;
  4507. }
  4508. pnodeFnc->scope = fncExprScope;
  4509. // Start a new statement stack.
  4510. bool topLevelStmt =
  4511. buildAST &&
  4512. !fFunctionInBlock &&
  4513. (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);
  4514. pstmtSave = m_pstmtCur;
  4515. SetCurrentStatement(nullptr);
  4516. RestorePoint beginFormals;
  4517. this->GetScanner()->Capture(&beginFormals);
  4518. BOOL fWasAlreadyStrictMode = IsStrictMode();
  4519. BOOL oldStrictMode = this->m_fUseStrictMode;
  4520. if (fLambda)
  4521. {
  4522. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Lambda, m_scriptContext);
  4523. }
  4524. uint uCanDeferSave = m_grfscr & fscrCanDeferFncParse;
  4525. uint uDeferSave = m_grfscr & fscrWillDeferFncParse;
  4526. if (flags & fFncClassMember)
  4527. {
  4528. // Disable deferral on class members or other construct with unusual text bounds
  4529. // as these are usually trivial, and re-parsing is problematic.
  4530. // NOTE: It is probably worth supporting these cases for memory and load-time purposes,
  4531. // especially as they become more and more common.
  4532. m_grfscr &= ~(fscrCanDeferFncParse | fscrWillDeferFncParse);
  4533. }
  4534. bool isTopLevelDeferredFunc = false;
  4535. #if ENABLE_BACKGROUND_PARSING
  4536. struct AutoFastScanFlag {
  4537. bool savedDoingFastScan;
  4538. AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }
  4539. ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }
  4540. Parser *m_parser;
  4541. } flag(this);
  4542. #endif
  4543. bool doParallel = false;
  4544. #if ENABLE_BACKGROUND_PARSING
  4545. bool parallelJobStarted = false;
  4546. #endif
  4547. if (buildAST)
  4548. {
  4549. bool isLikelyIIFE = !fDeclaration && fUnaryOrParen;
  4550. BOOL isDeferredFnc = IsDeferredFnc();
  4551. // These are the conditions that prohibit upfront deferral *and* redeferral.
  4552. isTopLevelDeferredFunc =
  4553. (m_grfscr & fscrCanDeferFncParse)
  4554. && !m_InAsmMode
  4555. // Don't defer a module function wrapper because we need to do export resolution at parse time
  4556. && !fModule;
  4557. pnodeFnc->SetCanBeDeferred(isTopLevelDeferredFunc && ParseNodeFnc::CanBeRedeferred(pnodeFnc->fncFlags));
  4558. // These are heuristic conditions that prohibit upfront deferral but not redeferral.
  4559. isTopLevelDeferredFunc = isTopLevelDeferredFunc && !isDeferredFnc && WillDeferParse(pnodeFnc->functionId) &&
  4560. (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId));
  4561. #if ENABLE_BACKGROUND_PARSING
  4562. if (!fLambda &&
  4563. !isDeferredFnc &&
  4564. !isLikelyIIFE &&
  4565. !this->IsBackgroundParser() &&
  4566. !this->m_doingFastScan &&
  4567. !(pnodeFncSave && m_currDeferredStub) &&
  4568. !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))
  4569. {
  4570. doParallel = DoParallelParse(pnodeFnc);
  4571. if (doParallel)
  4572. {
  4573. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  4574. Assert(bgp);
  4575. if (bgp->HasFailedBackgroundParseItem())
  4576. {
  4577. Error(ERRsyntax);
  4578. }
  4579. doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);
  4580. if (doParallel)
  4581. {
  4582. parallelJobStarted = true;
  4583. this->m_hasParallelJob = true;
  4584. this->m_doingFastScan = true;
  4585. doParallel = FastScanFormalsAndBody();
  4586. if (doParallel)
  4587. {
  4588. // Let the foreground thread take care of marking the limit on the function node,
  4589. // because in some cases this function's caller will want to change that limit,
  4590. // so we don't want the background thread to try and touch it.
  4591. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  4592. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  4593. }
  4594. }
  4595. }
  4596. }
  4597. #endif
  4598. }
  4599. if (!doParallel)
  4600. {
  4601. #if ENABLE_BACKGROUND_PARSING
  4602. // We don't want to, or couldn't, let the main thread scan past this function body, so parse
  4603. // it for real.
  4604. ParseNodeFnc * pnodeRealFnc = pnodeFnc;
  4605. if (parallelJobStarted)
  4606. {
  4607. // We have to deal with a failure to fast-scan the function (due to syntax error? "/"?) when
  4608. // a background thread may already have begun to work on the job. Both threads can't be allowed to
  4609. // operate on the same node.
  4610. pnodeFnc = CreateDummyFuncNode(fDeclaration);
  4611. }
  4612. #endif
  4613. AnalysisAssert(pnodeFnc);
  4614. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  4615. AnalysisAssert(pnodeBlock != nullptr);
  4616. pnodeFnc->pnodeScopes = pnodeBlock;
  4617. m_ppnodeVar = &pnodeFnc->pnodeParams;
  4618. pnodeFnc->pnodeVars = nullptr;
  4619. ParseNodePtr* varNodesList = &pnodeFnc->pnodeVars;
  4620. ParseNodeVar * argNode = nullptr;
  4621. if (!fModule && !fLambda)
  4622. {
  4623. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  4624. m_ppnodeVar = &pnodeFnc->pnodeVars;
  4625. // Create the built-in arguments symbol
  4626. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  4627. // Save the updated var list
  4628. varNodesList = m_ppnodeVar;
  4629. m_ppnodeVar = ppnodeVarSave;
  4630. }
  4631. ParseNodePtr *ppnodeScopeSave = nullptr;
  4632. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4633. ppnodeScopeSave = m_ppnodeScope;
  4634. if (pnodeBlock)
  4635. {
  4636. // This synthetic block scope will contain all the nested scopes.
  4637. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  4638. pnodeBlock->pnodeStmt = pnodeFnc;
  4639. }
  4640. // Keep nested function declarations and expressions in the same list at function scope.
  4641. // (Indicate this by nulling out the current function expressions list.)
  4642. ppnodeExprScopeSave = m_ppnodeExprScope;
  4643. m_ppnodeExprScope = nullptr;
  4644. uint parenExprDepthSave = m_funcParenExprDepth;
  4645. m_funcParenExprDepth = 0;
  4646. if (!skipFormals)
  4647. {
  4648. bool fLambdaParamsSave = m_reparsingLambdaParams;
  4649. if (fLambda)
  4650. {
  4651. m_reparsingLambdaParams = true;
  4652. }
  4653. DeferredFunctionStub* savedDeferredStub = m_currDeferredStub;
  4654. m_currDeferredStub = nullptr;
  4655. this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags, isTopLevelDeferredFunc);
  4656. m_currDeferredStub = savedDeferredStub;
  4657. m_reparsingLambdaParams = fLambdaParamsSave;
  4658. }
  4659. // Create function body scope
  4660. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  4661. // Set the parameter block's child to the function body block.
  4662. // The pnodeFnc->pnodeScopes list is constructed in such a way that it includes all the scopes in this list.
  4663. // For example if the param scope has one function and body scope has one function then the list will look like below,
  4664. // param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.
  4665. *m_ppnodeScope = pnodeInnerBlock;
  4666. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  4667. // This synthetic block scope will contain all the nested scopes.
  4668. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  4669. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  4670. // DEFER: Begin deferral here (after names are parsed and name nodes created).
  4671. // Create no more AST nodes until we're done.
  4672. // Try to defer this func if all these are true:
  4673. // 0. We are not already in deferred parsing (i.e. buildAST is true)
  4674. // 1. We are not re-parsing a deferred func which is being invoked.
  4675. // 2. Dynamic profile suggests this func can be deferred (and deferred parse is on).
  4676. // 3. This func is top level or defer nested func is on.
  4677. // 4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,
  4678. // or the function is sufficiently long. (I.e., don't defer little nested functions unless we're
  4679. // confident they'll never be executed, because un-deferring nested functions is more expensive.)
  4680. // NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,
  4681. // and we don't want to create function bodies aggressively for little functions.
  4682. // We will also temporarily defer all asm.js functions, except for the asm.js
  4683. // module itself, which we will never defer
  4684. bool strictModeTurnedOn = false;
  4685. if (isTopLevelDeferredFunc &&
  4686. !(this->m_grfscr & fscrEvalCode) &&
  4687. pnodeFnc->IsNested() &&
  4688. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4689. m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&
  4690. #endif
  4691. PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) &&
  4692. (
  4693. !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) ||
  4694. PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId)
  4695. ))
  4696. {
  4697. // Try to scan ahead to the end of the function. If we get there before we've scanned a minimum
  4698. // number of tokens, don't bother deferring, because it's too small.
  4699. if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))
  4700. {
  4701. isTopLevelDeferredFunc = false;
  4702. }
  4703. }
  4704. Scope* paramScope = pnodeFnc->pnodeScopes ? pnodeFnc->pnodeScopes->scope : nullptr;
  4705. if (paramScope != nullptr)
  4706. {
  4707. if (CONFIG_FLAG(ForceSplitScope))
  4708. {
  4709. pnodeFnc->ResetBodyAndParamScopeMerged();
  4710. }
  4711. else if (pnodeFnc->HasNonSimpleParameterList() && pnodeFnc->IsBodyAndParamScopeMerged())
  4712. {
  4713. paramScope->ForEachSymbolUntil([this, paramScope, pnodeFnc](Symbol* sym) {
  4714. if (sym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  4715. {
  4716. // One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.
  4717. pnodeFnc->ResetBodyAndParamScopeMerged();
  4718. return true;
  4719. }
  4720. return false;
  4721. });
  4722. }
  4723. }
  4724. // If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.
  4725. // So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice
  4726. // in the same pid ref stack.
  4727. if (paramScope != nullptr && pnodeFnc->IsBodyAndParamScopeMerged())
  4728. {
  4729. paramScope->ForEachSymbol([this](Symbol* paramSym)
  4730. {
  4731. PidRefStack* ref = PushPidRef(paramSym->GetPid());
  4732. ref->SetSym(paramSym);
  4733. });
  4734. }
  4735. AssertMsg(m_funcParenExprDepth == 0, "Paren exprs should have been resolved by the time we finish function formals");
  4736. if (fLambda)
  4737. {
  4738. #ifdef ASMJS_PLAT
  4739. if (m_InAsmMode && (isTopLevelDeferredFunc && m_deferAsmJs))
  4740. {
  4741. // asm.js doesn't support lambda functions
  4742. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Lambda functions are not supported."));
  4743. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Asm.js compilation failed."));
  4744. throw Js::AsmJsParseException();
  4745. }
  4746. #endif
  4747. }
  4748. if (m_token.tk == tkRParen)
  4749. {
  4750. this->GetScanner()->Scan();
  4751. }
  4752. if (fLambda)
  4753. {
  4754. BOOL hadNewLine = this->GetScanner()->FHadNewLine();
  4755. // it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side
  4756. // of the fat arrow, but that expression does not parse as a parameter list. E.g.
  4757. // a.x => { }
  4758. // Therefore check for it and error if not found.
  4759. ChkCurTok(tkDArrow, ERRnoDArrow);
  4760. // Newline character between arrow parameters and fat arrow is a syntax error but we want to check for
  4761. // this after verifying there was a => token. Otherwise we would throw the wrong error.
  4762. if (hadNewLine)
  4763. {
  4764. Error(ERRsyntax);
  4765. }
  4766. }
  4767. if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))
  4768. {
  4769. fDeferred = true;
  4770. this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint, fLambda, pNeedScanRCurly, fAllowIn);
  4771. }
  4772. else
  4773. {
  4774. AnalysisAssert(pnodeFnc);
  4775. // Shouldn't be any temps in the arg list.
  4776. Assert(*m_ppnodeVar == nullptr);
  4777. // Start the var list.
  4778. m_ppnodeVar = varNodesList;
  4779. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  4780. {
  4781. 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"));
  4782. }
  4783. // Keep nested function declarations and expressions in the same list at function scope.
  4784. // (Indicate this by nulling out the current function expressions list.)
  4785. m_ppnodeExprScope = nullptr;
  4786. if (buildAST)
  4787. {
  4788. if (m_token.tk != tkLCurly && fLambda)
  4789. {
  4790. *pNeedScanRCurly = false;
  4791. }
  4792. uint savedStubCount = m_currDeferredStubCount;
  4793. DeferredFunctionStub* savedStub = m_currDeferredStub;
  4794. if (pnodeFnc->IsNested() && pnodeFncSave != nullptr && m_currDeferredStub != nullptr && pnodeFncSave->ichMin != pnodeFnc->ichMin)
  4795. {
  4796. DeferredFunctionStub* childStub = m_currDeferredStub + (pnodeFncSave->nestedCount - 1);
  4797. m_currDeferredStubCount = childStub->nestedCount;
  4798. m_currDeferredStub = childStub->deferredStubs;
  4799. }
  4800. this->FinishFncDecl(pnodeFnc, pNameHint, fLambda, skipFormals, fAllowIn);
  4801. m_currDeferredStub = savedStub;
  4802. m_currDeferredStubCount = savedStubCount;
  4803. }
  4804. else
  4805. {
  4806. this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn, fAllowIn);
  4807. }
  4808. }
  4809. // Restore the paren count for any outer spread/rest error checking.
  4810. m_funcParenExprDepth = parenExprDepthSave;
  4811. if (pnodeInnerBlock)
  4812. {
  4813. FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);
  4814. }
  4815. if (!fModule && (m_token.tk == tkLCurly || !fLambda))
  4816. {
  4817. UpdateArgumentsNode(pnodeFnc, argNode);
  4818. }
  4819. CreateSpecialSymbolDeclarations(pnodeFnc);
  4820. // Restore the lists of scopes that contain function expressions.
  4821. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  4822. m_ppnodeExprScope = ppnodeExprScopeSave;
  4823. Assert(m_ppnodeScope);
  4824. Assert(nullptr == *m_ppnodeScope);
  4825. m_ppnodeScope = ppnodeScopeSave;
  4826. if (pnodeBlock)
  4827. {
  4828. FinishParseBlock(pnodeBlock, *pNeedScanRCurly);
  4829. }
  4830. if (IsStrictMode() || strictModeTurnedOn)
  4831. {
  4832. this->m_fUseStrictMode = TRUE; // Now we know this function is in strict mode
  4833. if (!fWasAlreadyStrictMode)
  4834. {
  4835. // If this function turned on strict mode then we didn't check the formal
  4836. // parameters or function name hint for future reserved word usage. So do that now.
  4837. RestorePoint afterFnc;
  4838. this->GetScanner()->Capture(&afterFnc);
  4839. if (pnodeFnc->pnodeName != nullptr)
  4840. {
  4841. // Rewind to the function name hint and check if the token is a reserved word.
  4842. this->GetScanner()->SeekTo(beginNameHint);
  4843. this->GetScanner()->Scan();
  4844. if (pnodeFnc->IsGenerator())
  4845. {
  4846. Assert(m_token.tk == tkStar);
  4847. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  4848. Assert(!(flags & fFncClassMember));
  4849. this->GetScanner()->Scan();
  4850. }
  4851. if (m_token.IsReservedWord())
  4852. {
  4853. IdentifierExpectedError(m_token);
  4854. }
  4855. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  4856. }
  4857. // Fast forward to formal parameter list, check for future reserved words,
  4858. // then restore scanner as it was.
  4859. this->GetScanner()->SeekToForcingPid(beginFormals);
  4860. CheckStrictFormalParameters();
  4861. this->GetScanner()->SeekTo(afterFnc);
  4862. }
  4863. if (buildAST)
  4864. {
  4865. if (pnodeFnc->pnodeName != nullptr)
  4866. {
  4867. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  4868. CheckStrictModeEvalArgumentsUsage(pnodeFnc->pnodeName->pid, pnodeFnc->pnodeName);
  4869. }
  4870. }
  4871. this->m_fUseStrictMode = oldStrictMode;
  4872. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StrictModeFunction, m_scriptContext);
  4873. }
  4874. ProcessCapturedNames(pnodeFnc);
  4875. if (fDeferred)
  4876. {
  4877. AnalysisAssert(pnodeFnc);
  4878. pnodeFnc->pnodeVars = nullptr;
  4879. }
  4880. #if ENABLE_BACKGROUND_PARSING
  4881. if (parallelJobStarted)
  4882. {
  4883. pnodeFnc = pnodeRealFnc;
  4884. m_currentNodeFunc = pnodeRealFnc;
  4885. // Let the foreground thread take care of marking the limit on the function node,
  4886. // because in some cases this function's caller will want to change that limit,
  4887. // so we don't want the background thread to try and touch it.
  4888. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  4889. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  4890. }
  4891. #endif
  4892. }
  4893. // after parsing asm.js module, we want to reset asm.js state before continuing
  4894. AnalysisAssert(pnodeFnc);
  4895. if (pnodeFnc->GetAsmjsMode())
  4896. {
  4897. m_InAsmMode = false;
  4898. }
  4899. // Restore the statement stack.
  4900. Assert(nullptr == m_pstmtCur);
  4901. SetCurrentStatement(pstmtSave);
  4902. if (pnodeFncExprScope)
  4903. {
  4904. FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);
  4905. }
  4906. m_grfscr |= uCanDeferSave;
  4907. if (!m_stoppedDeferredParse)
  4908. {
  4909. m_grfscr |= uDeferSave;
  4910. }
  4911. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  4912. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  4913. // Restore the current function.
  4914. if (buildAST)
  4915. {
  4916. Assert(pnodeFnc == m_currentNodeFunc);
  4917. m_currentNodeFunc = pnodeFncSave;
  4918. m_pCurrentAstSize = pAstSizeSave;
  4919. if (!fLambda)
  4920. {
  4921. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  4922. m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;
  4923. }
  4924. }
  4925. else
  4926. {
  4927. Assert(pnodeFnc == m_currentNodeDeferredFunc);
  4928. if (!fLambda)
  4929. {
  4930. Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);
  4931. m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;
  4932. }
  4933. m_currentNodeDeferredFunc = pnodeFncSave;
  4934. }
  4935. if (m_currentNodeFunc && pnodeFnc->HasWithStmt())
  4936. {
  4937. GetCurrentFunctionNode()->SetHasWithStmt(true);
  4938. }
  4939. }
  4940. template<bool buildAST>
  4941. void Parser::UpdateCurrentNodeFunc(ParseNodeFnc * pnodeFnc, bool fLambda)
  4942. {
  4943. if (buildAST)
  4944. {
  4945. // Make this the current function and start its sub-function list.
  4946. m_currentNodeFunc = pnodeFnc;
  4947. Assert(m_currentNodeDeferredFunc == nullptr);
  4948. if (!fLambda)
  4949. {
  4950. m_currentNodeNonLambdaFunc = pnodeFnc;
  4951. }
  4952. }
  4953. else // if !buildAST
  4954. {
  4955. AnalysisAssert(pnodeFnc);
  4956. if (!fLambda)
  4957. {
  4958. m_currentNodeNonLambdaDeferredFunc = pnodeFnc;
  4959. }
  4960. m_currentNodeDeferredFunc = pnodeFnc;
  4961. }
  4962. }
  4963. void Parser::ParseTopLevelDeferredFunc(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeFncParent, LPCOLESTR pNameHint, bool fLambda, bool *pNeedScanRCurly, bool fAllowIn)
  4964. {
  4965. // Parse a function body that is a transition point from building AST to doing fast syntax check.
  4966. pnodeFnc->pnodeVars = nullptr;
  4967. pnodeFnc->pnodeBody = nullptr;
  4968. this->m_deferringAST = TRUE;
  4969. // Put the scanner into "no hashing" mode.
  4970. BYTE deferFlags = this->GetScanner()->SetDeferredParse(TRUE);
  4971. if (!fLambda)
  4972. {
  4973. ChkCurTok(tkLCurly, ERRnoLcurly);
  4974. }
  4975. else
  4976. {
  4977. // Lambda may consist of a single expression instead of a block
  4978. if (this->GetScanner()->m_ptoken->tk == tkLCurly)
  4979. {
  4980. this->GetScanner()->Scan();
  4981. }
  4982. else
  4983. {
  4984. *pNeedScanRCurly = false;
  4985. }
  4986. }
  4987. ParseNodePtr *ppnodeVarSave = m_ppnodeVar;
  4988. m_ppnodeVar = &pnodeFnc->pnodeVars;
  4989. // Don't try and skip scanning nested deferred lambdas which have only a single expression in the body.
  4990. // Their more-complicated text extents won't match the deferred-stub and the single expression should be fast to scan, anyway.
  4991. if (fLambda && !*pNeedScanRCurly)
  4992. {
  4993. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  4994. }
  4995. else if (pnodeFncParent != nullptr && m_currDeferredStub != nullptr && !pnodeFncParent->HasDefaultArguments())
  4996. {
  4997. // We've already parsed this function body for syntax errors on the initial parse of the script.
  4998. // We have information that allows us to skip it, so do so.
  4999. Assert(pnodeFncParent->nestedCount != 0);
  5000. DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->nestedCount - 1);
  5001. Assert(pnodeFnc->ichMin == stub->ichMin
  5002. || (stub->fncFlags & kFunctionIsAsync) == kFunctionIsAsync
  5003. || ((stub->fncFlags & kFunctionIsGenerator) == kFunctionIsGenerator && (stub->fncFlags & kFunctionIsMethod) == kFunctionIsMethod));
  5004. if (stub->fncFlags & kFunctionCallsEval)
  5005. {
  5006. this->MarkEvalCaller();
  5007. }
  5008. PHASE_PRINT_TRACE1(
  5009. Js::SkipNestedDeferredPhase,
  5010. _u("Skipping nested deferred function %d. %s: %d...%d\n"),
  5011. pnodeFnc->functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);
  5012. this->GetScanner()->SeekTo(stub->restorePoint, m_nextFunctionId);
  5013. for (uint i = 0; i < stub->capturedNameCount; i++)
  5014. {
  5015. int stringId = stub->capturedNameSerializedIds[i];
  5016. uint32 stringLength = 0;
  5017. LPCWSTR stringVal = Js::ByteCodeSerializer::DeserializeString(stub, stringId, stringLength);
  5018. OUTPUT_TRACE_DEBUGONLY(Js::SkipNestedDeferredPhase, _u("\tPushing a reference to '%s'\n"), stringVal);
  5019. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(stringVal, stringLength);
  5020. PushPidRef(pid);
  5021. }
  5022. pnodeFnc->nestedCount = stub->nestedCount;
  5023. pnodeFnc->deferredStub = stub->deferredStubs;
  5024. pnodeFnc->fncFlags = (FncFlags)(pnodeFnc->fncFlags | stub->fncFlags);
  5025. }
  5026. else
  5027. {
  5028. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */);
  5029. }
  5030. if (!fLambda || *pNeedScanRCurly)
  5031. {
  5032. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5033. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5034. }
  5035. m_ppnodeVar = ppnodeVarSave;
  5036. // Restore the scanner's default hashing mode.
  5037. // Do this before we consume the next token.
  5038. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  5039. if (*pNeedScanRCurly)
  5040. {
  5041. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5042. }
  5043. #if DBG
  5044. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  5045. #endif
  5046. this->m_deferringAST = FALSE;
  5047. }
  5048. bool Parser::DoParallelParse(ParseNodeFnc * pnodeFnc) const
  5049. {
  5050. #if ENABLE_BACKGROUND_PARSING
  5051. if (!PHASE_ENABLED_RAW(ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId))
  5052. {
  5053. return false;
  5054. }
  5055. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  5056. return bgp != nullptr;
  5057. #else
  5058. return false;
  5059. #endif
  5060. }
  5061. bool Parser::ScanAheadToFunctionEnd(uint count)
  5062. {
  5063. bool found = false;
  5064. uint curlyDepth = 0;
  5065. RestorePoint funcStart;
  5066. this->GetScanner()->Capture(&funcStart);
  5067. for (uint i = 0; i < count; i++)
  5068. {
  5069. switch (m_token.tk)
  5070. {
  5071. case tkStrTmplBegin:
  5072. case tkStrTmplMid:
  5073. case tkStrTmplEnd:
  5074. case tkDiv:
  5075. case tkAsgDiv:
  5076. case tkScanError:
  5077. case tkEOF:
  5078. goto LEnd;
  5079. case tkLCurly:
  5080. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5081. break;
  5082. case tkRCurly:
  5083. if (curlyDepth == 1)
  5084. {
  5085. found = true;
  5086. goto LEnd;
  5087. }
  5088. if (curlyDepth == 0)
  5089. {
  5090. goto LEnd;
  5091. }
  5092. curlyDepth--;
  5093. break;
  5094. }
  5095. this->GetScanner()->ScanAhead();
  5096. }
  5097. LEnd:
  5098. this->GetScanner()->SeekTo(funcStart);
  5099. return found;
  5100. }
  5101. #if ENABLE_BACKGROUND_PARSING
  5102. bool Parser::FastScanFormalsAndBody()
  5103. {
  5104. // The scanner is currently pointing just past the name of a function.
  5105. // The idea here is to find the end of the function body as quickly as possible,
  5106. // by tokenizing and tracking {}'s if possible.
  5107. // String templates require some extra logic but can be handled.
  5108. // The real wrinkle is "/" and "/=", which may indicate either a RegExp literal or a division, depending
  5109. // on the context.
  5110. // To handle this with minimal work, keep track of the last ";" seen at each {} depth. If we see one of the
  5111. // difficult tokens, rewind to the last ";" at the current {} depth and parse statements until we pass the
  5112. // point where we had to rewind. This will process the "/" as required.
  5113. RestorePoint funcStart;
  5114. this->GetScanner()->Capture(&funcStart);
  5115. const int maxRestorePointDepth = 16;
  5116. struct FastScanRestorePoint
  5117. {
  5118. RestorePoint restorePoint;
  5119. uint parenDepth;
  5120. Js::LocalFunctionId functionId;
  5121. int blockId;
  5122. FastScanRestorePoint() : restorePoint(), parenDepth(0) {};
  5123. };
  5124. FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];
  5125. charcount_t ichStart = this->GetScanner()->IchMinTok();
  5126. uint blockIdSave = m_nextBlockId;
  5127. uint functionIdSave = *m_nextFunctionId;
  5128. uint curlyDepth = 0;
  5129. uint strTmplDepth = 0;
  5130. for (;;)
  5131. {
  5132. switch (m_token.tk)
  5133. {
  5134. case tkStrTmplBegin:
  5135. UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);
  5136. // Fall through
  5137. case tkStrTmplMid:
  5138. case tkLCurly:
  5139. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5140. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5141. break;
  5142. case tkStrTmplEnd:
  5143. // We can assert here, because the scanner will only return this token if we've told it we're
  5144. // in a string template.
  5145. Assert(strTmplDepth > 0);
  5146. strTmplDepth--;
  5147. break;
  5148. case tkRCurly:
  5149. if (curlyDepth == 1)
  5150. {
  5151. Assert(strTmplDepth == 0);
  5152. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5153. {
  5154. Output::Print(_u("Finished fast seek: %d. %s -- %d...%d\n"),
  5155. m_currentNodeFunc->functionId,
  5156. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5157. ichStart, this->GetScanner()->IchLimTok());
  5158. }
  5159. return true;
  5160. }
  5161. if (curlyDepth < maxRestorePointDepth)
  5162. {
  5163. lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;
  5164. }
  5165. curlyDepth--;
  5166. if (strTmplDepth > 0)
  5167. {
  5168. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  5169. }
  5170. break;
  5171. case tkSColon:
  5172. // Track the location of the ";" (if it's outside parens, as we don't, for instance, want
  5173. // to track the ";"'s in a for-loop header. If we find it's important to rewind within a paren
  5174. // expression, we can do something more sophisticated.)
  5175. if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)
  5176. {
  5177. this->GetScanner()->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);
  5178. lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;
  5179. lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;
  5180. }
  5181. break;
  5182. case tkLParen:
  5183. if (curlyDepth < maxRestorePointDepth)
  5184. {
  5185. UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);
  5186. }
  5187. break;
  5188. case tkRParen:
  5189. if (curlyDepth < maxRestorePointDepth)
  5190. {
  5191. Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);
  5192. lastSColonAtCurlyDepth[curlyDepth].parenDepth--;
  5193. }
  5194. break;
  5195. case tkID:
  5196. {
  5197. charcount_t tokLength = this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok();
  5198. // Detect the function and class keywords so we can track function ID's.
  5199. // (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token
  5200. // to a PID.)
  5201. // Detect try/catch/for to increment block count for them.
  5202. switch (tokLength)
  5203. {
  5204. case 3:
  5205. if (!memcmp(this->GetScanner()->PchMinTok(), "try", 3) || !memcmp(this->GetScanner()->PchMinTok(), "for", 3))
  5206. {
  5207. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5208. }
  5209. break;
  5210. case 5:
  5211. if (!memcmp(this->GetScanner()->PchMinTok(), "catch", 5))
  5212. {
  5213. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5214. }
  5215. else if (!memcmp(this->GetScanner()->PchMinTok(), "class", 5))
  5216. {
  5217. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5218. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5219. }
  5220. break;
  5221. case 8:
  5222. if (!memcmp(this->GetScanner()->PchMinTok(), "function", 8))
  5223. {
  5224. // Account for the possible func expr scope or dummy block for missing {}'s around a declaration
  5225. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5226. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5227. }
  5228. break;
  5229. }
  5230. break;
  5231. }
  5232. case tkDArrow:
  5233. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5234. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5235. break;
  5236. case tkDiv:
  5237. case tkAsgDiv:
  5238. {
  5239. int opl;
  5240. OpCode nop;
  5241. tokens tkPrev = this->GetScanner()->m_tkPrevious;
  5242. if ((this->GetHashTbl()->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||
  5243. (this->GetHashTbl()->TokIsUnop(tkPrev, &opl, &nop) &&
  5244. nop != knopNone &&
  5245. tkPrev != tkInc &&
  5246. tkPrev != tkDec) ||
  5247. tkPrev == tkColon ||
  5248. tkPrev == tkLParen ||
  5249. tkPrev == tkLBrack ||
  5250. tkPrev == tkRETURN)
  5251. {
  5252. // Previous token indicates that we're starting an expression here and can't have a
  5253. // binary operator now.
  5254. // Assume this is a RegExp.
  5255. ParseRegExp<false>();
  5256. break;
  5257. }
  5258. uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;
  5259. for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)
  5260. {
  5261. // We don't know whether we've got a RegExp or a divide. Rewind to the last safe ";"
  5262. // if we can and parse statements until we pass this point.
  5263. if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)
  5264. {
  5265. break;
  5266. }
  5267. }
  5268. if (tempCurlyDepth != (uint)-1)
  5269. {
  5270. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5271. int32 *pastSizeSave = m_pCurrentAstSize;
  5272. uint *pnestedCountSave = m_pnestedCount;
  5273. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  5274. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  5275. ParseNodeFnc * pnodeFnc = CreateDummyFuncNode(true);
  5276. charcount_t ichStop = this->GetScanner()->IchLimTok();
  5277. curlyDepth = tempCurlyDepth;
  5278. this->GetScanner()->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);
  5279. m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;
  5280. *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;
  5281. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5282. pnodeFnc->pnodeScopes = pnodeBlock;
  5283. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  5284. m_ppnodeExprScope = nullptr;
  5285. this->GetScanner()->Scan();
  5286. do
  5287. {
  5288. ParseStatement<false>();
  5289. } while (this->GetScanner()->IchMinTok() < ichStop);
  5290. FinishParseBlock(pnodeBlock);
  5291. m_currentNodeFunc = pnodeFncSave;
  5292. m_pCurrentAstSize = pastSizeSave;
  5293. m_pnestedCount = pnestedCountSave;
  5294. m_ppnodeScope = ppnodeScopeSave;
  5295. m_ppnodeExprScope = ppnodeExprScopeSave;
  5296. // We've already consumed the first token of the next statement, so just continue
  5297. // without a further scan.
  5298. continue;
  5299. }
  5300. }
  5301. // fall through to rewind to function start
  5302. case tkScanError:
  5303. case tkEOF:
  5304. // Unexpected token.
  5305. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5306. {
  5307. Output::Print(_u("Failed fast seek: %d. %s -- %d...%d\n"),
  5308. m_currentNodeFunc->functionId,
  5309. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5310. ichStart, this->GetScanner()->IchLimTok());
  5311. }
  5312. m_nextBlockId = blockIdSave;
  5313. *m_nextFunctionId = functionIdSave;
  5314. this->GetScanner()->SeekTo(funcStart);
  5315. return false;
  5316. }
  5317. this->GetScanner()->ScanNoKeywords();
  5318. }
  5319. }
  5320. #endif
  5321. ParseNodeFnc * Parser::CreateDummyFuncNode(bool fDeclaration)
  5322. {
  5323. // Create a dummy node and make it look like the current function declaration.
  5324. // Do this in situations where we want to parse statements without impacting
  5325. // the state of the "real" AST.
  5326. ParseNodeFnc * pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5327. pnodeFnc->SetDeclaration(fDeclaration);
  5328. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  5329. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  5330. m_pCurrentAstSize = &pnodeFnc->astSize;
  5331. m_currentNodeFunc = pnodeFnc;
  5332. m_pnestedCount = &pnodeFnc->nestedCount;
  5333. return pnodeFnc;
  5334. }
  5335. void Parser::ParseNestedDeferredFunc(ParseNodeFnc * pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn, bool fAllowIn)
  5336. {
  5337. // Parse a function nested inside another deferred function.
  5338. size_t lengthBeforeBody = this->GetSourceLength();
  5339. if (m_token.tk != tkLCurly && fLambda)
  5340. {
  5341. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5342. *pNeedScanRCurly = false;
  5343. }
  5344. else
  5345. {
  5346. ChkCurTok(tkLCurly, ERRnoLcurly);
  5347. bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;
  5348. m_ppnodeVar = &m_currentNodeDeferredFunc->pnodeVars;
  5349. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */, detectStrictModeOn);
  5350. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5351. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5352. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5353. }
  5354. if (*pStrictModeTurnedOn)
  5355. {
  5356. pnodeFnc->SetStrictMode(true);
  5357. }
  5358. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  5359. {
  5360. // Record the end of the function and the function ID increment that happens inside the function.
  5361. // Byte code gen will use this to build stub information to allow us to skip this function when the
  5362. // enclosing function is fully parsed.
  5363. RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);
  5364. this->GetScanner()->Capture(restorePoint,
  5365. *m_nextFunctionId - pnodeFnc->functionId - 1,
  5366. lengthBeforeBody - this->GetSourceLength());
  5367. pnodeFnc->pRestorePoint = restorePoint;
  5368. }
  5369. }
  5370. template<bool buildAST>
  5371. void Parser::ParseFncName(ParseNodeFnc * pnodeFnc, ushort flags, IdentPtr* pFncNamePid)
  5372. {
  5373. Assert(pnodeFnc);
  5374. BOOL fDeclaration = flags & fFncDeclaration;
  5375. BOOL fIsAsync = flags & fFncAsync;
  5376. this->GetScanner()->Scan();
  5377. // If generators are enabled then we are in a recent enough version
  5378. // that deferred parsing will create a parse node for pnodeFnc and
  5379. // it is safe to assume it is not null.
  5380. if (flags & fFncGenerator)
  5381. {
  5382. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5383. pnodeFnc->SetIsGenerator();
  5384. }
  5385. else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  5386. m_token.tk == tkStar &&
  5387. !(flags & fFncClassMember))
  5388. {
  5389. if (!fDeclaration)
  5390. {
  5391. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(!fDeclaration);
  5392. this->GetScanner()->Scan();
  5393. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5394. }
  5395. else
  5396. {
  5397. this->GetScanner()->Scan();
  5398. }
  5399. pnodeFnc->SetIsGenerator();
  5400. }
  5401. if (fIsAsync)
  5402. {
  5403. if (pnodeFnc->IsGenerator())
  5404. {
  5405. Error(ERRsyntax);
  5406. }
  5407. pnodeFnc->SetIsAsync();
  5408. }
  5409. pnodeFnc->pnodeName = nullptr;
  5410. if ((m_token.tk != tkID || flags & fFncNoName)
  5411. && (IsStrictMode() || fDeclaration
  5412. || pnodeFnc->IsGenerator() || pnodeFnc->IsAsync()
  5413. || (m_token.tk != tkYIELD && m_token.tk != tkAWAIT))) // Function expressions can have the name yield/await even inside generator/async functions
  5414. {
  5415. if (fDeclaration ||
  5416. m_token.IsReservedWord()) // For example: var x = (function break(){});
  5417. {
  5418. IdentifierExpectedError(m_token);
  5419. }
  5420. return;
  5421. }
  5422. Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration) || (m_token.tk == tkAWAIT && !fDeclaration));
  5423. if (IsStrictMode())
  5424. {
  5425. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  5426. }
  5427. IdentPtr pidBase = m_token.GetIdentifier(this->GetHashTbl());
  5428. pnodeFnc->pnodeName = CreateDeclNode(knopVarDecl, pidBase, STFunction);
  5429. pnodeFnc->pid = pnodeFnc->pnodeName->pid;
  5430. if (pFncNamePid != nullptr)
  5431. {
  5432. *pFncNamePid = pidBase;
  5433. }
  5434. this->GetScanner()->Scan();
  5435. }
  5436. void Parser::ValidateFormals()
  5437. {
  5438. ParseFncFormals<false>(this->GetCurrentFunctionNode(), nullptr, fFncNoFlgs);
  5439. // Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.
  5440. this->GetScanner()->Scan();
  5441. }
  5442. void Parser::ValidateSourceElementList()
  5443. {
  5444. ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);
  5445. }
  5446. void Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)
  5447. {
  5448. bool isStrictMode = IsStrictMode();
  5449. if (isStrictMode)
  5450. {
  5451. CheckStrictModeEvalArgumentsUsage(pid);
  5452. }
  5453. if (formals->Has(pid))
  5454. {
  5455. if (isStrictMode)
  5456. {
  5457. Error(ERRES5ArgSame);
  5458. }
  5459. else
  5460. {
  5461. Error(ERRFormalSame);
  5462. }
  5463. }
  5464. else
  5465. {
  5466. formals->Prepend(pid);
  5467. }
  5468. }
  5469. template<bool buildAST>
  5470. void Parser::ParseFncFormals(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeParentFnc, ushort flags, bool isTopLevelDeferredFunc)
  5471. {
  5472. bool fLambda = (flags & fFncLambda) != 0;
  5473. bool fMethod = (flags & fFncMethod) != 0;
  5474. bool fNoArg = (flags & fFncNoArg) != 0;
  5475. bool fOneArg = (flags & fFncOneArg) != 0;
  5476. bool fAsync = (flags & fFncAsync) != 0;
  5477. bool fPreviousYieldIsKeyword = false;
  5478. bool fPreviousAwaitIsKeyword = false;
  5479. if (fLambda)
  5480. {
  5481. fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeParentFnc != nullptr && pnodeParentFnc->IsGenerator());
  5482. fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->IsAsync()));
  5483. }
  5484. Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.
  5485. // strictFormals corresponds to the StrictFormalParameters grammar production
  5486. // in the ES spec which just means duplicate names are not allowed
  5487. bool fStrictFormals = IsStrictMode() || fLambda || fMethod;
  5488. // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
  5489. bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
  5490. AutoTempForcePid autoForcePid(this->GetScanner(), forcePid);
  5491. // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
  5492. if (fLambda && m_token.tk == tkID)
  5493. {
  5494. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5495. CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5496. CheckPidIsValid(pid);
  5497. this->GetScanner()->Scan();
  5498. if (m_token.tk != tkDArrow)
  5499. {
  5500. Error(ERRsyntax, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  5501. }
  5502. if (fLambda)
  5503. {
  5504. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5505. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5506. }
  5507. return;
  5508. }
  5509. else if (fLambda && m_token.tk == tkAWAIT)
  5510. {
  5511. // async await => {}
  5512. IdentifierExpectedError(m_token);
  5513. }
  5514. // Otherwise, must have a parameter list within parens.
  5515. ChkCurTok(tkLParen, ERRnoLparen);
  5516. // Now parse the list of arguments, if present
  5517. if (m_token.tk == tkRParen)
  5518. {
  5519. if (fOneArg)
  5520. {
  5521. Error(ERRSetterMustHaveOneParameter);
  5522. }
  5523. }
  5524. else
  5525. {
  5526. if (fNoArg)
  5527. {
  5528. Error(ERRGetterMustHaveNoParameters);
  5529. }
  5530. SList<IdentPtr> formals(&m_nodeAllocator);
  5531. ParseNodeVar * pnodeT = nullptr;
  5532. bool seenRestParameter = false;
  5533. bool isNonSimpleParameterList = false;
  5534. for (Js::ArgSlot argPos = 0; ; ++argPos)
  5535. {
  5536. bool isBindingPattern = false;
  5537. if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
  5538. {
  5539. // Possible rest parameter
  5540. this->GetScanner()->Scan();
  5541. seenRestParameter = true;
  5542. }
  5543. if (m_token.tk != tkID)
  5544. {
  5545. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  5546. {
  5547. // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
  5548. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5549. this->GetCurrentFunctionNode()->SetHasDestructuredParams();
  5550. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5551. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5552. ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
  5553. Assert(ppNodeLex != nullptr);
  5554. ParseNodeParamPattern * paramPattern = nullptr;
  5555. ParseNode * pnodePattern = nullptr;
  5556. if (isTopLevelDeferredFunc)
  5557. {
  5558. pnodePattern = ParseDestructuredLiteral<false>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5559. }
  5560. else
  5561. {
  5562. pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5563. }
  5564. // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
  5565. for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->AsParseNodeVar()->pnodeNext)
  5566. {
  5567. Assert(lexNode->IsVarLetOrConst());
  5568. UpdateOrCheckForDuplicateInFormals(lexNode->AsParseNodeVar()->pid, &formals);
  5569. lexNode->AsParseNodeVar()->sym->SetSymbolType(STFormal);
  5570. if (lexNode->AsParseNodeVar()->pid == wellKnownPropertyPids.arguments)
  5571. {
  5572. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5573. }
  5574. }
  5575. m_ppnodeVar = ppnodeVarSave;
  5576. if (buildAST)
  5577. {
  5578. if (isTopLevelDeferredFunc)
  5579. {
  5580. Assert(pnodePattern == nullptr);
  5581. // Create a dummy pattern node as we need the node to be considered for the param count
  5582. paramPattern = CreateDummyParamPatternNode(this->GetScanner()->IchMinTok());
  5583. }
  5584. else
  5585. {
  5586. Assert(pnodePattern);
  5587. paramPattern = CreateParamPatternNode(pnodePattern);
  5588. }
  5589. // Linking the current formal parameter (which is pattern parameter) with other formals.
  5590. *m_ppnodeVar = paramPattern;
  5591. paramPattern->pnodeNext = nullptr;
  5592. m_ppnodeVar = &paramPattern->pnodeNext;
  5593. }
  5594. isBindingPattern = true;
  5595. isNonSimpleParameterList = true;
  5596. }
  5597. else
  5598. {
  5599. IdentifierExpectedError(m_token);
  5600. }
  5601. }
  5602. if (!isBindingPattern)
  5603. {
  5604. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5605. LPCOLESTR pNameHint = pid->Psz();
  5606. uint32 nameHintLength = pid->Cch();
  5607. uint32 nameHintOffset = 0;
  5608. if (seenRestParameter)
  5609. {
  5610. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5611. if (flags & fFncOneArg)
  5612. {
  5613. // The parameter of a setter cannot be a rest parameter.
  5614. Error(ERRUnexpectedEllipsis);
  5615. }
  5616. pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
  5617. pnodeT->sym->SetIsNonSimpleParameter(true);
  5618. if (buildAST)
  5619. {
  5620. // When only validating formals, we won't have a function node.
  5621. pnodeFnc->pnodeRest = pnodeT;
  5622. if (!isNonSimpleParameterList)
  5623. {
  5624. // This is the first non-simple parameter we've seen. We need to go back
  5625. // and set the Symbols of all previous parameters.
  5626. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5627. }
  5628. }
  5629. isNonSimpleParameterList = true;
  5630. }
  5631. else
  5632. {
  5633. pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5634. if (isNonSimpleParameterList)
  5635. {
  5636. pnodeT->sym->SetIsNonSimpleParameter(true);
  5637. }
  5638. }
  5639. if (buildAST && pid == wellKnownPropertyPids.arguments)
  5640. {
  5641. // This formal parameter overrides the built-in 'arguments' object
  5642. m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5643. }
  5644. if (fStrictFormals)
  5645. {
  5646. UpdateOrCheckForDuplicateInFormals(pid, &formals);
  5647. }
  5648. this->GetScanner()->Scan();
  5649. if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)
  5650. {
  5651. Error(ERRRestLastArg);
  5652. }
  5653. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5654. {
  5655. if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
  5656. {
  5657. Error(ERRRestWithDefault);
  5658. }
  5659. // In defer parse mode we have to flag the function node to indicate that it has default arguments
  5660. // so that it will be considered for any syntax error scenario.
  5661. // Also mark it before parsing the expression as it may contain functions.
  5662. ParseNodeFnc * currentFncNode = GetCurrentFunctionNode();
  5663. if (!currentFncNode->HasDefaultArguments())
  5664. {
  5665. currentFncNode->SetHasDefaultArguments();
  5666. currentFncNode->SetHasNonSimpleParameterList();
  5667. currentFncNode->firstDefaultArg = argPos;
  5668. }
  5669. this->GetScanner()->Scan();
  5670. ParseNodePtr pnodeInit;
  5671. if (isTopLevelDeferredFunc)
  5672. {
  5673. // Defer default expressions if the function will be deferred, since we know they can't be evaluated
  5674. // until the function is fully compiled, and generating code for a function nested inside a deferred function
  5675. // creates inconsistencies.
  5676. pnodeInit = ParseExpr<false>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5677. }
  5678. else
  5679. {
  5680. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5681. }
  5682. if (buildAST && pnodeInit && pnodeInit->nop == knopFncDecl)
  5683. {
  5684. Assert(nameHintLength >= nameHintOffset);
  5685. ParseNodeFnc * pnodeFncInit = pnodeInit->AsParseNodeFnc();
  5686. pnodeFncInit->hint = pNameHint;
  5687. pnodeFncInit->hintLength = nameHintLength;
  5688. pnodeFncInit->hintOffset = nameHintOffset;
  5689. }
  5690. AnalysisAssert(pnodeT);
  5691. pnodeT->sym->SetIsNonSimpleParameter(true);
  5692. if (!isNonSimpleParameterList)
  5693. {
  5694. if (buildAST)
  5695. {
  5696. // This is the first non-simple parameter we've seen. We need to go back
  5697. // and set the Symbols of all previous parameters.
  5698. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5699. }
  5700. // There may be previous parameters that need to be checked for duplicates.
  5701. isNonSimpleParameterList = true;
  5702. }
  5703. if (buildAST)
  5704. {
  5705. if (!m_currentNodeFunc->HasDefaultArguments())
  5706. {
  5707. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, DefaultArgFunction, m_scriptContext);
  5708. }
  5709. pnodeT->pnodeInit = pnodeInit;
  5710. pnodeT->ichLim = this->GetScanner()->IchLimTok();
  5711. }
  5712. }
  5713. }
  5714. if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
  5715. {
  5716. Error(ERRFormalSame);
  5717. }
  5718. if (flags & fFncOneArg)
  5719. {
  5720. if (m_token.tk != tkRParen)
  5721. {
  5722. Error(ERRSetterMustHaveOneParameter);
  5723. }
  5724. break; //enforce only one arg
  5725. }
  5726. if (m_token.tk != tkComma)
  5727. {
  5728. break;
  5729. }
  5730. this->GetScanner()->Scan();
  5731. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5732. {
  5733. break;
  5734. }
  5735. }
  5736. if (seenRestParameter)
  5737. {
  5738. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Rest, m_scriptContext);
  5739. }
  5740. if (m_token.tk != tkRParen)
  5741. {
  5742. Error(ERRnoRparen);
  5743. }
  5744. if (this->GetCurrentFunctionNode()->CallsEval() || this->GetCurrentFunctionNode()->ChildCallsEval())
  5745. {
  5746. Assert(pnodeFnc->HasNonSimpleParameterList());
  5747. pnodeFnc->ResetBodyAndParamScopeMerged();
  5748. }
  5749. }
  5750. Assert(m_token.tk == tkRParen);
  5751. if (fLambda)
  5752. {
  5753. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5754. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5755. }
  5756. }
  5757. template<bool buildAST>
  5758. ParseNodePtr Parser::GenerateModuleFunctionWrapper()
  5759. {
  5760. ParseNodePtr pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fFncModule, SuperRestrictionState::Disallowed, nullptr, /* needsPIDOnRCurlyScan */ false, /* fUnaryOrParen */ true);
  5761. ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);
  5762. return callNode;
  5763. }
  5764. template<bool buildAST>
  5765. ParseNodeFnc * Parser::GenerateEmptyConstructor(bool extends)
  5766. {
  5767. ParseNodeFnc * pnodeFnc;
  5768. // Create the node.
  5769. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5770. pnodeFnc->SetNested(NULL != m_currentNodeFunc);
  5771. pnodeFnc->SetStrictMode();
  5772. pnodeFnc->SetDeclaration(TRUE);
  5773. pnodeFnc->SetIsMethod(TRUE);
  5774. pnodeFnc->SetIsClassMember(TRUE);
  5775. pnodeFnc->SetIsClassConstructor(TRUE);
  5776. pnodeFnc->SetIsBaseClassConstructor(!extends);
  5777. pnodeFnc->SetHasNonThisStmt();
  5778. pnodeFnc->SetIsGeneratedDefault(TRUE);
  5779. pnodeFnc->SetHasComputedName();
  5780. pnodeFnc->SetHasHomeObj();
  5781. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  5782. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5783. pnodeFnc->ichMin = this->GetScanner()->IchMinTok();
  5784. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5785. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  5786. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  5787. pnodeFnc->functionId = (*m_nextFunctionId);
  5788. // In order to (re-)defer the default constructor, we need to, for instance, track
  5789. // deferred class expression the way we track function expression, since we lose the part of the source
  5790. // that tells us which we have.
  5791. Assert(!pnodeFnc->canBeDeferred);
  5792. #ifdef DBG
  5793. pnodeFnc->deferredParseNextFunctionId = *(this->m_nextFunctionId);
  5794. #endif
  5795. AppendFunctionToScopeList(true, pnodeFnc);
  5796. if (m_nextFunctionId)
  5797. {
  5798. (*m_nextFunctionId)++;
  5799. }
  5800. // Update the count of functions nested in the current parent.
  5801. if (m_pnestedCount)
  5802. {
  5803. (*m_pnestedCount)++;
  5804. }
  5805. if (this->GetScanner()->IchMinTok() >= this->GetScanner()->IchMinLine())
  5806. {
  5807. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  5808. pnodeFnc->columnNumber = this->GetScanner()->IchMinTok() - this->GetScanner()->IchMinLine();
  5809. }
  5810. else if (m_currentNodeFunc)
  5811. {
  5812. // For the first line after defer parse, compute the column relative to the column number
  5813. // of the lexically parent function.
  5814. ULONG offsetFromCurrentFunction = this->GetScanner()->IchMinTok() - m_currentNodeFunc->ichMin;
  5815. pnodeFnc->columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  5816. }
  5817. else
  5818. {
  5819. // if there is no current function, lets give a default of 0.
  5820. pnodeFnc->columnNumber = 0;
  5821. }
  5822. int32 * pAstSizeSave = m_pCurrentAstSize;
  5823. m_pCurrentAstSize = &(pnodeFnc->astSize);
  5824. // Make this the current function.
  5825. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5826. m_currentNodeFunc = pnodeFnc;
  5827. ParseNodeName * argsId = nullptr;
  5828. ParseNodePtr *lastNodeRef = nullptr;
  5829. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  5830. if (buildAST && extends)
  5831. {
  5832. // constructor(...args) { super(...args); }
  5833. // ^^^^^^^
  5834. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5835. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5836. IdentPtr pidargs = this->GetHashTbl()->PidHashNameLen(_u("args"), sizeof("args") - 1);
  5837. ParseNodeVar * pnodeT = CreateVarDeclNode(pidargs, STFormal);
  5838. pnodeT->sym->SetIsNonSimpleParameter(true);
  5839. pnodeFnc->pnodeRest = pnodeT;
  5840. PidRefStack *ref = this->PushPidRef(pidargs);
  5841. argsId = CreateNameNode(pidargs, ref, pnodeFnc->ichMin, pnodeFnc->ichLim);
  5842. m_ppnodeVar = ppnodeVarSave;
  5843. }
  5844. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5845. pnodeBlock->pnodeScopes = pnodeInnerBlock;
  5846. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  5847. pnodeFnc->pnodeScopes = pnodeBlock;
  5848. if (buildAST)
  5849. {
  5850. if (extends)
  5851. {
  5852. // constructor(...args) { super(...args); }
  5853. // ^^^^^^^^^^^^^^^
  5854. Assert(argsId);
  5855. ParseNodeUni * spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);
  5856. ParseNodeSpecialName * superRef = ReferenceSpecialName(wellKnownPropertyPids._superConstructor, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5857. pnodeFnc->SetHasSuperReference(TRUE);
  5858. ParseNodeSuperCall * callNode = CreateSuperCallNode(superRef, spreadArg);
  5859. callNode->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5860. callNode->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5861. callNode->spreadArgCount = 1;
  5862. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, callNode);
  5863. }
  5864. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  5865. }
  5866. FinishParseBlock(pnodeInnerBlock);
  5867. CreateSpecialSymbolDeclarations(pnodeFnc);
  5868. FinishParseBlock(pnodeBlock);
  5869. m_currentNodeFunc = pnodeFncSave;
  5870. m_pCurrentAstSize = pAstSizeSave;
  5871. return pnodeFnc;
  5872. }
  5873. template<bool buildAST>
  5874. void Parser::ParseExpressionLambdaBody(ParseNodeFnc * pnodeLambda, bool fAllowIn)
  5875. {
  5876. ParseNodePtr *lastNodeRef = nullptr;
  5877. // The lambda body is a single expression, the result of which is the return value.
  5878. ParseNodeReturn * pnodeRet = nullptr;
  5879. if (buildAST)
  5880. {
  5881. pnodeRet = CreateNodeForOpT<knopReturn>();
  5882. pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;
  5883. pnodeLambda->pnodeScopes->pnodeStmt = pnodeRet;
  5884. }
  5885. IdentToken token;
  5886. charcount_t lastRParen = 0;
  5887. // We need to disable deferred parse mode in the scanner because the lambda body doesn't end with a right paren.
  5888. // The scanner needs to create a pid in the case of a string constant token immediately following the lambda body expression.
  5889. // Otherwise, we'll save null for the string constant pid which will AV during ByteCode generation.
  5890. BYTE fScanDeferredFlagsSave = this->GetScanner()->SetDeferredParse(FALSE);
  5891. ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, fAllowIn, FALSE, nullptr, nullptr, nullptr, &token, false, nullptr, &lastRParen);
  5892. this->GetScanner()->SetDeferredParseFlags(fScanDeferredFlagsSave);
  5893. this->MarkEscapingRef(result, &token);
  5894. if (buildAST)
  5895. {
  5896. pnodeRet->pnodeExpr = result;
  5897. pnodeRet->ichMin = pnodeRet->pnodeExpr->ichMin;
  5898. pnodeRet->ichLim = pnodeRet->pnodeExpr->ichLim;
  5899. // Pushing a statement node with PushStmt<>() normally does this initialization
  5900. // but do it here manually since we know there is no outer statement node.
  5901. pnodeRet->grfnop = 0;
  5902. pnodeRet->pnodeOuter = nullptr;
  5903. pnodeLambda->ichLim = max(pnodeRet->ichLim, lastRParen);
  5904. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  5905. pnodeLambda->pnodeScopes->ichLim = pnodeRet->ichLim;
  5906. pnodeLambda->pnodeBody = nullptr;
  5907. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, pnodeRet);
  5908. // Append an EndCode node.
  5909. ParseNodePtr end = CreateNodeForOpT<knopEndCode>(pnodeRet->ichLim);
  5910. end->ichLim = end->ichMin; // make end code zero width at the immediate end of lambda body
  5911. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, end);
  5912. // Lambda's do not have arguments binding
  5913. pnodeLambda->SetHasReferenceableBuiltInArguments(false);
  5914. }
  5915. else
  5916. {
  5917. pnodeLambda->ichLim = max(this->GetScanner()->IchLimTokPrevious(), lastRParen);
  5918. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  5919. }
  5920. }
  5921. void Parser::CheckStrictFormalParameters()
  5922. {
  5923. if (m_token.tk == tkID)
  5924. {
  5925. // single parameter arrow function case
  5926. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5927. CheckStrictModeEvalArgumentsUsage(pid);
  5928. return;
  5929. }
  5930. Assert(m_token.tk == tkLParen);
  5931. this->GetScanner()->ScanForcingPid();
  5932. if (m_token.tk != tkRParen)
  5933. {
  5934. SList<IdentPtr> formals(&m_nodeAllocator);
  5935. for (;;)
  5936. {
  5937. if (m_token.tk != tkID)
  5938. {
  5939. IdentifierExpectedError(m_token);
  5940. }
  5941. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5942. CheckStrictModeEvalArgumentsUsage(pid);
  5943. if (formals.Has(pid))
  5944. {
  5945. Error(ERRES5ArgSame, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  5946. }
  5947. else
  5948. {
  5949. formals.Prepend(pid);
  5950. }
  5951. this->GetScanner()->Scan();
  5952. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5953. {
  5954. this->GetScanner()->Scan();
  5955. // We can avoid building the AST since we are just checking the default expression.
  5956. ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);
  5957. Assert(pnodeInit == nullptr);
  5958. }
  5959. if (m_token.tk != tkComma)
  5960. {
  5961. break;
  5962. }
  5963. this->GetScanner()->ScanForcingPid();
  5964. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5965. {
  5966. break;
  5967. }
  5968. }
  5969. }
  5970. Assert(m_token.tk == tkRParen);
  5971. }
  5972. void Parser::FinishFncNode(ParseNodeFnc * pnodeFnc, bool fAllowIn)
  5973. {
  5974. AnalysisAssert(pnodeFnc);
  5975. // Finish the AST for a function that was deferred earlier, but which we decided
  5976. // to finish after the fact.
  5977. // We assume that the name(s) and arg(s) have already got parse nodes, so
  5978. // we just have to do the function body.
  5979. // Save the current next function Id, and resume from the old one.
  5980. Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;
  5981. Js::LocalFunctionId tempNextFunctionId = pnodeFnc->functionId + 1;
  5982. this->m_nextFunctionId = &tempNextFunctionId;
  5983. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5984. uint *pnestedCountSave = m_pnestedCount;
  5985. int32* pAstSizeSave = m_pCurrentAstSize;
  5986. m_currentNodeFunc = pnodeFnc;
  5987. m_pCurrentAstSize = &(pnodeFnc->astSize);
  5988. pnodeFnc->nestedCount = 0;
  5989. m_pnestedCount = &pnodeFnc->nestedCount;
  5990. bool fLambda = pnodeFnc->IsLambda();
  5991. bool fMethod = pnodeFnc->IsMethod();
  5992. // Cue up the parser to the start of the function body.
  5993. if (pnodeFnc->pnodeName)
  5994. {
  5995. // Skip the name(s).
  5996. this->GetScanner()->SetCurrentCharacter(pnodeFnc->pnodeName->ichLim, pnodeFnc->lineNumber);
  5997. }
  5998. else
  5999. {
  6000. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->lineNumber);
  6001. if (fMethod)
  6002. {
  6003. // Method. Skip identifier name, computed property name, "async", "get", "set", and '*' or '(' characters.
  6004. for (;;)
  6005. {
  6006. this->GetScanner()->Scan();
  6007. // '[' character indicates a computed property name for this method. We should consume it.
  6008. if (m_token.tk == tkLBrack)
  6009. {
  6010. // We don't care what the name expr is.
  6011. this->GetScanner()->Scan();
  6012. ParseExpr<false>();
  6013. Assert(m_token.tk == tkRBrack);
  6014. continue;
  6015. }
  6016. // Quit scanning ahead when we reach a '(' character which opens the arg list.
  6017. if (m_token.tk == tkLParen)
  6018. {
  6019. break;
  6020. }
  6021. }
  6022. }
  6023. else if (pnodeFnc->IsAccessor())
  6024. {
  6025. // Getter/setter. The node text starts with the name, so eat that.
  6026. this->GetScanner()->ScanNoKeywords();
  6027. }
  6028. else if (!fLambda)
  6029. {
  6030. // Anonymous function. Skip "async", "function", and '(' or '*' characters.
  6031. for (;;)
  6032. {
  6033. this->GetScanner()->Scan();
  6034. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6035. {
  6036. Assert(pnodeFnc->IsAsync());
  6037. continue;
  6038. }
  6039. // Quit scanning ahead when we reach a 'function' keyword which precedes the arg list.
  6040. if (m_token.tk == tkFUNCTION)
  6041. {
  6042. break;
  6043. }
  6044. Assert(m_token.tk == tkLParen || m_token.tk == tkStar);
  6045. }
  6046. }
  6047. }
  6048. // switch scanner to treat 'yield' as keyword in generator functions
  6049. // or as an identifier in non-generator functions
  6050. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->IsGenerator());
  6051. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(pnodeFnc && pnodeFnc->IsAsync());
  6052. // Skip the arg list.
  6053. if (!fMethod)
  6054. {
  6055. // If this is a method, we've already advanced to the '(' token.
  6056. this->GetScanner()->Scan();
  6057. }
  6058. if (m_token.tk == tkStar)
  6059. {
  6060. Assert(pnodeFnc->IsGenerator());
  6061. this->GetScanner()->ScanNoKeywords();
  6062. }
  6063. if (fLambda && m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6064. {
  6065. Assert(pnodeFnc->IsAsync());
  6066. this->GetScanner()->ScanNoKeywords();
  6067. }
  6068. Assert(m_token.tk == tkLParen || (fLambda && m_token.tk == tkID));
  6069. this->GetScanner()->ScanNoKeywords();
  6070. if (m_token.tk != tkRParen && m_token.tk != tkDArrow)
  6071. {
  6072. for (;;)
  6073. {
  6074. if (m_token.tk == tkEllipsis)
  6075. {
  6076. this->GetScanner()->ScanNoKeywords();
  6077. }
  6078. if (m_token.tk == tkID)
  6079. {
  6080. this->GetScanner()->ScanNoKeywords();
  6081. if (m_token.tk == tkAsg)
  6082. {
  6083. // Eat the default expression
  6084. this->GetScanner()->Scan();
  6085. ParseExpr<false>(koplCma);
  6086. }
  6087. }
  6088. else if (IsPossiblePatternStart())
  6089. {
  6090. ParseDestructuredLiteralWithScopeSave(tkLET, false/*isDecl*/, false /*topLevel*/);
  6091. }
  6092. else
  6093. {
  6094. AssertMsg(false, "Unexpected identifier prefix while fast-scanning formals");
  6095. }
  6096. if (m_token.tk != tkComma)
  6097. {
  6098. break;
  6099. }
  6100. this->GetScanner()->ScanNoKeywords();
  6101. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6102. {
  6103. break;
  6104. }
  6105. }
  6106. }
  6107. if (m_token.tk == tkRParen)
  6108. {
  6109. this->GetScanner()->Scan();
  6110. }
  6111. if (fLambda && m_token.tk == tkDArrow)
  6112. {
  6113. this->GetScanner()->Scan();
  6114. }
  6115. // Finish the function body.
  6116. {
  6117. // Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. "( function x(){} )".
  6118. // We lose that context here since we start from middle of function body. So save and restore source range info.
  6119. const charcount_t ichLim = pnodeFnc->ichLim;
  6120. const size_t cbLim = pnodeFnc->cbLim;
  6121. this->FinishFncDecl(pnodeFnc, NULL, fLambda, /* skipCurlyBraces */ false, fAllowIn);
  6122. #if DBG
  6123. // The pnode extent may not match the original extent.
  6124. // We expect this to happen only when there are trailing ")"'s.
  6125. // Consume them and make sure that's all we've got.
  6126. if (pnodeFnc->ichLim != ichLim)
  6127. {
  6128. Assert(pnodeFnc->ichLim < ichLim);
  6129. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichLim);
  6130. while (this->GetScanner()->IchLimTok() != ichLim)
  6131. {
  6132. this->GetScanner()->ScanNoKeywords();
  6133. Assert(m_token.tk == tkRParen);
  6134. }
  6135. }
  6136. #endif
  6137. pnodeFnc->ichLim = ichLim;
  6138. pnodeFnc->cbLim = cbLim;
  6139. }
  6140. m_currentNodeFunc = pnodeFncSave;
  6141. m_pCurrentAstSize = pAstSizeSave;
  6142. m_pnestedCount = pnestedCountSave;
  6143. Assert(m_pnestedCount);
  6144. Assert(tempNextFunctionId == pnodeFnc->deferredParseNextFunctionId);
  6145. this->m_nextFunctionId = nextFunctionIdSave;
  6146. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6147. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6148. }
  6149. void Parser::FinishFncDecl(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, bool fLambda, bool skipCurlyBraces, bool fAllowIn)
  6150. {
  6151. LPCOLESTR name = NULL;
  6152. JS_ETW(int32 startAstSize = *m_pCurrentAstSize);
  6153. if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))
  6154. {
  6155. name = GetFunctionName(pnodeFnc, pNameHint);
  6156. m_functionBody = NULL; // for nested functions we do not want to get the name of the top deferred function return name;
  6157. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, 0, m_parseType, name));
  6158. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), name, pnodeFnc->functionId);
  6159. }
  6160. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->functionId, /*Undefer*/FALSE));
  6161. // Do the work of creating an AST for a function body.
  6162. // This is common to the un-deferred case and the case in which we un-defer late in the game.
  6163. Assert(pnodeFnc->nop == knopFncDecl);
  6164. if (fLambda && m_token.tk != tkLCurly)
  6165. {
  6166. ParseExpressionLambdaBody<true>(pnodeFnc, fAllowIn);
  6167. }
  6168. else
  6169. {
  6170. if (!skipCurlyBraces)
  6171. {
  6172. ChkCurTok(tkLCurly, ERRnoLcurly);
  6173. }
  6174. ParseNodePtr * lastNodeRef = nullptr;
  6175. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true /* isSourceElementList */);
  6176. // Append an EndCode node.
  6177. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  6178. if (!skipCurlyBraces)
  6179. {
  6180. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6181. }
  6182. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  6183. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  6184. }
  6185. #ifdef ENABLE_JS_ETW
  6186. int32 astSize = *m_pCurrentAstSize - startAstSize;
  6187. EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, astSize, m_parseType, name);
  6188. #endif
  6189. }
  6190. ParseNodeVar * Parser::CreateSpecialVarDeclNode(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6191. {
  6192. ParseNodeVar * pnode = InsertVarAtBeginning(pnodeFnc, pid);
  6193. pnode->grfpn |= fpnSpecialSymbol;
  6194. // special symbol must not be global
  6195. pnode->sym->SetIsGlobal(false);
  6196. return pnode;
  6197. }
  6198. ParseNodeVar * Parser::InsertVarAtBeginning(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6199. {
  6200. ParseNodeVar * pnode = nullptr;
  6201. if (m_ppnodeVar == &pnodeFnc->pnodeVars)
  6202. {
  6203. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6204. }
  6205. else
  6206. {
  6207. ParseNodePtr * const ppnodeVarSave = m_ppnodeVar;
  6208. m_ppnodeVar = &pnodeFnc->pnodeVars;
  6209. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6210. m_ppnodeVar = ppnodeVarSave;
  6211. }
  6212. Assert(pnode);
  6213. return pnode;
  6214. }
  6215. ParseNodeVar * Parser::AddArgumentsNodeToVars(ParseNodeFnc * pnodeFnc)
  6216. {
  6217. Assert(!GetCurrentFunctionNode()->IsLambda());
  6218. ParseNodeVar * argNode = InsertVarAtBeginning(pnodeFnc, wellKnownPropertyPids.arguments);
  6219. argNode->grfpn |= PNodeFlags::fpnArguments; // Flag this as the built-in arguments node
  6220. return argNode;
  6221. }
  6222. void Parser::UpdateArgumentsNode(ParseNodeFnc * pnodeFnc, ParseNodeVar * argNode)
  6223. {
  6224. if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam) || pnodeFnc->IsLambda())
  6225. {
  6226. // There is a parameter named arguments. So we don't have to create the built-in arguments.
  6227. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6228. }
  6229. else if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) && pnodeFnc->IsBodyAndParamScopeMerged())
  6230. {
  6231. // In non-split scope case there is a var or function definition named arguments in the body
  6232. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6233. }
  6234. else
  6235. {
  6236. pnodeFnc->SetHasReferenceableBuiltInArguments(true);
  6237. Assert(argNode);
  6238. }
  6239. if (argNode != nullptr && !argNode->sym->IsArguments())
  6240. {
  6241. // A duplicate definition has updated the declaration node. Need to reset it back.
  6242. argNode->grfpn |= PNodeFlags::fpnArguments;
  6243. argNode->sym->SetDecl(argNode);
  6244. }
  6245. }
  6246. LPCOLESTR Parser::GetFunctionName(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint)
  6247. {
  6248. LPCOLESTR name = nullptr;
  6249. if (pnodeFnc->pnodeName != nullptr)
  6250. {
  6251. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  6252. name = pnodeFnc->pnodeName->pid->Psz();
  6253. }
  6254. if (name == nullptr && pNameHint != nullptr)
  6255. {
  6256. name = pNameHint;
  6257. }
  6258. if (name == nullptr && (pnodeFnc->IsLambda() ||
  6259. (!pnodeFnc->IsDeclaration() && !pnodeFnc->IsMethod())))
  6260. {
  6261. name = Js::Constants::AnonymousFunction;
  6262. }
  6263. if (name == nullptr && m_functionBody != nullptr)
  6264. {
  6265. name = m_functionBody->GetExternalDisplayName();
  6266. }
  6267. else if (name == nullptr)
  6268. {
  6269. name = Js::Constants::AnonymousFunction;
  6270. }
  6271. return name;
  6272. }
  6273. IdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)
  6274. {
  6275. if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())
  6276. {
  6277. IdentPtr pid;
  6278. if (m_token.tk == tkStrCon)
  6279. {
  6280. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6281. {
  6282. Error(ERRES5NoOctal);
  6283. }
  6284. pid = m_token.GetStr();
  6285. }
  6286. else
  6287. {
  6288. pid = m_token.GetIdentifier(this->GetHashTbl());
  6289. }
  6290. *pidHint = pid;
  6291. return pid;
  6292. }
  6293. else if (m_token.tk == tkIntCon)
  6294. {
  6295. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6296. {
  6297. Error(ERRES5NoOctal);
  6298. }
  6299. return this->GetScanner()->PidFromLong(m_token.GetLong());
  6300. }
  6301. else if (m_token.tk == tkFltCon)
  6302. {
  6303. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6304. {
  6305. Error(ERRES5NoOctal);
  6306. }
  6307. return this->GetScanner()->PidFromDbl(m_token.GetDouble());
  6308. }
  6309. Error(ERRnoMemberIdent);
  6310. }
  6311. LPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)
  6312. {
  6313. if ((pMemberName == nullptr && !isComputedName) ||
  6314. (pMemberNameHint == nullptr && isComputedName) ||
  6315. !CONFIG_FLAG(UseFullName))
  6316. {
  6317. return nullptr;
  6318. }
  6319. LPCOLESTR pFinalName = isComputedName ? pMemberNameHint : pMemberName->Psz();
  6320. uint32 fullNameHintLength = (uint32)wcslen(pFinalName);
  6321. uint32 shortNameOffset = 0;
  6322. if (!isStatic)
  6323. {
  6324. // Add prototype.
  6325. pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);
  6326. }
  6327. if (pClassName)
  6328. {
  6329. uint32 classNameOffset = 0;
  6330. pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);
  6331. shortNameOffset += classNameOffset;
  6332. }
  6333. if (pGetSet)
  6334. {
  6335. // displays as get/set prototype.funcname
  6336. uint32 getSetOffset = 0;
  6337. pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);
  6338. shortNameOffset += getSetOffset;
  6339. }
  6340. *nameLength = fullNameHintLength;
  6341. *pShortNameOffset = shortNameOffset;
  6342. return pFinalName;
  6343. }
  6344. template<bool buildAST>
  6345. ParseNodeClass * Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)
  6346. {
  6347. bool hasConstructor = false;
  6348. bool hasExtends = false;
  6349. IdentPtr name = nullptr;
  6350. ParseNodeVar * pnodeName = nullptr;
  6351. ParseNodeFnc * pnodeConstructor = nullptr;
  6352. ParseNodePtr pnodeExtends = nullptr;
  6353. ParseNodePtr pnodeMembers = nullptr;
  6354. ParseNodePtr *lastMemberNodeRef = nullptr;
  6355. ParseNodePtr pnodeStaticMembers = nullptr;
  6356. ParseNodePtr *lastStaticMemberNodeRef = nullptr;
  6357. uint32 nameHintLength = pHintLength ? *pHintLength : 0;
  6358. uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;
  6359. ArenaAllocator tempAllocator(_u("ClassMemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  6360. size_t cbMinConstructor = 0;
  6361. ParseNodeClass * pnodeClass = nullptr;
  6362. if (buildAST)
  6363. {
  6364. pnodeClass = CreateNodeForOpT<knopClassDecl>();
  6365. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Class, m_scriptContext);
  6366. cbMinConstructor = this->GetScanner()->IecpMinTok();
  6367. }
  6368. this->GetScanner()->Scan();
  6369. if (m_token.tk == tkID)
  6370. {
  6371. name = m_token.GetIdentifier(this->GetHashTbl());
  6372. this->GetScanner()->Scan();
  6373. }
  6374. else if (isDeclaration)
  6375. {
  6376. IdentifierExpectedError(m_token);
  6377. }
  6378. if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  6379. {
  6380. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  6381. }
  6382. BOOL strictSave = m_fUseStrictMode;
  6383. m_fUseStrictMode = TRUE;
  6384. ParseNodeVar * pnodeDeclName = nullptr;
  6385. if (isDeclaration)
  6386. {
  6387. pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);
  6388. }
  6389. ParseNodePtr *ppnodeScopeSave = nullptr;
  6390. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  6391. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  6392. if (buildAST)
  6393. {
  6394. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  6395. pnodeClass->pnodeBlock = pnodeBlock;
  6396. }
  6397. if (name)
  6398. {
  6399. pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);
  6400. }
  6401. if (m_token.tk == tkEXTENDS)
  6402. {
  6403. this->GetScanner()->Scan();
  6404. pnodeExtends = ParseTerm<buildAST>();
  6405. hasExtends = true;
  6406. }
  6407. if (m_token.tk != tkLCurly)
  6408. {
  6409. Error(ERRnoLcurly);
  6410. }
  6411. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Parsing class (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6412. RestorePoint beginClass;
  6413. this->GetScanner()->Capture(&beginClass);
  6414. this->GetScanner()->ScanForcingPid();
  6415. IdentPtr pClassNamePid = pnodeName ? pnodeName->pid : nullptr;
  6416. for (;;)
  6417. {
  6418. if (m_token.tk == tkSColon)
  6419. {
  6420. this->GetScanner()->ScanForcingPid();
  6421. continue;
  6422. }
  6423. if (m_token.tk == tkRCurly)
  6424. {
  6425. break;
  6426. }
  6427. bool isStatic = false;
  6428. if (m_token.tk == tkSTATIC)
  6429. {
  6430. // 'static' can be used as an IdentifierName here, even in strict mode code. We need to see the next token before we know
  6431. // if this is being used as a keyword. This is similar to the way we treat 'let' in some cases.
  6432. // See https://tc39.github.io/ecma262/#sec-keywords for more info.
  6433. RestorePoint beginStatic;
  6434. this->GetScanner()->Capture(&beginStatic);
  6435. this->GetScanner()->ScanForcingPid();
  6436. if (m_token.tk == tkLParen)
  6437. {
  6438. this->GetScanner()->SeekTo(beginStatic);
  6439. }
  6440. else
  6441. {
  6442. isStatic = true;
  6443. }
  6444. }
  6445. ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;
  6446. charcount_t ichMin = 0;
  6447. size_t iecpMin = 0;
  6448. ParseNodePtr pnodeMemberName = nullptr;
  6449. IdentPtr pidHint = nullptr;
  6450. IdentPtr memberPid = nullptr;
  6451. LPCOLESTR pMemberNameHint = nullptr;
  6452. uint32 memberNameHintLength = 0;
  6453. uint32 memberNameOffset = 0;
  6454. bool isComputedName = false;
  6455. bool isAsyncMethod = false;
  6456. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  6457. {
  6458. RestorePoint parsedAsync;
  6459. this->GetScanner()->Capture(&parsedAsync);
  6460. ichMin = this->GetScanner()->IchMinTok();
  6461. iecpMin = this->GetScanner()->IecpMinTok();
  6462. this->GetScanner()->Scan();
  6463. if (m_token.tk == tkLParen || this->GetScanner()->FHadNewLine())
  6464. {
  6465. this->GetScanner()->SeekTo(parsedAsync);
  6466. }
  6467. else
  6468. {
  6469. isAsyncMethod = true;
  6470. }
  6471. }
  6472. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  6473. m_token.tk == tkStar;
  6474. if (isGenerator)
  6475. {
  6476. fncDeclFlags |= fFncGenerator;
  6477. this->GetScanner()->ScanForcingPid();
  6478. }
  6479. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6480. {
  6481. // Computed member name: [expr] () { }
  6482. LPCOLESTR emptyHint = nullptr;
  6483. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6484. isComputedName = true;
  6485. }
  6486. else // not computed name
  6487. {
  6488. memberPid = this->ParseClassPropertyName(&pidHint);
  6489. if (pidHint)
  6490. {
  6491. pMemberNameHint = pidHint->Psz();
  6492. memberNameHintLength = pidHint->Cch();
  6493. }
  6494. }
  6495. if (buildAST && memberPid)
  6496. {
  6497. pnodeMemberName = CreateStrNode(memberPid);
  6498. }
  6499. if (!isStatic && memberPid == wellKnownPropertyPids.constructor)
  6500. {
  6501. if (hasConstructor || isAsyncMethod)
  6502. {
  6503. Error(ERRsyntax);
  6504. }
  6505. hasConstructor = true;
  6506. LPCOLESTR pConstructorName = nullptr;
  6507. uint32 constructorNameLength = 0;
  6508. uint32 constructorShortNameHintOffset = 0;
  6509. if (pnodeName && pnodeName->pid)
  6510. {
  6511. pConstructorName = pnodeName->pid->Psz();
  6512. constructorNameLength = pnodeName->pid->Cch();
  6513. }
  6514. else
  6515. {
  6516. pConstructorName = pNameHint;
  6517. constructorNameLength = nameHintLength;
  6518. constructorShortNameHintOffset = nameHintOffset;
  6519. }
  6520. {
  6521. SuperRestrictionState::State state = hasExtends ? SuperRestrictionState::CallAndPropertyAllowed : SuperRestrictionState::PropertyAllowed;
  6522. // Add the class constructor flag and base class constructor flag if pnodeExtends is nullptr
  6523. fncDeclFlags |= fFncClassConstructor | (hasExtends ? kFunctionNone : fFncBaseClassConstructor);
  6524. pnodeConstructor = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, state, pConstructorName, /* needsPIDOnRCurlyScan */ true);
  6525. }
  6526. if (pnodeConstructor->IsGenerator())
  6527. {
  6528. Error(ERRConstructorCannotBeGenerator);
  6529. }
  6530. Assert(constructorNameLength >= constructorShortNameHintOffset);
  6531. // The constructor function will get the same name as class.
  6532. pnodeConstructor->hint = pConstructorName;
  6533. pnodeConstructor->hintLength = constructorNameLength;
  6534. pnodeConstructor->hintOffset = constructorShortNameHintOffset;
  6535. pnodeConstructor->pid = pnodeName && pnodeName->pid ? pnodeName->pid : wellKnownPropertyPids.constructor;
  6536. pnodeConstructor->SetHasNonThisStmt();
  6537. pnodeConstructor->SetHasComputedName();
  6538. pnodeConstructor->SetHasHomeObj();
  6539. }
  6540. else
  6541. {
  6542. ParseNodePtr pnodeMember = nullptr;
  6543. bool isMemberNamedGetOrSet = false;
  6544. RestorePoint beginMethodName;
  6545. this->GetScanner()->Capture(&beginMethodName);
  6546. if (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set)
  6547. {
  6548. this->GetScanner()->ScanForcingPid();
  6549. }
  6550. if (m_token.tk == tkLParen)
  6551. {
  6552. this->GetScanner()->SeekTo(beginMethodName);
  6553. isMemberNamedGetOrSet = true;
  6554. }
  6555. if ((memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set) && !isMemberNamedGetOrSet)
  6556. {
  6557. bool isGetter = (memberPid == wellKnownPropertyPids.get);
  6558. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6559. {
  6560. // Computed get/set member name: get|set [expr] () { }
  6561. LPCOLESTR emptyHint = nullptr;
  6562. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6563. isComputedName = true;
  6564. }
  6565. else // not computed name
  6566. {
  6567. memberPid = this->ParseClassPropertyName(&pidHint);
  6568. }
  6569. if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)
  6570. {
  6571. Error(ERRsyntax);
  6572. }
  6573. if (buildAST && memberPid && !isComputedName)
  6574. {
  6575. pnodeMemberName = CreateStrNode(memberPid);
  6576. }
  6577. ParseNodeFnc * pnodeFnc = nullptr;
  6578. {
  6579. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),
  6580. SuperRestrictionState::PropertyAllowed, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true);
  6581. }
  6582. pnodeFnc->SetIsStaticMember(isStatic);
  6583. if (isComputedName)
  6584. {
  6585. pnodeFnc->SetHasComputedName();
  6586. }
  6587. pnodeFnc->SetHasHomeObj();
  6588. if (buildAST)
  6589. {
  6590. pnodeFnc->SetIsAccessor();
  6591. pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);
  6592. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,
  6593. isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,
  6594. &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6595. }
  6596. }
  6597. else
  6598. {
  6599. if (isStatic && (memberPid == wellKnownPropertyPids.prototype))
  6600. {
  6601. Error(ERRsyntax);
  6602. }
  6603. ParseNodeFnc * pnodeFnc = nullptr;
  6604. {
  6605. if (isAsyncMethod)
  6606. {
  6607. fncDeclFlags |= fFncAsync;
  6608. }
  6609. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, SuperRestrictionState::PropertyAllowed, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true);
  6610. if (isAsyncMethod)
  6611. {
  6612. pnodeFnc->cbMin = iecpMin;
  6613. pnodeFnc->ichMin = ichMin;
  6614. }
  6615. }
  6616. pnodeFnc->SetIsStaticMember(isStatic);
  6617. if (isComputedName)
  6618. {
  6619. pnodeFnc->SetHasComputedName();
  6620. }
  6621. pnodeFnc->SetHasHomeObj();
  6622. if (buildAST)
  6623. {
  6624. pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);
  6625. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr /*pgetset*/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6626. }
  6627. }
  6628. if (buildAST)
  6629. {
  6630. Assert(memberNameHintLength >= memberNameOffset);
  6631. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pMemberNameHint; // Fully qualified name
  6632. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = memberNameHintLength;
  6633. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = memberNameOffset;
  6634. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->pid = memberPid; // Short name
  6635. AddToNodeList(isStatic ? &pnodeStaticMembers : &pnodeMembers, isStatic ? &lastStaticMemberNodeRef : &lastMemberNodeRef, pnodeMember);
  6636. }
  6637. }
  6638. }
  6639. size_t cbLimConstructor = 0;
  6640. if (buildAST)
  6641. {
  6642. pnodeClass->ichLim = this->GetScanner()->IchLimTok();
  6643. cbLimConstructor = this->GetScanner()->IecpLimTok();
  6644. }
  6645. if (!hasConstructor)
  6646. {
  6647. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Generating constructor (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6648. RestorePoint endClass;
  6649. this->GetScanner()->Capture(&endClass);
  6650. this->GetScanner()->SeekTo(beginClass);
  6651. pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);
  6652. if (buildAST)
  6653. {
  6654. if (pClassNamePid)
  6655. {
  6656. pnodeConstructor->hint = pClassNamePid->Psz();
  6657. pnodeConstructor->hintLength = pClassNamePid->Cch();
  6658. pnodeConstructor->hintOffset = 0;
  6659. }
  6660. else
  6661. {
  6662. Assert(nameHintLength >= nameHintOffset);
  6663. pnodeConstructor->hint = pNameHint;
  6664. pnodeConstructor->hintLength = nameHintLength;
  6665. pnodeConstructor->hintOffset = nameHintOffset;
  6666. }
  6667. pnodeConstructor->pid = pClassNamePid;
  6668. }
  6669. this->GetScanner()->SeekTo(endClass);
  6670. }
  6671. if (buildAST)
  6672. {
  6673. pnodeConstructor->cbMin = cbMinConstructor;
  6674. pnodeConstructor->cbLim = cbLimConstructor;
  6675. pnodeConstructor->ichMin = pnodeClass->ichMin;
  6676. pnodeConstructor->ichLim = pnodeClass->ichLim;
  6677. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  6678. pnodeClass->pnodeDeclName = pnodeDeclName;
  6679. pnodeClass->pnodeName = pnodeName;
  6680. pnodeClass->pnodeConstructor = pnodeConstructor;
  6681. pnodeClass->pnodeExtends = pnodeExtends;
  6682. pnodeClass->pnodeMembers = pnodeMembers;
  6683. pnodeClass->pnodeStaticMembers = pnodeStaticMembers;
  6684. pnodeClass->isDefaultModuleExport = false;
  6685. }
  6686. FinishParseBlock(pnodeBlock);
  6687. m_fUseStrictMode = strictSave;
  6688. this->GetScanner()->Scan();
  6689. return pnodeClass;
  6690. }
  6691. template<bool buildAST>
  6692. ParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)
  6693. {
  6694. ParseNodePtr pnodeStringLiterals = nullptr;
  6695. ParseNodePtr* lastStringLiteralNodeRef = nullptr;
  6696. ParseNodePtr pnodeRawStringLiterals = nullptr;
  6697. ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;
  6698. ParseNodePtr pnodeSubstitutionExpressions = nullptr;
  6699. ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;
  6700. ParseNodePtr pnodeTagFncArgs = nullptr;
  6701. ParseNodePtr* lastTagFncArgNodeRef = nullptr;
  6702. ParseNodeStr * stringLiteral = nullptr;
  6703. ParseNodeStr * stringLiteralRaw = nullptr;
  6704. ParseNodeStrTemplate * pnodeStringTemplate = nullptr;
  6705. ParseNode * pnodeReturn = nullptr;
  6706. bool templateClosed = false;
  6707. const bool isTagged = pnodeTagFnc != nullptr;
  6708. uint16 stringConstantCount = 0;
  6709. charcount_t ichMin = 0;
  6710. Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);
  6711. if (buildAST)
  6712. {
  6713. pnodeReturn = pnodeStringTemplate = CreateNodeForOpT<knopStrTemplate>();
  6714. pnodeStringTemplate->countStringLiterals = 0;
  6715. pnodeStringTemplate->isTaggedTemplate = isTagged ? TRUE : FALSE;
  6716. // If this is a tagged string template, we need to start building the arg list for the call
  6717. if (isTagged)
  6718. {
  6719. ichMin = pnodeTagFnc->ichMin;
  6720. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);
  6721. }
  6722. }
  6723. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StringTemplates, m_scriptContext);
  6724. OUTPUT_TRACE_DEBUGONLY(
  6725. Js::StringTemplateParsePhase,
  6726. _u("Starting to parse a string template (%s)...\n\tis tagged = %s\n"),
  6727. GetParseType(),
  6728. isTagged ? _u("true") : _u("false (Raw and cooked strings will not differ!)"));
  6729. // String template grammar
  6730. // `...` Simple string template
  6731. // `...${ String template beginning
  6732. // }...${ String template middle
  6733. // }...` String template end
  6734. while (!templateClosed)
  6735. {
  6736. // First, extract the string constant part - we always have one
  6737. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6738. {
  6739. Error(ERRES5NoOctal);
  6740. }
  6741. // We are not able to pass more than a ushort worth of arguments to the tag
  6742. // so use that as a logical limit on the number of string constant pieces.
  6743. if (stringConstantCount >= Js::Constants::MaxAllowedArgs)
  6744. {
  6745. Error(ERRTooManyArgs);
  6746. }
  6747. // Keep track of the string literal count (must be the same for raw strings)
  6748. // We use this in code gen so we don't need to count the string literals list
  6749. stringConstantCount++;
  6750. // If we are not creating parse nodes, there is no need to create strings
  6751. if (buildAST)
  6752. {
  6753. stringLiteral = CreateStrNode(m_token.GetStr());
  6754. AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);
  6755. // We only need to collect a raw string when we are going to pass the string template to a tag
  6756. if (isTagged)
  6757. {
  6758. // Make the scanner create a PID for the raw string constant for the preceding scan
  6759. IdentPtr pid = this->GetScanner()->GetSecondaryBufferAsPid();
  6760. stringLiteralRaw = CreateStrNode(pid);
  6761. // Should have gotten a raw string literal above
  6762. AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);
  6763. }
  6764. else
  6765. {
  6766. #if DBG
  6767. // Assign the raw string for debug tracing below
  6768. stringLiteralRaw = stringLiteral;
  6769. #endif
  6770. }
  6771. OUTPUT_TRACE_DEBUGONLY(
  6772. Js::StringTemplateParsePhase,
  6773. _u("Parsed string constant: \n\tcooked = \"%s\" \n\traw = \"%s\" \n\tdiffer = %d\n"),
  6774. stringLiteral->pid->Psz(),
  6775. stringLiteralRaw->pid->Psz(),
  6776. stringLiteral->pid->Psz() == stringLiteralRaw->pid->Psz() ? 0 : 1);
  6777. }
  6778. switch (m_token.tk)
  6779. {
  6780. case tkStrTmplEnd:
  6781. case tkStrTmplBasic:
  6782. // We do not need to parse an expression for either the end or basic string template tokens
  6783. templateClosed = true;
  6784. break;
  6785. case tkStrTmplBegin:
  6786. case tkStrTmplMid:
  6787. {
  6788. // In the middle or begin string template token case, we need to parse an expression next
  6789. this->GetScanner()->Scan();
  6790. // Parse the contents of the curly braces as an expression
  6791. ParseNodePtr expression = ParseExpr<buildAST>(0);
  6792. // After parsing expression, scan should leave us with an RCurly token.
  6793. // Use the NoScan version so we do not automatically perform a scan - we need to
  6794. // set the scan state before next scan but we don't want to set that state if
  6795. // the token is not as expected since we'll error in that case.
  6796. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6797. // Notify the scanner that it should scan for a middle or end string template token
  6798. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  6799. this->GetScanner()->Scan();
  6800. if (buildAST)
  6801. {
  6802. // If we are going to call the tag function, add this expression into the list of args
  6803. if (isTagged)
  6804. {
  6805. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);
  6806. }
  6807. else
  6808. {
  6809. // Otherwise add it to the substitution expression list
  6810. // TODO: Store the arguments and substitution expressions in a single list?
  6811. AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);
  6812. }
  6813. }
  6814. if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))
  6815. {
  6816. // Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return
  6817. // tkStrTmpMid/End unless it is EOF or tkScanError
  6818. Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);
  6819. Error(ERRsyntax);
  6820. }
  6821. OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u("Parsed expression\n"));
  6822. }
  6823. break;
  6824. default:
  6825. Assert(false);
  6826. break;
  6827. }
  6828. }
  6829. if (buildAST)
  6830. {
  6831. pnodeStringTemplate->pnodeStringLiterals = pnodeStringLiterals;
  6832. pnodeStringTemplate->pnodeStringRawLiterals = pnodeRawStringLiterals;
  6833. pnodeStringTemplate->pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;
  6834. pnodeStringTemplate->countStringLiterals = stringConstantCount;
  6835. // We should still have the last string literal.
  6836. // Use the char offset of the end of that constant as the end of the string template.
  6837. pnodeStringTemplate->ichLim = stringLiteral->ichLim;
  6838. // If this is a tagged template, we now have the argument list and can construct a call node
  6839. if (isTagged)
  6840. {
  6841. // Return the call node here and let the byte code generator Emit the string template automagically
  6842. ParseNodeCall * pnodeCall;
  6843. pnodeReturn = pnodeCall = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);
  6844. // We need to set the arg count explicitly
  6845. pnodeCall->argCount = stringConstantCount;
  6846. pnodeCall->hasDestructuring = m_hasDestructuringPattern;
  6847. }
  6848. }
  6849. this->GetScanner()->Scan();
  6850. return pnodeReturn;
  6851. }
  6852. LPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)
  6853. {
  6854. // propertyString could be null, such as 'this.foo' =
  6855. // propertyString could be empty, found in pattern as in (-1)[""][(x = z)]
  6856. OpCode op = pNode->nop;
  6857. LPCOLESTR rightNode = nullptr;
  6858. if (propertyString == nullptr)
  6859. {
  6860. propertyString = _u("");
  6861. }
  6862. if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)
  6863. {
  6864. rightNode = _u("");
  6865. }
  6866. else if (op == knopStr)
  6867. {
  6868. return AppendNameHints(propertyString, pNode->AsParseNodeStr()->pid, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  6869. }
  6870. else if (op == knopFlt)
  6871. {
  6872. rightNode = this->GetScanner()->StringFromDbl(pNode->AsParseNodeFloat()->dbl);
  6873. }
  6874. else
  6875. {
  6876. rightNode = op == knopInt ? this->GetScanner()->StringFromLong(pNode->AsParseNodeInt()->lw)
  6877. : pNode->AsParseNodeName()->pid->Psz();
  6878. }
  6879. return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  6880. }
  6881. LPCOLESTR Parser::ConstructNameHint(ParseNodeBin * pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)
  6882. {
  6883. Assert(pNode != nullptr);
  6884. Assert(pNode->nop == knopDot || pNode->nop == knopIndex);
  6885. // This method recursively visits nodes in the AST and could cause an SOE crash for long knopDot chains.
  6886. // Although this method could be made non-recursive, Emit (ByteCodeEmitter.cpp) hits a stack probe
  6887. // for shorter chains than which cause SOE here, so add a stack probe to throw SOE rather than crash on SOE.
  6888. // Because of that correspondence, use Js::Constants::MinStackByteCodeVisitor (which is used in Emit)
  6889. // for the stack probe here. See OS#14711878.
  6890. PROBE_STACK_NO_DISPOSE(this->m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  6891. LPCOLESTR leftNode = nullptr;
  6892. if (pNode->pnode1->nop == knopDot || pNode->pnode1->nop == knopIndex)
  6893. {
  6894. leftNode = ConstructNameHint(pNode->pnode1->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  6895. }
  6896. else if (pNode->pnode1->nop == knopName && !pNode->pnode1->AsParseNodeName()->IsSpecialName())
  6897. {
  6898. // We need to skip special names like 'this' because those shouldn't be appended to the
  6899. // name hint in the debugger stack trace.
  6900. // function ctor() {
  6901. // this.func = function() {
  6902. // // If we break here, the stack should say we are in 'func' and not 'this.func'
  6903. // }
  6904. // }
  6905. IdentPtr pid = pNode->pnode1->AsParseNodeName()->pid;
  6906. leftNode = pid->Psz();
  6907. *fullNameHintLength = pid->Cch();
  6908. *pShortNameOffset = 0;
  6909. }
  6910. if (pNode->nop == knopIndex)
  6911. {
  6912. return FormatPropertyString(
  6913. leftNode ? leftNode : Js::Constants::AnonymousFunction, // e.g. f()[0] = function () {}
  6914. pNode->pnode2, fullNameHintLength, pShortNameOffset);
  6915. }
  6916. Assert(pNode->pnode2->nop == knopDot || pNode->pnode2->nop == knopName);
  6917. LPCOLESTR rightNode = nullptr;
  6918. bool wrapWithBrackets = false;
  6919. if (pNode->pnode2->nop == knopDot)
  6920. {
  6921. rightNode = ConstructNameHint(pNode->pnode2->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  6922. }
  6923. else
  6924. {
  6925. rightNode = pNode->pnode2->AsParseNodeName()->pid->Psz();
  6926. wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);
  6927. }
  6928. Assert(rightNode != nullptr);
  6929. return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);
  6930. }
  6931. LPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  6932. {
  6933. Assert(rightStr != nullptr);
  6934. Assert(leftLen != 0 || wrapInBrackets);
  6935. Assert(rightLen != 0 || wrapInBrackets);
  6936. 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
  6937. uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); // 1 (for dot or [) + 1 (for null termination)
  6938. if (wrapInBrackets)
  6939. {
  6940. totalLength++; //1 for ']';
  6941. }
  6942. WCHAR * finalName = AllocateStringOfLength(totalLength);
  6943. if (leftStr != nullptr && leftLen != 0)
  6944. {
  6945. wcscpy_s(finalName, leftLen + 1, leftStr);
  6946. }
  6947. if (ignoreAddDotWithSpace)
  6948. {
  6949. finalName[leftLen++] = (OLECHAR)_u(' ');
  6950. }
  6951. // mutually exclusive from ignoreAddDotWithSpace which is used for getters/setters
  6952. else if (wrapInBrackets)
  6953. {
  6954. finalName[leftLen++] = (OLECHAR)_u('[');
  6955. finalName[totalLength - 2] = (OLECHAR)_u(']');
  6956. }
  6957. else if (!ignoreDot)
  6958. {
  6959. finalName[leftLen++] = (OLECHAR)_u('.');
  6960. }
  6961. //ignore case falls through
  6962. js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);
  6963. finalName[totalLength - 1] = (OLECHAR)_u('\0');
  6964. if (pNameLength != nullptr)
  6965. {
  6966. *pNameLength = totalLength - 1;
  6967. }
  6968. if (pShortNameOffset != nullptr)
  6969. {
  6970. *pShortNameOffset = leftLen;
  6971. }
  6972. return finalName;
  6973. }
  6974. WCHAR * Parser::AllocateStringOfLength(ULONG length)
  6975. {
  6976. Assert(length > 0);
  6977. ULONG totalBytes;
  6978. if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)
  6979. {
  6980. Error(ERRnoMemory);
  6981. }
  6982. WCHAR* finalName = (WCHAR*)this->GetHashTbl()->GetAllocator()->Alloc(totalBytes);
  6983. if (finalName == nullptr)
  6984. {
  6985. Error(ERRnoMemory);
  6986. }
  6987. return finalName;
  6988. }
  6989. LPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  6990. {
  6991. if (pShortNameOffset != nullptr)
  6992. {
  6993. *pShortNameOffset = 0;
  6994. }
  6995. if (left == nullptr && !wrapInBrackets)
  6996. {
  6997. if (right)
  6998. {
  6999. *pNameLength = right->Cch();
  7000. return right->Psz();
  7001. }
  7002. return nullptr;
  7003. }
  7004. uint32 leftLen = 0;
  7005. LPCOLESTR leftStr = _u("");
  7006. if (left != nullptr) // if wrapInBrackets is true
  7007. {
  7008. leftStr = left->Psz();
  7009. leftLen = left->Cch();
  7010. }
  7011. if (right == nullptr)
  7012. {
  7013. *pNameLength = leftLen;
  7014. return left->Psz();
  7015. }
  7016. uint32 rightLen = right->Cch();
  7017. return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7018. }
  7019. LPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7020. {
  7021. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7022. if (pShortNameOffset != nullptr)
  7023. {
  7024. *pShortNameOffset = 0;
  7025. }
  7026. Assert(rightLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7027. if (left == nullptr && !wrapInBrackets)
  7028. {
  7029. *pNameLength = rightLen;
  7030. return right;
  7031. }
  7032. LPCOLESTR leftStr = _u("");
  7033. uint32 leftLen = 0;
  7034. if (left != nullptr) // if wrapInBrackets is true
  7035. {
  7036. leftStr = left->Psz();
  7037. leftLen = left->Cch();
  7038. }
  7039. if (rightLen == 0 && !wrapInBrackets)
  7040. {
  7041. *pNameLength = leftLen;
  7042. return left->Psz();
  7043. }
  7044. return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7045. }
  7046. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7047. {
  7048. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7049. if (pShortNameOffset != nullptr)
  7050. {
  7051. *pShortNameOffset = 0;
  7052. }
  7053. Assert(leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7054. if (left == nullptr || (leftLen == 0 && !wrapInBrackets))
  7055. {
  7056. if (right != nullptr)
  7057. {
  7058. *pNameLength = right->Cch();
  7059. return right->Psz();
  7060. }
  7061. return nullptr;
  7062. }
  7063. if (right == nullptr)
  7064. {
  7065. *pNameLength = leftLen;
  7066. return left;
  7067. }
  7068. uint32 rightLen = right->Cch();
  7069. return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7070. }
  7071. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7072. {
  7073. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7074. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7075. if (pShortNameOffset != nullptr)
  7076. {
  7077. *pShortNameOffset = 0;
  7078. }
  7079. Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7080. if (leftLen == 0 && !wrapInBrackets)
  7081. {
  7082. *pNameLength = right ? rightLen : 0;
  7083. return right;
  7084. }
  7085. if (rightLen == 0 && !wrapInBrackets)
  7086. {
  7087. *pNameLength = leftLen;
  7088. return left;
  7089. }
  7090. return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7091. }
  7092. /**
  7093. * Emits a spread error if there is no ambiguity, or marks defers the error for
  7094. * when we can determine if it is a rest error or a spread error.
  7095. *
  7096. * The ambiguity arises when we are parsing a lambda parameter list but we have
  7097. * not seen the => token. At this point, we are either in a parenthesized
  7098. * expression or a parameter list, and cannot issue an error until the matching
  7099. * RParen has been scanned.
  7100. *
  7101. * The actual emission of the error happens in ParseExpr, when we first know if
  7102. * the expression is a lambda parameter list or not.
  7103. *
  7104. */
  7105. void Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)
  7106. {
  7107. if (m_funcParenExprDepth > 0)
  7108. {
  7109. if (m_token.tk == tkRParen)
  7110. {
  7111. if (!m_deferEllipsisError)
  7112. {
  7113. // Capture only the first error instance. Because a lambda will cause a reparse in a formals context, we can assume
  7114. // that this will be a spread error. Nested paren exprs will have their own error instance.
  7115. this->GetScanner()->Capture(&m_deferEllipsisErrorLoc);
  7116. m_deferEllipsisError = true;
  7117. }
  7118. }
  7119. else
  7120. {
  7121. Error(ERRUnexpectedEllipsis);
  7122. }
  7123. }
  7124. else
  7125. {
  7126. Error(ERRInvalidSpreadUse);
  7127. }
  7128. }
  7129. bool Parser::IsTerminateToken(bool fAllowIn)
  7130. {
  7131. return (m_token.tk == tkRCurly ||
  7132. m_token.tk == tkRBrack ||
  7133. m_token.tk == tkRParen ||
  7134. m_token.tk == tkSColon ||
  7135. m_token.tk == tkColon ||
  7136. m_token.tk == tkComma ||
  7137. m_token.tk == tkLimKwd ||
  7138. (m_token.tk == tkIN && fAllowIn) ||
  7139. this->GetScanner()->FHadNewLine());
  7140. }
  7141. /***************************************************************************
  7142. Parse an optional sub expression returning null if there was no expression.
  7143. Checks for no expression by looking for a token that can follow an
  7144. Expression grammar production.
  7145. ***************************************************************************/
  7146. template<bool buildAST>
  7147. bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
  7148. {
  7149. *pnode = nullptr;
  7150. if (IsTerminateToken(!fAllowIn))
  7151. {
  7152. return false;
  7153. }
  7154. IdentToken token;
  7155. ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
  7156. // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
  7157. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7158. // is not detected at byte code gen time because of deferred parsing.
  7159. this->MarkEscapingRef(pnodeT, &token);
  7160. if (pToken)
  7161. {
  7162. *pToken = token;
  7163. }
  7164. *pnode = pnodeT;
  7165. return true;
  7166. }
  7167. /***************************************************************************
  7168. Parse a sub expression.
  7169. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7170. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7171. ***************************************************************************/
  7172. template<bool buildAST>
  7173. ParseNodePtr Parser::ParseExpr(int oplMin,
  7174. BOOL *pfCanAssign,
  7175. BOOL fAllowIn,
  7176. BOOL fAllowEllipsis,
  7177. LPCOLESTR pNameHint,
  7178. uint32 *pHintLength,
  7179. uint32 *pShortNameOffset,
  7180. _Inout_opt_ IdentToken* pToken,
  7181. bool fUnaryOrParen,
  7182. _Inout_opt_ bool* pfLikelyPattern,
  7183. _Inout_opt_ charcount_t *plastRParen)
  7184. {
  7185. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  7186. int opl;
  7187. OpCode nop;
  7188. charcount_t ichMin;
  7189. ParseNodePtr pnode = nullptr;
  7190. ParseNodePtr pnodeT = nullptr;
  7191. BOOL fCanAssign = TRUE;
  7192. bool assignmentStmt = false;
  7193. bool fIsDotOrIndex = false;
  7194. IdentToken term;
  7195. RestorePoint termStart;
  7196. uint32 hintLength = 0;
  7197. uint32 hintOffset = 0;
  7198. BOOL fLikelyPattern = FALSE;
  7199. ParserState parserState;
  7200. if (pHintLength != nullptr)
  7201. {
  7202. hintLength = *pHintLength;
  7203. }
  7204. if (pShortNameOffset != nullptr)
  7205. {
  7206. hintOffset = *pShortNameOffset;
  7207. }
  7208. EnsureStackAvailable();
  7209. // Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.
  7210. CaptureState(&parserState);
  7211. this->GetScanner()->Capture(&termStart);
  7212. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  7213. m_hasDeferredShorthandInitError = false;
  7214. // Is the current token a unary operator?
  7215. if (this->GetHashTbl()->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)
  7216. {
  7217. IdentToken operandToken;
  7218. ichMin = this->GetScanner()->IchMinTok();
  7219. if (nop == knopYield)
  7220. {
  7221. if (!this->GetScanner()->YieldIsKeywordRegion() || oplMin > opl)
  7222. {
  7223. // The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner
  7224. // is not treating yield as a keyword (!this->GetScanner()->YieldIsKeywordRegion()) occurs
  7225. // in strict mode non-generator function contexts.
  7226. //
  7227. // That is, 'yield' is a keyword because of strict mode, but YieldExpression
  7228. // is not a grammar production outside of generator functions.
  7229. //
  7230. // Otherwise it is an error for a yield to appear in the context of a higher level
  7231. // binding operator, be it unary or binary.
  7232. Error(ERRsyntax);
  7233. }
  7234. if(m_currentScope->AncestorScopeIsParameter()) // Yield is not allowed within any parameter scope
  7235. {
  7236. Error(ERRsyntax);
  7237. }
  7238. }
  7239. else if (nop == knopAwait)
  7240. {
  7241. if (!this->GetScanner()->AwaitIsKeywordRegion() ||
  7242. m_currentScope->AncestorScopeIsParameter()) // Await is not allowed within any parameter scope
  7243. {
  7244. // As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)
  7245. // but the scanner is not treating await as a keyword (!this->GetScanner()->AwaitIsKeyword())
  7246. // occurs in strict mode non-async function contexts.
  7247. //
  7248. // That is, 'await' is a keyword because of strict mode, but AwaitExpression
  7249. // is not a grammar production outside of async functions.
  7250. //
  7251. // Further, await expressions are disallowed within parameter scopes.
  7252. Error(ERRBadAwait);
  7253. }
  7254. }
  7255. this->GetScanner()->Scan();
  7256. if (m_token.tk == tkEllipsis) {
  7257. // ... cannot have a unary prefix.
  7258. Error(ERRUnexpectedEllipsis);
  7259. }
  7260. if (nop == knopYield && !this->GetScanner()->FHadNewLine() && m_token.tk == tkStar)
  7261. {
  7262. this->GetScanner()->Scan();
  7263. nop = knopYieldStar;
  7264. }
  7265. if (nop == knopYield)
  7266. {
  7267. if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, fAllowIn, fAllowEllipsis))
  7268. {
  7269. nop = knopYieldLeaf;
  7270. if (buildAST)
  7271. {
  7272. pnode = CreateNodeForOpT<knopYieldLeaf>(ichMin, this->GetScanner()->IchLimTok());
  7273. }
  7274. }
  7275. }
  7276. else if (nop == knopAwait && m_token.tk == tkColon)
  7277. {
  7278. Error(ERRAwaitAsLabelInAsync);
  7279. }
  7280. else
  7281. {
  7282. // Disallow spread after a unary operator.
  7283. pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr /*hint*/, nullptr /*hintLength*/, nullptr /*hintOffset*/, &operandToken, true, nullptr, plastRParen);
  7284. }
  7285. if (nop != knopYieldLeaf)
  7286. {
  7287. if ((nop == knopIncPre || nop == knopDecPre) && (m_token.tk != tkDArrow))
  7288. {
  7289. if (!fCanAssign &&
  7290. (m_sourceContextInfo
  7291. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7292. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7293. {
  7294. Error(JSERR_CantAssignTo);
  7295. }
  7296. TrackAssignment<buildAST>(pnodeT, &operandToken);
  7297. if (buildAST)
  7298. {
  7299. if (IsStrictMode() && pnodeT->nop == knopName)
  7300. {
  7301. CheckStrictModeEvalArgumentsUsage(pnodeT->AsParseNodeName()->pid);
  7302. }
  7303. }
  7304. else
  7305. {
  7306. if (IsStrictMode() && operandToken.tk == tkID)
  7307. {
  7308. CheckStrictModeEvalArgumentsUsage(operandToken.pid);
  7309. }
  7310. }
  7311. }
  7312. else if (nop == knopEllipsis)
  7313. {
  7314. if (!fAllowEllipsis)
  7315. {
  7316. DeferOrEmitPotentialSpreadError(pnodeT);
  7317. }
  7318. }
  7319. else if (m_token.tk == tkExpo)
  7320. {
  7321. //Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...
  7322. Error(ERRInvalidUseofExponentiationOperator);
  7323. }
  7324. if (buildAST)
  7325. {
  7326. //Do not do the folding for Asm in case of KnopPos as we need this to determine the type
  7327. if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)
  7328. {
  7329. // Fold away a unary '+' on a number.
  7330. pnode = pnodeT;
  7331. }
  7332. else if (nop == knopNeg &&
  7333. ((pnodeT->nop == knopInt && pnodeT->AsParseNodeInt()->lw != 0) ||
  7334. (pnodeT->nop == knopFlt && (pnodeT->AsParseNodeFloat()->dbl != 0 || this->m_InAsmMode))))
  7335. {
  7336. // Fold a unary '-' on a number into the value of the number itself.
  7337. pnode = pnodeT;
  7338. if (pnode->nop == knopInt)
  7339. {
  7340. pnode->AsParseNodeInt()->lw = -pnode->AsParseNodeInt()->lw;
  7341. }
  7342. else
  7343. {
  7344. pnode->AsParseNodeFloat()->dbl = -pnode->AsParseNodeFloat()->dbl;
  7345. }
  7346. }
  7347. else
  7348. {
  7349. pnode = CreateUniNode(nop, pnodeT);
  7350. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  7351. }
  7352. pnode->ichMin = ichMin;
  7353. }
  7354. if (nop == knopDelete)
  7355. {
  7356. if (IsStrictMode())
  7357. {
  7358. if ((buildAST && pnode->AsParseNodeUni()->pnode1->IsUserIdentifier()) ||
  7359. (!buildAST && operandToken.tk == tkID && !this->IsSpecialName(operandToken.pid)))
  7360. {
  7361. Error(ERRInvalidDelete);
  7362. }
  7363. }
  7364. if (buildAST)
  7365. {
  7366. ParseNodePtr pnode1 = pnode->AsParseNodeUni()->pnode1;
  7367. if (m_currentNodeFunc)
  7368. {
  7369. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  7370. {
  7371. // If we delete an arguments property, use the conservative,
  7372. // heap-allocated arguments object.
  7373. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  7374. }
  7375. }
  7376. }
  7377. }
  7378. }
  7379. fCanAssign = FALSE;
  7380. }
  7381. else
  7382. {
  7383. ichMin = this->GetScanner()->IchMinTok();
  7384. pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, TRUE, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex, plastRParen);
  7385. if (pfLikelyPattern != nullptr)
  7386. {
  7387. *pfLikelyPattern = !!fLikelyPattern;
  7388. }
  7389. if (m_token.tk == tkDArrow
  7390. // If we have introduced shorthand error above in the ParseExpr, we need to reset if next token is the assignment.
  7391. || (m_token.tk == tkAsg && oplMin <= koplAsg))
  7392. {
  7393. m_hasDeferredShorthandInitError = false;
  7394. }
  7395. if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)
  7396. {
  7397. this->GetScanner()->SeekTo(termStart);
  7398. // 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
  7399. // on the pidref stack match.
  7400. int saveNextBlockId = m_nextBlockId;
  7401. m_nextBlockId = parserState.m_nextBlockId;
  7402. ParseDestructuredLiteralWithScopeSave(tkLCurly, false/*isDecl*/, false /*topLevel*/, DIC_ShouldNotParseInitializer);
  7403. // 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
  7404. // because we don't parse initializers during reparse and there may be additional blocks (e.g. a class declaration)
  7405. // in the initializers that will cause the next Block ID at the end of the reparsing to be different.
  7406. m_nextBlockId = saveNextBlockId;
  7407. if (buildAST)
  7408. {
  7409. this->SetHasDestructuringPattern(true);
  7410. pnode = ConvertToPattern(pnode);
  7411. }
  7412. }
  7413. if (buildAST)
  7414. {
  7415. pNameHint = NULL;
  7416. if (pnode->nop == knopName)
  7417. {
  7418. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7419. pNameHint = pid->Psz();
  7420. hintLength = pid->Cch();
  7421. hintOffset = 0;
  7422. }
  7423. else if (pnode->nop == knopDot || pnode->nop == knopIndex)
  7424. {
  7425. if (CONFIG_FLAG(UseFullName))
  7426. {
  7427. pNameHint = ConstructNameHint(pnode->AsParseNodeBin(), &hintLength, &hintOffset);
  7428. }
  7429. else
  7430. {
  7431. ParseNodePtr pnodeName = pnode;
  7432. while (pnodeName->nop == knopDot)
  7433. {
  7434. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  7435. }
  7436. if (pnodeName->nop == knopName)
  7437. {
  7438. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7439. pNameHint = pid->Psz();
  7440. hintLength = pid->Cch();
  7441. hintOffset = 0;
  7442. }
  7443. }
  7444. }
  7445. }
  7446. // Check for postfix unary operators.
  7447. if (!this->GetScanner()->FHadNewLine() &&
  7448. (tkInc == m_token.tk || tkDec == m_token.tk))
  7449. {
  7450. if (!fCanAssign &&
  7451. (m_sourceContextInfo
  7452. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7453. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7454. {
  7455. Error(JSERR_CantAssignTo);
  7456. }
  7457. TrackAssignment<buildAST>(pnode, &term);
  7458. fCanAssign = FALSE;
  7459. if (buildAST)
  7460. {
  7461. if (IsStrictMode() && pnode->nop == knopName)
  7462. {
  7463. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7464. }
  7465. this->CheckArguments(pnode);
  7466. pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);
  7467. pnode->ichLim = this->GetScanner()->IchLimTok();
  7468. }
  7469. else
  7470. {
  7471. if (IsStrictMode() && term.tk == tkID)
  7472. {
  7473. CheckStrictModeEvalArgumentsUsage(term.pid);
  7474. }
  7475. // This expression is not an identifier
  7476. term.tk = tkNone;
  7477. }
  7478. this->GetScanner()->Scan();
  7479. }
  7480. }
  7481. // Process a sequence of operators and operands.
  7482. for (;;)
  7483. {
  7484. if (!this->GetHashTbl()->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)
  7485. {
  7486. break;
  7487. }
  7488. if (!fAllowIn && nop == knopIn)
  7489. {
  7490. break;
  7491. }
  7492. Assert(opl != koplNo);
  7493. if (opl == koplAsg)
  7494. {
  7495. if (m_token.tk != tkDArrow)
  7496. {
  7497. // Assignment operator. These are the only right associative
  7498. // binary operators. We also need to special case the left
  7499. // operand - it should only be a LeftHandSideExpression.
  7500. Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);
  7501. TrackAssignment<buildAST>(pnode, &term);
  7502. if (buildAST)
  7503. {
  7504. if (IsStrictMode() && pnode->nop == knopName)
  7505. {
  7506. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7507. }
  7508. // Assignment stmt of the form "this.<id> = <expr>"
  7509. if (nop == knopAsg
  7510. && pnode->nop == knopDot
  7511. && pnode->AsParseNodeBin()->pnode1->nop == knopName
  7512. && pnode->AsParseNodeBin()->pnode1->AsParseNodeName()->pid == wellKnownPropertyPids._this
  7513. && pnode->AsParseNodeBin()->pnode2->nop == knopName)
  7514. {
  7515. if (pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->pid != wellKnownPropertyPids.__proto__)
  7516. {
  7517. assignmentStmt = true;
  7518. }
  7519. }
  7520. }
  7521. else
  7522. {
  7523. if (IsStrictMode() && term.tk == tkID)
  7524. {
  7525. CheckStrictModeEvalArgumentsUsage(term.pid);
  7526. }
  7527. }
  7528. }
  7529. if (opl < oplMin)
  7530. {
  7531. break;
  7532. }
  7533. if (m_token.tk != tkDArrow && !fCanAssign &&
  7534. (m_sourceContextInfo
  7535. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7536. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7537. {
  7538. Error(JSERR_CantAssignTo);
  7539. // No recovery necessary since this is a semantic, not structural, error.
  7540. }
  7541. }
  7542. else if (opl == koplExpo)
  7543. {
  7544. // ** operator is right associative
  7545. if (opl < oplMin)
  7546. {
  7547. break;
  7548. }
  7549. }
  7550. else if (opl <= oplMin)
  7551. {
  7552. break;
  7553. }
  7554. // This expression is not an identifier
  7555. term.tk = tkNone;
  7556. // Precedence is high enough. Consume the operator token.
  7557. this->GetScanner()->Scan();
  7558. fCanAssign = !!fLikelyPattern;
  7559. // Special case the "?:" operator
  7560. if (nop == knopQmark)
  7561. {
  7562. pnodeT = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);
  7563. ChkCurTok(tkColon, ERRnoColon);
  7564. ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, plastRParen);
  7565. if (buildAST)
  7566. {
  7567. pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);
  7568. this->CheckArguments(pnode->AsParseNodeTri()->pnode2);
  7569. this->CheckArguments(pnode->AsParseNodeTri()->pnode3);
  7570. }
  7571. }
  7572. else if (nop == knopFncDecl)
  7573. {
  7574. ushort flags = fFncLambda;
  7575. size_t iecpMin = 0;
  7576. bool isAsyncMethod = false;
  7577. RestoreStateFrom(&parserState);
  7578. this->GetScanner()->SeekTo(termStart);
  7579. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  7580. {
  7581. ichMin = this->GetScanner()->IchMinTok();
  7582. iecpMin = this->GetScanner()->IecpMinTok();
  7583. this->GetScanner()->Scan();
  7584. if ((m_token.tk == tkID || m_token.tk == tkLParen) && !this->GetScanner()->FHadNewLine())
  7585. {
  7586. flags |= fFncAsync;
  7587. isAsyncMethod = true;
  7588. }
  7589. else
  7590. {
  7591. this->GetScanner()->SeekTo(termStart);
  7592. }
  7593. }
  7594. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::Disallowed, nullptr, /* needsPIDOnRCurlyScan = */false, /* fUnaryOrParen = */ false, fAllowIn);
  7595. if (isAsyncMethod)
  7596. {
  7597. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  7598. pnode->ichMin = ichMin;
  7599. }
  7600. // ArrowFunction/AsyncArrowFunction is part of AssignmentExpression, which should terminate the expression unless followed by a comma
  7601. if (m_token.tk != tkComma && m_token.tk != tkIN)
  7602. {
  7603. if (!(IsTerminateToken(false)))
  7604. {
  7605. Error(ERRnoSemic);
  7606. }
  7607. break;
  7608. }
  7609. }
  7610. else // a binary operator
  7611. {
  7612. if (nop == knopComma && m_token.tk == tkRParen)
  7613. {
  7614. // Trailing comma
  7615. this->GetScanner()->Capture(&m_deferCommaErrorLoc);
  7616. m_deferCommaError = true;
  7617. break;
  7618. }
  7619. ParseNode* pnode1 = pnode;
  7620. // Parse the operand, make a new node, and look for more
  7621. IdentToken token;
  7622. ParseNode* pnode2 = ParseExpr<buildAST>(
  7623. opl, nullptr, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token, false, nullptr, plastRParen);
  7624. // Detect nested function escapes of the pattern "o.f = function(){...}" or "o[s] = function(){...}".
  7625. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7626. // is not detected at byte code gen time because of deferred parsing.
  7627. if (fIsDotOrIndex && nop == knopAsg)
  7628. {
  7629. this->MarkEscapingRef(pnodeT, &token);
  7630. }
  7631. if (buildAST)
  7632. {
  7633. Assert(pnode2 != nullptr);
  7634. if (pnode2->nop == knopFncDecl)
  7635. {
  7636. Assert(hintLength >= hintOffset);
  7637. pnode2->AsParseNodeFnc()->hint = pNameHint;
  7638. pnode2->AsParseNodeFnc()->hintLength = hintLength;
  7639. pnode2->AsParseNodeFnc()->hintOffset = hintOffset;
  7640. if (pnode1->nop == knopDot)
  7641. {
  7642. pnode2->AsParseNodeFnc()->isNameIdentifierRef = false;
  7643. }
  7644. else if (pnode1->nop == knopName)
  7645. {
  7646. PidRefStack *pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7647. pidRef->isFuncAssignment = true;
  7648. }
  7649. }
  7650. else if (pnode2->nop == knopClassDecl && pnode1->nop == knopDot)
  7651. {
  7652. Assert(pnode2->AsParseNodeClass()->pnodeConstructor);
  7653. if (!pnode2->AsParseNodeClass()->pnodeConstructor->pid)
  7654. {
  7655. pnode2->AsParseNodeClass()->pnodeConstructor->isNameIdentifierRef = false;
  7656. }
  7657. }
  7658. else if (pnode1->nop == knopName && nop == knopIn)
  7659. {
  7660. PidRefStack* pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7661. pidRef->SetIsUsedInLdElem(true);
  7662. }
  7663. pnode = CreateBinNode(nop, pnode1, pnode2);
  7664. }
  7665. pNameHint = nullptr;
  7666. }
  7667. }
  7668. if (buildAST)
  7669. {
  7670. if (!assignmentStmt)
  7671. {
  7672. // Don't set the flag for following nodes
  7673. switch (pnode->nop)
  7674. {
  7675. case knopName:
  7676. case knopInt:
  7677. case knopFlt:
  7678. case knopStr:
  7679. case knopRegExp:
  7680. case knopNull:
  7681. case knopFalse:
  7682. case knopTrue:
  7683. break;
  7684. default:
  7685. if (m_currentNodeFunc)
  7686. {
  7687. m_currentNodeFunc->SetHasNonThisStmt();
  7688. }
  7689. else if (m_currentNodeProg)
  7690. {
  7691. m_currentNodeProg->SetHasNonThisStmt();
  7692. }
  7693. }
  7694. }
  7695. }
  7696. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;
  7697. if (NULL != pfCanAssign)
  7698. {
  7699. *pfCanAssign = fCanAssign;
  7700. }
  7701. // Pass back identifier if requested
  7702. if (pToken && term.tk == tkID)
  7703. {
  7704. *pToken = term;
  7705. }
  7706. //Track "obj.a" assignment patterns here - Promote the Assignment state for the property's PID.
  7707. // This includes =, += etc.
  7708. if (pnode != NULL)
  7709. {
  7710. uint nodeType = ParseNode::Grfnop(pnode->nop);
  7711. if (nodeType & fnopAsg)
  7712. {
  7713. if (nodeType & fnopBin)
  7714. {
  7715. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  7716. Assert(lhs);
  7717. if (lhs->nop == knopDot)
  7718. {
  7719. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7720. if (propertyNode->nop == knopName)
  7721. {
  7722. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  7723. }
  7724. }
  7725. }
  7726. else if (nodeType & fnopUni)
  7727. {
  7728. // cases like obj.a++, ++obj.a
  7729. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  7730. if (lhs->nop == knopDot)
  7731. {
  7732. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7733. if (propertyNode->nop == knopName)
  7734. {
  7735. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  7736. }
  7737. }
  7738. }
  7739. }
  7740. }
  7741. return pnode;
  7742. }
  7743. template<bool buildAST>
  7744. void Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)
  7745. {
  7746. if (buildAST)
  7747. {
  7748. Assert(pnodeT != nullptr);
  7749. if (pnodeT->nop == knopName)
  7750. {
  7751. PidRefStack *ref = pnodeT->AsParseNodeName()->pid->GetTopRef();
  7752. Assert(ref);
  7753. ref->isAsg = true;
  7754. }
  7755. }
  7756. else
  7757. {
  7758. Assert(pToken != nullptr);
  7759. if (pToken->tk == tkID)
  7760. {
  7761. PidRefStack *ref = pToken->pid->GetTopRef();
  7762. Assert(ref);
  7763. ref->isAsg = true;
  7764. }
  7765. }
  7766. }
  7767. PidRefStack* Parser::PushPidRef(IdentPtr pid)
  7768. {
  7769. ParseNodeFnc* currentFnc = GetCurrentFunctionNode();
  7770. if (this->IsCreatingStateCache())
  7771. {
  7772. IdentPtrSet* capturedNames = currentFnc->EnsureCapturedNames(&m_nodeAllocator);
  7773. capturedNames->AddNew(pid);
  7774. }
  7775. if (PHASE_ON1(Js::ParallelParsePhase))
  7776. {
  7777. // NOTE: the phase check is here to protect perf. See OSG 1020424.
  7778. // In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather
  7779. // than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.
  7780. return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->blockId, currentFnc->functionId);
  7781. }
  7782. Assert(GetCurrentBlock() != nullptr);
  7783. AssertMsg(pid != nullptr, "PID should be created");
  7784. PidRefStack *ref = pid->GetTopRef(m_nextBlockId - 1);
  7785. int blockId = GetCurrentBlock()->blockId;
  7786. int funcId = currentFnc->functionId;
  7787. if (!ref || (ref->GetScopeId() < blockId))
  7788. {
  7789. ref = Anew(&m_nodeAllocator, PidRefStack);
  7790. if (ref == nullptr)
  7791. {
  7792. Error(ERRnoMemory);
  7793. }
  7794. pid->PushPidRef(blockId, funcId, ref);
  7795. }
  7796. else if (m_reparsingLambdaParams)
  7797. {
  7798. // If we're reparsing params, then we may have pid refs left behind from the first pass. Make sure we're
  7799. // working with the right ref at this point.
  7800. ref = this->FindOrAddPidRef(pid, blockId, funcId);
  7801. // Fix up the function ID if we're reparsing lambda parameters.
  7802. ref->funcId = funcId;
  7803. }
  7804. return ref;
  7805. }
  7806. PidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)
  7807. {
  7808. PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);
  7809. if (ref == NULL)
  7810. {
  7811. Error(ERRnoMemory);
  7812. }
  7813. return ref;
  7814. }
  7815. void Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)
  7816. {
  7817. PidRefStack *prevRef = pid->RemovePrevPidRef(ref);
  7818. Assert(prevRef);
  7819. if (prevRef->GetSym() == nullptr)
  7820. {
  7821. AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);
  7822. }
  7823. }
  7824. void Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)
  7825. {
  7826. PidRefStack *ref = pid->GetTopRef();
  7827. while (ref && ref->GetScopeId() >= blockId)
  7828. {
  7829. ref->SetDynamicBinding();
  7830. ref = ref->prev;
  7831. }
  7832. }
  7833. ParseNodeBlock* Parser::GetFunctionBlock()
  7834. {
  7835. Assert(m_currentBlockInfo != nullptr);
  7836. return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;
  7837. }
  7838. ParseNodeBlock* Parser::GetCurrentBlock()
  7839. {
  7840. return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;
  7841. }
  7842. BlockInfoStack* Parser::GetCurrentBlockInfo()
  7843. {
  7844. return m_currentBlockInfo;
  7845. }
  7846. BlockInfoStack* Parser::GetCurrentFunctionBlockInfo()
  7847. {
  7848. return m_currentBlockInfo->pBlockInfoFunction;
  7849. }
  7850. /***************************************************************************
  7851. Parse a variable declaration.
  7852. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7853. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7854. ***************************************************************************/
  7855. template<bool buildAST>
  7856. ParseNodePtr Parser::ParseVariableDeclaration(
  7857. tokens declarationType, charcount_t ichMin,
  7858. BOOL fAllowIn/* = TRUE*/,
  7859. BOOL* pfForInOk/* = nullptr*/,
  7860. BOOL singleDefOnly/* = FALSE*/,
  7861. BOOL allowInit/* = TRUE*/,
  7862. BOOL isTopVarParse/* = TRUE*/,
  7863. BOOL isFor/* = FALSE*/,
  7864. BOOL* nativeForOk /*= nullptr*/)
  7865. {
  7866. ParseNodePtr pnodeThis = nullptr;
  7867. ParseNodePtr pnodeInit;
  7868. ParseNodePtr pnodeList = nullptr;
  7869. ParseNodePtr *lastNodeRef = nullptr;
  7870. LPCOLESTR pNameHint = nullptr;
  7871. uint32 nameHintLength = 0;
  7872. uint32 nameHintOffset = 0;
  7873. Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);
  7874. for (;;)
  7875. {
  7876. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  7877. {
  7878. pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);
  7879. if (pnodeThis != nullptr)
  7880. {
  7881. pnodeThis->ichMin = ichMin;
  7882. pnodeThis->SetIsPatternDeclaration();
  7883. }
  7884. }
  7885. else
  7886. {
  7887. if (m_token.tk != tkID)
  7888. {
  7889. IdentifierExpectedError(m_token);
  7890. }
  7891. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  7892. Assert(pid);
  7893. pNameHint = pid->Psz();
  7894. nameHintLength = pid->Cch();
  7895. nameHintOffset = 0;
  7896. if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))
  7897. {
  7898. Error(ERRLetIDInLexicalDecl, pnodeThis);
  7899. }
  7900. if (declarationType == tkVAR)
  7901. {
  7902. pnodeThis = CreateVarDeclNode(pid, STVariable);
  7903. }
  7904. else if (declarationType == tkCONST)
  7905. {
  7906. pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);
  7907. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Const, m_scriptContext);
  7908. }
  7909. else
  7910. {
  7911. pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);
  7912. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Let, m_scriptContext);
  7913. }
  7914. if (pid == wellKnownPropertyPids.arguments)
  7915. {
  7916. // This var declaration may change the way an 'arguments' identifier in the function is resolved
  7917. if (declarationType == tkVAR)
  7918. {
  7919. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_varDeclaration;
  7920. }
  7921. else
  7922. {
  7923. if (GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  7924. {
  7925. // Only override arguments if we are at the function block level.
  7926. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  7927. }
  7928. }
  7929. }
  7930. if (pnodeThis)
  7931. {
  7932. pnodeThis->ichMin = ichMin;
  7933. }
  7934. this->GetScanner()->Scan();
  7935. if (m_token.tk == tkAsg)
  7936. {
  7937. if (!allowInit)
  7938. {
  7939. Error(ERRUnexpectedDefault);
  7940. }
  7941. if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))
  7942. {
  7943. *pfForInOk = FALSE;
  7944. }
  7945. this->GetScanner()->Scan();
  7946. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  7947. if (buildAST)
  7948. {
  7949. AnalysisAssert(pnodeThis);
  7950. pnodeThis->AsParseNodeVar()->pnodeInit = pnodeInit;
  7951. pnodeThis->ichLim = pnodeInit->ichLim;
  7952. if (pnodeInit->nop == knopFncDecl)
  7953. {
  7954. Assert(nameHintLength >= nameHintOffset);
  7955. pnodeInit->AsParseNodeFnc()->hint = pNameHint;
  7956. pnodeInit->AsParseNodeFnc()->hintLength = nameHintLength;
  7957. pnodeInit->AsParseNodeFnc()->hintOffset = nameHintOffset;
  7958. pnodeThis->AsParseNodeVar()->pid->GetTopRef()->isFuncAssignment = true;
  7959. }
  7960. else
  7961. {
  7962. this->CheckArguments(pnodeInit);
  7963. }
  7964. pNameHint = nullptr;
  7965. }
  7966. //Track var a =, let a= , const a =
  7967. // This is for FixedFields Constant Heuristics
  7968. if (pnodeThis && pnodeThis->AsParseNodeVar()->pnodeInit != nullptr)
  7969. {
  7970. pnodeThis->AsParseNodeVar()->sym->PromoteAssignmentState();
  7971. }
  7972. }
  7973. else if (declarationType == tkCONST /*pnodeThis->nop == knopConstDecl*/
  7974. && !singleDefOnly
  7975. && !(isFor && TokIsForInOrForOf()))
  7976. {
  7977. Error(ERRUninitializedConst);
  7978. }
  7979. if (m_currentNodeFunc && pnodeThis && pnodeThis->AsParseNodeVar()->sym->GetIsFormal())
  7980. {
  7981. m_currentNodeFunc->SetHasAnyWriteToFormals(true);
  7982. }
  7983. }
  7984. if (singleDefOnly)
  7985. {
  7986. return pnodeThis;
  7987. }
  7988. if (buildAST)
  7989. {
  7990. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);
  7991. }
  7992. if (m_token.tk != tkComma)
  7993. {
  7994. return pnodeList;
  7995. }
  7996. if (pfForInOk)
  7997. {
  7998. // don't allow "for (var a, b in c)"
  7999. *pfForInOk = FALSE;
  8000. }
  8001. this->GetScanner()->Scan();
  8002. ichMin = this->GetScanner()->IchMinTok();
  8003. }
  8004. }
  8005. /***************************************************************************
  8006. Parse try-catch-finally statement
  8007. ***************************************************************************/
  8008. // The try-catch-finally tree nests the try-catch within a try-finally.
  8009. // This matches the new runtime implementation.
  8010. template<bool buildAST>
  8011. ParseNodeStmt * Parser::ParseTryCatchFinally()
  8012. {
  8013. this->m_tryCatchOrFinallyDepth++;
  8014. ParseNodeTry * pnodeT = ParseTry<buildAST>();
  8015. ParseNodeTryCatch * pnodeTC = nullptr;
  8016. StmtNest stmt;
  8017. bool hasCatch = false;
  8018. if (tkCATCH == m_token.tk)
  8019. {
  8020. hasCatch = true;
  8021. if (buildAST)
  8022. {
  8023. pnodeTC = CreateNodeForOpT<knopTryCatch>();
  8024. pnodeT->pnodeOuter = pnodeTC;
  8025. pnodeTC->pnodeTry = pnodeT;
  8026. }
  8027. PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr);
  8028. ParseNodeCatch * pnodeCatch = ParseCatch<buildAST>();
  8029. if (buildAST)
  8030. {
  8031. pnodeTC->pnodeCatch = pnodeCatch;
  8032. }
  8033. PopStmt(&stmt);
  8034. }
  8035. if (tkFINALLY != m_token.tk)
  8036. {
  8037. if (!hasCatch)
  8038. {
  8039. Error(ERRnoCatch);
  8040. }
  8041. Assert(!buildAST || pnodeTC);
  8042. this->m_tryCatchOrFinallyDepth--;
  8043. return pnodeTC;
  8044. }
  8045. ParseNodeTryFinally * pnodeTF = nullptr;
  8046. if (buildAST)
  8047. {
  8048. pnodeTF = CreateNodeForOpT<knopTryFinally>();
  8049. }
  8050. PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr);
  8051. ParseNodeFinally * pnodeFinally = ParseFinally<buildAST>();
  8052. if (buildAST)
  8053. {
  8054. if (!hasCatch)
  8055. {
  8056. pnodeTF->pnodeTry = pnodeT;
  8057. pnodeT->pnodeOuter = pnodeTF;
  8058. }
  8059. else
  8060. {
  8061. pnodeTF->pnodeTry = CreateNodeForOpT<knopTry>();
  8062. pnodeTF->pnodeTry->pnodeOuter = pnodeTF;
  8063. pnodeTF->pnodeTry->pnodeBody = pnodeTC;
  8064. pnodeTC->pnodeOuter = pnodeTF->pnodeTry;
  8065. }
  8066. pnodeTF->pnodeFinally = pnodeFinally;
  8067. }
  8068. PopStmt(&stmt);
  8069. this->m_tryCatchOrFinallyDepth--;
  8070. return pnodeTF;
  8071. }
  8072. template<bool buildAST>
  8073. ParseNodeTry * Parser::ParseTry()
  8074. {
  8075. ParseNodeTry * pnode = nullptr;
  8076. StmtNest stmt;
  8077. Assert(tkTRY == m_token.tk);
  8078. if (buildAST)
  8079. {
  8080. pnode = CreateNodeForOpT<knopTry>();
  8081. }
  8082. this->GetScanner()->Scan();
  8083. if (tkLCurly != m_token.tk)
  8084. {
  8085. Error(ERRnoLcurly);
  8086. }
  8087. PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr);
  8088. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8089. if (buildAST)
  8090. {
  8091. pnode->pnodeBody = pnodeBody;
  8092. if (pnode->pnodeBody)
  8093. pnode->ichLim = pnode->pnodeBody->ichLim;
  8094. }
  8095. PopStmt(&stmt);
  8096. return pnode;
  8097. }
  8098. template<bool buildAST>
  8099. ParseNodeFinally * Parser::ParseFinally()
  8100. {
  8101. ParseNodeFinally * pnode = nullptr;
  8102. StmtNest stmt;
  8103. Assert(tkFINALLY == m_token.tk);
  8104. if (buildAST)
  8105. {
  8106. pnode = CreateNodeForOpT<knopFinally>();
  8107. }
  8108. this->GetScanner()->Scan();
  8109. if (tkLCurly != m_token.tk)
  8110. {
  8111. Error(ERRnoLcurly);
  8112. }
  8113. PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr);
  8114. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8115. if (buildAST)
  8116. {
  8117. pnode->pnodeBody = pnodeBody;
  8118. if (!pnode->pnodeBody)
  8119. // Will only occur due to error correction.
  8120. pnode->pnodeBody = CreateNodeForOpT<knopEmpty>();
  8121. else
  8122. pnode->ichLim = pnode->pnodeBody->ichLim;
  8123. }
  8124. PopStmt(&stmt);
  8125. return pnode;
  8126. }
  8127. template<bool buildAST>
  8128. ParseNodeCatch * Parser::ParseCatch()
  8129. {
  8130. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8131. ParseNodeCatch * pnode = nullptr;
  8132. ParseNodeBlock * pnodeCatchScope = nullptr;
  8133. StmtNest stmt;
  8134. IdentPtr pidCatch = nullptr;
  8135. if (tkCATCH == m_token.tk)
  8136. {
  8137. charcount_t ichMin;
  8138. if (buildAST)
  8139. {
  8140. ichMin = this->GetScanner()->IchMinTok();
  8141. }
  8142. this->GetScanner()->Scan(); //catch
  8143. ChkCurTok(tkLParen, ERRnoLparen); //catch(
  8144. bool isPattern = false;
  8145. if (tkID != m_token.tk)
  8146. {
  8147. isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();
  8148. if (!isPattern)
  8149. {
  8150. IdentifierExpectedError(m_token);
  8151. }
  8152. }
  8153. if (buildAST)
  8154. {
  8155. pnode = CreateNodeForOpT<knopCatch>(ichMin);
  8156. pnode->pnodeNext = nullptr;
  8157. PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr);
  8158. }
  8159. pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);
  8160. if (buildAST)
  8161. {
  8162. // Add this catch to the current scope list.
  8163. if (m_ppnodeExprScope)
  8164. {
  8165. Assert(*m_ppnodeExprScope == nullptr);
  8166. *m_ppnodeExprScope = pnode;
  8167. m_ppnodeExprScope = &pnode->pnodeNext;
  8168. }
  8169. else
  8170. {
  8171. Assert(m_ppnodeScope);
  8172. Assert(*m_ppnodeScope == nullptr);
  8173. *m_ppnodeScope = pnode;
  8174. m_ppnodeScope = &pnode->pnodeNext;
  8175. }
  8176. // Keep a list of function expressions (not declarations) at this scope.
  8177. ppnodeExprScopeSave = m_ppnodeExprScope;
  8178. m_ppnodeExprScope = &pnode->pnodeScopes;
  8179. pnode->pnodeScopes = nullptr;
  8180. }
  8181. if (isPattern)
  8182. {
  8183. ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, true /*topLevel*/, DIC_ForceErrorOnInitializer);
  8184. if (buildAST)
  8185. {
  8186. pnode->SetParam(CreateParamPatternNode(pnodePattern));
  8187. Scope *scope = pnodeCatchScope->scope;
  8188. pnode->scope = scope;
  8189. }
  8190. }
  8191. else
  8192. {
  8193. if (IsStrictMode())
  8194. {
  8195. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  8196. if (pid == wellKnownPropertyPids.eval)
  8197. {
  8198. Error(ERREvalUsage);
  8199. }
  8200. else if (pid == wellKnownPropertyPids.arguments)
  8201. {
  8202. Error(ERRArgsUsage);
  8203. }
  8204. }
  8205. pidCatch = m_token.GetIdentifier(this->GetHashTbl());
  8206. PidRefStack *ref = this->FindOrAddPidRef(pidCatch, GetCurrentBlock()->blockId, GetCurrentFunctionNode()->functionId);
  8207. ParseNodeName * pnodeParam = CreateNameNode(pidCatch);
  8208. pnodeParam->SetSymRef(ref);
  8209. const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());
  8210. int nameLength = pidCatch->Cch();
  8211. SymbolName const symName(name, nameLength);
  8212. Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);
  8213. if (sym == nullptr)
  8214. {
  8215. Error(ERRnoMemory);
  8216. }
  8217. sym->SetPid(pidCatch);
  8218. Assert(ref->GetSym() == nullptr);
  8219. ref->SetSym(sym);
  8220. Scope *scope = pnodeCatchScope->scope;
  8221. scope->AddNewSymbol(sym);
  8222. if (buildAST)
  8223. {
  8224. pnode->SetParam(pnodeParam);
  8225. pnode->scope = scope;
  8226. }
  8227. this->GetScanner()->Scan();
  8228. }
  8229. charcount_t ichLim;
  8230. if (buildAST)
  8231. {
  8232. ichLim = this->GetScanner()->IchLimTok();
  8233. }
  8234. ChkCurTok(tkRParen, ERRnoRparen); //catch(id[:expr])
  8235. if (tkLCurly != m_token.tk)
  8236. {
  8237. Error(ERRnoLcurly);
  8238. }
  8239. ParseNodePtr pnodeBody = ParseStatement<buildAST>(); //catch(id[:expr]) {block}
  8240. if (buildAST)
  8241. {
  8242. pnode->pnodeBody = pnodeBody;
  8243. pnode->ichLim = ichLim;
  8244. }
  8245. if (pnodeCatchScope != nullptr)
  8246. {
  8247. FinishParseBlock(pnodeCatchScope);
  8248. }
  8249. if (pnodeCatchScope->GetCallsEval() || pnodeCatchScope->GetChildCallsEval())
  8250. {
  8251. GetCurrentBlock()->SetChildCallsEval(true);
  8252. }
  8253. if (pnodeCatchScope->GetCallsEval())
  8254. {
  8255. pnodeBody->AsParseNodeBlock()->SetCallsEval(true);
  8256. }
  8257. if (pnodeCatchScope->GetChildCallsEval())
  8258. {
  8259. pnodeBody->AsParseNodeBlock()->SetChildCallsEval(true);
  8260. }
  8261. if (buildAST)
  8262. {
  8263. PopStmt(&stmt);
  8264. // Restore the lists of function expression scopes.
  8265. Assert(m_ppnodeExprScope);
  8266. Assert(*m_ppnodeExprScope == nullptr);
  8267. m_ppnodeExprScope = ppnodeExprScopeSave;
  8268. }
  8269. }
  8270. return pnode;
  8271. }
  8272. template<bool buildAST>
  8273. ParseNodeCase * Parser::ParseCase(ParseNodePtr *ppnodeBody)
  8274. {
  8275. ParseNodeCase * pnodeT = nullptr;
  8276. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8277. this->GetScanner()->Scan();
  8278. ParseNodePtr pnodeExpr = ParseExpr<buildAST>();
  8279. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8280. ChkCurTok(tkColon, ERRnoColon);
  8281. if (buildAST)
  8282. {
  8283. pnodeT = CreateNodeForOpT<knopCase>(ichMinT);
  8284. pnodeT->pnodeExpr = pnodeExpr;
  8285. pnodeT->ichLim = ichLim;
  8286. }
  8287. ParseStmtList<buildAST>(ppnodeBody);
  8288. return pnodeT;
  8289. }
  8290. /***************************************************************************
  8291. Parse a single statement. Digest a trailing semicolon.
  8292. ***************************************************************************/
  8293. template<bool buildAST>
  8294. ParseNodePtr Parser::ParseStatement()
  8295. {
  8296. ParseNodePtr pnode = nullptr;
  8297. LabelId* pLabelIdList = nullptr;
  8298. charcount_t ichMin = 0;
  8299. size_t iecpMin = 0;
  8300. StmtNest stmt;
  8301. StmtNest *pstmt;
  8302. BOOL fForInOrOfOkay;
  8303. BOOL fCanAssign;
  8304. IdentPtr pid;
  8305. uint fnop;
  8306. bool expressionStmt = false;
  8307. bool isAsyncMethod = false;
  8308. bool labelledStatement = false;
  8309. tokens tok;
  8310. #if EXCEPTION_RECOVERY
  8311. ParseNodeTryCatch * pParentTryCatch = nullptr;
  8312. ParseNodeBlock * pTryBlock = nullptr;
  8313. ParseNodeTry * pTry = nullptr;
  8314. ParseNodeBlock * pParentTryCatchBlock = nullptr;
  8315. StmtNest stmtTryCatchBlock;
  8316. StmtNest stmtTryCatch;
  8317. StmtNest stmtTry;
  8318. StmtNest stmtTryBlock;
  8319. #endif
  8320. if (buildAST)
  8321. {
  8322. #if EXCEPTION_RECOVERY
  8323. if (Js::Configuration::Global.flags.SwallowExceptions)
  8324. {
  8325. // If we're swallowing exceptions, surround this statement with a try/catch block:
  8326. //
  8327. // Before: x.y = 3;
  8328. // After: try { x.y = 3; } catch(__ehobj) { }
  8329. //
  8330. // This is done to force the runtime to recover from exceptions at the most granular
  8331. // possible point. Recovering from EH dramatically improves coverage of testing via
  8332. // fault injection.
  8333. // create and push the try-catch node
  8334. pParentTryCatchBlock = CreateBlockNode();
  8335. PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr);
  8336. pParentTryCatch = CreateNodeForOpT<knopTryCatch>();
  8337. PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr);
  8338. // create and push a try node
  8339. pTry = CreateNodeForOpT<knopTry>();
  8340. PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr);
  8341. pTryBlock = CreateBlockNode();
  8342. PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr);
  8343. // these nodes will be closed after the statement is parsed.
  8344. }
  8345. #endif // EXCEPTION_RECOVERY
  8346. }
  8347. EnsureStackAvailable();
  8348. LRestart:
  8349. tok = m_token.tk;
  8350. switch (tok)
  8351. {
  8352. case tkEOF:
  8353. if (labelledStatement)
  8354. {
  8355. Error(ERRLabelFollowedByEOF);
  8356. }
  8357. if (buildAST)
  8358. {
  8359. pnode = nullptr;
  8360. }
  8361. break;
  8362. case tkFUNCTION:
  8363. {
  8364. LFunctionStatement:
  8365. ParseNodeFnc *pnodeFnc = nullptr;
  8366. if (m_grfscr & fscrDeferredFncExpression)
  8367. {
  8368. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  8369. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  8370. // first time we see it.
  8371. m_grfscr &= ~fscrDeferredFncExpression;
  8372. pnode = ParseFncDeclNoCheckScope<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs);
  8373. pnodeFnc = pnode->AsParseNodeFnc();
  8374. }
  8375. else
  8376. {
  8377. pnode = ParseFncDeclCheckScope<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs));
  8378. pnodeFnc = pnode->nop == knopBlock ? pnode->AsParseNodeBlock()->pnodeStmt->AsParseNodeFnc() : pnode->AsParseNodeFnc();
  8379. }
  8380. Assert(pnode != nullptr);
  8381. Assert(pnodeFnc != nullptr);
  8382. if (labelledStatement)
  8383. {
  8384. if (IsStrictMode())
  8385. {
  8386. Error(ERRFunctionAfterLabelInStrict);
  8387. }
  8388. else if (pnodeFnc->IsAsync())
  8389. {
  8390. Error(ERRLabelBeforeAsyncFncDeclaration);
  8391. }
  8392. else if (pnodeFnc->IsGenerator())
  8393. {
  8394. Error(ERRLabelBeforeGeneratorDeclaration);
  8395. }
  8396. }
  8397. if (isAsyncMethod)
  8398. {
  8399. pnodeFnc->cbMin = iecpMin;
  8400. pnodeFnc->ichMin = ichMin;
  8401. }
  8402. break;
  8403. }
  8404. case tkCLASS:
  8405. if (labelledStatement)
  8406. {
  8407. Error(ERRLabelBeforeClassDeclaration);
  8408. }
  8409. else if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  8410. {
  8411. pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);
  8412. }
  8413. else
  8414. {
  8415. goto LDefaultToken;
  8416. }
  8417. break;
  8418. case tkID:
  8419. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.let)
  8420. {
  8421. if (labelledStatement)
  8422. {
  8423. Error(ERRLabelBeforeLexicalDeclaration);
  8424. }
  8425. // We see "let" at the start of a statement. This could either be a declaration or an identifier
  8426. // reference. The next token determines which.
  8427. RestorePoint parsedLet;
  8428. this->GetScanner()->Capture(&parsedLet);
  8429. ichMin = this->GetScanner()->IchMinTok();
  8430. this->GetScanner()->Scan();
  8431. if (this->NextTokenConfirmsLetDecl())
  8432. {
  8433. pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);
  8434. goto LNeedTerminator;
  8435. }
  8436. this->GetScanner()->SeekTo(parsedLet);
  8437. }
  8438. else if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8439. {
  8440. RestorePoint parsedAsync;
  8441. this->GetScanner()->Capture(&parsedAsync);
  8442. ichMin = this->GetScanner()->IchMinTok();
  8443. iecpMin = this->GetScanner()->IecpMinTok();
  8444. this->GetScanner()->Scan();
  8445. if (m_token.tk == tkFUNCTION && !this->GetScanner()->FHadNewLine())
  8446. {
  8447. isAsyncMethod = true;
  8448. goto LFunctionStatement;
  8449. }
  8450. this->GetScanner()->SeekTo(parsedAsync);
  8451. }
  8452. goto LDefaultToken;
  8453. case tkCONST:
  8454. case tkLET:
  8455. if (labelledStatement)
  8456. {
  8457. Error(ERRLabelBeforeLexicalDeclaration);
  8458. }
  8459. ichMin = this->GetScanner()->IchMinTok();
  8460. this->GetScanner()->Scan();
  8461. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8462. goto LNeedTerminator;
  8463. case tkVAR:
  8464. ichMin = this->GetScanner()->IchMinTok();
  8465. this->GetScanner()->Scan();
  8466. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8467. goto LNeedTerminator;
  8468. case tkFOR:
  8469. {
  8470. ParseNodeBlock * pnodeBlock = nullptr;
  8471. ParseNodePtr *ppnodeScopeSave = nullptr;
  8472. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8473. ichMin = this->GetScanner()->IchMinTok();
  8474. ChkNxtTok(tkLParen, ERRnoLparen);
  8475. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8476. if (buildAST)
  8477. {
  8478. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8479. }
  8480. RestorePoint startExprOrIdentifier;
  8481. fForInOrOfOkay = TRUE;
  8482. fCanAssign = TRUE;
  8483. tok = m_token.tk;
  8484. BOOL nativeForOkay = TRUE;
  8485. ParseNodePtr pnodeT;
  8486. switch (tok)
  8487. {
  8488. case tkID:
  8489. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.let)
  8490. {
  8491. // We see "let" in the init part of a for loop. This could either be a declaration or an identifier
  8492. // reference. The next token determines which.
  8493. RestorePoint parsedLet;
  8494. this->GetScanner()->Capture(&parsedLet);
  8495. auto ichMinInner = this->GetScanner()->IchMinTok();
  8496. this->GetScanner()->Scan();
  8497. if (IsPossiblePatternStart())
  8498. {
  8499. this->GetScanner()->Capture(&startExprOrIdentifier);
  8500. }
  8501. if (this->NextTokenConfirmsLetDecl() && m_token.tk != tkIN)
  8502. {
  8503. pnodeT = ParseVariableDeclaration<buildAST>(tkLET, ichMinInner
  8504. , /*fAllowIn = */FALSE
  8505. , /*pfForInOk = */&fForInOrOfOkay
  8506. , /*singleDefOnly*/FALSE
  8507. , /*allowInit*/TRUE
  8508. , /*isTopVarParse*/TRUE
  8509. , /*isFor*/TRUE
  8510. , &nativeForOkay);
  8511. break;
  8512. }
  8513. this->GetScanner()->SeekTo(parsedLet);
  8514. }
  8515. goto LDefaultTokenFor;
  8516. case tkLET:
  8517. case tkCONST:
  8518. case tkVAR:
  8519. {
  8520. auto ichMinInner = this->GetScanner()->IchMinTok();
  8521. this->GetScanner()->Scan();
  8522. if (IsPossiblePatternStart())
  8523. {
  8524. this->GetScanner()->Capture(&startExprOrIdentifier);
  8525. }
  8526. pnodeT = ParseVariableDeclaration<buildAST>(tok, ichMinInner
  8527. , /*fAllowIn = */FALSE
  8528. , /*pfForInOk = */&fForInOrOfOkay
  8529. , /*singleDefOnly*/FALSE
  8530. , /*allowInit*/TRUE
  8531. , /*isTopVarParse*/TRUE
  8532. , /*isFor*/TRUE
  8533. , &nativeForOkay);
  8534. }
  8535. break;
  8536. case tkSColon:
  8537. pnodeT = nullptr;
  8538. fForInOrOfOkay = FALSE;
  8539. break;
  8540. default:
  8541. {
  8542. LDefaultTokenFor:
  8543. RestorePoint exprStart;
  8544. tokens beforeToken = tok;
  8545. this->GetScanner()->Capture(&exprStart);
  8546. if (IsPossiblePatternStart())
  8547. {
  8548. this->GetScanner()->Capture(&startExprOrIdentifier);
  8549. }
  8550. bool fLikelyPattern = false;
  8551. if (IsES6DestructuringEnabled() && (beforeToken == tkLBrack || beforeToken == tkLCurly))
  8552. {
  8553. pnodeT = ParseExpr<buildAST>(koplNo,
  8554. &fCanAssign,
  8555. /*fAllowIn = */FALSE,
  8556. /*fAllowEllipsis*/FALSE,
  8557. /*pHint*/nullptr,
  8558. /*pHintLength*/nullptr,
  8559. /*pShortNameOffset*/nullptr,
  8560. /*pToken*/nullptr,
  8561. /**fUnaryOrParen*/false,
  8562. &fLikelyPattern);
  8563. }
  8564. else
  8565. {
  8566. pnodeT = ParseExpr<buildAST>(koplNo, &fCanAssign, /*fAllowIn = */FALSE);
  8567. }
  8568. // 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
  8569. // has already converted them appropriately.
  8570. if (fLikelyPattern && TokIsForInOrForOf())
  8571. {
  8572. this->GetScanner()->SeekTo(exprStart);
  8573. ParseDestructuredLiteralWithScopeSave(tkNone, false/*isDecl*/, false /*topLevel*/, DIC_None, false /*allowIn*/);
  8574. if (buildAST)
  8575. {
  8576. pnodeT = ConvertToPattern(pnodeT);
  8577. }
  8578. }
  8579. if (buildAST)
  8580. {
  8581. Assert(pnodeT);
  8582. pnodeT->isUsed = false;
  8583. }
  8584. }
  8585. break;
  8586. }
  8587. if (TokIsForInOrForOf())
  8588. {
  8589. bool isForOf = (m_token.tk != tkIN);
  8590. Assert(!isForOf || (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.of));
  8591. if ((buildAST && nullptr == pnodeT) || !fForInOrOfOkay)
  8592. {
  8593. if (isForOf)
  8594. {
  8595. Error(ERRForOfNoInitAllowed);
  8596. }
  8597. else
  8598. {
  8599. Error(ERRForInNoInitAllowed);
  8600. }
  8601. }
  8602. if (!fCanAssign &&
  8603. (m_sourceContextInfo
  8604. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  8605. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  8606. {
  8607. Error(ERRInvalidLHSInFor);
  8608. }
  8609. this->GetScanner()->Scan();
  8610. ParseNodePtr pnodeObj = ParseExpr<buildAST>(isForOf ? koplCma : koplNo);
  8611. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8612. ChkCurTok(tkRParen, ERRnoRparen);
  8613. ParseNodeForInOrForOf * pnodeForInOrForOf = nullptr;
  8614. if (buildAST)
  8615. {
  8616. if (isForOf)
  8617. {
  8618. pnodeForInOrForOf = CreateNodeForOpT<knopForOf>(ichMin);
  8619. }
  8620. else
  8621. {
  8622. pnodeForInOrForOf = CreateNodeForOpT<knopForIn>(ichMin);
  8623. }
  8624. pnodeForInOrForOf->pnodeBlock = pnodeBlock;
  8625. pnodeForInOrForOf->pnodeLval = pnodeT;
  8626. pnodeForInOrForOf->pnodeObj = pnodeObj;
  8627. pnodeForInOrForOf->ichLim = ichLim;
  8628. TrackAssignment<true>(pnodeT, nullptr);
  8629. }
  8630. PushStmt<buildAST>(&stmt, pnodeForInOrForOf, isForOf ? knopForOf : knopForIn, pLabelIdList);
  8631. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8632. if (buildAST)
  8633. {
  8634. pnodeForInOrForOf->pnodeBody = pnodeBody;
  8635. pnode = pnodeForInOrForOf;
  8636. }
  8637. PopStmt(&stmt);
  8638. }
  8639. else
  8640. {
  8641. if (!nativeForOkay)
  8642. {
  8643. Error(ERRDestructInit);
  8644. }
  8645. ChkCurTok(tkSColon, ERRnoSemic);
  8646. ParseNodePtr pnodeCond = nullptr;
  8647. if (m_token.tk != tkSColon)
  8648. {
  8649. pnodeCond = ParseExpr<buildAST>();
  8650. if (m_token.tk != tkSColon)
  8651. {
  8652. Error(ERRnoSemic);
  8653. }
  8654. }
  8655. tokens tk;
  8656. tk = this->GetScanner()->Scan();
  8657. ParseNodePtr pnodeIncr = nullptr;
  8658. if (tk != tkRParen)
  8659. {
  8660. pnodeIncr = ParseExpr<buildAST>();
  8661. if (pnodeIncr)
  8662. {
  8663. pnodeIncr->isUsed = false;
  8664. }
  8665. }
  8666. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8667. ChkCurTok(tkRParen, ERRnoRparen);
  8668. ParseNodeFor * pnodeFor = nullptr;
  8669. if (buildAST)
  8670. {
  8671. pnodeFor = CreateNodeForOpT<knopFor>(ichMin);
  8672. pnodeFor->pnodeBlock = pnodeBlock;
  8673. pnodeFor->pnodeInverted = nullptr;
  8674. pnodeFor->pnodeInit = pnodeT;
  8675. pnodeFor->pnodeCond = pnodeCond;
  8676. pnodeFor->pnodeIncr = pnodeIncr;
  8677. pnodeFor->ichLim = ichLim;
  8678. }
  8679. PushStmt<buildAST>(&stmt, pnodeFor, knopFor, pLabelIdList);
  8680. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8681. if (buildAST)
  8682. {
  8683. pnodeFor->pnodeBody = pnodeBody;
  8684. pnode = pnodeFor;
  8685. }
  8686. PopStmt(&stmt);
  8687. }
  8688. if (buildAST)
  8689. {
  8690. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8691. }
  8692. FinishParseBlock(pnodeBlock);
  8693. break;
  8694. }
  8695. case tkSWITCH:
  8696. {
  8697. BOOL fSeenDefault = FALSE;
  8698. ParseNodeBlock * pnodeBlock = nullptr;
  8699. ParseNodePtr *ppnodeScopeSave = nullptr;
  8700. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8701. ichMin = this->GetScanner()->IchMinTok();
  8702. ChkNxtTok(tkLParen, ERRnoLparen);
  8703. ParseNodePtr pnodeVal = ParseExpr<buildAST>();
  8704. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8705. ChkCurTok(tkRParen, ERRnoRparen);
  8706. ChkCurTok(tkLCurly, ERRnoLcurly);
  8707. ParseNodeSwitch * pnodeSwitch = nullptr;
  8708. if (buildAST)
  8709. {
  8710. pnodeSwitch = CreateNodeForOpT<knopSwitch>(ichMin);
  8711. }
  8712. PushStmt<buildAST>(&stmt, pnodeSwitch, knopSwitch, pLabelIdList);
  8713. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8714. ParseNodeCase ** ppnodeCase = nullptr;
  8715. if (buildAST)
  8716. {
  8717. pnodeSwitch->pnodeVal = pnodeVal;
  8718. pnodeSwitch->pnodeBlock = pnodeBlock;
  8719. pnodeSwitch->ichLim = ichLim;
  8720. PushFuncBlockScope(pnodeSwitch->pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8721. pnodeSwitch->pnodeDefault = nullptr;
  8722. ppnodeCase = &pnodeSwitch->pnodeCases;
  8723. pnode = pnodeSwitch;
  8724. }
  8725. for (;;)
  8726. {
  8727. ParseNodeCase * pnodeCase;
  8728. ParseNodePtr pnodeBody = nullptr;
  8729. switch (m_token.tk)
  8730. {
  8731. default:
  8732. goto LEndSwitch;
  8733. case tkCASE:
  8734. {
  8735. pnodeCase = this->ParseCase<buildAST>(&pnodeBody);
  8736. break;
  8737. }
  8738. case tkDEFAULT:
  8739. if (fSeenDefault)
  8740. {
  8741. Error(ERRdupDefault);
  8742. // No recovery necessary since this is a semantic, not structural, error
  8743. }
  8744. fSeenDefault = TRUE;
  8745. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8746. this->GetScanner()->Scan();
  8747. charcount_t ichMinInner = this->GetScanner()->IchLimTok();
  8748. ChkCurTok(tkColon, ERRnoColon);
  8749. if (buildAST)
  8750. {
  8751. pnodeCase = CreateNodeForOpT<knopCase>(ichMinT);
  8752. pnodeSwitch->pnodeDefault = pnodeCase;
  8753. pnodeCase->ichLim = ichMinInner;
  8754. pnodeCase->pnodeExpr = nullptr;
  8755. }
  8756. ParseStmtList<buildAST>(&pnodeBody);
  8757. break;
  8758. }
  8759. // Create a block node to contain the statement list for this case.
  8760. // This helps us insert byte code to return the right value from
  8761. // global/eval code.
  8762. ParseNodeBlock * pnodeFakeBlock = CreateBlockNode();
  8763. if (buildAST)
  8764. {
  8765. if (pnodeBody)
  8766. {
  8767. pnodeFakeBlock->ichMin = pnodeCase->ichMin;
  8768. pnodeFakeBlock->ichLim = pnodeCase->ichLim;
  8769. pnodeCase->pnodeBody = pnodeFakeBlock;
  8770. pnodeCase->pnodeBody->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  8771. pnodeCase->pnodeBody->pnodeStmt = pnodeBody;
  8772. }
  8773. else
  8774. {
  8775. pnodeCase->pnodeBody = nullptr;
  8776. }
  8777. *ppnodeCase = pnodeCase;
  8778. ppnodeCase = &pnodeCase->pnodeNext;
  8779. }
  8780. }
  8781. LEndSwitch:
  8782. ChkCurTok(tkRCurly, ERRnoRcurly);
  8783. if (buildAST)
  8784. {
  8785. *ppnodeCase = nullptr;
  8786. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8787. FinishParseBlock(pnode->AsParseNodeSwitch()->pnodeBlock);
  8788. }
  8789. else
  8790. {
  8791. FinishParseBlock(pnodeBlock);
  8792. }
  8793. PopStmt(&stmt);
  8794. break;
  8795. }
  8796. case tkWHILE:
  8797. {
  8798. ichMin = this->GetScanner()->IchMinTok();
  8799. ChkNxtTok(tkLParen, ERRnoLparen);
  8800. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8801. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8802. ChkCurTok(tkRParen, ERRnoRparen);
  8803. ParseNodeWhile * pnodeWhile = nullptr;
  8804. if (buildAST)
  8805. {
  8806. pnodeWhile = CreateNodeForOpT<knopWhile>(ichMin);
  8807. pnodeWhile->pnodeCond = pnodeCond;
  8808. pnodeWhile->ichLim = ichLim;
  8809. }
  8810. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8811. m_disallowImportExportStmt = true;
  8812. PushStmt<buildAST>(&stmt, pnodeWhile, knopWhile, pLabelIdList);
  8813. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8814. PopStmt(&stmt);
  8815. if (buildAST)
  8816. {
  8817. pnodeWhile->pnodeBody = pnodeBody;
  8818. pnode = pnodeWhile;
  8819. }
  8820. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8821. break;
  8822. }
  8823. case tkDO:
  8824. {
  8825. ParseNodeWhile * pnodeWhile = nullptr;
  8826. if (buildAST)
  8827. {
  8828. pnodeWhile = CreateNodeForOpT<knopDoWhile>();
  8829. }
  8830. PushStmt<buildAST>(&stmt, pnodeWhile, knopDoWhile, pLabelIdList);
  8831. this->GetScanner()->Scan();
  8832. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8833. m_disallowImportExportStmt = true;
  8834. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8835. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8836. PopStmt(&stmt);
  8837. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8838. ChkCurTok(tkWHILE, ERRnoWhile);
  8839. ChkCurTok(tkLParen, ERRnoLparen);
  8840. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8841. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8842. ChkCurTok(tkRParen, ERRnoRparen);
  8843. if (buildAST)
  8844. {
  8845. pnodeWhile->pnodeBody = pnodeBody;
  8846. pnodeWhile->pnodeCond = pnodeCond;
  8847. pnodeWhile->ichLim = ichLim;
  8848. pnodeWhile->ichMin = ichMinT;
  8849. pnode = pnodeWhile;
  8850. }
  8851. // REVIEW: Allow do...while statements to be embedded in other compound statements like if..else, or do..while?
  8852. // goto LNeedTerminator;
  8853. // For now just eat the trailing semicolon if present.
  8854. if (m_token.tk == tkSColon)
  8855. {
  8856. if (pnode)
  8857. {
  8858. pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  8859. }
  8860. this->GetScanner()->Scan();
  8861. }
  8862. else if (pnode)
  8863. {
  8864. pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  8865. }
  8866. break;
  8867. }
  8868. case tkIF:
  8869. {
  8870. ichMin = this->GetScanner()->IchMinTok();
  8871. ChkNxtTok(tkLParen, ERRnoLparen);
  8872. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8873. ParseNodeIf * pnodeIf = nullptr;
  8874. if (buildAST)
  8875. {
  8876. pnodeIf = CreateNodeForOpT<knopIf>(ichMin);
  8877. pnodeIf->ichLim = this->GetScanner()->IchLimTok();
  8878. pnodeIf->pnodeCond = pnodeCond;
  8879. }
  8880. ChkCurTok(tkRParen, ERRnoRparen);
  8881. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8882. m_disallowImportExportStmt = true;
  8883. PushStmt<buildAST>(&stmt, pnodeIf, knopIf, pLabelIdList);
  8884. ParseNodePtr pnodeTrue = ParseStatement<buildAST>();
  8885. ParseNodePtr pnodeFalse = nullptr;
  8886. if (m_token.tk == tkELSE)
  8887. {
  8888. this->GetScanner()->Scan();
  8889. pnodeFalse = ParseStatement<buildAST>();
  8890. }
  8891. if (buildAST)
  8892. {
  8893. pnodeIf->pnodeTrue = pnodeTrue;
  8894. pnodeIf->pnodeFalse = pnodeFalse;
  8895. pnode = pnodeIf;
  8896. }
  8897. PopStmt(&stmt);
  8898. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8899. break;
  8900. }
  8901. case tkTRY:
  8902. {
  8903. ParseNodeBlock * pnodeBlock = CreateBlockNode();
  8904. pnodeBlock->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  8905. PushStmt<buildAST>(&stmt, pnodeBlock, knopBlock, pLabelIdList);
  8906. ParseNodePtr pnodeStmt = ParseTryCatchFinally<buildAST>();
  8907. if (buildAST)
  8908. {
  8909. pnodeBlock->pnodeStmt = pnodeStmt;
  8910. }
  8911. PopStmt(&stmt);
  8912. pnode = pnodeBlock;
  8913. break;
  8914. }
  8915. case tkWITH:
  8916. {
  8917. if (IsStrictMode())
  8918. {
  8919. Error(ERRES5NoWith);
  8920. }
  8921. if (m_currentNodeFunc)
  8922. {
  8923. GetCurrentFunctionNode()->SetHasWithStmt(); // Used by DeferNested
  8924. }
  8925. ichMin = this->GetScanner()->IchMinTok();
  8926. ChkNxtTok(tkLParen, ERRnoLparen);
  8927. ParseNodePtr pnodeObj = ParseExpr<buildAST>();
  8928. if (!buildAST)
  8929. {
  8930. m_scopeCountNoAst++;
  8931. }
  8932. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8933. ChkCurTok(tkRParen, ERRnoRparen);
  8934. ParseNodeWith * pnodeWith = nullptr;
  8935. if (buildAST)
  8936. {
  8937. pnodeWith = CreateNodeForOpT<knopWith>(ichMin);
  8938. }
  8939. PushStmt<buildAST>(&stmt, pnodeWith, knopWith, pLabelIdList);
  8940. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8941. if (buildAST)
  8942. {
  8943. pnodeWith->pnodeObj = pnodeObj;
  8944. this->CheckArguments(pnodeWith->pnodeObj);
  8945. if (m_ppnodeExprScope)
  8946. {
  8947. Assert(*m_ppnodeExprScope == nullptr);
  8948. *m_ppnodeExprScope = pnodeWith;
  8949. m_ppnodeExprScope = &pnodeWith->pnodeNext;
  8950. }
  8951. else
  8952. {
  8953. Assert(m_ppnodeScope);
  8954. Assert(*m_ppnodeScope == nullptr);
  8955. *m_ppnodeScope = pnodeWith;
  8956. m_ppnodeScope = &pnodeWith->pnodeNext;
  8957. }
  8958. pnodeWith->pnodeNext = nullptr;
  8959. pnodeWith->scope = nullptr;
  8960. ppnodeExprScopeSave = m_ppnodeExprScope;
  8961. m_ppnodeExprScope = &pnodeWith->pnodeScopes;
  8962. pnodeWith->pnodeScopes = nullptr;
  8963. pnodeWith->ichLim = ichLim;
  8964. pnode = pnodeWith;
  8965. }
  8966. PushBlockInfo(CreateBlockNode());
  8967. PushDynamicBlock();
  8968. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8969. if (buildAST)
  8970. {
  8971. pnode->AsParseNodeWith()->pnodeBody = pnodeBody;
  8972. m_ppnodeExprScope = ppnodeExprScopeSave;
  8973. }
  8974. else
  8975. {
  8976. m_scopeCountNoAst--;
  8977. }
  8978. // The dynamic block is not stored in the actual parse tree and so will not
  8979. // be visited by the byte code generator. Grab the callsEval flag off it and
  8980. // pass on to outer block in case of:
  8981. // with (...) eval(...); // i.e. blockless form of with
  8982. bool callsEval = GetCurrentBlock()->GetCallsEval();
  8983. PopBlockInfo();
  8984. if (callsEval)
  8985. {
  8986. // be careful not to overwrite an existing true with false
  8987. GetCurrentBlock()->SetCallsEval(true);
  8988. }
  8989. PopStmt(&stmt);
  8990. break;
  8991. }
  8992. case tkLCurly:
  8993. pnode = ParseBlock<buildAST>(pLabelIdList);
  8994. break;
  8995. case tkSColon:
  8996. pnode = nullptr;
  8997. this->GetScanner()->Scan();
  8998. break;
  8999. case tkBREAK:
  9000. if (buildAST)
  9001. {
  9002. pnode = CreateNodeForOpT<knopBreak>();
  9003. }
  9004. fnop = fnopBreak;
  9005. goto LGetJumpStatement;
  9006. case tkCONTINUE:
  9007. if (buildAST)
  9008. {
  9009. pnode = CreateNodeForOpT<knopContinue>();
  9010. }
  9011. fnop = fnopContinue;
  9012. LGetJumpStatement:
  9013. this->GetScanner()->ScanForcingPid();
  9014. if (tkID == m_token.tk && !this->GetScanner()->FHadNewLine())
  9015. {
  9016. // Labeled break or continue.
  9017. pid = m_token.GetIdentifier(this->GetHashTbl());
  9018. if (buildAST)
  9019. {
  9020. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9021. pnodeJump->hasExplicitTarget = true;
  9022. pnodeJump->ichLim = this->GetScanner()->IchLimTok();
  9023. this->GetScanner()->Scan();
  9024. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9025. Assert(pnodeJump->grfnop == 0);
  9026. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9027. {
  9028. for (LabelId* label = pstmt->pLabelId; label != nullptr; label = label->next)
  9029. {
  9030. if (pid == label->pid)
  9031. {
  9032. // Found the label. Make sure we can use it. We can
  9033. // break out of any statement, but we can only
  9034. // continue loops.
  9035. if (fnop == fnopContinue &&
  9036. !(pstmt->pnodeStmt->Grfnop() & fnop))
  9037. {
  9038. Error(ERRbadContinue);
  9039. }
  9040. else
  9041. {
  9042. pstmt->pnodeStmt->grfnop |= fnop;
  9043. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9044. }
  9045. PopStmt(&stmt);
  9046. goto LNeedTerminator;
  9047. }
  9048. }
  9049. pnodeJump->grfnop |=
  9050. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9051. }
  9052. }
  9053. else
  9054. {
  9055. this->GetScanner()->Scan();
  9056. for (pstmt = m_pstmtCur; pstmt; pstmt = pstmt->pstmtOuter)
  9057. {
  9058. LabelId* pLabelId;
  9059. for (pLabelId = pstmt->pLabelId; pLabelId; pLabelId = pLabelId->next)
  9060. {
  9061. if (pid == pLabelId->pid)
  9062. {
  9063. // Found the label. Make sure we can use it. We can
  9064. // break out of any statement, but we can only
  9065. // continue loops.
  9066. if (fnop == fnopContinue &&
  9067. !(ParseNode::Grfnop(pstmt->op) & fnop))
  9068. {
  9069. Error(ERRbadContinue);
  9070. }
  9071. goto LNeedTerminator;
  9072. }
  9073. }
  9074. }
  9075. }
  9076. Error(ERRnoLabel);
  9077. }
  9078. else
  9079. {
  9080. // If we're doing a fast scan, we're not tracking labels, so we can't accurately do this analysis.
  9081. // Let the thread that's doing the full parse detect the error, if there is one.
  9082. if (!this->IsDoingFastScan())
  9083. {
  9084. // Unlabeled break or continue.
  9085. ParseNodeJump * pnodeJump = nullptr;
  9086. if (buildAST)
  9087. {
  9088. pnodeJump = pnode->AsParseNodeJump();
  9089. pnodeJump->hasExplicitTarget = false;
  9090. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9091. Assert(pnodeJump->grfnop == 0);
  9092. }
  9093. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9094. {
  9095. if (buildAST)
  9096. {
  9097. AnalysisAssert(pstmt->pnodeStmt);
  9098. if (pstmt->pnodeStmt->Grfnop() & fnop)
  9099. {
  9100. pstmt->pnodeStmt->grfnop |= fnop;
  9101. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9102. PopStmt(&stmt);
  9103. goto LNeedTerminator;
  9104. }
  9105. pnodeJump->grfnop |=
  9106. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9107. }
  9108. else
  9109. {
  9110. if (ParseNode::Grfnop(pstmt->GetNop()) & fnop)
  9111. {
  9112. if (!pstmt->isDeferred)
  9113. {
  9114. AnalysisAssert(pstmt->pnodeStmt);
  9115. pstmt->pnodeStmt->grfnop |= fnop;
  9116. }
  9117. goto LNeedTerminator;
  9118. }
  9119. }
  9120. }
  9121. Error(fnop == fnopBreak ? ERRbadBreak : ERRbadContinue);
  9122. }
  9123. goto LNeedTerminator;
  9124. }
  9125. case tkRETURN:
  9126. {
  9127. ParseNodeReturn * pnodeReturn;
  9128. if (buildAST)
  9129. {
  9130. if (nullptr == m_currentNodeFunc || IsTopLevelModuleFunc())
  9131. {
  9132. Error(ERRbadReturn);
  9133. }
  9134. pnodeReturn = CreateNodeForOpT<knopReturn>();
  9135. }
  9136. this->GetScanner()->Scan();
  9137. ParseNodePtr pnodeExpr = nullptr;
  9138. ParseOptionalExpr<buildAST>(&pnodeExpr, true);
  9139. // Class constructors have special semantics regarding return statements.
  9140. // This might require a reference to 'this'
  9141. if (GetCurrentFunctionNode()->IsClassConstructor())
  9142. {
  9143. ReferenceSpecialName(wellKnownPropertyPids._this);
  9144. }
  9145. if (buildAST)
  9146. {
  9147. pnodeReturn->pnodeExpr = pnodeExpr;
  9148. if (pnodeExpr)
  9149. {
  9150. this->CheckArguments(pnodeReturn->pnodeExpr);
  9151. pnodeReturn->ichLim = pnodeReturn->pnodeExpr->ichLim;
  9152. }
  9153. // See if return should call finally
  9154. PushStmt<buildAST>(&stmt, pnodeReturn, knopReturn, pLabelIdList);
  9155. Assert(pnodeReturn->grfnop == 0);
  9156. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9157. {
  9158. if (pstmt->pnodeStmt->Grfnop() & fnopCleanup)
  9159. {
  9160. pnodeReturn->grfnop |= fnopCleanup;
  9161. break;
  9162. }
  9163. }
  9164. PopStmt(&stmt);
  9165. pnode = pnodeReturn;
  9166. }
  9167. goto LNeedTerminator;
  9168. }
  9169. case tkTHROW:
  9170. {
  9171. if (buildAST)
  9172. {
  9173. pnode = CreateUniNode(knopThrow, nullptr);
  9174. }
  9175. this->GetScanner()->Scan();
  9176. ParseNodePtr pnode1 = nullptr;
  9177. if (m_token.tk != tkSColon &&
  9178. m_token.tk != tkRCurly &&
  9179. !this->GetScanner()->FHadNewLine())
  9180. {
  9181. pnode1 = ParseExpr<buildAST>();
  9182. }
  9183. else
  9184. {
  9185. Error(ERRdanglingThrow);
  9186. }
  9187. if (buildAST)
  9188. {
  9189. pnode->AsParseNodeUni()->pnode1 = pnode1;
  9190. if (pnode1)
  9191. {
  9192. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  9193. pnode->ichLim = pnode->AsParseNodeUni()->pnode1->ichLim;
  9194. }
  9195. }
  9196. goto LNeedTerminator;
  9197. }
  9198. case tkDEBUGGER:
  9199. if (buildAST)
  9200. {
  9201. pnode = CreateNodeForOpT<knopDebugger>();
  9202. }
  9203. this->GetScanner()->Scan();
  9204. goto LNeedTerminator;
  9205. case tkIMPORT:
  9206. pnode = ParseImport<buildAST>();
  9207. goto LNeedTerminator;
  9208. case tkEXPORT:
  9209. {
  9210. if (!(m_grfscr & fscrIsModuleCode))
  9211. {
  9212. goto LDefaultToken;
  9213. }
  9214. bool needTerminator = false;
  9215. pnode = ParseExportDeclaration<buildAST>(&needTerminator);
  9216. if (needTerminator)
  9217. {
  9218. goto LNeedTerminator;
  9219. }
  9220. else
  9221. {
  9222. break;
  9223. }
  9224. }
  9225. LDefaultToken:
  9226. default:
  9227. {
  9228. // First check for a label via lookahead. If not found,
  9229. // rewind and reparse as expression statement.
  9230. if (m_token.tk == tkID)
  9231. {
  9232. RestorePoint idStart;
  9233. this->GetScanner()->Capture(&idStart);
  9234. IdentPtr pidInner = m_token.GetIdentifier(this->GetHashTbl());
  9235. this->GetScanner()->Scan();
  9236. if (m_token.tk == tkColon)
  9237. {
  9238. // We have a label.
  9239. if (LabelExists(pidInner, pLabelIdList))
  9240. {
  9241. Error(ERRbadLabel);
  9242. }
  9243. LabelId* pLabelId = CreateLabelId(pidInner);
  9244. pLabelId->next = pLabelIdList;
  9245. pLabelIdList = pLabelId;
  9246. this->GetScanner()->Scan();
  9247. labelledStatement = true;
  9248. goto LRestart;
  9249. }
  9250. // No label, rewind back to the tkID and parse an expression
  9251. this->GetScanner()->SeekTo(idStart);
  9252. }
  9253. // Must be an expression statement.
  9254. pnode = ParseExpr<buildAST>();
  9255. if (m_hasDeferredShorthandInitError)
  9256. {
  9257. Error(ERRnoColon);
  9258. }
  9259. if (buildAST)
  9260. {
  9261. expressionStmt = true;
  9262. AnalysisAssert(pnode);
  9263. pnode->isUsed = false;
  9264. }
  9265. }
  9266. LNeedTerminator:
  9267. // Need a semicolon, new-line, } or end-of-file.
  9268. // We digest a semicolon if it's there.
  9269. switch (m_token.tk)
  9270. {
  9271. case tkSColon:
  9272. this->GetScanner()->Scan();
  9273. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9274. break;
  9275. case tkEOF:
  9276. case tkRCurly:
  9277. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9278. break;
  9279. default:
  9280. if (!this->GetScanner()->FHadNewLine())
  9281. {
  9282. Error(ERRnoSemic);
  9283. }
  9284. else
  9285. {
  9286. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9287. }
  9288. break;
  9289. }
  9290. break;
  9291. }
  9292. if (m_hasDeferredShorthandInitError)
  9293. {
  9294. Error(ERRnoColon);
  9295. }
  9296. if (buildAST)
  9297. {
  9298. // All non expression statements excluded from the "this.x" optimization
  9299. // Another check while parsing expressions
  9300. if (!expressionStmt)
  9301. {
  9302. if (m_currentNodeFunc)
  9303. {
  9304. m_currentNodeFunc->SetHasNonThisStmt();
  9305. }
  9306. else if (m_currentNodeProg)
  9307. {
  9308. m_currentNodeProg->SetHasNonThisStmt();
  9309. }
  9310. }
  9311. #if EXCEPTION_RECOVERY
  9312. // close the try/catch block
  9313. if (Js::Configuration::Global.flags.SwallowExceptions)
  9314. {
  9315. // pop the try block and fill in the body
  9316. PopStmt(&stmtTryBlock);
  9317. pTryBlock->pnodeStmt = pnode;
  9318. PopStmt(&stmtTry);
  9319. if (pnode != nullptr)
  9320. {
  9321. pTry->ichLim = pnode->ichLim;
  9322. }
  9323. pTry->pnodeBody = pTryBlock;
  9324. // create a catch block with an empty body
  9325. StmtNest stmtCatch;
  9326. ParseNodeCatch * pCatch;
  9327. pCatch = CreateNodeForOpT<knopCatch>();
  9328. PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr);
  9329. pCatch->pnodeBody = nullptr;
  9330. if (pnode != nullptr)
  9331. {
  9332. pCatch->ichLim = pnode->ichLim;
  9333. }
  9334. pCatch->grfnop = 0;
  9335. pCatch->pnodeNext = nullptr;
  9336. // create a fake name for the catch var.
  9337. const WCHAR *uniqueNameStr = _u("__ehobj");
  9338. IdentPtr uniqueName = this->GetHashTbl()->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));
  9339. pCatch->SetParam(CreateNameNode(uniqueName));
  9340. // Add this catch to the current list. We don't bother adjusting the catch and function expression
  9341. // lists here because the catch is just an empty statement.
  9342. if (m_ppnodeExprScope)
  9343. {
  9344. Assert(*m_ppnodeExprScope == nullptr);
  9345. *m_ppnodeExprScope = pCatch;
  9346. m_ppnodeExprScope = &pCatch->pnodeNext;
  9347. }
  9348. else
  9349. {
  9350. Assert(m_ppnodeScope);
  9351. Assert(*m_ppnodeScope == nullptr);
  9352. *m_ppnodeScope = pCatch;
  9353. m_ppnodeScope = &pCatch->pnodeNext;
  9354. }
  9355. pCatch->pnodeScopes = nullptr;
  9356. PopStmt(&stmtCatch);
  9357. // fill in and pop the try-catch
  9358. pParentTryCatch->pnodeTry = pTry;
  9359. pParentTryCatch->pnodeCatch = pCatch;
  9360. PopStmt(&stmtTryCatch);
  9361. PopStmt(&stmtTryCatchBlock);
  9362. // replace the node that's being returned
  9363. pParentTryCatchBlock->pnodeStmt = pParentTryCatch;
  9364. pnode = pParentTryCatchBlock;
  9365. }
  9366. #endif // EXCEPTION_RECOVERY
  9367. }
  9368. return pnode;
  9369. }
  9370. BOOL
  9371. Parser::TokIsForInOrForOf()
  9372. {
  9373. return m_token.tk == tkIN ||
  9374. (m_token.tk == tkID &&
  9375. m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.of);
  9376. }
  9377. /***************************************************************************
  9378. Parse a sequence of statements.
  9379. ***************************************************************************/
  9380. template<bool buildAST>
  9381. void Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)
  9382. {
  9383. BOOL doneDirectives = !isSourceElementList; // directives may only exist in a SourceElementList, not a StatementList
  9384. BOOL seenDirectiveContainingOctal = false; // Have we seen an octal directive before a use strict directive?
  9385. BOOL old_UseStrictMode = m_fUseStrictMode;
  9386. ParseNodePtr pnodeStmt;
  9387. ParseNodePtr *lastNodeRef = nullptr;
  9388. if (buildAST)
  9389. {
  9390. Assert(ppnodeList);
  9391. *ppnodeList = nullptr;
  9392. }
  9393. if (CONFIG_FLAG(ForceStrictMode))
  9394. {
  9395. m_fUseStrictMode = TRUE;
  9396. }
  9397. for (;;)
  9398. {
  9399. switch (m_token.tk)
  9400. {
  9401. case tkCASE:
  9402. case tkDEFAULT:
  9403. case tkRCurly:
  9404. case tkEOF:
  9405. if (buildAST && nullptr != pppnodeLast)
  9406. {
  9407. *pppnodeLast = lastNodeRef;
  9408. }
  9409. if (!buildAST)
  9410. {
  9411. m_fUseStrictMode = old_UseStrictMode;
  9412. }
  9413. return;
  9414. }
  9415. if (doneDirectives == FALSE)
  9416. {
  9417. bool isOctalInString = false;
  9418. bool isUseStrictDirective = false;
  9419. bool isUseAsmDirective = false;
  9420. if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))
  9421. {
  9422. // Ignore "use asm" statement when not building the AST
  9423. isUseAsmDirective &= buildAST;
  9424. if (isUseStrictDirective)
  9425. {
  9426. // Functions with non-simple parameter list cannot be made strict mode
  9427. if (GetCurrentFunctionNode()->HasNonSimpleParameterList())
  9428. {
  9429. Error(ERRNonSimpleParamListInStrictMode);
  9430. }
  9431. if (seenDirectiveContainingOctal)
  9432. {
  9433. // Directives seen before a "use strict" cannot contain an octal.
  9434. Error(ERRES5NoOctal);
  9435. }
  9436. if (!buildAST)
  9437. {
  9438. // Turning on strict mode in deferred code.
  9439. m_fUseStrictMode = TRUE;
  9440. if (!m_inDeferredNestedFunc)
  9441. {
  9442. // Top-level deferred function, so there's a parse node
  9443. Assert(m_currentNodeFunc != nullptr);
  9444. m_currentNodeFunc->SetStrictMode();
  9445. }
  9446. else if (strictModeOn)
  9447. {
  9448. // This turns on strict mode in a deferred function, we need to go back
  9449. // and re-check duplicated formals.
  9450. *strictModeOn = true;
  9451. }
  9452. }
  9453. else
  9454. {
  9455. if (smEnvironment == SM_OnGlobalCode)
  9456. {
  9457. // Turning on strict mode at the top level
  9458. m_fUseStrictMode = TRUE;
  9459. }
  9460. else
  9461. {
  9462. // i.e. smEnvironment == SM_OnFunctionCode
  9463. Assert(m_currentNodeFunc != nullptr);
  9464. m_currentNodeFunc->SetStrictMode();
  9465. }
  9466. }
  9467. }
  9468. else if (isUseAsmDirective)
  9469. {
  9470. if (smEnvironment != SM_OnGlobalCode) //Top level use asm doesn't mean anything.
  9471. {
  9472. // i.e. smEnvironment == SM_OnFunctionCode
  9473. Assert(m_currentNodeFunc != nullptr);
  9474. m_currentNodeFunc->SetAsmjsMode();
  9475. m_currentNodeFunc->SetCanBeDeferred(false);
  9476. m_InAsmMode = true;
  9477. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, AsmJSFunction, m_scriptContext);
  9478. }
  9479. }
  9480. else if (isOctalInString)
  9481. {
  9482. seenDirectiveContainingOctal = TRUE;
  9483. }
  9484. }
  9485. else
  9486. {
  9487. // The first time we see anything other than a directive we can have no more directives.
  9488. doneDirectives = TRUE;
  9489. }
  9490. }
  9491. if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))
  9492. {
  9493. if (buildAST)
  9494. {
  9495. AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);
  9496. }
  9497. }
  9498. }
  9499. }
  9500. template <class Fn>
  9501. void Parser::FinishFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)
  9502. {
  9503. Scope * scope;
  9504. Scope * origCurrentScope = this->m_currentScope;
  9505. ParseNodePtr pnodeScope;
  9506. ParseNodeBlock * pnodeBlock;
  9507. for (pnodeScope = pnodeScopeList; pnodeScope;)
  9508. {
  9509. switch (pnodeScope->nop)
  9510. {
  9511. case knopBlock:
  9512. {
  9513. ParseNodeBlock * pnodeBlockScope = pnodeScope->AsParseNodeBlock();
  9514. m_nextBlockId = pnodeBlockScope->blockId + 1;
  9515. PushBlockInfo(pnodeBlockScope);
  9516. scope = pnodeBlockScope->scope;
  9517. if (scope && scope != origCurrentScope)
  9518. {
  9519. PushScope(scope);
  9520. }
  9521. FinishFunctionsInScope(pnodeBlockScope->pnodeScopes, fn);
  9522. if (scope && scope != origCurrentScope)
  9523. {
  9524. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9525. PopScope(scope);
  9526. }
  9527. PopBlockInfo();
  9528. pnodeScope = pnodeBlockScope->pnodeNext;
  9529. break;
  9530. }
  9531. case knopFncDecl:
  9532. fn(pnodeScope->AsParseNodeFnc());
  9533. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  9534. break;
  9535. case knopCatch:
  9536. scope = pnodeScope->AsParseNodeCatch()->scope;
  9537. if (scope)
  9538. {
  9539. PushScope(scope);
  9540. }
  9541. pnodeBlock = CreateBlockNode(PnodeBlockType::Regular);
  9542. pnodeBlock->scope = scope;
  9543. PushBlockInfo(pnodeBlock);
  9544. FinishFunctionsInScope(pnodeScope->AsParseNodeCatch()->pnodeScopes, fn);
  9545. if (scope)
  9546. {
  9547. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9548. PopScope(scope);
  9549. }
  9550. PopBlockInfo();
  9551. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  9552. break;
  9553. case knopWith:
  9554. PushBlockInfo(CreateBlockNode());
  9555. PushDynamicBlock();
  9556. FinishFunctionsInScope(pnodeScope->AsParseNodeWith()->pnodeScopes, fn);
  9557. PopBlockInfo();
  9558. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  9559. break;
  9560. default:
  9561. AssertMsg(false, "Unexpected node with scope list");
  9562. return;
  9563. }
  9564. }
  9565. }
  9566. // Scripts above this size (minus string literals and comments) will have parsing of
  9567. // function bodies deferred.
  9568. ULONG Parser::GetDeferralThreshold(bool isProfileLoaded)
  9569. {
  9570. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9571. if (CONFIG_FLAG(ForceDeferParse) ||
  9572. PHASE_FORCE1(Js::DeferParsePhase) ||
  9573. Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  9574. {
  9575. return 0;
  9576. }
  9577. else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))
  9578. {
  9579. return Js::Configuration::Global.flags.DeferParse;
  9580. }
  9581. else
  9582. #endif
  9583. {
  9584. if (isProfileLoaded)
  9585. {
  9586. return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;
  9587. }
  9588. return DEFAULT_CONFIG_DeferParseThreshold;
  9589. }
  9590. }
  9591. void Parser::FinishDeferredFunction(ParseNodeBlock * pnodeScopeList)
  9592. {
  9593. uint saveNextBlockId = m_nextBlockId;
  9594. m_nextBlockId = pnodeScopeList->blockId + 1;
  9595. FinishFunctionsInScope(pnodeScopeList,
  9596. [this](ParseNodeFnc * pnodeFnc)
  9597. {
  9598. Assert(pnodeFnc->nop == knopFncDecl);
  9599. // Non-simple params (such as default) require a good amount of logic to put vars on appropriate scopes. ParseFncDecl handles it
  9600. // properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param
  9601. // will remain deferred until they are called.
  9602. if (pnodeFnc->pnodeBody == nullptr && !pnodeFnc->HasNonSimpleParameterList())
  9603. {
  9604. // Go back and generate an AST for this function.
  9605. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->functionId, /*Undefer*/TRUE));
  9606. ParseNodeFnc * pnodeFncSave = this->m_currentNodeFunc;
  9607. this->m_currentNodeFunc = pnodeFnc;
  9608. ParseNodeBlock * pnodeFncExprBlock = nullptr;
  9609. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  9610. if (pnodeName)
  9611. {
  9612. Assert(pnodeName->nop == knopVarDecl);
  9613. ParseNodeVar * pnodeVarName = pnodeName->AsParseNodeVar();
  9614. Assert(pnodeVarName->pnodeNext == nullptr);
  9615. if (!pnodeFnc->IsDeclaration())
  9616. {
  9617. // Set up the named function expression symbol so references inside the function can be bound.
  9618. pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);
  9619. PidRefStack *ref = this->PushPidRef(pnodeVarName->pid);
  9620. pnodeVarName->symRef = ref->GetSymRef();
  9621. ref->SetSym(pnodeVarName->sym);
  9622. Scope *fncExprScope = pnodeFncExprBlock->scope;
  9623. fncExprScope->AddNewSymbol(pnodeVarName->sym);
  9624. pnodeFnc->scope = fncExprScope;
  9625. }
  9626. }
  9627. ParseNodeBlock * pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);
  9628. pnodeFnc->pnodeScopes = pnodeBlock;
  9629. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  9630. pnodeBlock->pnodeStmt = pnodeFnc;
  9631. ParseNodePtr * varNodesList = &pnodeFnc->pnodeVars;
  9632. ParseNodeVar * argNode = nullptr;
  9633. if (!pnodeFnc->IsModule() && !pnodeFnc->IsLambda() && !(pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam))
  9634. {
  9635. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  9636. m_ppnodeVar = &pnodeFnc->pnodeVars;
  9637. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  9638. varNodesList = m_ppnodeVar;
  9639. m_ppnodeVar = ppnodeVarSave;
  9640. }
  9641. // Add the args to the scope, since we won't re-parse those.
  9642. Scope *scope = pnodeBlock->scope;
  9643. uint blockId = GetCurrentBlock()->blockId;
  9644. uint funcId = GetCurrentFunctionNode()->functionId;
  9645. auto addArgsToScope = [&](ParseNodePtr pnodeArg) {
  9646. if (pnodeArg->IsVarLetOrConst())
  9647. {
  9648. ParseNodeVar * pnodeVarArg = pnodeArg->AsParseNodeVar();
  9649. PidRefStack *ref = this->FindOrAddPidRef(pnodeVarArg->pid, blockId, funcId);
  9650. pnodeVarArg->symRef = ref->GetSymRef();
  9651. if (ref->GetSym() != nullptr)
  9652. {
  9653. // Duplicate parameter in a configuration that allows them.
  9654. // The symbol is already in the scope, just point it to the right declaration.
  9655. Assert(ref->GetSym() == pnodeVarArg->sym);
  9656. ref->GetSym()->SetDecl(pnodeVarArg);
  9657. }
  9658. else
  9659. {
  9660. ref->SetSym(pnodeArg->AsParseNodeVar()->sym);
  9661. scope->AddNewSymbol(pnodeVarArg->sym);
  9662. }
  9663. }
  9664. };
  9665. MapFormals(pnodeFnc, addArgsToScope);
  9666. MapFormalsFromPattern(pnodeFnc, addArgsToScope);
  9667. ParseNodeBlock * pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  9668. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  9669. // Set the parameter block's child to the function body block.
  9670. *m_ppnodeScope = pnodeInnerBlock;
  9671. ParseNodePtr *ppnodeScopeSave = nullptr;
  9672. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9673. ppnodeScopeSave = m_ppnodeScope;
  9674. // This synthetic block scope will contain all the nested scopes.
  9675. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  9676. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  9677. // Keep nested function declarations and expressions in the same list at function scope.
  9678. // (Indicate this by nulling out the current function expressions list.)
  9679. ppnodeExprScopeSave = m_ppnodeExprScope;
  9680. m_ppnodeExprScope = nullptr;
  9681. // Shouldn't be any temps in the arg list.
  9682. Assert(*m_ppnodeVar == nullptr);
  9683. // Start the var list.
  9684. m_ppnodeVar = varNodesList;
  9685. if (scope != nullptr)
  9686. {
  9687. Assert(pnodeFnc->IsBodyAndParamScopeMerged());
  9688. blockId = GetCurrentBlock()->blockId;
  9689. funcId = GetCurrentFunctionNode()->functionId;
  9690. scope->ForEachSymbol([this, blockId, funcId](Symbol* paramSym)
  9691. {
  9692. PidRefStack* ref = this->FindOrAddPidRef(paramSym->GetPid(), blockId, funcId);
  9693. ref->SetSym(paramSym);
  9694. });
  9695. }
  9696. Assert(m_currentNodeNonLambdaFunc == nullptr);
  9697. m_currentNodeNonLambdaFunc = pnodeFnc;
  9698. this->FinishFncNode(pnodeFnc);
  9699. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  9700. m_currentNodeNonLambdaFunc = nullptr;
  9701. m_ppnodeExprScope = ppnodeExprScopeSave;
  9702. Assert(m_ppnodeScope);
  9703. Assert(nullptr == *m_ppnodeScope);
  9704. m_ppnodeScope = ppnodeScopeSave;
  9705. this->FinishParseBlock(pnodeInnerBlock);
  9706. if (!pnodeFnc->IsModule() && (m_token.tk == tkLCurly || !pnodeFnc->IsLambda()))
  9707. {
  9708. UpdateArgumentsNode(pnodeFnc, argNode);
  9709. }
  9710. CreateSpecialSymbolDeclarations(pnodeFnc);
  9711. this->FinishParseBlock(pnodeBlock);
  9712. if (pnodeFncExprBlock)
  9713. {
  9714. this->FinishParseBlock(pnodeFncExprBlock);
  9715. }
  9716. this->m_currentNodeFunc = pnodeFncSave;
  9717. }
  9718. });
  9719. m_nextBlockId = saveNextBlockId;
  9720. }
  9721. void Parser::InitPids()
  9722. {
  9723. wellKnownPropertyPids.arguments = this->GetHashTbl()->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);
  9724. wellKnownPropertyPids.async = this->GetHashTbl()->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);
  9725. wellKnownPropertyPids.eval = this->GetHashTbl()->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);
  9726. wellKnownPropertyPids.get = this->GetHashTbl()->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);
  9727. wellKnownPropertyPids.set = this->GetHashTbl()->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);
  9728. wellKnownPropertyPids.let = this->GetHashTbl()->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);
  9729. wellKnownPropertyPids.constructor = this->GetHashTbl()->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);
  9730. wellKnownPropertyPids.prototype = this->GetHashTbl()->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);
  9731. wellKnownPropertyPids.__proto__ = this->GetHashTbl()->PidHashNameLen(_u("__proto__"), sizeof("__proto__") - 1);
  9732. wellKnownPropertyPids.of = this->GetHashTbl()->PidHashNameLen(_u("of"), sizeof("of") - 1);
  9733. wellKnownPropertyPids.target = this->GetHashTbl()->PidHashNameLen(_u("target"), sizeof("target") - 1);
  9734. wellKnownPropertyPids.as = this->GetHashTbl()->PidHashNameLen(_u("as"), sizeof("as") - 1);
  9735. wellKnownPropertyPids.from = this->GetHashTbl()->PidHashNameLen(_u("from"), sizeof("from") - 1);
  9736. wellKnownPropertyPids._default = this->GetHashTbl()->PidHashNameLen(_u("default"), sizeof("default") - 1);
  9737. wellKnownPropertyPids._starDefaultStar = this->GetHashTbl()->PidHashNameLen(_u("*default*"), sizeof("*default*") - 1);
  9738. wellKnownPropertyPids._star = this->GetHashTbl()->PidHashNameLen(_u("*"), sizeof("*") - 1);
  9739. wellKnownPropertyPids._this = this->GetHashTbl()->PidHashNameLen(_u("*this*"), sizeof("*this*") - 1);
  9740. wellKnownPropertyPids._newTarget = this->GetHashTbl()->PidHashNameLen(_u("*new.target*"), sizeof("*new.target*") - 1);
  9741. wellKnownPropertyPids._super = this->GetHashTbl()->PidHashNameLen(_u("*super*"), sizeof("*super*") - 1);
  9742. wellKnownPropertyPids._superConstructor = this->GetHashTbl()->PidHashNameLen(_u("*superconstructor*"), sizeof("*superconstructor*") - 1);
  9743. }
  9744. void Parser::RestoreScopeInfo(Js::ScopeInfo * scopeInfo)
  9745. {
  9746. if (!scopeInfo)
  9747. {
  9748. return;
  9749. }
  9750. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9751. RestoreScopeInfo(scopeInfo->GetParentScopeInfo()); // Recursively restore outer func scope info
  9752. scopeInfo->SetScopeId(m_nextBlockId);
  9753. ParseNodeBlock * pnodeScope = nullptr;
  9754. ScopeType scopeType = scopeInfo->GetScopeType();
  9755. PnodeBlockType blockType;
  9756. switch (scopeType)
  9757. {
  9758. case ScopeType_With:
  9759. PushDynamicBlock();
  9760. // fall through
  9761. case ScopeType_Block:
  9762. case ScopeType_Catch:
  9763. case ScopeType_CatchParamPattern:
  9764. case ScopeType_GlobalEvalBlock:
  9765. blockType = PnodeBlockType::Regular;
  9766. break;
  9767. case ScopeType_FunctionBody:
  9768. case ScopeType_FuncExpr:
  9769. blockType = PnodeBlockType::Function;
  9770. break;
  9771. case ScopeType_Parameter:
  9772. blockType = PnodeBlockType::Parameter;
  9773. break;
  9774. default:
  9775. Assert(0);
  9776. return;
  9777. }
  9778. pnodeScope = StartParseBlockWithCapacity<true>(blockType, scopeType, scopeInfo->GetSymbolCount());
  9779. Scope *scope = pnodeScope->scope;
  9780. scope->SetScopeInfo(scopeInfo);
  9781. scopeInfo->ExtractScopeInfo(this, /*nullptr, nullptr,*/ scope);
  9782. }
  9783. void Parser::FinishScopeInfo(Js::ScopeInfo * scopeInfo)
  9784. {
  9785. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9786. for (; scopeInfo != nullptr; scopeInfo = scopeInfo->GetParentScopeInfo())
  9787. {
  9788. int scopeId = scopeInfo->GetScopeId();
  9789. scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)
  9790. {
  9791. this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);
  9792. });
  9793. PopScope(scopeInfo->GetScope());
  9794. PopStmt(&m_currentBlockInfo->pstmt);
  9795. PopBlockInfo();
  9796. }
  9797. }
  9798. /***************************************************************************
  9799. Parse the code.
  9800. ***************************************************************************/
  9801. 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)
  9802. {
  9803. ParseNodeProg * pnodeProg;
  9804. ParseNodePtr *lastNodeRef = nullptr;
  9805. m_nextBlockId = 0;
  9806. bool isDeferred = (grfscr & fscrDeferredFnc) != 0;
  9807. bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;
  9808. bool isGlobalCode = (grfscr & fscrGlobalCode) != 0;
  9809. if (this->m_scriptContext->IsScriptContextInDebugMode()
  9810. #ifdef ENABLE_PREJIT
  9811. || Js::Configuration::Global.flags.Prejit
  9812. #endif
  9813. || ((grfscr & fscrNoDeferParse) != 0)
  9814. )
  9815. {
  9816. // Don't do deferred parsing if debugger is attached or feature is disabled
  9817. // by command-line switch.
  9818. grfscr &= ~fscrWillDeferFncParse;
  9819. }
  9820. else if (!isGlobalCode &&
  9821. (
  9822. PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||
  9823. this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  9824. )
  9825. )
  9826. {
  9827. // Don't defer event handlers in debug/rundown mode, because we need to register the document,
  9828. // so we need to create a full FunctionBody for the script body.
  9829. grfscr &= ~fscrWillDeferFncParse;
  9830. }
  9831. m_grfscr = grfscr;
  9832. m_length = length;
  9833. m_originalLength = length;
  9834. m_nextFunctionId = nextFunctionId;
  9835. if (m_parseType != ParseType_Deferred)
  9836. {
  9837. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));
  9838. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);
  9839. }
  9840. // Give the scanner the source and get the first token
  9841. this->GetScanner()->SetText(pszSrc, offset, length, charOffset, isUtf8, grfscr, lineNumber);
  9842. this->GetScanner()->Scan();
  9843. // Make the main 'knopProg' node
  9844. int32 initSize = 0;
  9845. m_pCurrentAstSize = &initSize;
  9846. pnodeProg = CreateProgNode(isModuleSource, lineNumber);
  9847. if (!isDeferred || (isDeferred && isGlobalCode))
  9848. {
  9849. // In the deferred case, if the global function is deferred parse (which is in no-refresh case),
  9850. // we will re-use the same function body, so start with the correct functionId.
  9851. pnodeProg->functionId = (*m_nextFunctionId)++;
  9852. }
  9853. if (isModuleSource)
  9854. {
  9855. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  9856. pnodeProg->AsParseNodeModule()->localExportEntries = nullptr;
  9857. pnodeProg->AsParseNodeModule()->indirectExportEntries = nullptr;
  9858. pnodeProg->AsParseNodeModule()->starExportEntries = nullptr;
  9859. pnodeProg->AsParseNodeModule()->importEntries = nullptr;
  9860. pnodeProg->AsParseNodeModule()->requestedModules = nullptr;
  9861. }
  9862. m_pCurrentAstSize = &(pnodeProg->astSize);
  9863. // initialize parsing variables
  9864. m_currentNodeFunc = nullptr;
  9865. m_currentNodeDeferredFunc = nullptr;
  9866. m_currentNodeProg = pnodeProg;
  9867. m_cactIdentToNodeLookup = 1;
  9868. m_pnestedCount = &pnodeProg->nestedCount;
  9869. m_inDeferredNestedFunc = false;
  9870. m_ppnodeVar = &pnodeProg->pnodeVars;
  9871. SetCurrentStatement(nullptr);
  9872. AssertMsg(m_pstmtCur == nullptr, "Statement stack should be empty when we start parse global code");
  9873. // Create block for const's and let's
  9874. ParseNodeBlock * pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);
  9875. pnodeProg->scope = pnodeGlobalBlock->scope;
  9876. ParseNodeBlock * pnodeGlobalEvalBlock = nullptr;
  9877. // Don't track function expressions separately from declarations at global scope.
  9878. m_ppnodeExprScope = nullptr;
  9879. // This synthetic block scope will contain all the nested scopes.
  9880. pnodeProg->pnodeScopes = pnodeGlobalBlock;
  9881. m_ppnodeScope = &pnodeGlobalBlock->pnodeScopes;
  9882. if ((this->m_grfscr & fscrEvalCode) &&
  9883. !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))
  9884. {
  9885. pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);
  9886. pnodeProg->pnodeScopes = pnodeGlobalEvalBlock;
  9887. m_ppnodeScope = &pnodeGlobalEvalBlock->pnodeScopes;
  9888. }
  9889. Js::ScopeInfo *scopeInfo = nullptr;
  9890. if (m_parseType == ParseType_Deferred && m_functionBody)
  9891. {
  9892. // this->m_functionBody can be cleared during parsing, but we need access to the scope info later.
  9893. scopeInfo = m_functionBody->GetScopeInfo();
  9894. if (scopeInfo)
  9895. {
  9896. // Create an enclosing function context.
  9897. m_currentNodeFunc = CreateNodeForOpT<knopFncDecl>();
  9898. m_currentNodeFunc->functionId = m_functionBody->GetLocalFunctionId();
  9899. m_currentNodeFunc->nestedCount = m_functionBody->GetNestedCount();
  9900. m_currentNodeFunc->SetStrictMode(!!this->m_fUseStrictMode);
  9901. this->RestoreScopeInfo(scopeInfo);
  9902. m_currentNodeFunc->SetIsGenerator(scopeInfo->IsGeneratorFunctionBody());
  9903. m_currentNodeFunc->SetIsAsync(scopeInfo->IsAsyncFunctionBody());
  9904. }
  9905. }
  9906. // It's possible for the module global to be defer-parsed in debug scenarios.
  9907. if (isModuleSource && (!isDeferred || (isDeferred && isGlobalCode)))
  9908. {
  9909. ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();
  9910. pnodeProg->pnodeBody = nullptr;
  9911. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, moduleFunction);
  9912. }
  9913. else
  9914. {
  9915. if (isDeferred && !isGlobalCode)
  9916. {
  9917. // Defer parse for a single function should just parse that one function - there are no other statements.
  9918. ushort flags = fFncNoFlgs;
  9919. size_t iecpMin = 0;
  9920. charcount_t ichMin = 0;
  9921. bool isAsync = false;
  9922. bool isGenerator = false;
  9923. bool isMethod = false;
  9924. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  9925. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  9926. // first time we see it.
  9927. //
  9928. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  9929. // token of the source code of the function may not be a 'function' token though, so we still need to reset this flag
  9930. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  9931. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  9932. if (m_grfscr & fscrDeferredFncExpression)
  9933. {
  9934. m_grfscr &= ~fscrDeferredFncExpression;
  9935. }
  9936. else
  9937. {
  9938. flags |= fFncDeclaration;
  9939. }
  9940. if (m_grfscr & fscrDeferredFncIsMethod)
  9941. {
  9942. m_grfscr &= ~fscrDeferredFncIsMethod;
  9943. isMethod = true;
  9944. flags |= fFncNoName | fFncMethod;
  9945. }
  9946. // These are the cases which can confirm async function:
  9947. // async function() {} -> async function
  9948. // async () => {} -> async lambda with parens around the formal parameter
  9949. // async arg => {} -> async lambda with single identifier parameter
  9950. // async name() {} -> async method
  9951. // async [computed_name]() {} -> async method with a computed name
  9952. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  9953. {
  9954. ichMin = this->GetScanner()->IchMinTok();
  9955. iecpMin = this->GetScanner()->IecpMinTok();
  9956. // Keep state so we can rewind if it turns out that this isn't an async function:
  9957. // async() {} -> method named async
  9958. // async => {} -> lambda with single parameter named async
  9959. RestorePoint termStart;
  9960. this->GetScanner()->Capture(&termStart);
  9961. this->GetScanner()->Scan();
  9962. if (m_token.tk == tkDArrow || (m_token.tk == tkLParen && isMethod) || this->GetScanner()->FHadNewLine())
  9963. {
  9964. this->GetScanner()->SeekTo(termStart);
  9965. }
  9966. else
  9967. {
  9968. flags |= fFncAsync;
  9969. isAsync = true;
  9970. }
  9971. }
  9972. if (m_token.tk == tkStar && m_scriptContext->GetConfig()->IsES6GeneratorsEnabled())
  9973. {
  9974. ichMin = this->GetScanner()->IchMinTok();
  9975. iecpMin = this->GetScanner()->IecpMinTok();
  9976. flags |= fFncGenerator;
  9977. isGenerator = true;
  9978. this->GetScanner()->Scan();
  9979. }
  9980. // Eat the computed name expression
  9981. if (m_token.tk == tkLBrack && isMethod)
  9982. {
  9983. this->GetScanner()->Scan();
  9984. ParseExpr<false>();
  9985. }
  9986. if (!isMethod && (m_token.tk == tkID || m_token.tk == tkLParen))
  9987. {
  9988. // If first token of the function is tkID or tkLParen, this is a lambda.
  9989. flags |= fFncLambda;
  9990. }
  9991. ParseNode * pnodeFnc = ParseFncDeclNoCheckScope<true>(flags);
  9992. pnodeProg->pnodeBody = nullptr;
  9993. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, pnodeFnc);
  9994. // Include the async keyword or star character in the function extents
  9995. if (isAsync || isGenerator)
  9996. {
  9997. pnodeFnc->AsParseNodeFnc()->cbMin = iecpMin;
  9998. pnodeFnc->ichMin = ichMin;
  9999. }
  10000. }
  10001. else
  10002. {
  10003. // Process a sequence of statements/declarations
  10004. ParseStmtList<true>(
  10005. &pnodeProg->pnodeBody,
  10006. &lastNodeRef,
  10007. SM_OnGlobalCode,
  10008. !(m_grfscr & fscrDeferredFncExpression) /* isSourceElementList */);
  10009. }
  10010. }
  10011. if (m_parseType == ParseType_Deferred)
  10012. {
  10013. if (scopeInfo)
  10014. {
  10015. this->FinishScopeInfo(scopeInfo);
  10016. }
  10017. }
  10018. pnodeProg->m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;
  10019. if (IsStrictMode())
  10020. {
  10021. pnodeProg->SetStrictMode();
  10022. }
  10023. #if DEBUG
  10024. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->pnodeBody))
  10025. {
  10026. Error(ERRsyntax);
  10027. }
  10028. #endif
  10029. if (tkEOF != m_token.tk)
  10030. Error(ERRsyntax);
  10031. // Append an EndCode node.
  10032. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef,
  10033. CreateNodeForOpT<knopEndCode>());
  10034. Assert(lastNodeRef);
  10035. Assert(*lastNodeRef);
  10036. Assert((*lastNodeRef)->nop == knopEndCode);
  10037. (*lastNodeRef)->ichMin = 0;
  10038. (*lastNodeRef)->ichLim = 0;
  10039. // Get the extent of the code.
  10040. pnodeProg->ichLim = this->GetScanner()->IchLimTok();
  10041. pnodeProg->cbLim = this->GetScanner()->IecpLimTok();
  10042. // Terminate the local list
  10043. *m_ppnodeVar = nullptr;
  10044. Assert(nullptr == *m_ppnodeScope);
  10045. Assert(nullptr == pnodeProg->pnodeNext);
  10046. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10047. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10048. {
  10049. m_stoppedDeferredParse = true;
  10050. }
  10051. #endif
  10052. if (m_stoppedDeferredParse)
  10053. {
  10054. #if ENABLE_BACKGROUND_PARSING
  10055. if (this->m_hasParallelJob)
  10056. {
  10057. BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());
  10058. Assert(bgp);
  10059. this->WaitForBackgroundJobs(bgp, pse);
  10060. }
  10061. #endif
  10062. // Do any remaining bindings of globals referenced in non-deferred functions.
  10063. if (pnodeGlobalEvalBlock)
  10064. {
  10065. FinishParseBlock(pnodeGlobalEvalBlock);
  10066. }
  10067. FinishParseBlock(pnodeGlobalBlock);
  10068. // Clear out references to undeclared identifiers.
  10069. this->GetHashTbl()->VisitPids([&](IdentPtr pid) { pid->SetTopRef(nullptr); });
  10070. // Restore global scope and blockinfo stacks preparatory to reparsing deferred functions.
  10071. PushScope(pnodeGlobalBlock->scope);
  10072. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeGlobalBlock);
  10073. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalBlock, knopBlock, nullptr);
  10074. if (pnodeGlobalEvalBlock)
  10075. {
  10076. PushScope(pnodeGlobalEvalBlock->scope);
  10077. newBlockInfo = PushBlockInfo(pnodeGlobalEvalBlock);
  10078. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalEvalBlock, knopBlock, nullptr);
  10079. }
  10080. // Finally, see if there are any function bodies we now want to generate because we
  10081. // decided to stop deferring.
  10082. FinishDeferredFunction(pnodeProg->pnodeScopes);
  10083. }
  10084. if (pnodeGlobalEvalBlock)
  10085. {
  10086. FinishParseBlock(pnodeGlobalEvalBlock);
  10087. }
  10088. // Append block as body of pnodeProg
  10089. FinishParseBlock(pnodeGlobalBlock);
  10090. m_scriptContext->AddSourceSize(m_length);
  10091. if (m_parseType != ParseType_Deferred)
  10092. {
  10093. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));
  10094. }
  10095. return pnodeProg;
  10096. }
  10097. bool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)
  10098. {
  10099. // A directive is a string constant followed by a statement terminating token
  10100. if (m_token.tk != tkStrCon)
  10101. return false;
  10102. // Careful, need to check for octal before calling this->GetScanner()->Scan()
  10103. // because Scan() clears the "had octal" flag on the scanner and
  10104. // this->GetScanner()->Restore() does not restore this flag.
  10105. if (pIsOctalInString != nullptr)
  10106. {
  10107. *pIsOctalInString = this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber();
  10108. }
  10109. Ident* pidDirective = m_token.GetStr();
  10110. RestorePoint start;
  10111. this->GetScanner()->Capture(&start);
  10112. this->GetScanner()->Scan();
  10113. bool isDirective = true;
  10114. switch (m_token.tk)
  10115. {
  10116. case tkSColon:
  10117. case tkEOF:
  10118. case tkLCurly:
  10119. case tkRCurly:
  10120. break;
  10121. default:
  10122. if (!this->GetScanner()->FHadNewLine())
  10123. {
  10124. isDirective = false;
  10125. }
  10126. break;
  10127. }
  10128. if (isDirective)
  10129. {
  10130. if (pIsUseStrict != nullptr)
  10131. {
  10132. *pIsUseStrict = CheckStrictModeStrPid(pidDirective);
  10133. }
  10134. if (pIsUseAsm != nullptr)
  10135. {
  10136. *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);
  10137. }
  10138. }
  10139. this->GetScanner()->SeekTo(start);
  10140. return isDirective;
  10141. }
  10142. bool Parser::CheckStrictModeStrPid(IdentPtr pid)
  10143. {
  10144. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10145. if (Js::Configuration::Global.flags.NoStrictMode)
  10146. return false;
  10147. #endif
  10148. return pid != nullptr &&
  10149. pid->Cch() == 10 &&
  10150. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10151. wcsncmp(pid->Psz(), _u("use strict"), 10) == 0;
  10152. }
  10153. bool Parser::CheckAsmjsModeStrPid(IdentPtr pid)
  10154. {
  10155. #ifdef ASMJS_PLAT
  10156. if (!CONFIG_FLAG(AsmJs))
  10157. {
  10158. return false;
  10159. }
  10160. bool isAsmCandidate = (pid != nullptr &&
  10161. AutoSystemInfo::Data.SSE2Available() &&
  10162. pid->Cch() == 7 &&
  10163. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10164. wcsncmp(pid->Psz(), _u("use asm"), 10) == 0);
  10165. #ifdef ENABLE_SCRIPT_DEBUGGING
  10166. if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())
  10167. {
  10168. // We would like to report this to debugger - they may choose to disable debugging.
  10169. // TODO : localization of the string?
  10170. 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);
  10171. return false;
  10172. }
  10173. #endif
  10174. return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);
  10175. #else
  10176. return false;
  10177. #endif
  10178. }
  10179. HRESULT Parser::ParseUtf8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10180. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10181. {
  10182. m_functionBody = nullptr;
  10183. m_parseType = ParseType_Upfront;
  10184. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10185. }
  10186. HRESULT Parser::ParseCesu8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10187. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10188. {
  10189. m_functionBody = nullptr;
  10190. m_parseType = ParseType_Upfront;
  10191. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10192. }
  10193. #if ENABLE_BACKGROUND_PARSING
  10194. void Parser::PrepareForBackgroundParse()
  10195. {
  10196. this->GetScanner()->PrepareForBackgroundParse(m_scriptContext);
  10197. }
  10198. void Parser::AddBackgroundParseItem(BackgroundParseItem *const item)
  10199. {
  10200. if (currBackgroundParseItem == nullptr)
  10201. {
  10202. backgroundParseItems = item;
  10203. }
  10204. else
  10205. {
  10206. currBackgroundParseItem->SetNext(item);
  10207. }
  10208. currBackgroundParseItem = item;
  10209. }
  10210. void Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)
  10211. {
  10212. Assert(!IsBackgroundParser());
  10213. Assert(m_doingFastScan);
  10214. if (fastScannedRegExpNodes == nullptr)
  10215. {
  10216. fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);
  10217. }
  10218. fastScannedRegExpNodes->Append(pnode);
  10219. }
  10220. void Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)
  10221. {
  10222. Assert(IsBackgroundParser());
  10223. Assert(currBackgroundParseItem != nullptr);
  10224. currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);
  10225. }
  10226. HRESULT Parser::ParseFunctionInBackground(ParseNodeFnc * pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)
  10227. {
  10228. m_functionBody = nullptr;
  10229. m_parseType = ParseType_Upfront;
  10230. HRESULT hr = S_OK;
  10231. SmartFPUControl smartFpuControl;
  10232. uint nextFunctionId = pnodeFnc->functionId + 1;
  10233. this->RestoreContext(parseContext);
  10234. m_nextFunctionId = &nextFunctionId;
  10235. m_deferringAST = topLevelDeferred;
  10236. m_inDeferredNestedFunc = false;
  10237. m_scopeCountNoAst = 0;
  10238. SetCurrentStatement(nullptr);
  10239. pnodeFnc->pnodeVars = nullptr;
  10240. pnodeFnc->pnodeParams = nullptr;
  10241. pnodeFnc->pnodeBody = nullptr;
  10242. pnodeFnc->nestedCount = 0;
  10243. ParseNodeFnc * pnodeParentFnc = GetCurrentFunctionNode();
  10244. m_currentNodeFunc = pnodeFnc;
  10245. m_currentNodeDeferredFunc = nullptr;
  10246. m_ppnodeScope = nullptr;
  10247. m_ppnodeExprScope = nullptr;
  10248. m_pnestedCount = &pnodeFnc->nestedCount;
  10249. m_pCurrentAstSize = &pnodeFnc->astSize;
  10250. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10251. pnodeFnc->pnodeScopes = pnodeBlock;
  10252. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  10253. uint uDeferSave = m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse);
  10254. try
  10255. {
  10256. this->GetScanner()->Scan();
  10257. m_ppnodeVar = &pnodeFnc->pnodeParams;
  10258. this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);
  10259. if (m_token.tk == tkRParen)
  10260. {
  10261. this->GetScanner()->Scan();
  10262. }
  10263. ChkCurTok(tkLCurly, ERRnoLcurly);
  10264. m_ppnodeVar = &pnodeFnc->pnodeVars;
  10265. // Put the scanner into "no hashing" mode.
  10266. BYTE deferFlags = this->GetScanner()->SetDeferredParse(topLevelDeferred);
  10267. // Process a sequence of statements/declarations
  10268. if (topLevelDeferred)
  10269. {
  10270. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);
  10271. }
  10272. else
  10273. {
  10274. ParseNodePtr *lastNodeRef = nullptr;
  10275. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);
  10276. AddArgumentsNodeToVars(pnodeFnc);
  10277. // Append an EndCode node.
  10278. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  10279. }
  10280. // Restore the scanner's default hashing mode.
  10281. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  10282. #if DBG
  10283. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  10284. #endif
  10285. this->m_deferringAST = FALSE;
  10286. // Append block as body of pnodeProg
  10287. FinishParseBlock(pnodeBlock);
  10288. }
  10289. catch (ParseExceptionObject& e)
  10290. {
  10291. hr = e.GetError();
  10292. }
  10293. if (FAILED(hr))
  10294. {
  10295. hr = pse->ProcessError(this->GetScanner(), hr, nullptr);
  10296. }
  10297. if (IsStrictMode())
  10298. {
  10299. pnodeFnc->SetStrictMode();
  10300. }
  10301. if (topLevelDeferred)
  10302. {
  10303. pnodeFnc->pnodeVars = nullptr;
  10304. }
  10305. m_grfscr |= uDeferSave;
  10306. Assert(nullptr == *m_ppnodeScope);
  10307. return hr;
  10308. }
  10309. #endif
  10310. HRESULT Parser::ParseSourceWithOffset(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,
  10311. bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,
  10312. Js::ParseableFunctionInfo* functionInfo)
  10313. {
  10314. m_functionBody = functionInfo;
  10315. if (m_functionBody)
  10316. {
  10317. m_currDeferredStub = m_functionBody->GetDeferredStubs();
  10318. m_currDeferredStubCount = m_currDeferredStub != nullptr ? m_functionBody->GetNestedCount() : 0;
  10319. m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();
  10320. }
  10321. m_deferAsmJs = !m_InAsmMode;
  10322. m_parseType = ParseType_Deferred;
  10323. return ParseSourceInternal(parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);
  10324. }
  10325. bool Parser::IsStrictMode() const
  10326. {
  10327. return (m_fUseStrictMode ||
  10328. (m_currentNodeFunc != nullptr && m_currentNodeFunc->GetStrictMode()));
  10329. }
  10330. BOOL Parser::ExpectingExternalSource()
  10331. {
  10332. return m_fExpectExternalSource;
  10333. }
  10334. Symbol *ParseNodeFnc::GetFuncSymbol()
  10335. {
  10336. if (pnodeName)
  10337. {
  10338. Assert(pnodeName->nop == knopVarDecl);
  10339. return pnodeName->sym;
  10340. }
  10341. return nullptr;
  10342. }
  10343. void ParseNodeFnc::SetFuncSymbol(Symbol *sym)
  10344. {
  10345. Assert(pnodeName);
  10346. Assert(pnodeName->nop == knopVarDecl);
  10347. pnodeName->sym = sym;
  10348. }
  10349. ParseNodePtr ParseNodeFnc::GetParamScope() const
  10350. {
  10351. if (this->pnodeScopes == nullptr)
  10352. {
  10353. return nullptr;
  10354. }
  10355. Assert(this->pnodeScopes->nop == knopBlock &&
  10356. this->pnodeScopes->pnodeNext == nullptr);
  10357. return this->pnodeScopes->pnodeScopes;
  10358. }
  10359. ParseNodePtr ParseNodeFnc::GetBodyScope() const
  10360. {
  10361. if (this->pnodeBodyScope == nullptr)
  10362. {
  10363. return nullptr;
  10364. }
  10365. Assert(this->pnodeBodyScope->nop == knopBlock &&
  10366. this->pnodeBodyScope->pnodeNext == nullptr);
  10367. return this->pnodeBodyScope->pnodeScopes;
  10368. }
  10369. bool ParseNodeBlock::HasBlockScopedContent() const
  10370. {
  10371. // A block has its own content if a let, const, or function is declared there.
  10372. if (this->pnodeLexVars != nullptr || this->blockType == Parameter)
  10373. {
  10374. return true;
  10375. }
  10376. // The enclosing scopes can contain functions and other things, so walk the list
  10377. // looking specifically for functions.
  10378. for (ParseNodePtr pnode = this->pnodeScopes; pnode;)
  10379. {
  10380. switch (pnode->nop) {
  10381. case knopFncDecl:
  10382. return true;
  10383. case knopBlock:
  10384. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  10385. break;
  10386. case knopCatch:
  10387. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  10388. break;
  10389. case knopWith:
  10390. pnode = pnode->AsParseNodeWith()->pnodeNext;
  10391. break;
  10392. default:
  10393. Assert(UNREACHED);
  10394. return true;
  10395. }
  10396. }
  10397. return false;
  10398. }
  10399. class ByteCodeGenerator;
  10400. // Copy AST; this works mostly on expressions for now
  10401. ParseNode* Parser::CopyPnode(ParseNode *pnode) {
  10402. if (pnode == NULL)
  10403. return NULL;
  10404. switch (pnode->nop) {
  10405. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  10406. case knopName: {
  10407. ParseNodeName * nameNode = CreateNameNode(pnode->AsParseNodeName()->pid);
  10408. nameNode->ichMin = pnode->ichMin;
  10409. nameNode->ichLim = pnode->ichLim;
  10410. nameNode->sym = pnode->AsParseNodeName()->sym;
  10411. return nameNode;
  10412. }
  10413. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  10414. case knopInt:
  10415. return pnode;
  10416. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  10417. case knopFlt:
  10418. return pnode;
  10419. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  10420. case knopStr:
  10421. return pnode;
  10422. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  10423. case knopRegExp:
  10424. return pnode;
  10425. break;
  10426. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  10427. case knopNull:
  10428. return pnode;
  10429. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  10430. case knopFalse:
  10431. {
  10432. ParseNode* ret = CreateNodeForOpT<knopFalse>(pnode->ichMin, pnode->ichLim);
  10433. ret->location = pnode->location;
  10434. return ret;
  10435. }
  10436. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  10437. case knopTrue:
  10438. {
  10439. ParseNode* ret = CreateNodeForOpT<knopTrue>(pnode->ichMin, pnode->ichLim);
  10440. ret->location = pnode->location;
  10441. return ret;
  10442. }
  10443. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  10444. case knopEmpty:
  10445. return CreateNodeForOpT<knopEmpty>(pnode->ichMin, pnode->ichLim);
  10446. // Unary operators.
  10447. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  10448. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  10449. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  10450. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  10451. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  10452. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  10453. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  10454. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  10455. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  10456. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  10457. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  10458. case knopNot:
  10459. case knopNeg:
  10460. case knopPos:
  10461. case knopLogNot:
  10462. case knopEllipsis:
  10463. case knopIncPost:
  10464. case knopDecPost:
  10465. case knopIncPre:
  10466. case knopDecPre:
  10467. case knopTypeof:
  10468. case knopVoid:
  10469. case knopDelete:
  10470. return CreateUniNode(pnode->nop, CopyPnode(pnode->AsParseNodeUni()->pnode1), pnode->ichMin, pnode->ichLim);
  10471. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  10472. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  10473. case knopArray:
  10474. case knopObject:
  10475. // TODO: need to copy arr
  10476. Assert(false);
  10477. break;
  10478. // Binary operators
  10479. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  10480. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  10481. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  10482. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  10483. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  10484. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  10485. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  10486. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  10487. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  10488. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  10489. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  10490. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  10491. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  10492. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  10493. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  10494. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  10495. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  10496. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  10497. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  10498. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  10499. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10500. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10501. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  10502. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  10503. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  10504. case knopAdd:
  10505. case knopSub:
  10506. case knopMul:
  10507. case knopExpo:
  10508. case knopDiv:
  10509. case knopMod:
  10510. case knopOr:
  10511. case knopXor:
  10512. case knopAnd:
  10513. case knopEq:
  10514. case knopNe:
  10515. case knopLt:
  10516. case knopLe:
  10517. case knopGe:
  10518. case knopGt:
  10519. case knopEqv:
  10520. case knopIn:
  10521. case knopInstOf:
  10522. case knopNEqv:
  10523. case knopComma:
  10524. case knopLogOr:
  10525. case knopLogAnd:
  10526. case knopLsh:
  10527. case knopRsh:
  10528. case knopRs2:
  10529. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10530. case knopAsg:
  10531. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  10532. case knopDot:
  10533. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  10534. case knopAsgAdd:
  10535. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  10536. case knopAsgSub:
  10537. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  10538. case knopAsgMul:
  10539. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  10540. case knopAsgExpo:
  10541. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  10542. case knopAsgDiv:
  10543. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  10544. case knopAsgMod:
  10545. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  10546. case knopAsgAnd:
  10547. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  10548. case knopAsgXor:
  10549. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  10550. case knopAsgOr:
  10551. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  10552. case knopAsgLsh:
  10553. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  10554. case knopAsgRsh:
  10555. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  10556. case knopAsgRs2:
  10557. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  10558. case knopMember:
  10559. case knopMemberShort:
  10560. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  10561. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  10562. case knopIndex:
  10563. case knopList:
  10564. return CreateBinNode(pnode->nop, CopyPnode(pnode->AsParseNodeBin()->pnode1),
  10565. CopyPnode(pnode->AsParseNodeBin()->pnode2), pnode->ichMin, pnode->ichLim);
  10566. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  10567. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  10568. case knopNew:
  10569. case knopCall:
  10570. return CreateCallNode(pnode->nop, CopyPnode(pnode->AsParseNodeCall()->pnodeTarget),
  10571. CopyPnode(pnode->AsParseNodeCall()->pnodeArgs), pnode->ichMin, pnode->ichLim);
  10572. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10573. case knopQmark:
  10574. return CreateTriNode(pnode->nop, CopyPnode(pnode->AsParseNodeTri()->pnode1),
  10575. CopyPnode(pnode->AsParseNodeTri()->pnode2), CopyPnode(pnode->AsParseNodeTri()->pnode3),
  10576. pnode->ichMin, pnode->ichLim);
  10577. // General nodes.
  10578. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10579. case knopVarDecl: {
  10580. ParseNodeVar* copyNode = Anew(&m_nodeAllocator, ParseNodeVar, knopVarDecl, pnode->ichMin, pnode->ichLim, nullptr);
  10581. copyNode->pnodeInit = CopyPnode(pnode->AsParseNodeVar()->pnodeInit);
  10582. copyNode->sym = pnode->AsParseNodeVar()->sym;
  10583. // TODO: mult-decl
  10584. Assert(pnode->AsParseNodeVar()->pnodeNext == NULL);
  10585. copyNode->pnodeNext = NULL;
  10586. return copyNode;
  10587. }
  10588. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10589. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  10590. case knopFncDecl:
  10591. case knopProg:
  10592. Assert(false);
  10593. break;
  10594. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  10595. case knopEndCode:
  10596. break;
  10597. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10598. case knopDebugger:
  10599. break;
  10600. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10601. case knopFor: {
  10602. ParseNode* copyNode = CreateNodeForOpT<knopFor>(pnode->ichMin, pnode->ichLim);
  10603. copyNode->AsParseNodeFor()->pnodeInverted = NULL;
  10604. copyNode->AsParseNodeFor()->pnodeInit = CopyPnode(pnode->AsParseNodeFor()->pnodeInit);
  10605. copyNode->AsParseNodeFor()->pnodeCond = CopyPnode(pnode->AsParseNodeFor()->pnodeCond);
  10606. copyNode->AsParseNodeFor()->pnodeIncr = CopyPnode(pnode->AsParseNodeFor()->pnodeIncr);
  10607. copyNode->AsParseNodeFor()->pnodeBody = CopyPnode(pnode->AsParseNodeFor()->pnodeBody);
  10608. return copyNode;
  10609. }
  10610. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10611. case knopIf:
  10612. Assert(false);
  10613. break;
  10614. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  10615. case knopWhile:
  10616. Assert(false);
  10617. break;
  10618. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10619. case knopDoWhile:
  10620. Assert(false);
  10621. break;
  10622. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10623. case knopForIn:
  10624. Assert(false);
  10625. break;
  10626. case knopForOf:
  10627. Assert(false);
  10628. break;
  10629. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10630. case knopReturn: {
  10631. ParseNode* copyNode = CreateNodeForOpT<knopReturn>(pnode->ichMin, pnode->ichLim);
  10632. copyNode->AsParseNodeReturn()->pnodeExpr = CopyPnode(pnode->AsParseNodeReturn()->pnodeExpr);
  10633. return copyNode;
  10634. }
  10635. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10636. case knopBlock: {
  10637. ParseNodeBlock* copyNode = CreateBlockNode(pnode->ichMin, pnode->ichLim, pnode->AsParseNodeBlock()->blockType);
  10638. if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {
  10639. // fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which
  10640. // CreateBlockNode() will not automatically set for us, so set it here if it's
  10641. // specified on the source node.
  10642. copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;
  10643. }
  10644. copyNode->pnodeStmt = CopyPnode(pnode->AsParseNodeBlock()->pnodeStmt);
  10645. return copyNode;
  10646. }
  10647. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10648. case knopWith:
  10649. Assert(false);
  10650. break;
  10651. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10652. case knopBreak:
  10653. Assert(false);
  10654. break;
  10655. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10656. case knopContinue:
  10657. Assert(false);
  10658. break;
  10659. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  10660. case knopSwitch:
  10661. Assert(false);
  10662. break;
  10663. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  10664. case knopCase:
  10665. Assert(false);
  10666. break;
  10667. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  10668. case knopTryFinally:
  10669. Assert(false);
  10670. break;
  10671. case knopFinally:
  10672. Assert(false);
  10673. break;
  10674. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  10675. case knopCatch:
  10676. Assert(false);
  10677. break;
  10678. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  10679. case knopTryCatch:
  10680. Assert(false);
  10681. break;
  10682. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  10683. case knopTry:
  10684. Assert(false);
  10685. break;
  10686. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  10687. case knopThrow:
  10688. Assert(false);
  10689. break;
  10690. default:
  10691. Assert(false);
  10692. break;
  10693. }
  10694. return NULL;
  10695. }
  10696. // Returns true when str is string for Nan, Infinity or -Infinity.
  10697. // Does not check for double number value being in NaN/Infinity range.
  10698. // static
  10699. template<bool CheckForNegativeInfinity>
  10700. inline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)
  10701. {
  10702. // Note: wcscmp crashes when one of the parameters is NULL.
  10703. return str &&
  10704. (wcscmp(_u("NaN"), str) == 0 ||
  10705. wcscmp(_u("Infinity"), str) == 0 ||
  10706. (CheckForNegativeInfinity && wcscmp(_u("-Infinity"), str) == 0));
  10707. }
  10708. template <bool buildAST>
  10709. IdentPtr Parser::ParseSuper(bool fAllowCall)
  10710. {
  10711. ParseNodeFnc * currentNodeFunc = GetCurrentFunctionNode();
  10712. ParseNodeFnc * currentNonLambdaFunc = GetCurrentNonLambdaFunctionNode();
  10713. IdentPtr superPid = nullptr;
  10714. switch (m_token.tk)
  10715. {
  10716. case tkDot: // super.prop
  10717. case tkLBrack: // super[foo]
  10718. superPid = wellKnownPropertyPids._super;
  10719. break;
  10720. case tkLParen: // super(args)
  10721. superPid = wellKnownPropertyPids._superConstructor;
  10722. break;
  10723. default:
  10724. Error(ERRInvalidSuper);
  10725. break;
  10726. }
  10727. currentNodeFunc->SetHasSuperReference(TRUE);
  10728. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Super, m_scriptContext);
  10729. // If we are defer parsing, we can skip verifying that the super reference is valid.
  10730. // If it wasn't the parser would have thrown during upfront parsing and we wouldn't be defer parsing the function.
  10731. if (m_parseType == ParseType_Deferred)
  10732. {
  10733. return superPid;
  10734. }
  10735. if (!fAllowCall && (m_token.tk == tkLParen))
  10736. {
  10737. Error(ERRInvalidSuper); // new super() is not allowed
  10738. }
  10739. else if ((currentNodeFunc->IsConstructor() && currentNodeFunc->superRestrictionState == SuperRestrictionState::CallAndPropertyAllowed)
  10740. || (currentNonLambdaFunc != nullptr && currentNonLambdaFunc->superRestrictionState == SuperRestrictionState::CallAndPropertyAllowed))
  10741. {
  10742. // Any super access is good within a class constructor
  10743. }
  10744. else if ((this->m_grfscr & fscrEval) == fscrEval || (currentNonLambdaFunc != nullptr && currentNonLambdaFunc->superRestrictionState == SuperRestrictionState::PropertyAllowed))
  10745. {
  10746. // Currently for eval cases during compile time we use propertyallowed and throw during runtime for error cases
  10747. if (m_token.tk == tkLParen)
  10748. {
  10749. if ((this->m_grfscr & fscrEval) == fscrNil)
  10750. {
  10751. // Cannot call super within a class member
  10752. Error(ERRInvalidSuper);
  10753. }
  10754. else
  10755. {
  10756. Js::JavascriptFunction * caller = nullptr;
  10757. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  10758. {
  10759. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  10760. Assert(callerBody);
  10761. if (!callerBody->GetFunctionInfo()->GetAllowDirectSuper())
  10762. {
  10763. Error(ERRInvalidSuper);
  10764. }
  10765. }
  10766. }
  10767. }
  10768. }
  10769. else
  10770. {
  10771. // Anything else is an error
  10772. Error(ERRInvalidSuper);
  10773. }
  10774. return superPid;
  10775. }
  10776. void Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)
  10777. {
  10778. Assert(nodeToAppend);
  10779. ParseNodePtr* lastPtr = node;
  10780. while ((*lastPtr) && (*lastPtr)->nop == knopList)
  10781. {
  10782. lastPtr = &(*lastPtr)->AsParseNodeBin()->pnode2;
  10783. }
  10784. auto last = (*lastPtr);
  10785. if (last)
  10786. {
  10787. *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);
  10788. }
  10789. else
  10790. {
  10791. *lastPtr = nodeToAppend;
  10792. }
  10793. }
  10794. ParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)
  10795. {
  10796. Assert(pnode->nop == knopArray);
  10797. pnode->nop = knopArrayPattern;
  10798. ForEachItemRefInList(&pnode->AsParseNodeArrLit()->pnode1, [&](ParseNodePtr *itemRef) {
  10799. ParseNodePtr item = *itemRef;
  10800. if (item->nop == knopEllipsis)
  10801. {
  10802. itemRef = &item->AsParseNodeUni()->pnode1;
  10803. item = *itemRef;
  10804. if (!(item->nop == knopName
  10805. || item->nop == knopDot
  10806. || item->nop == knopIndex
  10807. || item->nop == knopArray
  10808. || item->nop == knopObject))
  10809. {
  10810. Error(ERRInvalidAssignmentTarget);
  10811. }
  10812. }
  10813. else if (item->nop == knopAsg)
  10814. {
  10815. itemRef = &item->AsParseNodeBin()->pnode1;
  10816. item = *itemRef;
  10817. }
  10818. if (item->nop == knopArray)
  10819. {
  10820. ConvertArrayToArrayPattern(item);
  10821. }
  10822. else if (item->nop == knopObject)
  10823. {
  10824. *itemRef = ConvertObjectToObjectPattern(item);
  10825. }
  10826. else if (item->nop == knopName)
  10827. {
  10828. TrackAssignment<true>(item, nullptr);
  10829. }
  10830. });
  10831. return pnode;
  10832. }
  10833. ParseNodeUni * Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)
  10834. {
  10835. charcount_t ichMin = this->GetScanner()->IchMinTok();
  10836. charcount_t ichLim = this->GetScanner()->IchLimTok();
  10837. ParseNodePtr pnodeMemberNodeList = nullptr;
  10838. if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)
  10839. {
  10840. ichMin = pnodeMemberList->ichMin;
  10841. ichLim = pnodeMemberList->ichLim;
  10842. pnodeMemberList = pnodeMemberList->AsParseNodeUni()->pnode1;
  10843. }
  10844. ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {
  10845. ParseNodePtr memberNode = ConvertMemberToMemberPattern(item);
  10846. AppendToList(&pnodeMemberNodeList, memberNode);
  10847. });
  10848. return CreateUniNode(knopObjectPattern, pnodeMemberNodeList, ichMin, ichLim);
  10849. }
  10850. ParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)
  10851. {
  10852. Assert(pnode != nullptr);
  10853. ParseNodePtr rightNode = nullptr;
  10854. OpCode op = pnode->nop;
  10855. if (op == knopObject)
  10856. {
  10857. rightNode = ConvertObjectToObjectPattern(pnode);
  10858. }
  10859. else if (op == knopArray)
  10860. {
  10861. rightNode = ConvertArrayToArrayPattern(pnode);
  10862. }
  10863. else
  10864. {
  10865. rightNode = pnode;
  10866. if (op == knopName)
  10867. {
  10868. TrackAssignment<true>(pnode, nullptr);
  10869. }
  10870. else if (op == knopAsg)
  10871. {
  10872. TrackAssignment<true>(pnode->AsParseNodeBin()->pnode1, nullptr);
  10873. }
  10874. }
  10875. return rightNode;
  10876. }
  10877. ParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)
  10878. {
  10879. if (pnodeMember->nop == knopObjectPatternMember)
  10880. {
  10881. return pnodeMember;
  10882. }
  10883. Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);
  10884. ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->AsParseNodeBin()->pnode2);
  10885. ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->AsParseNodeBin()->pnode1, rightNode);
  10886. resultNode->ichMin = pnodeMember->ichMin;
  10887. resultNode->ichLim = pnodeMember->ichLim;
  10888. return resultNode;
  10889. }
  10890. ParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)
  10891. {
  10892. if (pnode != nullptr)
  10893. {
  10894. if (pnode->nop == knopArray)
  10895. {
  10896. ConvertArrayToArrayPattern(pnode);
  10897. }
  10898. else if (pnode->nop == knopObject)
  10899. {
  10900. pnode = ConvertObjectToObjectPattern(pnode);
  10901. }
  10902. }
  10903. return pnode;
  10904. }
  10905. // This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.
  10906. void Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,
  10907. bool isDecl,
  10908. bool topLevel,
  10909. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  10910. bool allowIn /*= true*/)
  10911. {
  10912. // We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and
  10913. // AST related information before the validation parsing and later they will be restored.
  10914. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  10915. ParseNodeFnc * pnodeDeferredFncSave = m_currentNodeDeferredFunc;
  10916. if (m_currentNodeDeferredFunc == nullptr)
  10917. {
  10918. m_currentNodeDeferredFunc = m_currentNodeFunc;
  10919. }
  10920. int32 *pAstSizeSave = m_pCurrentAstSize;
  10921. uint *pNestedCountSave = m_pnestedCount;
  10922. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  10923. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  10924. ParseNodePtr newTempScope = nullptr;
  10925. m_ppnodeScope = &newTempScope;
  10926. int32 newTempAstSize = 0;
  10927. m_pCurrentAstSize = &newTempAstSize;
  10928. uint newTempNestedCount = 0;
  10929. m_pnestedCount = &newTempNestedCount;
  10930. m_ppnodeExprScope = nullptr;
  10931. charcount_t funcInArraySave = m_funcInArray;
  10932. uint funcInArrayDepthSave = m_funcInArrayDepth;
  10933. // we need to reset this as we are going to parse the grammar again.
  10934. m_hasDeferredShorthandInitError = false;
  10935. ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);
  10936. m_currentNodeFunc = pnodeFncSave;
  10937. m_currentNodeDeferredFunc = pnodeDeferredFncSave;
  10938. m_pCurrentAstSize = pAstSizeSave;
  10939. m_pnestedCount = pNestedCountSave;
  10940. m_ppnodeScope = ppnodeScopeSave;
  10941. m_ppnodeExprScope = ppnodeExprScopeSave;
  10942. m_funcInArray = funcInArraySave;
  10943. m_funcInArrayDepth = funcInArrayDepthSave;
  10944. }
  10945. template <bool buildAST>
  10946. ParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,
  10947. bool isDecl,
  10948. bool topLevel/* = true*/,
  10949. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  10950. bool allowIn/* = true*/,
  10951. BOOL *forInOfOkay/* = nullptr*/,
  10952. BOOL *nativeForOkay/* = nullptr*/)
  10953. {
  10954. ParseNodeUni * pnode = nullptr;
  10955. Assert(IsPossiblePatternStart());
  10956. if (m_token.tk == tkLCurly)
  10957. {
  10958. pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);
  10959. }
  10960. else
  10961. {
  10962. pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);
  10963. }
  10964. return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);
  10965. }
  10966. template <bool buildAST>
  10967. ParseNodePtr Parser::ParseDestructuredInitializer(ParseNodeUni * lhsNode,
  10968. bool isDecl,
  10969. bool topLevel,
  10970. DestructuringInitializerContext initializerContext,
  10971. bool allowIn,
  10972. BOOL *forInOfOkay,
  10973. BOOL *nativeForOkay)
  10974. {
  10975. this->GetScanner()->Scan();
  10976. if (topLevel && nativeForOkay == nullptr)
  10977. {
  10978. if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)
  10979. {
  10980. // e.g. var {x};
  10981. Error(ERRDestructInit);
  10982. }
  10983. else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)
  10984. {
  10985. // e.g. catch([x] = [0])
  10986. Error(ERRDestructNotInit);
  10987. }
  10988. }
  10989. if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)
  10990. {
  10991. if (topLevel && nativeForOkay != nullptr)
  10992. {
  10993. // Native loop should have destructuring initializer
  10994. *nativeForOkay = FALSE;
  10995. }
  10996. return lhsNode;
  10997. }
  10998. if (forInOfOkay)
  10999. {
  11000. *forInOfOkay = FALSE;
  11001. }
  11002. this->GetScanner()->Scan();
  11003. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11004. ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);
  11005. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11006. {
  11007. Error(ERRnoColon);
  11008. }
  11009. ParseNodeBin * pnodeDestructAsg = nullptr;
  11010. if (buildAST)
  11011. {
  11012. Assert(lhsNode != nullptr);
  11013. pnodeDestructAsg = CreateBinNode(knopAsg, lhsNode, pnodeDefault, lhsNode->ichMin, pnodeDefault->ichLim);
  11014. }
  11015. return pnodeDestructAsg;
  11016. }
  11017. template <bool buildAST>
  11018. ParseNodeUni * Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel/* = true*/)
  11019. {
  11020. Assert(m_token.tk == tkLCurly);
  11021. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11022. this->GetScanner()->Scan();
  11023. if (!isDecl)
  11024. {
  11025. declarationType = tkLCurly;
  11026. }
  11027. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr/*pNameHint*/, nullptr/*pHintLength*/, declarationType);
  11028. Assert(m_token.tk == tkRCurly);
  11029. ParseNodeUni * objectPatternNode = nullptr;
  11030. if (buildAST)
  11031. {
  11032. charcount_t ichLim = this->GetScanner()->IchLimTok();
  11033. objectPatternNode = CreateUniNode(knopObjectPattern, pnodeMemberList, ichMin, ichLim);
  11034. }
  11035. return objectPatternNode;
  11036. }
  11037. template <bool buildAST>
  11038. ParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel/* = true*/, bool allowEmptyExpression/* = true*/)
  11039. {
  11040. ParseNodePtr pnodeElem = nullptr;
  11041. int parenCount = 0;
  11042. bool seenRest = false;
  11043. // Save the Block ID prior to the increments, so we can restore it back.
  11044. int originalCurrentBlockId = GetCurrentBlock()->blockId;
  11045. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11046. if (!isDecl)
  11047. {
  11048. while (m_token.tk == tkLParen)
  11049. {
  11050. this->GetScanner()->Scan();
  11051. ++parenCount;
  11052. // Match the block increment we do upon entering parenthetical expressions
  11053. // so that the block ID's will match on reparsing of parameters.
  11054. GetCurrentBlock()->blockId = m_nextBlockId++;
  11055. }
  11056. }
  11057. if (m_token.tk == tkEllipsis)
  11058. {
  11059. // As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed
  11060. // But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.
  11061. seenRest = true;
  11062. this->GetScanner()->Scan();
  11063. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11064. if (!isDecl)
  11065. {
  11066. while (m_token.tk == tkLParen)
  11067. {
  11068. this->GetScanner()->Scan();
  11069. ++parenCount;
  11070. // Match the block increment we do upon entering parenthetical expressions
  11071. // so that the block ID's will match on reparsing of parameters.
  11072. GetCurrentBlock()->blockId = m_nextBlockId++;
  11073. }
  11074. }
  11075. if (m_token.tk != tkID && m_token.tk != tkTHIS && m_token.tk != tkSUPER && m_token.tk != tkLCurly && m_token.tk != tkLBrack)
  11076. {
  11077. if (isDecl)
  11078. {
  11079. Error(ERRnoIdent);
  11080. }
  11081. else
  11082. {
  11083. Error(ERRInvalidAssignmentTarget);
  11084. }
  11085. }
  11086. }
  11087. if (IsPossiblePatternStart())
  11088. {
  11089. // For the possible pattern start we do not allow the parens before
  11090. if (parenCount != 0)
  11091. {
  11092. Error(ERRDestructIDRef);
  11093. }
  11094. // Go recursively
  11095. pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false /*topLevel*/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);
  11096. if (!isDecl)
  11097. {
  11098. BOOL fCanAssign;
  11099. IdentToken token;
  11100. // Look for postfix operator
  11101. pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  11102. }
  11103. }
  11104. else if (m_token.tk == tkSUPER || m_token.tk == tkID || m_token.tk == tkTHIS)
  11105. {
  11106. if (isDecl)
  11107. {
  11108. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11109. pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin
  11110. ,/* fAllowIn */false, /* pfForInOk */nullptr, /* singleDefOnly */true, /* allowInit */!seenRest, false /*topLevelParse*/);
  11111. }
  11112. else
  11113. {
  11114. BOOL fCanAssign;
  11115. IdentToken token;
  11116. // We aren't declaring anything, so scan the ID reference manually.
  11117. pnodeElem = ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false,
  11118. FALSE, &fCanAssign);
  11119. // In this destructuring case we can force error here as we cannot assign.
  11120. if (!fCanAssign)
  11121. {
  11122. Error(ERRInvalidAssignmentTarget);
  11123. }
  11124. if (buildAST)
  11125. {
  11126. if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)
  11127. {
  11128. CheckStrictModeEvalArgumentsUsage(pnodeElem->AsParseNodeName()->pid);
  11129. }
  11130. }
  11131. else
  11132. {
  11133. if (IsStrictMode() && token.tk == tkID)
  11134. {
  11135. CheckStrictModeEvalArgumentsUsage(token.pid);
  11136. }
  11137. token.tk = tkNone;
  11138. }
  11139. }
  11140. }
  11141. else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))
  11142. {
  11143. if (m_token.IsOperator())
  11144. {
  11145. Error(ERRDestructNoOper);
  11146. }
  11147. Error(ERRDestructIDRef);
  11148. }
  11149. // Swallow RParens before a default expression, if any.
  11150. // 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.
  11151. if (!isDecl)
  11152. {
  11153. while (m_token.tk == tkRParen)
  11154. {
  11155. this->GetScanner()->Scan();
  11156. --parenCount;
  11157. }
  11158. // Restore the Block ID of the current block after the parsing of destructured variable declarations and initializers.
  11159. GetCurrentBlock()->blockId = originalCurrentBlockId;
  11160. }
  11161. if (parenCount != 0)
  11162. {
  11163. Error(ERRnoRparen);
  11164. }
  11165. if (hasSeenRest != nullptr)
  11166. {
  11167. *hasSeenRest = seenRest;
  11168. }
  11169. if (m_token.tk == tkAsg)
  11170. {
  11171. // Parse the initializer.
  11172. if (seenRest)
  11173. {
  11174. Error(ERRRestWithDefault);
  11175. }
  11176. this->GetScanner()->Scan();
  11177. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11178. ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);
  11179. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11180. {
  11181. Error(ERRnoColon);
  11182. }
  11183. if (buildAST)
  11184. {
  11185. pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);
  11186. }
  11187. }
  11188. if (buildAST && seenRest)
  11189. {
  11190. ParseNodePtr pnodeRest = CreateUniNode(knopEllipsis, pnodeElem);
  11191. pnodeElem = pnodeRest;
  11192. }
  11193. if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))
  11194. {
  11195. if (m_token.IsOperator())
  11196. {
  11197. Error(ERRDestructNoOper);
  11198. }
  11199. Error(ERRsyntax);
  11200. }
  11201. return pnodeElem;
  11202. }
  11203. template <bool buildAST>
  11204. ParseNodeUni * Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)
  11205. {
  11206. Assert(m_token.tk == tkLBrack);
  11207. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11208. this->GetScanner()->Scan();
  11209. ParseNodeArrLit * pnodeDestructArr = nullptr;
  11210. ParseNodePtr pnodeList = nullptr;
  11211. ParseNodePtr *lastNodeRef = nullptr;
  11212. uint count = 0;
  11213. bool hasMissingValues = false;
  11214. bool seenRest = false;
  11215. if (m_token.tk != tkRBrack)
  11216. {
  11217. while (true)
  11218. {
  11219. ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);
  11220. if (buildAST)
  11221. {
  11222. if (pnodeElem == nullptr && buildAST)
  11223. {
  11224. pnodeElem = CreateNodeForOpT<knopEmpty>();
  11225. hasMissingValues = true;
  11226. }
  11227. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);
  11228. }
  11229. count++;
  11230. if (m_token.tk == tkRBrack)
  11231. {
  11232. break;
  11233. }
  11234. if (m_token.tk != tkComma)
  11235. {
  11236. Error(ERRDestructNoOper);
  11237. }
  11238. if (seenRest) // Rest must be in the last position.
  11239. {
  11240. Error(ERRDestructRestLast);
  11241. }
  11242. this->GetScanner()->Scan();
  11243. // break if we have the trailing comma as well, eg. [a,]
  11244. if (m_token.tk == tkRBrack)
  11245. {
  11246. break;
  11247. }
  11248. }
  11249. }
  11250. if (buildAST)
  11251. {
  11252. pnodeDestructArr = CreateNodeForOpT<knopArrayPattern>(ichMin);
  11253. pnodeDestructArr->pnode1 = pnodeList;
  11254. pnodeDestructArr->arrayOfTaggedInts = false;
  11255. pnodeDestructArr->arrayOfInts = false;
  11256. pnodeDestructArr->arrayOfNumbers = false;
  11257. pnodeDestructArr->hasMissingValues = hasMissingValues;
  11258. pnodeDestructArr->count = count;
  11259. pnodeDestructArr->spreadCount = seenRest ? 1 : 0;
  11260. if (pnodeDestructArr->pnode1)
  11261. {
  11262. this->CheckArguments(pnodeDestructArr->pnode1);
  11263. }
  11264. }
  11265. return pnodeDestructArr;
  11266. }
  11267. void Parser::CaptureContext(ParseContext *parseContext) const
  11268. {
  11269. parseContext->pszSrc = this->GetScanner()->PchBase();
  11270. parseContext->length = this->m_originalLength;
  11271. parseContext->characterOffset = this->GetScanner()->IchMinTok();
  11272. parseContext->offset = parseContext->characterOffset + this->GetScanner()->m_cMultiUnits;
  11273. parseContext->grfscr = this->m_grfscr;
  11274. parseContext->lineNumber = this->GetScanner()->LineCur();
  11275. parseContext->pnodeProg = this->m_currentNodeProg;
  11276. parseContext->isUtf8 = this->GetScanner()->IsUtf8();
  11277. parseContext->strictMode = this->IsStrictMode();
  11278. parseContext->sourceContextInfo = this->m_sourceContextInfo;
  11279. parseContext->currentBlockInfo = this->m_currentBlockInfo;
  11280. parseContext->nextBlockId = this->m_nextBlockId;
  11281. }
  11282. void Parser::RestoreContext(ParseContext *const parseContext)
  11283. {
  11284. m_sourceContextInfo = parseContext->sourceContextInfo;
  11285. m_currentBlockInfo = parseContext->currentBlockInfo;
  11286. m_nextBlockId = parseContext->nextBlockId;
  11287. m_grfscr = parseContext->grfscr;
  11288. m_length = parseContext->length;
  11289. this->GetScanner()->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->isUtf8, parseContext->grfscr, parseContext->lineNumber);
  11290. m_currentNodeProg = parseContext->pnodeProg;
  11291. m_fUseStrictMode = parseContext->strictMode;
  11292. }
  11293. class ByteCodeGenerator;
  11294. #if DBG_DUMP
  11295. #define INDENT_SIZE 2
  11296. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt);
  11297. void PrintFormalsWIndent(ParseNode *pnode, int indentAmt);
  11298. void Indent(int indentAmt) {
  11299. for (int i = 0; i < indentAmt; i++) {
  11300. Output::Print(_u(" "));
  11301. }
  11302. }
  11303. void PrintBlockType(PnodeBlockType type)
  11304. {
  11305. switch (type)
  11306. {
  11307. case Global:
  11308. Output::Print(_u("(Global)"));
  11309. break;
  11310. case Function:
  11311. Output::Print(_u("(Function)"));
  11312. break;
  11313. case Regular:
  11314. Output::Print(_u("(Regular)"));
  11315. break;
  11316. case Parameter:
  11317. Output::Print(_u("(Parameter)"));
  11318. break;
  11319. default:
  11320. Output::Print(_u("(unknown blocktype)"));
  11321. break;
  11322. }
  11323. }
  11324. void PrintScopesWIndent(ParseNode *pnode, int indentAmt) {
  11325. ParseNode *scope = nullptr;
  11326. bool firstOnly = false;
  11327. switch (pnode->nop)
  11328. {
  11329. case knopProg:
  11330. case knopFncDecl: scope = pnode->AsParseNodeFnc()->pnodeScopes; break;
  11331. case knopBlock: scope = pnode->AsParseNodeBlock()->pnodeScopes; break;
  11332. case knopCatch: scope = pnode->AsParseNodeCatch()->pnodeScopes; break;
  11333. case knopWith: scope = pnode->AsParseNodeWith()->pnodeScopes; break;
  11334. case knopSwitch: scope = pnode->AsParseNodeSwitch()->pnodeBlock; firstOnly = true; break;
  11335. case knopFor: scope = pnode->AsParseNodeFor()->pnodeBlock; firstOnly = true; break;
  11336. case knopForIn: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11337. case knopForOf: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11338. }
  11339. if (scope) {
  11340. Output::Print(_u("[%4d, %4d): "), scope->ichMin, scope->ichLim);
  11341. Indent(indentAmt);
  11342. Output::Print(_u("Scopes: "));
  11343. ParseNode *next = nullptr;
  11344. ParseNode *syntheticBlock = nullptr;
  11345. while (scope) {
  11346. switch (scope->nop) {
  11347. case knopFncDecl: Output::Print(_u("knopFncDecl")); next = scope->AsParseNodeFnc()->pnodeNext; break;
  11348. case knopBlock: Output::Print(_u("knopBlock")); PrintBlockType(scope->AsParseNodeBlock()->blockType); next = scope->AsParseNodeBlock()->pnodeNext; break;
  11349. case knopCatch: Output::Print(_u("knopCatch")); next = scope->AsParseNodeCatch()->pnodeNext; break;
  11350. case knopWith: Output::Print(_u("knopWith")); next = scope->AsParseNodeWith()->pnodeNext; break;
  11351. default: Output::Print(_u("unknown")); break;
  11352. }
  11353. if (firstOnly) {
  11354. next = nullptr;
  11355. syntheticBlock = scope;
  11356. }
  11357. if (scope->grfpn & fpnSyntheticNode) {
  11358. Output::Print(_u(" synthetic"));
  11359. if (scope->nop == knopBlock)
  11360. syntheticBlock = scope;
  11361. }
  11362. Output::Print(_u(" (%d-%d)"), scope->ichMin, scope->ichLim);
  11363. if (next) Output::Print(_u(", "));
  11364. scope = next;
  11365. }
  11366. Output::Print(_u("\n"));
  11367. if (syntheticBlock || firstOnly) {
  11368. PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);
  11369. }
  11370. }
  11371. }
  11372. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt) {
  11373. if (pnode == NULL)
  11374. return;
  11375. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11376. switch (pnode->nop) {
  11377. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  11378. case knopName:
  11379. Indent(indentAmt);
  11380. if (pnode->AsParseNodeName()->pid != NULL) {
  11381. Output::Print(_u("id: %s\n"), pnode->AsParseNodeName()->pid->Psz());
  11382. }
  11383. else {
  11384. Output::Print(_u("name node\n"));
  11385. }
  11386. break;
  11387. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11388. case knopInt:
  11389. Indent(indentAmt);
  11390. Output::Print(_u("%d\n"), pnode->AsParseNodeInt()->lw);
  11391. break;
  11392. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  11393. case knopFlt:
  11394. Indent(indentAmt);
  11395. Output::Print(_u("%lf\n"), pnode->AsParseNodeFloat()->dbl);
  11396. break;
  11397. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  11398. case knopStr:
  11399. Indent(indentAmt);
  11400. Output::Print(_u("\"%s\"\n"), pnode->AsParseNodeStr()->pid->Psz());
  11401. break;
  11402. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  11403. case knopRegExp:
  11404. Indent(indentAmt);
  11405. Output::Print(_u("/%x/\n"), pnode->AsParseNodeRegExp()->regexPattern);
  11406. break;
  11407. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  11408. case knopNull:
  11409. Indent(indentAmt);
  11410. Output::Print(_u("null\n"));
  11411. break;
  11412. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  11413. case knopFalse:
  11414. Indent(indentAmt);
  11415. Output::Print(_u("false\n"));
  11416. break;
  11417. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  11418. case knopTrue:
  11419. Indent(indentAmt);
  11420. Output::Print(_u("true\n"));
  11421. break;
  11422. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  11423. case knopEmpty:
  11424. Indent(indentAmt);
  11425. Output::Print(_u("empty\n"));
  11426. break;
  11427. // Unary operators.
  11428. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  11429. case knopNot:
  11430. Indent(indentAmt);
  11431. Output::Print(_u("~\n"));
  11432. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11433. break;
  11434. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  11435. case knopNeg:
  11436. Indent(indentAmt);
  11437. Output::Print(_u("U-\n"));
  11438. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11439. break;
  11440. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  11441. case knopPos:
  11442. Indent(indentAmt);
  11443. Output::Print(_u("U+\n"));
  11444. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11445. break;
  11446. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  11447. case knopLogNot:
  11448. Indent(indentAmt);
  11449. Output::Print(_u("!\n"));
  11450. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11451. break;
  11452. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  11453. case knopEllipsis:
  11454. Indent(indentAmt);
  11455. Output::Print(_u("...<expr>\n"));
  11456. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11457. break;
  11458. //PTNODE(knopIncPost , "++ post" ,Inc ,Uni ,fnopUni|fnopAsg)
  11459. case knopIncPost:
  11460. Indent(indentAmt);
  11461. Output::Print(_u("<expr>++\n"));
  11462. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11463. break;
  11464. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  11465. case knopDecPost:
  11466. Indent(indentAmt);
  11467. Output::Print(_u("<expr>--\n"));
  11468. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11469. break;
  11470. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  11471. case knopIncPre:
  11472. Indent(indentAmt);
  11473. Output::Print(_u("++<expr>\n"));
  11474. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11475. break;
  11476. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  11477. case knopDecPre:
  11478. Indent(indentAmt);
  11479. Output::Print(_u("--<expr>\n"));
  11480. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11481. break;
  11482. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  11483. case knopTypeof:
  11484. Indent(indentAmt);
  11485. Output::Print(_u("typeof\n"));
  11486. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11487. break;
  11488. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  11489. case knopVoid:
  11490. Indent(indentAmt);
  11491. Output::Print(_u("void\n"));
  11492. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11493. break;
  11494. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  11495. case knopDelete:
  11496. Indent(indentAmt);
  11497. Output::Print(_u("delete\n"));
  11498. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11499. break;
  11500. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  11501. case knopArrayPattern:
  11502. Indent(indentAmt);
  11503. Output::Print(_u("Array Pattern\n"));
  11504. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11505. break;
  11506. case knopObjectPattern:
  11507. Indent(indentAmt);
  11508. Output::Print(_u("Object Pattern\n"));
  11509. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11510. break;
  11511. case knopArray:
  11512. Indent(indentAmt);
  11513. Output::Print(_u("Array Literal\n"));
  11514. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11515. break;
  11516. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  11517. case knopObject:
  11518. Indent(indentAmt);
  11519. Output::Print(_u("Object Literal\n"));
  11520. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11521. break;
  11522. // Binary and Ternary Operators
  11523. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  11524. case knopAdd:
  11525. Indent(indentAmt);
  11526. Output::Print(_u("+\n"));
  11527. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11528. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11529. break;
  11530. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  11531. case knopSub:
  11532. Indent(indentAmt);
  11533. Output::Print(_u("-\n"));
  11534. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11535. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11536. break;
  11537. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  11538. case knopMul:
  11539. Indent(indentAmt);
  11540. Output::Print(_u("*\n"));
  11541. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11542. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11543. break;
  11544. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  11545. case knopExpo:
  11546. Indent(indentAmt);
  11547. Output::Print(_u("**\n"));
  11548. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11549. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11550. break;
  11551. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  11552. case knopDiv:
  11553. Indent(indentAmt);
  11554. Output::Print(_u("/\n"));
  11555. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11556. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11557. break;
  11558. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  11559. case knopMod:
  11560. Indent(indentAmt);
  11561. Output::Print(_u("%%\n"));
  11562. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11563. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11564. break;
  11565. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  11566. case knopOr:
  11567. Indent(indentAmt);
  11568. Output::Print(_u("|\n"));
  11569. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11570. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11571. break;
  11572. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  11573. case knopXor:
  11574. Indent(indentAmt);
  11575. Output::Print(_u("^\n"));
  11576. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11577. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11578. break;
  11579. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  11580. case knopAnd:
  11581. Indent(indentAmt);
  11582. Output::Print(_u("&\n"));
  11583. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11584. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11585. break;
  11586. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  11587. case knopEq:
  11588. Indent(indentAmt);
  11589. Output::Print(_u("==\n"));
  11590. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11591. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11592. break;
  11593. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  11594. case knopNe:
  11595. Indent(indentAmt);
  11596. Output::Print(_u("!=\n"));
  11597. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11598. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11599. break;
  11600. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  11601. case knopLt:
  11602. Indent(indentAmt);
  11603. Output::Print(_u("<\n"));
  11604. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11605. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11606. break;
  11607. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  11608. case knopLe:
  11609. Indent(indentAmt);
  11610. Output::Print(_u("<=\n"));
  11611. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11612. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11613. break;
  11614. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  11615. case knopGe:
  11616. Indent(indentAmt);
  11617. Output::Print(_u(">=\n"));
  11618. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11619. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11620. break;
  11621. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  11622. case knopGt:
  11623. Indent(indentAmt);
  11624. Output::Print(_u(">\n"));
  11625. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11626. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11627. break;
  11628. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  11629. case knopCall:
  11630. Indent(indentAmt);
  11631. Output::Print(_u("Call\n"));
  11632. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11633. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11634. break;
  11635. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  11636. case knopDot:
  11637. Indent(indentAmt);
  11638. Output::Print(_u(".\n"));
  11639. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11640. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11641. break;
  11642. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  11643. case knopAsg:
  11644. Indent(indentAmt);
  11645. Output::Print(_u("=\n"));
  11646. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11647. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11648. break;
  11649. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  11650. case knopInstOf:
  11651. Indent(indentAmt);
  11652. Output::Print(_u("instanceof\n"));
  11653. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11654. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11655. break;
  11656. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  11657. case knopIn:
  11658. Indent(indentAmt);
  11659. Output::Print(_u("in\n"));
  11660. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11661. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11662. break;
  11663. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  11664. case knopEqv:
  11665. Indent(indentAmt);
  11666. Output::Print(_u("===\n"));
  11667. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11668. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11669. break;
  11670. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  11671. case knopNEqv:
  11672. Indent(indentAmt);
  11673. Output::Print(_u("!==\n"));
  11674. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11675. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11676. break;
  11677. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  11678. case knopComma:
  11679. Indent(indentAmt);
  11680. Output::Print(_u(",\n"));
  11681. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11682. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11683. break;
  11684. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  11685. case knopLogOr:
  11686. Indent(indentAmt);
  11687. Output::Print(_u("||\n"));
  11688. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11689. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11690. break;
  11691. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  11692. case knopLogAnd:
  11693. Indent(indentAmt);
  11694. Output::Print(_u("&&\n"));
  11695. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11696. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11697. break;
  11698. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  11699. case knopLsh:
  11700. Indent(indentAmt);
  11701. Output::Print(_u("<<\n"));
  11702. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11703. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11704. break;
  11705. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  11706. case knopRsh:
  11707. Indent(indentAmt);
  11708. Output::Print(_u(">>\n"));
  11709. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11710. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11711. break;
  11712. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  11713. case knopRs2:
  11714. Indent(indentAmt);
  11715. Output::Print(_u(">>>\n"));
  11716. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11717. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11718. break;
  11719. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  11720. case knopNew:
  11721. Indent(indentAmt);
  11722. Output::Print(_u("new\n"));
  11723. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11724. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11725. break;
  11726. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  11727. case knopIndex:
  11728. Indent(indentAmt);
  11729. Output::Print(_u("[]\n"));
  11730. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11731. PrintPnodeListWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11732. break;
  11733. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  11734. case knopQmark:
  11735. Indent(indentAmt);
  11736. Output::Print(_u("?:\n"));
  11737. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode1, indentAmt + INDENT_SIZE);
  11738. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode2, indentAmt + INDENT_SIZE);
  11739. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode3, indentAmt + INDENT_SIZE);
  11740. break;
  11741. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  11742. case knopAsgAdd:
  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(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  11749. case knopAsgSub:
  11750. Indent(indentAmt);
  11751. Output::Print(_u("-=\n"));
  11752. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11753. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11754. break;
  11755. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  11756. case knopAsgMul:
  11757. Indent(indentAmt);
  11758. Output::Print(_u("*=\n"));
  11759. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11760. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11761. break;
  11762. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  11763. case knopAsgExpo:
  11764. Indent(indentAmt);
  11765. Output::Print(_u("**=\n"));
  11766. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11767. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11768. break;
  11769. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  11770. case knopAsgDiv:
  11771. Indent(indentAmt);
  11772. Output::Print(_u("/=\n"));
  11773. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11774. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11775. break;
  11776. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  11777. case knopAsgMod:
  11778. Indent(indentAmt);
  11779. Output::Print(_u("%=\n"));
  11780. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11781. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11782. break;
  11783. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  11784. case knopAsgAnd:
  11785. Indent(indentAmt);
  11786. Output::Print(_u("&=\n"));
  11787. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11788. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11789. break;
  11790. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  11791. case knopAsgXor:
  11792. Indent(indentAmt);
  11793. Output::Print(_u("^=\n"));
  11794. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11795. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11796. break;
  11797. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  11798. case knopAsgOr:
  11799. Indent(indentAmt);
  11800. Output::Print(_u("|=\n"));
  11801. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11802. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11803. break;
  11804. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  11805. case knopAsgLsh:
  11806. Indent(indentAmt);
  11807. Output::Print(_u("<<=\n"));
  11808. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11809. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11810. break;
  11811. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  11812. case knopAsgRsh:
  11813. Indent(indentAmt);
  11814. Output::Print(_u(">>=\n"));
  11815. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11816. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11817. break;
  11818. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  11819. case knopAsgRs2:
  11820. Indent(indentAmt);
  11821. Output::Print(_u(">>>=\n"));
  11822. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11823. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11824. break;
  11825. case knopComputedName:
  11826. Indent(indentAmt);
  11827. Output::Print(_u("ComputedProperty\n"));
  11828. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11829. break;
  11830. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  11831. case knopMember:
  11832. case knopMemberShort:
  11833. case knopObjectPatternMember:
  11834. Indent(indentAmt);
  11835. Output::Print(_u(":\n"));
  11836. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11837. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11838. break;
  11839. // General nodes.
  11840. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  11841. case knopList:
  11842. Indent(indentAmt);
  11843. Output::Print(_u("List\n"));
  11844. PrintPnodeListWIndent(pnode, indentAmt + INDENT_SIZE);
  11845. break;
  11846. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  11847. case knopVarDecl:
  11848. Indent(indentAmt);
  11849. Output::Print(_u("var %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11850. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11851. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11852. break;
  11853. case knopConstDecl:
  11854. Indent(indentAmt);
  11855. Output::Print(_u("const %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11856. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11857. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11858. break;
  11859. case knopLetDecl:
  11860. Indent(indentAmt);
  11861. Output::Print(_u("let %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11862. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11863. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11864. break;
  11865. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  11866. case knopFncDecl:
  11867. Indent(indentAmt);
  11868. if (pnode->AsParseNodeFnc()->pid != NULL)
  11869. {
  11870. Output::Print(_u("fn decl %d nested %d name %s (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(),
  11871. pnode->AsParseNodeFnc()->pid->Psz(), pnode->ichMin, pnode->ichLim);
  11872. }
  11873. else
  11874. {
  11875. Output::Print(_u("fn decl %d nested %d anonymous (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(), pnode->ichMin, pnode->ichLim);
  11876. }
  11877. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11878. PrintFormalsWIndent(pnode->AsParseNodeFnc()->pnodeParams, indentAmt + INDENT_SIZE);
  11879. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeRest, indentAmt + INDENT_SIZE);
  11880. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  11881. if (pnode->AsParseNodeFnc()->pnodeBody == nullptr)
  11882. {
  11883. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11884. Indent(indentAmt + INDENT_SIZE);
  11885. Output::Print(_u("<parse deferred body>\n"));
  11886. }
  11887. break;
  11888. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  11889. case knopProg:
  11890. Indent(indentAmt);
  11891. Output::Print(_u("program\n"));
  11892. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11893. PrintPnodeListWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  11894. break;
  11895. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  11896. case knopEndCode:
  11897. Indent(indentAmt);
  11898. Output::Print(_u("<endcode>\n"));
  11899. break;
  11900. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  11901. case knopDebugger:
  11902. Indent(indentAmt);
  11903. Output::Print(_u("<debugger>\n"));
  11904. break;
  11905. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  11906. case knopFor:
  11907. Indent(indentAmt);
  11908. Output::Print(_u("for\n"));
  11909. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11910. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeInit, indentAmt + INDENT_SIZE);
  11911. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeCond, indentAmt + INDENT_SIZE);
  11912. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeIncr, indentAmt + INDENT_SIZE);
  11913. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeBody, indentAmt + INDENT_SIZE);
  11914. break;
  11915. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  11916. case knopIf:
  11917. Indent(indentAmt);
  11918. Output::Print(_u("if\n"));
  11919. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeCond, indentAmt + INDENT_SIZE);
  11920. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeTrue, indentAmt + INDENT_SIZE);
  11921. if (pnode->AsParseNodeIf()->pnodeFalse != NULL)
  11922. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeFalse, indentAmt + INDENT_SIZE);
  11923. break;
  11924. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  11925. case knopWhile:
  11926. Indent(indentAmt);
  11927. Output::Print(_u("while\n"));
  11928. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  11929. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  11930. break;
  11931. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  11932. case knopDoWhile:
  11933. Indent(indentAmt);
  11934. Output::Print(_u("do\n"));
  11935. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  11936. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  11937. break;
  11938. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  11939. case knopForIn:
  11940. Indent(indentAmt);
  11941. Output::Print(_u("forIn\n"));
  11942. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11943. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  11944. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  11945. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  11946. break;
  11947. case knopForOf:
  11948. Indent(indentAmt);
  11949. Output::Print(_u("forOf\n"));
  11950. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11951. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  11952. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  11953. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  11954. break;
  11955. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  11956. case knopReturn:
  11957. Indent(indentAmt);
  11958. Output::Print(_u("return\n"));
  11959. if (pnode->AsParseNodeReturn()->pnodeExpr != NULL)
  11960. PrintPnodeWIndent(pnode->AsParseNodeReturn()->pnodeExpr, indentAmt + INDENT_SIZE);
  11961. break;
  11962. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  11963. case knopBlock:
  11964. Indent(indentAmt);
  11965. Output::Print(_u("block "));
  11966. if (pnode->grfpn & fpnSyntheticNode)
  11967. Output::Print(_u("synthetic "));
  11968. PrintBlockType(pnode->AsParseNodeBlock()->blockType);
  11969. Output::Print(_u("(%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  11970. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11971. if (pnode->AsParseNodeBlock()->pnodeStmt != NULL)
  11972. PrintPnodeWIndent(pnode->AsParseNodeBlock()->pnodeStmt, indentAmt + INDENT_SIZE);
  11973. break;
  11974. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  11975. case knopWith:
  11976. Indent(indentAmt);
  11977. Output::Print(_u("with (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  11978. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11979. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeObj, indentAmt + INDENT_SIZE);
  11980. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeBody, indentAmt + INDENT_SIZE);
  11981. break;
  11982. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  11983. case knopBreak:
  11984. Indent(indentAmt);
  11985. Output::Print(_u("break\n"));
  11986. // TODO: some representation of target
  11987. break;
  11988. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  11989. case knopContinue:
  11990. Indent(indentAmt);
  11991. Output::Print(_u("continue\n"));
  11992. // TODO: some representation of target
  11993. break;
  11994. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  11995. case knopSwitch:
  11996. Indent(indentAmt);
  11997. Output::Print(_u("switch\n"));
  11998. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11999. for (ParseNodeCase *pnodeT = pnode->AsParseNodeSwitch()->pnodeCases; NULL != pnodeT; pnodeT = pnodeT->pnodeNext) {
  12000. PrintPnodeWIndent(pnodeT, indentAmt + 2);
  12001. }
  12002. break;
  12003. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  12004. case knopCase:
  12005. Indent(indentAmt);
  12006. Output::Print(_u("case\n"));
  12007. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeExpr, indentAmt + INDENT_SIZE);
  12008. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeBody, indentAmt + INDENT_SIZE);
  12009. break;
  12010. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  12011. case knopTryFinally:
  12012. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeTry, indentAmt);
  12013. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeFinally, indentAmt);
  12014. break;
  12015. case knopFinally:
  12016. Indent(indentAmt);
  12017. Output::Print(_u("finally\n"));
  12018. PrintPnodeWIndent(pnode->AsParseNodeFinally()->pnodeBody, indentAmt + INDENT_SIZE);
  12019. break;
  12020. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  12021. case knopCatch:
  12022. Indent(indentAmt);
  12023. Output::Print(_u("catch (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12024. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12025. PrintPnodeWIndent(pnode->AsParseNodeCatch()->GetParam(), indentAmt + INDENT_SIZE);
  12026. // if (pnode->AsParseNodeCatch()->pnodeGuard!=NULL)
  12027. // PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeGuard,indentAmt+INDENT_SIZE);
  12028. PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeBody, indentAmt + INDENT_SIZE);
  12029. break;
  12030. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  12031. case knopTryCatch:
  12032. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeTry, indentAmt);
  12033. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeCatch, indentAmt);
  12034. break;
  12035. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  12036. case knopTry:
  12037. Indent(indentAmt);
  12038. Output::Print(_u("try\n"));
  12039. PrintPnodeWIndent(pnode->AsParseNodeTry()->pnodeBody, indentAmt + INDENT_SIZE);
  12040. break;
  12041. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  12042. case knopThrow:
  12043. Indent(indentAmt);
  12044. Output::Print(_u("throw\n"));
  12045. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12046. break;
  12047. //PTNODE(knopClassDecl, "classDecl", None , Class, fnopLeaf)
  12048. case knopClassDecl:
  12049. Indent(indentAmt);
  12050. Output::Print(_u("class %s"), pnode->AsParseNodeClass()->pnodeName->pid->Psz());
  12051. if (pnode->AsParseNodeClass()->pnodeExtends != nullptr)
  12052. {
  12053. Output::Print(_u(" extends "));
  12054. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeExtends, 0);
  12055. }
  12056. else {
  12057. Output::Print(_u("\n"));
  12058. }
  12059. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeConstructor, indentAmt + INDENT_SIZE);
  12060. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeMembers, indentAmt + INDENT_SIZE);
  12061. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeStaticMembers, indentAmt + INDENT_SIZE);
  12062. break;
  12063. case knopStrTemplate:
  12064. Indent(indentAmt);
  12065. Output::Print(_u("string template\n"));
  12066. PrintPnodeListWIndent(pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);
  12067. break;
  12068. case knopYieldStar:
  12069. Indent(indentAmt);
  12070. Output::Print(_u("yield*\n"));
  12071. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12072. break;
  12073. case knopYield:
  12074. case knopYieldLeaf:
  12075. Indent(indentAmt);
  12076. Output::Print(_u("yield\n"));
  12077. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12078. break;
  12079. case knopAwait:
  12080. Indent(indentAmt);
  12081. Output::Print(_u("await\n"));
  12082. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12083. break;
  12084. case knopExportDefault:
  12085. Indent(indentAmt);
  12086. Output::Print(_u("export default\n"));
  12087. PrintPnodeListWIndent(pnode->AsParseNodeExportDefault()->pnodeExpr, indentAmt + INDENT_SIZE);
  12088. break;
  12089. default:
  12090. Output::Print(_u("unhandled pnode op %d\n"), pnode->nop);
  12091. break;
  12092. }
  12093. }
  12094. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt) {
  12095. if (pnode != NULL) {
  12096. while (pnode->nop == knopList) {
  12097. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt);
  12098. pnode = pnode->AsParseNodeBin()->pnode2;
  12099. }
  12100. PrintPnodeWIndent(pnode, indentAmt);
  12101. }
  12102. }
  12103. void PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)
  12104. {
  12105. for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())
  12106. {
  12107. PrintPnodeWIndent(pnode->nop == knopParamPattern ? pnode->AsParseNodeParamPattern()->pnode1 : pnode, indentAmt);
  12108. }
  12109. }
  12110. void PrintPnode(ParseNode *pnode) {
  12111. PrintPnodeWIndent(pnode, 0);
  12112. }
  12113. void ParseNode::Dump()
  12114. {
  12115. switch (nop)
  12116. {
  12117. case knopFncDecl:
  12118. case knopProg:
  12119. LPCOLESTR name = Js::Constants::AnonymousFunction;
  12120. if (this->AsParseNodeFnc()->pnodeName)
  12121. {
  12122. Assert(this->AsParseNodeFnc()->pnodeName->nop == knopVarDecl);
  12123. name = this->AsParseNodeFnc()->pnodeName->pid->Psz();
  12124. }
  12125. Output::Print(_u("%s (%d) [%d, %d]:\n"), name, this->AsParseNodeFnc()->functionId, this->AsParseNodeFnc()->lineNumber, this->AsParseNodeFnc()->columnNumber);
  12126. Output::Print(_u("hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasOnlyThis:%s \n"),
  12127. IsTrueOrFalse(this->AsParseNodeFnc()->HasHeapArguments()),
  12128. IsTrueOrFalse(this->AsParseNodeFnc()->CallsEval()),
  12129. IsTrueOrFalse(this->AsParseNodeFnc()->ChildCallsEval()),
  12130. IsTrueOrFalse(this->AsParseNodeFnc()->HasReferenceableBuiltInArguments()),
  12131. IsTrueOrFalse(this->AsParseNodeFnc()->GetArgumentsObjectEscapes()),
  12132. IsTrueOrFalse(this->AsParseNodeFnc()->HasWithStmt()),
  12133. IsTrueOrFalse(this->AsParseNodeFnc()->HasOnlyThisStmts()));
  12134. if (this->AsParseNodeFnc()->funcInfo)
  12135. {
  12136. this->AsParseNodeFnc()->funcInfo->Dump();
  12137. }
  12138. break;
  12139. }
  12140. }
  12141. void DumpCapturedNames(ParseNodeFnc* pnodeFnc, IdentPtrSet* capturedNames, ArenaAllocator* alloc)
  12142. {
  12143. auto sortedNames = JsUtil::List<IdentPtr, ArenaAllocator>::New(alloc);
  12144. capturedNames->Map([=](const IdentPtr& pid) -> void {
  12145. sortedNames->Add(pid);
  12146. });
  12147. sortedNames->Sort([](void* context, const void* left, const void* right) -> int {
  12148. const IdentPtr leftIdentPtr = *(const IdentPtr*)(left);
  12149. const IdentPtr rightIdentPtr = *(const IdentPtr*)(right);
  12150. return ::wcscmp(leftIdentPtr->Psz(), rightIdentPtr->Psz());
  12151. }, nullptr);
  12152. sortedNames->Map([=](int index, const IdentPtr pid) -> void {
  12153. OUTPUT_TRACE_DEBUGONLY(Js::CreateParserStatePhase, _u(" Function %u captured name \"%s\"\n"), pnodeFnc->functionId, pid->Psz());
  12154. });
  12155. }
  12156. #endif
  12157. void Parser::AddNestedCapturedNames(ParseNodeFnc* pnodeChildFnc)
  12158. {
  12159. if (m_currentNodeFunc && this->IsCreatingStateCache() && pnodeChildFnc->HasAnyCapturedNames())
  12160. {
  12161. IdentPtrSet* parentCapturedNames = GetCurrentFunctionNode()->EnsureCapturedNames(&m_nodeAllocator);
  12162. IdentPtrSet* childCaptureNames = pnodeChildFnc->GetCapturedNames();
  12163. auto iter = childCaptureNames->GetIterator();
  12164. while (iter.IsValid())
  12165. {
  12166. parentCapturedNames->AddNew(iter.CurrentValue());
  12167. iter.MoveNext();
  12168. }
  12169. }
  12170. }
  12171. void Parser::ProcessCapturedNames(ParseNodeFnc* pnodeFnc)
  12172. {
  12173. if (this->IsCreatingStateCache() && pnodeFnc->HasAnyCapturedNames())
  12174. {
  12175. IdentPtrSet* capturedNames = pnodeFnc->GetCapturedNames();
  12176. auto iter = capturedNames->GetIteratorWithRemovalSupport();
  12177. while (iter.IsValid())
  12178. {
  12179. const IdentPtr& pid = iter.CurrentValueReference();
  12180. PidRefStack* ref = pid->GetTopRef();
  12181. // If the pid has no refs left in our function's scope after binding, we didn't capture it.
  12182. if (!ref || ref->GetFuncScopeId() < pnodeFnc->functionId)
  12183. {
  12184. iter.RemoveCurrent();
  12185. }
  12186. iter.MoveNext();
  12187. }
  12188. #if DBG_DUMP
  12189. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::CreateParserStatePhase))
  12190. {
  12191. DumpCapturedNames(pnodeFnc, capturedNames, &this->m_nodeAllocator);
  12192. fflush(stdout);
  12193. }
  12194. #endif
  12195. }
  12196. }
  12197. void Parser::ReleaseTemporaryGuestArena()
  12198. {
  12199. // In case of modules the Parser lives longer than the temporary Guest Arena. We may have already released the arena explicitly.
  12200. if (!m_tempGuestArenaReleased)
  12201. {
  12202. // The regex patterns list has references to the temporary Guest Arena. Reset it first.
  12203. m_registeredRegexPatterns.Reset();
  12204. if (this->m_scriptContext != nullptr)
  12205. {
  12206. this->m_scriptContext->ReleaseTemporaryGuestAllocator(m_tempGuestArena);
  12207. m_tempGuestArena.Unroot();
  12208. }
  12209. m_tempGuestArenaReleased = true;
  12210. }
  12211. }
  12212. bool Parser::IsCreatingStateCache()
  12213. {
  12214. return (((this->m_grfscr & fscrCreateParserState) == fscrCreateParserState)
  12215. && this->m_functionBody == nullptr
  12216. && CONFIG_FLAG(ParserStateCache));
  12217. }
  12218. DeferredFunctionStub * Parser::BuildDeferredStubTree(ParseNodeFnc *pnodeFnc, Recycler *recycler)
  12219. {
  12220. Assert(CONFIG_FLAG(ParserStateCache));
  12221. uint nestedCount = pnodeFnc->nestedCount;
  12222. if (nestedCount == 0)
  12223. {
  12224. return nullptr;
  12225. }
  12226. if (pnodeFnc->deferredStub)
  12227. {
  12228. return pnodeFnc->deferredStub;
  12229. }
  12230. DeferredFunctionStub* deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);
  12231. uint i = 0;
  12232. ParseNodeBlock* pnodeBlock = pnodeFnc->pnodeBodyScope;
  12233. ParseNodePtr pnodeChild = nullptr;
  12234. if (pnodeFnc->nop == knopProg)
  12235. {
  12236. Assert(pnodeFnc->pnodeBodyScope == nullptr
  12237. && pnodeFnc->pnodeScopes != nullptr
  12238. && pnodeFnc->pnodeScopes->blockType == PnodeBlockType::Global);
  12239. pnodeBlock = pnodeFnc->pnodeScopes;
  12240. pnodeChild = pnodeFnc->pnodeScopes->pnodeScopes;
  12241. }
  12242. else
  12243. {
  12244. Assert(pnodeBlock != nullptr
  12245. && (pnodeBlock->blockType == PnodeBlockType::Function
  12246. || pnodeBlock->blockType == PnodeBlockType::Parameter));
  12247. pnodeChild = pnodeBlock->pnodeScopes;
  12248. }
  12249. while (pnodeChild != nullptr)
  12250. {
  12251. if (pnodeChild->nop != knopFncDecl)
  12252. {
  12253. // We only expect to find a function body block in a parameter scope block.
  12254. Assert(pnodeChild->nop == knopBlock
  12255. && (pnodeBlock->blockType == PnodeBlockType::Parameter
  12256. || pnodeChild->AsParseNodeBlock()->blockType == PnodeBlockType::Function));
  12257. pnodeChild = pnodeChild->AsParseNodeBlock()->pnodeNext;
  12258. continue;
  12259. }
  12260. ParseNodeFnc* pnodeFncChild = pnodeChild->AsParseNodeFnc();
  12261. AnalysisAssertOrFailFast(i < nestedCount);
  12262. if (pnodeFncChild->pnodeBody != nullptr)
  12263. {
  12264. // Anomalous case of a non-deferred function nested within a deferred one.
  12265. // Work around by discarding the stub tree.
  12266. return nullptr;
  12267. }
  12268. if (pnodeFncChild->IsGeneratedDefault())
  12269. {
  12270. ++i;
  12271. pnodeChild = pnodeFncChild->pnodeNext;
  12272. continue;
  12273. }
  12274. deferredStubs[i].fncFlags = pnodeFncChild->fncFlags;
  12275. deferredStubs[i].nestedCount = pnodeFncChild->nestedCount;
  12276. deferredStubs[i].restorePoint = *pnodeFncChild->pRestorePoint;
  12277. deferredStubs[i].deferredStubs = BuildDeferredStubTree(pnodeFncChild, recycler);
  12278. deferredStubs[i].ichMin = pnodeChild->ichMin;
  12279. // Save the set of captured names onto the deferred stub.
  12280. // Since this set is allocated in the Parser arena, we'll have to convert these
  12281. // into indices in a string table which will survive when the parser goes away.
  12282. deferredStubs[i].capturedNamePointers = pnodeFncChild->GetCapturedNames();
  12283. ++i;
  12284. pnodeChild = pnodeFncChild->pnodeNext;
  12285. }
  12286. pnodeFnc->deferredStub = deferredStubs;
  12287. return deferredStubs;
  12288. }