Parse.cpp 482 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "ParserPch.h"
  6. #include "FormalsUtil.h"
  7. #include "../Runtime/Language/SourceDynamicProfileManager.h"
  8. #include "ByteCode/ByteCodeSerializer.h"
  9. #if DBG_DUMP
  10. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt);
  11. #endif
  12. const char* const nopNames[knopLim] = {
  13. #define PTNODE(nop,sn,pc,nk,grfnop,json) sn,
  14. #include "ptlist.h"
  15. };
  16. void printNop(int nop) {
  17. Output::Print(_u("%S\n"), nopNames[nop]);
  18. }
  19. const uint ParseNode::mpnopgrfnop[knopLim] =
  20. {
  21. #define PTNODE(nop,sn,pc,nk,grfnop,json) grfnop,
  22. #include "ptlist.h"
  23. };
  24. bool Parser::IsES6DestructuringEnabled() const
  25. {
  26. return m_scriptContext->GetConfig()->IsES6DestructuringEnabled();
  27. }
  28. struct StmtNest
  29. {
  30. union
  31. {
  32. struct
  33. {
  34. ParseNodeStmt * pnodeStmt; // This statement node.
  35. };
  36. struct
  37. {
  38. bool isDeferred : 1;
  39. OpCode op; // This statement operation.
  40. };
  41. };
  42. LabelId* pLabelId; // Labels for this statement.
  43. StmtNest *pstmtOuter; // Enclosing statement.
  44. OpCode GetNop() const
  45. {
  46. AnalysisAssert(isDeferred || pnodeStmt != nullptr);
  47. return isDeferred ? op : pnodeStmt->nop;
  48. }
  49. };
  50. struct BlockInfoStack
  51. {
  52. StmtNest pstmt;
  53. ParseNodeBlock *pnodeBlock;
  54. ParseNodePtr *m_ppnodeLex; // lexical variable list tail
  55. BlockInfoStack *pBlockInfoOuter; // containing block's BlockInfoStack
  56. BlockInfoStack *pBlockInfoFunction; // nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)
  57. };
  58. #if DEBUG
  59. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)
  60. #else
  61. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)
  62. #endif
  63. : m_nodeAllocator(_u("Parser"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),
  64. m_cactIdentToNodeLookup(0),
  65. m_grfscr(fscrNil),
  66. m_length(0),
  67. m_originalLength(0),
  68. m_nextFunctionId(nullptr),
  69. m_sourceContextInfo(nullptr),
  70. #if ENABLE_BACKGROUND_PARSING
  71. m_isInBackground(isBackground),
  72. m_hasParallelJob(false),
  73. m_doingFastScan(false),
  74. #endif
  75. m_nextBlockId(0),
  76. m_tempGuestArena(scriptContext->GetTemporaryGuestAllocator(_u("ParserRegex")), scriptContext->GetRecycler()),
  77. // use the GuestArena directly for keeping the RegexPattern* alive during byte code generation
  78. m_registeredRegexPatterns(m_tempGuestArena->GetAllocator()),
  79. m_scriptContext(scriptContext),
  80. m_token(), // should initialize to 0/nullptrs
  81. m_scan(this, &m_token, scriptContext),
  82. m_currentNodeNonLambdaFunc(nullptr),
  83. m_currentNodeNonLambdaDeferredFunc(nullptr),
  84. m_currentNodeFunc(nullptr),
  85. m_currentNodeDeferredFunc(nullptr),
  86. m_currentNodeProg(nullptr),
  87. m_currDeferredStub(nullptr),
  88. m_currDeferredStubCount(0),
  89. m_pCurrentAstSize(nullptr),
  90. m_ppnodeScope(nullptr),
  91. m_ppnodeExprScope(nullptr),
  92. m_ppnodeVar(nullptr),
  93. m_inDeferredNestedFunc(false),
  94. m_reparsingLambdaParams(false),
  95. m_disallowImportExportStmt(false),
  96. m_isInParsingArgList(false),
  97. m_hasDestructuringPattern(false),
  98. m_hasDeferredShorthandInitError(false),
  99. m_pnestedCount(nullptr),
  100. wellKnownPropertyPids(), // should initialize to nullptrs
  101. m_sourceLim(0),
  102. m_functionBody(nullptr),
  103. m_parseType(ParseType_Upfront),
  104. m_arrayDepth(0),
  105. m_funcInArrayDepth(0),
  106. m_funcInArray(0),
  107. m_scopeCountNoAst(0),
  108. m_parsingSuperRestrictionState(ParsingSuperRestrictionState_SuperDisallowed),
  109. m_funcParenExprDepth(0),
  110. m_deferEllipsisError(false),
  111. m_deferEllipsisErrorLoc(), // calls default initializer
  112. m_tryCatchOrFinallyDepth(0),
  113. m_pstmtCur(nullptr),
  114. m_currentBlockInfo(nullptr),
  115. m_currentScope(nullptr),
  116. currBackgroundParseItem(nullptr),
  117. backgroundParseItems(nullptr),
  118. fastScannedRegExpNodes(nullptr),
  119. m_currentDynamicBlock(nullptr),
  120. m_UsesArgumentsAtGlobal(false),
  121. m_fUseStrictMode(strictMode),
  122. m_InAsmMode(false),
  123. m_deferAsmJs(true),
  124. m_fExpectExternalSource(FALSE),
  125. m_deferringAST(FALSE),
  126. m_stoppedDeferredParse(FALSE)
  127. {
  128. AssertMsg(size == sizeof(Parser), "verify conditionals affecting the size of Parser agree");
  129. Assert(scriptContext != nullptr);
  130. // init PID members
  131. InitPids();
  132. }
  133. Parser::~Parser(void)
  134. {
  135. m_registeredRegexPatterns.Reset();
  136. if (m_scriptContext != nullptr)
  137. {
  138. m_scriptContext->ReleaseTemporaryGuestAllocator(m_tempGuestArena);
  139. }
  140. #if ENABLE_BACKGROUND_PARSING
  141. if (this->m_hasParallelJob)
  142. {
  143. // Let the background threads know that they can decommit their arena pages.
  144. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  145. Assert(bgp);
  146. if (bgp->Processor()->ProcessesInBackground())
  147. {
  148. JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());
  149. bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {
  150. threadData->canDecommit = true;
  151. return false;
  152. });
  153. Assert(result);
  154. }
  155. }
  156. #endif
  157. }
  158. void Parser::OutOfMemory()
  159. {
  160. throw ParseExceptionObject(ERRnoMemory);
  161. }
  162. void Parser::Error(HRESULT hr)
  163. {
  164. throw ParseExceptionObject(hr);
  165. }
  166. void Parser::Error(HRESULT hr, ParseNodePtr pnode)
  167. {
  168. if (pnode && pnode->ichLim)
  169. {
  170. Error(hr, pnode->ichMin, pnode->ichLim);
  171. }
  172. else
  173. {
  174. Error(hr);
  175. }
  176. }
  177. void Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim)
  178. {
  179. this->GetScanner()->SetErrorPosition(ichMin, ichLim);
  180. Error(hr);
  181. }
  182. void Parser::IdentifierExpectedError(const Token& token)
  183. {
  184. Assert(token.tk != tkID);
  185. HRESULT hr;
  186. if (token.IsReservedWord())
  187. {
  188. if (token.IsKeyword())
  189. {
  190. hr = ERRKeywordNotId;
  191. }
  192. else
  193. {
  194. Assert(token.IsFutureReservedWord(true));
  195. if (token.IsFutureReservedWord(false))
  196. {
  197. // Future reserved word in strict and non-strict modes
  198. hr = ERRFutureReservedWordNotId;
  199. }
  200. else
  201. {
  202. // Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not
  203. // in strict mode.
  204. Assert(IsStrictMode());
  205. hr = ERRFutureReservedWordInStrictModeNotId;
  206. }
  207. }
  208. }
  209. else
  210. {
  211. hr = ERRnoIdent;
  212. }
  213. Error(hr);
  214. }
  215. HRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())
  216. {
  217. Assert(pszSrc);
  218. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  219. HRESULT hr;
  220. SmartFPUControl smartFpuControl;
  221. BOOL fDeferSave = m_deferringAST;
  222. try
  223. {
  224. hr = NOERROR;
  225. m_length = encodedCharCount;
  226. m_originalLength = encodedCharCount;
  227. // make sure deferred parsing is turned off
  228. ULONG grfscr = fscrNil;
  229. // Give the scanner the source and get the first token
  230. this->GetScanner()->SetText(pszSrc, 0, encodedCharCount, 0, false, grfscr);
  231. this->GetScanner()->SetYieldIsKeywordRegion(isGenerator);
  232. this->GetScanner()->SetAwaitIsKeywordRegion(isAsync);
  233. this->GetScanner()->Scan();
  234. uint nestedCount = 0;
  235. m_pnestedCount = &nestedCount;
  236. ParseNodePtr pnodeScope = nullptr;
  237. m_ppnodeScope = &pnodeScope;
  238. m_ppnodeExprScope = nullptr;
  239. uint nextFunctionId = 0;
  240. m_nextFunctionId = &nextFunctionId;
  241. m_inDeferredNestedFunc = false;
  242. m_deferringAST = true;
  243. m_nextBlockId = 0;
  244. ParseNodeFnc *pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  245. pnodeFnc->SetIsGenerator(isGenerator);
  246. pnodeFnc->SetIsAsync(isAsync);
  247. m_ppnodeVar = &pnodeFnc->pnodeVars;
  248. m_currentNodeFunc = pnodeFnc;
  249. m_currentNodeDeferredFunc = NULL;
  250. m_sourceContextInfo = nullptr;
  251. AssertMsg(m_pstmtCur == NULL, "Statement stack should be empty when we start parse function body");
  252. ParseNodeBlock * block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);
  253. (this->*validateFunction)();
  254. FinishParseBlock(block);
  255. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  256. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  257. pnodeFnc->pnodeVars = nullptr;
  258. // there should be nothing after successful parsing for a given construct
  259. if (m_token.tk != tkEOF)
  260. Error(ERRsyntax);
  261. m_deferringAST = fDeferSave;
  262. }
  263. catch (ParseExceptionObject& e)
  264. {
  265. m_deferringAST = fDeferSave;
  266. hr = e.GetError();
  267. }
  268. if (nullptr != pse && FAILED(hr))
  269. {
  270. hr = pse->ProcessError(this->GetScanner(), hr, /* pnodeBase */ NULL);
  271. }
  272. return hr;
  273. }
  274. HRESULT Parser::ParseSourceInternal(
  275. __out ParseNodeProg ** parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,
  276. bool isUtf8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)
  277. {
  278. Assert(parseTree);
  279. Assert(pszSrc);
  280. if (this->IsBackgroundParser())
  281. {
  282. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  283. }
  284. else
  285. {
  286. PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);
  287. }
  288. #ifdef PROFILE_EXEC
  289. m_scriptContext->ProfileBegin(Js::ParsePhase);
  290. #endif
  291. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_START(m_scriptContext, 0));
  292. *parseTree = NULL;
  293. m_sourceLim = 0;
  294. m_grfscr = grfscr;
  295. m_sourceContextInfo = sourceContextInfo;
  296. ParseNodeProg * pnodeBase = NULL;
  297. HRESULT hr;
  298. SmartFPUControl smartFpuControl;
  299. try
  300. {
  301. if ((grfscr & fscrEvalCode) != 0)
  302. {
  303. this->m_parsingSuperRestrictionState = Parser::ParsingSuperRestrictionState_SuperPropertyAllowed;
  304. }
  305. if ((grfscr & fscrIsModuleCode) != 0)
  306. {
  307. // Module source flag should not be enabled unless module is enabled
  308. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  309. // Module code is always strict mode code.
  310. this->m_fUseStrictMode = TRUE;
  311. }
  312. // parse the source
  313. pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, isUtf8, grfscr, lineNumber, nextFunctionId, pse);
  314. Assert(pnodeBase);
  315. // Record the actual number of words parsed.
  316. m_sourceLim = pnodeBase->ichLim - offsetInChars;
  317. // TODO: The assert can be false positive in some scenarios and chuckj to fix it later
  318. // Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, isUtf8 ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);
  319. #if DBG_DUMP
  320. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))
  321. {
  322. PrintPnodeWIndent(pnodeBase, 4);
  323. fflush(stdout);
  324. }
  325. #endif
  326. *parseTree = pnodeBase;
  327. hr = NOERROR;
  328. }
  329. catch (ParseExceptionObject& e)
  330. {
  331. hr = e.GetError();
  332. }
  333. catch (Js::AsmJsParseException&)
  334. {
  335. hr = JSERR_AsmJsCompileError;
  336. }
  337. if (FAILED(hr))
  338. {
  339. hr = pse->ProcessError(this->GetScanner(), hr, pnodeBase);
  340. }
  341. #if ENABLE_BACKGROUND_PARSING
  342. if (this->m_hasParallelJob)
  343. {
  344. ///// Wait here for remaining jobs to finish. Then look for errors, do final const bindings.
  345. // pleath TODO: If there are remaining jobs, let the main thread help finish them.
  346. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  347. Assert(bgp);
  348. CompileScriptException se;
  349. this->WaitForBackgroundJobs(bgp, &se);
  350. BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();
  351. if (failedItem)
  352. {
  353. CompileScriptException *bgPse = failedItem->GetPSE();
  354. Assert(bgPse);
  355. *pse = *bgPse;
  356. hr = failedItem->GetHR();
  357. bgp->SetFailedBackgroundParseItem(nullptr);
  358. }
  359. if (this->fastScannedRegExpNodes != nullptr)
  360. {
  361. this->FinishBackgroundRegExpNodes();
  362. }
  363. for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())
  364. {
  365. Parser *parser = item->GetParser();
  366. parser->FinishBackgroundPidRefs(item, this != parser);
  367. }
  368. }
  369. #endif
  370. // done with the scanner
  371. this->GetScanner()->Clear();
  372. #ifdef PROFILE_EXEC
  373. m_scriptContext->ProfileEnd(Js::ParsePhase);
  374. #endif
  375. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));
  376. return hr;
  377. }
  378. #if ENABLE_BACKGROUND_PARSING
  379. void Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)
  380. {
  381. // The scan of the script is done, but there may be unfinished background jobs in the queue.
  382. // Enlist the main thread to help with those.
  383. BackgroundParseItem *item;
  384. if (!*bgp->GetPendingBackgroundItemsPtr())
  385. {
  386. // We're done.
  387. return;
  388. }
  389. // Save parser state, since we'll need to restore it in order to bind references correctly later.
  390. this->m_isInBackground = true;
  391. this->SetCurrBackgroundParseItem(nullptr);
  392. uint blockIdSave = this->m_nextBlockId;
  393. uint functionIdSave = *this->m_nextFunctionId;
  394. StmtNest *pstmtSave = this->m_pstmtCur;
  395. if (!bgp->Processor()->ProcessesInBackground())
  396. {
  397. // No background thread. Just walk the jobs with no locking and process them.
  398. for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())
  399. {
  400. bgp->Processor()->RemoveJob(item);
  401. bool succeeded = bgp->Process(item, this, pse);
  402. bgp->JobProcessed(item, succeeded);
  403. }
  404. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  405. }
  406. else
  407. {
  408. // Background threads. We need to have the critical section in order to:
  409. // - Check for unprocessed jobs;
  410. // - Remove jobs from the processor queue;
  411. // - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).
  412. CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();
  413. pcs->Enter();
  414. for (;;)
  415. {
  416. // Grab a job (in lock)
  417. item = bgp->GetNextUnprocessedItem();
  418. if (item == nullptr)
  419. {
  420. break;
  421. }
  422. bgp->Processor()->RemoveJob(item);
  423. pcs->Leave();
  424. // Process job (if there is one) (outside lock)
  425. bool succeeded = bgp->Process(item, this, pse);
  426. pcs->Enter();
  427. bgp->JobProcessed(item, succeeded);
  428. }
  429. pcs->Leave();
  430. // Wait for the background threads to finish jobs they're already processing (if any).
  431. // TODO: Replace with a proper semaphore.
  432. while (*bgp->GetPendingBackgroundItemsPtr());
  433. }
  434. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  435. // Restore parser state.
  436. this->m_pstmtCur = pstmtSave;
  437. this->m_isInBackground = false;
  438. this->m_nextBlockId = blockIdSave;
  439. *this->m_nextFunctionId = functionIdSave;
  440. }
  441. void Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)
  442. {
  443. for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)
  444. {
  445. if (isOtherParser)
  446. {
  447. this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());
  448. }
  449. else
  450. {
  451. this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());
  452. }
  453. }
  454. }
  455. void Parser::FinishBackgroundRegExpNodes()
  456. {
  457. // We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,
  458. // and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.
  459. // We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the
  460. // background nodes.
  461. // There may be UI thread nodes for which there are no background thread equivalents, because the UI thread
  462. // has to assume that the background thread won't defer anything.
  463. // Note that because these lists (and the list of background jobs) are SList's built by prepending, they are
  464. // all in reverse lexical order.
  465. Assert(!this->IsBackgroundParser());
  466. Assert(this->fastScannedRegExpNodes);
  467. Assert(this->backgroundParseItems != nullptr);
  468. BackgroundParseItem *currBackgroundItem;
  469. #if DBG
  470. for (currBackgroundItem = this->backgroundParseItems;
  471. currBackgroundItem;
  472. currBackgroundItem = currBackgroundItem->GetNext())
  473. {
  474. if (currBackgroundItem->RegExpNodeList())
  475. {
  476. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  477. {
  478. Assert(pnode->AsParseNodeRegExp()->regexPattern == nullptr);
  479. }
  480. NEXT_DLIST_ENTRY;
  481. }
  482. }
  483. #endif
  484. // Hook up the patterns allocated on the main thread to the nodes created on the background thread.
  485. // Walk the list of foreground nodes, advancing through the work items and looking up each item.
  486. // Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground
  487. // node will have a matching background node. Doesn't matter for correctness.
  488. // (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's
  489. // list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how
  490. // to start the inner loop from a known internal node within the list if that turns out to be important.)
  491. currBackgroundItem = this->backgroundParseItems;
  492. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)
  493. {
  494. Assert(pnodeFgnd->nop == knopRegExp);
  495. Assert(pnodeFgnd->AsParseNodeRegExp()->regexPattern != nullptr);
  496. bool quit = false;
  497. while (!quit)
  498. {
  499. // Find the next work item with a RegEx in it.
  500. while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)
  501. {
  502. currBackgroundItem = currBackgroundItem->GetNext();
  503. }
  504. if (!currBackgroundItem)
  505. {
  506. break;
  507. }
  508. // Walk the RegExps in the work item.
  509. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())
  510. {
  511. Assert(pnodeBgnd->nop == knopRegExp);
  512. if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)
  513. {
  514. // Either we found a match, or the next background node is past the foreground node.
  515. // In any case, we can stop searching.
  516. if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)
  517. {
  518. Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);
  519. pnodeBgnd->AsParseNodeRegExp()->regexPattern = pnodeFgnd->AsParseNodeRegExp()->regexPattern;
  520. }
  521. quit = true;
  522. break;
  523. }
  524. }
  525. NEXT_DLIST_ENTRY;
  526. if (!quit)
  527. {
  528. // Need to advance to the next work item.
  529. currBackgroundItem = currBackgroundItem->GetNext();
  530. }
  531. }
  532. }
  533. NEXT_DLIST_ENTRY;
  534. #if DBG
  535. for (currBackgroundItem = this->backgroundParseItems;
  536. currBackgroundItem;
  537. currBackgroundItem = currBackgroundItem->GetNext())
  538. {
  539. if (currBackgroundItem->RegExpNodeList())
  540. {
  541. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  542. {
  543. Assert(pnode->AsParseNodeRegExp()->regexPattern != nullptr);
  544. }
  545. NEXT_DLIST_ENTRY;
  546. }
  547. }
  548. #endif
  549. }
  550. #endif
  551. LabelId* Parser::CreateLabelId(IdentPtr pid)
  552. {
  553. LabelId* pLabelId;
  554. pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));
  555. if (NULL == pLabelId)
  556. Error(ERRnoMemory);
  557. pLabelId->pid = pid;
  558. pLabelId->next = NULL;
  559. return pLabelId;
  560. }
  561. /*****************************************************************************
  562. The following set of routines allocate parse tree nodes of various kinds.
  563. They catch an exception on out of memory.
  564. *****************************************************************************/
  565. void
  566. Parser::AddAstSize(int size)
  567. {
  568. Assert(!this->m_deferringAST);
  569. Assert(m_pCurrentAstSize != NULL);
  570. *m_pCurrentAstSize += size;
  571. }
  572. void
  573. Parser::AddAstSizeAllowDefer(int size)
  574. {
  575. if (!this->m_deferringAST)
  576. {
  577. AddAstSize(size);
  578. }
  579. }
  580. // StaticCreate
  581. ParseNodeVar * Parser::StaticCreateTempNode(ParseNode* initExpr, ArenaAllocator * alloc)
  582. {
  583. ParseNodeVar * pnode = Anew(alloc, ParseNodeVar, knopTemp, 0, 0, nullptr);
  584. pnode->pnodeInit = initExpr;
  585. return pnode;
  586. }
  587. ParseNodeUni * Parser::StaticCreateTempRef(ParseNode* tempNode, ArenaAllocator * alloc)
  588. {
  589. return Anew(alloc, ParseNodeUni, knopTempRef, 0, 0, tempNode);
  590. }
  591. // Create Node with limit
  592. template <OpCode nop>
  593. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  594. {
  595. Assert(!this->m_deferringAST);
  596. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  597. AddAstSize(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  598. return pnode;
  599. }
  600. template <OpCode nop>
  601. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateAllowDeferNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  602. {
  603. CompileAssert(OpCodeTrait<nop>::AllowDefer);
  604. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  605. AddAstSizeAllowDefer(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  606. return pnode;
  607. }
  608. #if DBG
  609. static const int g_mpnopcbNode[] =
  610. {
  611. #define PTNODE(nop,sn,pc,nk,ok,json) sizeof(ParseNode##nk),
  612. #include "ptlist.h"
  613. };
  614. void VerifyNodeSize(OpCode nop, int size)
  615. {
  616. Assert(nop >= 0 && nop < knopLim);
  617. __analysis_assume(nop < knopLim);
  618. Assert(g_mpnopcbNode[nop] == size);
  619. }
  620. #endif
  621. // Create ParseNodeUni
  622. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)
  623. {
  624. charcount_t ichMin;
  625. charcount_t ichLim;
  626. if (nullptr == pnode1)
  627. {
  628. // no ops
  629. ichMin = this->GetScanner()->IchMinTok();
  630. ichLim = this->GetScanner()->IchLimTok();
  631. }
  632. else
  633. {
  634. // 1 op
  635. ichMin = pnode1->ichMin;
  636. ichLim = pnode1->ichLim;
  637. this->CheckArguments(pnode1);
  638. }
  639. return CreateUniNode(nop, pnode1, ichMin, ichLim);
  640. }
  641. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin, charcount_t ichLim)
  642. {
  643. Assert(!this->m_deferringAST);
  644. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeUni)));
  645. ParseNodeUni * pnode = Anew(&m_nodeAllocator, ParseNodeUni, nop, ichMin, ichLim, pnode1);
  646. AddAstSize(sizeof(ParseNodeUni));
  647. return pnode;
  648. }
  649. // Create ParseNodeBin
  650. ParseNodeBin * Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim)
  651. {
  652. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeBin)));
  653. return Anew(alloc, ParseNodeBin, nop, ichMin, ichLim, pnode1, pnode2);
  654. }
  655. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  656. {
  657. Assert(!this->m_deferringAST);
  658. charcount_t ichMin;
  659. charcount_t ichLim;
  660. if (nullptr == pnode1)
  661. {
  662. // no ops
  663. Assert(nullptr == pnode2);
  664. ichMin = this->GetScanner()->IchMinTok();
  665. ichLim = this->GetScanner()->IchLimTok();
  666. }
  667. else
  668. {
  669. if (nullptr == pnode2)
  670. {
  671. // 1 op
  672. ichMin = pnode1->ichMin;
  673. ichLim = pnode1->ichLim;
  674. }
  675. else
  676. {
  677. // 2 ops
  678. ichMin = pnode1->ichMin;
  679. ichLim = pnode2->ichLim;
  680. if (nop != knopDot && nop != knopIndex)
  681. {
  682. this->CheckArguments(pnode2);
  683. }
  684. }
  685. if (nop != knopDot && nop != knopIndex)
  686. {
  687. this->CheckArguments(pnode1);
  688. }
  689. }
  690. return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
  691. }
  692. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
  693. ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  694. {
  695. Assert(!this->m_deferringAST);
  696. ParseNodeBin * pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator, ichMin, ichLim);
  697. AddAstSize(sizeof(ParseNodeBin));
  698. return pnode;
  699. }
  700. // Create ParseNodeTri
  701. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  702. ParseNodePtr pnode2, ParseNodePtr pnode3)
  703. {
  704. charcount_t ichMin;
  705. charcount_t ichLim;
  706. if (nullptr == pnode1)
  707. {
  708. // no ops
  709. Assert(nullptr == pnode2);
  710. Assert(nullptr == pnode3);
  711. ichMin = this->GetScanner()->IchMinTok();
  712. ichLim = this->GetScanner()->IchLimTok();
  713. }
  714. else if (nullptr == pnode2)
  715. {
  716. // 1 op
  717. Assert(nullptr == pnode3);
  718. ichMin = pnode1->ichMin;
  719. ichLim = pnode1->ichLim;
  720. }
  721. else if (nullptr == pnode3)
  722. {
  723. // 2 op
  724. ichMin = pnode1->ichMin;
  725. ichLim = pnode2->ichLim;
  726. }
  727. else
  728. {
  729. // 3 ops
  730. ichMin = pnode1->ichMin;
  731. ichLim = pnode3->ichLim;
  732. }
  733. return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);
  734. }
  735. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  736. ParseNodePtr pnode2, ParseNodePtr pnode3,
  737. charcount_t ichMin, charcount_t ichLim)
  738. {
  739. Assert(!this->m_deferringAST);
  740. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeTri)));
  741. ParseNodeTri * pnode = Anew(&m_nodeAllocator, ParseNodeTri, nop, ichMin, ichLim);
  742. AddAstSize(sizeof(ParseNodeTri));
  743. pnode->pnode1 = pnode1;
  744. pnode->pnode2 = pnode2;
  745. pnode->pnode3 = pnode3;
  746. return pnode;
  747. }
  748. // Create ParseNodeBlock
  749. ParseNodeBlock *
  750. Parser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim, int blockId, PnodeBlockType blockType)
  751. {
  752. return Anew(alloc, ParseNodeBlock, ichMin, ichLim, blockId, blockType);
  753. }
  754. ParseNodeBlock * Parser::CreateBlockNode(PnodeBlockType blockType)
  755. {
  756. return CreateBlockNode(this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), blockType);
  757. }
  758. ParseNodeBlock * Parser::CreateBlockNode(charcount_t ichMin, charcount_t ichLim, PnodeBlockType blockType)
  759. {
  760. Assert(OpCodeTrait<knopBlock>::AllowDefer);
  761. ParseNodeBlock * pnode = StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);
  762. AddAstSizeAllowDefer(sizeof(ParseNodeBlock));
  763. return pnode;
  764. }
  765. // Create ParseNodeVar
  766. ParseNodeVar * Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  767. {
  768. Assert(nop == knopVarDecl || nop == knopLetDecl || nop == knopConstDecl);
  769. ParseNodeVar * pnode = Anew(&m_nodeAllocator, ParseNodeVar, nop, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  770. if (symbolType != STUnknown)
  771. {
  772. pnode->sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);
  773. }
  774. return pnode;
  775. }
  776. ParseNodeInt * Parser::CreateIntNode(int32 lw)
  777. {
  778. Assert(!this->m_deferringAST);
  779. ParseNodeInt * pnode = Anew(&m_nodeAllocator, ParseNodeInt, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), lw);
  780. AddAstSize(sizeof(ParseNodeInt));
  781. return pnode;
  782. }
  783. ParseNodeStr * Parser::CreateStrNode(IdentPtr pid)
  784. {
  785. Assert(!this->m_deferringAST);
  786. ParseNodeStr * pnode = Anew(&m_nodeAllocator, ParseNodeStr, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  787. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  788. AddAstSize(sizeof(ParseNodeStr));
  789. return pnode;
  790. }
  791. ParseNodeName * Parser::CreateNameNode(IdentPtr pid)
  792. {
  793. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  794. AddAstSizeAllowDefer(sizeof(ParseNodeName));
  795. return pnode;
  796. }
  797. ParseNodeName * Parser::CreateNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  798. {
  799. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, ichMin, ichLim, pid);
  800. pnode->SetSymRef(ref);
  801. AddAstSize(sizeof(ParseNodeName));
  802. return pnode;
  803. }
  804. ParseNodeSpecialName * Parser::CreateSpecialNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  805. {
  806. Assert(!this->m_deferringAST);
  807. ParseNodeSpecialName * pnode = Anew(&m_nodeAllocator, ParseNodeSpecialName, ichMin, ichLim, pid);
  808. pnode->SetSymRef(ref);
  809. if (pid == wellKnownPropertyPids._this)
  810. {
  811. pnode->isThis = true;
  812. }
  813. else if (pid == wellKnownPropertyPids._super || pid == wellKnownPropertyPids._superConstructor)
  814. {
  815. pnode->isSuper = true;
  816. }
  817. AddAstSize(sizeof(ParseNodeSpecialName));
  818. return pnode;
  819. }
  820. ParseNodeSuperReference * Parser::CreateSuperReferenceNode(OpCode nop, ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  821. {
  822. Assert(!this->m_deferringAST);
  823. Assert(pnode1 && pnode1->isSuper);
  824. Assert(pnode2 != nullptr);
  825. Assert(nop == knopDot || nop == knopIndex);
  826. ParseNodeSuperReference * pnode = Anew(&m_nodeAllocator, ParseNodeSuperReference, nop, pnode1->ichMin, pnode2->ichLim, pnode1, pnode2);
  827. AddAstSize(sizeof(ParseNodeSuperReference));
  828. return pnode;
  829. }
  830. ParseNodeProg * Parser::CreateProgNode(bool isModuleSource, ULONG lineNumber)
  831. {
  832. ParseNodeProg * pnodeProg;
  833. if (isModuleSource)
  834. {
  835. pnodeProg = CreateNodeForOpT<knopModule>();
  836. // knopModule is not actually handled anywhere since we would need to handle it everywhere we could
  837. // have knopProg and it would be treated exactly the same except for import/export statements.
  838. // We are only using it as a way to get the correct size for PnModule.
  839. // Consider: Should we add a flag to PnProg which is false but set to true in PnModule?
  840. // If we do, it can't be a virtual method since the parse nodes are all in a union.
  841. pnodeProg->nop = knopProg;
  842. }
  843. else
  844. {
  845. pnodeProg = CreateNodeForOpT<knopProg>();
  846. }
  847. pnodeProg->cbMin = this->GetScanner()->IecpMinTok();
  848. pnodeProg->lineNumber = lineNumber;
  849. pnodeProg->homeObjLocation = Js::Constants::NoRegister;
  850. return pnodeProg;
  851. }
  852. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  853. {
  854. charcount_t ichMin;
  855. charcount_t ichLim;
  856. if (nullptr == pnode1)
  857. {
  858. Assert(nullptr == pnode2);
  859. ichMin = this->GetScanner()->IchMinTok();
  860. ichLim = this->GetScanner()->IchLimTok();
  861. }
  862. else
  863. {
  864. ichMin = pnode1->ichMin;
  865. ichLim = pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim;
  866. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  867. {
  868. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  869. }
  870. }
  871. return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);
  872. }
  873. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  874. {
  875. Assert(!this->m_deferringAST);
  876. // Classes, derived from ParseNodeCall, can be created here as well,
  877. // as long as their size matches kcbPnCall (that is, they don't add
  878. // any data members of their own).
  879. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeCall)));
  880. ParseNodeCall* pnode = Anew(&m_nodeAllocator, ParseNodeCall, nop, ichMin, ichLim, pnode1, pnode2);
  881. AddAstSize(sizeof(ParseNodeCall));
  882. return pnode;
  883. }
  884. ParseNodeSuperCall * Parser::CreateSuperCallNode(ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  885. {
  886. Assert(!this->m_deferringAST);
  887. Assert(pnode1 && pnode1->isSuper);
  888. ParseNodeSuperCall* pnode = Anew(&m_nodeAllocator, ParseNodeSuperCall, knopCall, pnode1->ichMin, pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim, pnode1, pnode2);
  889. AddAstSize(sizeof(ParseNodeSuperCall));
  890. return pnode;
  891. }
  892. ParseNodeParamPattern * Parser::CreateParamPatternNode(ParseNode * pnode1)
  893. {
  894. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(pnode1->ichMin, pnode1->ichLim);
  895. paramPatternNode->pnode1 = pnode1;
  896. paramPatternNode->pnodeNext = nullptr;
  897. paramPatternNode->location = Js::Constants::NoRegister;
  898. return paramPatternNode;
  899. }
  900. ParseNodeParamPattern * Parser::CreateDummyParamPatternNode(charcount_t ichMin)
  901. {
  902. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(ichMin);
  903. paramPatternNode->pnode1 = nullptr;
  904. paramPatternNode->pnodeNext = nullptr;
  905. paramPatternNode->location = Js::Constants::NoRegister;
  906. return paramPatternNode;
  907. }
  908. Symbol* Parser::AddDeclForPid(ParseNodeVar * pnodeVar, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  909. {
  910. Assert(pnodeVar->IsVarLetOrConst());
  911. PidRefStack *refForUse = nullptr, *refForDecl = nullptr;
  912. BlockInfoStack *blockInfo;
  913. bool fBlockScope = false;
  914. if (pnodeVar->nop != knopVarDecl || symbolType == STFunction)
  915. {
  916. Assert(m_pstmtCur);
  917. if (m_pstmtCur->GetNop() != knopBlock)
  918. {
  919. // Let/const declared in a bare statement context.
  920. Error(ERRDeclOutOfStmt);
  921. }
  922. if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->GetNop() == knopSwitch)
  923. {
  924. // Let/const declared inside a switch block (requiring conservative use-before-decl check).
  925. pnodeVar->isSwitchStmtDecl = true;
  926. }
  927. fBlockScope = pnodeVar->nop != knopVarDecl ||
  928. (
  929. !GetCurrentBlockInfo()->pnodeBlock->scope ||
  930. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock
  931. );
  932. }
  933. if (fBlockScope)
  934. {
  935. blockInfo = GetCurrentBlockInfo();
  936. }
  937. else
  938. {
  939. blockInfo = GetCurrentFunctionBlockInfo();
  940. }
  941. refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->blockId, GetCurrentFunctionNode()->functionId);
  942. if (refForDecl == nullptr)
  943. {
  944. Error(ERRnoMemory);
  945. }
  946. if (refForDecl->funcId != GetCurrentFunctionNode()->functionId)
  947. {
  948. // Fix up the function id, which is incorrect if we're reparsing lambda parameters
  949. Assert(this->m_reparsingLambdaParams);
  950. refForDecl->funcId = GetCurrentFunctionNode()->functionId;
  951. }
  952. if (blockInfo == GetCurrentBlockInfo())
  953. {
  954. refForUse = refForDecl;
  955. }
  956. else
  957. {
  958. refForUse = this->PushPidRef(pid);
  959. }
  960. pnodeVar->symRef = refForUse->GetSymRef();
  961. Symbol *sym = refForDecl->GetSym();
  962. if (sym != nullptr)
  963. {
  964. // Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.
  965. switch (pnodeVar->nop)
  966. {
  967. case knopLetDecl:
  968. case knopConstDecl:
  969. if (!sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar && !sym->IsArguments())
  970. {
  971. // If the built-in arguments is shadowed then don't throw
  972. Assert(errorOnRedecl);
  973. // Redeclaration error.
  974. Error(ERRRedeclaration);
  975. }
  976. else
  977. {
  978. // (New) let/const hides the (old) var
  979. sym->SetSymbolType(symbolType);
  980. sym->SetDecl(pnodeVar);
  981. }
  982. break;
  983. case knopVarDecl:
  984. if (m_currentScope->GetScopeType() == ScopeType_Parameter && !sym->IsArguments())
  985. {
  986. // If this is a parameter list, mark the scope to indicate that it has duplicate definition unless it is shadowing the default arguments symbol.
  987. // 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.
  988. m_currentScope->SetHasDuplicateFormals();
  989. }
  990. if (sym->GetDecl() == nullptr)
  991. {
  992. sym->SetDecl(pnodeVar);
  993. break;
  994. }
  995. switch (sym->GetDecl()->nop)
  996. {
  997. case knopLetDecl:
  998. case knopConstDecl:
  999. // Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.
  1000. if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))
  1001. {
  1002. Error(ERRRedeclaration);
  1003. }
  1004. // If !errorOnRedecl, (old) let/const hides the (new) var, so do nothing.
  1005. break;
  1006. case knopVarDecl:
  1007. // Legal redeclaration. Who wins?
  1008. if (errorOnRedecl || sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsArguments())
  1009. {
  1010. if (symbolType == STFormal ||
  1011. (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||
  1012. sym->GetSymbolType() == STVariable)
  1013. {
  1014. // New decl wins.
  1015. sym->SetSymbolType(symbolType);
  1016. sym->SetDecl(pnodeVar);
  1017. }
  1018. }
  1019. break;
  1020. }
  1021. break;
  1022. }
  1023. }
  1024. else
  1025. {
  1026. Scope *scope = blockInfo->pnodeBlock->scope;
  1027. if (scope == nullptr)
  1028. {
  1029. Assert(blockInfo->pnodeBlock->blockType == PnodeBlockType::Regular);
  1030. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);
  1031. if (this->IsCurBlockInLoop())
  1032. {
  1033. scope->SetIsBlockInLoop();
  1034. }
  1035. blockInfo->pnodeBlock->scope = scope;
  1036. PushScope(scope);
  1037. }
  1038. ParseNodeFnc * pnodeFnc = GetCurrentFunctionNode();
  1039. if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)
  1040. {
  1041. Assert(fBlockScope);
  1042. Assert(scope->GetEnclosingScope() == m_currentNodeProg->scope);
  1043. // Check for same-named decl in Global scope.
  1044. CheckRedeclarationErrorForBlockId(pid, 0);
  1045. }
  1046. else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&
  1047. !(m_functionBody && m_functionBody->GetScopeInfo()))
  1048. {
  1049. // Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary
  1050. // if we're compiling a deferred nested function and the global scope was restored from cached info,
  1051. // because in that case we don't need a GlobalEvalScope.
  1052. Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);
  1053. CheckRedeclarationErrorForBlockId(pid, 1);
  1054. }
  1055. else if (!pnodeFnc->IsBodyAndParamScopeMerged()
  1056. && scope->GetScopeType() == ScopeType_FunctionBody
  1057. && (pnodeVar->nop == knopLetDecl || pnodeVar->nop == knopConstDecl))
  1058. {
  1059. // In case of split scope function when we add a new let or const declaration to the body
  1060. // we have to check whether the param scope already has the same symbol defined.
  1061. CheckRedeclarationErrorForBlockId(pid, pnodeFnc->pnodeScopes->blockId);
  1062. }
  1063. if (!sym)
  1064. {
  1065. const char16 *name = reinterpret_cast<const char16*>(pid->Psz());
  1066. int nameLength = pid->Cch();
  1067. SymbolName const symName(name, nameLength);
  1068. Assert(!scope->FindLocalSymbol(symName));
  1069. sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeVar, symbolType);
  1070. scope->AddNewSymbol(sym);
  1071. sym->SetPid(pid);
  1072. }
  1073. refForDecl->SetSym(sym);
  1074. }
  1075. return sym;
  1076. }
  1077. void Parser::CheckRedeclarationErrorForBlockId(IdentPtr pid, int blockId)
  1078. {
  1079. // If the ref stack entry for the blockId contains a sym then throw redeclaration error
  1080. PidRefStack *pidRefOld = pid->GetPidRefForScopeId(blockId);
  1081. if (pidRefOld && pidRefOld->GetSym() && !pidRefOld->GetSym()->IsArguments())
  1082. {
  1083. Error(ERRRedeclaration);
  1084. }
  1085. }
  1086. bool Parser::IsCurBlockInLoop() const
  1087. {
  1088. for (StmtNest *stmt = this->m_pstmtCur; stmt != nullptr; stmt = stmt->pstmtOuter)
  1089. {
  1090. OpCode nop = stmt->GetNop();
  1091. if (ParseNode::Grfnop(nop) & fnopContinue)
  1092. {
  1093. return true;
  1094. }
  1095. if (nop == knopFncDecl)
  1096. {
  1097. return false;
  1098. }
  1099. }
  1100. return false;
  1101. }
  1102. void Parser::RestorePidRefForSym(Symbol *sym)
  1103. {
  1104. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());
  1105. Assert(pid);
  1106. sym->SetPid(pid);
  1107. PidRefStack *ref = this->PushPidRef(pid);
  1108. ref->SetSym(sym);
  1109. }
  1110. void Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)
  1111. {
  1112. if (IsStrictMode())
  1113. {
  1114. // in strict mode, variable named 'eval' cannot be created
  1115. if (pid == wellKnownPropertyPids.eval)
  1116. {
  1117. Error(ERREvalUsage);
  1118. }
  1119. else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)
  1120. {
  1121. Error(ERRArgsUsage);
  1122. }
  1123. }
  1124. }
  1125. // CreateVarDecl needs m_ppnodeVar to be pointing to the right function.
  1126. // Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.
  1127. // This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.
  1128. // This prevents accidentally adding var declarations to the last parsed function.
  1129. ParseNodeVar * Parser::AddVarDeclNode(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1130. {
  1131. AnalysisAssert(pnodeFnc);
  1132. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  1133. m_ppnodeVar = &pnodeFnc->pnodeVars;
  1134. while (*m_ppnodeVar != nullptr)
  1135. {
  1136. m_ppnodeVar = &(*m_ppnodeVar)->AsParseNodeVar()->pnodeNext;
  1137. }
  1138. ParseNodeVar * pnode = CreateVarDeclNode(pid, STUnknown, false, 0, /* checkReDecl = */ false);
  1139. m_ppnodeVar = ppnodeVarSave;
  1140. return pnode;
  1141. }
  1142. ParseNodeVar * Parser::CreateModuleImportDeclNode(IdentPtr localName)
  1143. {
  1144. ParseNodeVar * declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);
  1145. Symbol* sym = declNode->sym;
  1146. sym->SetIsModuleExportStorage(true);
  1147. sym->SetIsModuleImport(true);
  1148. return declNode;
  1149. }
  1150. ParseNodeVar * Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)
  1151. {
  1152. ParseNodeVar * pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);
  1153. // Append the variable to the end of the current variable list.
  1154. Assert(m_ppnodeVar);
  1155. pnode->pnodeNext = *m_ppnodeVar;
  1156. *m_ppnodeVar = pnode;
  1157. if (nullptr != pid)
  1158. {
  1159. // this is not a temp - make sure temps go after this node
  1160. Assert(pid);
  1161. m_ppnodeVar = &pnode->pnodeNext;
  1162. CheckPidIsValid(pid, autoArgumentsObject);
  1163. }
  1164. return pnode;
  1165. }
  1166. ParseNodeVar * Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)
  1167. {
  1168. Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);
  1169. ParseNodeVar * pnode = CreateDeclNode(nodeType, pid, STVariable, true);
  1170. if (nullptr != pid)
  1171. {
  1172. Assert(pid);
  1173. AddVarDeclToBlock(pnode);
  1174. CheckPidIsValid(pid);
  1175. }
  1176. return pnode;
  1177. }
  1178. void Parser::AddVarDeclToBlock(ParseNodeVar *pnode)
  1179. {
  1180. Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);
  1181. // Maintain a combined list of let and const declarations to keep
  1182. // track of declaration order.
  1183. Assert(m_currentBlockInfo->m_ppnodeLex);
  1184. *m_currentBlockInfo->m_ppnodeLex = pnode;
  1185. m_currentBlockInfo->m_ppnodeLex = &pnode->pnodeNext;
  1186. pnode->pnodeNext = nullptr;
  1187. }
  1188. void Parser::SetCurrentStatement(StmtNest *stmt)
  1189. {
  1190. m_pstmtCur = stmt;
  1191. }
  1192. template<bool buildAST>
  1193. ParseNodeBlock * Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)
  1194. {
  1195. Scope *scope = nullptr;
  1196. // Block scopes are not created lazily in the case where we're repopulating a persisted scope.
  1197. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);
  1198. PushScope(scope);
  1199. return StartParseBlockHelper<buildAST>(blockType, scope, nullptr);
  1200. }
  1201. template<bool buildAST>
  1202. ParseNodeBlock * Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, LabelId* pLabelId)
  1203. {
  1204. Scope *scope = nullptr;
  1205. // Block scopes are created lazily when we discover block-scoped content.
  1206. if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)
  1207. {
  1208. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);
  1209. PushScope(scope);
  1210. }
  1211. return StartParseBlockHelper<buildAST>(blockType, scope, pLabelId);
  1212. }
  1213. template<bool buildAST>
  1214. ParseNodeBlock * Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, LabelId* pLabelId)
  1215. {
  1216. ParseNodeBlock * pnodeBlock = CreateBlockNode(blockType);
  1217. pnodeBlock->scope = scope;
  1218. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);
  1219. PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pLabelId);
  1220. return pnodeBlock;
  1221. }
  1222. void Parser::PushScope(Scope *scope)
  1223. {
  1224. Assert(scope);
  1225. scope->SetEnclosingScope(m_currentScope);
  1226. m_currentScope = scope;
  1227. }
  1228. void Parser::PopScope(Scope *scope)
  1229. {
  1230. Assert(scope == m_currentScope);
  1231. m_currentScope = scope->GetEnclosingScope();
  1232. scope->SetEnclosingScope(nullptr);
  1233. }
  1234. void Parser::PushFuncBlockScope(ParseNodeBlock * pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)
  1235. {
  1236. // Maintain the scope tree.
  1237. pnodeBlock->pnodeScopes = nullptr;
  1238. pnodeBlock->pnodeNext = nullptr;
  1239. // Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).
  1240. // Save the current block's "next" pointer as the new endpoint of that list.
  1241. if (m_ppnodeExprScope)
  1242. {
  1243. *ppnodeScopeSave = m_ppnodeScope;
  1244. Assert(*m_ppnodeExprScope == nullptr);
  1245. *m_ppnodeExprScope = pnodeBlock;
  1246. *ppnodeExprScopeSave = &pnodeBlock->pnodeNext;
  1247. }
  1248. else
  1249. {
  1250. Assert(m_ppnodeScope);
  1251. Assert(*m_ppnodeScope == nullptr);
  1252. *m_ppnodeScope = pnodeBlock;
  1253. *ppnodeScopeSave = &pnodeBlock->pnodeNext;
  1254. *ppnodeExprScopeSave = m_ppnodeExprScope;
  1255. }
  1256. // Advance the global scope list pointer to the new block's child list.
  1257. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  1258. // Set m_ppnodeExprScope to NULL to make that list inactive.
  1259. m_ppnodeExprScope = nullptr;
  1260. }
  1261. void Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)
  1262. {
  1263. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  1264. m_ppnodeExprScope = ppnodeExprScopeSave;
  1265. Assert(m_ppnodeScope);
  1266. Assert(nullptr == *m_ppnodeScope);
  1267. m_ppnodeScope = ppnodeScopeSave;
  1268. }
  1269. template<bool buildAST>
  1270. ParseNodeBlock * Parser::ParseBlock(LabelId* pLabelId)
  1271. {
  1272. ParseNodeBlock * pnodeBlock = nullptr;
  1273. ParseNodePtr *ppnodeScopeSave = nullptr;
  1274. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  1275. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pLabelId);
  1276. BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1277. if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr
  1278. && outerBlockInfo->pnodeBlock->scope != nullptr
  1279. && outerBlockInfo->pnodeBlock->scope->GetScopeType() == ScopeType_CatchParamPattern)
  1280. {
  1281. // If we are parsing the catch block then destructured params can have let declarations. Let's add them to the new block.
  1282. for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1283. {
  1284. PidRefStack* ref = PushPidRef(pnode->AsParseNodeVar()->sym->GetPid());
  1285. ref->SetSym(pnode->AsParseNodeVar()->sym);
  1286. }
  1287. }
  1288. ChkCurTok(tkLCurly, ERRnoLcurly);
  1289. ParseNodePtr * ppnodeList = nullptr;
  1290. if (buildAST)
  1291. {
  1292. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  1293. ppnodeList = &pnodeBlock->pnodeStmt;
  1294. }
  1295. ParseStmtList<buildAST>(ppnodeList);
  1296. if (buildAST)
  1297. {
  1298. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  1299. }
  1300. FinishParseBlock(pnodeBlock);
  1301. ChkCurTok(tkRCurly, ERRnoRcurly);
  1302. return pnodeBlock;
  1303. }
  1304. bool Parser::IsSpecialName(IdentPtr pid)
  1305. {
  1306. return pid == wellKnownPropertyPids._this ||
  1307. pid == wellKnownPropertyPids._super ||
  1308. pid == wellKnownPropertyPids._superConstructor ||
  1309. pid == wellKnownPropertyPids._newTarget;
  1310. }
  1311. ParseNodeSpecialName * Parser::ReferenceSpecialName(IdentPtr pid, charcount_t ichMin, charcount_t ichLim, bool createNode)
  1312. {
  1313. PidRefStack* ref = this->PushPidRef(pid);
  1314. if (!createNode)
  1315. {
  1316. return nullptr;
  1317. }
  1318. return CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  1319. }
  1320. ParseNodeVar * Parser::CreateSpecialVarDeclIfNeeded(ParseNodeFnc * pnodeFnc, IdentPtr pid, bool forceCreate)
  1321. {
  1322. Assert(pid != nullptr);
  1323. PidRefStack* ref = pid->GetTopRef();
  1324. // If the function has a reference to pid or we set forceCreate, make a special var decl
  1325. if (forceCreate || (ref && ref->GetScopeId() >= m_currentBlockInfo->pnodeBlock->blockId))
  1326. {
  1327. return this->CreateSpecialVarDeclNode(pnodeFnc, pid);
  1328. }
  1329. return nullptr;
  1330. }
  1331. void Parser::CreateSpecialSymbolDeclarations(ParseNodeFnc * pnodeFnc)
  1332. {
  1333. // Lambda function cannot have any special bindings.
  1334. if (pnodeFnc->IsLambda())
  1335. {
  1336. return;
  1337. }
  1338. bool isTopLevelEventHandler = (this->m_grfscr & fscrImplicitThis) && !pnodeFnc->IsNested();
  1339. // Create a 'this' symbol for non-lambda functions with references to 'this', and all class constructors and top level event hanlders.
  1340. ParseNodePtr varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._this, pnodeFnc->IsClassConstructor() || isTopLevelEventHandler);
  1341. if (varDeclNode)
  1342. {
  1343. varDeclNode->AsParseNodeVar()->sym->SetIsThis(true);
  1344. if (pnodeFnc->IsDerivedClassConstructor())
  1345. {
  1346. varDeclNode->AsParseNodeVar()->sym->SetNeedDeclaration(true);
  1347. }
  1348. }
  1349. // Create a 'new.target' symbol for any ordinary function with a reference and all class constructors.
  1350. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._newTarget, pnodeFnc->IsClassConstructor());
  1351. if (varDeclNode)
  1352. {
  1353. varDeclNode->AsParseNodeVar()->sym->SetIsNewTarget(true);
  1354. }
  1355. // Create a 'super' (as a reference) symbol.
  1356. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._super);
  1357. if (varDeclNode)
  1358. {
  1359. varDeclNode->AsParseNodeVar()->sym->SetIsSuper(true);
  1360. }
  1361. // Create a 'super' (as the call target for super()) symbol only for derived class constructors.
  1362. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._superConstructor);
  1363. if (varDeclNode)
  1364. {
  1365. varDeclNode->AsParseNodeVar()->sym->SetIsSuperConstructor(true);
  1366. }
  1367. }
  1368. void Parser::FinishParseBlock(ParseNodeBlock *pnodeBlock, bool needScanRCurly)
  1369. {
  1370. Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);
  1371. if (needScanRCurly)
  1372. {
  1373. // Only update the ichLim if we were expecting an RCurly. If there is an
  1374. // expression body without a necessary RCurly, the correct ichLim will
  1375. // have been set already.
  1376. pnodeBlock->ichLim = this->GetScanner()->IchLimTok();
  1377. }
  1378. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  1379. PopStmt(&m_currentBlockInfo->pstmt);
  1380. PopBlockInfo();
  1381. Scope *scope = pnodeBlock->scope;
  1382. if (scope)
  1383. {
  1384. PopScope(scope);
  1385. }
  1386. }
  1387. void Parser::FinishParseFncExprScope(ParseNodeFnc * pnodeFnc, ParseNodeBlock * pnodeFncExprScope)
  1388. {
  1389. int fncExprScopeId = pnodeFncExprScope->blockId;
  1390. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  1391. if (pnodeName)
  1392. {
  1393. Assert(pnodeName->nop == knopVarDecl);
  1394. BindPidRefsInScope(pnodeName->AsParseNodeVar()->pid, pnodeName->AsParseNodeVar()->sym, fncExprScopeId, m_nextBlockId - 1);
  1395. }
  1396. FinishParseBlock(pnodeFncExprScope);
  1397. }
  1398. template <const bool backgroundPidRef>
  1399. void Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)
  1400. {
  1401. // We need to bind all assignments in order to emit assignment to 'const' error
  1402. int blockId = blockInfo->pnodeBlock->blockId;
  1403. Scope *scope = blockInfo->pnodeBlock->scope;
  1404. if (scope)
  1405. {
  1406. auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)
  1407. {
  1408. ParseNodePtr pnode = sym->GetDecl();
  1409. IdentPtr pid;
  1410. #if PROFILE_DICTIONARY
  1411. int depth = 0;
  1412. #endif
  1413. Assert(pnode);
  1414. switch (pnode->nop)
  1415. {
  1416. case knopVarDecl:
  1417. case knopLetDecl:
  1418. case knopConstDecl:
  1419. pid = pnode->AsParseNodeVar()->pid;
  1420. if (backgroundPidRef)
  1421. {
  1422. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1423. #if PROFILE_DICTIONARY
  1424. , depth
  1425. #endif
  1426. );
  1427. if (pid == nullptr)
  1428. {
  1429. break;
  1430. }
  1431. }
  1432. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1433. break;
  1434. case knopName:
  1435. pid = pnode->AsParseNodeName()->pid;
  1436. if (backgroundPidRef)
  1437. {
  1438. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1439. #if PROFILE_DICTIONARY
  1440. , depth
  1441. #endif
  1442. );
  1443. if (pid == nullptr)
  1444. {
  1445. break;
  1446. }
  1447. }
  1448. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1449. break;
  1450. default:
  1451. Assert(0);
  1452. break;
  1453. }
  1454. };
  1455. scope->ForEachSymbol(bindPidRefs);
  1456. }
  1457. }
  1458. void Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)
  1459. {
  1460. PidRefStack *ref, *nextRef, *lastRef = nullptr;
  1461. Js::LocalFunctionId funcId = GetCurrentFunctionNode()->functionId;
  1462. Assert(sym);
  1463. if (pid->GetIsModuleExport() && IsTopLevelModuleFunc())
  1464. {
  1465. sym->SetIsModuleExportStorage(true);
  1466. }
  1467. bool hasFuncAssignment = sym->GetHasFuncAssignment();
  1468. bool doesEscape = false;
  1469. for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)
  1470. {
  1471. // Fix up sym* on PID ref.
  1472. Assert(!ref->GetSym() || ref->GetSym() == sym);
  1473. nextRef = ref->prev;
  1474. Assert(ref->GetScopeId() >= 0);
  1475. if ((uint)ref->GetScopeId() > maxBlockId)
  1476. {
  1477. lastRef = ref;
  1478. continue;
  1479. }
  1480. ref->SetSym(sym);
  1481. this->RemovePrevPidRef(pid, lastRef);
  1482. if (ref->IsUsedInLdElem())
  1483. {
  1484. sym->SetIsUsedInLdElem(true);
  1485. }
  1486. if (ref->IsAssignment())
  1487. {
  1488. sym->PromoteAssignmentState();
  1489. if (sym->GetIsFormal())
  1490. {
  1491. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  1492. }
  1493. }
  1494. if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1495. {
  1496. Assert(ref->GetFuncScopeId() > funcId);
  1497. sym->SetHasNonLocalReference();
  1498. if (ref->IsDynamicBinding())
  1499. {
  1500. sym->SetNeedsScopeObject();
  1501. }
  1502. }
  1503. if (ref->IsFuncAssignment())
  1504. {
  1505. hasFuncAssignment = true;
  1506. }
  1507. if (ref->IsEscape())
  1508. {
  1509. doesEscape = true;
  1510. }
  1511. if (m_currentNodeFunc && doesEscape && hasFuncAssignment)
  1512. {
  1513. if (m_sourceContextInfo ?
  1514. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1515. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1516. {
  1517. m_currentNodeFunc->SetNestedFuncEscapes();
  1518. }
  1519. }
  1520. if (ref->GetScopeId() == blockId)
  1521. {
  1522. break;
  1523. }
  1524. }
  1525. }
  1526. void Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)
  1527. {
  1528. if (m_currentNodeFunc == nullptr)
  1529. {
  1530. return;
  1531. }
  1532. if (pnode && pnode->nop == knopFncDecl)
  1533. {
  1534. this->SetNestedFuncEscapes();
  1535. }
  1536. else if (pToken->pid)
  1537. {
  1538. PidRefStack *pidRef = pToken->pid->GetTopRef();
  1539. if (pidRef->sym)
  1540. {
  1541. if (pidRef->sym->GetSymbolType() == STFunction)
  1542. {
  1543. this->SetNestedFuncEscapes();
  1544. }
  1545. }
  1546. else
  1547. {
  1548. pidRef->isEscape = true;
  1549. }
  1550. }
  1551. }
  1552. void Parser::SetNestedFuncEscapes() const
  1553. {
  1554. if (m_sourceContextInfo ?
  1555. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1556. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1557. {
  1558. m_currentNodeFunc->SetNestedFuncEscapes();
  1559. }
  1560. }
  1561. void Parser::PopStmt(StmtNest *pStmt)
  1562. {
  1563. Assert(pStmt == m_pstmtCur);
  1564. SetCurrentStatement(m_pstmtCur->pstmtOuter);
  1565. }
  1566. BlockInfoStack *Parser::PushBlockInfo(ParseNodeBlock * pnodeBlock)
  1567. {
  1568. BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));
  1569. Assert(nullptr != newBlockInfo);
  1570. newBlockInfo->pnodeBlock = pnodeBlock;
  1571. newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;
  1572. newBlockInfo->m_ppnodeLex = &pnodeBlock->pnodeLexVars;
  1573. if (pnodeBlock->blockType != PnodeBlockType::Regular)
  1574. {
  1575. newBlockInfo->pBlockInfoFunction = newBlockInfo;
  1576. }
  1577. else
  1578. {
  1579. Assert(m_currentBlockInfo);
  1580. newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;
  1581. }
  1582. m_currentBlockInfo = newBlockInfo;
  1583. return newBlockInfo;
  1584. }
  1585. void Parser::PopBlockInfo()
  1586. {
  1587. Assert(m_currentBlockInfo);
  1588. PopDynamicBlock();
  1589. m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1590. }
  1591. void Parser::PushDynamicBlock()
  1592. {
  1593. Assert(GetCurrentBlock());
  1594. int blockId = GetCurrentBlock()->blockId;
  1595. if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)
  1596. {
  1597. return;
  1598. }
  1599. BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));
  1600. if (nullptr == info)
  1601. {
  1602. Error(ERRnoMemory);
  1603. }
  1604. info->id = blockId;
  1605. info->prev = m_currentDynamicBlock;
  1606. m_currentDynamicBlock = info;
  1607. }
  1608. void Parser::PopDynamicBlock()
  1609. {
  1610. int blockId = GetCurrentDynamicBlockId();
  1611. if (GetCurrentBlock()->blockId != blockId || blockId == -1)
  1612. {
  1613. return;
  1614. }
  1615. Assert(m_currentDynamicBlock);
  1616. this->GetHashTbl()->VisitPids([&](IdentPtr pid) {
  1617. for (PidRefStack *ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = ref->prev)
  1618. {
  1619. ref->SetDynamicBinding();
  1620. }
  1621. });
  1622. m_currentDynamicBlock = m_currentDynamicBlock->prev;
  1623. }
  1624. int Parser::GetCurrentDynamicBlockId() const
  1625. {
  1626. return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;
  1627. }
  1628. ParseNodeFnc *Parser::GetCurrentFunctionNode()
  1629. {
  1630. if (m_currentNodeDeferredFunc != nullptr)
  1631. {
  1632. return m_currentNodeDeferredFunc;
  1633. }
  1634. else if (m_currentNodeFunc != nullptr)
  1635. {
  1636. return m_currentNodeFunc;
  1637. }
  1638. else
  1639. {
  1640. AssertMsg(GetFunctionBlock()->blockType == PnodeBlockType::Global,
  1641. "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'");
  1642. return m_currentNodeProg;
  1643. }
  1644. }
  1645. ParseNodeFnc *Parser::GetCurrentNonLambdaFunctionNode()
  1646. {
  1647. if (m_currentNodeNonLambdaDeferredFunc != nullptr)
  1648. {
  1649. return m_currentNodeNonLambdaDeferredFunc;
  1650. }
  1651. return m_currentNodeNonLambdaFunc;
  1652. }
  1653. void Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)
  1654. {
  1655. Assert(regexPattern);
  1656. // ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator
  1657. if (!m_registeredRegexPatterns.PrependNoThrow(m_tempGuestArena->GetAllocator(), regexPattern))
  1658. {
  1659. Parser::Error(ERRnoMemory);
  1660. }
  1661. }
  1662. void Parser::CaptureState(ParserState *state)
  1663. {
  1664. Assert(state != nullptr);
  1665. state->m_funcInArraySave = m_funcInArray;
  1666. state->m_funcInArrayDepthSave = m_funcInArrayDepth;
  1667. state->m_nestedCountSave = *m_pnestedCount;
  1668. state->m_ppnodeScopeSave = m_ppnodeScope;
  1669. state->m_ppnodeExprScopeSave = m_ppnodeExprScope;
  1670. state->m_pCurrentAstSizeSave = m_pCurrentAstSize;
  1671. state->m_nextBlockId = m_nextBlockId;
  1672. Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);
  1673. Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);
  1674. #if DEBUG
  1675. state->m_currentBlockInfo = m_currentBlockInfo;
  1676. #endif
  1677. }
  1678. void Parser::RestoreStateFrom(ParserState *state)
  1679. {
  1680. Assert(state != nullptr);
  1681. Assert(state->m_currentBlockInfo == m_currentBlockInfo);
  1682. m_funcInArray = state->m_funcInArraySave;
  1683. m_funcInArrayDepth = state->m_funcInArrayDepthSave;
  1684. *m_pnestedCount = state->m_nestedCountSave;
  1685. m_pCurrentAstSize = state->m_pCurrentAstSizeSave;
  1686. m_nextBlockId = state->m_nextBlockId;
  1687. if (state->m_ppnodeScopeSave != nullptr)
  1688. {
  1689. *state->m_ppnodeScopeSave = nullptr;
  1690. }
  1691. if (state->m_ppnodeExprScopeSave != nullptr)
  1692. {
  1693. *state->m_ppnodeExprScopeSave = nullptr;
  1694. }
  1695. m_ppnodeScope = state->m_ppnodeScopeSave;
  1696. m_ppnodeExprScope = state->m_ppnodeExprScopeSave;
  1697. }
  1698. void Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1699. ParseNode * pnodeAdd)
  1700. {
  1701. AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);
  1702. pnodeAdd->SetIsInList();
  1703. }
  1704. void Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1705. ParseNode * pnodeAdd)
  1706. {
  1707. Assert(!this->m_deferringAST);
  1708. if (nullptr == *pppnodeLast)
  1709. {
  1710. // should be an empty list
  1711. Assert(nullptr == *ppnodeList);
  1712. *ppnodeList = pnodeAdd;
  1713. *pppnodeLast = ppnodeList;
  1714. }
  1715. else
  1716. {
  1717. //
  1718. Assert(*ppnodeList);
  1719. Assert(**pppnodeLast);
  1720. ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);
  1721. **pppnodeLast = pnodeT;
  1722. *pppnodeLast = &pnodeT->AsParseNodeBin()->pnode2;
  1723. }
  1724. }
  1725. // Check reference to "arguments" that indicates the object may escape.
  1726. void Parser::CheckArguments(ParseNodePtr pnode)
  1727. {
  1728. if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))
  1729. {
  1730. m_currentNodeFunc->SetHasHeapArguments();
  1731. }
  1732. }
  1733. // Check use of "arguments" that requires instantiation of the object.
  1734. void Parser::CheckArgumentsUse(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1735. {
  1736. if (pid == wellKnownPropertyPids.arguments)
  1737. {
  1738. if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)
  1739. {
  1740. pnodeFnc->SetUsesArguments(TRUE);
  1741. }
  1742. else
  1743. {
  1744. m_UsesArgumentsAtGlobal = true;
  1745. }
  1746. }
  1747. }
  1748. void Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)
  1749. {
  1750. if (pid != nullptr)
  1751. {
  1752. // In strict mode, 'eval' / 'arguments' cannot be assigned to.
  1753. if (pid == wellKnownPropertyPids.eval)
  1754. {
  1755. Error(ERREvalUsage, pnode);
  1756. }
  1757. if (pid == wellKnownPropertyPids.arguments)
  1758. {
  1759. Error(ERRArgsUsage, pnode);
  1760. }
  1761. }
  1762. }
  1763. void Parser::ReduceDeferredScriptLength(size_t chars)
  1764. {
  1765. // If we're in deferred mode, subtract the given char count from the total length,
  1766. // and see if this puts us under the deferral threshold.
  1767. if (((m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse)) == (fscrCanDeferFncParse | fscrWillDeferFncParse)) &&
  1768. (
  1769. PHASE_OFF1(Js::DeferEventHandlersPhase) ||
  1770. (m_grfscr & fscrGlobalCode)
  1771. )
  1772. )
  1773. {
  1774. if (m_length > chars)
  1775. {
  1776. m_length -= chars;
  1777. }
  1778. else
  1779. {
  1780. m_length = 0;
  1781. }
  1782. if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))
  1783. {
  1784. // Stop deferring.
  1785. m_grfscr &= ~fscrWillDeferFncParse;
  1786. m_stoppedDeferredParse = TRUE;
  1787. }
  1788. }
  1789. }
  1790. void Parser::EnsureStackAvailable()
  1791. {
  1792. bool isInterrupt = false;
  1793. if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile, &isInterrupt))
  1794. {
  1795. Error(isInterrupt ? E_ABORT : VBSERR_OutOfStack);
  1796. }
  1797. }
  1798. void Parser::ThrowNewTargetSyntaxErrForGlobalScope()
  1799. {
  1800. // If we are parsing a previously deferred function, we can skip throwing the SyntaxError for `new.target` at global scope.
  1801. // If we are at global scope, we would have thrown a SyntaxError when we did the Upfront parse pass and we would not have
  1802. // deferred the function in order to come back now and reparse it.
  1803. if (m_parseType == ParseType_Deferred)
  1804. {
  1805. return;
  1806. }
  1807. if (GetCurrentNonLambdaFunctionNode() != nullptr)
  1808. {
  1809. return;
  1810. }
  1811. if ((this->m_grfscr & fscrEval) != 0)
  1812. {
  1813. Js::JavascriptFunction * caller = nullptr;
  1814. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  1815. {
  1816. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  1817. Assert(callerBody);
  1818. if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))
  1819. {
  1820. return;
  1821. }
  1822. }
  1823. }
  1824. Error(ERRInvalidNewTarget);
  1825. }
  1826. template<bool buildAST>
  1827. IdentPtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)
  1828. {
  1829. AssertMsg(metaParentKeyword == tkNEW, "Only supported for tkNEW parent keywords");
  1830. AssertMsg(this->m_token.tk == tkDot, "We must be currently sitting on the dot after the parent keyword");
  1831. this->GetScanner()->Scan();
  1832. if (this->m_token.tk == tkID && this->m_token.GetIdentifier(this->GetHashTbl()) == this->GetTargetPid())
  1833. {
  1834. ThrowNewTargetSyntaxErrForGlobalScope();
  1835. if (pfCanAssign)
  1836. {
  1837. *pfCanAssign = FALSE;
  1838. }
  1839. return wellKnownPropertyPids._newTarget;
  1840. }
  1841. else
  1842. {
  1843. Error(ERRsyntax);
  1844. }
  1845. }
  1846. template<bool buildAST>
  1847. void Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)
  1848. {
  1849. Assert(m_token.tk == tkLCurly);
  1850. Assert(importOrExportEntryList != nullptr);
  1851. this->GetScanner()->Scan();
  1852. while (m_token.tk != tkRCurly && m_token.tk != tkEOF)
  1853. {
  1854. tokens firstToken = m_token.tk;
  1855. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1856. {
  1857. Error(ERRsyntax);
  1858. }
  1859. IdentPtr identifierName = m_token.GetIdentifier(this->GetHashTbl());
  1860. IdentPtr identifierAs = identifierName;
  1861. this->GetScanner()->Scan();
  1862. if (m_token.tk == tkID)
  1863. {
  1864. // We have the pattern "IdentifierName as"
  1865. if (wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  1866. {
  1867. Error(ERRsyntax);
  1868. }
  1869. this->GetScanner()->Scan();
  1870. // If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.
  1871. if (!isExportClause)
  1872. {
  1873. ChkCurTokNoScan(tkID, ERRsyntax);
  1874. }
  1875. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1876. {
  1877. Error(ERRsyntax);
  1878. }
  1879. identifierAs = m_token.GetIdentifier(this->GetHashTbl());
  1880. // Scan to the next token.
  1881. this->GetScanner()->Scan();
  1882. }
  1883. else if (!isExportClause && firstToken != tkID)
  1884. {
  1885. // If we are parsing an import statement and this ImportSpecifier clause did not have
  1886. // 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.
  1887. Error(ERRsyntax);
  1888. }
  1889. if (m_token.tk == tkComma)
  1890. {
  1891. // Consume a trailing comma
  1892. this->GetScanner()->Scan();
  1893. }
  1894. if (buildAST)
  1895. {
  1896. // The name we will use 'as' this import/export is a binding identifier in import statements.
  1897. if (!isExportClause)
  1898. {
  1899. CreateModuleImportDeclNode(identifierAs);
  1900. AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);
  1901. }
  1902. else
  1903. {
  1904. identifierName->SetIsModuleExport();
  1905. AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr);
  1906. }
  1907. }
  1908. }
  1909. // Final token in a named import or export clause must be a '}'
  1910. ChkCurTokNoScan(tkRCurly, ERRsyntax);
  1911. }
  1912. IdentPtrList* Parser::GetRequestedModulesList()
  1913. {
  1914. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1915. }
  1916. ModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()
  1917. {
  1918. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  1919. }
  1920. ModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()
  1921. {
  1922. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  1923. }
  1924. ModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()
  1925. {
  1926. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  1927. }
  1928. ModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()
  1929. {
  1930. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  1931. }
  1932. IdentPtrList* Parser::EnsureRequestedModulesList()
  1933. {
  1934. if (m_currentNodeProg->AsParseNodeModule()->requestedModules == nullptr)
  1935. {
  1936. m_currentNodeProg->AsParseNodeModule()->requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);
  1937. }
  1938. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1939. }
  1940. ModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()
  1941. {
  1942. if (m_currentNodeProg->AsParseNodeModule()->importEntries == nullptr)
  1943. {
  1944. m_currentNodeProg->AsParseNodeModule()->importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1945. }
  1946. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  1947. }
  1948. ModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()
  1949. {
  1950. if (m_currentNodeProg->AsParseNodeModule()->localExportEntries == nullptr)
  1951. {
  1952. m_currentNodeProg->AsParseNodeModule()->localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1953. }
  1954. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  1955. }
  1956. ModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()
  1957. {
  1958. if (m_currentNodeProg->AsParseNodeModule()->indirectExportEntries == nullptr)
  1959. {
  1960. m_currentNodeProg->AsParseNodeModule()->indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1961. }
  1962. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  1963. }
  1964. ModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()
  1965. {
  1966. if (m_currentNodeProg->AsParseNodeModule()->starExportEntries == nullptr)
  1967. {
  1968. m_currentNodeProg->AsParseNodeModule()->starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  1969. }
  1970. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  1971. }
  1972. void Parser::AddModuleSpecifier(IdentPtr moduleRequest)
  1973. {
  1974. IdentPtrList* requestedModulesList = EnsureRequestedModulesList();
  1975. if (!requestedModulesList->Has(moduleRequest))
  1976. {
  1977. requestedModulesList->Prepend(moduleRequest);
  1978. }
  1979. }
  1980. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)
  1981. {
  1982. if (importOrExportEntry->exportName != nullptr)
  1983. {
  1984. CheckForDuplicateExportEntry(importOrExportEntryList, importOrExportEntry->exportName);
  1985. }
  1986. importOrExportEntryList->Prepend(*importOrExportEntry);
  1987. return importOrExportEntry;
  1988. }
  1989. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest)
  1990. {
  1991. ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);
  1992. importOrExportEntry->importName = importName;
  1993. importOrExportEntry->localName = localName;
  1994. importOrExportEntry->exportName = exportName;
  1995. importOrExportEntry->moduleRequest = moduleRequest;
  1996. return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);
  1997. }
  1998. void Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)
  1999. {
  2000. AssertOrFailFast(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);
  2001. IdentPtr localName = varDeclNode->AsParseNodeVar()->pid;
  2002. varDeclNode->AsParseNodeVar()->sym->SetIsModuleExportStorage(true);
  2003. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2004. }
  2005. void Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)
  2006. {
  2007. ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)
  2008. {
  2009. if (exportName == exportEntry.exportName)
  2010. {
  2011. return true;
  2012. }
  2013. return false;
  2014. });
  2015. if (findResult != nullptr)
  2016. {
  2017. Error(ERRsyntax);
  2018. }
  2019. }
  2020. template<bool buildAST>
  2021. void Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)
  2022. {
  2023. bool parsedNamespaceOrNamedImport = false;
  2024. switch (m_token.tk)
  2025. {
  2026. case tkID:
  2027. // This is the default binding identifier.
  2028. // If we already saw a comma in the import clause, this is a syntax error.
  2029. if (parsingAfterComma)
  2030. {
  2031. Error(ERRsyntax);
  2032. }
  2033. if (buildAST)
  2034. {
  2035. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2036. IdentPtr importName = wellKnownPropertyPids._default;
  2037. CreateModuleImportDeclNode(localName);
  2038. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2039. }
  2040. break;
  2041. case tkLCurly:
  2042. // This begins a list of named imports.
  2043. ParseNamedImportOrExportClause<buildAST>(importEntryList, false);
  2044. parsedNamespaceOrNamedImport = true;
  2045. break;
  2046. case tkStar:
  2047. // This begins a namespace import clause.
  2048. // "* as ImportedBinding"
  2049. // Token following * must be the identifier 'as'
  2050. this->GetScanner()->Scan();
  2051. if (m_token.tk != tkID || wellKnownPropertyPids.as != m_token.GetIdentifier(this->GetHashTbl()))
  2052. {
  2053. Error(ERRsyntax);
  2054. }
  2055. // Token following 'as' must be a binding identifier.
  2056. this->GetScanner()->Scan();
  2057. ChkCurTokNoScan(tkID, ERRsyntax);
  2058. if (buildAST)
  2059. {
  2060. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2061. IdentPtr importName = wellKnownPropertyPids._star;
  2062. CreateModuleImportDeclNode(localName);
  2063. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2064. }
  2065. parsedNamespaceOrNamedImport = true;
  2066. break;
  2067. default:
  2068. Error(ERRsyntax);
  2069. }
  2070. this->GetScanner()->Scan();
  2071. if (m_token.tk == tkComma)
  2072. {
  2073. // There cannot be more than one comma in a module import clause.
  2074. // There cannot be a namespace import or named imports list on the left of the comma in a module import clause.
  2075. if (parsingAfterComma || parsedNamespaceOrNamedImport)
  2076. {
  2077. Error(ERRsyntax);
  2078. }
  2079. this->GetScanner()->Scan();
  2080. ParseImportClause<buildAST>(importEntryList, true);
  2081. }
  2082. }
  2083. bool Parser::IsImportOrExportStatementValidHere()
  2084. {
  2085. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2086. // Import must be located in the top scope of the module body.
  2087. return curFunc->nop == knopFncDecl
  2088. && curFunc->IsModule()
  2089. && this->m_currentBlockInfo->pnodeBlock == curFunc->pnodeBodyScope
  2090. && (this->m_grfscr & fscrEvalCode) != fscrEvalCode
  2091. && this->m_tryCatchOrFinallyDepth == 0
  2092. && !this->m_disallowImportExportStmt;
  2093. }
  2094. bool Parser::IsTopLevelModuleFunc()
  2095. {
  2096. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2097. return curFunc->nop == knopFncDecl && curFunc->IsModule();
  2098. }
  2099. template<bool buildAST> ParseNodePtr Parser::ParseImportCall()
  2100. {
  2101. this->GetScanner()->Scan();
  2102. ParseNodePtr specifier = ParseExpr<buildAST>(koplCma, nullptr, /* fAllowIn */FALSE, /* fAllowEllipsis */FALSE);
  2103. if (m_token.tk != tkRParen)
  2104. {
  2105. Error(ERRnoRparen);
  2106. }
  2107. this->GetScanner()->Scan();
  2108. return buildAST ? CreateCallNode(knopCall, CreateNodeForOpT<knopImport>(), specifier) : nullptr;
  2109. }
  2110. template<bool buildAST>
  2111. ParseNodePtr Parser::ParseImport()
  2112. {
  2113. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2114. Assert(m_token.tk == tkIMPORT);
  2115. RestorePoint parsedImport;
  2116. this->GetScanner()->Capture(&parsedImport);
  2117. this->GetScanner()->Scan();
  2118. // import()
  2119. if (m_token.tk == tkLParen)
  2120. {
  2121. if (!m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2122. {
  2123. Error(ERRsyntax);
  2124. }
  2125. ParseNodePtr pnode = ParseImportCall<buildAST>();
  2126. BOOL fCanAssign;
  2127. IdentToken token;
  2128. return ParsePostfixOperators<buildAST>(pnode, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  2129. }
  2130. this->GetScanner()->SeekTo(parsedImport);
  2131. if (!IsImportOrExportStatementValidHere())
  2132. {
  2133. Error(ERRInvalidModuleImportOrExport);
  2134. }
  2135. // We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.
  2136. this->GetScanner()->Scan();
  2137. if (m_token.tk == tkStrCon)
  2138. {
  2139. // This import declaration has no import clause.
  2140. // "import ModuleSpecifier;"
  2141. if (buildAST)
  2142. {
  2143. AddModuleSpecifier(m_token.GetStr());
  2144. }
  2145. // Scan past the module identifier.
  2146. this->GetScanner()->Scan();
  2147. }
  2148. else
  2149. {
  2150. ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);
  2151. // Parse the import clause (default binding can only exist before the comma).
  2152. ParseImportClause<buildAST>(&importEntryList);
  2153. // Token following import clause must be the identifier 'from'
  2154. IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);
  2155. if (buildAST)
  2156. {
  2157. Assert(moduleSpecifier != nullptr);
  2158. AddModuleSpecifier(moduleSpecifier);
  2159. importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {
  2160. importEntry.moduleRequest = moduleSpecifier;
  2161. AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);
  2162. });
  2163. }
  2164. importEntryList.Clear();
  2165. }
  2166. // Import statement is actually a nop, we hoist all the imported bindings to the top of the module.
  2167. return nullptr;
  2168. }
  2169. template<bool buildAST>
  2170. IdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)
  2171. {
  2172. IdentPtr moduleSpecifier = nullptr;
  2173. if (m_token.tk == tkID && wellKnownPropertyPids.from == m_token.GetIdentifier(this->GetHashTbl()))
  2174. {
  2175. this->GetScanner()->Scan();
  2176. // Token following the 'from' token must be a string constant - the module specifier.
  2177. ChkCurTokNoScan(tkStrCon, ERRsyntax);
  2178. if (buildAST)
  2179. {
  2180. moduleSpecifier = m_token.GetStr();
  2181. }
  2182. this->GetScanner()->Scan();
  2183. }
  2184. else if (throwIfNotFound)
  2185. {
  2186. Error(ERRsyntax);
  2187. }
  2188. return moduleSpecifier;
  2189. }
  2190. template<bool buildAST>
  2191. ParseNodePtr Parser::ParseDefaultExportClause()
  2192. {
  2193. Assert(m_token.tk == tkDEFAULT);
  2194. this->GetScanner()->Scan();
  2195. ParseNodePtr pnode = nullptr;
  2196. ushort flags = fFncNoFlgs;
  2197. switch (m_token.tk)
  2198. {
  2199. case tkCLASS:
  2200. {
  2201. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2202. {
  2203. goto LDefault;
  2204. }
  2205. // Before we parse the class itself we need to know if the class has an identifier name.
  2206. // If it does, we'll treat this class as an ordinary class declaration which will bind
  2207. // it to that name. Otherwise the class should parse as a nameless class expression and
  2208. // bind only to the export binding.
  2209. BOOL classHasName = false;
  2210. RestorePoint parsedClass;
  2211. this->GetScanner()->Capture(&parsedClass);
  2212. this->GetScanner()->Scan();
  2213. if (m_token.tk == tkID)
  2214. {
  2215. classHasName = true;
  2216. }
  2217. this->GetScanner()->SeekTo(parsedClass);
  2218. ParseNodeClass * pnodeClass;
  2219. pnode = pnodeClass = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);
  2220. if (buildAST)
  2221. {
  2222. AnalysisAssert(pnode != nullptr);
  2223. Assert(pnode->nop == knopClassDecl);
  2224. pnodeClass->SetIsDefaultModuleExport(true);
  2225. }
  2226. break;
  2227. }
  2228. case tkID:
  2229. // If we parsed an async token, it could either modify the next token (if it is a
  2230. // function token) or it could be an identifier (let async = 0; export default async;).
  2231. // To handle both cases, when we parse an async token we need to keep the parser state
  2232. // and rewind if the next token is not function.
  2233. if (wellKnownPropertyPids.async == m_token.GetIdentifier(this->GetHashTbl()))
  2234. {
  2235. RestorePoint parsedAsync;
  2236. this->GetScanner()->Capture(&parsedAsync);
  2237. this->GetScanner()->Scan();
  2238. if (m_token.tk == tkFUNCTION)
  2239. {
  2240. // Token after async is function, consume the async token and continue to parse the
  2241. // function as an async function.
  2242. flags |= fFncAsync;
  2243. goto LFunction;
  2244. }
  2245. // Token after async is not function, no idea what the async token is supposed to mean
  2246. // so rewind and let the default case handle it.
  2247. this->GetScanner()->SeekTo(parsedAsync);
  2248. }
  2249. goto LDefault;
  2250. break;
  2251. case tkFUNCTION:
  2252. {
  2253. LFunction:
  2254. // We just parsed a function token but we need to figure out if the function
  2255. // has an identifier name or not before we call the helper.
  2256. RestorePoint parsedFunction;
  2257. this->GetScanner()->Capture(&parsedFunction);
  2258. this->GetScanner()->Scan();
  2259. if (m_token.tk == tkStar)
  2260. {
  2261. // If we saw 'function*' that indicates we are going to parse a generator,
  2262. // but doesn't tell us if the generator has an identifier or not.
  2263. // Skip the '*' token for now as it doesn't matter yet.
  2264. this->GetScanner()->Scan();
  2265. }
  2266. // We say that if the function has an identifier name, it is a 'normal' declaration
  2267. // and should create a binding to that identifier as well as one for our default export.
  2268. if (m_token.tk == tkID)
  2269. {
  2270. flags |= fFncDeclaration;
  2271. }
  2272. else
  2273. {
  2274. flags |= fFncNoName;
  2275. }
  2276. // Rewind back to the function token and let the helper handle the parsing.
  2277. this->GetScanner()->SeekTo(parsedFunction);
  2278. pnode = ParseFncDeclCheckScope<buildAST>(flags);
  2279. if (buildAST)
  2280. {
  2281. AnalysisAssert(pnode != nullptr);
  2282. Assert(pnode->nop == knopFncDecl);
  2283. pnode->AsParseNodeFnc()->SetIsDefaultModuleExport(true);
  2284. }
  2285. break;
  2286. }
  2287. default:
  2288. LDefault:
  2289. {
  2290. ParseNodePtr pnodeExpression = ParseExpr<buildAST>();
  2291. // Consider: Can we detect this syntax error earlier?
  2292. if (pnodeExpression && pnodeExpression->nop == knopComma)
  2293. {
  2294. Error(ERRsyntax);
  2295. }
  2296. if (buildAST)
  2297. {
  2298. AnalysisAssert(pnodeExpression != nullptr);
  2299. // Mark this node as the default module export. We need to make sure it is put into the correct
  2300. // module export slot when we emit the node.
  2301. ParseNodeExportDefault * pnodeExportDefault;
  2302. pnode = pnodeExportDefault = CreateNodeForOpT<knopExportDefault>();
  2303. pnode->AsParseNodeExportDefault()->pnodeExpr = pnodeExpression;
  2304. }
  2305. break;
  2306. }
  2307. }
  2308. IdentPtr exportName = wellKnownPropertyPids._default;
  2309. IdentPtr localName = wellKnownPropertyPids._starDefaultStar;
  2310. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, exportName, nullptr);
  2311. return pnode;
  2312. }
  2313. template<bool buildAST>
  2314. ParseNodePtr Parser::ParseExportDeclaration(bool *needTerminator)
  2315. {
  2316. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2317. Assert(m_token.tk == tkEXPORT);
  2318. if (!IsImportOrExportStatementValidHere())
  2319. {
  2320. Error(ERRInvalidModuleImportOrExport);
  2321. }
  2322. ParseNodePtr pnode = nullptr;
  2323. IdentPtr moduleIdentifier = nullptr;
  2324. tokens declarationType;
  2325. if (needTerminator != nullptr)
  2326. {
  2327. *needTerminator = false;
  2328. }
  2329. // We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.
  2330. this->GetScanner()->Scan();
  2331. switch (m_token.tk)
  2332. {
  2333. case tkStar:
  2334. this->GetScanner()->Scan();
  2335. // A star token in an export declaration must be followed by a from clause which begins with a token 'from'.
  2336. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);
  2337. if (buildAST)
  2338. {
  2339. Assert(moduleIdentifier != nullptr);
  2340. AddModuleSpecifier(moduleIdentifier);
  2341. IdentPtr importName = wellKnownPropertyPids._star;
  2342. AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), importName, nullptr, nullptr, moduleIdentifier);
  2343. }
  2344. if (needTerminator != nullptr)
  2345. {
  2346. *needTerminator = true;
  2347. }
  2348. break;
  2349. case tkLCurly:
  2350. {
  2351. ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);
  2352. ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);
  2353. this->GetScanner()->Scan();
  2354. // Export clause may be followed by a from clause.
  2355. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);
  2356. if (buildAST)
  2357. {
  2358. if (moduleIdentifier != nullptr)
  2359. {
  2360. AddModuleSpecifier(moduleIdentifier);
  2361. }
  2362. exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {
  2363. if (moduleIdentifier != nullptr)
  2364. {
  2365. exportEntry.moduleRequest = moduleIdentifier;
  2366. // We need to swap localname and importname when this is a re-export.
  2367. exportEntry.importName = exportEntry.localName;
  2368. exportEntry.localName = nullptr;
  2369. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);
  2370. }
  2371. else
  2372. {
  2373. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);
  2374. }
  2375. });
  2376. exportEntryList.Clear();
  2377. }
  2378. }
  2379. if (needTerminator != nullptr)
  2380. {
  2381. *needTerminator = true;
  2382. }
  2383. break;
  2384. case tkID:
  2385. {
  2386. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  2387. if (wellKnownPropertyPids.let == pid)
  2388. {
  2389. declarationType = tkLET;
  2390. goto ParseVarDecl;
  2391. }
  2392. if (wellKnownPropertyPids.async == pid && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2393. {
  2394. // In module export statements, async token is only valid if it's followed by function.
  2395. // We need to check here because ParseStatement would think 'async = 20' is a var decl.
  2396. RestorePoint parsedAsync;
  2397. this->GetScanner()->Capture(&parsedAsync);
  2398. this->GetScanner()->Scan();
  2399. if (m_token.tk == tkFUNCTION)
  2400. {
  2401. // Token after async is function, rewind to the async token and let ParseStatement handle it.
  2402. this->GetScanner()->SeekTo(parsedAsync);
  2403. goto ParseFunctionDecl;
  2404. }
  2405. // Token after async is not function, it's a syntax error.
  2406. }
  2407. goto ErrorToken;
  2408. }
  2409. case tkVAR:
  2410. case tkLET:
  2411. case tkCONST:
  2412. {
  2413. declarationType = m_token.tk;
  2414. ParseVarDecl:
  2415. this->GetScanner()->Scan();
  2416. pnode = ParseVariableDeclaration<buildAST>(declarationType, this->GetScanner()->IchMinTok());
  2417. if (buildAST)
  2418. {
  2419. ForEachItemInList(pnode, [&](ParseNodePtr item) {
  2420. if (item->nop == knopAsg)
  2421. {
  2422. Parser::MapBindIdentifier(item, [&](ParseNodePtr subItem)
  2423. {
  2424. AddModuleLocalExportEntry(subItem);
  2425. });
  2426. }
  2427. else
  2428. {
  2429. AddModuleLocalExportEntry(item);
  2430. }
  2431. });
  2432. }
  2433. }
  2434. break;
  2435. case tkFUNCTION:
  2436. case tkCLASS:
  2437. {
  2438. ParseFunctionDecl:
  2439. pnode = ParseStatement<buildAST>();
  2440. if (buildAST)
  2441. {
  2442. IdentPtr localName;
  2443. if (pnode->nop == knopClassDecl)
  2444. {
  2445. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  2446. pnodeClass->pnodeDeclName->sym->SetIsModuleExportStorage(true);
  2447. localName = pnodeClass->pnodeName->pid;
  2448. }
  2449. else
  2450. {
  2451. Assert(pnode->nop == knopFncDecl);
  2452. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  2453. pnodeFnc->GetFuncSymbol()->SetIsModuleExportStorage(true);
  2454. localName = pnodeFnc->pid;
  2455. }
  2456. Assert(localName != nullptr);
  2457. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2458. }
  2459. }
  2460. break;
  2461. case tkDEFAULT:
  2462. {
  2463. pnode = ParseDefaultExportClause<buildAST>();
  2464. }
  2465. break;
  2466. default:
  2467. {
  2468. ErrorToken:
  2469. Error(ERRsyntax);
  2470. }
  2471. }
  2472. return pnode;
  2473. }
  2474. /***************************************************************************
  2475. Parse an expression term.
  2476. ***************************************************************************/
  2477. template<bool buildAST>
  2478. ParseNodePtr Parser::ParseTerm(BOOL fAllowCall,
  2479. LPCOLESTR pNameHint,
  2480. uint32 *pHintLength,
  2481. uint32 *pShortNameOffset,
  2482. _Inout_opt_ IdentToken* pToken /*= nullptr*/,
  2483. bool fUnaryOrParen /*= false*/,
  2484. BOOL fCanAssignToCall /*= TRUE*/,
  2485. _Out_opt_ BOOL* pfCanAssign /*= nullptr*/,
  2486. _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/,
  2487. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/,
  2488. _Inout_opt_ charcount_t *plastRParen /*= nullptr*/)
  2489. {
  2490. ParseNodePtr pnode = nullptr;
  2491. PidRefStack *savedTopAsyncRef = nullptr;
  2492. charcount_t ichMin = 0;
  2493. charcount_t ichLim = 0;
  2494. size_t iecpMin = 0;
  2495. size_t iecpLim = 0;
  2496. size_t iuMin;
  2497. IdentToken term;
  2498. BOOL fInNew = FALSE;
  2499. BOOL fCanAssign = TRUE;
  2500. bool isAsyncExpr = false;
  2501. bool isLambdaExpr = false;
  2502. bool isSpecialName = false;
  2503. IdentPtr pid = nullptr;
  2504. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  2505. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);
  2506. switch (m_token.tk)
  2507. {
  2508. case tkID:
  2509. {
  2510. pid = m_token.GetIdentifier(this->GetHashTbl());
  2511. ichMin = this->GetScanner()->IchMinTok();
  2512. iecpMin = this->GetScanner()->IecpMinTok();
  2513. ichLim = this->GetScanner()->IchLimTok();
  2514. iecpLim = this->GetScanner()->IecpLimTok();
  2515. if (pid == wellKnownPropertyPids.async &&
  2516. m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2517. {
  2518. isAsyncExpr = true;
  2519. }
  2520. // Put this into a block to avoid previousAwaitIsKeyword being not initialized after jump to LIdentifier
  2521. {
  2522. bool previousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(isAsyncExpr);
  2523. this->GetScanner()->Scan();
  2524. this->GetScanner()->SetAwaitIsKeywordRegion(previousAwaitIsKeyword);
  2525. }
  2526. // We search for an Async expression (a function declaration or an async lambda expression)
  2527. if (isAsyncExpr && !this->GetScanner()->FHadNewLine())
  2528. {
  2529. if (m_token.tk == tkFUNCTION)
  2530. {
  2531. goto LFunction;
  2532. }
  2533. else if (m_token.tk == tkID || m_token.tk == tkAWAIT)
  2534. {
  2535. isLambdaExpr = true;
  2536. goto LFunction;
  2537. }
  2538. else if (m_token.tk == tkLParen)
  2539. {
  2540. // This is potentially an async arrow function. Save the state of the async references
  2541. // in case it needs to be restored. (Note that the case of a single parameter with no ()'s
  2542. // is detected upstream and need not be handled here.)
  2543. savedTopAsyncRef = pid->GetTopRef();
  2544. }
  2545. }
  2546. CheckArgumentsUse(pid, GetCurrentFunctionNode());
  2547. // Assume this pid is not special - overwrite when we parse a special name
  2548. isSpecialName = false;
  2549. LIdentifier:
  2550. PidRefStack * ref = nullptr;
  2551. // Don't push a reference if this is a single lambda parameter, because we'll reparse with
  2552. // a correct function ID.
  2553. if (m_token.tk != tkDArrow)
  2554. {
  2555. ref = this->PushPidRef(pid);
  2556. }
  2557. if (buildAST)
  2558. {
  2559. if (isSpecialName)
  2560. {
  2561. pnode = CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  2562. }
  2563. else
  2564. {
  2565. pnode = CreateNameNode(pid, ref, ichMin, ichLim);
  2566. }
  2567. }
  2568. else
  2569. {
  2570. // Remember the identifier start and end in case it turns out to be a statement label.
  2571. term.tk = tkID;
  2572. term.pid = pid; // Record the identifier for detection of eval
  2573. term.ichMin = static_cast<charcount_t>(iecpMin);
  2574. term.ichLim = static_cast<charcount_t>(iecpLim);
  2575. }
  2576. break;
  2577. }
  2578. case tkSUPER:
  2579. ichMin = this->GetScanner()->IchMinTok();
  2580. iecpMin = this->GetScanner()->IecpMinTok();
  2581. ichLim = this->GetScanner()->IchLimTok();
  2582. iecpLim = this->GetScanner()->IecpLimTok();
  2583. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2584. {
  2585. goto LUnknown;
  2586. }
  2587. this->GetScanner()->Scan();
  2588. pid = ParseSuper<buildAST>(!!fAllowCall);
  2589. isSpecialName = true;
  2590. // Super reference and super call need to push a pid ref to 'this' even when not building an AST
  2591. ReferenceSpecialName(wellKnownPropertyPids._this, ichMin, ichLim);
  2592. // Super call needs to reference 'new.target'
  2593. if (pid == wellKnownPropertyPids._superConstructor)
  2594. {
  2595. ReferenceSpecialName(wellKnownPropertyPids._newTarget, ichMin, ichLim);
  2596. }
  2597. goto LIdentifier;
  2598. case tkTHIS:
  2599. ichMin = this->GetScanner()->IchMinTok();
  2600. iecpMin = this->GetScanner()->IecpMinTok();
  2601. ichLim = this->GetScanner()->IchLimTok();
  2602. iecpLim = this->GetScanner()->IecpLimTok();
  2603. pid = wellKnownPropertyPids._this;
  2604. this->GetScanner()->Scan();
  2605. isSpecialName = true;
  2606. goto LIdentifier;
  2607. case tkLParen:
  2608. {
  2609. ichMin = this->GetScanner()->IchMinTok();
  2610. iuMin = this->GetScanner()->IecpMinTok();
  2611. // If we are undeferring a function which has deferred stubs, we can check to see if the next deferred stub
  2612. // is a lambda at the current character. If it is, we know this LParen is the beginning of a lambda nested
  2613. // function and we can avoid parsing the next series of tokens as a parenthetical expression and reparsing
  2614. // after finding the => token.
  2615. if (buildAST && m_currDeferredStub != nullptr && GetCurrentFunctionNode() != nullptr && GetCurrentFunctionNode()->nestedCount < m_currDeferredStubCount)
  2616. {
  2617. DeferredFunctionStub* stub = m_currDeferredStub + GetCurrentFunctionNode()->nestedCount;
  2618. if (stub->ichMin == ichMin)
  2619. {
  2620. Assert((stub->fncFlags & kFunctionIsLambda) == kFunctionIsLambda);
  2621. pnode = ParseFncDeclCheckScope<true>(fFncLambda, /* resetParsingSuperRestrictionState*/ false);
  2622. break;
  2623. }
  2624. }
  2625. this->GetScanner()->Scan();
  2626. if (m_token.tk == tkRParen)
  2627. {
  2628. // Empty parens can only be legal as an empty parameter list to a lambda declaration.
  2629. // We're in a lambda if the next token is =>.
  2630. fAllowCall = FALSE;
  2631. this->GetScanner()->Scan();
  2632. // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error
  2633. if (!IsDoingFastScan() && (m_token.tk != tkDArrow || this->GetScanner()->FHadNewLine()))
  2634. {
  2635. Error(ERRsyntax);
  2636. }
  2637. if (buildAST)
  2638. {
  2639. pnode = CreateNodeForOpT<knopEmpty>();
  2640. }
  2641. break;
  2642. }
  2643. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  2644. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  2645. // up function ID's.
  2646. uint saveNextBlockId = m_nextBlockId;
  2647. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  2648. GetCurrentBlock()->blockId = m_nextBlockId++;
  2649. // Push the deferred error state for ellipsis errors. It is possible that another syntax error will occur before we undefer this one.
  2650. bool deferEllipsisErrorSave = m_deferEllipsisError;
  2651. RestorePoint ellipsisErrorLocSave = m_deferEllipsisErrorLoc;
  2652. this->m_funcParenExprDepth++;
  2653. pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen);
  2654. this->m_funcParenExprDepth--;
  2655. if (buildAST && plastRParen)
  2656. {
  2657. *plastRParen = this->GetScanner()->IchLimTok();
  2658. }
  2659. ChkCurTok(tkRParen, ERRnoRparen);
  2660. GetCurrentBlock()->blockId = saveCurrBlockId;
  2661. if (m_token.tk == tkDArrow)
  2662. {
  2663. // We're going to rewind and reinterpret the expression as a parameter list.
  2664. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  2665. m_nextBlockId = saveNextBlockId;
  2666. }
  2667. // Emit a deferred ... error if one was parsed.
  2668. if (m_deferEllipsisError && m_token.tk != tkDArrow)
  2669. {
  2670. this->GetScanner()->SeekTo(m_deferEllipsisErrorLoc);
  2671. Error(ERRInvalidSpreadUse);
  2672. }
  2673. else
  2674. {
  2675. m_deferEllipsisError = false;
  2676. }
  2677. // We didn't error out, so restore the deferred error state.
  2678. m_deferEllipsisError = deferEllipsisErrorSave;
  2679. m_deferEllipsisErrorLoc = ellipsisErrorLocSave;
  2680. break;
  2681. }
  2682. case tkIntCon:
  2683. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2684. {
  2685. Error(ERRES5NoOctal);
  2686. }
  2687. if (buildAST)
  2688. {
  2689. pnode = CreateIntNode(m_token.GetLong());
  2690. }
  2691. fCanAssign = FALSE;
  2692. this->GetScanner()->Scan();
  2693. break;
  2694. case tkFltCon:
  2695. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2696. {
  2697. Error(ERRES5NoOctal);
  2698. }
  2699. if (buildAST)
  2700. {
  2701. ParseNodeFloat * pnodeFloat;
  2702. pnode = pnodeFloat = CreateNodeForOpT<knopFlt>();
  2703. pnodeFloat->dbl = m_token.GetDouble();
  2704. pnodeFloat->maybeInt = m_token.GetDoubleMayBeInt();
  2705. }
  2706. fCanAssign = FALSE;
  2707. this->GetScanner()->Scan();
  2708. break;
  2709. case tkStrCon:
  2710. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2711. {
  2712. Error(ERRES5NoOctal);
  2713. }
  2714. if (buildAST)
  2715. {
  2716. pnode = CreateStrNode(m_token.GetStr());
  2717. }
  2718. else
  2719. {
  2720. // Subtract the string literal length from the total char count for the purpose
  2721. // of deciding whether to defer parsing and byte code generation.
  2722. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok());
  2723. }
  2724. fCanAssign = FALSE;
  2725. this->GetScanner()->Scan();
  2726. break;
  2727. case tkTRUE:
  2728. if (buildAST)
  2729. {
  2730. pnode = CreateNodeForOpT<knopTrue>();
  2731. }
  2732. fCanAssign = FALSE;
  2733. this->GetScanner()->Scan();
  2734. break;
  2735. case tkFALSE:
  2736. if (buildAST)
  2737. {
  2738. pnode = CreateNodeForOpT<knopFalse>();
  2739. }
  2740. fCanAssign = FALSE;
  2741. this->GetScanner()->Scan();
  2742. break;
  2743. case tkNULL:
  2744. if (buildAST)
  2745. {
  2746. pnode = CreateNodeForOpT<knopNull>();
  2747. }
  2748. fCanAssign = FALSE;
  2749. this->GetScanner()->Scan();
  2750. break;
  2751. case tkDiv:
  2752. case tkAsgDiv:
  2753. pnode = ParseRegExp<buildAST>();
  2754. fCanAssign = FALSE;
  2755. this->GetScanner()->Scan();
  2756. break;
  2757. case tkNEW:
  2758. {
  2759. ichMin = this->GetScanner()->IchMinTok();
  2760. iecpMin = this->GetScanner()->IecpMinTok();
  2761. this->GetScanner()->Scan();
  2762. if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2763. {
  2764. pid = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);
  2765. ichLim = this->GetScanner()->IchLimTok();
  2766. iecpLim = this->GetScanner()->IecpLimTok();
  2767. this->GetScanner()->Scan();
  2768. isSpecialName = true;
  2769. goto LIdentifier;
  2770. }
  2771. else
  2772. {
  2773. ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset, nullptr, false, TRUE, nullptr, nullptr, nullptr, plastRParen);
  2774. if (buildAST)
  2775. {
  2776. pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);
  2777. pnode->ichMin = ichMin;
  2778. }
  2779. fInNew = TRUE;
  2780. fCanAssign = FALSE;
  2781. }
  2782. break;
  2783. }
  2784. case tkLBrack:
  2785. {
  2786. ichMin = this->GetScanner()->IchMinTok();
  2787. this->GetScanner()->Scan();
  2788. pnode = ParseArrayLiteral<buildAST>();
  2789. if (buildAST)
  2790. {
  2791. pnode->ichMin = ichMin;
  2792. pnode->ichLim = this->GetScanner()->IchLimTok();
  2793. }
  2794. if (this->m_arrayDepth == 0)
  2795. {
  2796. Assert(this->GetScanner()->IchLimTok() - ichMin > m_funcInArray);
  2797. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - ichMin - this->m_funcInArray);
  2798. this->m_funcInArray = 0;
  2799. this->m_funcInArrayDepth = 0;
  2800. }
  2801. ChkCurTok(tkRBrack, ERRnoRbrack);
  2802. if (!IsES6DestructuringEnabled())
  2803. {
  2804. fCanAssign = FALSE;
  2805. }
  2806. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2807. {
  2808. *pfLikelyPattern = TRUE;
  2809. }
  2810. break;
  2811. }
  2812. case tkLCurly:
  2813. {
  2814. ichMin = this->GetScanner()->IchMinTok();
  2815. this->GetScanner()->ScanForcingPid();
  2816. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);
  2817. if (buildAST)
  2818. {
  2819. pnode = CreateUniNode(knopObject, pnodeMemberList);
  2820. pnode->ichMin = ichMin;
  2821. pnode->ichLim = this->GetScanner()->IchLimTok();
  2822. }
  2823. ChkCurTok(tkRCurly, ERRnoRcurly);
  2824. if (!IsES6DestructuringEnabled())
  2825. {
  2826. fCanAssign = FALSE;
  2827. }
  2828. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2829. {
  2830. *pfLikelyPattern = TRUE;
  2831. }
  2832. break;
  2833. }
  2834. case tkFUNCTION:
  2835. {
  2836. LFunction:
  2837. if (m_grfscr & fscrDeferredFncExpression)
  2838. {
  2839. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  2840. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  2841. // first time we see it.
  2842. //
  2843. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  2844. // token of the source code of the function may not a 'function' token though, so we still need to reset this flag
  2845. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  2846. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  2847. m_grfscr &= ~fscrDeferredFncExpression;
  2848. }
  2849. ushort flags = fFncNoFlgs;
  2850. if (isLambdaExpr)
  2851. {
  2852. flags |= fFncLambda;
  2853. }
  2854. if (isAsyncExpr)
  2855. {
  2856. flags |= fFncAsync;
  2857. }
  2858. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, pNameHint, false, true, fUnaryOrParen);
  2859. if (isAsyncExpr)
  2860. {
  2861. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  2862. pnode->ichMin = ichMin;
  2863. }
  2864. fCanAssign = FALSE;
  2865. break;
  2866. }
  2867. case tkCLASS:
  2868. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2869. {
  2870. pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);
  2871. }
  2872. else
  2873. {
  2874. goto LUnknown;
  2875. }
  2876. fCanAssign = FALSE;
  2877. break;
  2878. case tkStrTmplBasic:
  2879. case tkStrTmplBegin:
  2880. pnode = ParseStringTemplateDecl<buildAST>(nullptr);
  2881. fCanAssign = FALSE;
  2882. break;
  2883. case tkIMPORT:
  2884. if (m_scriptContext->GetConfig()->IsES6ModuleEnabled() && m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2885. {
  2886. this->GetScanner()->Scan();
  2887. ChkCurTokNoScan(tkLParen, ERRnoLparen);
  2888. pnode = ParseImportCall<buildAST>();
  2889. }
  2890. else
  2891. {
  2892. goto LUnknown;
  2893. }
  2894. break;
  2895. #if ENABLE_BACKGROUND_PARSING
  2896. case tkCASE:
  2897. {
  2898. if (!m_doingFastScan)
  2899. {
  2900. goto LUnknown;
  2901. }
  2902. ParseNodePtr pnodeUnused;
  2903. pnode = ParseCase<buildAST>(&pnodeUnused);
  2904. break;
  2905. }
  2906. case tkELSE:
  2907. if (!m_doingFastScan)
  2908. {
  2909. goto LUnknown;
  2910. }
  2911. this->GetScanner()->Scan();
  2912. ParseStatement<buildAST>();
  2913. break;
  2914. #endif
  2915. default:
  2916. LUnknown:
  2917. Error(ERRsyntax);
  2918. break;
  2919. }
  2920. pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, fCanAssignToCall, &fCanAssign, &term, pfIsDotOrIndex);
  2921. if (savedTopAsyncRef != nullptr &&
  2922. this->m_token.tk == tkDArrow)
  2923. {
  2924. // This is an async arrow function; we're going to back up and reparse it.
  2925. // Make sure we don't leave behind a bogus reference to the 'async' identifier.
  2926. for (pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;)
  2927. {
  2928. Assert(pid->GetTopRef() != nullptr);
  2929. pid->RemovePrevPidRef(nullptr);
  2930. }
  2931. }
  2932. // Pass back identifier if requested
  2933. if (pToken && term.tk == tkID)
  2934. {
  2935. *pToken = term;
  2936. }
  2937. if (pfCanAssign)
  2938. {
  2939. *pfCanAssign = fCanAssign;
  2940. }
  2941. return pnode;
  2942. }
  2943. template <bool buildAST>
  2944. ParseNodeRegExp * Parser::ParseRegExp()
  2945. {
  2946. ParseNodeRegExp * pnode = nullptr;
  2947. if (buildAST || IsDoingFastScan())
  2948. {
  2949. this->GetScanner()->RescanRegExp();
  2950. #if ENABLE_BACKGROUND_PARSING
  2951. BOOL saveDeferringAST = this->m_deferringAST;
  2952. if (m_doingFastScan)
  2953. {
  2954. this->m_deferringAST = false;
  2955. }
  2956. #endif
  2957. pnode = CreateNodeForOpT<knopRegExp>();
  2958. pnode->regexPattern = m_token.GetRegex();
  2959. #if ENABLE_BACKGROUND_PARSING
  2960. if (m_doingFastScan)
  2961. {
  2962. this->m_deferringAST = saveDeferringAST;
  2963. this->AddFastScannedRegExpNode(pnode);
  2964. if (!buildAST)
  2965. {
  2966. pnode = nullptr;
  2967. }
  2968. }
  2969. else if (this->IsBackgroundParser())
  2970. {
  2971. Assert(pnode->regexPattern == nullptr);
  2972. this->AddBackgroundRegExpNode(pnode);
  2973. }
  2974. #endif
  2975. }
  2976. else
  2977. {
  2978. this->GetScanner()->RescanRegExpNoAST();
  2979. }
  2980. Assert(m_token.tk == tkRegExp);
  2981. return pnode;
  2982. }
  2983. BOOL Parser::NodeIsEvalName(ParseNodePtr pnode)
  2984. {
  2985. //WOOB 1107758 Special case of indirect eval binds to local scope in standards mode
  2986. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids.eval);
  2987. }
  2988. BOOL Parser::NodeIsSuperName(ParseNodePtr pnode)
  2989. {
  2990. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids._superConstructor);
  2991. }
  2992. BOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)
  2993. {
  2994. return pnode->nop == knopName &&
  2995. pnode->AsParseNodeName()->pid->Cch() == cch &&
  2996. !wmemcmp(pnode->AsParseNodeName()->pid->Psz(), sz, cch);
  2997. }
  2998. BOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)
  2999. {
  3000. for (;;)
  3001. {
  3002. switch (pnode->nop)
  3003. {
  3004. case knopName:
  3005. return (pnode->AsParseNodeName()->pid == pid);
  3006. case knopComma:
  3007. pnode = pnode->AsParseNodeBin()->pnode2;
  3008. break;
  3009. default:
  3010. return FALSE;
  3011. }
  3012. }
  3013. }
  3014. template<bool buildAST>
  3015. ParseNodePtr Parser::ParsePostfixOperators(
  3016. ParseNodePtr pnode,
  3017. BOOL fAllowCall,
  3018. BOOL fInNew,
  3019. BOOL isAsyncExpr,
  3020. BOOL fCanAssignToCallResult,
  3021. BOOL *pfCanAssign,
  3022. _Inout_ IdentToken* pToken,
  3023. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr */)
  3024. {
  3025. uint16 count = 0;
  3026. bool callOfConstants = false;
  3027. if (pfIsDotOrIndex)
  3028. {
  3029. *pfIsDotOrIndex = false;
  3030. }
  3031. for (;;)
  3032. {
  3033. uint16 spreadArgCount = 0;
  3034. switch (m_token.tk)
  3035. {
  3036. case tkLParen:
  3037. {
  3038. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3039. if (fInNew)
  3040. {
  3041. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3042. if (buildAST)
  3043. {
  3044. Assert(pnode->nop == knopNew);
  3045. Assert(pnode->AsParseNodeCall()->pnodeArgs == nullptr);
  3046. pnode->AsParseNodeCall()->pnodeArgs = pnodeArgs;
  3047. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3048. pnode->AsParseNodeCall()->isApplyCall = false;
  3049. pnode->AsParseNodeCall()->isEvalCall = false;
  3050. pnode->AsParseNodeCall()->isSuperCall = false;
  3051. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3052. Assert(!m_hasDestructuringPattern || count > 0);
  3053. pnode->AsParseNodeCall()->argCount = count;
  3054. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3055. pnode->ichLim = this->GetScanner()->IchLimTok();
  3056. }
  3057. else
  3058. {
  3059. pnode = nullptr;
  3060. pToken->tk = tkNone; // This is no longer an identifier
  3061. }
  3062. fInNew = FALSE;
  3063. ChkCurTok(tkRParen, ERRnoRparen);
  3064. }
  3065. else
  3066. {
  3067. if (!fAllowCall)
  3068. {
  3069. return pnode;
  3070. }
  3071. uint saveNextBlockId = m_nextBlockId;
  3072. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  3073. if (isAsyncExpr)
  3074. {
  3075. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  3076. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  3077. // up function ID's.
  3078. GetCurrentBlock()->blockId = m_nextBlockId++;
  3079. }
  3080. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3081. // We used to un-defer a deferred function body here if it was called as part of the expression that declared it.
  3082. // We now detect this case up front in ParseFncDecl, which is cheaper and simpler.
  3083. if (buildAST)
  3084. {
  3085. bool fCallIsEval = false;
  3086. // Detect super()
  3087. if (this->NodeIsSuperName(pnode))
  3088. {
  3089. pnode = CreateSuperCallNode(pnode->AsParseNodeSpecialName(), pnodeArgs);
  3090. Assert(pnode);
  3091. pnode->AsParseNodeSuperCall()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3092. pnode->AsParseNodeSuperCall()->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3093. }
  3094. else
  3095. {
  3096. pnode = CreateCallNode(knopCall, pnode, pnodeArgs);
  3097. Assert(pnode);
  3098. }
  3099. // Detect call to "eval" and record it on the function.
  3100. // Note: we used to leave it up to the byte code generator to detect eval calls
  3101. // at global scope, but now it relies on the flag the parser sets, so set it here.
  3102. if (count > 0 && this->NodeIsEvalName(pnode->AsParseNodeCall()->pnodeTarget))
  3103. {
  3104. this->MarkEvalCaller();
  3105. fCallIsEval = true;
  3106. // Eval may reference any of the special symbols so we need to push refs to them here.
  3107. ReferenceSpecialName(wellKnownPropertyPids._this);
  3108. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3109. ReferenceSpecialName(wellKnownPropertyPids._super);
  3110. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3111. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3112. }
  3113. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3114. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3115. pnode->AsParseNodeCall()->isApplyCall = false;
  3116. pnode->AsParseNodeCall()->isEvalCall = fCallIsEval;
  3117. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3118. Assert(!m_hasDestructuringPattern || count > 0);
  3119. pnode->AsParseNodeCall()->argCount = count;
  3120. pnode->ichLim = this->GetScanner()->IchLimTok();
  3121. }
  3122. else
  3123. {
  3124. pnode = nullptr;
  3125. if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) // Detect eval
  3126. {
  3127. this->MarkEvalCaller();
  3128. ReferenceSpecialName(wellKnownPropertyPids._this);
  3129. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3130. ReferenceSpecialName(wellKnownPropertyPids._super);
  3131. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3132. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3133. }
  3134. pToken->tk = tkNone; // This is no longer an identifier
  3135. }
  3136. ChkCurTok(tkRParen, ERRnoRparen);
  3137. if (isAsyncExpr)
  3138. {
  3139. GetCurrentBlock()->blockId = saveCurrBlockId;
  3140. if (m_token.tk == tkDArrow)
  3141. {
  3142. // We're going to rewind and reinterpret the expression as a parameter list.
  3143. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  3144. m_nextBlockId = saveNextBlockId;
  3145. }
  3146. }
  3147. }
  3148. if (pfCanAssign)
  3149. {
  3150. *pfCanAssign = fCanAssignToCallResult &&
  3151. (m_sourceContextInfo ?
  3152. !PHASE_ON_RAW(Js::EarlyErrorOnAssignToCallPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId) :
  3153. !PHASE_ON1(Js::EarlyErrorOnAssignToCallPhase));
  3154. }
  3155. if (pfIsDotOrIndex)
  3156. {
  3157. *pfIsDotOrIndex = false;
  3158. }
  3159. break;
  3160. }
  3161. case tkLBrack:
  3162. {
  3163. this->GetScanner()->Scan();
  3164. IdentToken tok;
  3165. ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
  3166. if (buildAST)
  3167. {
  3168. AnalysisAssert(pnodeExpr);
  3169. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3170. {
  3171. pnode = CreateSuperReferenceNode(knopIndex, pnode->AsParseNodeSpecialName(), pnodeExpr);
  3172. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3173. }
  3174. else
  3175. {
  3176. pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
  3177. }
  3178. AnalysisAssert(pnode);
  3179. pnode->ichLim = this->GetScanner()->IchLimTok();
  3180. }
  3181. else
  3182. {
  3183. pnode = nullptr;
  3184. pToken->tk = tkNone; // This is no longer an identifier
  3185. }
  3186. ChkCurTok(tkRBrack, ERRnoRbrack);
  3187. if (pfCanAssign)
  3188. {
  3189. *pfCanAssign = TRUE;
  3190. }
  3191. if (pfIsDotOrIndex)
  3192. {
  3193. *pfIsDotOrIndex = true;
  3194. }
  3195. PidRefStack * topPidRef = nullptr;
  3196. if (buildAST)
  3197. {
  3198. if (pnodeExpr && pnodeExpr->nop == knopName)
  3199. {
  3200. topPidRef = pnodeExpr->AsParseNodeName()->pid->GetTopRef();
  3201. }
  3202. }
  3203. else if (tok.tk == tkID)
  3204. {
  3205. topPidRef = tok.pid->GetTopRef();
  3206. }
  3207. if (topPidRef)
  3208. {
  3209. topPidRef->SetIsUsedInLdElem(true);
  3210. }
  3211. if (!buildAST)
  3212. {
  3213. break;
  3214. }
  3215. bool shouldConvertToDot = false;
  3216. if (pnode->AsParseNodeBin()->pnode2->nop == knopStr)
  3217. {
  3218. // if the string is empty or contains escape character, we will not convert them to dot node
  3219. shouldConvertToDot = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch() > 0 && !this->GetScanner()->IsEscapeOnLastTkStrCon();
  3220. }
  3221. if (shouldConvertToDot)
  3222. {
  3223. LPCOLESTR str = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Psz();
  3224. // See if we can convert o["p"] into o.p and o["0"] into o[0] since they're equivalent and the latter forms
  3225. // are faster
  3226. uint32 uintValue;
  3227. if (Js::JavascriptOperators::TryConvertToUInt32(
  3228. str,
  3229. pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch(),
  3230. &uintValue) &&
  3231. !Js::TaggedInt::IsOverflow(uintValue)) // the optimization is not very useful if the number can't be represented as a TaggedInt
  3232. {
  3233. // No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes
  3234. auto intNode = CreateIntNode(uintValue); // implicit conversion from uint32 to int32
  3235. pnode->AsParseNodeBin()->pnode2 = intNode;
  3236. }
  3237. // Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,
  3238. // and since NaN/Infinity is a number it won't kill o.NaN/o.Infinity which would cause a problem
  3239. // if we decide to hoist o.NaN/o.Infinity.
  3240. // We need to keep o["NaN"] and o["+/-Infinity"] as array element access (we don't hoist that but we may hoist field access),
  3241. // so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.
  3242. // We need to follow same logic for strings that convert to a floating point number.
  3243. else
  3244. {
  3245. bool doConvertToProperty = false; // Convert a["x"] -> a.x.
  3246. if (!Parser::IsNaNOrInfinityLiteral<true>(str))
  3247. {
  3248. const OLECHAR* terminalChar;
  3249. double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);
  3250. bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);
  3251. doConvertToProperty = !convertsToFloat;
  3252. }
  3253. if (doConvertToProperty)
  3254. {
  3255. ParseNodeName * pnodeNewExpr = CreateNameNode(pnodeExpr->AsParseNodeStr()->pid);
  3256. pnodeNewExpr->ichMin = pnodeExpr->ichMin;
  3257. pnodeNewExpr->ichLim = pnodeExpr->ichLim;
  3258. pnode->AsParseNodeBin()->pnode2 = pnodeNewExpr;
  3259. pnode->nop = knopDot;
  3260. pnode->grfpn |= PNodeFlags::fpnIndexOperator;
  3261. }
  3262. }
  3263. }
  3264. }
  3265. break;
  3266. case tkDot:
  3267. {
  3268. ParseNodePtr name = nullptr;
  3269. OpCode opCode = knopDot;
  3270. this->GetScanner()->Scan();
  3271. if (!m_token.IsIdentifier())
  3272. {
  3273. //allow reserved words in ES5 mode
  3274. if (!(m_token.IsReservedWord()))
  3275. {
  3276. IdentifierExpectedError(m_token);
  3277. }
  3278. }
  3279. // Note: see comment above about field optimization WRT NaN/Infinity/-Infinity.
  3280. // Convert a.Nan, a.Infinity into a["NaN"], a["Infinity"].
  3281. // We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.
  3282. // Both NaN and Infinity are identifiers.
  3283. else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(this->GetHashTbl())->Psz()))
  3284. {
  3285. opCode = knopIndex;
  3286. }
  3287. if (buildAST)
  3288. {
  3289. if (opCode == knopDot)
  3290. {
  3291. name = CreateNameNode(m_token.GetIdentifier(this->GetHashTbl()));
  3292. }
  3293. else
  3294. {
  3295. Assert(opCode == knopIndex);
  3296. name = CreateStrNode(m_token.GetIdentifier(this->GetHashTbl()));
  3297. }
  3298. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3299. {
  3300. pnode = CreateSuperReferenceNode(opCode, pnode->AsParseNodeSpecialName(), name);
  3301. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3302. }
  3303. else
  3304. {
  3305. pnode = CreateBinNode(opCode, pnode, name);
  3306. }
  3307. }
  3308. else
  3309. {
  3310. pnode = nullptr;
  3311. pToken->tk = tkNone;
  3312. }
  3313. if (pfCanAssign)
  3314. {
  3315. *pfCanAssign = TRUE;
  3316. }
  3317. if (pfIsDotOrIndex)
  3318. {
  3319. *pfIsDotOrIndex = true;
  3320. }
  3321. this->GetScanner()->Scan();
  3322. break;
  3323. }
  3324. case tkStrTmplBasic:
  3325. case tkStrTmplBegin:
  3326. {
  3327. ParseNode* templateNode = nullptr;
  3328. if (pnode != nullptr)
  3329. {
  3330. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3331. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3332. }
  3333. else
  3334. {
  3335. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3336. }
  3337. if (!buildAST)
  3338. {
  3339. pToken->tk = tkNone; // This is no longer an identifier
  3340. }
  3341. pnode = templateNode;
  3342. if (pfCanAssign)
  3343. {
  3344. *pfCanAssign = FALSE;
  3345. }
  3346. if (pfIsDotOrIndex)
  3347. {
  3348. *pfIsDotOrIndex = false;
  3349. }
  3350. break;
  3351. }
  3352. default:
  3353. return pnode;
  3354. }
  3355. }
  3356. }
  3357. /***************************************************************************
  3358. Look for an existing label with the given name.
  3359. ***************************************************************************/
  3360. bool Parser::LabelExists(IdentPtr pid, LabelId* pLabelIdList)
  3361. {
  3362. StmtNest dummy;
  3363. dummy.pLabelId = pLabelIdList;
  3364. dummy.pstmtOuter = m_pstmtCur;
  3365. // Look through each label list for the current stack of statements
  3366. for (StmtNest* pStmt = &dummy; pStmt != nullptr; pStmt = pStmt->pstmtOuter)
  3367. {
  3368. for (LabelId* pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)
  3369. {
  3370. if (pLabelId->pid == pid)
  3371. return true;
  3372. }
  3373. }
  3374. return false;
  3375. }
  3376. // Currently only ints and floats are treated as constants in function call
  3377. // TODO: Check if we need for other constants as well
  3378. BOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)
  3379. {
  3380. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3381. {
  3382. return TRUE;
  3383. }
  3384. if (pnode->nop == knopFlt)
  3385. {
  3386. return TRUE;
  3387. }
  3388. return FALSE;
  3389. }
  3390. /***************************************************************************
  3391. Parse a list of arguments.
  3392. ***************************************************************************/
  3393. template<bool buildAST>
  3394. ParseNodePtr Parser::ParseArgList(bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)
  3395. {
  3396. ParseNodePtr pnodeArg;
  3397. ParseNodePtr pnodeList = nullptr;
  3398. ParseNodePtr *lastNodeRef = nullptr;
  3399. // Check for an empty list
  3400. Assert(m_token.tk == tkLParen);
  3401. if (this->GetScanner()->Scan() == tkRParen)
  3402. {
  3403. return nullptr;
  3404. }
  3405. *pCallOfConstants = true;
  3406. *pSpreadArgCount = 0;
  3407. int count = 0;
  3408. while (true)
  3409. {
  3410. if (count >= Js::Constants::MaxAllowedArgs)
  3411. {
  3412. Error(ERRTooManyArgs);
  3413. }
  3414. // Allow spread in argument lists.
  3415. IdentToken token;
  3416. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */TRUE, NULL, nullptr, nullptr, &token);
  3417. ++count;
  3418. this->MarkEscapingRef(pnodeArg, &token);
  3419. if (buildAST)
  3420. {
  3421. this->CheckArguments(pnodeArg);
  3422. if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))
  3423. {
  3424. *pCallOfConstants = false;
  3425. }
  3426. if (pnodeArg->nop == knopEllipsis)
  3427. {
  3428. (*pSpreadArgCount)++;
  3429. }
  3430. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3431. }
  3432. if (m_token.tk != tkComma)
  3433. {
  3434. break;
  3435. }
  3436. this->GetScanner()->Scan();
  3437. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  3438. {
  3439. break;
  3440. }
  3441. }
  3442. if (pSpreadArgCount != nullptr && (*pSpreadArgCount) > 0) {
  3443. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3444. }
  3445. *pCount = static_cast<uint16>(count);
  3446. if (buildAST)
  3447. {
  3448. Assert(lastNodeRef);
  3449. Assert(*lastNodeRef);
  3450. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3451. }
  3452. return pnodeList;
  3453. }
  3454. // Currently only ints are treated as constants in ArrayLiterals
  3455. BOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)
  3456. {
  3457. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3458. {
  3459. return TRUE;
  3460. }
  3461. return FALSE;
  3462. }
  3463. template<bool buildAST>
  3464. ParseNodeArrLit * Parser::ParseArrayLiteral()
  3465. {
  3466. ParseNodeArrLit * pnode = nullptr;
  3467. bool arrayOfTaggedInts = false;
  3468. bool arrayOfInts = false;
  3469. bool arrayOfNumbers = false;
  3470. bool hasMissingValues = false;
  3471. uint count = 0;
  3472. uint spreadCount = 0;
  3473. ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);
  3474. if (buildAST)
  3475. {
  3476. pnode = CreateNodeForOpT<knopArray>();
  3477. pnode->pnode1 = pnode1;
  3478. pnode->arrayOfTaggedInts = arrayOfTaggedInts;
  3479. pnode->arrayOfInts = arrayOfInts;
  3480. pnode->arrayOfNumbers = arrayOfNumbers;
  3481. pnode->hasMissingValues = hasMissingValues;
  3482. pnode->count = count;
  3483. pnode->spreadCount = spreadCount;
  3484. if (pnode->pnode1)
  3485. {
  3486. this->CheckArguments(pnode->pnode1);
  3487. }
  3488. }
  3489. return pnode;
  3490. }
  3491. /***************************************************************************
  3492. Create an ArrayLiteral node
  3493. Parse a list of array elements. [ a, b, , c, ]
  3494. ***************************************************************************/
  3495. template<bool buildAST>
  3496. ParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)
  3497. {
  3498. ParseNodePtr pnodeArg = nullptr;
  3499. ParseNodePtr pnodeList = nullptr;
  3500. ParseNodePtr *lastNodeRef = nullptr;
  3501. *count = 0;
  3502. // Check for an empty list
  3503. if (tkRBrack == m_token.tk)
  3504. {
  3505. return nullptr;
  3506. }
  3507. this->m_arrayDepth++;
  3508. bool arrayOfTaggedInts = buildAST;
  3509. bool arrayOfInts = buildAST;
  3510. bool arrayOfNumbers = buildAST;
  3511. bool arrayOfVarInts = false;
  3512. bool hasMissingValues = false;
  3513. for (;;)
  3514. {
  3515. (*count)++;
  3516. if (tkComma == m_token.tk || tkRBrack == m_token.tk)
  3517. {
  3518. hasMissingValues = true;
  3519. arrayOfTaggedInts = false;
  3520. arrayOfInts = false;
  3521. arrayOfNumbers = false;
  3522. if (buildAST)
  3523. {
  3524. pnodeArg = CreateNodeForOpT<knopEmpty>();
  3525. }
  3526. }
  3527. else
  3528. {
  3529. // Allow Spread in array literals.
  3530. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  3531. if (buildAST)
  3532. {
  3533. if (pnodeArg->nop == knopEllipsis)
  3534. {
  3535. (*spreadCount)++;
  3536. }
  3537. this->CheckArguments(pnodeArg);
  3538. }
  3539. }
  3540. #if DEBUG
  3541. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))
  3542. {
  3543. Error(ERRsyntax);
  3544. }
  3545. #endif
  3546. if (buildAST)
  3547. {
  3548. if (arrayOfNumbers)
  3549. {
  3550. if (pnodeArg->nop != knopInt)
  3551. {
  3552. arrayOfTaggedInts = false;
  3553. if (pnodeArg->nop != knopFlt)
  3554. {
  3555. // Not an array of constants.
  3556. arrayOfInts = false;
  3557. arrayOfNumbers = false;
  3558. }
  3559. else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->AsParseNodeFloat()->dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->AsParseNodeFloat()->dbl) || pnodeArg->AsParseNodeFloat()->dbl == -2147483648.0))
  3560. {
  3561. // We've seen nothing but ints, and this is a uint32 but not an int32.
  3562. // Unless we see an actual float at some point, we want an array of vars
  3563. // so we can work with tagged ints.
  3564. arrayOfVarInts = true;
  3565. }
  3566. else
  3567. {
  3568. // Not an int array, but it may still be a float array.
  3569. arrayOfInts = false;
  3570. }
  3571. }
  3572. else
  3573. {
  3574. if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->AsParseNodeInt()->lw))
  3575. {
  3576. arrayOfInts = false;
  3577. }
  3578. if (Js::TaggedInt::IsOverflow(pnodeArg->AsParseNodeInt()->lw))
  3579. {
  3580. arrayOfTaggedInts = false;
  3581. }
  3582. }
  3583. }
  3584. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3585. }
  3586. if (tkComma != m_token.tk)
  3587. {
  3588. break;
  3589. }
  3590. this->GetScanner()->Scan();
  3591. if (tkRBrack == m_token.tk)
  3592. {
  3593. break;
  3594. }
  3595. }
  3596. if (spreadCount != nullptr && *spreadCount > 0) {
  3597. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3598. }
  3599. if (buildAST)
  3600. {
  3601. Assert(lastNodeRef);
  3602. Assert(*lastNodeRef);
  3603. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3604. if (arrayOfVarInts && arrayOfInts)
  3605. {
  3606. arrayOfInts = false;
  3607. arrayOfNumbers = false;
  3608. }
  3609. *pArrayOfTaggedInts = arrayOfTaggedInts;
  3610. *pArrayOfInts = arrayOfInts;
  3611. *pArrayOfNumbers = arrayOfNumbers;
  3612. *pHasMissingValues = hasMissingValues;
  3613. }
  3614. this->m_arrayDepth--;
  3615. return pnodeList;
  3616. }
  3617. Parser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)
  3618. {
  3619. Assert(pAllocator);
  3620. return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);
  3621. }
  3622. template<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)
  3623. {
  3624. this->GetScanner()->Scan();
  3625. ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);
  3626. if (buildAST)
  3627. {
  3628. *ppnodeName = CreateUniNode(knopComputedName, pnodeNameExpr, pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);
  3629. }
  3630. if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))
  3631. {
  3632. *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);
  3633. }
  3634. ChkCurTokNoScan(tkRBrack, ERRnoRbrack);
  3635. }
  3636. /***************************************************************************
  3637. Parse a list of object set/get members, e.g.:
  3638. { get foo(){ ... }, set bar(arg) { ... } }
  3639. ***************************************************************************/
  3640. template<bool buildAST>
  3641. ParseNodeBin * Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint)
  3642. {
  3643. ParseNodePtr pnodeName = nullptr;
  3644. Assert(nop == knopGetMember || nop == knopSetMember);
  3645. Assert(ppNameHint);
  3646. IdentPtr pid = nullptr;
  3647. bool isComputedName = false;
  3648. *ppNameHint = nullptr;
  3649. switch (m_token.tk)
  3650. {
  3651. default:
  3652. if (!m_token.IsReservedWord())
  3653. {
  3654. Error(ERRnoMemberIdent);
  3655. }
  3656. // fall through
  3657. case tkID:
  3658. pid = m_token.GetIdentifier(this->GetHashTbl());
  3659. *ppNameHint = pid->Psz();
  3660. if (buildAST)
  3661. {
  3662. pnodeName = CreateStrNode(pid);
  3663. }
  3664. break;
  3665. case tkStrCon:
  3666. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3667. {
  3668. Error(ERRES5NoOctal);
  3669. }
  3670. pid = m_token.GetStr();
  3671. *ppNameHint = pid->Psz();
  3672. if (buildAST)
  3673. {
  3674. pnodeName = CreateStrNode(pid);
  3675. }
  3676. break;
  3677. case tkIntCon:
  3678. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3679. {
  3680. Error(ERRES5NoOctal);
  3681. }
  3682. pid = this->GetScanner()->PidFromLong(m_token.GetLong());
  3683. if (buildAST)
  3684. {
  3685. pnodeName = CreateStrNode(pid);
  3686. }
  3687. break;
  3688. case tkFltCon:
  3689. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3690. {
  3691. Error(ERRES5NoOctal);
  3692. }
  3693. pid = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  3694. if (buildAST)
  3695. {
  3696. pnodeName = CreateStrNode(pid);
  3697. }
  3698. break;
  3699. case tkLBrack:
  3700. // Computed property name: get|set [expr] () { }
  3701. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3702. {
  3703. Error(ERRnoMemberIdent);
  3704. }
  3705. LPCOLESTR emptyHint = nullptr;
  3706. uint32 offset = 0;
  3707. ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);
  3708. isComputedName = true;
  3709. break;
  3710. }
  3711. MemberType memberType;
  3712. ushort flags = fFncMethod | fFncNoName;
  3713. if (nop == knopGetMember)
  3714. {
  3715. memberType = MemberTypeGetter;
  3716. flags |= fFncNoArg;
  3717. }
  3718. else
  3719. {
  3720. Assert(nop == knopSetMember);
  3721. memberType = MemberTypeSetter;
  3722. flags |= fFncOneArg;
  3723. }
  3724. AutoParsingSuperRestrictionStateRestorer restorer(this);
  3725. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  3726. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(flags, *ppNameHint,
  3727. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  3728. if (isComputedName)
  3729. {
  3730. pnodeFnc->SetHasComputedName();
  3731. }
  3732. pnodeFnc->SetHasHomeObj();
  3733. if (buildAST)
  3734. {
  3735. pnodeFnc->SetIsAccessor();
  3736. return CreateBinNode(nop, pnodeName, pnodeFnc);
  3737. }
  3738. else
  3739. {
  3740. return nullptr;
  3741. }
  3742. }
  3743. /***************************************************************************
  3744. Parse a list of object members. e.g. { x:foo, 'y me':bar }
  3745. ***************************************************************************/
  3746. template<bool buildAST>
  3747. ParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)
  3748. {
  3749. ParseNodeBin * pnodeArg = nullptr;
  3750. ParseNodePtr pnodeName = nullptr;
  3751. ParseNodePtr pnodeList = nullptr;
  3752. ParseNodePtr *lastNodeRef = nullptr;
  3753. LPCOLESTR pFullNameHint = nullptr; // A calculated full name
  3754. uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;
  3755. uint32 shortNameOffset = 0;
  3756. bool isProtoDeclared = false;
  3757. // we get declaration tkLCurly - when the possible object pattern found under the expression.
  3758. bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();
  3759. // Check for an empty list
  3760. if (tkRCurly == m_token.tk)
  3761. {
  3762. return nullptr;
  3763. }
  3764. ArenaAllocator tempAllocator(_u("MemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  3765. bool hasDeferredInitError = false;
  3766. for (;;)
  3767. {
  3768. bool isComputedName = false;
  3769. #if DEBUG
  3770. if ((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(this->GetScanner()->IsDoubleQuoteOnLastTkStrCon())))
  3771. {
  3772. Error(ERRsyntax);
  3773. }
  3774. #endif
  3775. bool isAsyncMethod = false;
  3776. charcount_t ichMin = 0;
  3777. size_t iecpMin = 0;
  3778. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  3779. {
  3780. RestorePoint parsedAsync;
  3781. this->GetScanner()->Capture(&parsedAsync);
  3782. ichMin = this->GetScanner()->IchMinTok();
  3783. iecpMin = this->GetScanner()->IecpMinTok();
  3784. this->GetScanner()->ScanForcingPid();
  3785. if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || this->GetScanner()->FHadNewLine() || m_token.tk == tkComma)
  3786. {
  3787. this->GetScanner()->SeekTo(parsedAsync);
  3788. }
  3789. else
  3790. {
  3791. isAsyncMethod = true;
  3792. }
  3793. }
  3794. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  3795. m_token.tk == tkStar;
  3796. ushort fncDeclFlags = fFncNoName | fFncMethod;
  3797. if (isGenerator)
  3798. {
  3799. if (isAsyncMethod)
  3800. {
  3801. Error(ERRsyntax);
  3802. }
  3803. // Include star character in the function extents
  3804. ichMin = this->GetScanner()->IchMinTok();
  3805. iecpMin = this->GetScanner()->IecpMinTok();
  3806. this->GetScanner()->ScanForcingPid();
  3807. fncDeclFlags |= fFncGenerator;
  3808. }
  3809. IdentPtr pidHint = nullptr; // A name scoped to current expression
  3810. Token tkHint = m_token;
  3811. charcount_t idHintIchMin = static_cast<charcount_t>(this->GetScanner()->IecpMinTok());
  3812. charcount_t idHintIchLim = static_cast<charcount_t>(this->GetScanner()->IecpLimTok());
  3813. bool wrapInBrackets = false;
  3814. switch (m_token.tk)
  3815. {
  3816. default:
  3817. if (!m_token.IsReservedWord())
  3818. {
  3819. Error(ERRnoMemberIdent);
  3820. }
  3821. // allow reserved words
  3822. wrapInBrackets = true;
  3823. // fall-through
  3824. case tkID:
  3825. pidHint = m_token.GetIdentifier(this->GetHashTbl());
  3826. if (buildAST)
  3827. {
  3828. pnodeName = CreateStrNode(pidHint);
  3829. }
  3830. break;
  3831. case tkStrCon:
  3832. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3833. {
  3834. Error(ERRES5NoOctal);
  3835. }
  3836. wrapInBrackets = true;
  3837. pidHint = m_token.GetStr();
  3838. if (buildAST)
  3839. {
  3840. pnodeName = CreateStrNode(pidHint);
  3841. }
  3842. break;
  3843. case tkIntCon:
  3844. // Object initializers with numeric labels allowed in JS6
  3845. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3846. {
  3847. Error(ERRES5NoOctal);
  3848. }
  3849. pidHint = this->GetScanner()->PidFromLong(m_token.GetLong());
  3850. if (buildAST)
  3851. {
  3852. pnodeName = CreateStrNode(pidHint);
  3853. }
  3854. break;
  3855. case tkFltCon:
  3856. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3857. {
  3858. Error(ERRES5NoOctal);
  3859. }
  3860. pidHint = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  3861. if (buildAST)
  3862. {
  3863. pnodeName = CreateStrNode(pidHint);
  3864. }
  3865. wrapInBrackets = true;
  3866. break;
  3867. case tkLBrack:
  3868. // Computed property name: [expr] : value
  3869. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3870. {
  3871. Error(ERRnoMemberIdent);
  3872. }
  3873. ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3874. isComputedName = true;
  3875. break;
  3876. }
  3877. if (pFullNameHint == nullptr)
  3878. {
  3879. if (CONFIG_FLAG(UseFullName))
  3880. {
  3881. pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);
  3882. }
  3883. else
  3884. {
  3885. pFullNameHint = pidHint ? pidHint->Psz() : nullptr;
  3886. fullNameHintLength = pidHint ? pidHint->Cch() : 0;
  3887. shortNameOffset = 0;
  3888. }
  3889. }
  3890. RestorePoint atPid;
  3891. this->GetScanner()->Capture(&atPid);
  3892. this->GetScanner()->ScanForcingPid();
  3893. if (isGenerator && m_token.tk != tkLParen)
  3894. {
  3895. Error(ERRnoLparen);
  3896. }
  3897. if (tkColon == m_token.tk)
  3898. {
  3899. // It is a syntax error is the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.
  3900. // Note that previous scan is important because only after that we can determine we have a variable.
  3901. if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)
  3902. {
  3903. if (isProtoDeclared)
  3904. {
  3905. Error(ERRsyntax);
  3906. }
  3907. else
  3908. {
  3909. isProtoDeclared = true;
  3910. }
  3911. }
  3912. this->GetScanner()->Scan();
  3913. ParseNodePtr pnodeExpr = nullptr;
  3914. if (isObjectPattern)
  3915. {
  3916. if (m_token.tk == tkEllipsis)
  3917. {
  3918. Error(ERRUnexpectedEllipsis);
  3919. }
  3920. RestorePoint atExpression;
  3921. if (!buildAST && declarationType == tkLCurly && IsPossiblePatternStart())
  3922. {
  3923. this->GetScanner()->Capture(&atExpression);
  3924. int saveNextBlockId = m_nextBlockId;
  3925. // It is possible that we might encounter the shorthand init error. Lets find that out.
  3926. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  3927. m_hasDeferredShorthandInitError = false;
  3928. IdentToken token;
  3929. BOOL fLikelyPattern = false;
  3930. // First identify that the current expression is indeed the object/array literal. Otherwise we will just use the ParsrExpr to parse that.
  3931. ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false /*fUnaryOrParen*/,
  3932. TRUE, nullptr /*pfCanAssign*/, &fLikelyPattern);
  3933. m_nextBlockId = saveNextBlockId;
  3934. this->GetScanner()->SeekTo(atExpression);
  3935. if (fLikelyPattern)
  3936. {
  3937. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3938. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3939. {
  3940. if (m_token.IsOperator())
  3941. {
  3942. Error(ERRDestructNoOper);
  3943. }
  3944. Error(ERRsyntax);
  3945. }
  3946. }
  3947. else
  3948. {
  3949. if (m_hasDeferredShorthandInitError)
  3950. {
  3951. Error(ERRnoColon);
  3952. }
  3953. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3954. }
  3955. m_hasDeferredShorthandInitError = savedDeferredInitError;
  3956. }
  3957. else
  3958. {
  3959. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3960. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3961. {
  3962. if (m_token.IsOperator())
  3963. {
  3964. Error(ERRDestructNoOper);
  3965. }
  3966. Error(ERRsyntax);
  3967. }
  3968. }
  3969. }
  3970. else
  3971. {
  3972. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3973. if (pnodeExpr && pnodeExpr->nop == knopFncDecl)
  3974. {
  3975. ParseNodeFnc* funcNode = pnodeExpr->AsParseNodeFnc();
  3976. if (isComputedName)
  3977. {
  3978. funcNode->SetHasComputedName();
  3979. }
  3980. funcNode->SetHasHomeObj();
  3981. }
  3982. }
  3983. #if DEBUG
  3984. if ((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))
  3985. {
  3986. Error(ERRsyntax);
  3987. }
  3988. #endif
  3989. if (buildAST)
  3990. {
  3991. pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);
  3992. if (pnodeArg->pnode1->nop == knopStr)
  3993. {
  3994. pnodeArg->pnode1->AsParseNodeStr()->pid->PromoteAssignmentState();
  3995. }
  3996. }
  3997. }
  3998. else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3999. {
  4000. if (isObjectPattern)
  4001. {
  4002. Error(ERRInvalidAssignmentTarget);
  4003. }
  4004. // Shorthand syntax: foo() {} -> foo: function() {}
  4005. // Rewind to the PID and parse a function expression.
  4006. this->GetScanner()->SeekTo(atPid);
  4007. AutoParsingSuperRestrictionStateRestorer restorer(this);
  4008. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  4009. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), pFullNameHint,
  4010. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  4011. if (isAsyncMethod || isGenerator)
  4012. {
  4013. pnodeFnc->cbMin = iecpMin;
  4014. pnodeFnc->ichMin = ichMin;
  4015. }
  4016. if (isComputedName)
  4017. {
  4018. pnodeFnc->SetHasComputedName();
  4019. }
  4020. pnodeFnc->SetHasHomeObj();
  4021. if (buildAST)
  4022. {
  4023. pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFnc);
  4024. }
  4025. }
  4026. else if (nullptr != pidHint) //Its either tkID/tkStrCon/tkFloatCon/tkIntCon
  4027. {
  4028. Assert(pidHint->Psz() != nullptr);
  4029. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&
  4030. // get/set are only pseudo keywords when they are identifiers (i.e. not strings)
  4031. tkHint.tk == tkID && NextTokenIsPropertyNameStart())
  4032. {
  4033. if (isObjectPattern)
  4034. {
  4035. Error(ERRInvalidAssignmentTarget);
  4036. }
  4037. LPCOLESTR pNameGetOrSet = nullptr;
  4038. OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;
  4039. pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet);
  4040. if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->pnode2->nop == knopFncDecl)
  4041. {
  4042. // displays as "get object.funcname" or "set object.funcname"
  4043. uint32 getOrSetOffset = 0;
  4044. LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);
  4045. pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);
  4046. shortNameOffset += getOrSetOffset;
  4047. }
  4048. }
  4049. else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4050. {
  4051. // Shorthand {foo} -> {foo:foo} syntax.
  4052. // {foo = <initializer>} supported only when on object pattern rules are being applied
  4053. if (tkHint.tk != tkID)
  4054. {
  4055. Assert(tkHint.IsReservedWord()
  4056. || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);
  4057. // All keywords are banned in non-strict mode.
  4058. // Future reserved words are banned in strict mode.
  4059. if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))
  4060. {
  4061. IdentifierExpectedError(tkHint);
  4062. }
  4063. }
  4064. if (buildAST)
  4065. {
  4066. CheckArgumentsUse(pidHint, GetCurrentFunctionNode());
  4067. }
  4068. bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;
  4069. // Saving the current state as we may change the isObjectPattern down below.
  4070. bool oldState = isObjectPattern;
  4071. if (couldBeObjectPattern)
  4072. {
  4073. declarationType = tkLCurly;
  4074. isObjectPattern = true;
  4075. // This may be an error but we are deferring for favouring destructuring.
  4076. hasDeferredInitError = true;
  4077. }
  4078. ParseNodePtr pnodeIdent = nullptr;
  4079. if (isObjectPattern)
  4080. {
  4081. this->GetScanner()->SeekTo(atPid);
  4082. pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  4083. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4084. {
  4085. if (m_token.IsOperator())
  4086. {
  4087. Error(ERRDestructNoOper);
  4088. }
  4089. Error(ERRsyntax);
  4090. }
  4091. }
  4092. else
  4093. {
  4094. // Add a reference to the hinted name so we can bind it properly.
  4095. PidRefStack *ref = PushPidRef(pidHint);
  4096. if (buildAST)
  4097. {
  4098. pnodeIdent = CreateNameNode(pidHint, ref, idHintIchMin, idHintIchLim);
  4099. }
  4100. }
  4101. if (buildAST)
  4102. {
  4103. pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);
  4104. }
  4105. isObjectPattern = oldState;
  4106. }
  4107. else
  4108. {
  4109. Error(ERRnoColon);
  4110. }
  4111. }
  4112. else
  4113. {
  4114. Error(ERRnoColon);
  4115. }
  4116. if (buildAST)
  4117. {
  4118. Assert(pnodeArg->pnode2 != nullptr);
  4119. if (pnodeArg->pnode2->nop == knopFncDecl)
  4120. {
  4121. Assert(fullNameHintLength >= shortNameOffset);
  4122. ParseNodeFnc * pnodeFunc = pnodeArg->pnode2->AsParseNodeFnc();
  4123. pnodeFunc->hint = pFullNameHint;
  4124. pnodeFunc->hintLength = fullNameHintLength;
  4125. pnodeFunc->hintOffset = shortNameOffset;
  4126. }
  4127. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  4128. }
  4129. pidHint = nullptr;
  4130. pFullNameHint = nullptr;
  4131. if (tkComma != m_token.tk)
  4132. {
  4133. break;
  4134. }
  4135. this->GetScanner()->ScanForcingPid();
  4136. if (tkRCurly == m_token.tk)
  4137. {
  4138. break;
  4139. }
  4140. }
  4141. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;
  4142. if (buildAST)
  4143. {
  4144. Assert(lastNodeRef);
  4145. Assert(*lastNodeRef);
  4146. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  4147. }
  4148. return pnodeList;
  4149. }
  4150. BOOL Parser::WillDeferParse(Js::LocalFunctionId functionId)
  4151. {
  4152. if ((m_grfscr & fscrWillDeferFncParse) != 0)
  4153. {
  4154. if (m_stoppedDeferredParse)
  4155. {
  4156. return false;
  4157. }
  4158. if (!PHASE_ENABLED_RAW(DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))
  4159. {
  4160. return false;
  4161. }
  4162. if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId)
  4163. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4164. || Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag)
  4165. #endif
  4166. )
  4167. {
  4168. return true;
  4169. }
  4170. #if ENABLE_PROFILE_INFO
  4171. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4172. if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)
  4173. {
  4174. Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);
  4175. return flags != Js::ExecutionFlags_Executed;
  4176. }
  4177. #endif
  4178. #endif
  4179. return true;
  4180. }
  4181. return false;
  4182. }
  4183. //
  4184. // Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred
  4185. // function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.
  4186. //
  4187. BOOL Parser::IsDeferredFnc()
  4188. {
  4189. if (m_grfscr & fscrDeferredFnc)
  4190. {
  4191. m_grfscr &= ~fscrDeferredFnc;
  4192. return true;
  4193. }
  4194. return false;
  4195. }
  4196. template<bool buildAST>
  4197. ParseNode * Parser::ParseFncDeclCheckScope(ushort flags, bool resetParsingSuperRestrictionState, bool fAllowIn)
  4198. {
  4199. ParseNodeBlock * pnodeFncBlockScope = nullptr;
  4200. ParseNodePtr *ppnodeScopeSave = nullptr;
  4201. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4202. bool fDeclaration = flags & fFncDeclaration;
  4203. bool noStmtContext = false;
  4204. if (fDeclaration)
  4205. {
  4206. noStmtContext = m_pstmtCur->GetNop() != knopBlock;
  4207. if (noStmtContext)
  4208. {
  4209. // We have a function declaration like "if (a) function f() {}". We didn't see
  4210. // a block scope on the way in, so we need to pretend we did. Note that this is a syntax error
  4211. // in strict mode.
  4212. if (!this->FncDeclAllowedWithoutContext(flags))
  4213. {
  4214. Error(ERRsyntax);
  4215. }
  4216. pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  4217. if (buildAST)
  4218. {
  4219. PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);
  4220. }
  4221. }
  4222. }
  4223. ParseNodeFnc * pnodeFnc = ParseFncDeclInternal<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan */ false, resetParsingSuperRestrictionState, /* fUnaryOrParen */ false, noStmtContext, fAllowIn);
  4224. if (pnodeFncBlockScope)
  4225. {
  4226. Assert(pnodeFncBlockScope->pnodeStmt == nullptr);
  4227. pnodeFncBlockScope->pnodeStmt = pnodeFnc;
  4228. if (buildAST)
  4229. {
  4230. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  4231. }
  4232. FinishParseBlock(pnodeFncBlockScope);
  4233. return pnodeFncBlockScope;
  4234. }
  4235. return pnodeFnc;
  4236. }
  4237. template<bool buildAST>
  4238. ParseNodeFnc * Parser::ParseFncDeclNoCheckScope(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool resetParsingSuperRestrictionState, bool fUnaryOrParen, bool fAllowIn)
  4239. {
  4240. Assert((flags & fFncDeclaration) == 0);
  4241. return ParseFncDeclInternal<buildAST>(flags, pNameHint, needsPIDOnRCurlyScan, resetParsingSuperRestrictionState, fUnaryOrParen, /* noStmtContext */ false, fAllowIn);
  4242. }
  4243. template<bool buildAST>
  4244. ParseNodeFnc * Parser::ParseFncDeclInternal(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool resetParsingSuperRestrictionState, bool fUnaryOrParen, bool noStmtContext, bool fAllowIn)
  4245. {
  4246. AutoParsingSuperRestrictionStateRestorer restorer(this);
  4247. if (resetParsingSuperRestrictionState)
  4248. {
  4249. // ParseFncDecl will always reset m_parsingSuperRestrictionState to super disallowed unless explicitly disabled
  4250. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperDisallowed;
  4251. }
  4252. ParseNodeFnc * pnodeFnc = nullptr;
  4253. ParseNodePtr *ppnodeVarSave = nullptr;
  4254. bool fDeclaration = flags & fFncDeclaration;
  4255. bool fModule = (flags & fFncModule) != 0;
  4256. bool fLambda = (flags & fFncLambda) != 0;
  4257. charcount_t ichMin = this->GetScanner()->IchMinTok();
  4258. bool wasInDeferredNestedFunc = false;
  4259. uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;
  4260. this->m_tryCatchOrFinallyDepth = 0;
  4261. if (this->m_arrayDepth)
  4262. {
  4263. this->m_funcInArrayDepth++; // Count function depth within array literal
  4264. }
  4265. // Update the count of functions nested in the current parent.
  4266. Assert(m_pnestedCount || !buildAST);
  4267. uint *pnestedCountSave = m_pnestedCount;
  4268. if (buildAST || m_pnestedCount)
  4269. {
  4270. (*m_pnestedCount)++;
  4271. }
  4272. uint scopeCountNoAstSave = m_scopeCountNoAst;
  4273. m_scopeCountNoAst = 0;
  4274. // Create the node.
  4275. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  4276. pnodeFnc->SetDeclaration(fDeclaration);
  4277. pnodeFnc->nestedFuncEscapes = false;
  4278. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  4279. pnodeFnc->functionId = (*m_nextFunctionId)++;
  4280. // Push new parser state with this new function node
  4281. AppendFunctionToScopeList(fDeclaration, pnodeFnc);
  4282. // Start the argument list.
  4283. ppnodeVarSave = m_ppnodeVar;
  4284. if (buildAST)
  4285. {
  4286. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  4287. pnodeFnc->columnNumber = CalculateFunctionColumnNumber();
  4288. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  4289. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  4290. m_pCurrentAstSize = &pnodeFnc->astSize;
  4291. }
  4292. else // if !buildAST
  4293. {
  4294. wasInDeferredNestedFunc = m_inDeferredNestedFunc;
  4295. m_inDeferredNestedFunc = true;
  4296. }
  4297. m_pnestedCount = &pnodeFnc->nestedCount;
  4298. AnalysisAssert(pnodeFnc);
  4299. pnodeFnc->SetIsAsync((flags & fFncAsync) != 0);
  4300. pnodeFnc->SetIsLambda(fLambda);
  4301. pnodeFnc->SetIsMethod((flags & fFncMethod) != 0);
  4302. pnodeFnc->SetIsClassMember((flags & fFncClassMember) != 0);
  4303. pnodeFnc->SetIsModule(fModule);
  4304. pnodeFnc->SetIsClassConstructor((flags & fFncClassConstructor) != 0);
  4305. pnodeFnc->SetIsBaseClassConstructor((flags & fFncBaseClassConstructor) != 0);
  4306. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  4307. IdentPtr pFncNamePid = nullptr;
  4308. bool needScanRCurly = true;
  4309. ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule, &pFncNamePid, fAllowIn);
  4310. AddNestedCapturedNames(pnodeFnc);
  4311. AnalysisAssert(pnodeFnc);
  4312. *m_ppnodeVar = nullptr;
  4313. m_ppnodeVar = ppnodeVarSave;
  4314. if (m_currentNodeFunc && (pnodeFnc->CallsEval() || pnodeFnc->ChildCallsEval()))
  4315. {
  4316. GetCurrentFunctionNode()->SetChildCallsEval(true);
  4317. }
  4318. // Lambdas do not have "arguments" and instead capture their parent's
  4319. // binding of "arguments. To ensure the arguments object of the enclosing
  4320. // non-lambda function is loaded propagate the UsesArguments flag up to
  4321. // the parent function
  4322. if (fLambda && (pnodeFnc->UsesArguments() || pnodeFnc->CallsEval()))
  4323. {
  4324. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4325. if (pnodeFncParent != nullptr)
  4326. {
  4327. pnodeFncParent->SetUsesArguments();
  4328. }
  4329. else
  4330. {
  4331. m_UsesArgumentsAtGlobal = true;
  4332. }
  4333. }
  4334. if (needScanRCurly && !fModule)
  4335. {
  4336. // Consume the next token now that we're back in the enclosing function (whose strictness may be
  4337. // different from the function we just finished).
  4338. #if DBG
  4339. bool expectedTokenValid = m_token.tk == tkRCurly;
  4340. AssertMsg(expectedTokenValid, "Invalid token expected for RCurly match");
  4341. #endif
  4342. // The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.
  4343. if (needsPIDOnRCurlyScan)
  4344. {
  4345. this->GetScanner()->ScanForcingPid();
  4346. }
  4347. else
  4348. {
  4349. this->GetScanner()->Scan();
  4350. }
  4351. }
  4352. m_pnestedCount = pnestedCountSave;
  4353. Assert(!buildAST || !wasInDeferredNestedFunc);
  4354. m_inDeferredNestedFunc = wasInDeferredNestedFunc;
  4355. if (this->m_arrayDepth)
  4356. {
  4357. this->m_funcInArrayDepth--;
  4358. if (this->m_funcInArrayDepth == 0)
  4359. {
  4360. // We disable deferred parsing if array literals dominate.
  4361. // But don't do this if the array literal is dominated by function bodies.
  4362. if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)
  4363. {
  4364. // Class member methods have optional separators. We need to check whether we are
  4365. // getting the IchLim of the correct token.
  4366. Assert(this->GetScanner()->m_tkPrevious == tkRCurly && needScanRCurly);
  4367. this->m_funcInArray += this->GetScanner()->IchMinTok() - /*tkRCurly*/ 1 - ichMin;
  4368. }
  4369. else
  4370. {
  4371. this->m_funcInArray += this->GetScanner()->IchLimTok() - ichMin;
  4372. }
  4373. }
  4374. }
  4375. m_scopeCountNoAst = scopeCountNoAstSave;
  4376. if (fDeclaration && !IsStrictMode())
  4377. {
  4378. if (pFncNamePid != nullptr &&
  4379. GetCurrentBlock() &&
  4380. GetCurrentBlock()->blockType == PnodeBlockType::Regular)
  4381. {
  4382. // Add a function-scoped VarDecl with the same name as the function for
  4383. // back compat with pre-ES6 code that declares functions in blocks. The
  4384. // idea is that the last executed declaration wins at the function scope
  4385. // level and we accomplish this by having each block scoped function
  4386. // declaration assign to both the block scoped "let" binding, as well
  4387. // as the function scoped "var" binding.
  4388. ParseNodeVar * vardecl = CreateVarDeclNode(pFncNamePid, STVariable, false, nullptr, false);
  4389. vardecl->isBlockScopeFncDeclVar = true;
  4390. if (GetCurrentFunctionNode() && vardecl->sym->GetIsFormal())
  4391. {
  4392. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4393. }
  4394. }
  4395. }
  4396. if (buildAST && fDeclaration)
  4397. {
  4398. Symbol* funcSym = pnodeFnc->GetFuncSymbol();
  4399. if (funcSym->GetIsFormal())
  4400. {
  4401. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4402. }
  4403. } this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;
  4404. return pnodeFnc;
  4405. }
  4406. bool Parser::FncDeclAllowedWithoutContext(ushort flags)
  4407. {
  4408. // Statement context required for strict mode, async functions, and generators.
  4409. // Note that generators aren't detected yet when this method is called; they're checked elsewhere.
  4410. return !IsStrictMode() && !(flags & fFncAsync);
  4411. }
  4412. uint Parser::CalculateFunctionColumnNumber()
  4413. {
  4414. uint columnNumber;
  4415. charcount_t ichMinTok = this->GetScanner()->IchMinTok();
  4416. charcount_t ichMinLine = this->GetScanner()->IchMinLine();
  4417. if (ichMinTok >= ichMinLine)
  4418. {
  4419. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  4420. columnNumber = ichMinTok - ichMinLine;
  4421. if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == this->GetScanner()->LineCur())
  4422. {
  4423. // Adjust the column if it falls on the first line, where the re-parse is happening.
  4424. columnNumber += m_functionBody->GetRelativeColumnNumber();
  4425. }
  4426. }
  4427. else if (m_currentNodeFunc)
  4428. {
  4429. // For the first line after defer parse, compute the column relative to the column number
  4430. // of the lexically parent function.
  4431. ULONG offsetFromCurrentFunction = ichMinTok - m_currentNodeFunc->ichMin;
  4432. columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  4433. }
  4434. else
  4435. {
  4436. // if there is no current function, lets give a default of 0.
  4437. columnNumber = 0;
  4438. }
  4439. return columnNumber;
  4440. }
  4441. void Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodeFnc * pnodeFnc)
  4442. {
  4443. if (!fDeclaration && m_ppnodeExprScope)
  4444. {
  4445. // We're tracking function expressions separately from declarations in this scope
  4446. // (e.g., inside a catch scope in standards mode).
  4447. Assert(*m_ppnodeExprScope == nullptr);
  4448. *m_ppnodeExprScope = pnodeFnc;
  4449. m_ppnodeExprScope = &pnodeFnc->pnodeNext;
  4450. }
  4451. else
  4452. {
  4453. Assert(*m_ppnodeScope == nullptr);
  4454. *m_ppnodeScope = pnodeFnc;
  4455. m_ppnodeScope = &pnodeFnc->pnodeNext;
  4456. }
  4457. }
  4458. /***************************************************************************
  4459. Parse a function definition.
  4460. ***************************************************************************/
  4461. template<bool buildAST>
  4462. void Parser::ParseFncDeclHelper(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals, IdentPtr* pFncNamePid, bool fAllowIn)
  4463. {
  4464. Assert(pnodeFnc);
  4465. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4466. // is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred
  4467. ParseNodeFnc * pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4468. ParseNodeFnc * pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;
  4469. int32* pAstSizeSave = m_pCurrentAstSize;
  4470. bool fDeclaration = (flags & fFncDeclaration) != 0;
  4471. bool fLambda = (flags & fFncLambda) != 0;
  4472. bool fAsync = (flags & fFncAsync) != 0;
  4473. bool fModule = (flags & fFncModule) != 0;
  4474. bool fDeferred = false;
  4475. StmtNest *pstmtSave;
  4476. bool fFunctionInBlock = false;
  4477. if (buildAST)
  4478. {
  4479. fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&
  4480. (GetCurrentBlockInfo()->pnodeBlock->scope == nullptr ||
  4481. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock);
  4482. }
  4483. // Save the position of the scanner in case we need to inspect the name hint later
  4484. RestorePoint beginNameHint;
  4485. this->GetScanner()->Capture(&beginNameHint);
  4486. ParseNodeBlock * pnodeFncExprScope = nullptr;
  4487. Scope *fncExprScope = nullptr;
  4488. if (!fDeclaration)
  4489. {
  4490. if (!fLambda)
  4491. {
  4492. pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);
  4493. fncExprScope = pnodeFncExprScope->scope;
  4494. }
  4495. // Function expression: push the new function onto the stack now so that the name (if any) will be
  4496. // local to the new function.
  4497. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4498. }
  4499. if (!fLambda && !fModule)
  4500. {
  4501. this->ParseFncName<buildAST>(pnodeFnc, flags, pFncNamePid);
  4502. }
  4503. if (fDeclaration)
  4504. {
  4505. // Declaration statement: push the new function now, after parsing the name, so the name is local to the
  4506. // enclosing function.
  4507. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4508. }
  4509. if (noStmtContext && pnodeFnc->IsGenerator())
  4510. {
  4511. // Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to
  4512. // detect generator.)
  4513. Error(ERRsyntax, pnodeFnc);
  4514. }
  4515. // switch scanner to treat 'yield' as keyword in generator functions
  4516. // or as an identifier in non-generator functions
  4517. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc->IsGenerator());
  4518. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync);
  4519. if (pnodeFnc->IsGenerator())
  4520. {
  4521. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Generator, m_scriptContext);
  4522. }
  4523. if (fncExprScope && pnodeFnc->pnodeName == nullptr)
  4524. {
  4525. FinishParseBlock(pnodeFncExprScope);
  4526. m_nextBlockId--;
  4527. Adelete(&m_nodeAllocator, fncExprScope);
  4528. fncExprScope = nullptr;
  4529. pnodeFncExprScope = nullptr;
  4530. }
  4531. pnodeFnc->scope = fncExprScope;
  4532. // Start a new statement stack.
  4533. bool topLevelStmt =
  4534. buildAST &&
  4535. !fFunctionInBlock &&
  4536. (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);
  4537. pstmtSave = m_pstmtCur;
  4538. SetCurrentStatement(nullptr);
  4539. RestorePoint beginFormals;
  4540. this->GetScanner()->Capture(&beginFormals);
  4541. BOOL fWasAlreadyStrictMode = IsStrictMode();
  4542. BOOL oldStrictMode = this->m_fUseStrictMode;
  4543. if (fLambda)
  4544. {
  4545. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Lambda, m_scriptContext);
  4546. }
  4547. uint uCanDeferSave = m_grfscr & fscrCanDeferFncParse;
  4548. uint uDeferSave = m_grfscr & fscrWillDeferFncParse;
  4549. if (flags & fFncClassMember)
  4550. {
  4551. // Disable deferral on class members or other construct with unusual text bounds
  4552. // as these are usually trivial, and re-parsing is problematic.
  4553. // NOTE: It is probably worth supporting these cases for memory and load-time purposes,
  4554. // especially as they become more and more common.
  4555. m_grfscr &= ~(fscrCanDeferFncParse | fscrWillDeferFncParse);
  4556. }
  4557. bool isTopLevelDeferredFunc = false;
  4558. #if ENABLE_BACKGROUND_PARSING
  4559. struct AutoFastScanFlag {
  4560. bool savedDoingFastScan;
  4561. AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }
  4562. ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }
  4563. Parser *m_parser;
  4564. } flag(this);
  4565. #endif
  4566. bool doParallel = false;
  4567. #if ENABLE_BACKGROUND_PARSING
  4568. bool parallelJobStarted = false;
  4569. #endif
  4570. if (buildAST)
  4571. {
  4572. bool isLikelyIIFE = !fDeclaration && fUnaryOrParen;
  4573. BOOL isDeferredFnc = IsDeferredFnc();
  4574. // These are the conditions that prohibit upfront deferral *and* redeferral.
  4575. isTopLevelDeferredFunc =
  4576. (m_grfscr & fscrCanDeferFncParse)
  4577. && !m_InAsmMode
  4578. // Don't defer a module function wrapper because we need to do export resolution at parse time
  4579. && !fModule;
  4580. pnodeFnc->SetCanBeDeferred(isTopLevelDeferredFunc && ParseNodeFnc::CanBeRedeferred(pnodeFnc->fncFlags));
  4581. // These are heuristic conditions that prohibit upfront deferral but not redeferral.
  4582. isTopLevelDeferredFunc = isTopLevelDeferredFunc && !isDeferredFnc && WillDeferParse(pnodeFnc->functionId) &&
  4583. (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId));
  4584. #if ENABLE_BACKGROUND_PARSING
  4585. if (!fLambda &&
  4586. !isDeferredFnc &&
  4587. !isLikelyIIFE &&
  4588. !this->IsBackgroundParser() &&
  4589. !this->m_doingFastScan &&
  4590. !(pnodeFncSave && m_currDeferredStub) &&
  4591. !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))
  4592. {
  4593. doParallel = DoParallelParse(pnodeFnc);
  4594. if (doParallel)
  4595. {
  4596. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  4597. Assert(bgp);
  4598. if (bgp->HasFailedBackgroundParseItem())
  4599. {
  4600. Error(ERRsyntax);
  4601. }
  4602. doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);
  4603. if (doParallel)
  4604. {
  4605. parallelJobStarted = true;
  4606. this->m_hasParallelJob = true;
  4607. this->m_doingFastScan = true;
  4608. doParallel = FastScanFormalsAndBody();
  4609. if (doParallel)
  4610. {
  4611. // Let the foreground thread take care of marking the limit on the function node,
  4612. // because in some cases this function's caller will want to change that limit,
  4613. // so we don't want the background thread to try and touch it.
  4614. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  4615. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  4616. }
  4617. }
  4618. }
  4619. }
  4620. #endif
  4621. }
  4622. if (!doParallel)
  4623. {
  4624. #if ENABLE_BACKGROUND_PARSING
  4625. // We don't want to, or couldn't, let the main thread scan past this function body, so parse
  4626. // it for real.
  4627. ParseNodeFnc * pnodeRealFnc = pnodeFnc;
  4628. if (parallelJobStarted)
  4629. {
  4630. // We have to deal with a failure to fast-scan the function (due to syntax error? "/"?) when
  4631. // a background thread may already have begun to work on the job. Both threads can't be allowed to
  4632. // operate on the same node.
  4633. pnodeFnc = CreateDummyFuncNode(fDeclaration);
  4634. }
  4635. #endif
  4636. AnalysisAssert(pnodeFnc);
  4637. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  4638. AnalysisAssert(pnodeBlock != nullptr);
  4639. pnodeFnc->pnodeScopes = pnodeBlock;
  4640. m_ppnodeVar = &pnodeFnc->pnodeParams;
  4641. pnodeFnc->pnodeVars = nullptr;
  4642. ParseNodePtr* varNodesList = &pnodeFnc->pnodeVars;
  4643. ParseNodeVar * argNode = nullptr;
  4644. if (!fModule && !fLambda)
  4645. {
  4646. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  4647. m_ppnodeVar = &pnodeFnc->pnodeVars;
  4648. // Create the built-in arguments symbol
  4649. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  4650. // Save the updated var list
  4651. varNodesList = m_ppnodeVar;
  4652. m_ppnodeVar = ppnodeVarSave;
  4653. }
  4654. ParseNodePtr *ppnodeScopeSave = nullptr;
  4655. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4656. ppnodeScopeSave = m_ppnodeScope;
  4657. if (pnodeBlock)
  4658. {
  4659. // This synthetic block scope will contain all the nested scopes.
  4660. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  4661. pnodeBlock->pnodeStmt = pnodeFnc;
  4662. }
  4663. // Keep nested function declarations and expressions in the same list at function scope.
  4664. // (Indicate this by nulling out the current function expressions list.)
  4665. ppnodeExprScopeSave = m_ppnodeExprScope;
  4666. m_ppnodeExprScope = nullptr;
  4667. uint parenExprDepthSave = m_funcParenExprDepth;
  4668. m_funcParenExprDepth = 0;
  4669. if (!skipFormals)
  4670. {
  4671. bool fLambdaParamsSave = m_reparsingLambdaParams;
  4672. if (fLambda)
  4673. {
  4674. m_reparsingLambdaParams = true;
  4675. }
  4676. DeferredFunctionStub* savedDeferredStub = m_currDeferredStub;
  4677. m_currDeferredStub = nullptr;
  4678. this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags, isTopLevelDeferredFunc);
  4679. m_currDeferredStub = savedDeferredStub;
  4680. m_reparsingLambdaParams = fLambdaParamsSave;
  4681. }
  4682. // Create function body scope
  4683. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  4684. // Set the parameter block's child to the function body block.
  4685. // The pnodeFnc->pnodeScopes list is constructed in such a way that it includes all the scopes in this list.
  4686. // For example if the param scope has one function and body scope has one function then the list will look like below,
  4687. // param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.
  4688. *m_ppnodeScope = pnodeInnerBlock;
  4689. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  4690. // This synthetic block scope will contain all the nested scopes.
  4691. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  4692. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  4693. // DEFER: Begin deferral here (after names are parsed and name nodes created).
  4694. // Create no more AST nodes until we're done.
  4695. // Try to defer this func if all these are true:
  4696. // 0. We are not already in deferred parsing (i.e. buildAST is true)
  4697. // 1. We are not re-parsing a deferred func which is being invoked.
  4698. // 2. Dynamic profile suggests this func can be deferred (and deferred parse is on).
  4699. // 3. This func is top level or defer nested func is on.
  4700. // 4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,
  4701. // or the function is sufficiently long. (I.e., don't defer little nested functions unless we're
  4702. // confident they'll never be executed, because un-deferring nested functions is more expensive.)
  4703. // NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,
  4704. // and we don't want to create function bodies aggressively for little functions.
  4705. // We will also temporarily defer all asm.js functions, except for the asm.js
  4706. // module itself, which we will never defer
  4707. bool strictModeTurnedOn = false;
  4708. if (isTopLevelDeferredFunc &&
  4709. !(this->m_grfscr & fscrEvalCode) &&
  4710. pnodeFnc->IsNested() &&
  4711. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4712. m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&
  4713. #endif
  4714. PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) &&
  4715. (
  4716. !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) ||
  4717. PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId)
  4718. ))
  4719. {
  4720. // Try to scan ahead to the end of the function. If we get there before we've scanned a minimum
  4721. // number of tokens, don't bother deferring, because it's too small.
  4722. if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))
  4723. {
  4724. isTopLevelDeferredFunc = false;
  4725. }
  4726. }
  4727. Scope* paramScope = pnodeFnc->pnodeScopes ? pnodeFnc->pnodeScopes->scope : nullptr;
  4728. if (paramScope != nullptr)
  4729. {
  4730. if (CONFIG_FLAG(ForceSplitScope))
  4731. {
  4732. pnodeFnc->ResetBodyAndParamScopeMerged();
  4733. }
  4734. else if (pnodeFnc->HasNonSimpleParameterList() && pnodeFnc->IsBodyAndParamScopeMerged())
  4735. {
  4736. paramScope->ForEachSymbolUntil([this, paramScope, pnodeFnc](Symbol* sym) {
  4737. if (sym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  4738. {
  4739. // One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.
  4740. pnodeFnc->ResetBodyAndParamScopeMerged();
  4741. return true;
  4742. }
  4743. return false;
  4744. });
  4745. if (pnodeFnc->IsBodyAndParamScopeMerged() && !fDeclaration && pnodeFnc->pnodeName != nullptr)
  4746. {
  4747. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  4748. Symbol* funcSym = pnodeFnc->pnodeName->sym;
  4749. if (funcSym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  4750. {
  4751. // This is a function expression with name captured in the param scope. In non-eval, non-split cases the function
  4752. // name symbol is added to the body scope to make it accessible in the body. But if there is a function or var
  4753. // declaration with the same name in the body then adding to the body will fail. So in this case we have to add
  4754. // the name symbol to the param scope by splitting it.
  4755. pnodeFnc->ResetBodyAndParamScopeMerged();
  4756. }
  4757. }
  4758. }
  4759. }
  4760. // If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.
  4761. // So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice
  4762. // in the same pid ref stack.
  4763. if (paramScope != nullptr && pnodeFnc->IsBodyAndParamScopeMerged())
  4764. {
  4765. paramScope->ForEachSymbol([this](Symbol* paramSym)
  4766. {
  4767. PidRefStack* ref = PushPidRef(paramSym->GetPid());
  4768. ref->SetSym(paramSym);
  4769. });
  4770. }
  4771. AssertMsg(m_funcParenExprDepth == 0, "Paren exprs should have been resolved by the time we finish function formals");
  4772. if (fLambda)
  4773. {
  4774. #ifdef ASMJS_PLAT
  4775. if (m_InAsmMode && (isTopLevelDeferredFunc && m_deferAsmJs))
  4776. {
  4777. // asm.js doesn't support lambda functions
  4778. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Lambda functions are not supported."));
  4779. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Asm.js compilation failed."));
  4780. throw Js::AsmJsParseException();
  4781. }
  4782. #endif
  4783. }
  4784. if (m_token.tk == tkRParen)
  4785. {
  4786. this->GetScanner()->Scan();
  4787. }
  4788. if (fLambda)
  4789. {
  4790. BOOL hadNewLine = this->GetScanner()->FHadNewLine();
  4791. // it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side
  4792. // of the fat arrow, but that expression does not parse as a parameter list. E.g.
  4793. // a.x => { }
  4794. // Therefore check for it and error if not found.
  4795. ChkCurTok(tkDArrow, ERRnoDArrow);
  4796. // Newline character between arrow parameters and fat arrow is a syntax error but we want to check for
  4797. // this after verifying there was a => token. Otherwise we would throw the wrong error.
  4798. if (hadNewLine)
  4799. {
  4800. Error(ERRsyntax);
  4801. }
  4802. }
  4803. if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))
  4804. {
  4805. fDeferred = true;
  4806. this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint, fLambda, pNeedScanRCurly, fAllowIn);
  4807. }
  4808. else
  4809. {
  4810. AnalysisAssert(pnodeFnc);
  4811. // Shouldn't be any temps in the arg list.
  4812. Assert(*m_ppnodeVar == nullptr);
  4813. // Start the var list.
  4814. m_ppnodeVar = varNodesList;
  4815. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  4816. {
  4817. 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"));
  4818. }
  4819. // Keep nested function declarations and expressions in the same list at function scope.
  4820. // (Indicate this by nulling out the current function expressions list.)
  4821. m_ppnodeExprScope = nullptr;
  4822. if (buildAST)
  4823. {
  4824. if (m_token.tk != tkLCurly && fLambda)
  4825. {
  4826. *pNeedScanRCurly = false;
  4827. }
  4828. uint savedStubCount = m_currDeferredStubCount;
  4829. DeferredFunctionStub* savedStub = m_currDeferredStub;
  4830. if (pnodeFnc->IsNested() && pnodeFncSave != nullptr && m_currDeferredStub != nullptr && pnodeFncSave->ichMin != pnodeFnc->ichMin)
  4831. {
  4832. DeferredFunctionStub* childStub = m_currDeferredStub + (pnodeFncSave->nestedCount - 1);
  4833. m_currDeferredStubCount = childStub->nestedCount;
  4834. m_currDeferredStub = childStub->deferredStubs;
  4835. }
  4836. this->FinishFncDecl(pnodeFnc, pNameHint, fLambda, skipFormals, fAllowIn);
  4837. m_currDeferredStub = savedStub;
  4838. m_currDeferredStubCount = savedStubCount;
  4839. }
  4840. else
  4841. {
  4842. this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn, fAllowIn);
  4843. }
  4844. }
  4845. // Restore the paren count for any outer spread/rest error checking.
  4846. m_funcParenExprDepth = parenExprDepthSave;
  4847. if (pnodeInnerBlock)
  4848. {
  4849. FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);
  4850. }
  4851. if (!fModule && (m_token.tk == tkLCurly || !fLambda))
  4852. {
  4853. UpdateArgumentsNode(pnodeFnc, argNode);
  4854. }
  4855. CreateSpecialSymbolDeclarations(pnodeFnc);
  4856. // Restore the lists of scopes that contain function expressions.
  4857. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  4858. m_ppnodeExprScope = ppnodeExprScopeSave;
  4859. Assert(m_ppnodeScope);
  4860. Assert(nullptr == *m_ppnodeScope);
  4861. m_ppnodeScope = ppnodeScopeSave;
  4862. if (pnodeBlock)
  4863. {
  4864. FinishParseBlock(pnodeBlock, *pNeedScanRCurly);
  4865. }
  4866. if (IsStrictMode() || strictModeTurnedOn)
  4867. {
  4868. this->m_fUseStrictMode = TRUE; // Now we know this function is in strict mode
  4869. if (!fWasAlreadyStrictMode)
  4870. {
  4871. // If this function turned on strict mode then we didn't check the formal
  4872. // parameters or function name hint for future reserved word usage. So do that now.
  4873. RestorePoint afterFnc;
  4874. this->GetScanner()->Capture(&afterFnc);
  4875. if (pnodeFnc->pnodeName != nullptr)
  4876. {
  4877. // Rewind to the function name hint and check if the token is a reserved word.
  4878. this->GetScanner()->SeekTo(beginNameHint);
  4879. this->GetScanner()->Scan();
  4880. if (pnodeFnc->IsGenerator())
  4881. {
  4882. Assert(m_token.tk == tkStar);
  4883. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  4884. Assert(!(flags & fFncClassMember));
  4885. this->GetScanner()->Scan();
  4886. }
  4887. if (m_token.IsReservedWord())
  4888. {
  4889. IdentifierExpectedError(m_token);
  4890. }
  4891. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  4892. }
  4893. // Fast forward to formal parameter list, check for future reserved words,
  4894. // then restore scanner as it was.
  4895. this->GetScanner()->SeekToForcingPid(beginFormals);
  4896. CheckStrictFormalParameters();
  4897. this->GetScanner()->SeekTo(afterFnc);
  4898. }
  4899. if (buildAST)
  4900. {
  4901. if (pnodeFnc->pnodeName != nullptr)
  4902. {
  4903. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  4904. CheckStrictModeEvalArgumentsUsage(pnodeFnc->pnodeName->pid, pnodeFnc->pnodeName);
  4905. }
  4906. }
  4907. this->m_fUseStrictMode = oldStrictMode;
  4908. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StrictModeFunction, m_scriptContext);
  4909. }
  4910. ProcessCapturedNames(pnodeFnc);
  4911. if (fDeferred)
  4912. {
  4913. AnalysisAssert(pnodeFnc);
  4914. pnodeFnc->pnodeVars = nullptr;
  4915. }
  4916. #if ENABLE_BACKGROUND_PARSING
  4917. if (parallelJobStarted)
  4918. {
  4919. pnodeFnc = pnodeRealFnc;
  4920. m_currentNodeFunc = pnodeRealFnc;
  4921. // Let the foreground thread take care of marking the limit on the function node,
  4922. // because in some cases this function's caller will want to change that limit,
  4923. // so we don't want the background thread to try and touch it.
  4924. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  4925. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  4926. }
  4927. #endif
  4928. }
  4929. // after parsing asm.js module, we want to reset asm.js state before continuing
  4930. AnalysisAssert(pnodeFnc);
  4931. if (pnodeFnc->GetAsmjsMode())
  4932. {
  4933. m_InAsmMode = false;
  4934. }
  4935. // Restore the statement stack.
  4936. Assert(nullptr == m_pstmtCur);
  4937. SetCurrentStatement(pstmtSave);
  4938. if (pnodeFncExprScope)
  4939. {
  4940. FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);
  4941. }
  4942. m_grfscr |= uCanDeferSave;
  4943. if (!m_stoppedDeferredParse)
  4944. {
  4945. m_grfscr |= uDeferSave;
  4946. }
  4947. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  4948. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  4949. // Restore the current function.
  4950. if (buildAST)
  4951. {
  4952. Assert(pnodeFnc == m_currentNodeFunc);
  4953. m_currentNodeFunc = pnodeFncSave;
  4954. m_pCurrentAstSize = pAstSizeSave;
  4955. if (!fLambda)
  4956. {
  4957. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  4958. m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;
  4959. }
  4960. }
  4961. else
  4962. {
  4963. Assert(pnodeFnc == m_currentNodeDeferredFunc);
  4964. if (!fLambda)
  4965. {
  4966. Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);
  4967. m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;
  4968. }
  4969. m_currentNodeDeferredFunc = pnodeFncSave;
  4970. }
  4971. if (m_currentNodeFunc && pnodeFnc->HasWithStmt())
  4972. {
  4973. GetCurrentFunctionNode()->SetHasWithStmt(true);
  4974. }
  4975. }
  4976. template<bool buildAST>
  4977. void Parser::UpdateCurrentNodeFunc(ParseNodeFnc * pnodeFnc, bool fLambda)
  4978. {
  4979. if (buildAST)
  4980. {
  4981. // Make this the current function and start its sub-function list.
  4982. m_currentNodeFunc = pnodeFnc;
  4983. Assert(m_currentNodeDeferredFunc == nullptr);
  4984. if (!fLambda)
  4985. {
  4986. m_currentNodeNonLambdaFunc = pnodeFnc;
  4987. }
  4988. }
  4989. else // if !buildAST
  4990. {
  4991. AnalysisAssert(pnodeFnc);
  4992. if (!fLambda)
  4993. {
  4994. m_currentNodeNonLambdaDeferredFunc = pnodeFnc;
  4995. }
  4996. m_currentNodeDeferredFunc = pnodeFnc;
  4997. }
  4998. }
  4999. void Parser::ParseTopLevelDeferredFunc(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeFncParent, LPCOLESTR pNameHint, bool fLambda, bool *pNeedScanRCurly, bool fAllowIn)
  5000. {
  5001. // Parse a function body that is a transition point from building AST to doing fast syntax check.
  5002. pnodeFnc->pnodeVars = nullptr;
  5003. pnodeFnc->pnodeBody = nullptr;
  5004. this->m_deferringAST = TRUE;
  5005. // Put the scanner into "no hashing" mode.
  5006. BYTE deferFlags = this->GetScanner()->SetDeferredParse(TRUE);
  5007. if (!fLambda)
  5008. {
  5009. ChkCurTok(tkLCurly, ERRnoLcurly);
  5010. }
  5011. else
  5012. {
  5013. // Lambda may consist of a single expression instead of a block
  5014. if (this->GetScanner()->m_ptoken->tk == tkLCurly)
  5015. {
  5016. this->GetScanner()->Scan();
  5017. }
  5018. else
  5019. {
  5020. *pNeedScanRCurly = false;
  5021. }
  5022. }
  5023. ParseNodePtr *ppnodeVarSave = m_ppnodeVar;
  5024. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5025. // Don't try and skip scanning nested deferred lambdas which have only a single expression in the body.
  5026. // Their more-complicated text extents won't match the deferred-stub and the single expression should be fast to scan, anyway.
  5027. if (fLambda && !*pNeedScanRCurly)
  5028. {
  5029. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5030. }
  5031. else if (pnodeFncParent != nullptr && m_currDeferredStub != nullptr && !pnodeFncParent->HasDefaultArguments())
  5032. {
  5033. // We've already parsed this function body for syntax errors on the initial parse of the script.
  5034. // We have information that allows us to skip it, so do so.
  5035. Assert(pnodeFncParent->nestedCount != 0);
  5036. DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->nestedCount - 1);
  5037. Assert(pnodeFnc->ichMin == stub->ichMin
  5038. || (stub->fncFlags & kFunctionIsAsync) == kFunctionIsAsync
  5039. || ((stub->fncFlags & kFunctionIsGenerator) == kFunctionIsGenerator && (stub->fncFlags & kFunctionIsMethod) == kFunctionIsMethod));
  5040. if (stub->fncFlags & kFunctionCallsEval)
  5041. {
  5042. this->MarkEvalCaller();
  5043. }
  5044. PHASE_PRINT_TRACE1(
  5045. Js::SkipNestedDeferredPhase,
  5046. _u("Skipping nested deferred function %d. %s: %d...%d\n"),
  5047. pnodeFnc->functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);
  5048. this->GetScanner()->SeekTo(stub->restorePoint, m_nextFunctionId);
  5049. for (uint i = 0; i < stub->capturedNameCount; i++)
  5050. {
  5051. int stringId = stub->capturedNameSerializedIds[i];
  5052. uint32 stringLength = 0;
  5053. LPCWSTR stringVal = Js::ByteCodeSerializer::DeserializeString(stub, stringId, stringLength);
  5054. OUTPUT_TRACE_DEBUGONLY(Js::SkipNestedDeferredPhase, _u("\tPushing a reference to '%s'\n"), stringVal);
  5055. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(stringVal, stringLength);
  5056. PushPidRef(pid);
  5057. }
  5058. pnodeFnc->nestedCount = stub->nestedCount;
  5059. pnodeFnc->deferredStub = stub->deferredStubs;
  5060. pnodeFnc->fncFlags = (FncFlags)(pnodeFnc->fncFlags | stub->fncFlags);
  5061. }
  5062. else
  5063. {
  5064. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */);
  5065. }
  5066. if (!fLambda || *pNeedScanRCurly)
  5067. {
  5068. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5069. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5070. }
  5071. m_ppnodeVar = ppnodeVarSave;
  5072. // Restore the scanner's default hashing mode.
  5073. // Do this before we consume the next token.
  5074. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  5075. if (*pNeedScanRCurly)
  5076. {
  5077. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5078. }
  5079. #if DBG
  5080. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  5081. #endif
  5082. this->m_deferringAST = FALSE;
  5083. }
  5084. bool Parser::DoParallelParse(ParseNodeFnc * pnodeFnc) const
  5085. {
  5086. #if ENABLE_BACKGROUND_PARSING
  5087. if (!PHASE_ENABLED_RAW(ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId))
  5088. {
  5089. return false;
  5090. }
  5091. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  5092. return bgp != nullptr;
  5093. #else
  5094. return false;
  5095. #endif
  5096. }
  5097. bool Parser::ScanAheadToFunctionEnd(uint count)
  5098. {
  5099. bool found = false;
  5100. uint curlyDepth = 0;
  5101. RestorePoint funcStart;
  5102. this->GetScanner()->Capture(&funcStart);
  5103. for (uint i = 0; i < count; i++)
  5104. {
  5105. switch (m_token.tk)
  5106. {
  5107. case tkStrTmplBegin:
  5108. case tkStrTmplMid:
  5109. case tkStrTmplEnd:
  5110. case tkDiv:
  5111. case tkAsgDiv:
  5112. case tkScanError:
  5113. case tkEOF:
  5114. goto LEnd;
  5115. case tkLCurly:
  5116. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5117. break;
  5118. case tkRCurly:
  5119. if (curlyDepth == 1)
  5120. {
  5121. found = true;
  5122. goto LEnd;
  5123. }
  5124. if (curlyDepth == 0)
  5125. {
  5126. goto LEnd;
  5127. }
  5128. curlyDepth--;
  5129. break;
  5130. }
  5131. this->GetScanner()->ScanAhead();
  5132. }
  5133. LEnd:
  5134. this->GetScanner()->SeekTo(funcStart);
  5135. return found;
  5136. }
  5137. #if ENABLE_BACKGROUND_PARSING
  5138. bool Parser::FastScanFormalsAndBody()
  5139. {
  5140. // The scanner is currently pointing just past the name of a function.
  5141. // The idea here is to find the end of the function body as quickly as possible,
  5142. // by tokenizing and tracking {}'s if possible.
  5143. // String templates require some extra logic but can be handled.
  5144. // The real wrinkle is "/" and "/=", which may indicate either a RegExp literal or a division, depending
  5145. // on the context.
  5146. // To handle this with minimal work, keep track of the last ";" seen at each {} depth. If we see one of the
  5147. // difficult tokens, rewind to the last ";" at the current {} depth and parse statements until we pass the
  5148. // point where we had to rewind. This will process the "/" as required.
  5149. RestorePoint funcStart;
  5150. this->GetScanner()->Capture(&funcStart);
  5151. const int maxRestorePointDepth = 16;
  5152. struct FastScanRestorePoint
  5153. {
  5154. RestorePoint restorePoint;
  5155. uint parenDepth;
  5156. Js::LocalFunctionId functionId;
  5157. int blockId;
  5158. FastScanRestorePoint() : restorePoint(), parenDepth(0) {};
  5159. };
  5160. FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];
  5161. charcount_t ichStart = this->GetScanner()->IchMinTok();
  5162. uint blockIdSave = m_nextBlockId;
  5163. uint functionIdSave = *m_nextFunctionId;
  5164. uint curlyDepth = 0;
  5165. uint strTmplDepth = 0;
  5166. for (;;)
  5167. {
  5168. switch (m_token.tk)
  5169. {
  5170. case tkStrTmplBegin:
  5171. UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);
  5172. // Fall through
  5173. case tkStrTmplMid:
  5174. case tkLCurly:
  5175. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5176. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5177. break;
  5178. case tkStrTmplEnd:
  5179. // We can assert here, because the scanner will only return this token if we've told it we're
  5180. // in a string template.
  5181. Assert(strTmplDepth > 0);
  5182. strTmplDepth--;
  5183. break;
  5184. case tkRCurly:
  5185. if (curlyDepth == 1)
  5186. {
  5187. Assert(strTmplDepth == 0);
  5188. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5189. {
  5190. Output::Print(_u("Finished fast seek: %d. %s -- %d...%d\n"),
  5191. m_currentNodeFunc->functionId,
  5192. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5193. ichStart, this->GetScanner()->IchLimTok());
  5194. }
  5195. return true;
  5196. }
  5197. if (curlyDepth < maxRestorePointDepth)
  5198. {
  5199. lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;
  5200. }
  5201. curlyDepth--;
  5202. if (strTmplDepth > 0)
  5203. {
  5204. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  5205. }
  5206. break;
  5207. case tkSColon:
  5208. // Track the location of the ";" (if it's outside parens, as we don't, for instance, want
  5209. // to track the ";"'s in a for-loop header. If we find it's important to rewind within a paren
  5210. // expression, we can do something more sophisticated.)
  5211. if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)
  5212. {
  5213. this->GetScanner()->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);
  5214. lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;
  5215. lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;
  5216. }
  5217. break;
  5218. case tkLParen:
  5219. if (curlyDepth < maxRestorePointDepth)
  5220. {
  5221. UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);
  5222. }
  5223. break;
  5224. case tkRParen:
  5225. if (curlyDepth < maxRestorePointDepth)
  5226. {
  5227. Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);
  5228. lastSColonAtCurlyDepth[curlyDepth].parenDepth--;
  5229. }
  5230. break;
  5231. case tkID:
  5232. {
  5233. charcount_t tokLength = this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok();
  5234. // Detect the function and class keywords so we can track function ID's.
  5235. // (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token
  5236. // to a PID.)
  5237. // Detect try/catch/for to increment block count for them.
  5238. switch (tokLength)
  5239. {
  5240. case 3:
  5241. if (!memcmp(this->GetScanner()->PchMinTok(), "try", 3) || !memcmp(this->GetScanner()->PchMinTok(), "for", 3))
  5242. {
  5243. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5244. }
  5245. break;
  5246. case 5:
  5247. if (!memcmp(this->GetScanner()->PchMinTok(), "catch", 5))
  5248. {
  5249. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5250. }
  5251. else if (!memcmp(this->GetScanner()->PchMinTok(), "class", 5))
  5252. {
  5253. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5254. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5255. }
  5256. break;
  5257. case 8:
  5258. if (!memcmp(this->GetScanner()->PchMinTok(), "function", 8))
  5259. {
  5260. // Account for the possible func expr scope or dummy block for missing {}'s around a declaration
  5261. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5262. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5263. }
  5264. break;
  5265. }
  5266. break;
  5267. }
  5268. case tkDArrow:
  5269. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5270. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5271. break;
  5272. case tkDiv:
  5273. case tkAsgDiv:
  5274. {
  5275. int opl;
  5276. OpCode nop;
  5277. tokens tkPrev = this->GetScanner()->m_tkPrevious;
  5278. if ((this->GetHashTbl()->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||
  5279. (this->GetHashTbl()->TokIsUnop(tkPrev, &opl, &nop) &&
  5280. nop != knopNone &&
  5281. tkPrev != tkInc &&
  5282. tkPrev != tkDec) ||
  5283. tkPrev == tkColon ||
  5284. tkPrev == tkLParen ||
  5285. tkPrev == tkLBrack ||
  5286. tkPrev == tkRETURN)
  5287. {
  5288. // Previous token indicates that we're starting an expression here and can't have a
  5289. // binary operator now.
  5290. // Assume this is a RegExp.
  5291. ParseRegExp<false>();
  5292. break;
  5293. }
  5294. uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;
  5295. for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)
  5296. {
  5297. // We don't know whether we've got a RegExp or a divide. Rewind to the last safe ";"
  5298. // if we can and parse statements until we pass this point.
  5299. if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)
  5300. {
  5301. break;
  5302. }
  5303. }
  5304. if (tempCurlyDepth != (uint)-1)
  5305. {
  5306. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5307. int32 *pastSizeSave = m_pCurrentAstSize;
  5308. uint *pnestedCountSave = m_pnestedCount;
  5309. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  5310. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  5311. ParseNodeFnc * pnodeFnc = CreateDummyFuncNode(true);
  5312. charcount_t ichStop = this->GetScanner()->IchLimTok();
  5313. curlyDepth = tempCurlyDepth;
  5314. this->GetScanner()->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);
  5315. m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;
  5316. *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;
  5317. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5318. pnodeFnc->pnodeScopes = pnodeBlock;
  5319. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  5320. m_ppnodeExprScope = nullptr;
  5321. this->GetScanner()->Scan();
  5322. do
  5323. {
  5324. ParseStatement<false>();
  5325. } while (this->GetScanner()->IchMinTok() < ichStop);
  5326. FinishParseBlock(pnodeBlock);
  5327. m_currentNodeFunc = pnodeFncSave;
  5328. m_pCurrentAstSize = pastSizeSave;
  5329. m_pnestedCount = pnestedCountSave;
  5330. m_ppnodeScope = ppnodeScopeSave;
  5331. m_ppnodeExprScope = ppnodeExprScopeSave;
  5332. // We've already consumed the first token of the next statement, so just continue
  5333. // without a further scan.
  5334. continue;
  5335. }
  5336. }
  5337. // fall through to rewind to function start
  5338. case tkScanError:
  5339. case tkEOF:
  5340. // Unexpected token.
  5341. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5342. {
  5343. Output::Print(_u("Failed fast seek: %d. %s -- %d...%d\n"),
  5344. m_currentNodeFunc->functionId,
  5345. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5346. ichStart, this->GetScanner()->IchLimTok());
  5347. }
  5348. m_nextBlockId = blockIdSave;
  5349. *m_nextFunctionId = functionIdSave;
  5350. this->GetScanner()->SeekTo(funcStart);
  5351. return false;
  5352. }
  5353. this->GetScanner()->ScanNoKeywords();
  5354. }
  5355. }
  5356. #endif
  5357. ParseNodeFnc * Parser::CreateDummyFuncNode(bool fDeclaration)
  5358. {
  5359. // Create a dummy node and make it look like the current function declaration.
  5360. // Do this in situations where we want to parse statements without impacting
  5361. // the state of the "real" AST.
  5362. ParseNodeFnc * pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5363. pnodeFnc->SetDeclaration(fDeclaration);
  5364. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  5365. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  5366. m_pCurrentAstSize = &pnodeFnc->astSize;
  5367. m_currentNodeFunc = pnodeFnc;
  5368. m_pnestedCount = &pnodeFnc->nestedCount;
  5369. return pnodeFnc;
  5370. }
  5371. void Parser::ParseNestedDeferredFunc(ParseNodeFnc * pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn, bool fAllowIn)
  5372. {
  5373. // Parse a function nested inside another deferred function.
  5374. size_t lengthBeforeBody = this->GetSourceLength();
  5375. if (m_token.tk != tkLCurly && fLambda)
  5376. {
  5377. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5378. *pNeedScanRCurly = false;
  5379. }
  5380. else
  5381. {
  5382. ChkCurTok(tkLCurly, ERRnoLcurly);
  5383. bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;
  5384. m_ppnodeVar = &m_currentNodeDeferredFunc->pnodeVars;
  5385. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */, detectStrictModeOn);
  5386. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5387. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5388. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5389. }
  5390. if (*pStrictModeTurnedOn)
  5391. {
  5392. pnodeFnc->SetStrictMode(true);
  5393. }
  5394. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  5395. {
  5396. // Record the end of the function and the function ID increment that happens inside the function.
  5397. // Byte code gen will use this to build stub information to allow us to skip this function when the
  5398. // enclosing function is fully parsed.
  5399. RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);
  5400. this->GetScanner()->Capture(restorePoint,
  5401. *m_nextFunctionId - pnodeFnc->functionId - 1,
  5402. lengthBeforeBody - this->GetSourceLength());
  5403. pnodeFnc->pRestorePoint = restorePoint;
  5404. }
  5405. }
  5406. template<bool buildAST>
  5407. void Parser::ParseFncName(ParseNodeFnc * pnodeFnc, ushort flags, IdentPtr* pFncNamePid)
  5408. {
  5409. Assert(pnodeFnc);
  5410. BOOL fDeclaration = flags & fFncDeclaration;
  5411. BOOL fIsAsync = flags & fFncAsync;
  5412. this->GetScanner()->Scan();
  5413. // If generators are enabled then we are in a recent enough version
  5414. // that deferred parsing will create a parse node for pnodeFnc and
  5415. // it is safe to assume it is not null.
  5416. if (flags & fFncGenerator)
  5417. {
  5418. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5419. pnodeFnc->SetIsGenerator();
  5420. }
  5421. else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  5422. m_token.tk == tkStar &&
  5423. !(flags & fFncClassMember))
  5424. {
  5425. if (!fDeclaration)
  5426. {
  5427. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(!fDeclaration);
  5428. this->GetScanner()->Scan();
  5429. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5430. }
  5431. else
  5432. {
  5433. this->GetScanner()->Scan();
  5434. }
  5435. pnodeFnc->SetIsGenerator();
  5436. }
  5437. if (fIsAsync)
  5438. {
  5439. if (pnodeFnc->IsGenerator())
  5440. {
  5441. Error(ERRsyntax);
  5442. }
  5443. pnodeFnc->SetIsAsync();
  5444. }
  5445. pnodeFnc->pnodeName = nullptr;
  5446. if ((m_token.tk != tkID || flags & fFncNoName)
  5447. && (IsStrictMode() || (pnodeFnc->IsGenerator()) || m_token.tk != tkYIELD || fDeclaration)) // Function expressions can have the name yield even inside generator functions
  5448. {
  5449. if (fDeclaration ||
  5450. m_token.IsReservedWord()) // For example: var x = (function break(){});
  5451. {
  5452. IdentifierExpectedError(m_token);
  5453. }
  5454. return;
  5455. }
  5456. Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration));
  5457. if (IsStrictMode())
  5458. {
  5459. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  5460. }
  5461. IdentPtr pidBase = m_token.GetIdentifier(this->GetHashTbl());
  5462. pnodeFnc->pnodeName = CreateDeclNode(knopVarDecl, pidBase, STFunction);
  5463. pnodeFnc->pid = pnodeFnc->pnodeName->pid;
  5464. if (pFncNamePid != nullptr)
  5465. {
  5466. *pFncNamePid = pidBase;
  5467. }
  5468. this->GetScanner()->Scan();
  5469. }
  5470. void Parser::ValidateFormals()
  5471. {
  5472. ParseFncFormals<false>(this->GetCurrentFunctionNode(), nullptr, fFncNoFlgs);
  5473. // Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.
  5474. this->GetScanner()->Scan();
  5475. }
  5476. void Parser::ValidateSourceElementList()
  5477. {
  5478. ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);
  5479. }
  5480. void Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)
  5481. {
  5482. bool isStrictMode = IsStrictMode();
  5483. if (isStrictMode)
  5484. {
  5485. CheckStrictModeEvalArgumentsUsage(pid);
  5486. }
  5487. if (formals->Has(pid))
  5488. {
  5489. if (isStrictMode)
  5490. {
  5491. Error(ERRES5ArgSame);
  5492. }
  5493. else
  5494. {
  5495. Error(ERRFormalSame);
  5496. }
  5497. }
  5498. else
  5499. {
  5500. formals->Prepend(pid);
  5501. }
  5502. }
  5503. template<bool buildAST>
  5504. void Parser::ParseFncFormals(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeParentFnc, ushort flags, bool isTopLevelDeferredFunc)
  5505. {
  5506. bool fLambda = (flags & fFncLambda) != 0;
  5507. bool fMethod = (flags & fFncMethod) != 0;
  5508. bool fNoArg = (flags & fFncNoArg) != 0;
  5509. bool fOneArg = (flags & fFncOneArg) != 0;
  5510. bool fAsync = (flags & fFncAsync) != 0;
  5511. bool fPreviousYieldIsKeyword = false;
  5512. bool fPreviousAwaitIsKeyword = false;
  5513. if (fLambda)
  5514. {
  5515. fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeParentFnc != nullptr && pnodeParentFnc->IsGenerator());
  5516. fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->IsAsync()));
  5517. }
  5518. Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.
  5519. // strictFormals corresponds to the StrictFormalParameters grammar production
  5520. // in the ES spec which just means duplicate names are not allowed
  5521. bool fStrictFormals = IsStrictMode() || fLambda || fMethod;
  5522. // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
  5523. bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
  5524. AutoTempForcePid autoForcePid(this->GetScanner(), forcePid);
  5525. // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
  5526. if (fLambda && m_token.tk == tkID)
  5527. {
  5528. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5529. CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5530. CheckPidIsValid(pid);
  5531. this->GetScanner()->Scan();
  5532. if (m_token.tk != tkDArrow)
  5533. {
  5534. Error(ERRsyntax, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  5535. }
  5536. if (fLambda)
  5537. {
  5538. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5539. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5540. }
  5541. return;
  5542. }
  5543. else if (fLambda && m_token.tk == tkAWAIT)
  5544. {
  5545. // async await => {}
  5546. IdentifierExpectedError(m_token);
  5547. }
  5548. // Otherwise, must have a parameter list within parens.
  5549. ChkCurTok(tkLParen, ERRnoLparen);
  5550. // Now parse the list of arguments, if present
  5551. if (m_token.tk == tkRParen)
  5552. {
  5553. if (fOneArg)
  5554. {
  5555. Error(ERRSetterMustHaveOneParameter);
  5556. }
  5557. }
  5558. else
  5559. {
  5560. if (fNoArg)
  5561. {
  5562. Error(ERRGetterMustHaveNoParameters);
  5563. }
  5564. SList<IdentPtr> formals(&m_nodeAllocator);
  5565. ParseNodeVar * pnodeT = nullptr;
  5566. bool seenRestParameter = false;
  5567. bool isNonSimpleParameterList = false;
  5568. for (Js::ArgSlot argPos = 0; ; ++argPos)
  5569. {
  5570. bool isBindingPattern = false;
  5571. if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
  5572. {
  5573. // Possible rest parameter
  5574. this->GetScanner()->Scan();
  5575. seenRestParameter = true;
  5576. }
  5577. if (m_token.tk != tkID)
  5578. {
  5579. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  5580. {
  5581. // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
  5582. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5583. this->GetCurrentFunctionNode()->SetHasDestructuredParams();
  5584. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5585. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5586. ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
  5587. Assert(ppNodeLex != nullptr);
  5588. ParseNodeParamPattern * paramPattern = nullptr;
  5589. ParseNode * pnodePattern = nullptr;
  5590. if (isTopLevelDeferredFunc)
  5591. {
  5592. pnodePattern = ParseDestructuredLiteral<false>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5593. }
  5594. else
  5595. {
  5596. pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5597. }
  5598. // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
  5599. for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->AsParseNodeVar()->pnodeNext)
  5600. {
  5601. Assert(lexNode->IsVarLetOrConst());
  5602. UpdateOrCheckForDuplicateInFormals(lexNode->AsParseNodeVar()->pid, &formals);
  5603. lexNode->AsParseNodeVar()->sym->SetSymbolType(STFormal);
  5604. if (lexNode->AsParseNodeVar()->pid == wellKnownPropertyPids.arguments)
  5605. {
  5606. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5607. }
  5608. }
  5609. m_ppnodeVar = ppnodeVarSave;
  5610. if (buildAST)
  5611. {
  5612. if (isTopLevelDeferredFunc)
  5613. {
  5614. Assert(pnodePattern == nullptr);
  5615. // Create a dummy pattern node as we need the node to be considered for the param count
  5616. paramPattern = CreateDummyParamPatternNode(this->GetScanner()->IchMinTok());
  5617. }
  5618. else
  5619. {
  5620. Assert(pnodePattern);
  5621. paramPattern = CreateParamPatternNode(pnodePattern);
  5622. }
  5623. // Linking the current formal parameter (which is pattern parameter) with other formals.
  5624. *m_ppnodeVar = paramPattern;
  5625. paramPattern->pnodeNext = nullptr;
  5626. m_ppnodeVar = &paramPattern->pnodeNext;
  5627. }
  5628. isBindingPattern = true;
  5629. isNonSimpleParameterList = true;
  5630. }
  5631. else
  5632. {
  5633. IdentifierExpectedError(m_token);
  5634. }
  5635. }
  5636. if (!isBindingPattern)
  5637. {
  5638. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5639. LPCOLESTR pNameHint = pid->Psz();
  5640. uint32 nameHintLength = pid->Cch();
  5641. uint32 nameHintOffset = 0;
  5642. if (seenRestParameter)
  5643. {
  5644. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5645. if (flags & fFncOneArg)
  5646. {
  5647. // The parameter of a setter cannot be a rest parameter.
  5648. Error(ERRUnexpectedEllipsis);
  5649. }
  5650. pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
  5651. pnodeT->sym->SetIsNonSimpleParameter(true);
  5652. if (buildAST)
  5653. {
  5654. // When only validating formals, we won't have a function node.
  5655. pnodeFnc->pnodeRest = pnodeT;
  5656. if (!isNonSimpleParameterList)
  5657. {
  5658. // This is the first non-simple parameter we've seen. We need to go back
  5659. // and set the Symbols of all previous parameters.
  5660. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5661. }
  5662. }
  5663. isNonSimpleParameterList = true;
  5664. }
  5665. else
  5666. {
  5667. pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5668. if (isNonSimpleParameterList)
  5669. {
  5670. pnodeT->sym->SetIsNonSimpleParameter(true);
  5671. }
  5672. }
  5673. if (buildAST && pid == wellKnownPropertyPids.arguments)
  5674. {
  5675. // This formal parameter overrides the built-in 'arguments' object
  5676. m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5677. }
  5678. if (fStrictFormals)
  5679. {
  5680. UpdateOrCheckForDuplicateInFormals(pid, &formals);
  5681. }
  5682. this->GetScanner()->Scan();
  5683. if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)
  5684. {
  5685. Error(ERRRestLastArg);
  5686. }
  5687. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5688. {
  5689. if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
  5690. {
  5691. Error(ERRRestWithDefault);
  5692. }
  5693. // In defer parse mode we have to flag the function node to indicate that it has default arguments
  5694. // so that it will be considered for any syntax error scenario.
  5695. // Also mark it before parsing the expression as it may contain functions.
  5696. ParseNodeFnc * currentFncNode = GetCurrentFunctionNode();
  5697. if (!currentFncNode->HasDefaultArguments())
  5698. {
  5699. currentFncNode->SetHasDefaultArguments();
  5700. currentFncNode->SetHasNonSimpleParameterList();
  5701. currentFncNode->firstDefaultArg = argPos;
  5702. }
  5703. this->GetScanner()->Scan();
  5704. ParseNodePtr pnodeInit;
  5705. if (isTopLevelDeferredFunc)
  5706. {
  5707. // Defer default expressions if the function will be deferred, since we know they can't be evaluated
  5708. // until the function is fully compiled, and generating code for a function nested inside a deferred function
  5709. // creates inconsistencies.
  5710. pnodeInit = ParseExpr<false>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5711. }
  5712. else
  5713. {
  5714. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5715. }
  5716. if (buildAST && pnodeInit && pnodeInit->nop == knopFncDecl)
  5717. {
  5718. Assert(nameHintLength >= nameHintOffset);
  5719. ParseNodeFnc * pnodeFncInit = pnodeInit->AsParseNodeFnc();
  5720. pnodeFncInit->hint = pNameHint;
  5721. pnodeFncInit->hintLength = nameHintLength;
  5722. pnodeFncInit->hintOffset = nameHintOffset;
  5723. }
  5724. AnalysisAssert(pnodeT);
  5725. pnodeT->sym->SetIsNonSimpleParameter(true);
  5726. if (!isNonSimpleParameterList)
  5727. {
  5728. if (buildAST)
  5729. {
  5730. // This is the first non-simple parameter we've seen. We need to go back
  5731. // and set the Symbols of all previous parameters.
  5732. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5733. }
  5734. // There may be previous parameters that need to be checked for duplicates.
  5735. isNonSimpleParameterList = true;
  5736. }
  5737. if (buildAST)
  5738. {
  5739. if (!m_currentNodeFunc->HasDefaultArguments())
  5740. {
  5741. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, DefaultArgFunction, m_scriptContext);
  5742. }
  5743. pnodeT->pnodeInit = pnodeInit;
  5744. pnodeT->ichLim = this->GetScanner()->IchLimTok();
  5745. }
  5746. }
  5747. }
  5748. if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
  5749. {
  5750. Error(ERRFormalSame);
  5751. }
  5752. if (flags & fFncOneArg)
  5753. {
  5754. if (m_token.tk != tkRParen)
  5755. {
  5756. Error(ERRSetterMustHaveOneParameter);
  5757. }
  5758. break; //enforce only one arg
  5759. }
  5760. if (m_token.tk != tkComma)
  5761. {
  5762. break;
  5763. }
  5764. this->GetScanner()->Scan();
  5765. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5766. {
  5767. break;
  5768. }
  5769. }
  5770. if (seenRestParameter)
  5771. {
  5772. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Rest, m_scriptContext);
  5773. }
  5774. if (m_token.tk != tkRParen)
  5775. {
  5776. Error(ERRnoRparen);
  5777. }
  5778. if (this->GetCurrentFunctionNode()->CallsEval() || this->GetCurrentFunctionNode()->ChildCallsEval())
  5779. {
  5780. Assert(pnodeFnc->HasNonSimpleParameterList());
  5781. pnodeFnc->ResetBodyAndParamScopeMerged();
  5782. }
  5783. }
  5784. Assert(m_token.tk == tkRParen);
  5785. if (fLambda)
  5786. {
  5787. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5788. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5789. }
  5790. }
  5791. template<bool buildAST>
  5792. ParseNodePtr Parser::GenerateModuleFunctionWrapper()
  5793. {
  5794. ParseNodePtr pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fFncModule, nullptr, false, true, true);
  5795. ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);
  5796. return callNode;
  5797. }
  5798. template<bool buildAST>
  5799. ParseNodeFnc * Parser::GenerateEmptyConstructor(bool extends)
  5800. {
  5801. ParseNodeFnc * pnodeFnc;
  5802. // Create the node.
  5803. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5804. pnodeFnc->SetNested(NULL != m_currentNodeFunc);
  5805. pnodeFnc->SetStrictMode();
  5806. pnodeFnc->SetDeclaration(TRUE);
  5807. pnodeFnc->SetIsMethod(TRUE);
  5808. pnodeFnc->SetIsClassMember(TRUE);
  5809. pnodeFnc->SetIsClassConstructor(TRUE);
  5810. pnodeFnc->SetIsBaseClassConstructor(!extends);
  5811. pnodeFnc->SetHasNonThisStmt();
  5812. pnodeFnc->SetIsGeneratedDefault(TRUE);
  5813. pnodeFnc->SetHasComputedName();
  5814. pnodeFnc->SetHasHomeObj();
  5815. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  5816. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5817. pnodeFnc->ichMin = this->GetScanner()->IchMinTok();
  5818. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5819. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  5820. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  5821. pnodeFnc->functionId = (*m_nextFunctionId);
  5822. // In order to (re-)defer the default constructor, we need to, for instance, track
  5823. // deferred class expression the way we track function expression, since we lose the part of the source
  5824. // that tells us which we have.
  5825. Assert(!pnodeFnc->canBeDeferred);
  5826. #ifdef DBG
  5827. pnodeFnc->deferredParseNextFunctionId = *(this->m_nextFunctionId);
  5828. #endif
  5829. AppendFunctionToScopeList(true, pnodeFnc);
  5830. if (m_nextFunctionId)
  5831. {
  5832. (*m_nextFunctionId)++;
  5833. }
  5834. // Update the count of functions nested in the current parent.
  5835. if (m_pnestedCount)
  5836. {
  5837. (*m_pnestedCount)++;
  5838. }
  5839. if (this->GetScanner()->IchMinTok() >= this->GetScanner()->IchMinLine())
  5840. {
  5841. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  5842. pnodeFnc->columnNumber = this->GetScanner()->IchMinTok() - this->GetScanner()->IchMinLine();
  5843. }
  5844. else if (m_currentNodeFunc)
  5845. {
  5846. // For the first line after defer parse, compute the column relative to the column number
  5847. // of the lexically parent function.
  5848. ULONG offsetFromCurrentFunction = this->GetScanner()->IchMinTok() - m_currentNodeFunc->ichMin;
  5849. pnodeFnc->columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  5850. }
  5851. else
  5852. {
  5853. // if there is no current function, lets give a default of 0.
  5854. pnodeFnc->columnNumber = 0;
  5855. }
  5856. int32 * pAstSizeSave = m_pCurrentAstSize;
  5857. m_pCurrentAstSize = &(pnodeFnc->astSize);
  5858. // Make this the current function.
  5859. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5860. m_currentNodeFunc = pnodeFnc;
  5861. ParseNodeName * argsId = nullptr;
  5862. ParseNodePtr *lastNodeRef = nullptr;
  5863. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  5864. if (buildAST && extends)
  5865. {
  5866. // constructor(...args) { super(...args); }
  5867. // ^^^^^^^
  5868. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5869. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5870. IdentPtr pidargs = this->GetHashTbl()->PidHashNameLen(_u("args"), sizeof("args") - 1);
  5871. ParseNodeVar * pnodeT = CreateVarDeclNode(pidargs, STFormal);
  5872. pnodeT->sym->SetIsNonSimpleParameter(true);
  5873. pnodeFnc->pnodeRest = pnodeT;
  5874. PidRefStack *ref = this->PushPidRef(pidargs);
  5875. argsId = CreateNameNode(pidargs, ref, pnodeFnc->ichMin, pnodeFnc->ichLim);
  5876. m_ppnodeVar = ppnodeVarSave;
  5877. }
  5878. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5879. pnodeBlock->pnodeScopes = pnodeInnerBlock;
  5880. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  5881. pnodeFnc->pnodeScopes = pnodeBlock;
  5882. if (buildAST)
  5883. {
  5884. if (extends)
  5885. {
  5886. // constructor(...args) { super(...args); }
  5887. // ^^^^^^^^^^^^^^^
  5888. Assert(argsId);
  5889. ParseNodeUni * spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);
  5890. ParseNodeSpecialName * superRef = ReferenceSpecialName(wellKnownPropertyPids._superConstructor, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5891. pnodeFnc->SetHasSuperReference(TRUE);
  5892. ParseNodeSuperCall * callNode = CreateSuperCallNode(superRef, spreadArg);
  5893. callNode->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5894. callNode->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  5895. callNode->spreadArgCount = 1;
  5896. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, callNode);
  5897. }
  5898. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  5899. }
  5900. FinishParseBlock(pnodeInnerBlock);
  5901. CreateSpecialSymbolDeclarations(pnodeFnc);
  5902. FinishParseBlock(pnodeBlock);
  5903. m_currentNodeFunc = pnodeFncSave;
  5904. m_pCurrentAstSize = pAstSizeSave;
  5905. return pnodeFnc;
  5906. }
  5907. template<bool buildAST>
  5908. void Parser::ParseExpressionLambdaBody(ParseNodeFnc * pnodeLambda, bool fAllowIn)
  5909. {
  5910. ParseNodePtr *lastNodeRef = nullptr;
  5911. // The lambda body is a single expression, the result of which is the return value.
  5912. ParseNodeReturn * pnodeRet = nullptr;
  5913. if (buildAST)
  5914. {
  5915. pnodeRet = CreateNodeForOpT<knopReturn>();
  5916. pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;
  5917. pnodeLambda->pnodeScopes->pnodeStmt = pnodeRet;
  5918. }
  5919. IdentToken token;
  5920. charcount_t lastRParen = 0;
  5921. // We need to disable deferred parse mode in the scanner because the lambda body doesn't end with a right paren.
  5922. // The scanner needs to create a pid in the case of a string constant token immediately following the lambda body expression.
  5923. // Otherwise, we'll save null for the string constant pid which will AV during ByteCode generation.
  5924. BYTE fScanDeferredFlagsSave = this->GetScanner()->SetDeferredParse(FALSE);
  5925. ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, fAllowIn, FALSE, nullptr, nullptr, nullptr, &token, false, nullptr, &lastRParen);
  5926. this->GetScanner()->SetDeferredParseFlags(fScanDeferredFlagsSave);
  5927. this->MarkEscapingRef(result, &token);
  5928. if (buildAST)
  5929. {
  5930. pnodeRet->pnodeExpr = result;
  5931. pnodeRet->ichMin = pnodeRet->pnodeExpr->ichMin;
  5932. pnodeRet->ichLim = pnodeRet->pnodeExpr->ichLim;
  5933. // Pushing a statement node with PushStmt<>() normally does this initialization
  5934. // but do it here manually since we know there is no outer statement node.
  5935. pnodeRet->grfnop = 0;
  5936. pnodeRet->pnodeOuter = nullptr;
  5937. pnodeLambda->ichLim = max(pnodeRet->ichLim, lastRParen);
  5938. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  5939. pnodeLambda->pnodeScopes->ichLim = pnodeRet->ichLim;
  5940. pnodeLambda->pnodeBody = nullptr;
  5941. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, pnodeRet);
  5942. // Append an EndCode node.
  5943. ParseNodePtr end = CreateNodeForOpT<knopEndCode>(pnodeRet->ichLim);
  5944. end->ichLim = end->ichMin; // make end code zero width at the immediate end of lambda body
  5945. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, end);
  5946. // Lambda's do not have arguments binding
  5947. pnodeLambda->SetHasReferenceableBuiltInArguments(false);
  5948. }
  5949. else
  5950. {
  5951. pnodeLambda->ichLim = max(this->GetScanner()->IchLimTokPrevious(), lastRParen);
  5952. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  5953. }
  5954. }
  5955. void Parser::CheckStrictFormalParameters()
  5956. {
  5957. if (m_token.tk == tkID)
  5958. {
  5959. // single parameter arrow function case
  5960. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5961. CheckStrictModeEvalArgumentsUsage(pid);
  5962. return;
  5963. }
  5964. Assert(m_token.tk == tkLParen);
  5965. this->GetScanner()->ScanForcingPid();
  5966. if (m_token.tk != tkRParen)
  5967. {
  5968. SList<IdentPtr> formals(&m_nodeAllocator);
  5969. for (;;)
  5970. {
  5971. if (m_token.tk != tkID)
  5972. {
  5973. IdentifierExpectedError(m_token);
  5974. }
  5975. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5976. CheckStrictModeEvalArgumentsUsage(pid);
  5977. if (formals.Has(pid))
  5978. {
  5979. Error(ERRES5ArgSame, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  5980. }
  5981. else
  5982. {
  5983. formals.Prepend(pid);
  5984. }
  5985. this->GetScanner()->Scan();
  5986. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5987. {
  5988. this->GetScanner()->Scan();
  5989. // We can avoid building the AST since we are just checking the default expression.
  5990. ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);
  5991. Assert(pnodeInit == nullptr);
  5992. }
  5993. if (m_token.tk != tkComma)
  5994. {
  5995. break;
  5996. }
  5997. this->GetScanner()->ScanForcingPid();
  5998. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5999. {
  6000. break;
  6001. }
  6002. }
  6003. }
  6004. Assert(m_token.tk == tkRParen);
  6005. }
  6006. void Parser::FinishFncNode(ParseNodeFnc * pnodeFnc, bool fAllowIn)
  6007. {
  6008. AnalysisAssert(pnodeFnc);
  6009. // Finish the AST for a function that was deferred earlier, but which we decided
  6010. // to finish after the fact.
  6011. // We assume that the name(s) and arg(s) have already got parse nodes, so
  6012. // we just have to do the function body.
  6013. // Save the current next function Id, and resume from the old one.
  6014. Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;
  6015. Js::LocalFunctionId tempNextFunctionId = pnodeFnc->functionId + 1;
  6016. this->m_nextFunctionId = &tempNextFunctionId;
  6017. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  6018. uint *pnestedCountSave = m_pnestedCount;
  6019. int32* pAstSizeSave = m_pCurrentAstSize;
  6020. m_currentNodeFunc = pnodeFnc;
  6021. m_pCurrentAstSize = &(pnodeFnc->astSize);
  6022. pnodeFnc->nestedCount = 0;
  6023. m_pnestedCount = &pnodeFnc->nestedCount;
  6024. bool fLambda = pnodeFnc->IsLambda();
  6025. bool fMethod = pnodeFnc->IsMethod();
  6026. // Cue up the parser to the start of the function body.
  6027. if (pnodeFnc->pnodeName)
  6028. {
  6029. // Skip the name(s).
  6030. this->GetScanner()->SetCurrentCharacter(pnodeFnc->pnodeName->ichLim, pnodeFnc->lineNumber);
  6031. }
  6032. else
  6033. {
  6034. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->lineNumber);
  6035. if (fMethod)
  6036. {
  6037. // Method. Skip identifier name, computed property name, "async", "get", "set", and '*' or '(' characters.
  6038. for (;;)
  6039. {
  6040. this->GetScanner()->Scan();
  6041. // '[' character indicates a computed property name for this method. We should consume it.
  6042. if (m_token.tk == tkLBrack)
  6043. {
  6044. // We don't care what the name expr is.
  6045. this->GetScanner()->Scan();
  6046. ParseExpr<false>();
  6047. Assert(m_token.tk == tkRBrack);
  6048. continue;
  6049. }
  6050. // Quit scanning ahead when we reach a '(' character which opens the arg list.
  6051. if (m_token.tk == tkLParen)
  6052. {
  6053. break;
  6054. }
  6055. }
  6056. }
  6057. else if (pnodeFnc->IsAccessor())
  6058. {
  6059. // Getter/setter. The node text starts with the name, so eat that.
  6060. this->GetScanner()->ScanNoKeywords();
  6061. }
  6062. else if (!fLambda)
  6063. {
  6064. // Anonymous function. Skip "async", "function", and '(' or '*' characters.
  6065. for (;;)
  6066. {
  6067. this->GetScanner()->Scan();
  6068. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6069. {
  6070. Assert(pnodeFnc->IsAsync());
  6071. continue;
  6072. }
  6073. // Quit scanning ahead when we reach a 'function' keyword which precedes the arg list.
  6074. if (m_token.tk == tkFUNCTION)
  6075. {
  6076. break;
  6077. }
  6078. Assert(m_token.tk == tkLParen || m_token.tk == tkStar);
  6079. }
  6080. }
  6081. }
  6082. // switch scanner to treat 'yield' as keyword in generator functions
  6083. // or as an identifier in non-generator functions
  6084. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->IsGenerator());
  6085. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(pnodeFnc && pnodeFnc->IsAsync());
  6086. // Skip the arg list.
  6087. if (!fMethod)
  6088. {
  6089. // If this is a method, we've already advanced to the '(' token.
  6090. this->GetScanner()->Scan();
  6091. }
  6092. if (m_token.tk == tkStar)
  6093. {
  6094. Assert(pnodeFnc->IsGenerator());
  6095. this->GetScanner()->ScanNoKeywords();
  6096. }
  6097. if (fLambda && m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async)
  6098. {
  6099. Assert(pnodeFnc->IsAsync());
  6100. this->GetScanner()->ScanNoKeywords();
  6101. }
  6102. Assert(m_token.tk == tkLParen || (fLambda && m_token.tk == tkID));
  6103. this->GetScanner()->ScanNoKeywords();
  6104. if (m_token.tk != tkRParen && m_token.tk != tkDArrow)
  6105. {
  6106. for (;;)
  6107. {
  6108. if (m_token.tk == tkEllipsis)
  6109. {
  6110. this->GetScanner()->ScanNoKeywords();
  6111. }
  6112. if (m_token.tk == tkID)
  6113. {
  6114. this->GetScanner()->ScanNoKeywords();
  6115. if (m_token.tk == tkAsg)
  6116. {
  6117. // Eat the default expression
  6118. this->GetScanner()->Scan();
  6119. ParseExpr<false>(koplCma);
  6120. }
  6121. }
  6122. else if (IsPossiblePatternStart())
  6123. {
  6124. ParseDestructuredLiteralWithScopeSave(tkLET, false/*isDecl*/, false /*topLevel*/);
  6125. }
  6126. else
  6127. {
  6128. AssertMsg(false, "Unexpected identifier prefix while fast-scanning formals");
  6129. }
  6130. if (m_token.tk != tkComma)
  6131. {
  6132. break;
  6133. }
  6134. this->GetScanner()->ScanNoKeywords();
  6135. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6136. {
  6137. break;
  6138. }
  6139. }
  6140. }
  6141. if (m_token.tk == tkRParen)
  6142. {
  6143. this->GetScanner()->Scan();
  6144. }
  6145. if (fLambda && m_token.tk == tkDArrow)
  6146. {
  6147. this->GetScanner()->Scan();
  6148. }
  6149. // Finish the function body.
  6150. {
  6151. // Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. "( function x(){} )".
  6152. // We lose that context here since we start from middle of function body. So save and restore source range info.
  6153. const charcount_t ichLim = pnodeFnc->ichLim;
  6154. const size_t cbLim = pnodeFnc->cbLim;
  6155. this->FinishFncDecl(pnodeFnc, NULL, fLambda, /* skipCurlyBraces */ false, fAllowIn);
  6156. #if DBG
  6157. // The pnode extent may not match the original extent.
  6158. // We expect this to happen only when there are trailing ")"'s.
  6159. // Consume them and make sure that's all we've got.
  6160. if (pnodeFnc->ichLim != ichLim)
  6161. {
  6162. Assert(pnodeFnc->ichLim < ichLim);
  6163. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichLim);
  6164. while (this->GetScanner()->IchLimTok() != ichLim)
  6165. {
  6166. this->GetScanner()->ScanNoKeywords();
  6167. Assert(m_token.tk == tkRParen);
  6168. }
  6169. }
  6170. #endif
  6171. pnodeFnc->ichLim = ichLim;
  6172. pnodeFnc->cbLim = cbLim;
  6173. }
  6174. m_currentNodeFunc = pnodeFncSave;
  6175. m_pCurrentAstSize = pAstSizeSave;
  6176. m_pnestedCount = pnestedCountSave;
  6177. Assert(m_pnestedCount);
  6178. Assert(tempNextFunctionId == pnodeFnc->deferredParseNextFunctionId);
  6179. this->m_nextFunctionId = nextFunctionIdSave;
  6180. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6181. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6182. }
  6183. void Parser::FinishFncDecl(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, bool fLambda, bool skipCurlyBraces, bool fAllowIn)
  6184. {
  6185. LPCOLESTR name = NULL;
  6186. JS_ETW(int32 startAstSize = *m_pCurrentAstSize);
  6187. if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))
  6188. {
  6189. name = GetFunctionName(pnodeFnc, pNameHint);
  6190. m_functionBody = NULL; // for nested functions we do not want to get the name of the top deferred function return name;
  6191. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, 0, m_parseType, name));
  6192. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), name, pnodeFnc->functionId);
  6193. }
  6194. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->functionId, /*Undefer*/FALSE));
  6195. // Do the work of creating an AST for a function body.
  6196. // This is common to the un-deferred case and the case in which we un-defer late in the game.
  6197. Assert(pnodeFnc->nop == knopFncDecl);
  6198. if (fLambda && m_token.tk != tkLCurly)
  6199. {
  6200. ParseExpressionLambdaBody<true>(pnodeFnc, fAllowIn);
  6201. }
  6202. else
  6203. {
  6204. if (!skipCurlyBraces)
  6205. {
  6206. ChkCurTok(tkLCurly, ERRnoLcurly);
  6207. }
  6208. ParseNodePtr * lastNodeRef = nullptr;
  6209. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true /* isSourceElementList */);
  6210. // Append an EndCode node.
  6211. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  6212. if (!skipCurlyBraces)
  6213. {
  6214. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6215. }
  6216. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  6217. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  6218. }
  6219. #ifdef ENABLE_JS_ETW
  6220. int32 astSize = *m_pCurrentAstSize - startAstSize;
  6221. EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, astSize, m_parseType, name);
  6222. #endif
  6223. }
  6224. ParseNodeVar * Parser::CreateSpecialVarDeclNode(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6225. {
  6226. ParseNodeVar * pnode = InsertVarAtBeginning(pnodeFnc, pid);
  6227. pnode->grfpn |= fpnSpecialSymbol;
  6228. // special symbol must not be global
  6229. pnode->sym->SetIsGlobal(false);
  6230. return pnode;
  6231. }
  6232. ParseNodeVar * Parser::InsertVarAtBeginning(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6233. {
  6234. ParseNodeVar * pnode = nullptr;
  6235. if (m_ppnodeVar == &pnodeFnc->pnodeVars)
  6236. {
  6237. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6238. }
  6239. else
  6240. {
  6241. ParseNodePtr * const ppnodeVarSave = m_ppnodeVar;
  6242. m_ppnodeVar = &pnodeFnc->pnodeVars;
  6243. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6244. m_ppnodeVar = ppnodeVarSave;
  6245. }
  6246. Assert(pnode);
  6247. return pnode;
  6248. }
  6249. ParseNodeVar * Parser::AddArgumentsNodeToVars(ParseNodeFnc * pnodeFnc)
  6250. {
  6251. Assert(!GetCurrentFunctionNode()->IsLambda());
  6252. ParseNodeVar * argNode = InsertVarAtBeginning(pnodeFnc, wellKnownPropertyPids.arguments);
  6253. argNode->grfpn |= PNodeFlags::fpnArguments; // Flag this as the built-in arguments node
  6254. return argNode;
  6255. }
  6256. void Parser::UpdateArgumentsNode(ParseNodeFnc * pnodeFnc, ParseNodeVar * argNode)
  6257. {
  6258. if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam) || pnodeFnc->IsLambda())
  6259. {
  6260. // There is a parameter named arguments. So we don't have to create the built-in arguments.
  6261. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6262. }
  6263. else if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) && pnodeFnc->IsBodyAndParamScopeMerged())
  6264. {
  6265. // In non-split scope case there is a var or function definition named arguments in the body
  6266. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6267. }
  6268. else
  6269. {
  6270. pnodeFnc->SetHasReferenceableBuiltInArguments(true);
  6271. Assert(argNode);
  6272. }
  6273. if (argNode != nullptr && !argNode->sym->IsArguments())
  6274. {
  6275. // A duplicate definition has updated the declaration node. Need to reset it back.
  6276. argNode->grfpn |= PNodeFlags::fpnArguments;
  6277. argNode->sym->SetDecl(argNode);
  6278. }
  6279. }
  6280. LPCOLESTR Parser::GetFunctionName(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint)
  6281. {
  6282. LPCOLESTR name = nullptr;
  6283. if (pnodeFnc->pnodeName != nullptr)
  6284. {
  6285. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  6286. name = pnodeFnc->pnodeName->pid->Psz();
  6287. }
  6288. if (name == nullptr && pNameHint != nullptr)
  6289. {
  6290. name = pNameHint;
  6291. }
  6292. if (name == nullptr && (pnodeFnc->IsLambda() ||
  6293. (!pnodeFnc->IsDeclaration() && !pnodeFnc->IsMethod())))
  6294. {
  6295. name = Js::Constants::AnonymousFunction;
  6296. }
  6297. if (name == nullptr && m_functionBody != nullptr)
  6298. {
  6299. name = m_functionBody->GetExternalDisplayName();
  6300. }
  6301. else if (name == nullptr)
  6302. {
  6303. name = Js::Constants::AnonymousFunction;
  6304. }
  6305. return name;
  6306. }
  6307. IdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)
  6308. {
  6309. if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())
  6310. {
  6311. IdentPtr pid;
  6312. if (m_token.tk == tkStrCon)
  6313. {
  6314. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6315. {
  6316. Error(ERRES5NoOctal);
  6317. }
  6318. pid = m_token.GetStr();
  6319. }
  6320. else
  6321. {
  6322. pid = m_token.GetIdentifier(this->GetHashTbl());
  6323. }
  6324. *pidHint = pid;
  6325. return pid;
  6326. }
  6327. else if (m_token.tk == tkIntCon)
  6328. {
  6329. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6330. {
  6331. Error(ERRES5NoOctal);
  6332. }
  6333. return this->GetScanner()->PidFromLong(m_token.GetLong());
  6334. }
  6335. else if (m_token.tk == tkFltCon)
  6336. {
  6337. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6338. {
  6339. Error(ERRES5NoOctal);
  6340. }
  6341. return this->GetScanner()->PidFromDbl(m_token.GetDouble());
  6342. }
  6343. Error(ERRnoMemberIdent);
  6344. }
  6345. LPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)
  6346. {
  6347. if ((pMemberName == nullptr && !isComputedName) ||
  6348. (pMemberNameHint == nullptr && isComputedName) ||
  6349. !CONFIG_FLAG(UseFullName))
  6350. {
  6351. return nullptr;
  6352. }
  6353. LPCOLESTR pFinalName = isComputedName ? pMemberNameHint : pMemberName->Psz();
  6354. uint32 fullNameHintLength = (uint32)wcslen(pFinalName);
  6355. uint32 shortNameOffset = 0;
  6356. if (!isStatic)
  6357. {
  6358. // Add prototype.
  6359. pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);
  6360. }
  6361. if (pClassName)
  6362. {
  6363. uint32 classNameOffset = 0;
  6364. pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);
  6365. shortNameOffset += classNameOffset;
  6366. }
  6367. if (pGetSet)
  6368. {
  6369. // displays as get/set prototype.funcname
  6370. uint32 getSetOffset = 0;
  6371. pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);
  6372. shortNameOffset += getSetOffset;
  6373. }
  6374. *nameLength = fullNameHintLength;
  6375. *pShortNameOffset = shortNameOffset;
  6376. return pFinalName;
  6377. }
  6378. class AutoParsingSuperRestrictionStateRestorer
  6379. {
  6380. public:
  6381. AutoParsingSuperRestrictionStateRestorer(Parser* parser) : m_parser(parser)
  6382. {
  6383. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6384. this->m_originalParsingSuperRestrictionState = this->m_parser->m_parsingSuperRestrictionState;
  6385. }
  6386. ~AutoParsingSuperRestrictionStateRestorer()
  6387. {
  6388. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6389. this->m_parser->m_parsingSuperRestrictionState = m_originalParsingSuperRestrictionState;
  6390. }
  6391. private:
  6392. Parser * m_parser;
  6393. int m_originalParsingSuperRestrictionState;
  6394. };
  6395. template<bool buildAST>
  6396. ParseNodeClass * Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)
  6397. {
  6398. bool hasConstructor = false;
  6399. bool hasExtends = false;
  6400. IdentPtr name = nullptr;
  6401. ParseNodeVar * pnodeName = nullptr;
  6402. ParseNodeFnc * pnodeConstructor = nullptr;
  6403. ParseNodePtr pnodeExtends = nullptr;
  6404. ParseNodePtr pnodeMembers = nullptr;
  6405. ParseNodePtr *lastMemberNodeRef = nullptr;
  6406. ParseNodePtr pnodeStaticMembers = nullptr;
  6407. ParseNodePtr *lastStaticMemberNodeRef = nullptr;
  6408. uint32 nameHintLength = pHintLength ? *pHintLength : 0;
  6409. uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;
  6410. ArenaAllocator tempAllocator(_u("ClassMemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  6411. size_t cbMinConstructor = 0;
  6412. ParseNodeClass * pnodeClass = nullptr;
  6413. if (buildAST)
  6414. {
  6415. pnodeClass = CreateNodeForOpT<knopClassDecl>();
  6416. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Class, m_scriptContext);
  6417. cbMinConstructor = this->GetScanner()->IecpMinTok();
  6418. }
  6419. this->GetScanner()->Scan();
  6420. if (m_token.tk == tkID)
  6421. {
  6422. name = m_token.GetIdentifier(this->GetHashTbl());
  6423. this->GetScanner()->Scan();
  6424. }
  6425. else if (isDeclaration)
  6426. {
  6427. IdentifierExpectedError(m_token);
  6428. }
  6429. if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  6430. {
  6431. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  6432. }
  6433. BOOL strictSave = m_fUseStrictMode;
  6434. m_fUseStrictMode = TRUE;
  6435. ParseNodeVar * pnodeDeclName = nullptr;
  6436. if (isDeclaration)
  6437. {
  6438. pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);
  6439. }
  6440. ParseNodePtr *ppnodeScopeSave = nullptr;
  6441. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  6442. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  6443. if (buildAST)
  6444. {
  6445. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  6446. pnodeClass->pnodeBlock = pnodeBlock;
  6447. }
  6448. if (name)
  6449. {
  6450. pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);
  6451. }
  6452. if (m_token.tk == tkEXTENDS)
  6453. {
  6454. this->GetScanner()->Scan();
  6455. pnodeExtends = ParseTerm<buildAST>();
  6456. hasExtends = true;
  6457. }
  6458. if (m_token.tk != tkLCurly)
  6459. {
  6460. Error(ERRnoLcurly);
  6461. }
  6462. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Parsing class (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6463. RestorePoint beginClass;
  6464. this->GetScanner()->Capture(&beginClass);
  6465. this->GetScanner()->ScanForcingPid();
  6466. IdentPtr pClassNamePid = pnodeName ? pnodeName->pid : nullptr;
  6467. for (;;)
  6468. {
  6469. if (m_token.tk == tkSColon)
  6470. {
  6471. this->GetScanner()->ScanForcingPid();
  6472. continue;
  6473. }
  6474. if (m_token.tk == tkRCurly)
  6475. {
  6476. break;
  6477. }
  6478. bool isStatic = false;
  6479. if (m_token.tk == tkSTATIC)
  6480. {
  6481. // 'static' can be used as an IdentifierName here, even in strict mode code. We need to see the next token before we know
  6482. // if this is being used as a keyword. This is similar to the way we treat 'let' in some cases.
  6483. // See https://tc39.github.io/ecma262/#sec-keywords for more info.
  6484. RestorePoint beginStatic;
  6485. this->GetScanner()->Capture(&beginStatic);
  6486. this->GetScanner()->ScanForcingPid();
  6487. if (m_token.tk == tkLParen)
  6488. {
  6489. this->GetScanner()->SeekTo(beginStatic);
  6490. }
  6491. else
  6492. {
  6493. isStatic = true;
  6494. }
  6495. }
  6496. ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;
  6497. charcount_t ichMin = 0;
  6498. size_t iecpMin = 0;
  6499. ParseNodePtr pnodeMemberName = nullptr;
  6500. IdentPtr pidHint = nullptr;
  6501. IdentPtr memberPid = nullptr;
  6502. LPCOLESTR pMemberNameHint = nullptr;
  6503. uint32 memberNameHintLength = 0;
  6504. uint32 memberNameOffset = 0;
  6505. bool isComputedName = false;
  6506. bool isAsyncMethod = false;
  6507. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  6508. {
  6509. RestorePoint parsedAsync;
  6510. this->GetScanner()->Capture(&parsedAsync);
  6511. ichMin = this->GetScanner()->IchMinTok();
  6512. iecpMin = this->GetScanner()->IecpMinTok();
  6513. this->GetScanner()->Scan();
  6514. if (m_token.tk == tkLParen || this->GetScanner()->FHadNewLine())
  6515. {
  6516. this->GetScanner()->SeekTo(parsedAsync);
  6517. }
  6518. else
  6519. {
  6520. isAsyncMethod = true;
  6521. }
  6522. }
  6523. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  6524. m_token.tk == tkStar;
  6525. if (isGenerator)
  6526. {
  6527. fncDeclFlags |= fFncGenerator;
  6528. this->GetScanner()->ScanForcingPid();
  6529. }
  6530. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6531. {
  6532. // Computed member name: [expr] () { }
  6533. LPCOLESTR emptyHint = nullptr;
  6534. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6535. isComputedName = true;
  6536. }
  6537. else // not computed name
  6538. {
  6539. memberPid = this->ParseClassPropertyName(&pidHint);
  6540. if (pidHint)
  6541. {
  6542. pMemberNameHint = pidHint->Psz();
  6543. memberNameHintLength = pidHint->Cch();
  6544. }
  6545. }
  6546. if (buildAST && memberPid)
  6547. {
  6548. pnodeMemberName = CreateStrNode(memberPid);
  6549. }
  6550. if (!isStatic && memberPid == wellKnownPropertyPids.constructor)
  6551. {
  6552. if (hasConstructor || isAsyncMethod)
  6553. {
  6554. Error(ERRsyntax);
  6555. }
  6556. hasConstructor = true;
  6557. LPCOLESTR pConstructorName = nullptr;
  6558. uint32 constructorNameLength = 0;
  6559. uint32 constructorShortNameHintOffset = 0;
  6560. if (pnodeName && pnodeName->pid)
  6561. {
  6562. pConstructorName = pnodeName->pid->Psz();
  6563. constructorNameLength = pnodeName->pid->Cch();
  6564. }
  6565. else
  6566. {
  6567. pConstructorName = pNameHint;
  6568. constructorNameLength = nameHintLength;
  6569. constructorShortNameHintOffset = nameHintOffset;
  6570. }
  6571. {
  6572. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6573. this->m_parsingSuperRestrictionState = hasExtends ? ParsingSuperRestrictionState_SuperCallAndPropertyAllowed : ParsingSuperRestrictionState_SuperPropertyAllowed;
  6574. // Add the class constructor flag and base class constructor flag if pnodeExtends is nullptr
  6575. fncDeclFlags |= fFncClassConstructor | (hasExtends ? kFunctionNone : fFncBaseClassConstructor);
  6576. pnodeConstructor = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, pConstructorName, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState = */false);
  6577. }
  6578. if (pnodeConstructor->IsGenerator())
  6579. {
  6580. Error(ERRConstructorCannotBeGenerator);
  6581. }
  6582. Assert(constructorNameLength >= constructorShortNameHintOffset);
  6583. // The constructor function will get the same name as class.
  6584. pnodeConstructor->hint = pConstructorName;
  6585. pnodeConstructor->hintLength = constructorNameLength;
  6586. pnodeConstructor->hintOffset = constructorShortNameHintOffset;
  6587. pnodeConstructor->pid = pnodeName && pnodeName->pid ? pnodeName->pid : wellKnownPropertyPids.constructor;
  6588. pnodeConstructor->SetHasNonThisStmt();
  6589. pnodeConstructor->SetHasComputedName();
  6590. pnodeConstructor->SetHasHomeObj();
  6591. }
  6592. else
  6593. {
  6594. ParseNodePtr pnodeMember = nullptr;
  6595. bool isMemberNamedGetOrSet = false;
  6596. RestorePoint beginMethodName;
  6597. this->GetScanner()->Capture(&beginMethodName);
  6598. if (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set)
  6599. {
  6600. this->GetScanner()->ScanForcingPid();
  6601. }
  6602. if (m_token.tk == tkLParen)
  6603. {
  6604. this->GetScanner()->SeekTo(beginMethodName);
  6605. isMemberNamedGetOrSet = true;
  6606. }
  6607. if ((memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set) && !isMemberNamedGetOrSet)
  6608. {
  6609. bool isGetter = (memberPid == wellKnownPropertyPids.get);
  6610. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6611. {
  6612. // Computed get/set member name: get|set [expr] () { }
  6613. LPCOLESTR emptyHint = nullptr;
  6614. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6615. isComputedName = true;
  6616. }
  6617. else // not computed name
  6618. {
  6619. memberPid = this->ParseClassPropertyName(&pidHint);
  6620. }
  6621. if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)
  6622. {
  6623. Error(ERRsyntax);
  6624. }
  6625. if (buildAST && memberPid && !isComputedName)
  6626. {
  6627. pnodeMemberName = CreateStrNode(memberPid);
  6628. }
  6629. ParseNodeFnc * pnodeFnc = nullptr;
  6630. {
  6631. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6632. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6633. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),
  6634. pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true,
  6635. /* resetParsingSuperRestrictionState */false);
  6636. }
  6637. pnodeFnc->SetIsStaticMember(isStatic);
  6638. if (isComputedName)
  6639. {
  6640. pnodeFnc->SetHasComputedName();
  6641. }
  6642. pnodeFnc->SetHasHomeObj();
  6643. if (buildAST)
  6644. {
  6645. pnodeFnc->SetIsAccessor();
  6646. pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);
  6647. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,
  6648. isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,
  6649. &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6650. }
  6651. }
  6652. else
  6653. {
  6654. if (isStatic && (memberPid == wellKnownPropertyPids.prototype))
  6655. {
  6656. Error(ERRsyntax);
  6657. }
  6658. ParseNodeFnc * pnodeFnc = nullptr;
  6659. {
  6660. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6661. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6662. if (isAsyncMethod)
  6663. {
  6664. fncDeclFlags |= fFncAsync;
  6665. }
  6666. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState */false);
  6667. if (isAsyncMethod)
  6668. {
  6669. pnodeFnc->cbMin = iecpMin;
  6670. pnodeFnc->ichMin = ichMin;
  6671. }
  6672. }
  6673. pnodeFnc->SetIsStaticMember(isStatic);
  6674. if (isComputedName)
  6675. {
  6676. pnodeFnc->SetHasComputedName();
  6677. }
  6678. pnodeFnc->SetHasHomeObj();
  6679. if (buildAST)
  6680. {
  6681. pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);
  6682. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr /*pgetset*/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6683. }
  6684. }
  6685. if (buildAST)
  6686. {
  6687. Assert(memberNameHintLength >= memberNameOffset);
  6688. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pMemberNameHint; // Fully qualified name
  6689. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = memberNameHintLength;
  6690. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = memberNameOffset;
  6691. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->pid = memberPid; // Short name
  6692. AddToNodeList(isStatic ? &pnodeStaticMembers : &pnodeMembers, isStatic ? &lastStaticMemberNodeRef : &lastMemberNodeRef, pnodeMember);
  6693. }
  6694. }
  6695. }
  6696. size_t cbLimConstructor = 0;
  6697. if (buildAST)
  6698. {
  6699. pnodeClass->ichLim = this->GetScanner()->IchLimTok();
  6700. cbLimConstructor = this->GetScanner()->IecpLimTok();
  6701. }
  6702. if (!hasConstructor)
  6703. {
  6704. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Generating constructor (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6705. RestorePoint endClass;
  6706. this->GetScanner()->Capture(&endClass);
  6707. this->GetScanner()->SeekTo(beginClass);
  6708. pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);
  6709. if (buildAST)
  6710. {
  6711. if (pClassNamePid)
  6712. {
  6713. pnodeConstructor->hint = pClassNamePid->Psz();
  6714. pnodeConstructor->hintLength = pClassNamePid->Cch();
  6715. pnodeConstructor->hintOffset = 0;
  6716. }
  6717. else
  6718. {
  6719. Assert(nameHintLength >= nameHintOffset);
  6720. pnodeConstructor->hint = pNameHint;
  6721. pnodeConstructor->hintLength = nameHintLength;
  6722. pnodeConstructor->hintOffset = nameHintOffset;
  6723. }
  6724. pnodeConstructor->pid = pClassNamePid;
  6725. }
  6726. this->GetScanner()->SeekTo(endClass);
  6727. }
  6728. if (buildAST)
  6729. {
  6730. pnodeConstructor->cbMin = cbMinConstructor;
  6731. pnodeConstructor->cbLim = cbLimConstructor;
  6732. pnodeConstructor->ichMin = pnodeClass->ichMin;
  6733. pnodeConstructor->ichLim = pnodeClass->ichLim;
  6734. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  6735. pnodeClass->pnodeDeclName = pnodeDeclName;
  6736. pnodeClass->pnodeName = pnodeName;
  6737. pnodeClass->pnodeConstructor = pnodeConstructor;
  6738. pnodeClass->pnodeExtends = pnodeExtends;
  6739. pnodeClass->pnodeMembers = pnodeMembers;
  6740. pnodeClass->pnodeStaticMembers = pnodeStaticMembers;
  6741. pnodeClass->isDefaultModuleExport = false;
  6742. }
  6743. FinishParseBlock(pnodeBlock);
  6744. m_fUseStrictMode = strictSave;
  6745. this->GetScanner()->Scan();
  6746. return pnodeClass;
  6747. }
  6748. template<bool buildAST>
  6749. ParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)
  6750. {
  6751. ParseNodePtr pnodeStringLiterals = nullptr;
  6752. ParseNodePtr* lastStringLiteralNodeRef = nullptr;
  6753. ParseNodePtr pnodeRawStringLiterals = nullptr;
  6754. ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;
  6755. ParseNodePtr pnodeSubstitutionExpressions = nullptr;
  6756. ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;
  6757. ParseNodePtr pnodeTagFncArgs = nullptr;
  6758. ParseNodePtr* lastTagFncArgNodeRef = nullptr;
  6759. ParseNodeStr * stringLiteral = nullptr;
  6760. ParseNodeStr * stringLiteralRaw = nullptr;
  6761. ParseNodeStrTemplate * pnodeStringTemplate = nullptr;
  6762. ParseNode * pnodeReturn = nullptr;
  6763. bool templateClosed = false;
  6764. const bool isTagged = pnodeTagFnc != nullptr;
  6765. uint16 stringConstantCount = 0;
  6766. charcount_t ichMin = 0;
  6767. Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);
  6768. if (buildAST)
  6769. {
  6770. pnodeReturn = pnodeStringTemplate = CreateNodeForOpT<knopStrTemplate>();
  6771. pnodeStringTemplate->countStringLiterals = 0;
  6772. pnodeStringTemplate->isTaggedTemplate = isTagged ? TRUE : FALSE;
  6773. // If this is a tagged string template, we need to start building the arg list for the call
  6774. if (isTagged)
  6775. {
  6776. ichMin = pnodeTagFnc->ichMin;
  6777. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);
  6778. }
  6779. }
  6780. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StringTemplates, m_scriptContext);
  6781. OUTPUT_TRACE_DEBUGONLY(
  6782. Js::StringTemplateParsePhase,
  6783. _u("Starting to parse a string template (%s)...\n\tis tagged = %s\n"),
  6784. GetParseType(),
  6785. isTagged ? _u("true") : _u("false (Raw and cooked strings will not differ!)"));
  6786. // String template grammar
  6787. // `...` Simple string template
  6788. // `...${ String template beginning
  6789. // }...${ String template middle
  6790. // }...` String template end
  6791. while (!templateClosed)
  6792. {
  6793. // First, extract the string constant part - we always have one
  6794. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6795. {
  6796. Error(ERRES5NoOctal);
  6797. }
  6798. // We are not able to pass more than a ushort worth of arguments to the tag
  6799. // so use that as a logical limit on the number of string constant pieces.
  6800. if (stringConstantCount >= Js::Constants::MaxAllowedArgs)
  6801. {
  6802. Error(ERRTooManyArgs);
  6803. }
  6804. // Keep track of the string literal count (must be the same for raw strings)
  6805. // We use this in code gen so we don't need to count the string literals list
  6806. stringConstantCount++;
  6807. // If we are not creating parse nodes, there is no need to create strings
  6808. if (buildAST)
  6809. {
  6810. stringLiteral = CreateStrNode(m_token.GetStr());
  6811. AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);
  6812. // We only need to collect a raw string when we are going to pass the string template to a tag
  6813. if (isTagged)
  6814. {
  6815. // Make the scanner create a PID for the raw string constant for the preceding scan
  6816. IdentPtr pid = this->GetScanner()->GetSecondaryBufferAsPid();
  6817. stringLiteralRaw = CreateStrNode(pid);
  6818. // Should have gotten a raw string literal above
  6819. AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);
  6820. }
  6821. else
  6822. {
  6823. #if DBG
  6824. // Assign the raw string for debug tracing below
  6825. stringLiteralRaw = stringLiteral;
  6826. #endif
  6827. }
  6828. OUTPUT_TRACE_DEBUGONLY(
  6829. Js::StringTemplateParsePhase,
  6830. _u("Parsed string constant: \n\tcooked = \"%s\" \n\traw = \"%s\" \n\tdiffer = %d\n"),
  6831. stringLiteral->pid->Psz(),
  6832. stringLiteralRaw->pid->Psz(),
  6833. stringLiteral->pid->Psz() == stringLiteralRaw->pid->Psz() ? 0 : 1);
  6834. }
  6835. switch (m_token.tk)
  6836. {
  6837. case tkStrTmplEnd:
  6838. case tkStrTmplBasic:
  6839. // We do not need to parse an expression for either the end or basic string template tokens
  6840. templateClosed = true;
  6841. break;
  6842. case tkStrTmplBegin:
  6843. case tkStrTmplMid:
  6844. {
  6845. // In the middle or begin string template token case, we need to parse an expression next
  6846. this->GetScanner()->Scan();
  6847. // Parse the contents of the curly braces as an expression
  6848. ParseNodePtr expression = ParseExpr<buildAST>(0);
  6849. // After parsing expression, scan should leave us with an RCurly token.
  6850. // Use the NoScan version so we do not automatically perform a scan - we need to
  6851. // set the scan state before next scan but we don't want to set that state if
  6852. // the token is not as expected since we'll error in that case.
  6853. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6854. // Notify the scanner that it should scan for a middle or end string template token
  6855. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  6856. this->GetScanner()->Scan();
  6857. if (buildAST)
  6858. {
  6859. // If we are going to call the tag function, add this expression into the list of args
  6860. if (isTagged)
  6861. {
  6862. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);
  6863. }
  6864. else
  6865. {
  6866. // Otherwise add it to the substitution expression list
  6867. // TODO: Store the arguments and substitution expressions in a single list?
  6868. AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);
  6869. }
  6870. }
  6871. if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))
  6872. {
  6873. // Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return
  6874. // tkStrTmpMid/End unless it is EOF or tkScanError
  6875. Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);
  6876. Error(ERRsyntax);
  6877. }
  6878. OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u("Parsed expression\n"));
  6879. }
  6880. break;
  6881. default:
  6882. Assert(false);
  6883. break;
  6884. }
  6885. }
  6886. if (buildAST)
  6887. {
  6888. pnodeStringTemplate->pnodeStringLiterals = pnodeStringLiterals;
  6889. pnodeStringTemplate->pnodeStringRawLiterals = pnodeRawStringLiterals;
  6890. pnodeStringTemplate->pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;
  6891. pnodeStringTemplate->countStringLiterals = stringConstantCount;
  6892. // We should still have the last string literal.
  6893. // Use the char offset of the end of that constant as the end of the string template.
  6894. pnodeStringTemplate->ichLim = stringLiteral->ichLim;
  6895. // If this is a tagged template, we now have the argument list and can construct a call node
  6896. if (isTagged)
  6897. {
  6898. // Return the call node here and let the byte code generator Emit the string template automagically
  6899. ParseNodeCall * pnodeCall;
  6900. pnodeReturn = pnodeCall = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);
  6901. // We need to set the arg count explicitly
  6902. pnodeCall->argCount = stringConstantCount;
  6903. pnodeCall->hasDestructuring = m_hasDestructuringPattern;
  6904. }
  6905. }
  6906. this->GetScanner()->Scan();
  6907. return pnodeReturn;
  6908. }
  6909. LPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)
  6910. {
  6911. // propertyString could be null, such as 'this.foo' =
  6912. // propertyString could be empty, found in pattern as in (-1)[""][(x = z)]
  6913. OpCode op = pNode->nop;
  6914. LPCOLESTR rightNode = nullptr;
  6915. if (propertyString == nullptr)
  6916. {
  6917. propertyString = _u("");
  6918. }
  6919. if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)
  6920. {
  6921. rightNode = _u("");
  6922. }
  6923. else if (op == knopStr)
  6924. {
  6925. return AppendNameHints(propertyString, pNode->AsParseNodeStr()->pid, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  6926. }
  6927. else if (op == knopFlt)
  6928. {
  6929. rightNode = this->GetScanner()->StringFromDbl(pNode->AsParseNodeFloat()->dbl);
  6930. }
  6931. else
  6932. {
  6933. rightNode = op == knopInt ? this->GetScanner()->StringFromLong(pNode->AsParseNodeInt()->lw)
  6934. : pNode->AsParseNodeName()->pid->Psz();
  6935. }
  6936. return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  6937. }
  6938. LPCOLESTR Parser::ConstructNameHint(ParseNodeBin * pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)
  6939. {
  6940. Assert(pNode != nullptr);
  6941. Assert(pNode->nop == knopDot || pNode->nop == knopIndex);
  6942. // This method recursively visits nodes in the AST and could cause an SOE crash for long knopDot chains.
  6943. // Although this method could be made non-recursive, Emit (ByteCodeEmitter.cpp) hits a stack probe
  6944. // for shorter chains than which cause SOE here, so add a stack probe to throw SOE rather than crash on SOE.
  6945. // Because of that correspondence, use Js::Constants::MinStackByteCodeVisitor (which is used in Emit)
  6946. // for the stack probe here. See OS#14711878.
  6947. PROBE_STACK_NO_DISPOSE(this->m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  6948. LPCOLESTR leftNode = nullptr;
  6949. if (pNode->pnode1->nop == knopDot || pNode->pnode1->nop == knopIndex)
  6950. {
  6951. leftNode = ConstructNameHint(pNode->pnode1->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  6952. }
  6953. else if (pNode->pnode1->nop == knopName && !pNode->pnode1->AsParseNodeName()->IsSpecialName())
  6954. {
  6955. // We need to skip special names like 'this' because those shouldn't be appended to the
  6956. // name hint in the debugger stack trace.
  6957. // function ctor() {
  6958. // this.func = function() {
  6959. // // If we break here, the stack should say we are in 'func' and not 'this.func'
  6960. // }
  6961. // }
  6962. IdentPtr pid = pNode->pnode1->AsParseNodeName()->pid;
  6963. leftNode = pid->Psz();
  6964. *fullNameHintLength = pid->Cch();
  6965. *pShortNameOffset = 0;
  6966. }
  6967. if (pNode->nop == knopIndex)
  6968. {
  6969. return FormatPropertyString(
  6970. leftNode ? leftNode : Js::Constants::AnonymousFunction, // e.g. f()[0] = function () {}
  6971. pNode->pnode2, fullNameHintLength, pShortNameOffset);
  6972. }
  6973. Assert(pNode->pnode2->nop == knopDot || pNode->pnode2->nop == knopName);
  6974. LPCOLESTR rightNode = nullptr;
  6975. bool wrapWithBrackets = false;
  6976. if (pNode->pnode2->nop == knopDot)
  6977. {
  6978. rightNode = ConstructNameHint(pNode->pnode2->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  6979. }
  6980. else
  6981. {
  6982. rightNode = pNode->pnode2->AsParseNodeName()->pid->Psz();
  6983. wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);
  6984. }
  6985. Assert(rightNode != nullptr);
  6986. return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);
  6987. }
  6988. LPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  6989. {
  6990. Assert(rightStr != nullptr);
  6991. Assert(leftLen != 0 || wrapInBrackets);
  6992. Assert(rightLen != 0 || wrapInBrackets);
  6993. 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
  6994. uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); // 1 (for dot or [) + 1 (for null termination)
  6995. if (wrapInBrackets)
  6996. {
  6997. totalLength++; //1 for ']';
  6998. }
  6999. WCHAR * finalName = AllocateStringOfLength(totalLength);
  7000. if (leftStr != nullptr && leftLen != 0)
  7001. {
  7002. wcscpy_s(finalName, leftLen + 1, leftStr);
  7003. }
  7004. if (ignoreAddDotWithSpace)
  7005. {
  7006. finalName[leftLen++] = (OLECHAR)_u(' ');
  7007. }
  7008. // mutually exclusive from ignoreAddDotWithSpace which is used for getters/setters
  7009. else if (wrapInBrackets)
  7010. {
  7011. finalName[leftLen++] = (OLECHAR)_u('[');
  7012. finalName[totalLength - 2] = (OLECHAR)_u(']');
  7013. }
  7014. else if (!ignoreDot)
  7015. {
  7016. finalName[leftLen++] = (OLECHAR)_u('.');
  7017. }
  7018. //ignore case falls through
  7019. js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);
  7020. finalName[totalLength - 1] = (OLECHAR)_u('\0');
  7021. if (pNameLength != nullptr)
  7022. {
  7023. *pNameLength = totalLength - 1;
  7024. }
  7025. if (pShortNameOffset != nullptr)
  7026. {
  7027. *pShortNameOffset = leftLen;
  7028. }
  7029. return finalName;
  7030. }
  7031. WCHAR * Parser::AllocateStringOfLength(ULONG length)
  7032. {
  7033. Assert(length > 0);
  7034. ULONG totalBytes;
  7035. if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)
  7036. {
  7037. Error(ERRnoMemory);
  7038. }
  7039. WCHAR* finalName = (WCHAR*)this->GetHashTbl()->GetAllocator()->Alloc(totalBytes);
  7040. if (finalName == nullptr)
  7041. {
  7042. Error(ERRnoMemory);
  7043. }
  7044. return finalName;
  7045. }
  7046. LPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7047. {
  7048. if (pShortNameOffset != nullptr)
  7049. {
  7050. *pShortNameOffset = 0;
  7051. }
  7052. if (left == nullptr && !wrapInBrackets)
  7053. {
  7054. if (right)
  7055. {
  7056. *pNameLength = right->Cch();
  7057. return right->Psz();
  7058. }
  7059. return nullptr;
  7060. }
  7061. uint32 leftLen = 0;
  7062. LPCOLESTR leftStr = _u("");
  7063. if (left != nullptr) // if wrapInBrackets is true
  7064. {
  7065. leftStr = left->Psz();
  7066. leftLen = left->Cch();
  7067. }
  7068. if (right == nullptr)
  7069. {
  7070. *pNameLength = leftLen;
  7071. return left->Psz();
  7072. }
  7073. uint32 rightLen = right->Cch();
  7074. return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7075. }
  7076. LPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7077. {
  7078. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7079. if (pShortNameOffset != nullptr)
  7080. {
  7081. *pShortNameOffset = 0;
  7082. }
  7083. Assert(rightLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7084. if (left == nullptr && !wrapInBrackets)
  7085. {
  7086. *pNameLength = rightLen;
  7087. return right;
  7088. }
  7089. LPCOLESTR leftStr = _u("");
  7090. uint32 leftLen = 0;
  7091. if (left != nullptr) // if wrapInBrackets is true
  7092. {
  7093. leftStr = left->Psz();
  7094. leftLen = left->Cch();
  7095. }
  7096. if (rightLen == 0 && !wrapInBrackets)
  7097. {
  7098. *pNameLength = leftLen;
  7099. return left->Psz();
  7100. }
  7101. return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7102. }
  7103. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7104. {
  7105. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7106. if (pShortNameOffset != nullptr)
  7107. {
  7108. *pShortNameOffset = 0;
  7109. }
  7110. Assert(leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7111. if (left == nullptr || (leftLen == 0 && !wrapInBrackets))
  7112. {
  7113. if (right != nullptr)
  7114. {
  7115. *pNameLength = right->Cch();
  7116. return right->Psz();
  7117. }
  7118. return nullptr;
  7119. }
  7120. if (right == nullptr)
  7121. {
  7122. *pNameLength = leftLen;
  7123. return left;
  7124. }
  7125. uint32 rightLen = right->Cch();
  7126. return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7127. }
  7128. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7129. {
  7130. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7131. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7132. if (pShortNameOffset != nullptr)
  7133. {
  7134. *pShortNameOffset = 0;
  7135. }
  7136. Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7137. if (leftLen == 0 && !wrapInBrackets)
  7138. {
  7139. *pNameLength = right ? rightLen : 0;
  7140. return right;
  7141. }
  7142. if (rightLen == 0 && !wrapInBrackets)
  7143. {
  7144. *pNameLength = leftLen;
  7145. return left;
  7146. }
  7147. return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7148. }
  7149. /**
  7150. * Emits a spread error if there is no ambiguity, or marks defers the error for
  7151. * when we can determine if it is a rest error or a spread error.
  7152. *
  7153. * The ambiguity arises when we are parsing a lambda parameter list but we have
  7154. * not seen the => token. At this point, we are either in a parenthesized
  7155. * expression or a parameter list, and cannot issue an error until the matching
  7156. * RParen has been scanned.
  7157. *
  7158. * The actual emission of the error happens in ParseExpr, when we first know if
  7159. * the expression is a lambda parameter list or not.
  7160. *
  7161. */
  7162. void Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)
  7163. {
  7164. if (m_funcParenExprDepth > 0)
  7165. {
  7166. if (m_token.tk == tkRParen)
  7167. {
  7168. if (!m_deferEllipsisError)
  7169. {
  7170. // Capture only the first error instance. Because a lambda will cause a reparse in a formals context, we can assume
  7171. // that this will be a spread error. Nested paren exprs will have their own error instance.
  7172. this->GetScanner()->Capture(&m_deferEllipsisErrorLoc);
  7173. m_deferEllipsisError = true;
  7174. }
  7175. }
  7176. else
  7177. {
  7178. Error(ERRUnexpectedEllipsis);
  7179. }
  7180. }
  7181. else
  7182. {
  7183. Error(ERRInvalidSpreadUse);
  7184. }
  7185. }
  7186. bool Parser::IsTerminateToken()
  7187. {
  7188. return (m_token.tk == tkRCurly ||
  7189. m_token.tk == tkRBrack ||
  7190. m_token.tk == tkRParen ||
  7191. m_token.tk == tkSColon ||
  7192. m_token.tk == tkColon ||
  7193. m_token.tk == tkComma ||
  7194. m_token.tk == tkLimKwd ||
  7195. this->GetScanner()->FHadNewLine());
  7196. }
  7197. /***************************************************************************
  7198. Parse an optional sub expression returning null if there was no expression.
  7199. Checks for no expression by looking for a token that can follow an
  7200. Expression grammar production.
  7201. ***************************************************************************/
  7202. template<bool buildAST>
  7203. bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
  7204. {
  7205. *pnode = nullptr;
  7206. if (IsTerminateToken())
  7207. {
  7208. return false;
  7209. }
  7210. IdentToken token;
  7211. ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
  7212. // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
  7213. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7214. // is not detected at byte code gen time because of deferred parsing.
  7215. this->MarkEscapingRef(pnodeT, &token);
  7216. if (pToken)
  7217. {
  7218. *pToken = token;
  7219. }
  7220. *pnode = pnodeT;
  7221. return true;
  7222. }
  7223. /***************************************************************************
  7224. Parse a sub expression.
  7225. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7226. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7227. ***************************************************************************/
  7228. template<bool buildAST>
  7229. ParseNodePtr Parser::ParseExpr(int oplMin,
  7230. BOOL *pfCanAssign,
  7231. BOOL fAllowIn,
  7232. BOOL fAllowEllipsis,
  7233. LPCOLESTR pNameHint,
  7234. uint32 *pHintLength,
  7235. uint32 *pShortNameOffset,
  7236. _Inout_opt_ IdentToken* pToken,
  7237. bool fUnaryOrParen,
  7238. _Inout_opt_ bool* pfLikelyPattern,
  7239. _Inout_opt_ charcount_t *plastRParen)
  7240. {
  7241. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  7242. int opl;
  7243. OpCode nop;
  7244. charcount_t ichMin;
  7245. ParseNodePtr pnode = nullptr;
  7246. ParseNodePtr pnodeT = nullptr;
  7247. BOOL fCanAssign = TRUE;
  7248. bool assignmentStmt = false;
  7249. bool fIsDotOrIndex = false;
  7250. IdentToken term;
  7251. RestorePoint termStart;
  7252. uint32 hintLength = 0;
  7253. uint32 hintOffset = 0;
  7254. BOOL fLikelyPattern = FALSE;
  7255. ParserState parserState;
  7256. if (pHintLength != nullptr)
  7257. {
  7258. hintLength = *pHintLength;
  7259. }
  7260. if (pShortNameOffset != nullptr)
  7261. {
  7262. hintOffset = *pShortNameOffset;
  7263. }
  7264. EnsureStackAvailable();
  7265. // Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.
  7266. CaptureState(&parserState);
  7267. this->GetScanner()->Capture(&termStart);
  7268. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  7269. m_hasDeferredShorthandInitError = false;
  7270. // Is the current token a unary operator?
  7271. if (this->GetHashTbl()->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)
  7272. {
  7273. IdentToken operandToken;
  7274. ichMin = this->GetScanner()->IchMinTok();
  7275. if (nop == knopYield)
  7276. {
  7277. if (!this->GetScanner()->YieldIsKeywordRegion() || oplMin > opl)
  7278. {
  7279. // The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner
  7280. // is not treating yield as a keyword (!this->GetScanner()->YieldIsKeywordRegion()) occurs
  7281. // in strict mode non-generator function contexts.
  7282. //
  7283. // That is, 'yield' is a keyword because of strict mode, but YieldExpression
  7284. // is not a grammar production outside of generator functions.
  7285. //
  7286. // Otherwise it is an error for a yield to appear in the context of a higher level
  7287. // binding operator, be it unary or binary.
  7288. Error(ERRsyntax);
  7289. }
  7290. if (m_currentScope->GetScopeType() == ScopeType_Parameter)
  7291. {
  7292. Error(ERRsyntax);
  7293. }
  7294. }
  7295. else if (nop == knopAwait)
  7296. {
  7297. if (!this->GetScanner()->AwaitIsKeywordRegion() ||
  7298. m_currentScope->GetScopeType() == ScopeType_Parameter)
  7299. {
  7300. // As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)
  7301. // but the scanner is not treating await as a keyword (!this->GetScanner()->AwaitIsKeyword())
  7302. // occurs in strict mode non-async function contexts.
  7303. //
  7304. // That is, 'await' is a keyword because of strict mode, but AwaitExpression
  7305. // is not a grammar production outside of async functions.
  7306. //
  7307. // Further, await expressions are disallowed within parameter scopes.
  7308. Error(ERRBadAwait);
  7309. }
  7310. }
  7311. this->GetScanner()->Scan();
  7312. if (m_token.tk == tkEllipsis) {
  7313. // ... cannot have a unary prefix.
  7314. Error(ERRUnexpectedEllipsis);
  7315. }
  7316. if (nop == knopYield && !this->GetScanner()->FHadNewLine() && m_token.tk == tkStar)
  7317. {
  7318. this->GetScanner()->Scan();
  7319. nop = knopYieldStar;
  7320. }
  7321. if (nop == knopYield)
  7322. {
  7323. if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, TRUE, fAllowEllipsis))
  7324. {
  7325. nop = knopYieldLeaf;
  7326. if (buildAST)
  7327. {
  7328. pnode = CreateNodeForOpT<knopYieldLeaf>(ichMin, this->GetScanner()->IchLimTok());
  7329. }
  7330. }
  7331. }
  7332. else
  7333. {
  7334. // Disallow spread after a unary operator.
  7335. pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr /*hint*/, nullptr /*hintLength*/, nullptr /*hintOffset*/, &operandToken, true, nullptr, plastRParen);
  7336. }
  7337. if (nop != knopYieldLeaf)
  7338. {
  7339. if ((nop == knopIncPre || nop == knopDecPre) && (m_token.tk != tkDArrow))
  7340. {
  7341. if (!fCanAssign &&
  7342. (m_sourceContextInfo
  7343. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7344. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7345. {
  7346. Error(JSERR_CantAssignTo);
  7347. }
  7348. TrackAssignment<buildAST>(pnodeT, &operandToken);
  7349. if (buildAST)
  7350. {
  7351. if (IsStrictMode() && pnodeT->nop == knopName)
  7352. {
  7353. CheckStrictModeEvalArgumentsUsage(pnodeT->AsParseNodeName()->pid);
  7354. }
  7355. }
  7356. else
  7357. {
  7358. if (IsStrictMode() && operandToken.tk == tkID)
  7359. {
  7360. CheckStrictModeEvalArgumentsUsage(operandToken.pid);
  7361. }
  7362. }
  7363. }
  7364. else if (nop == knopEllipsis)
  7365. {
  7366. if (!fAllowEllipsis)
  7367. {
  7368. DeferOrEmitPotentialSpreadError(pnodeT);
  7369. }
  7370. }
  7371. else if (m_token.tk == tkExpo)
  7372. {
  7373. //Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...
  7374. Error(ERRInvalidUseofExponentiationOperator);
  7375. }
  7376. if (buildAST)
  7377. {
  7378. //Do not do the folding for Asm in case of KnopPos as we need this to determine the type
  7379. if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)
  7380. {
  7381. // Fold away a unary '+' on a number.
  7382. pnode = pnodeT;
  7383. }
  7384. else if (nop == knopNeg &&
  7385. ((pnodeT->nop == knopInt && pnodeT->AsParseNodeInt()->lw != 0) ||
  7386. (pnodeT->nop == knopFlt && (pnodeT->AsParseNodeFloat()->dbl != 0 || this->m_InAsmMode))))
  7387. {
  7388. // Fold a unary '-' on a number into the value of the number itself.
  7389. pnode = pnodeT;
  7390. if (pnode->nop == knopInt)
  7391. {
  7392. pnode->AsParseNodeInt()->lw = -pnode->AsParseNodeInt()->lw;
  7393. }
  7394. else
  7395. {
  7396. pnode->AsParseNodeFloat()->dbl = -pnode->AsParseNodeFloat()->dbl;
  7397. }
  7398. }
  7399. else
  7400. {
  7401. pnode = CreateUniNode(nop, pnodeT);
  7402. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  7403. }
  7404. pnode->ichMin = ichMin;
  7405. }
  7406. if (nop == knopDelete)
  7407. {
  7408. if (IsStrictMode())
  7409. {
  7410. if ((buildAST && pnode->AsParseNodeUni()->pnode1->IsUserIdentifier()) ||
  7411. (!buildAST && operandToken.tk == tkID && !this->IsSpecialName(operandToken.pid)))
  7412. {
  7413. Error(ERRInvalidDelete);
  7414. }
  7415. }
  7416. if (buildAST)
  7417. {
  7418. ParseNodePtr pnode1 = pnode->AsParseNodeUni()->pnode1;
  7419. if (m_currentNodeFunc)
  7420. {
  7421. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  7422. {
  7423. // If we delete an arguments property, use the conservative,
  7424. // heap-allocated arguments object.
  7425. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  7426. }
  7427. }
  7428. }
  7429. }
  7430. }
  7431. fCanAssign = FALSE;
  7432. }
  7433. else
  7434. {
  7435. ichMin = this->GetScanner()->IchMinTok();
  7436. pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, TRUE, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex, plastRParen);
  7437. if (pfLikelyPattern != nullptr)
  7438. {
  7439. *pfLikelyPattern = !!fLikelyPattern;
  7440. }
  7441. if (m_token.tk == tkDArrow
  7442. // If we have introduced shorthand error above in the ParseExpr, we need to reset if next token is the assignment.
  7443. || (m_token.tk == tkAsg && oplMin <= koplAsg))
  7444. {
  7445. m_hasDeferredShorthandInitError = false;
  7446. }
  7447. if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)
  7448. {
  7449. this->GetScanner()->SeekTo(termStart);
  7450. // 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
  7451. // on the pidref stack match.
  7452. int saveNextBlockId = m_nextBlockId;
  7453. m_nextBlockId = parserState.m_nextBlockId;
  7454. ParseDestructuredLiteralWithScopeSave(tkLCurly, false/*isDecl*/, false /*topLevel*/, DIC_ShouldNotParseInitializer);
  7455. // 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
  7456. // because we don't parse initializers during reparse and there may be additional blocks (e.g. a class declaration)
  7457. // in the initializers that will cause the next Block ID at the end of the reparsing to be different.
  7458. m_nextBlockId = saveNextBlockId;
  7459. if (buildAST)
  7460. {
  7461. this->SetHasDestructuringPattern(true);
  7462. pnode = ConvertToPattern(pnode);
  7463. }
  7464. }
  7465. if (buildAST)
  7466. {
  7467. pNameHint = NULL;
  7468. if (pnode->nop == knopName)
  7469. {
  7470. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7471. pNameHint = pid->Psz();
  7472. hintLength = pid->Cch();
  7473. hintOffset = 0;
  7474. }
  7475. else if (pnode->nop == knopDot || pnode->nop == knopIndex)
  7476. {
  7477. if (CONFIG_FLAG(UseFullName))
  7478. {
  7479. pNameHint = ConstructNameHint(pnode->AsParseNodeBin(), &hintLength, &hintOffset);
  7480. }
  7481. else
  7482. {
  7483. ParseNodePtr pnodeName = pnode;
  7484. while (pnodeName->nop == knopDot)
  7485. {
  7486. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  7487. }
  7488. if (pnodeName->nop == knopName)
  7489. {
  7490. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7491. pNameHint = pid->Psz();
  7492. hintLength = pid->Cch();
  7493. hintOffset = 0;
  7494. }
  7495. }
  7496. }
  7497. }
  7498. // Check for postfix unary operators.
  7499. if (!this->GetScanner()->FHadNewLine() &&
  7500. (tkInc == m_token.tk || tkDec == m_token.tk))
  7501. {
  7502. if (!fCanAssign &&
  7503. (m_sourceContextInfo
  7504. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7505. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7506. {
  7507. Error(JSERR_CantAssignTo);
  7508. }
  7509. TrackAssignment<buildAST>(pnode, &term);
  7510. fCanAssign = FALSE;
  7511. if (buildAST)
  7512. {
  7513. if (IsStrictMode() && pnode->nop == knopName)
  7514. {
  7515. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7516. }
  7517. this->CheckArguments(pnode);
  7518. pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);
  7519. pnode->ichLim = this->GetScanner()->IchLimTok();
  7520. }
  7521. else
  7522. {
  7523. if (IsStrictMode() && term.tk == tkID)
  7524. {
  7525. CheckStrictModeEvalArgumentsUsage(term.pid);
  7526. }
  7527. // This expression is not an identifier
  7528. term.tk = tkNone;
  7529. }
  7530. this->GetScanner()->Scan();
  7531. }
  7532. }
  7533. // Process a sequence of operators and operands.
  7534. for (;;)
  7535. {
  7536. if (!this->GetHashTbl()->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)
  7537. {
  7538. break;
  7539. }
  7540. if (!fAllowIn && nop == knopIn)
  7541. {
  7542. break;
  7543. }
  7544. Assert(opl != koplNo);
  7545. if (opl == koplAsg)
  7546. {
  7547. if (m_token.tk != tkDArrow)
  7548. {
  7549. // Assignment operator. These are the only right associative
  7550. // binary operators. We also need to special case the left
  7551. // operand - it should only be a LeftHandSideExpression.
  7552. Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);
  7553. TrackAssignment<buildAST>(pnode, &term);
  7554. if (buildAST)
  7555. {
  7556. if (IsStrictMode() && pnode->nop == knopName)
  7557. {
  7558. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7559. }
  7560. // Assignment stmt of the form "this.<id> = <expr>"
  7561. if (nop == knopAsg
  7562. && pnode->nop == knopDot
  7563. && pnode->AsParseNodeBin()->pnode1->nop == knopName
  7564. && pnode->AsParseNodeBin()->pnode1->AsParseNodeName()->pid == wellKnownPropertyPids._this
  7565. && pnode->AsParseNodeBin()->pnode2->nop == knopName)
  7566. {
  7567. if (pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->pid != wellKnownPropertyPids.__proto__)
  7568. {
  7569. assignmentStmt = true;
  7570. }
  7571. }
  7572. }
  7573. else
  7574. {
  7575. if (IsStrictMode() && term.tk == tkID)
  7576. {
  7577. CheckStrictModeEvalArgumentsUsage(term.pid);
  7578. }
  7579. }
  7580. }
  7581. if (opl < oplMin)
  7582. {
  7583. break;
  7584. }
  7585. if (m_token.tk != tkDArrow && !fCanAssign &&
  7586. (m_sourceContextInfo
  7587. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7588. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7589. {
  7590. Error(JSERR_CantAssignTo);
  7591. // No recovery necessary since this is a semantic, not structural, error.
  7592. }
  7593. }
  7594. else if (opl == koplExpo)
  7595. {
  7596. // ** operator is right associative
  7597. if (opl < oplMin)
  7598. {
  7599. break;
  7600. }
  7601. }
  7602. else if (opl <= oplMin)
  7603. {
  7604. break;
  7605. }
  7606. // This expression is not an identifier
  7607. term.tk = tkNone;
  7608. // Precedence is high enough. Consume the operator token.
  7609. this->GetScanner()->Scan();
  7610. fCanAssign = !!fLikelyPattern;
  7611. // Special case the "?:" operator
  7612. if (nop == knopQmark)
  7613. {
  7614. pnodeT = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);
  7615. ChkCurTok(tkColon, ERRnoColon);
  7616. ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, plastRParen);
  7617. if (buildAST)
  7618. {
  7619. pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);
  7620. this->CheckArguments(pnode->AsParseNodeTri()->pnode2);
  7621. this->CheckArguments(pnode->AsParseNodeTri()->pnode3);
  7622. }
  7623. }
  7624. else if (nop == knopFncDecl)
  7625. {
  7626. ushort flags = fFncLambda;
  7627. size_t iecpMin = 0;
  7628. bool isAsyncMethod = false;
  7629. RestoreStateFrom(&parserState);
  7630. this->GetScanner()->SeekTo(termStart);
  7631. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  7632. {
  7633. ichMin = this->GetScanner()->IchMinTok();
  7634. iecpMin = this->GetScanner()->IecpMinTok();
  7635. this->GetScanner()->Scan();
  7636. if ((m_token.tk == tkID || m_token.tk == tkLParen) && !this->GetScanner()->FHadNewLine())
  7637. {
  7638. flags |= fFncAsync;
  7639. isAsyncMethod = true;
  7640. }
  7641. else
  7642. {
  7643. this->GetScanner()->SeekTo(termStart);
  7644. }
  7645. }
  7646. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan = */false, /* resetParsingSuperRestrictionState = */false, /* fUnaryOrParen = */ false, fAllowIn);
  7647. if (isAsyncMethod)
  7648. {
  7649. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  7650. pnode->ichMin = ichMin;
  7651. }
  7652. // ArrowFunction/AsyncArrowFunction is part of AssignmentExpression, which should terminate the expression unless followed by a comma
  7653. if (m_token.tk != tkComma && m_token.tk != tkIN)
  7654. {
  7655. if (!(IsTerminateToken()))
  7656. {
  7657. Error(ERRnoSemic);
  7658. }
  7659. break;
  7660. }
  7661. }
  7662. else // a binary operator
  7663. {
  7664. ParseNode* pnode1 = pnode;
  7665. // Parse the operand, make a new node, and look for more
  7666. IdentToken token;
  7667. ParseNode* pnode2 = ParseExpr<buildAST>(
  7668. opl, nullptr, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token, false, nullptr, plastRParen);
  7669. // Detect nested function escapes of the pattern "o.f = function(){...}" or "o[s] = function(){...}".
  7670. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7671. // is not detected at byte code gen time because of deferred parsing.
  7672. if (fIsDotOrIndex && nop == knopAsg)
  7673. {
  7674. this->MarkEscapingRef(pnodeT, &token);
  7675. }
  7676. if (buildAST)
  7677. {
  7678. Assert(pnode2 != nullptr);
  7679. if (pnode2->nop == knopFncDecl)
  7680. {
  7681. Assert(hintLength >= hintOffset);
  7682. pnode2->AsParseNodeFnc()->hint = pNameHint;
  7683. pnode2->AsParseNodeFnc()->hintLength = hintLength;
  7684. pnode2->AsParseNodeFnc()->hintOffset = hintOffset;
  7685. if (pnode1->nop == knopDot)
  7686. {
  7687. pnode2->AsParseNodeFnc()->isNameIdentifierRef = false;
  7688. }
  7689. else if (pnode1->nop == knopName)
  7690. {
  7691. PidRefStack *pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7692. pidRef->isFuncAssignment = true;
  7693. }
  7694. }
  7695. else if (pnode2->nop == knopClassDecl && pnode1->nop == knopDot)
  7696. {
  7697. Assert(pnode2->AsParseNodeClass()->pnodeConstructor);
  7698. if (!pnode2->AsParseNodeClass()->pnodeConstructor->pid)
  7699. {
  7700. pnode2->AsParseNodeClass()->pnodeConstructor->isNameIdentifierRef = false;
  7701. }
  7702. }
  7703. else if (pnode1->nop == knopName && nop == knopIn)
  7704. {
  7705. PidRefStack* pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  7706. pidRef->SetIsUsedInLdElem(true);
  7707. }
  7708. pnode = CreateBinNode(nop, pnode1, pnode2);
  7709. }
  7710. pNameHint = nullptr;
  7711. }
  7712. }
  7713. if (buildAST)
  7714. {
  7715. if (!assignmentStmt)
  7716. {
  7717. // Don't set the flag for following nodes
  7718. switch (pnode->nop)
  7719. {
  7720. case knopName:
  7721. case knopInt:
  7722. case knopFlt:
  7723. case knopStr:
  7724. case knopRegExp:
  7725. case knopNull:
  7726. case knopFalse:
  7727. case knopTrue:
  7728. break;
  7729. default:
  7730. if (m_currentNodeFunc)
  7731. {
  7732. m_currentNodeFunc->SetHasNonThisStmt();
  7733. }
  7734. else if (m_currentNodeProg)
  7735. {
  7736. m_currentNodeProg->SetHasNonThisStmt();
  7737. }
  7738. }
  7739. }
  7740. }
  7741. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;
  7742. if (NULL != pfCanAssign)
  7743. {
  7744. *pfCanAssign = fCanAssign;
  7745. }
  7746. // Pass back identifier if requested
  7747. if (pToken && term.tk == tkID)
  7748. {
  7749. *pToken = term;
  7750. }
  7751. //Track "obj.a" assignment patterns here - Promote the Assignment state for the property's PID.
  7752. // This includes =, += etc.
  7753. if (pnode != NULL)
  7754. {
  7755. uint nodeType = ParseNode::Grfnop(pnode->nop);
  7756. if (nodeType & fnopAsg)
  7757. {
  7758. if (nodeType & fnopBin)
  7759. {
  7760. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  7761. Assert(lhs);
  7762. if (lhs->nop == knopDot)
  7763. {
  7764. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7765. if (propertyNode->nop == knopName)
  7766. {
  7767. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  7768. }
  7769. }
  7770. }
  7771. else if (nodeType & fnopUni)
  7772. {
  7773. // cases like obj.a++, ++obj.a
  7774. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  7775. if (lhs->nop == knopDot)
  7776. {
  7777. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7778. if (propertyNode->nop == knopName)
  7779. {
  7780. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  7781. }
  7782. }
  7783. }
  7784. }
  7785. }
  7786. return pnode;
  7787. }
  7788. template<bool buildAST>
  7789. void Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)
  7790. {
  7791. if (buildAST)
  7792. {
  7793. Assert(pnodeT != nullptr);
  7794. if (pnodeT->nop == knopName)
  7795. {
  7796. PidRefStack *ref = pnodeT->AsParseNodeName()->pid->GetTopRef();
  7797. Assert(ref);
  7798. ref->isAsg = true;
  7799. }
  7800. }
  7801. else
  7802. {
  7803. Assert(pToken != nullptr);
  7804. if (pToken->tk == tkID)
  7805. {
  7806. PidRefStack *ref = pToken->pid->GetTopRef();
  7807. Assert(ref);
  7808. ref->isAsg = true;
  7809. }
  7810. }
  7811. }
  7812. PidRefStack* Parser::PushPidRef(IdentPtr pid)
  7813. {
  7814. ParseNodeFnc* currentFnc = GetCurrentFunctionNode();
  7815. if (this->IsCreatingStateCache())
  7816. {
  7817. IdentPtrSet* capturedNames = currentFnc->EnsureCapturedNames(&m_nodeAllocator);
  7818. capturedNames->AddNew(pid);
  7819. }
  7820. if (PHASE_ON1(Js::ParallelParsePhase))
  7821. {
  7822. // NOTE: the phase check is here to protect perf. See OSG 1020424.
  7823. // In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather
  7824. // than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.
  7825. return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->blockId, currentFnc->functionId);
  7826. }
  7827. Assert(GetCurrentBlock() != nullptr);
  7828. AssertMsg(pid != nullptr, "PID should be created");
  7829. PidRefStack *ref = pid->GetTopRef(m_nextBlockId - 1);
  7830. int blockId = GetCurrentBlock()->blockId;
  7831. int funcId = currentFnc->functionId;
  7832. if (!ref || (ref->GetScopeId() < blockId))
  7833. {
  7834. ref = Anew(&m_nodeAllocator, PidRefStack);
  7835. if (ref == nullptr)
  7836. {
  7837. Error(ERRnoMemory);
  7838. }
  7839. pid->PushPidRef(blockId, funcId, ref);
  7840. }
  7841. else if (m_reparsingLambdaParams)
  7842. {
  7843. // If we're reparsing params, then we may have pid refs left behind from the first pass. Make sure we're
  7844. // working with the right ref at this point.
  7845. ref = this->FindOrAddPidRef(pid, blockId, funcId);
  7846. // Fix up the function ID if we're reparsing lambda parameters.
  7847. ref->funcId = funcId;
  7848. }
  7849. return ref;
  7850. }
  7851. PidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)
  7852. {
  7853. PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);
  7854. if (ref == NULL)
  7855. {
  7856. Error(ERRnoMemory);
  7857. }
  7858. return ref;
  7859. }
  7860. void Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)
  7861. {
  7862. PidRefStack *prevRef = pid->RemovePrevPidRef(ref);
  7863. Assert(prevRef);
  7864. if (prevRef->GetSym() == nullptr)
  7865. {
  7866. AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);
  7867. }
  7868. }
  7869. void Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)
  7870. {
  7871. PidRefStack *ref = pid->GetTopRef();
  7872. while (ref && ref->GetScopeId() >= blockId)
  7873. {
  7874. ref->SetDynamicBinding();
  7875. ref = ref->prev;
  7876. }
  7877. }
  7878. ParseNodeBlock* Parser::GetFunctionBlock()
  7879. {
  7880. Assert(m_currentBlockInfo != nullptr);
  7881. return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;
  7882. }
  7883. ParseNodeBlock* Parser::GetCurrentBlock()
  7884. {
  7885. return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;
  7886. }
  7887. BlockInfoStack* Parser::GetCurrentBlockInfo()
  7888. {
  7889. return m_currentBlockInfo;
  7890. }
  7891. BlockInfoStack* Parser::GetCurrentFunctionBlockInfo()
  7892. {
  7893. return m_currentBlockInfo->pBlockInfoFunction;
  7894. }
  7895. /***************************************************************************
  7896. Parse a variable declaration.
  7897. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7898. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7899. ***************************************************************************/
  7900. template<bool buildAST>
  7901. ParseNodePtr Parser::ParseVariableDeclaration(
  7902. tokens declarationType, charcount_t ichMin,
  7903. BOOL fAllowIn/* = TRUE*/,
  7904. BOOL* pfForInOk/* = nullptr*/,
  7905. BOOL singleDefOnly/* = FALSE*/,
  7906. BOOL allowInit/* = TRUE*/,
  7907. BOOL isTopVarParse/* = TRUE*/,
  7908. BOOL isFor/* = FALSE*/,
  7909. BOOL* nativeForOk /*= nullptr*/)
  7910. {
  7911. ParseNodePtr pnodeThis = nullptr;
  7912. ParseNodePtr pnodeInit;
  7913. ParseNodePtr pnodeList = nullptr;
  7914. ParseNodePtr *lastNodeRef = nullptr;
  7915. LPCOLESTR pNameHint = nullptr;
  7916. uint32 nameHintLength = 0;
  7917. uint32 nameHintOffset = 0;
  7918. Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);
  7919. for (;;)
  7920. {
  7921. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  7922. {
  7923. pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);
  7924. if (pnodeThis != nullptr)
  7925. {
  7926. pnodeThis->ichMin = ichMin;
  7927. pnodeThis->SetIsPatternDeclaration();
  7928. }
  7929. }
  7930. else
  7931. {
  7932. if (m_token.tk != tkID)
  7933. {
  7934. IdentifierExpectedError(m_token);
  7935. }
  7936. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  7937. Assert(pid);
  7938. pNameHint = pid->Psz();
  7939. nameHintLength = pid->Cch();
  7940. nameHintOffset = 0;
  7941. if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))
  7942. {
  7943. Error(ERRLetIDInLexicalDecl, pnodeThis);
  7944. }
  7945. if (declarationType == tkVAR)
  7946. {
  7947. pnodeThis = CreateVarDeclNode(pid, STVariable);
  7948. }
  7949. else if (declarationType == tkCONST)
  7950. {
  7951. pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);
  7952. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Const, m_scriptContext);
  7953. }
  7954. else
  7955. {
  7956. pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);
  7957. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Let, m_scriptContext);
  7958. }
  7959. if (pid == wellKnownPropertyPids.arguments)
  7960. {
  7961. // This var declaration may change the way an 'arguments' identifier in the function is resolved
  7962. if (declarationType == tkVAR)
  7963. {
  7964. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_varDeclaration;
  7965. }
  7966. else
  7967. {
  7968. if (GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  7969. {
  7970. // Only override arguments if we are at the function block level.
  7971. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  7972. }
  7973. }
  7974. }
  7975. if (pnodeThis)
  7976. {
  7977. pnodeThis->ichMin = ichMin;
  7978. }
  7979. this->GetScanner()->Scan();
  7980. if (m_token.tk == tkAsg)
  7981. {
  7982. if (!allowInit)
  7983. {
  7984. Error(ERRUnexpectedDefault);
  7985. }
  7986. if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))
  7987. {
  7988. *pfForInOk = FALSE;
  7989. }
  7990. this->GetScanner()->Scan();
  7991. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  7992. if (buildAST)
  7993. {
  7994. AnalysisAssert(pnodeThis);
  7995. pnodeThis->AsParseNodeVar()->pnodeInit = pnodeInit;
  7996. pnodeThis->ichLim = pnodeInit->ichLim;
  7997. if (pnodeInit->nop == knopFncDecl)
  7998. {
  7999. Assert(nameHintLength >= nameHintOffset);
  8000. pnodeInit->AsParseNodeFnc()->hint = pNameHint;
  8001. pnodeInit->AsParseNodeFnc()->hintLength = nameHintLength;
  8002. pnodeInit->AsParseNodeFnc()->hintOffset = nameHintOffset;
  8003. pnodeThis->AsParseNodeVar()->pid->GetTopRef()->isFuncAssignment = true;
  8004. }
  8005. else
  8006. {
  8007. this->CheckArguments(pnodeInit);
  8008. }
  8009. pNameHint = nullptr;
  8010. }
  8011. //Track var a =, let a= , const a =
  8012. // This is for FixedFields Constant Heuristics
  8013. if (pnodeThis && pnodeThis->AsParseNodeVar()->pnodeInit != nullptr)
  8014. {
  8015. pnodeThis->AsParseNodeVar()->sym->PromoteAssignmentState();
  8016. }
  8017. }
  8018. else if (declarationType == tkCONST /*pnodeThis->nop == knopConstDecl*/
  8019. && !singleDefOnly
  8020. && !(isFor && TokIsForInOrForOf()))
  8021. {
  8022. Error(ERRUninitializedConst);
  8023. }
  8024. if (m_currentNodeFunc && pnodeThis && pnodeThis->AsParseNodeVar()->sym->GetIsFormal())
  8025. {
  8026. m_currentNodeFunc->SetHasAnyWriteToFormals(true);
  8027. }
  8028. }
  8029. if (singleDefOnly)
  8030. {
  8031. return pnodeThis;
  8032. }
  8033. if (buildAST)
  8034. {
  8035. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);
  8036. }
  8037. if (m_token.tk != tkComma)
  8038. {
  8039. return pnodeList;
  8040. }
  8041. if (pfForInOk)
  8042. {
  8043. // don't allow "for (var a, b in c)"
  8044. *pfForInOk = FALSE;
  8045. }
  8046. this->GetScanner()->Scan();
  8047. ichMin = this->GetScanner()->IchMinTok();
  8048. }
  8049. }
  8050. /***************************************************************************
  8051. Parse try-catch-finally statement
  8052. ***************************************************************************/
  8053. // The try-catch-finally tree nests the try-catch within a try-finally.
  8054. // This matches the new runtime implementation.
  8055. template<bool buildAST>
  8056. ParseNodeStmt * Parser::ParseTryCatchFinally()
  8057. {
  8058. this->m_tryCatchOrFinallyDepth++;
  8059. ParseNodeTry * pnodeT = ParseTry<buildAST>();
  8060. ParseNodeTryCatch * pnodeTC = nullptr;
  8061. StmtNest stmt;
  8062. bool hasCatch = false;
  8063. if (tkCATCH == m_token.tk)
  8064. {
  8065. hasCatch = true;
  8066. if (buildAST)
  8067. {
  8068. pnodeTC = CreateNodeForOpT<knopTryCatch>();
  8069. pnodeT->pnodeOuter = pnodeTC;
  8070. pnodeTC->pnodeTry = pnodeT;
  8071. }
  8072. PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr);
  8073. ParseNodeCatch * pnodeCatch = ParseCatch<buildAST>();
  8074. if (buildAST)
  8075. {
  8076. pnodeTC->pnodeCatch = pnodeCatch;
  8077. }
  8078. PopStmt(&stmt);
  8079. }
  8080. if (tkFINALLY != m_token.tk)
  8081. {
  8082. if (!hasCatch)
  8083. {
  8084. Error(ERRnoCatch);
  8085. }
  8086. Assert(!buildAST || pnodeTC);
  8087. this->m_tryCatchOrFinallyDepth--;
  8088. return pnodeTC;
  8089. }
  8090. ParseNodeTryFinally * pnodeTF = nullptr;
  8091. if (buildAST)
  8092. {
  8093. pnodeTF = CreateNodeForOpT<knopTryFinally>();
  8094. }
  8095. PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr);
  8096. ParseNodeFinally * pnodeFinally = ParseFinally<buildAST>();
  8097. if (buildAST)
  8098. {
  8099. if (!hasCatch)
  8100. {
  8101. pnodeTF->pnodeTry = pnodeT;
  8102. pnodeT->pnodeOuter = pnodeTF;
  8103. }
  8104. else
  8105. {
  8106. pnodeTF->pnodeTry = CreateNodeForOpT<knopTry>();
  8107. pnodeTF->pnodeTry->pnodeOuter = pnodeTF;
  8108. pnodeTF->pnodeTry->pnodeBody = pnodeTC;
  8109. pnodeTC->pnodeOuter = pnodeTF->pnodeTry;
  8110. }
  8111. pnodeTF->pnodeFinally = pnodeFinally;
  8112. }
  8113. PopStmt(&stmt);
  8114. this->m_tryCatchOrFinallyDepth--;
  8115. return pnodeTF;
  8116. }
  8117. template<bool buildAST>
  8118. ParseNodeTry * Parser::ParseTry()
  8119. {
  8120. ParseNodeTry * pnode = nullptr;
  8121. StmtNest stmt;
  8122. Assert(tkTRY == m_token.tk);
  8123. if (buildAST)
  8124. {
  8125. pnode = CreateNodeForOpT<knopTry>();
  8126. }
  8127. this->GetScanner()->Scan();
  8128. if (tkLCurly != m_token.tk)
  8129. {
  8130. Error(ERRnoLcurly);
  8131. }
  8132. PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr);
  8133. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8134. if (buildAST)
  8135. {
  8136. pnode->pnodeBody = pnodeBody;
  8137. if (pnode->pnodeBody)
  8138. pnode->ichLim = pnode->pnodeBody->ichLim;
  8139. }
  8140. PopStmt(&stmt);
  8141. return pnode;
  8142. }
  8143. template<bool buildAST>
  8144. ParseNodeFinally * Parser::ParseFinally()
  8145. {
  8146. ParseNodeFinally * pnode = nullptr;
  8147. StmtNest stmt;
  8148. Assert(tkFINALLY == m_token.tk);
  8149. if (buildAST)
  8150. {
  8151. pnode = CreateNodeForOpT<knopFinally>();
  8152. }
  8153. this->GetScanner()->Scan();
  8154. if (tkLCurly != m_token.tk)
  8155. {
  8156. Error(ERRnoLcurly);
  8157. }
  8158. PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr);
  8159. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8160. if (buildAST)
  8161. {
  8162. pnode->pnodeBody = pnodeBody;
  8163. if (!pnode->pnodeBody)
  8164. // Will only occur due to error correction.
  8165. pnode->pnodeBody = CreateNodeForOpT<knopEmpty>();
  8166. else
  8167. pnode->ichLim = pnode->pnodeBody->ichLim;
  8168. }
  8169. PopStmt(&stmt);
  8170. return pnode;
  8171. }
  8172. template<bool buildAST>
  8173. ParseNodeCatch * Parser::ParseCatch()
  8174. {
  8175. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8176. ParseNodeCatch * pnode = nullptr;
  8177. ParseNodeBlock * pnodeCatchScope = nullptr;
  8178. StmtNest stmt;
  8179. IdentPtr pidCatch = nullptr;
  8180. if (tkCATCH == m_token.tk)
  8181. {
  8182. charcount_t ichMin;
  8183. if (buildAST)
  8184. {
  8185. ichMin = this->GetScanner()->IchMinTok();
  8186. }
  8187. this->GetScanner()->Scan(); //catch
  8188. ChkCurTok(tkLParen, ERRnoLparen); //catch(
  8189. bool isPattern = false;
  8190. if (tkID != m_token.tk)
  8191. {
  8192. isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();
  8193. if (!isPattern)
  8194. {
  8195. IdentifierExpectedError(m_token);
  8196. }
  8197. }
  8198. if (buildAST)
  8199. {
  8200. pnode = CreateNodeForOpT<knopCatch>(ichMin);
  8201. pnode->pnodeNext = nullptr;
  8202. PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr);
  8203. }
  8204. pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);
  8205. if (buildAST)
  8206. {
  8207. // Add this catch to the current scope list.
  8208. if (m_ppnodeExprScope)
  8209. {
  8210. Assert(*m_ppnodeExprScope == nullptr);
  8211. *m_ppnodeExprScope = pnode;
  8212. m_ppnodeExprScope = &pnode->pnodeNext;
  8213. }
  8214. else
  8215. {
  8216. Assert(m_ppnodeScope);
  8217. Assert(*m_ppnodeScope == nullptr);
  8218. *m_ppnodeScope = pnode;
  8219. m_ppnodeScope = &pnode->pnodeNext;
  8220. }
  8221. // Keep a list of function expressions (not declarations) at this scope.
  8222. ppnodeExprScopeSave = m_ppnodeExprScope;
  8223. m_ppnodeExprScope = &pnode->pnodeScopes;
  8224. pnode->pnodeScopes = nullptr;
  8225. }
  8226. if (isPattern)
  8227. {
  8228. ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, true /*topLevel*/, DIC_ForceErrorOnInitializer);
  8229. if (buildAST)
  8230. {
  8231. pnode->SetParam(CreateParamPatternNode(pnodePattern));
  8232. Scope *scope = pnodeCatchScope->scope;
  8233. pnode->scope = scope;
  8234. }
  8235. }
  8236. else
  8237. {
  8238. if (IsStrictMode())
  8239. {
  8240. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  8241. if (pid == wellKnownPropertyPids.eval)
  8242. {
  8243. Error(ERREvalUsage);
  8244. }
  8245. else if (pid == wellKnownPropertyPids.arguments)
  8246. {
  8247. Error(ERRArgsUsage);
  8248. }
  8249. }
  8250. pidCatch = m_token.GetIdentifier(this->GetHashTbl());
  8251. PidRefStack *ref = this->FindOrAddPidRef(pidCatch, GetCurrentBlock()->blockId, GetCurrentFunctionNode()->functionId);
  8252. ParseNodeName * pnodeParam = CreateNameNode(pidCatch);
  8253. pnodeParam->SetSymRef(ref);
  8254. const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());
  8255. int nameLength = pidCatch->Cch();
  8256. SymbolName const symName(name, nameLength);
  8257. Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);
  8258. if (sym == nullptr)
  8259. {
  8260. Error(ERRnoMemory);
  8261. }
  8262. sym->SetPid(pidCatch);
  8263. Assert(ref->GetSym() == nullptr);
  8264. ref->SetSym(sym);
  8265. Scope *scope = pnodeCatchScope->scope;
  8266. scope->AddNewSymbol(sym);
  8267. if (buildAST)
  8268. {
  8269. pnode->SetParam(pnodeParam);
  8270. pnode->scope = scope;
  8271. }
  8272. this->GetScanner()->Scan();
  8273. }
  8274. charcount_t ichLim;
  8275. if (buildAST)
  8276. {
  8277. ichLim = this->GetScanner()->IchLimTok();
  8278. }
  8279. ChkCurTok(tkRParen, ERRnoRparen); //catch(id[:expr])
  8280. if (tkLCurly != m_token.tk)
  8281. {
  8282. Error(ERRnoLcurly);
  8283. }
  8284. ParseNodePtr pnodeBody = ParseStatement<buildAST>(); //catch(id[:expr]) {block}
  8285. if (buildAST)
  8286. {
  8287. pnode->pnodeBody = pnodeBody;
  8288. pnode->ichLim = ichLim;
  8289. }
  8290. if (pnodeCatchScope != nullptr)
  8291. {
  8292. FinishParseBlock(pnodeCatchScope);
  8293. }
  8294. if (pnodeCatchScope->GetCallsEval() || pnodeCatchScope->GetChildCallsEval())
  8295. {
  8296. GetCurrentBlock()->SetChildCallsEval(true);
  8297. }
  8298. if (buildAST)
  8299. {
  8300. PopStmt(&stmt);
  8301. // Restore the lists of function expression scopes.
  8302. Assert(m_ppnodeExprScope);
  8303. Assert(*m_ppnodeExprScope == nullptr);
  8304. m_ppnodeExprScope = ppnodeExprScopeSave;
  8305. }
  8306. }
  8307. return pnode;
  8308. }
  8309. template<bool buildAST>
  8310. ParseNodeCase * Parser::ParseCase(ParseNodePtr *ppnodeBody)
  8311. {
  8312. ParseNodeCase * pnodeT = nullptr;
  8313. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8314. this->GetScanner()->Scan();
  8315. ParseNodePtr pnodeExpr = ParseExpr<buildAST>();
  8316. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8317. ChkCurTok(tkColon, ERRnoColon);
  8318. if (buildAST)
  8319. {
  8320. pnodeT = CreateNodeForOpT<knopCase>(ichMinT);
  8321. pnodeT->pnodeExpr = pnodeExpr;
  8322. pnodeT->ichLim = ichLim;
  8323. }
  8324. ParseStmtList<buildAST>(ppnodeBody);
  8325. return pnodeT;
  8326. }
  8327. /***************************************************************************
  8328. Parse a single statement. Digest a trailing semicolon.
  8329. ***************************************************************************/
  8330. template<bool buildAST>
  8331. ParseNodePtr Parser::ParseStatement()
  8332. {
  8333. ParseNodePtr pnode = nullptr;
  8334. LabelId* pLabelIdList = nullptr;
  8335. charcount_t ichMin = 0;
  8336. size_t iecpMin = 0;
  8337. StmtNest stmt;
  8338. StmtNest *pstmt;
  8339. BOOL fForInOrOfOkay;
  8340. BOOL fCanAssign;
  8341. IdentPtr pid;
  8342. uint fnop;
  8343. bool expressionStmt = false;
  8344. bool isAsyncMethod = false;
  8345. tokens tok;
  8346. #if EXCEPTION_RECOVERY
  8347. ParseNodeTryCatch * pParentTryCatch = nullptr;
  8348. ParseNodeBlock * pTryBlock = nullptr;
  8349. ParseNodeTry * pTry = nullptr;
  8350. ParseNodeBlock * pParentTryCatchBlock = nullptr;
  8351. StmtNest stmtTryCatchBlock;
  8352. StmtNest stmtTryCatch;
  8353. StmtNest stmtTry;
  8354. StmtNest stmtTryBlock;
  8355. #endif
  8356. if (buildAST)
  8357. {
  8358. #if EXCEPTION_RECOVERY
  8359. if (Js::Configuration::Global.flags.SwallowExceptions)
  8360. {
  8361. // If we're swallowing exceptions, surround this statement with a try/catch block:
  8362. //
  8363. // Before: x.y = 3;
  8364. // After: try { x.y = 3; } catch(__ehobj) { }
  8365. //
  8366. // This is done to force the runtime to recover from exceptions at the most granular
  8367. // possible point. Recovering from EH dramatically improves coverage of testing via
  8368. // fault injection.
  8369. // create and push the try-catch node
  8370. pParentTryCatchBlock = CreateBlockNode();
  8371. PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr);
  8372. pParentTryCatch = CreateNodeForOpT<knopTryCatch>();
  8373. PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr);
  8374. // create and push a try node
  8375. pTry = CreateNodeForOpT<knopTry>();
  8376. PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr);
  8377. pTryBlock = CreateBlockNode();
  8378. PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr);
  8379. // these nodes will be closed after the statement is parsed.
  8380. }
  8381. #endif // EXCEPTION_RECOVERY
  8382. }
  8383. EnsureStackAvailable();
  8384. LRestart:
  8385. tok = m_token.tk;
  8386. switch (tok)
  8387. {
  8388. case tkEOF:
  8389. if (buildAST)
  8390. {
  8391. pnode = nullptr;
  8392. }
  8393. break;
  8394. case tkFUNCTION:
  8395. {
  8396. LFunctionStatement:
  8397. if (m_grfscr & fscrDeferredFncExpression)
  8398. {
  8399. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  8400. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  8401. // first time we see it.
  8402. m_grfscr &= ~fscrDeferredFncExpression;
  8403. pnode = ParseFncDeclNoCheckScope<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs);
  8404. }
  8405. else
  8406. {
  8407. pnode = ParseFncDeclCheckScope<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs));
  8408. }
  8409. if (isAsyncMethod)
  8410. {
  8411. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  8412. pnode->ichMin = ichMin;
  8413. }
  8414. break;
  8415. }
  8416. case tkCLASS:
  8417. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  8418. {
  8419. pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);
  8420. }
  8421. else
  8422. {
  8423. goto LDefaultToken;
  8424. }
  8425. break;
  8426. case tkID:
  8427. if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.let)
  8428. {
  8429. // We see "let" at the start of a statement. This could either be a declaration or an identifier
  8430. // reference. The next token determines which.
  8431. RestorePoint parsedLet;
  8432. this->GetScanner()->Capture(&parsedLet);
  8433. ichMin = this->GetScanner()->IchMinTok();
  8434. this->GetScanner()->Scan();
  8435. if (this->NextTokenConfirmsLetDecl())
  8436. {
  8437. pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);
  8438. goto LNeedTerminator;
  8439. }
  8440. this->GetScanner()->SeekTo(parsedLet);
  8441. }
  8442. else if (m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8443. {
  8444. RestorePoint parsedAsync;
  8445. this->GetScanner()->Capture(&parsedAsync);
  8446. ichMin = this->GetScanner()->IchMinTok();
  8447. iecpMin = this->GetScanner()->IecpMinTok();
  8448. this->GetScanner()->Scan();
  8449. if (m_token.tk == tkFUNCTION && !this->GetScanner()->FHadNewLine())
  8450. {
  8451. isAsyncMethod = true;
  8452. goto LFunctionStatement;
  8453. }
  8454. this->GetScanner()->SeekTo(parsedAsync);
  8455. }
  8456. goto LDefaultToken;
  8457. case tkCONST:
  8458. case tkLET:
  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. goto LRestart;
  9248. }
  9249. // No label, rewind back to the tkID and parse an expression
  9250. this->GetScanner()->SeekTo(idStart);
  9251. }
  9252. // Must be an expression statement.
  9253. pnode = ParseExpr<buildAST>();
  9254. if (m_hasDeferredShorthandInitError)
  9255. {
  9256. Error(ERRnoColon);
  9257. }
  9258. if (buildAST)
  9259. {
  9260. expressionStmt = true;
  9261. AnalysisAssert(pnode);
  9262. pnode->isUsed = false;
  9263. }
  9264. }
  9265. LNeedTerminator:
  9266. // Need a semicolon, new-line, } or end-of-file.
  9267. // We digest a semicolon if it's there.
  9268. switch (m_token.tk)
  9269. {
  9270. case tkSColon:
  9271. this->GetScanner()->Scan();
  9272. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9273. break;
  9274. case tkEOF:
  9275. case tkRCurly:
  9276. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9277. break;
  9278. default:
  9279. if (!this->GetScanner()->FHadNewLine())
  9280. {
  9281. Error(ERRnoSemic);
  9282. }
  9283. else
  9284. {
  9285. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9286. }
  9287. break;
  9288. }
  9289. break;
  9290. }
  9291. if (m_hasDeferredShorthandInitError)
  9292. {
  9293. Error(ERRnoColon);
  9294. }
  9295. if (buildAST)
  9296. {
  9297. // All non expression statements excluded from the "this.x" optimization
  9298. // Another check while parsing expressions
  9299. if (!expressionStmt)
  9300. {
  9301. if (m_currentNodeFunc)
  9302. {
  9303. m_currentNodeFunc->SetHasNonThisStmt();
  9304. }
  9305. else if (m_currentNodeProg)
  9306. {
  9307. m_currentNodeProg->SetHasNonThisStmt();
  9308. }
  9309. }
  9310. #if EXCEPTION_RECOVERY
  9311. // close the try/catch block
  9312. if (Js::Configuration::Global.flags.SwallowExceptions)
  9313. {
  9314. // pop the try block and fill in the body
  9315. PopStmt(&stmtTryBlock);
  9316. pTryBlock->pnodeStmt = pnode;
  9317. PopStmt(&stmtTry);
  9318. if (pnode != nullptr)
  9319. {
  9320. pTry->ichLim = pnode->ichLim;
  9321. }
  9322. pTry->pnodeBody = pTryBlock;
  9323. // create a catch block with an empty body
  9324. StmtNest stmtCatch;
  9325. ParseNodeCatch * pCatch;
  9326. pCatch = CreateNodeForOpT<knopCatch>();
  9327. PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr);
  9328. pCatch->pnodeBody = nullptr;
  9329. if (pnode != nullptr)
  9330. {
  9331. pCatch->ichLim = pnode->ichLim;
  9332. }
  9333. pCatch->grfnop = 0;
  9334. pCatch->pnodeNext = nullptr;
  9335. // create a fake name for the catch var.
  9336. const WCHAR *uniqueNameStr = _u("__ehobj");
  9337. IdentPtr uniqueName = this->GetHashTbl()->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));
  9338. pCatch->SetParam(CreateNameNode(uniqueName));
  9339. // Add this catch to the current list. We don't bother adjusting the catch and function expression
  9340. // lists here because the catch is just an empty statement.
  9341. if (m_ppnodeExprScope)
  9342. {
  9343. Assert(*m_ppnodeExprScope == nullptr);
  9344. *m_ppnodeExprScope = pCatch;
  9345. m_ppnodeExprScope = &pCatch->pnodeNext;
  9346. }
  9347. else
  9348. {
  9349. Assert(m_ppnodeScope);
  9350. Assert(*m_ppnodeScope == nullptr);
  9351. *m_ppnodeScope = pCatch;
  9352. m_ppnodeScope = &pCatch->pnodeNext;
  9353. }
  9354. pCatch->pnodeScopes = nullptr;
  9355. PopStmt(&stmtCatch);
  9356. // fill in and pop the try-catch
  9357. pParentTryCatch->pnodeTry = pTry;
  9358. pParentTryCatch->pnodeCatch = pCatch;
  9359. PopStmt(&stmtTryCatch);
  9360. PopStmt(&stmtTryCatchBlock);
  9361. // replace the node that's being returned
  9362. pParentTryCatchBlock->pnodeStmt = pParentTryCatch;
  9363. pnode = pParentTryCatchBlock;
  9364. }
  9365. #endif // EXCEPTION_RECOVERY
  9366. }
  9367. return pnode;
  9368. }
  9369. BOOL
  9370. Parser::TokIsForInOrForOf()
  9371. {
  9372. return m_token.tk == tkIN ||
  9373. (m_token.tk == tkID &&
  9374. m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.of);
  9375. }
  9376. /***************************************************************************
  9377. Parse a sequence of statements.
  9378. ***************************************************************************/
  9379. template<bool buildAST>
  9380. void Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)
  9381. {
  9382. BOOL doneDirectives = !isSourceElementList; // directives may only exist in a SourceElementList, not a StatementList
  9383. BOOL seenDirectiveContainingOctal = false; // Have we seen an octal directive before a use strict directive?
  9384. BOOL old_UseStrictMode = m_fUseStrictMode;
  9385. ParseNodePtr pnodeStmt;
  9386. ParseNodePtr *lastNodeRef = nullptr;
  9387. if (buildAST)
  9388. {
  9389. Assert(ppnodeList);
  9390. *ppnodeList = nullptr;
  9391. }
  9392. if (CONFIG_FLAG(ForceStrictMode))
  9393. {
  9394. m_fUseStrictMode = TRUE;
  9395. }
  9396. for (;;)
  9397. {
  9398. switch (m_token.tk)
  9399. {
  9400. case tkCASE:
  9401. case tkDEFAULT:
  9402. case tkRCurly:
  9403. case tkEOF:
  9404. if (buildAST && nullptr != pppnodeLast)
  9405. {
  9406. *pppnodeLast = lastNodeRef;
  9407. }
  9408. if (!buildAST)
  9409. {
  9410. m_fUseStrictMode = old_UseStrictMode;
  9411. }
  9412. return;
  9413. }
  9414. if (doneDirectives == FALSE)
  9415. {
  9416. bool isOctalInString = false;
  9417. bool isUseStrictDirective = false;
  9418. bool isUseAsmDirective = false;
  9419. if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))
  9420. {
  9421. // Ignore "use asm" statement when not building the AST
  9422. isUseAsmDirective &= buildAST;
  9423. if (isUseStrictDirective)
  9424. {
  9425. // Functions with non-simple parameter list cannot be made strict mode
  9426. if (GetCurrentFunctionNode()->HasNonSimpleParameterList())
  9427. {
  9428. Error(ERRNonSimpleParamListInStrictMode);
  9429. }
  9430. if (seenDirectiveContainingOctal)
  9431. {
  9432. // Directives seen before a "use strict" cannot contain an octal.
  9433. Error(ERRES5NoOctal);
  9434. }
  9435. if (!buildAST)
  9436. {
  9437. // Turning on strict mode in deferred code.
  9438. m_fUseStrictMode = TRUE;
  9439. if (!m_inDeferredNestedFunc)
  9440. {
  9441. // Top-level deferred function, so there's a parse node
  9442. Assert(m_currentNodeFunc != nullptr);
  9443. m_currentNodeFunc->SetStrictMode();
  9444. }
  9445. else if (strictModeOn)
  9446. {
  9447. // This turns on strict mode in a deferred function, we need to go back
  9448. // and re-check duplicated formals.
  9449. *strictModeOn = true;
  9450. }
  9451. }
  9452. else
  9453. {
  9454. if (smEnvironment == SM_OnGlobalCode)
  9455. {
  9456. // Turning on strict mode at the top level
  9457. m_fUseStrictMode = TRUE;
  9458. }
  9459. else
  9460. {
  9461. // i.e. smEnvironment == SM_OnFunctionCode
  9462. Assert(m_currentNodeFunc != nullptr);
  9463. m_currentNodeFunc->SetStrictMode();
  9464. }
  9465. }
  9466. }
  9467. else if (isUseAsmDirective)
  9468. {
  9469. if (smEnvironment != SM_OnGlobalCode) //Top level use asm doesn't mean anything.
  9470. {
  9471. // i.e. smEnvironment == SM_OnFunctionCode
  9472. Assert(m_currentNodeFunc != nullptr);
  9473. m_currentNodeFunc->SetAsmjsMode();
  9474. m_currentNodeFunc->SetCanBeDeferred(false);
  9475. m_InAsmMode = true;
  9476. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, AsmJSFunction, m_scriptContext);
  9477. }
  9478. }
  9479. else if (isOctalInString)
  9480. {
  9481. seenDirectiveContainingOctal = TRUE;
  9482. }
  9483. }
  9484. else
  9485. {
  9486. // The first time we see anything other than a directive we can have no more directives.
  9487. doneDirectives = TRUE;
  9488. }
  9489. }
  9490. if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))
  9491. {
  9492. if (buildAST)
  9493. {
  9494. AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);
  9495. }
  9496. }
  9497. }
  9498. }
  9499. template <class Fn>
  9500. void Parser::FinishFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)
  9501. {
  9502. Scope * scope;
  9503. Scope * origCurrentScope = this->m_currentScope;
  9504. ParseNodePtr pnodeScope;
  9505. ParseNodeBlock * pnodeBlock;
  9506. for (pnodeScope = pnodeScopeList; pnodeScope;)
  9507. {
  9508. switch (pnodeScope->nop)
  9509. {
  9510. case knopBlock:
  9511. {
  9512. ParseNodeBlock * pnodeBlockScope = pnodeScope->AsParseNodeBlock();
  9513. m_nextBlockId = pnodeBlockScope->blockId + 1;
  9514. PushBlockInfo(pnodeBlockScope);
  9515. scope = pnodeBlockScope->scope;
  9516. if (scope && scope != origCurrentScope)
  9517. {
  9518. PushScope(scope);
  9519. }
  9520. FinishFunctionsInScope(pnodeBlockScope->pnodeScopes, fn);
  9521. if (scope && scope != origCurrentScope)
  9522. {
  9523. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9524. PopScope(scope);
  9525. }
  9526. PopBlockInfo();
  9527. pnodeScope = pnodeBlockScope->pnodeNext;
  9528. break;
  9529. }
  9530. case knopFncDecl:
  9531. fn(pnodeScope->AsParseNodeFnc());
  9532. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  9533. break;
  9534. case knopCatch:
  9535. scope = pnodeScope->AsParseNodeCatch()->scope;
  9536. if (scope)
  9537. {
  9538. PushScope(scope);
  9539. }
  9540. pnodeBlock = CreateBlockNode(PnodeBlockType::Regular);
  9541. pnodeBlock->scope = scope;
  9542. PushBlockInfo(pnodeBlock);
  9543. FinishFunctionsInScope(pnodeScope->AsParseNodeCatch()->pnodeScopes, fn);
  9544. if (scope)
  9545. {
  9546. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9547. PopScope(scope);
  9548. }
  9549. PopBlockInfo();
  9550. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  9551. break;
  9552. case knopWith:
  9553. PushBlockInfo(CreateBlockNode());
  9554. PushDynamicBlock();
  9555. FinishFunctionsInScope(pnodeScope->AsParseNodeWith()->pnodeScopes, fn);
  9556. PopBlockInfo();
  9557. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  9558. break;
  9559. default:
  9560. AssertMsg(false, "Unexpected node with scope list");
  9561. return;
  9562. }
  9563. }
  9564. }
  9565. // Scripts above this size (minus string literals and comments) will have parsing of
  9566. // function bodies deferred.
  9567. ULONG Parser::GetDeferralThreshold(bool isProfileLoaded)
  9568. {
  9569. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9570. if (CONFIG_FLAG(ForceDeferParse) ||
  9571. PHASE_FORCE1(Js::DeferParsePhase) ||
  9572. Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  9573. {
  9574. return 0;
  9575. }
  9576. else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))
  9577. {
  9578. return Js::Configuration::Global.flags.DeferParse;
  9579. }
  9580. else
  9581. #endif
  9582. {
  9583. if (isProfileLoaded)
  9584. {
  9585. return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;
  9586. }
  9587. return DEFAULT_CONFIG_DeferParseThreshold;
  9588. }
  9589. }
  9590. void Parser::FinishDeferredFunction(ParseNodeBlock * pnodeScopeList)
  9591. {
  9592. uint saveNextBlockId = m_nextBlockId;
  9593. m_nextBlockId = pnodeScopeList->blockId + 1;
  9594. FinishFunctionsInScope(pnodeScopeList,
  9595. [this](ParseNodeFnc * pnodeFnc)
  9596. {
  9597. Assert(pnodeFnc->nop == knopFncDecl);
  9598. // Non-simple params (such as default) require a good amount of logic to put vars on appropriate scopes. ParseFncDecl handles it
  9599. // properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param
  9600. // will remain deferred until they are called.
  9601. if (pnodeFnc->pnodeBody == nullptr && !pnodeFnc->HasNonSimpleParameterList())
  9602. {
  9603. // Go back and generate an AST for this function.
  9604. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->functionId, /*Undefer*/TRUE));
  9605. ParseNodeFnc * pnodeFncSave = this->m_currentNodeFunc;
  9606. this->m_currentNodeFunc = pnodeFnc;
  9607. ParseNodeBlock * pnodeFncExprBlock = nullptr;
  9608. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  9609. if (pnodeName)
  9610. {
  9611. Assert(pnodeName->nop == knopVarDecl);
  9612. ParseNodeVar * pnodeVarName = pnodeName->AsParseNodeVar();
  9613. Assert(pnodeVarName->pnodeNext == nullptr);
  9614. if (!pnodeFnc->IsDeclaration())
  9615. {
  9616. // Set up the named function expression symbol so references inside the function can be bound.
  9617. pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);
  9618. PidRefStack *ref = this->PushPidRef(pnodeVarName->pid);
  9619. pnodeVarName->symRef = ref->GetSymRef();
  9620. ref->SetSym(pnodeVarName->sym);
  9621. Scope *fncExprScope = pnodeFncExprBlock->scope;
  9622. fncExprScope->AddNewSymbol(pnodeVarName->sym);
  9623. pnodeFnc->scope = fncExprScope;
  9624. }
  9625. }
  9626. ParseNodeBlock * pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);
  9627. pnodeFnc->pnodeScopes = pnodeBlock;
  9628. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  9629. pnodeBlock->pnodeStmt = pnodeFnc;
  9630. ParseNodePtr * varNodesList = &pnodeFnc->pnodeVars;
  9631. ParseNodeVar * argNode = nullptr;
  9632. if (!pnodeFnc->IsModule() && !pnodeFnc->IsLambda() && !(pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam))
  9633. {
  9634. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  9635. m_ppnodeVar = &pnodeFnc->pnodeVars;
  9636. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  9637. varNodesList = m_ppnodeVar;
  9638. m_ppnodeVar = ppnodeVarSave;
  9639. }
  9640. // Add the args to the scope, since we won't re-parse those.
  9641. Scope *scope = pnodeBlock->scope;
  9642. uint blockId = GetCurrentBlock()->blockId;
  9643. uint funcId = GetCurrentFunctionNode()->functionId;
  9644. auto addArgsToScope = [&](ParseNodePtr pnodeArg) {
  9645. if (pnodeArg->IsVarLetOrConst())
  9646. {
  9647. ParseNodeVar * pnodeVarArg = pnodeArg->AsParseNodeVar();
  9648. PidRefStack *ref = this->FindOrAddPidRef(pnodeVarArg->pid, blockId, funcId);
  9649. pnodeVarArg->symRef = ref->GetSymRef();
  9650. if (ref->GetSym() != nullptr)
  9651. {
  9652. // Duplicate parameter in a configuration that allows them.
  9653. // The symbol is already in the scope, just point it to the right declaration.
  9654. Assert(ref->GetSym() == pnodeVarArg->sym);
  9655. ref->GetSym()->SetDecl(pnodeVarArg);
  9656. }
  9657. else
  9658. {
  9659. ref->SetSym(pnodeArg->AsParseNodeVar()->sym);
  9660. scope->AddNewSymbol(pnodeVarArg->sym);
  9661. }
  9662. }
  9663. };
  9664. MapFormals(pnodeFnc, addArgsToScope);
  9665. MapFormalsFromPattern(pnodeFnc, addArgsToScope);
  9666. ParseNodeBlock * pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  9667. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  9668. // Set the parameter block's child to the function body block.
  9669. *m_ppnodeScope = pnodeInnerBlock;
  9670. ParseNodePtr *ppnodeScopeSave = nullptr;
  9671. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9672. ppnodeScopeSave = m_ppnodeScope;
  9673. // This synthetic block scope will contain all the nested scopes.
  9674. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  9675. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  9676. // Keep nested function declarations and expressions in the same list at function scope.
  9677. // (Indicate this by nulling out the current function expressions list.)
  9678. ppnodeExprScopeSave = m_ppnodeExprScope;
  9679. m_ppnodeExprScope = nullptr;
  9680. // Shouldn't be any temps in the arg list.
  9681. Assert(*m_ppnodeVar == nullptr);
  9682. // Start the var list.
  9683. m_ppnodeVar = varNodesList;
  9684. if (scope != nullptr)
  9685. {
  9686. Assert(pnodeFnc->IsBodyAndParamScopeMerged());
  9687. blockId = GetCurrentBlock()->blockId;
  9688. funcId = GetCurrentFunctionNode()->functionId;
  9689. scope->ForEachSymbol([this, blockId, funcId](Symbol* paramSym)
  9690. {
  9691. PidRefStack* ref = this->FindOrAddPidRef(paramSym->GetPid(), blockId, funcId);
  9692. ref->SetSym(paramSym);
  9693. });
  9694. }
  9695. Assert(m_currentNodeNonLambdaFunc == nullptr);
  9696. m_currentNodeNonLambdaFunc = pnodeFnc;
  9697. this->FinishFncNode(pnodeFnc);
  9698. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  9699. m_currentNodeNonLambdaFunc = nullptr;
  9700. m_ppnodeExprScope = ppnodeExprScopeSave;
  9701. Assert(m_ppnodeScope);
  9702. Assert(nullptr == *m_ppnodeScope);
  9703. m_ppnodeScope = ppnodeScopeSave;
  9704. this->FinishParseBlock(pnodeInnerBlock);
  9705. if (!pnodeFnc->IsModule() && (m_token.tk == tkLCurly || !pnodeFnc->IsLambda()))
  9706. {
  9707. UpdateArgumentsNode(pnodeFnc, argNode);
  9708. }
  9709. CreateSpecialSymbolDeclarations(pnodeFnc);
  9710. this->FinishParseBlock(pnodeBlock);
  9711. if (pnodeFncExprBlock)
  9712. {
  9713. this->FinishParseBlock(pnodeFncExprBlock);
  9714. }
  9715. this->m_currentNodeFunc = pnodeFncSave;
  9716. }
  9717. });
  9718. m_nextBlockId = saveNextBlockId;
  9719. }
  9720. void Parser::InitPids()
  9721. {
  9722. wellKnownPropertyPids.arguments = this->GetHashTbl()->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);
  9723. wellKnownPropertyPids.async = this->GetHashTbl()->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);
  9724. wellKnownPropertyPids.eval = this->GetHashTbl()->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);
  9725. wellKnownPropertyPids.get = this->GetHashTbl()->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);
  9726. wellKnownPropertyPids.set = this->GetHashTbl()->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);
  9727. wellKnownPropertyPids.let = this->GetHashTbl()->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);
  9728. wellKnownPropertyPids.constructor = this->GetHashTbl()->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);
  9729. wellKnownPropertyPids.prototype = this->GetHashTbl()->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);
  9730. wellKnownPropertyPids.__proto__ = this->GetHashTbl()->PidHashNameLen(_u("__proto__"), sizeof("__proto__") - 1);
  9731. wellKnownPropertyPids.of = this->GetHashTbl()->PidHashNameLen(_u("of"), sizeof("of") - 1);
  9732. wellKnownPropertyPids.target = this->GetHashTbl()->PidHashNameLen(_u("target"), sizeof("target") - 1);
  9733. wellKnownPropertyPids.as = this->GetHashTbl()->PidHashNameLen(_u("as"), sizeof("as") - 1);
  9734. wellKnownPropertyPids.from = this->GetHashTbl()->PidHashNameLen(_u("from"), sizeof("from") - 1);
  9735. wellKnownPropertyPids._default = this->GetHashTbl()->PidHashNameLen(_u("default"), sizeof("default") - 1);
  9736. wellKnownPropertyPids._starDefaultStar = this->GetHashTbl()->PidHashNameLen(_u("*default*"), sizeof("*default*") - 1);
  9737. wellKnownPropertyPids._star = this->GetHashTbl()->PidHashNameLen(_u("*"), sizeof("*") - 1);
  9738. wellKnownPropertyPids._this = this->GetHashTbl()->PidHashNameLen(_u("*this*"), sizeof("*this*") - 1);
  9739. wellKnownPropertyPids._newTarget = this->GetHashTbl()->PidHashNameLen(_u("*new.target*"), sizeof("*new.target*") - 1);
  9740. wellKnownPropertyPids._super = this->GetHashTbl()->PidHashNameLen(_u("*super*"), sizeof("*super*") - 1);
  9741. wellKnownPropertyPids._superConstructor = this->GetHashTbl()->PidHashNameLen(_u("*superconstructor*"), sizeof("*superconstructor*") - 1);
  9742. }
  9743. void Parser::RestoreScopeInfo(Js::ScopeInfo * scopeInfo)
  9744. {
  9745. if (!scopeInfo)
  9746. {
  9747. return;
  9748. }
  9749. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9750. RestoreScopeInfo(scopeInfo->GetParentScopeInfo()); // Recursively restore outer func scope info
  9751. scopeInfo->SetScopeId(m_nextBlockId);
  9752. ParseNodeBlock * pnodeScope = nullptr;
  9753. ScopeType scopeType = scopeInfo->GetScopeType();
  9754. PnodeBlockType blockType;
  9755. switch (scopeType)
  9756. {
  9757. case ScopeType_With:
  9758. PushDynamicBlock();
  9759. // fall through
  9760. case ScopeType_Block:
  9761. case ScopeType_Catch:
  9762. case ScopeType_CatchParamPattern:
  9763. case ScopeType_GlobalEvalBlock:
  9764. blockType = PnodeBlockType::Regular;
  9765. break;
  9766. case ScopeType_FunctionBody:
  9767. case ScopeType_FuncExpr:
  9768. blockType = PnodeBlockType::Function;
  9769. break;
  9770. case ScopeType_Parameter:
  9771. blockType = PnodeBlockType::Parameter;
  9772. break;
  9773. default:
  9774. Assert(0);
  9775. return;
  9776. }
  9777. pnodeScope = StartParseBlockWithCapacity<true>(blockType, scopeType, scopeInfo->GetSymbolCount());
  9778. Scope *scope = pnodeScope->scope;
  9779. scope->SetScopeInfo(scopeInfo);
  9780. scopeInfo->ExtractScopeInfo(this, /*nullptr, nullptr,*/ scope);
  9781. }
  9782. void Parser::FinishScopeInfo(Js::ScopeInfo * scopeInfo)
  9783. {
  9784. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9785. for (; scopeInfo != nullptr; scopeInfo = scopeInfo->GetParentScopeInfo())
  9786. {
  9787. int scopeId = scopeInfo->GetScopeId();
  9788. scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)
  9789. {
  9790. this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);
  9791. });
  9792. PopScope(scopeInfo->GetScope());
  9793. PopStmt(&m_currentBlockInfo->pstmt);
  9794. PopBlockInfo();
  9795. }
  9796. }
  9797. /***************************************************************************
  9798. Parse the code.
  9799. ***************************************************************************/
  9800. 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)
  9801. {
  9802. ParseNodeProg * pnodeProg;
  9803. ParseNodePtr *lastNodeRef = nullptr;
  9804. m_nextBlockId = 0;
  9805. bool isDeferred = (grfscr & fscrDeferredFnc) != 0;
  9806. bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;
  9807. bool isGlobalCode = (grfscr & fscrGlobalCode) != 0;
  9808. if (this->m_scriptContext->IsScriptContextInDebugMode()
  9809. #ifdef ENABLE_PREJIT
  9810. || Js::Configuration::Global.flags.Prejit
  9811. #endif
  9812. || ((grfscr & fscrNoDeferParse) != 0)
  9813. )
  9814. {
  9815. // Don't do deferred parsing if debugger is attached or feature is disabled
  9816. // by command-line switch.
  9817. grfscr &= ~fscrWillDeferFncParse;
  9818. }
  9819. else if (!isGlobalCode &&
  9820. (
  9821. PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||
  9822. this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  9823. )
  9824. )
  9825. {
  9826. // Don't defer event handlers in debug/rundown mode, because we need to register the document,
  9827. // so we need to create a full FunctionBody for the script body.
  9828. grfscr &= ~fscrWillDeferFncParse;
  9829. }
  9830. m_grfscr = grfscr;
  9831. m_length = length;
  9832. m_originalLength = length;
  9833. m_nextFunctionId = nextFunctionId;
  9834. if (m_parseType != ParseType_Deferred)
  9835. {
  9836. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));
  9837. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);
  9838. }
  9839. // Give the scanner the source and get the first token
  9840. this->GetScanner()->SetText(pszSrc, offset, length, charOffset, isUtf8, grfscr, lineNumber);
  9841. this->GetScanner()->Scan();
  9842. // Make the main 'knopProg' node
  9843. int32 initSize = 0;
  9844. m_pCurrentAstSize = &initSize;
  9845. pnodeProg = CreateProgNode(isModuleSource, lineNumber);
  9846. if (!isDeferred || (isDeferred && isGlobalCode))
  9847. {
  9848. // In the deferred case, if the global function is deferred parse (which is in no-refresh case),
  9849. // we will re-use the same function body, so start with the correct functionId.
  9850. pnodeProg->functionId = (*m_nextFunctionId)++;
  9851. }
  9852. if (isModuleSource)
  9853. {
  9854. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  9855. pnodeProg->AsParseNodeModule()->localExportEntries = nullptr;
  9856. pnodeProg->AsParseNodeModule()->indirectExportEntries = nullptr;
  9857. pnodeProg->AsParseNodeModule()->starExportEntries = nullptr;
  9858. pnodeProg->AsParseNodeModule()->importEntries = nullptr;
  9859. pnodeProg->AsParseNodeModule()->requestedModules = nullptr;
  9860. }
  9861. m_pCurrentAstSize = &(pnodeProg->astSize);
  9862. // initialize parsing variables
  9863. m_currentNodeFunc = nullptr;
  9864. m_currentNodeDeferredFunc = nullptr;
  9865. m_currentNodeProg = pnodeProg;
  9866. m_cactIdentToNodeLookup = 1;
  9867. m_pnestedCount = &pnodeProg->nestedCount;
  9868. m_inDeferredNestedFunc = false;
  9869. m_ppnodeVar = &pnodeProg->pnodeVars;
  9870. SetCurrentStatement(nullptr);
  9871. AssertMsg(m_pstmtCur == nullptr, "Statement stack should be empty when we start parse global code");
  9872. // Create block for const's and let's
  9873. ParseNodeBlock * pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);
  9874. pnodeProg->scope = pnodeGlobalBlock->scope;
  9875. ParseNodeBlock * pnodeGlobalEvalBlock = nullptr;
  9876. // Don't track function expressions separately from declarations at global scope.
  9877. m_ppnodeExprScope = nullptr;
  9878. // This synthetic block scope will contain all the nested scopes.
  9879. pnodeProg->pnodeScopes = pnodeGlobalBlock;
  9880. m_ppnodeScope = &pnodeGlobalBlock->pnodeScopes;
  9881. if ((this->m_grfscr & fscrEvalCode) &&
  9882. !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))
  9883. {
  9884. pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);
  9885. pnodeProg->pnodeScopes = pnodeGlobalEvalBlock;
  9886. m_ppnodeScope = &pnodeGlobalEvalBlock->pnodeScopes;
  9887. }
  9888. Js::ScopeInfo *scopeInfo = nullptr;
  9889. if (m_parseType == ParseType_Deferred && m_functionBody)
  9890. {
  9891. // this->m_functionBody can be cleared during parsing, but we need access to the scope info later.
  9892. scopeInfo = m_functionBody->GetScopeInfo();
  9893. if (scopeInfo)
  9894. {
  9895. // Create an enclosing function context.
  9896. m_currentNodeFunc = CreateNodeForOpT<knopFncDecl>();
  9897. m_currentNodeFunc->functionId = m_functionBody->GetLocalFunctionId();
  9898. m_currentNodeFunc->nestedCount = m_functionBody->GetNestedCount();
  9899. m_currentNodeFunc->SetStrictMode(!!this->m_fUseStrictMode);
  9900. this->RestoreScopeInfo(scopeInfo);
  9901. m_currentNodeFunc->SetIsGenerator(scopeInfo->IsGeneratorFunctionBody());
  9902. m_currentNodeFunc->SetIsAsync(scopeInfo->IsAsyncFunctionBody());
  9903. }
  9904. }
  9905. // It's possible for the module global to be defer-parsed in debug scenarios.
  9906. if (isModuleSource && (!isDeferred || (isDeferred && isGlobalCode)))
  9907. {
  9908. ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();
  9909. pnodeProg->pnodeBody = nullptr;
  9910. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, moduleFunction);
  9911. }
  9912. else
  9913. {
  9914. if (isDeferred && !isGlobalCode)
  9915. {
  9916. // Defer parse for a single function should just parse that one function - there are no other statements.
  9917. ushort flags = fFncNoFlgs;
  9918. size_t iecpMin = 0;
  9919. charcount_t ichMin = 0;
  9920. bool isAsync = false;
  9921. bool isGenerator = false;
  9922. bool isMethod = false;
  9923. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  9924. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  9925. // first time we see it.
  9926. //
  9927. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  9928. // token of the source code of the function may not be a 'function' token though, so we still need to reset this flag
  9929. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  9930. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  9931. if (m_grfscr & fscrDeferredFncExpression)
  9932. {
  9933. m_grfscr &= ~fscrDeferredFncExpression;
  9934. }
  9935. else
  9936. {
  9937. flags |= fFncDeclaration;
  9938. }
  9939. if (m_grfscr & fscrDeferredFncIsMethod)
  9940. {
  9941. m_grfscr &= ~fscrDeferredFncIsMethod;
  9942. isMethod = true;
  9943. flags |= fFncNoName | fFncMethod;
  9944. }
  9945. // These are the cases which can confirm async function:
  9946. // async function() {} -> async function
  9947. // async () => {} -> async lambda with parens around the formal parameter
  9948. // async arg => {} -> async lambda with single identifier parameter
  9949. // async name() {} -> async method
  9950. // async [computed_name]() {} -> async method with a computed name
  9951. if (m_token.tk == tkID && m_token.GetIdentifier(this->GetHashTbl()) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  9952. {
  9953. ichMin = this->GetScanner()->IchMinTok();
  9954. iecpMin = this->GetScanner()->IecpMinTok();
  9955. // Keep state so we can rewind if it turns out that this isn't an async function:
  9956. // async() {} -> method named async
  9957. // async => {} -> lambda with single parameter named async
  9958. RestorePoint termStart;
  9959. this->GetScanner()->Capture(&termStart);
  9960. this->GetScanner()->Scan();
  9961. if (m_token.tk == tkDArrow || (m_token.tk == tkLParen && isMethod) || this->GetScanner()->FHadNewLine())
  9962. {
  9963. this->GetScanner()->SeekTo(termStart);
  9964. }
  9965. else
  9966. {
  9967. flags |= fFncAsync;
  9968. isAsync = true;
  9969. }
  9970. }
  9971. if (m_token.tk == tkStar && m_scriptContext->GetConfig()->IsES6GeneratorsEnabled())
  9972. {
  9973. ichMin = this->GetScanner()->IchMinTok();
  9974. iecpMin = this->GetScanner()->IecpMinTok();
  9975. flags |= fFncGenerator;
  9976. isGenerator = true;
  9977. this->GetScanner()->Scan();
  9978. }
  9979. // Eat the computed name expression
  9980. if (m_token.tk == tkLBrack && isMethod)
  9981. {
  9982. this->GetScanner()->Scan();
  9983. ParseExpr<false>();
  9984. }
  9985. if (!isMethod && (m_token.tk == tkID || m_token.tk == tkLParen))
  9986. {
  9987. // If first token of the function is tkID or tkLParen, this is a lambda.
  9988. flags |= fFncLambda;
  9989. }
  9990. ParseNode * pnodeFnc = ParseFncDeclCheckScope<true>(flags, /* resetParsingSuperRestrictionState*/ false);
  9991. pnodeProg->pnodeBody = nullptr;
  9992. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, pnodeFnc);
  9993. // Include the async keyword or star character in the function extents
  9994. if (isAsync || isGenerator)
  9995. {
  9996. pnodeFnc->AsParseNodeFnc()->cbMin = iecpMin;
  9997. pnodeFnc->ichMin = ichMin;
  9998. }
  9999. }
  10000. else
  10001. {
  10002. // Process a sequence of statements/declarations
  10003. ParseStmtList<true>(
  10004. &pnodeProg->pnodeBody,
  10005. &lastNodeRef,
  10006. SM_OnGlobalCode,
  10007. !(m_grfscr & fscrDeferredFncExpression) /* isSourceElementList */);
  10008. }
  10009. }
  10010. if (m_parseType == ParseType_Deferred)
  10011. {
  10012. if (scopeInfo)
  10013. {
  10014. this->FinishScopeInfo(scopeInfo);
  10015. }
  10016. }
  10017. pnodeProg->m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;
  10018. if (IsStrictMode())
  10019. {
  10020. pnodeProg->SetStrictMode();
  10021. }
  10022. #if DEBUG
  10023. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->pnodeBody))
  10024. {
  10025. Error(ERRsyntax);
  10026. }
  10027. #endif
  10028. if (tkEOF != m_token.tk)
  10029. Error(ERRsyntax);
  10030. // Append an EndCode node.
  10031. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef,
  10032. CreateNodeForOpT<knopEndCode>());
  10033. Assert(lastNodeRef);
  10034. Assert(*lastNodeRef);
  10035. Assert((*lastNodeRef)->nop == knopEndCode);
  10036. (*lastNodeRef)->ichMin = 0;
  10037. (*lastNodeRef)->ichLim = 0;
  10038. // Get the extent of the code.
  10039. pnodeProg->ichLim = this->GetScanner()->IchLimTok();
  10040. pnodeProg->cbLim = this->GetScanner()->IecpLimTok();
  10041. // Terminate the local list
  10042. *m_ppnodeVar = nullptr;
  10043. Assert(nullptr == *m_ppnodeScope);
  10044. Assert(nullptr == pnodeProg->pnodeNext);
  10045. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10046. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10047. {
  10048. m_stoppedDeferredParse = true;
  10049. }
  10050. #endif
  10051. if (m_stoppedDeferredParse)
  10052. {
  10053. #if ENABLE_BACKGROUND_PARSING
  10054. if (this->m_hasParallelJob)
  10055. {
  10056. BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());
  10057. Assert(bgp);
  10058. this->WaitForBackgroundJobs(bgp, pse);
  10059. }
  10060. #endif
  10061. // Do any remaining bindings of globals referenced in non-deferred functions.
  10062. if (pnodeGlobalEvalBlock)
  10063. {
  10064. FinishParseBlock(pnodeGlobalEvalBlock);
  10065. }
  10066. FinishParseBlock(pnodeGlobalBlock);
  10067. // Clear out references to undeclared identifiers.
  10068. this->GetHashTbl()->VisitPids([&](IdentPtr pid) { pid->SetTopRef(nullptr); });
  10069. // Restore global scope and blockinfo stacks preparatory to reparsing deferred functions.
  10070. PushScope(pnodeGlobalBlock->scope);
  10071. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeGlobalBlock);
  10072. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalBlock, knopBlock, nullptr);
  10073. if (pnodeGlobalEvalBlock)
  10074. {
  10075. PushScope(pnodeGlobalEvalBlock->scope);
  10076. newBlockInfo = PushBlockInfo(pnodeGlobalEvalBlock);
  10077. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalEvalBlock, knopBlock, nullptr);
  10078. }
  10079. // Finally, see if there are any function bodies we now want to generate because we
  10080. // decided to stop deferring.
  10081. FinishDeferredFunction(pnodeProg->pnodeScopes);
  10082. }
  10083. if (pnodeGlobalEvalBlock)
  10084. {
  10085. FinishParseBlock(pnodeGlobalEvalBlock);
  10086. }
  10087. // Append block as body of pnodeProg
  10088. FinishParseBlock(pnodeGlobalBlock);
  10089. m_scriptContext->AddSourceSize(m_length);
  10090. if (m_parseType != ParseType_Deferred)
  10091. {
  10092. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));
  10093. }
  10094. return pnodeProg;
  10095. }
  10096. bool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)
  10097. {
  10098. // A directive is a string constant followed by a statement terminating token
  10099. if (m_token.tk != tkStrCon)
  10100. return false;
  10101. // Careful, need to check for octal before calling this->GetScanner()->Scan()
  10102. // because Scan() clears the "had octal" flag on the scanner and
  10103. // this->GetScanner()->Restore() does not restore this flag.
  10104. if (pIsOctalInString != nullptr)
  10105. {
  10106. *pIsOctalInString = this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber();
  10107. }
  10108. Ident* pidDirective = m_token.GetStr();
  10109. RestorePoint start;
  10110. this->GetScanner()->Capture(&start);
  10111. this->GetScanner()->Scan();
  10112. bool isDirective = true;
  10113. switch (m_token.tk)
  10114. {
  10115. case tkSColon:
  10116. case tkEOF:
  10117. case tkLCurly:
  10118. case tkRCurly:
  10119. break;
  10120. default:
  10121. if (!this->GetScanner()->FHadNewLine())
  10122. {
  10123. isDirective = false;
  10124. }
  10125. break;
  10126. }
  10127. if (isDirective)
  10128. {
  10129. if (pIsUseStrict != nullptr)
  10130. {
  10131. *pIsUseStrict = CheckStrictModeStrPid(pidDirective);
  10132. }
  10133. if (pIsUseAsm != nullptr)
  10134. {
  10135. *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);
  10136. }
  10137. }
  10138. this->GetScanner()->SeekTo(start);
  10139. return isDirective;
  10140. }
  10141. bool Parser::CheckStrictModeStrPid(IdentPtr pid)
  10142. {
  10143. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10144. if (Js::Configuration::Global.flags.NoStrictMode)
  10145. return false;
  10146. #endif
  10147. return pid != nullptr &&
  10148. pid->Cch() == 10 &&
  10149. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10150. wcsncmp(pid->Psz(), _u("use strict"), 10) == 0;
  10151. }
  10152. bool Parser::CheckAsmjsModeStrPid(IdentPtr pid)
  10153. {
  10154. #ifdef ASMJS_PLAT
  10155. if (!CONFIG_FLAG(AsmJs))
  10156. {
  10157. return false;
  10158. }
  10159. bool isAsmCandidate = (pid != nullptr &&
  10160. AutoSystemInfo::Data.SSE2Available() &&
  10161. pid->Cch() == 7 &&
  10162. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10163. wcsncmp(pid->Psz(), _u("use asm"), 10) == 0);
  10164. #ifdef ENABLE_SCRIPT_DEBUGGING
  10165. if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())
  10166. {
  10167. // We would like to report this to debugger - they may choose to disable debugging.
  10168. // TODO : localization of the string?
  10169. 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);
  10170. return false;
  10171. }
  10172. #endif
  10173. return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);
  10174. #else
  10175. return false;
  10176. #endif
  10177. }
  10178. HRESULT Parser::ParseUtf8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10179. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10180. {
  10181. m_functionBody = nullptr;
  10182. m_parseType = ParseType_Upfront;
  10183. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10184. }
  10185. HRESULT Parser::ParseCesu8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10186. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10187. {
  10188. m_functionBody = nullptr;
  10189. m_parseType = ParseType_Upfront;
  10190. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10191. }
  10192. #if ENABLE_BACKGROUND_PARSING
  10193. void Parser::PrepareForBackgroundParse()
  10194. {
  10195. this->GetScanner()->PrepareForBackgroundParse(m_scriptContext);
  10196. }
  10197. void Parser::AddBackgroundParseItem(BackgroundParseItem *const item)
  10198. {
  10199. if (currBackgroundParseItem == nullptr)
  10200. {
  10201. backgroundParseItems = item;
  10202. }
  10203. else
  10204. {
  10205. currBackgroundParseItem->SetNext(item);
  10206. }
  10207. currBackgroundParseItem = item;
  10208. }
  10209. void Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)
  10210. {
  10211. Assert(!IsBackgroundParser());
  10212. Assert(m_doingFastScan);
  10213. if (fastScannedRegExpNodes == nullptr)
  10214. {
  10215. fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);
  10216. }
  10217. fastScannedRegExpNodes->Append(pnode);
  10218. }
  10219. void Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)
  10220. {
  10221. Assert(IsBackgroundParser());
  10222. Assert(currBackgroundParseItem != nullptr);
  10223. currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);
  10224. }
  10225. HRESULT Parser::ParseFunctionInBackground(ParseNodeFnc * pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)
  10226. {
  10227. m_functionBody = nullptr;
  10228. m_parseType = ParseType_Upfront;
  10229. HRESULT hr = S_OK;
  10230. SmartFPUControl smartFpuControl;
  10231. uint nextFunctionId = pnodeFnc->functionId + 1;
  10232. this->RestoreContext(parseContext);
  10233. m_nextFunctionId = &nextFunctionId;
  10234. m_deferringAST = topLevelDeferred;
  10235. m_inDeferredNestedFunc = false;
  10236. m_scopeCountNoAst = 0;
  10237. SetCurrentStatement(nullptr);
  10238. pnodeFnc->pnodeVars = nullptr;
  10239. pnodeFnc->pnodeParams = nullptr;
  10240. pnodeFnc->pnodeBody = nullptr;
  10241. pnodeFnc->nestedCount = 0;
  10242. ParseNodeFnc * pnodeParentFnc = GetCurrentFunctionNode();
  10243. m_currentNodeFunc = pnodeFnc;
  10244. m_currentNodeDeferredFunc = nullptr;
  10245. m_ppnodeScope = nullptr;
  10246. m_ppnodeExprScope = nullptr;
  10247. m_pnestedCount = &pnodeFnc->nestedCount;
  10248. m_pCurrentAstSize = &pnodeFnc->astSize;
  10249. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10250. pnodeFnc->pnodeScopes = pnodeBlock;
  10251. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  10252. uint uDeferSave = m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse);
  10253. try
  10254. {
  10255. this->GetScanner()->Scan();
  10256. m_ppnodeVar = &pnodeFnc->pnodeParams;
  10257. this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);
  10258. if (m_token.tk == tkRParen)
  10259. {
  10260. this->GetScanner()->Scan();
  10261. }
  10262. ChkCurTok(tkLCurly, ERRnoLcurly);
  10263. m_ppnodeVar = &pnodeFnc->pnodeVars;
  10264. // Put the scanner into "no hashing" mode.
  10265. BYTE deferFlags = this->GetScanner()->SetDeferredParse(topLevelDeferred);
  10266. // Process a sequence of statements/declarations
  10267. if (topLevelDeferred)
  10268. {
  10269. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);
  10270. }
  10271. else
  10272. {
  10273. ParseNodePtr *lastNodeRef = nullptr;
  10274. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);
  10275. AddArgumentsNodeToVars(pnodeFnc);
  10276. // Append an EndCode node.
  10277. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  10278. }
  10279. // Restore the scanner's default hashing mode.
  10280. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  10281. #if DBG
  10282. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  10283. #endif
  10284. this->m_deferringAST = FALSE;
  10285. // Append block as body of pnodeProg
  10286. FinishParseBlock(pnodeBlock);
  10287. }
  10288. catch (ParseExceptionObject& e)
  10289. {
  10290. hr = e.GetError();
  10291. }
  10292. if (FAILED(hr))
  10293. {
  10294. hr = pse->ProcessError(this->GetScanner(), hr, nullptr);
  10295. }
  10296. if (IsStrictMode())
  10297. {
  10298. pnodeFnc->SetStrictMode();
  10299. }
  10300. if (topLevelDeferred)
  10301. {
  10302. pnodeFnc->pnodeVars = nullptr;
  10303. }
  10304. m_grfscr |= uDeferSave;
  10305. Assert(nullptr == *m_ppnodeScope);
  10306. return hr;
  10307. }
  10308. #endif
  10309. HRESULT Parser::ParseSourceWithOffset(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,
  10310. bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,
  10311. Js::ParseableFunctionInfo* functionInfo)
  10312. {
  10313. m_functionBody = functionInfo;
  10314. if (m_functionBody)
  10315. {
  10316. m_currDeferredStub = m_functionBody->GetDeferredStubs();
  10317. m_currDeferredStubCount = m_currDeferredStub != nullptr ? m_functionBody->GetNestedCount() : 0;
  10318. m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();
  10319. }
  10320. m_deferAsmJs = !m_InAsmMode;
  10321. m_parseType = ParseType_Deferred;
  10322. return ParseSourceInternal(parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);
  10323. }
  10324. bool Parser::IsStrictMode() const
  10325. {
  10326. return (m_fUseStrictMode ||
  10327. (m_currentNodeFunc != nullptr && m_currentNodeFunc->GetStrictMode()));
  10328. }
  10329. BOOL Parser::ExpectingExternalSource()
  10330. {
  10331. return m_fExpectExternalSource;
  10332. }
  10333. Symbol *ParseNodeFnc::GetFuncSymbol()
  10334. {
  10335. if (pnodeName)
  10336. {
  10337. Assert(pnodeName->nop == knopVarDecl);
  10338. return pnodeName->sym;
  10339. }
  10340. return nullptr;
  10341. }
  10342. void ParseNodeFnc::SetFuncSymbol(Symbol *sym)
  10343. {
  10344. Assert(pnodeName);
  10345. Assert(pnodeName->nop == knopVarDecl);
  10346. pnodeName->sym = sym;
  10347. }
  10348. ParseNodePtr ParseNodeFnc::GetParamScope() const
  10349. {
  10350. if (this->pnodeScopes == nullptr)
  10351. {
  10352. return nullptr;
  10353. }
  10354. Assert(this->pnodeScopes->nop == knopBlock &&
  10355. this->pnodeScopes->pnodeNext == nullptr);
  10356. return this->pnodeScopes->pnodeScopes;
  10357. }
  10358. ParseNodePtr ParseNodeFnc::GetBodyScope() const
  10359. {
  10360. if (this->pnodeBodyScope == nullptr)
  10361. {
  10362. return nullptr;
  10363. }
  10364. Assert(this->pnodeBodyScope->nop == knopBlock &&
  10365. this->pnodeBodyScope->pnodeNext == nullptr);
  10366. return this->pnodeBodyScope->pnodeScopes;
  10367. }
  10368. bool ParseNodeBlock::HasBlockScopedContent() const
  10369. {
  10370. // A block has its own content if a let, const, or function is declared there.
  10371. if (this->pnodeLexVars != nullptr || this->blockType == Parameter)
  10372. {
  10373. return true;
  10374. }
  10375. // The enclosing scopes can contain functions and other things, so walk the list
  10376. // looking specifically for functions.
  10377. for (ParseNodePtr pnode = this->pnodeScopes; pnode;)
  10378. {
  10379. switch (pnode->nop) {
  10380. case knopFncDecl:
  10381. return true;
  10382. case knopBlock:
  10383. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  10384. break;
  10385. case knopCatch:
  10386. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  10387. break;
  10388. case knopWith:
  10389. pnode = pnode->AsParseNodeWith()->pnodeNext;
  10390. break;
  10391. default:
  10392. Assert(UNREACHED);
  10393. return true;
  10394. }
  10395. }
  10396. return false;
  10397. }
  10398. class ByteCodeGenerator;
  10399. // Copy AST; this works mostly on expressions for now
  10400. ParseNode* Parser::CopyPnode(ParseNode *pnode) {
  10401. if (pnode == NULL)
  10402. return NULL;
  10403. switch (pnode->nop) {
  10404. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  10405. case knopName: {
  10406. ParseNodeName * nameNode = CreateNameNode(pnode->AsParseNodeName()->pid);
  10407. nameNode->ichMin = pnode->ichMin;
  10408. nameNode->ichLim = pnode->ichLim;
  10409. nameNode->sym = pnode->AsParseNodeName()->sym;
  10410. return nameNode;
  10411. }
  10412. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  10413. case knopInt:
  10414. return pnode;
  10415. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  10416. case knopFlt:
  10417. return pnode;
  10418. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  10419. case knopStr:
  10420. return pnode;
  10421. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  10422. case knopRegExp:
  10423. return pnode;
  10424. break;
  10425. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  10426. case knopNull:
  10427. return pnode;
  10428. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  10429. case knopFalse:
  10430. {
  10431. ParseNode* ret = CreateNodeForOpT<knopFalse>(pnode->ichMin, pnode->ichLim);
  10432. ret->location = pnode->location;
  10433. return ret;
  10434. }
  10435. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  10436. case knopTrue:
  10437. {
  10438. ParseNode* ret = CreateNodeForOpT<knopTrue>(pnode->ichMin, pnode->ichLim);
  10439. ret->location = pnode->location;
  10440. return ret;
  10441. }
  10442. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  10443. case knopEmpty:
  10444. return CreateNodeForOpT<knopEmpty>(pnode->ichMin, pnode->ichLim);
  10445. // Unary operators.
  10446. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  10447. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  10448. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  10449. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  10450. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  10451. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  10452. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  10453. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  10454. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  10455. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  10456. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  10457. case knopNot:
  10458. case knopNeg:
  10459. case knopPos:
  10460. case knopLogNot:
  10461. case knopEllipsis:
  10462. case knopIncPost:
  10463. case knopDecPost:
  10464. case knopIncPre:
  10465. case knopDecPre:
  10466. case knopTypeof:
  10467. case knopVoid:
  10468. case knopDelete:
  10469. return CreateUniNode(pnode->nop, CopyPnode(pnode->AsParseNodeUni()->pnode1), pnode->ichMin, pnode->ichLim);
  10470. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  10471. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  10472. case knopArray:
  10473. case knopObject:
  10474. // TODO: need to copy arr
  10475. Assert(false);
  10476. break;
  10477. // Binary operators
  10478. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  10479. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  10480. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  10481. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  10482. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  10483. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  10484. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  10485. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  10486. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  10487. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  10488. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  10489. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  10490. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  10491. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  10492. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  10493. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  10494. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  10495. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  10496. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  10497. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  10498. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10499. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10500. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  10501. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  10502. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  10503. case knopAdd:
  10504. case knopSub:
  10505. case knopMul:
  10506. case knopExpo:
  10507. case knopDiv:
  10508. case knopMod:
  10509. case knopOr:
  10510. case knopXor:
  10511. case knopAnd:
  10512. case knopEq:
  10513. case knopNe:
  10514. case knopLt:
  10515. case knopLe:
  10516. case knopGe:
  10517. case knopGt:
  10518. case knopEqv:
  10519. case knopIn:
  10520. case knopInstOf:
  10521. case knopNEqv:
  10522. case knopComma:
  10523. case knopLogOr:
  10524. case knopLogAnd:
  10525. case knopLsh:
  10526. case knopRsh:
  10527. case knopRs2:
  10528. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10529. case knopAsg:
  10530. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  10531. case knopDot:
  10532. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  10533. case knopAsgAdd:
  10534. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  10535. case knopAsgSub:
  10536. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  10537. case knopAsgMul:
  10538. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  10539. case knopAsgExpo:
  10540. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  10541. case knopAsgDiv:
  10542. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  10543. case knopAsgMod:
  10544. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  10545. case knopAsgAnd:
  10546. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  10547. case knopAsgXor:
  10548. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  10549. case knopAsgOr:
  10550. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  10551. case knopAsgLsh:
  10552. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  10553. case knopAsgRsh:
  10554. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  10555. case knopAsgRs2:
  10556. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  10557. case knopMember:
  10558. case knopMemberShort:
  10559. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  10560. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  10561. case knopIndex:
  10562. case knopList:
  10563. return CreateBinNode(pnode->nop, CopyPnode(pnode->AsParseNodeBin()->pnode1),
  10564. CopyPnode(pnode->AsParseNodeBin()->pnode2), pnode->ichMin, pnode->ichLim);
  10565. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  10566. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  10567. case knopNew:
  10568. case knopCall:
  10569. return CreateCallNode(pnode->nop, CopyPnode(pnode->AsParseNodeCall()->pnodeTarget),
  10570. CopyPnode(pnode->AsParseNodeCall()->pnodeArgs), pnode->ichMin, pnode->ichLim);
  10571. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10572. case knopQmark:
  10573. return CreateTriNode(pnode->nop, CopyPnode(pnode->AsParseNodeTri()->pnode1),
  10574. CopyPnode(pnode->AsParseNodeTri()->pnode2), CopyPnode(pnode->AsParseNodeTri()->pnode3),
  10575. pnode->ichMin, pnode->ichLim);
  10576. // General nodes.
  10577. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10578. case knopVarDecl: {
  10579. ParseNodeVar* copyNode = Anew(&m_nodeAllocator, ParseNodeVar, knopVarDecl, pnode->ichMin, pnode->ichLim, nullptr);
  10580. copyNode->pnodeInit = CopyPnode(pnode->AsParseNodeVar()->pnodeInit);
  10581. copyNode->sym = pnode->AsParseNodeVar()->sym;
  10582. // TODO: mult-decl
  10583. Assert(pnode->AsParseNodeVar()->pnodeNext == NULL);
  10584. copyNode->pnodeNext = NULL;
  10585. return copyNode;
  10586. }
  10587. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10588. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  10589. case knopFncDecl:
  10590. case knopProg:
  10591. Assert(false);
  10592. break;
  10593. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  10594. case knopEndCode:
  10595. break;
  10596. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10597. case knopDebugger:
  10598. break;
  10599. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10600. case knopFor: {
  10601. ParseNode* copyNode = CreateNodeForOpT<knopFor>(pnode->ichMin, pnode->ichLim);
  10602. copyNode->AsParseNodeFor()->pnodeInverted = NULL;
  10603. copyNode->AsParseNodeFor()->pnodeInit = CopyPnode(pnode->AsParseNodeFor()->pnodeInit);
  10604. copyNode->AsParseNodeFor()->pnodeCond = CopyPnode(pnode->AsParseNodeFor()->pnodeCond);
  10605. copyNode->AsParseNodeFor()->pnodeIncr = CopyPnode(pnode->AsParseNodeFor()->pnodeIncr);
  10606. copyNode->AsParseNodeFor()->pnodeBody = CopyPnode(pnode->AsParseNodeFor()->pnodeBody);
  10607. return copyNode;
  10608. }
  10609. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10610. case knopIf:
  10611. Assert(false);
  10612. break;
  10613. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  10614. case knopWhile:
  10615. Assert(false);
  10616. break;
  10617. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10618. case knopDoWhile:
  10619. Assert(false);
  10620. break;
  10621. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10622. case knopForIn:
  10623. Assert(false);
  10624. break;
  10625. case knopForOf:
  10626. Assert(false);
  10627. break;
  10628. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10629. case knopReturn: {
  10630. ParseNode* copyNode = CreateNodeForOpT<knopReturn>(pnode->ichMin, pnode->ichLim);
  10631. copyNode->AsParseNodeReturn()->pnodeExpr = CopyPnode(pnode->AsParseNodeReturn()->pnodeExpr);
  10632. return copyNode;
  10633. }
  10634. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10635. case knopBlock: {
  10636. ParseNodeBlock* copyNode = CreateBlockNode(pnode->ichMin, pnode->ichLim, pnode->AsParseNodeBlock()->blockType);
  10637. if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {
  10638. // fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which
  10639. // CreateBlockNode() will not automatically set for us, so set it here if it's
  10640. // specified on the source node.
  10641. copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;
  10642. }
  10643. copyNode->pnodeStmt = CopyPnode(pnode->AsParseNodeBlock()->pnodeStmt);
  10644. return copyNode;
  10645. }
  10646. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10647. case knopWith:
  10648. Assert(false);
  10649. break;
  10650. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10651. case knopBreak:
  10652. Assert(false);
  10653. break;
  10654. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10655. case knopContinue:
  10656. Assert(false);
  10657. break;
  10658. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  10659. case knopSwitch:
  10660. Assert(false);
  10661. break;
  10662. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  10663. case knopCase:
  10664. Assert(false);
  10665. break;
  10666. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  10667. case knopTryFinally:
  10668. Assert(false);
  10669. break;
  10670. case knopFinally:
  10671. Assert(false);
  10672. break;
  10673. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  10674. case knopCatch:
  10675. Assert(false);
  10676. break;
  10677. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  10678. case knopTryCatch:
  10679. Assert(false);
  10680. break;
  10681. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  10682. case knopTry:
  10683. Assert(false);
  10684. break;
  10685. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  10686. case knopThrow:
  10687. Assert(false);
  10688. break;
  10689. default:
  10690. Assert(false);
  10691. break;
  10692. }
  10693. return NULL;
  10694. }
  10695. // Returns true when str is string for Nan, Infinity or -Infinity.
  10696. // Does not check for double number value being in NaN/Infinity range.
  10697. // static
  10698. template<bool CheckForNegativeInfinity>
  10699. inline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)
  10700. {
  10701. // Note: wcscmp crashes when one of the parameters is NULL.
  10702. return str &&
  10703. (wcscmp(_u("NaN"), str) == 0 ||
  10704. wcscmp(_u("Infinity"), str) == 0 ||
  10705. (CheckForNegativeInfinity && wcscmp(_u("-Infinity"), str) == 0));
  10706. }
  10707. template <bool buildAST>
  10708. IdentPtr Parser::ParseSuper(bool fAllowCall)
  10709. {
  10710. ParseNodeFnc * currentNodeFunc = GetCurrentFunctionNode();
  10711. IdentPtr superPid = nullptr;
  10712. switch (m_token.tk)
  10713. {
  10714. case tkDot: // super.prop
  10715. case tkLBrack: // super[foo]
  10716. superPid = wellKnownPropertyPids._super;
  10717. break;
  10718. case tkLParen: // super(args)
  10719. superPid = wellKnownPropertyPids._superConstructor;
  10720. break;
  10721. default:
  10722. Error(ERRInvalidSuper);
  10723. break;
  10724. }
  10725. currentNodeFunc->SetHasSuperReference(TRUE);
  10726. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Super, m_scriptContext);
  10727. // If we are defer parsing, we can skip verifying that the super reference is valid.
  10728. // If it wasn't the parser would have thrown during upfront parsing and we wouldn't be defer parsing the function.
  10729. if (m_parseType == ParseType_Deferred)
  10730. {
  10731. return superPid;
  10732. }
  10733. if (!fAllowCall && (m_token.tk == tkLParen))
  10734. {
  10735. Error(ERRInvalidSuper); // new super() is not allowed
  10736. }
  10737. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperCallAndPropertyAllowed)
  10738. {
  10739. // Any super access is good within a class constructor
  10740. }
  10741. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperPropertyAllowed)
  10742. {
  10743. if (m_token.tk == tkLParen)
  10744. {
  10745. if ((this->m_grfscr & fscrEval) == fscrNil)
  10746. {
  10747. // Cannot call super within a class member
  10748. Error(ERRInvalidSuper);
  10749. }
  10750. else
  10751. {
  10752. Js::JavascriptFunction * caller = nullptr;
  10753. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  10754. {
  10755. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  10756. Assert(callerBody);
  10757. if (!callerBody->GetFunctionInfo()->GetAllowDirectSuper())
  10758. {
  10759. Error(ERRInvalidSuper);
  10760. }
  10761. }
  10762. }
  10763. }
  10764. }
  10765. else
  10766. {
  10767. // Anything else is an error
  10768. Error(ERRInvalidSuper);
  10769. }
  10770. return superPid;
  10771. }
  10772. void Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)
  10773. {
  10774. Assert(nodeToAppend);
  10775. ParseNodePtr* lastPtr = node;
  10776. while ((*lastPtr) && (*lastPtr)->nop == knopList)
  10777. {
  10778. lastPtr = &(*lastPtr)->AsParseNodeBin()->pnode2;
  10779. }
  10780. auto last = (*lastPtr);
  10781. if (last)
  10782. {
  10783. *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);
  10784. }
  10785. else
  10786. {
  10787. *lastPtr = nodeToAppend;
  10788. }
  10789. }
  10790. ParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)
  10791. {
  10792. Assert(pnode->nop == knopArray);
  10793. pnode->nop = knopArrayPattern;
  10794. ForEachItemRefInList(&pnode->AsParseNodeArrLit()->pnode1, [&](ParseNodePtr *itemRef) {
  10795. ParseNodePtr item = *itemRef;
  10796. if (item->nop == knopEllipsis)
  10797. {
  10798. itemRef = &item->AsParseNodeUni()->pnode1;
  10799. item = *itemRef;
  10800. if (!(item->nop == knopName
  10801. || item->nop == knopDot
  10802. || item->nop == knopIndex
  10803. || item->nop == knopArray
  10804. || item->nop == knopObject))
  10805. {
  10806. Error(ERRInvalidAssignmentTarget);
  10807. }
  10808. }
  10809. else if (item->nop == knopAsg)
  10810. {
  10811. itemRef = &item->AsParseNodeBin()->pnode1;
  10812. item = *itemRef;
  10813. }
  10814. if (item->nop == knopArray)
  10815. {
  10816. ConvertArrayToArrayPattern(item);
  10817. }
  10818. else if (item->nop == knopObject)
  10819. {
  10820. *itemRef = ConvertObjectToObjectPattern(item);
  10821. }
  10822. else if (item->nop == knopName)
  10823. {
  10824. TrackAssignment<true>(item, nullptr);
  10825. }
  10826. });
  10827. return pnode;
  10828. }
  10829. ParseNodeUni * Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)
  10830. {
  10831. charcount_t ichMin = this->GetScanner()->IchMinTok();
  10832. charcount_t ichLim = this->GetScanner()->IchLimTok();
  10833. ParseNodePtr pnodeMemberNodeList = nullptr;
  10834. if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)
  10835. {
  10836. ichMin = pnodeMemberList->ichMin;
  10837. ichLim = pnodeMemberList->ichLim;
  10838. pnodeMemberList = pnodeMemberList->AsParseNodeUni()->pnode1;
  10839. }
  10840. ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {
  10841. ParseNodePtr memberNode = ConvertMemberToMemberPattern(item);
  10842. AppendToList(&pnodeMemberNodeList, memberNode);
  10843. });
  10844. return CreateUniNode(knopObjectPattern, pnodeMemberNodeList, ichMin, ichLim);
  10845. }
  10846. ParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)
  10847. {
  10848. Assert(pnode != nullptr);
  10849. ParseNodePtr rightNode = nullptr;
  10850. OpCode op = pnode->nop;
  10851. if (op == knopObject)
  10852. {
  10853. rightNode = ConvertObjectToObjectPattern(pnode);
  10854. }
  10855. else if (op == knopArray)
  10856. {
  10857. rightNode = ConvertArrayToArrayPattern(pnode);
  10858. }
  10859. else
  10860. {
  10861. rightNode = pnode;
  10862. if (op == knopName)
  10863. {
  10864. TrackAssignment<true>(pnode, nullptr);
  10865. }
  10866. else if (op == knopAsg)
  10867. {
  10868. TrackAssignment<true>(pnode->AsParseNodeBin()->pnode1, nullptr);
  10869. }
  10870. }
  10871. return rightNode;
  10872. }
  10873. ParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)
  10874. {
  10875. if (pnodeMember->nop == knopObjectPatternMember)
  10876. {
  10877. return pnodeMember;
  10878. }
  10879. Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);
  10880. ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->AsParseNodeBin()->pnode2);
  10881. ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->AsParseNodeBin()->pnode1, rightNode);
  10882. resultNode->ichMin = pnodeMember->ichMin;
  10883. resultNode->ichLim = pnodeMember->ichLim;
  10884. return resultNode;
  10885. }
  10886. ParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)
  10887. {
  10888. if (pnode != nullptr)
  10889. {
  10890. if (pnode->nop == knopArray)
  10891. {
  10892. ConvertArrayToArrayPattern(pnode);
  10893. }
  10894. else if (pnode->nop == knopObject)
  10895. {
  10896. pnode = ConvertObjectToObjectPattern(pnode);
  10897. }
  10898. }
  10899. return pnode;
  10900. }
  10901. // This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.
  10902. void Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,
  10903. bool isDecl,
  10904. bool topLevel,
  10905. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  10906. bool allowIn /*= true*/)
  10907. {
  10908. // We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and
  10909. // AST related information before the validation parsing and later they will be restored.
  10910. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  10911. ParseNodeFnc * pnodeDeferredFncSave = m_currentNodeDeferredFunc;
  10912. if (m_currentNodeDeferredFunc == nullptr)
  10913. {
  10914. m_currentNodeDeferredFunc = m_currentNodeFunc;
  10915. }
  10916. int32 *pAstSizeSave = m_pCurrentAstSize;
  10917. uint *pNestedCountSave = m_pnestedCount;
  10918. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  10919. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  10920. ParseNodePtr newTempScope = nullptr;
  10921. m_ppnodeScope = &newTempScope;
  10922. int32 newTempAstSize = 0;
  10923. m_pCurrentAstSize = &newTempAstSize;
  10924. uint newTempNestedCount = 0;
  10925. m_pnestedCount = &newTempNestedCount;
  10926. m_ppnodeExprScope = nullptr;
  10927. charcount_t funcInArraySave = m_funcInArray;
  10928. uint funcInArrayDepthSave = m_funcInArrayDepth;
  10929. // we need to reset this as we are going to parse the grammar again.
  10930. m_hasDeferredShorthandInitError = false;
  10931. ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);
  10932. m_currentNodeFunc = pnodeFncSave;
  10933. m_currentNodeDeferredFunc = pnodeDeferredFncSave;
  10934. m_pCurrentAstSize = pAstSizeSave;
  10935. m_pnestedCount = pNestedCountSave;
  10936. m_ppnodeScope = ppnodeScopeSave;
  10937. m_ppnodeExprScope = ppnodeExprScopeSave;
  10938. m_funcInArray = funcInArraySave;
  10939. m_funcInArrayDepth = funcInArrayDepthSave;
  10940. }
  10941. template <bool buildAST>
  10942. ParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,
  10943. bool isDecl,
  10944. bool topLevel/* = true*/,
  10945. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  10946. bool allowIn/* = true*/,
  10947. BOOL *forInOfOkay/* = nullptr*/,
  10948. BOOL *nativeForOkay/* = nullptr*/)
  10949. {
  10950. ParseNodeUni * pnode = nullptr;
  10951. Assert(IsPossiblePatternStart());
  10952. if (m_token.tk == tkLCurly)
  10953. {
  10954. pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);
  10955. }
  10956. else
  10957. {
  10958. pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);
  10959. }
  10960. return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);
  10961. }
  10962. template <bool buildAST>
  10963. ParseNodePtr Parser::ParseDestructuredInitializer(ParseNodeUni * lhsNode,
  10964. bool isDecl,
  10965. bool topLevel,
  10966. DestructuringInitializerContext initializerContext,
  10967. bool allowIn,
  10968. BOOL *forInOfOkay,
  10969. BOOL *nativeForOkay)
  10970. {
  10971. this->GetScanner()->Scan();
  10972. if (topLevel && nativeForOkay == nullptr)
  10973. {
  10974. if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)
  10975. {
  10976. // e.g. var {x};
  10977. Error(ERRDestructInit);
  10978. }
  10979. else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)
  10980. {
  10981. // e.g. catch([x] = [0])
  10982. Error(ERRDestructNotInit);
  10983. }
  10984. }
  10985. if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)
  10986. {
  10987. if (topLevel && nativeForOkay != nullptr)
  10988. {
  10989. // Native loop should have destructuring initializer
  10990. *nativeForOkay = FALSE;
  10991. }
  10992. return lhsNode;
  10993. }
  10994. if (forInOfOkay)
  10995. {
  10996. *forInOfOkay = FALSE;
  10997. }
  10998. this->GetScanner()->Scan();
  10999. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11000. ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);
  11001. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11002. {
  11003. Error(ERRnoColon);
  11004. }
  11005. ParseNodeBin * pnodeDestructAsg = nullptr;
  11006. if (buildAST)
  11007. {
  11008. Assert(lhsNode != nullptr);
  11009. pnodeDestructAsg = CreateBinNode(knopAsg, lhsNode, pnodeDefault, lhsNode->ichMin, pnodeDefault->ichLim);
  11010. }
  11011. return pnodeDestructAsg;
  11012. }
  11013. template <bool buildAST>
  11014. ParseNodeUni * Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel/* = true*/)
  11015. {
  11016. Assert(m_token.tk == tkLCurly);
  11017. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11018. this->GetScanner()->Scan();
  11019. if (!isDecl)
  11020. {
  11021. declarationType = tkLCurly;
  11022. }
  11023. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr/*pNameHint*/, nullptr/*pHintLength*/, declarationType);
  11024. Assert(m_token.tk == tkRCurly);
  11025. ParseNodeUni * objectPatternNode = nullptr;
  11026. if (buildAST)
  11027. {
  11028. charcount_t ichLim = this->GetScanner()->IchLimTok();
  11029. objectPatternNode = CreateUniNode(knopObjectPattern, pnodeMemberList, ichMin, ichLim);
  11030. }
  11031. return objectPatternNode;
  11032. }
  11033. template <bool buildAST>
  11034. ParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel/* = true*/, bool allowEmptyExpression/* = true*/)
  11035. {
  11036. ParseNodePtr pnodeElem = nullptr;
  11037. int parenCount = 0;
  11038. bool seenRest = false;
  11039. // Save the Block ID prior to the increments, so we can restore it back.
  11040. int originalCurrentBlockId = GetCurrentBlock()->blockId;
  11041. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11042. if (!isDecl)
  11043. {
  11044. while (m_token.tk == tkLParen)
  11045. {
  11046. this->GetScanner()->Scan();
  11047. ++parenCount;
  11048. // Match the block increment we do upon entering parenthetical expressions
  11049. // so that the block ID's will match on reparsing of parameters.
  11050. GetCurrentBlock()->blockId = m_nextBlockId++;
  11051. }
  11052. }
  11053. if (m_token.tk == tkEllipsis)
  11054. {
  11055. // As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed
  11056. // But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.
  11057. seenRest = true;
  11058. this->GetScanner()->Scan();
  11059. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11060. if (!isDecl)
  11061. {
  11062. while (m_token.tk == tkLParen)
  11063. {
  11064. this->GetScanner()->Scan();
  11065. ++parenCount;
  11066. // Match the block increment we do upon entering parenthetical expressions
  11067. // so that the block ID's will match on reparsing of parameters.
  11068. GetCurrentBlock()->blockId = m_nextBlockId++;
  11069. }
  11070. }
  11071. if (m_token.tk != tkID && m_token.tk != tkTHIS && m_token.tk != tkSUPER && m_token.tk != tkLCurly && m_token.tk != tkLBrack)
  11072. {
  11073. if (isDecl)
  11074. {
  11075. Error(ERRnoIdent);
  11076. }
  11077. else
  11078. {
  11079. Error(ERRInvalidAssignmentTarget);
  11080. }
  11081. }
  11082. }
  11083. if (IsPossiblePatternStart())
  11084. {
  11085. // For the possible pattern start we do not allow the parens before
  11086. if (parenCount != 0)
  11087. {
  11088. Error(ERRDestructIDRef);
  11089. }
  11090. // Go recursively
  11091. pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false /*topLevel*/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);
  11092. if (!isDecl)
  11093. {
  11094. BOOL fCanAssign;
  11095. IdentToken token;
  11096. // Look for postfix operator
  11097. pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  11098. }
  11099. }
  11100. else if (m_token.tk == tkSUPER || m_token.tk == tkID || m_token.tk == tkTHIS)
  11101. {
  11102. if (isDecl)
  11103. {
  11104. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11105. pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin
  11106. ,/* fAllowIn */false, /* pfForInOk */nullptr, /* singleDefOnly */true, /* allowInit */!seenRest, false /*topLevelParse*/);
  11107. }
  11108. else
  11109. {
  11110. BOOL fCanAssign;
  11111. IdentToken token;
  11112. // We aren't declaring anything, so scan the ID reference manually.
  11113. pnodeElem = ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false,
  11114. FALSE, &fCanAssign);
  11115. // In this destructuring case we can force error here as we cannot assign.
  11116. if (!fCanAssign)
  11117. {
  11118. Error(ERRInvalidAssignmentTarget);
  11119. }
  11120. if (buildAST)
  11121. {
  11122. if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)
  11123. {
  11124. CheckStrictModeEvalArgumentsUsage(pnodeElem->AsParseNodeName()->pid);
  11125. }
  11126. }
  11127. else
  11128. {
  11129. if (IsStrictMode() && token.tk == tkID)
  11130. {
  11131. CheckStrictModeEvalArgumentsUsage(token.pid);
  11132. }
  11133. token.tk = tkNone;
  11134. }
  11135. }
  11136. }
  11137. else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))
  11138. {
  11139. if (m_token.IsOperator())
  11140. {
  11141. Error(ERRDestructNoOper);
  11142. }
  11143. Error(ERRDestructIDRef);
  11144. }
  11145. // Swallow RParens before a default expression, if any.
  11146. // 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.
  11147. if (!isDecl)
  11148. {
  11149. while (m_token.tk == tkRParen)
  11150. {
  11151. this->GetScanner()->Scan();
  11152. --parenCount;
  11153. }
  11154. // Restore the Block ID of the current block after the parsing of destructured variable declarations and initializers.
  11155. GetCurrentBlock()->blockId = originalCurrentBlockId;
  11156. }
  11157. if (parenCount != 0)
  11158. {
  11159. Error(ERRnoRparen);
  11160. }
  11161. if (hasSeenRest != nullptr)
  11162. {
  11163. *hasSeenRest = seenRest;
  11164. }
  11165. if (m_token.tk == tkAsg)
  11166. {
  11167. // Parse the initializer.
  11168. if (seenRest)
  11169. {
  11170. Error(ERRRestWithDefault);
  11171. }
  11172. this->GetScanner()->Scan();
  11173. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11174. ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);
  11175. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11176. {
  11177. Error(ERRnoColon);
  11178. }
  11179. if (buildAST)
  11180. {
  11181. pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);
  11182. }
  11183. }
  11184. if (buildAST && seenRest)
  11185. {
  11186. ParseNodePtr pnodeRest = CreateUniNode(knopEllipsis, pnodeElem);
  11187. pnodeElem = pnodeRest;
  11188. }
  11189. if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))
  11190. {
  11191. if (m_token.IsOperator())
  11192. {
  11193. Error(ERRDestructNoOper);
  11194. }
  11195. Error(ERRsyntax);
  11196. }
  11197. return pnodeElem;
  11198. }
  11199. template <bool buildAST>
  11200. ParseNodeUni * Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)
  11201. {
  11202. Assert(m_token.tk == tkLBrack);
  11203. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11204. this->GetScanner()->Scan();
  11205. ParseNodeArrLit * pnodeDestructArr = nullptr;
  11206. ParseNodePtr pnodeList = nullptr;
  11207. ParseNodePtr *lastNodeRef = nullptr;
  11208. uint count = 0;
  11209. bool hasMissingValues = false;
  11210. bool seenRest = false;
  11211. if (m_token.tk != tkRBrack)
  11212. {
  11213. while (true)
  11214. {
  11215. ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);
  11216. if (buildAST)
  11217. {
  11218. if (pnodeElem == nullptr && buildAST)
  11219. {
  11220. pnodeElem = CreateNodeForOpT<knopEmpty>();
  11221. hasMissingValues = true;
  11222. }
  11223. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);
  11224. }
  11225. count++;
  11226. if (m_token.tk == tkRBrack)
  11227. {
  11228. break;
  11229. }
  11230. if (m_token.tk != tkComma)
  11231. {
  11232. Error(ERRDestructNoOper);
  11233. }
  11234. if (seenRest) // Rest must be in the last position.
  11235. {
  11236. Error(ERRDestructRestLast);
  11237. }
  11238. this->GetScanner()->Scan();
  11239. // break if we have the trailing comma as well, eg. [a,]
  11240. if (m_token.tk == tkRBrack)
  11241. {
  11242. break;
  11243. }
  11244. }
  11245. }
  11246. if (buildAST)
  11247. {
  11248. pnodeDestructArr = CreateNodeForOpT<knopArrayPattern>(ichMin);
  11249. pnodeDestructArr->pnode1 = pnodeList;
  11250. pnodeDestructArr->arrayOfTaggedInts = false;
  11251. pnodeDestructArr->arrayOfInts = false;
  11252. pnodeDestructArr->arrayOfNumbers = false;
  11253. pnodeDestructArr->hasMissingValues = hasMissingValues;
  11254. pnodeDestructArr->count = count;
  11255. pnodeDestructArr->spreadCount = seenRest ? 1 : 0;
  11256. if (pnodeDestructArr->pnode1)
  11257. {
  11258. this->CheckArguments(pnodeDestructArr->pnode1);
  11259. }
  11260. }
  11261. return pnodeDestructArr;
  11262. }
  11263. void Parser::CaptureContext(ParseContext *parseContext) const
  11264. {
  11265. parseContext->pszSrc = this->GetScanner()->PchBase();
  11266. parseContext->length = this->m_originalLength;
  11267. parseContext->characterOffset = this->GetScanner()->IchMinTok();
  11268. parseContext->offset = parseContext->characterOffset + this->GetScanner()->m_cMultiUnits;
  11269. parseContext->grfscr = this->m_grfscr;
  11270. parseContext->lineNumber = this->GetScanner()->LineCur();
  11271. parseContext->pnodeProg = this->m_currentNodeProg;
  11272. parseContext->isUtf8 = this->GetScanner()->IsUtf8();
  11273. parseContext->strictMode = this->IsStrictMode();
  11274. parseContext->sourceContextInfo = this->m_sourceContextInfo;
  11275. parseContext->currentBlockInfo = this->m_currentBlockInfo;
  11276. parseContext->nextBlockId = this->m_nextBlockId;
  11277. }
  11278. void Parser::RestoreContext(ParseContext *const parseContext)
  11279. {
  11280. m_sourceContextInfo = parseContext->sourceContextInfo;
  11281. m_currentBlockInfo = parseContext->currentBlockInfo;
  11282. m_nextBlockId = parseContext->nextBlockId;
  11283. m_grfscr = parseContext->grfscr;
  11284. m_length = parseContext->length;
  11285. this->GetScanner()->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->isUtf8, parseContext->grfscr, parseContext->lineNumber);
  11286. m_currentNodeProg = parseContext->pnodeProg;
  11287. m_fUseStrictMode = parseContext->strictMode;
  11288. }
  11289. class ByteCodeGenerator;
  11290. #if DBG_DUMP
  11291. #define INDENT_SIZE 2
  11292. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt);
  11293. void PrintFormalsWIndent(ParseNode *pnode, int indentAmt);
  11294. void Indent(int indentAmt) {
  11295. for (int i = 0; i < indentAmt; i++) {
  11296. Output::Print(_u(" "));
  11297. }
  11298. }
  11299. void PrintBlockType(PnodeBlockType type)
  11300. {
  11301. switch (type)
  11302. {
  11303. case Global:
  11304. Output::Print(_u("(Global)"));
  11305. break;
  11306. case Function:
  11307. Output::Print(_u("(Function)"));
  11308. break;
  11309. case Regular:
  11310. Output::Print(_u("(Regular)"));
  11311. break;
  11312. case Parameter:
  11313. Output::Print(_u("(Parameter)"));
  11314. break;
  11315. default:
  11316. Output::Print(_u("(unknown blocktype)"));
  11317. break;
  11318. }
  11319. }
  11320. void PrintScopesWIndent(ParseNode *pnode, int indentAmt) {
  11321. ParseNode *scope = nullptr;
  11322. bool firstOnly = false;
  11323. switch (pnode->nop)
  11324. {
  11325. case knopProg:
  11326. case knopFncDecl: scope = pnode->AsParseNodeFnc()->pnodeScopes; break;
  11327. case knopBlock: scope = pnode->AsParseNodeBlock()->pnodeScopes; break;
  11328. case knopCatch: scope = pnode->AsParseNodeCatch()->pnodeScopes; break;
  11329. case knopWith: scope = pnode->AsParseNodeWith()->pnodeScopes; break;
  11330. case knopSwitch: scope = pnode->AsParseNodeSwitch()->pnodeBlock; firstOnly = true; break;
  11331. case knopFor: scope = pnode->AsParseNodeFor()->pnodeBlock; firstOnly = true; break;
  11332. case knopForIn: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11333. case knopForOf: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11334. }
  11335. if (scope) {
  11336. Output::Print(_u("[%4d, %4d): "), scope->ichMin, scope->ichLim);
  11337. Indent(indentAmt);
  11338. Output::Print(_u("Scopes: "));
  11339. ParseNode *next = nullptr;
  11340. ParseNode *syntheticBlock = nullptr;
  11341. while (scope) {
  11342. switch (scope->nop) {
  11343. case knopFncDecl: Output::Print(_u("knopFncDecl")); next = scope->AsParseNodeFnc()->pnodeNext; break;
  11344. case knopBlock: Output::Print(_u("knopBlock")); PrintBlockType(scope->AsParseNodeBlock()->blockType); next = scope->AsParseNodeBlock()->pnodeNext; break;
  11345. case knopCatch: Output::Print(_u("knopCatch")); next = scope->AsParseNodeCatch()->pnodeNext; break;
  11346. case knopWith: Output::Print(_u("knopWith")); next = scope->AsParseNodeWith()->pnodeNext; break;
  11347. default: Output::Print(_u("unknown")); break;
  11348. }
  11349. if (firstOnly) {
  11350. next = nullptr;
  11351. syntheticBlock = scope;
  11352. }
  11353. if (scope->grfpn & fpnSyntheticNode) {
  11354. Output::Print(_u(" synthetic"));
  11355. if (scope->nop == knopBlock)
  11356. syntheticBlock = scope;
  11357. }
  11358. Output::Print(_u(" (%d-%d)"), scope->ichMin, scope->ichLim);
  11359. if (next) Output::Print(_u(", "));
  11360. scope = next;
  11361. }
  11362. Output::Print(_u("\n"));
  11363. if (syntheticBlock || firstOnly) {
  11364. PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);
  11365. }
  11366. }
  11367. }
  11368. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt) {
  11369. if (pnode == NULL)
  11370. return;
  11371. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11372. switch (pnode->nop) {
  11373. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  11374. case knopName:
  11375. Indent(indentAmt);
  11376. if (pnode->AsParseNodeName()->pid != NULL) {
  11377. Output::Print(_u("id: %s\n"), pnode->AsParseNodeName()->pid->Psz());
  11378. }
  11379. else {
  11380. Output::Print(_u("name node\n"));
  11381. }
  11382. break;
  11383. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11384. case knopInt:
  11385. Indent(indentAmt);
  11386. Output::Print(_u("%d\n"), pnode->AsParseNodeInt()->lw);
  11387. break;
  11388. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  11389. case knopFlt:
  11390. Indent(indentAmt);
  11391. Output::Print(_u("%lf\n"), pnode->AsParseNodeFloat()->dbl);
  11392. break;
  11393. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  11394. case knopStr:
  11395. Indent(indentAmt);
  11396. Output::Print(_u("\"%s\"\n"), pnode->AsParseNodeStr()->pid->Psz());
  11397. break;
  11398. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  11399. case knopRegExp:
  11400. Indent(indentAmt);
  11401. Output::Print(_u("/%x/\n"), pnode->AsParseNodeRegExp()->regexPattern);
  11402. break;
  11403. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  11404. case knopNull:
  11405. Indent(indentAmt);
  11406. Output::Print(_u("null\n"));
  11407. break;
  11408. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  11409. case knopFalse:
  11410. Indent(indentAmt);
  11411. Output::Print(_u("false\n"));
  11412. break;
  11413. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  11414. case knopTrue:
  11415. Indent(indentAmt);
  11416. Output::Print(_u("true\n"));
  11417. break;
  11418. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  11419. case knopEmpty:
  11420. Indent(indentAmt);
  11421. Output::Print(_u("empty\n"));
  11422. break;
  11423. // Unary operators.
  11424. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  11425. case knopNot:
  11426. Indent(indentAmt);
  11427. Output::Print(_u("~\n"));
  11428. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11429. break;
  11430. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  11431. case knopNeg:
  11432. Indent(indentAmt);
  11433. Output::Print(_u("U-\n"));
  11434. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11435. break;
  11436. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  11437. case knopPos:
  11438. Indent(indentAmt);
  11439. Output::Print(_u("U+\n"));
  11440. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11441. break;
  11442. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  11443. case knopLogNot:
  11444. Indent(indentAmt);
  11445. Output::Print(_u("!\n"));
  11446. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11447. break;
  11448. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  11449. case knopEllipsis:
  11450. Indent(indentAmt);
  11451. Output::Print(_u("...<expr>\n"));
  11452. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11453. break;
  11454. //PTNODE(knopIncPost , "++ post" ,Inc ,Uni ,fnopUni|fnopAsg)
  11455. case knopIncPost:
  11456. Indent(indentAmt);
  11457. Output::Print(_u("<expr>++\n"));
  11458. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11459. break;
  11460. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  11461. case knopDecPost:
  11462. Indent(indentAmt);
  11463. Output::Print(_u("<expr>--\n"));
  11464. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11465. break;
  11466. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  11467. case knopIncPre:
  11468. Indent(indentAmt);
  11469. Output::Print(_u("++<expr>\n"));
  11470. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11471. break;
  11472. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  11473. case knopDecPre:
  11474. Indent(indentAmt);
  11475. Output::Print(_u("--<expr>\n"));
  11476. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11477. break;
  11478. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  11479. case knopTypeof:
  11480. Indent(indentAmt);
  11481. Output::Print(_u("typeof\n"));
  11482. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11483. break;
  11484. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  11485. case knopVoid:
  11486. Indent(indentAmt);
  11487. Output::Print(_u("void\n"));
  11488. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11489. break;
  11490. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  11491. case knopDelete:
  11492. Indent(indentAmt);
  11493. Output::Print(_u("delete\n"));
  11494. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11495. break;
  11496. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  11497. case knopArrayPattern:
  11498. Indent(indentAmt);
  11499. Output::Print(_u("Array Pattern\n"));
  11500. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11501. break;
  11502. case knopObjectPattern:
  11503. Indent(indentAmt);
  11504. Output::Print(_u("Object Pattern\n"));
  11505. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11506. break;
  11507. case knopArray:
  11508. Indent(indentAmt);
  11509. Output::Print(_u("Array Literal\n"));
  11510. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11511. break;
  11512. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  11513. case knopObject:
  11514. Indent(indentAmt);
  11515. Output::Print(_u("Object Literal\n"));
  11516. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11517. break;
  11518. // Binary and Ternary Operators
  11519. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  11520. case knopAdd:
  11521. Indent(indentAmt);
  11522. Output::Print(_u("+\n"));
  11523. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11524. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11525. break;
  11526. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  11527. case knopSub:
  11528. Indent(indentAmt);
  11529. Output::Print(_u("-\n"));
  11530. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11531. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11532. break;
  11533. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  11534. case knopMul:
  11535. Indent(indentAmt);
  11536. Output::Print(_u("*\n"));
  11537. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11538. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11539. break;
  11540. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  11541. case knopExpo:
  11542. Indent(indentAmt);
  11543. Output::Print(_u("**\n"));
  11544. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11545. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11546. break;
  11547. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  11548. case knopDiv:
  11549. Indent(indentAmt);
  11550. Output::Print(_u("/\n"));
  11551. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11552. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11553. break;
  11554. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  11555. case knopMod:
  11556. Indent(indentAmt);
  11557. Output::Print(_u("%%\n"));
  11558. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11559. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11560. break;
  11561. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  11562. case knopOr:
  11563. Indent(indentAmt);
  11564. Output::Print(_u("|\n"));
  11565. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11566. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11567. break;
  11568. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  11569. case knopXor:
  11570. Indent(indentAmt);
  11571. Output::Print(_u("^\n"));
  11572. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11573. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11574. break;
  11575. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  11576. case knopAnd:
  11577. Indent(indentAmt);
  11578. Output::Print(_u("&\n"));
  11579. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11580. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11581. break;
  11582. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  11583. case knopEq:
  11584. Indent(indentAmt);
  11585. Output::Print(_u("==\n"));
  11586. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11587. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11588. break;
  11589. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  11590. case knopNe:
  11591. Indent(indentAmt);
  11592. Output::Print(_u("!=\n"));
  11593. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11594. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11595. break;
  11596. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  11597. case knopLt:
  11598. Indent(indentAmt);
  11599. Output::Print(_u("<\n"));
  11600. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11601. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11602. break;
  11603. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  11604. case knopLe:
  11605. Indent(indentAmt);
  11606. Output::Print(_u("<=\n"));
  11607. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11608. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11609. break;
  11610. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  11611. case knopGe:
  11612. Indent(indentAmt);
  11613. Output::Print(_u(">=\n"));
  11614. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11615. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11616. break;
  11617. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  11618. case knopGt:
  11619. Indent(indentAmt);
  11620. Output::Print(_u(">\n"));
  11621. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11622. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11623. break;
  11624. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  11625. case knopCall:
  11626. Indent(indentAmt);
  11627. Output::Print(_u("Call\n"));
  11628. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11629. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11630. break;
  11631. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  11632. case knopDot:
  11633. Indent(indentAmt);
  11634. Output::Print(_u(".\n"));
  11635. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11636. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11637. break;
  11638. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  11639. case knopAsg:
  11640. Indent(indentAmt);
  11641. Output::Print(_u("=\n"));
  11642. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11643. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11644. break;
  11645. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  11646. case knopInstOf:
  11647. Indent(indentAmt);
  11648. Output::Print(_u("instanceof\n"));
  11649. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11650. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11651. break;
  11652. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  11653. case knopIn:
  11654. Indent(indentAmt);
  11655. Output::Print(_u("in\n"));
  11656. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11657. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11658. break;
  11659. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  11660. case knopEqv:
  11661. Indent(indentAmt);
  11662. Output::Print(_u("===\n"));
  11663. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11664. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11665. break;
  11666. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  11667. case knopNEqv:
  11668. Indent(indentAmt);
  11669. Output::Print(_u("!==\n"));
  11670. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11671. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11672. break;
  11673. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  11674. case knopComma:
  11675. Indent(indentAmt);
  11676. Output::Print(_u(",\n"));
  11677. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11678. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11679. break;
  11680. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  11681. case knopLogOr:
  11682. Indent(indentAmt);
  11683. Output::Print(_u("||\n"));
  11684. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11685. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11686. break;
  11687. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  11688. case knopLogAnd:
  11689. Indent(indentAmt);
  11690. Output::Print(_u("&&\n"));
  11691. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11692. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11693. break;
  11694. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  11695. case knopLsh:
  11696. Indent(indentAmt);
  11697. Output::Print(_u("<<\n"));
  11698. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11699. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11700. break;
  11701. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  11702. case knopRsh:
  11703. Indent(indentAmt);
  11704. Output::Print(_u(">>\n"));
  11705. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11706. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11707. break;
  11708. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  11709. case knopRs2:
  11710. Indent(indentAmt);
  11711. Output::Print(_u(">>>\n"));
  11712. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11713. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11714. break;
  11715. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  11716. case knopNew:
  11717. Indent(indentAmt);
  11718. Output::Print(_u("new\n"));
  11719. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11720. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11721. break;
  11722. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  11723. case knopIndex:
  11724. Indent(indentAmt);
  11725. Output::Print(_u("[]\n"));
  11726. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11727. PrintPnodeListWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11728. break;
  11729. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  11730. case knopQmark:
  11731. Indent(indentAmt);
  11732. Output::Print(_u("?:\n"));
  11733. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode1, indentAmt + INDENT_SIZE);
  11734. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode2, indentAmt + INDENT_SIZE);
  11735. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode3, indentAmt + INDENT_SIZE);
  11736. break;
  11737. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  11738. case knopAsgAdd:
  11739. Indent(indentAmt);
  11740. Output::Print(_u("+=\n"));
  11741. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11742. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11743. break;
  11744. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  11745. case knopAsgSub:
  11746. Indent(indentAmt);
  11747. Output::Print(_u("-=\n"));
  11748. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11749. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11750. break;
  11751. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  11752. case knopAsgMul:
  11753. Indent(indentAmt);
  11754. Output::Print(_u("*=\n"));
  11755. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11756. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11757. break;
  11758. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  11759. case knopAsgExpo:
  11760. Indent(indentAmt);
  11761. Output::Print(_u("**=\n"));
  11762. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11763. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11764. break;
  11765. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  11766. case knopAsgDiv:
  11767. Indent(indentAmt);
  11768. Output::Print(_u("/=\n"));
  11769. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11770. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11771. break;
  11772. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  11773. case knopAsgMod:
  11774. Indent(indentAmt);
  11775. Output::Print(_u("%=\n"));
  11776. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11777. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11778. break;
  11779. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  11780. case knopAsgAnd:
  11781. Indent(indentAmt);
  11782. Output::Print(_u("&=\n"));
  11783. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11784. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11785. break;
  11786. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  11787. case knopAsgXor:
  11788. Indent(indentAmt);
  11789. Output::Print(_u("^=\n"));
  11790. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11791. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11792. break;
  11793. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  11794. case knopAsgOr:
  11795. Indent(indentAmt);
  11796. Output::Print(_u("|=\n"));
  11797. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11798. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11799. break;
  11800. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  11801. case knopAsgLsh:
  11802. Indent(indentAmt);
  11803. Output::Print(_u("<<=\n"));
  11804. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11805. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11806. break;
  11807. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  11808. case knopAsgRsh:
  11809. Indent(indentAmt);
  11810. Output::Print(_u(">>=\n"));
  11811. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11812. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11813. break;
  11814. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  11815. case knopAsgRs2:
  11816. Indent(indentAmt);
  11817. Output::Print(_u(">>>=\n"));
  11818. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11819. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11820. break;
  11821. case knopComputedName:
  11822. Indent(indentAmt);
  11823. Output::Print(_u("ComputedProperty\n"));
  11824. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11825. break;
  11826. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  11827. case knopMember:
  11828. case knopMemberShort:
  11829. case knopObjectPatternMember:
  11830. Indent(indentAmt);
  11831. Output::Print(_u(":\n"));
  11832. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11833. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11834. break;
  11835. // General nodes.
  11836. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  11837. case knopList:
  11838. Indent(indentAmt);
  11839. Output::Print(_u("List\n"));
  11840. PrintPnodeListWIndent(pnode, indentAmt + INDENT_SIZE);
  11841. break;
  11842. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  11843. case knopVarDecl:
  11844. Indent(indentAmt);
  11845. Output::Print(_u("var %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11846. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11847. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11848. break;
  11849. case knopConstDecl:
  11850. Indent(indentAmt);
  11851. Output::Print(_u("const %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11852. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11853. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11854. break;
  11855. case knopLetDecl:
  11856. Indent(indentAmt);
  11857. Output::Print(_u("let %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  11858. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  11859. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  11860. break;
  11861. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  11862. case knopFncDecl:
  11863. Indent(indentAmt);
  11864. if (pnode->AsParseNodeFnc()->pid != NULL)
  11865. {
  11866. Output::Print(_u("fn decl %d nested %d name %s (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(),
  11867. pnode->AsParseNodeFnc()->pid->Psz(), pnode->ichMin, pnode->ichLim);
  11868. }
  11869. else
  11870. {
  11871. Output::Print(_u("fn decl %d nested %d anonymous (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(), pnode->ichMin, pnode->ichLim);
  11872. }
  11873. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11874. PrintFormalsWIndent(pnode->AsParseNodeFnc()->pnodeParams, indentAmt + INDENT_SIZE);
  11875. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeRest, indentAmt + INDENT_SIZE);
  11876. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  11877. if (pnode->AsParseNodeFnc()->pnodeBody == nullptr)
  11878. {
  11879. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11880. Indent(indentAmt + INDENT_SIZE);
  11881. Output::Print(_u("<parse deferred body>\n"));
  11882. }
  11883. break;
  11884. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  11885. case knopProg:
  11886. Indent(indentAmt);
  11887. Output::Print(_u("program\n"));
  11888. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11889. PrintPnodeListWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  11890. break;
  11891. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  11892. case knopEndCode:
  11893. Indent(indentAmt);
  11894. Output::Print(_u("<endcode>\n"));
  11895. break;
  11896. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  11897. case knopDebugger:
  11898. Indent(indentAmt);
  11899. Output::Print(_u("<debugger>\n"));
  11900. break;
  11901. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  11902. case knopFor:
  11903. Indent(indentAmt);
  11904. Output::Print(_u("for\n"));
  11905. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11906. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeInit, indentAmt + INDENT_SIZE);
  11907. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeCond, indentAmt + INDENT_SIZE);
  11908. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeIncr, indentAmt + INDENT_SIZE);
  11909. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeBody, indentAmt + INDENT_SIZE);
  11910. break;
  11911. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  11912. case knopIf:
  11913. Indent(indentAmt);
  11914. Output::Print(_u("if\n"));
  11915. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeCond, indentAmt + INDENT_SIZE);
  11916. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeTrue, indentAmt + INDENT_SIZE);
  11917. if (pnode->AsParseNodeIf()->pnodeFalse != NULL)
  11918. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeFalse, indentAmt + INDENT_SIZE);
  11919. break;
  11920. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  11921. case knopWhile:
  11922. Indent(indentAmt);
  11923. Output::Print(_u("while\n"));
  11924. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  11925. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  11926. break;
  11927. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  11928. case knopDoWhile:
  11929. Indent(indentAmt);
  11930. Output::Print(_u("do\n"));
  11931. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  11932. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  11933. break;
  11934. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  11935. case knopForIn:
  11936. Indent(indentAmt);
  11937. Output::Print(_u("forIn\n"));
  11938. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11939. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  11940. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  11941. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  11942. break;
  11943. case knopForOf:
  11944. Indent(indentAmt);
  11945. Output::Print(_u("forOf\n"));
  11946. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11947. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  11948. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  11949. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  11950. break;
  11951. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  11952. case knopReturn:
  11953. Indent(indentAmt);
  11954. Output::Print(_u("return\n"));
  11955. if (pnode->AsParseNodeReturn()->pnodeExpr != NULL)
  11956. PrintPnodeWIndent(pnode->AsParseNodeReturn()->pnodeExpr, indentAmt + INDENT_SIZE);
  11957. break;
  11958. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  11959. case knopBlock:
  11960. Indent(indentAmt);
  11961. Output::Print(_u("block "));
  11962. if (pnode->grfpn & fpnSyntheticNode)
  11963. Output::Print(_u("synthetic "));
  11964. PrintBlockType(pnode->AsParseNodeBlock()->blockType);
  11965. Output::Print(_u("(%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  11966. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11967. if (pnode->AsParseNodeBlock()->pnodeStmt != NULL)
  11968. PrintPnodeWIndent(pnode->AsParseNodeBlock()->pnodeStmt, indentAmt + INDENT_SIZE);
  11969. break;
  11970. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  11971. case knopWith:
  11972. Indent(indentAmt);
  11973. Output::Print(_u("with (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  11974. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11975. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeObj, indentAmt + INDENT_SIZE);
  11976. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeBody, indentAmt + INDENT_SIZE);
  11977. break;
  11978. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  11979. case knopBreak:
  11980. Indent(indentAmt);
  11981. Output::Print(_u("break\n"));
  11982. // TODO: some representation of target
  11983. break;
  11984. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  11985. case knopContinue:
  11986. Indent(indentAmt);
  11987. Output::Print(_u("continue\n"));
  11988. // TODO: some representation of target
  11989. break;
  11990. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  11991. case knopSwitch:
  11992. Indent(indentAmt);
  11993. Output::Print(_u("switch\n"));
  11994. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  11995. for (ParseNodeCase *pnodeT = pnode->AsParseNodeSwitch()->pnodeCases; NULL != pnodeT; pnodeT = pnodeT->pnodeNext) {
  11996. PrintPnodeWIndent(pnodeT, indentAmt + 2);
  11997. }
  11998. break;
  11999. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  12000. case knopCase:
  12001. Indent(indentAmt);
  12002. Output::Print(_u("case\n"));
  12003. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeExpr, indentAmt + INDENT_SIZE);
  12004. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeBody, indentAmt + INDENT_SIZE);
  12005. break;
  12006. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  12007. case knopTryFinally:
  12008. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeTry, indentAmt);
  12009. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeFinally, indentAmt);
  12010. break;
  12011. case knopFinally:
  12012. Indent(indentAmt);
  12013. Output::Print(_u("finally\n"));
  12014. PrintPnodeWIndent(pnode->AsParseNodeFinally()->pnodeBody, indentAmt + INDENT_SIZE);
  12015. break;
  12016. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  12017. case knopCatch:
  12018. Indent(indentAmt);
  12019. Output::Print(_u("catch (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12020. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12021. PrintPnodeWIndent(pnode->AsParseNodeCatch()->GetParam(), indentAmt + INDENT_SIZE);
  12022. // if (pnode->AsParseNodeCatch()->pnodeGuard!=NULL)
  12023. // PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeGuard,indentAmt+INDENT_SIZE);
  12024. PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeBody, indentAmt + INDENT_SIZE);
  12025. break;
  12026. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  12027. case knopTryCatch:
  12028. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeTry, indentAmt);
  12029. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeCatch, indentAmt);
  12030. break;
  12031. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  12032. case knopTry:
  12033. Indent(indentAmt);
  12034. Output::Print(_u("try\n"));
  12035. PrintPnodeWIndent(pnode->AsParseNodeTry()->pnodeBody, indentAmt + INDENT_SIZE);
  12036. break;
  12037. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  12038. case knopThrow:
  12039. Indent(indentAmt);
  12040. Output::Print(_u("throw\n"));
  12041. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12042. break;
  12043. //PTNODE(knopClassDecl, "classDecl", None , Class, fnopLeaf)
  12044. case knopClassDecl:
  12045. Indent(indentAmt);
  12046. Output::Print(_u("class %s"), pnode->AsParseNodeClass()->pnodeName->pid->Psz());
  12047. if (pnode->AsParseNodeClass()->pnodeExtends != nullptr)
  12048. {
  12049. Output::Print(_u(" extends "));
  12050. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeExtends, 0);
  12051. }
  12052. else {
  12053. Output::Print(_u("\n"));
  12054. }
  12055. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeConstructor, indentAmt + INDENT_SIZE);
  12056. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeMembers, indentAmt + INDENT_SIZE);
  12057. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeStaticMembers, indentAmt + INDENT_SIZE);
  12058. break;
  12059. case knopStrTemplate:
  12060. Indent(indentAmt);
  12061. Output::Print(_u("string template\n"));
  12062. PrintPnodeListWIndent(pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);
  12063. break;
  12064. case knopYieldStar:
  12065. Indent(indentAmt);
  12066. Output::Print(_u("yield*\n"));
  12067. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12068. break;
  12069. case knopYield:
  12070. case knopYieldLeaf:
  12071. Indent(indentAmt);
  12072. Output::Print(_u("yield\n"));
  12073. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12074. break;
  12075. case knopAwait:
  12076. Indent(indentAmt);
  12077. Output::Print(_u("await\n"));
  12078. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12079. break;
  12080. case knopExportDefault:
  12081. Indent(indentAmt);
  12082. Output::Print(_u("export default\n"));
  12083. PrintPnodeListWIndent(pnode->AsParseNodeExportDefault()->pnodeExpr, indentAmt + INDENT_SIZE);
  12084. break;
  12085. default:
  12086. Output::Print(_u("unhandled pnode op %d\n"), pnode->nop);
  12087. break;
  12088. }
  12089. }
  12090. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt) {
  12091. if (pnode != NULL) {
  12092. while (pnode->nop == knopList) {
  12093. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt);
  12094. pnode = pnode->AsParseNodeBin()->pnode2;
  12095. }
  12096. PrintPnodeWIndent(pnode, indentAmt);
  12097. }
  12098. }
  12099. void PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)
  12100. {
  12101. for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())
  12102. {
  12103. PrintPnodeWIndent(pnode->nop == knopParamPattern ? pnode->AsParseNodeParamPattern()->pnode1 : pnode, indentAmt);
  12104. }
  12105. }
  12106. void PrintPnode(ParseNode *pnode) {
  12107. PrintPnodeWIndent(pnode, 0);
  12108. }
  12109. void ParseNode::Dump()
  12110. {
  12111. switch (nop)
  12112. {
  12113. case knopFncDecl:
  12114. case knopProg:
  12115. LPCOLESTR name = Js::Constants::AnonymousFunction;
  12116. if (this->AsParseNodeFnc()->pnodeName)
  12117. {
  12118. Assert(this->AsParseNodeFnc()->pnodeName->nop == knopVarDecl);
  12119. name = this->AsParseNodeFnc()->pnodeName->pid->Psz();
  12120. }
  12121. Output::Print(_u("%s (%d) [%d, %d]:\n"), name, this->AsParseNodeFnc()->functionId, this->AsParseNodeFnc()->lineNumber, this->AsParseNodeFnc()->columnNumber);
  12122. Output::Print(_u("hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasOnlyThis:%s \n"),
  12123. IsTrueOrFalse(this->AsParseNodeFnc()->HasHeapArguments()),
  12124. IsTrueOrFalse(this->AsParseNodeFnc()->CallsEval()),
  12125. IsTrueOrFalse(this->AsParseNodeFnc()->ChildCallsEval()),
  12126. IsTrueOrFalse(this->AsParseNodeFnc()->HasReferenceableBuiltInArguments()),
  12127. IsTrueOrFalse(this->AsParseNodeFnc()->GetArgumentsObjectEscapes()),
  12128. IsTrueOrFalse(this->AsParseNodeFnc()->HasWithStmt()),
  12129. IsTrueOrFalse(this->AsParseNodeFnc()->HasOnlyThisStmts()));
  12130. if (this->AsParseNodeFnc()->funcInfo)
  12131. {
  12132. this->AsParseNodeFnc()->funcInfo->Dump();
  12133. }
  12134. break;
  12135. }
  12136. }
  12137. void DumpCapturedNames(ParseNodeFnc* pnodeFnc, IdentPtrSet* capturedNames, ArenaAllocator* alloc)
  12138. {
  12139. auto sortedNames = JsUtil::List<IdentPtr, ArenaAllocator>::New(alloc);
  12140. capturedNames->Map([=](const IdentPtr& pid) -> void {
  12141. sortedNames->Add(pid);
  12142. });
  12143. sortedNames->Sort([](void* context, const void* left, const void* right) -> int {
  12144. const IdentPtr leftIdentPtr = *(const IdentPtr*)(left);
  12145. const IdentPtr rightIdentPtr = *(const IdentPtr*)(right);
  12146. return ::wcscmp(leftIdentPtr->Psz(), rightIdentPtr->Psz());
  12147. }, nullptr);
  12148. sortedNames->Map([=](int index, const IdentPtr pid) -> void {
  12149. OUTPUT_TRACE_DEBUGONLY(Js::CreateParserStatePhase, _u(" Function %u captured name \"%s\"\n"), pnodeFnc->functionId, pid->Psz());
  12150. });
  12151. }
  12152. #endif
  12153. void Parser::AddNestedCapturedNames(ParseNodeFnc* pnodeChildFnc)
  12154. {
  12155. if (m_currentNodeFunc && this->IsCreatingStateCache() && pnodeChildFnc->HasAnyCapturedNames())
  12156. {
  12157. IdentPtrSet* parentCapturedNames = GetCurrentFunctionNode()->EnsureCapturedNames(&m_nodeAllocator);
  12158. IdentPtrSet* childCaptureNames = pnodeChildFnc->GetCapturedNames();
  12159. auto iter = childCaptureNames->GetIterator();
  12160. while (iter.IsValid())
  12161. {
  12162. parentCapturedNames->AddNew(iter.CurrentValue());
  12163. iter.MoveNext();
  12164. }
  12165. }
  12166. }
  12167. void Parser::ProcessCapturedNames(ParseNodeFnc* pnodeFnc)
  12168. {
  12169. if (this->IsCreatingStateCache() && pnodeFnc->HasAnyCapturedNames())
  12170. {
  12171. IdentPtrSet* capturedNames = pnodeFnc->GetCapturedNames();
  12172. auto iter = capturedNames->GetIteratorWithRemovalSupport();
  12173. while (iter.IsValid())
  12174. {
  12175. const IdentPtr& pid = iter.CurrentValueReference();
  12176. PidRefStack* ref = pid->GetTopRef();
  12177. // If the pid has no refs left in our function's scope after binding, we didn't capture it.
  12178. if (!ref || ref->GetFuncScopeId() < pnodeFnc->functionId)
  12179. {
  12180. iter.RemoveCurrent();
  12181. }
  12182. iter.MoveNext();
  12183. }
  12184. #if DBG_DUMP
  12185. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::CreateParserStatePhase))
  12186. {
  12187. DumpCapturedNames(pnodeFnc, capturedNames, &this->m_nodeAllocator);
  12188. fflush(stdout);
  12189. }
  12190. #endif
  12191. }
  12192. }
  12193. bool Parser::IsCreatingStateCache()
  12194. {
  12195. return (((this->m_grfscr & fscrCreateParserState) == fscrCreateParserState)
  12196. && this->m_functionBody == nullptr
  12197. && CONFIG_FLAG(ParserStateCache));
  12198. }
  12199. DeferredFunctionStub * Parser::BuildDeferredStubTree(ParseNodeFnc *pnodeFnc, Recycler *recycler)
  12200. {
  12201. Assert(CONFIG_FLAG(ParserStateCache));
  12202. uint nestedCount = pnodeFnc->nestedCount;
  12203. if (nestedCount == 0)
  12204. {
  12205. return nullptr;
  12206. }
  12207. if (pnodeFnc->deferredStub)
  12208. {
  12209. return pnodeFnc->deferredStub;
  12210. }
  12211. DeferredFunctionStub* deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);
  12212. uint i = 0;
  12213. ParseNodeBlock* pnodeBlock = pnodeFnc->pnodeBodyScope;
  12214. ParseNodePtr pnodeChild = nullptr;
  12215. if (pnodeFnc->nop == knopProg)
  12216. {
  12217. Assert(pnodeFnc->pnodeBodyScope == nullptr
  12218. && pnodeFnc->pnodeScopes != nullptr
  12219. && pnodeFnc->pnodeScopes->blockType == PnodeBlockType::Global);
  12220. pnodeBlock = pnodeFnc->pnodeScopes;
  12221. pnodeChild = pnodeFnc->pnodeScopes->pnodeScopes;
  12222. }
  12223. else
  12224. {
  12225. Assert(pnodeBlock != nullptr
  12226. && (pnodeBlock->blockType == PnodeBlockType::Function
  12227. || pnodeBlock->blockType == PnodeBlockType::Parameter));
  12228. pnodeChild = pnodeBlock->pnodeScopes;
  12229. }
  12230. while (pnodeChild != nullptr)
  12231. {
  12232. if (pnodeChild->nop != knopFncDecl)
  12233. {
  12234. // We only expect to find a function body block in a parameter scope block.
  12235. Assert(pnodeChild->nop == knopBlock
  12236. && (pnodeBlock->blockType == PnodeBlockType::Parameter
  12237. || pnodeChild->AsParseNodeBlock()->blockType == PnodeBlockType::Function));
  12238. pnodeChild = pnodeChild->AsParseNodeBlock()->pnodeNext;
  12239. continue;
  12240. }
  12241. ParseNodeFnc* pnodeFncChild = pnodeChild->AsParseNodeFnc();
  12242. AnalysisAssertOrFailFast(i < nestedCount);
  12243. if (pnodeFncChild->pnodeBody != nullptr)
  12244. {
  12245. // Anomalous case of a non-deferred function nested within a deferred one.
  12246. // Work around by discarding the stub tree.
  12247. return nullptr;
  12248. }
  12249. if (pnodeFncChild->IsGeneratedDefault())
  12250. {
  12251. ++i;
  12252. pnodeChild = pnodeFncChild->pnodeNext;
  12253. continue;
  12254. }
  12255. deferredStubs[i].fncFlags = pnodeFncChild->fncFlags;
  12256. deferredStubs[i].nestedCount = pnodeFncChild->nestedCount;
  12257. deferredStubs[i].restorePoint = *pnodeFncChild->pRestorePoint;
  12258. deferredStubs[i].deferredStubs = BuildDeferredStubTree(pnodeFncChild, recycler);
  12259. deferredStubs[i].ichMin = pnodeChild->ichMin;
  12260. // Save the set of captured names onto the deferred stub.
  12261. // Since this set is allocated in the Parser arena, we'll have to convert these
  12262. // into indices in a string table which will survive when the parser goes away.
  12263. deferredStubs[i].capturedNamePointers = pnodeFncChild->GetCapturedNames();
  12264. ++i;
  12265. pnodeChild = pnodeFncChild->pnodeNext;
  12266. }
  12267. pnodeFnc->deferredStub = deferredStubs;
  12268. return deferredStubs;
  12269. }